SplashGUI

Session logging: fronting proxy on the public port + JSONL session store + Logging tab

New feature (scratch/spec-logging-proxy.md, Josh's decisions locked):
- Core/SessionProxy.swift: NWConnection byte pipe that fronts the user's serve
  port when logging is on; the engine is relaunched on an auto-picked free
  loopback port behind it, so client configs NEVER change. LAN binds move to
  the proxy (engine stays loopback). /v1/* is tee'd into records; everything
  else proxies silently; a logging failure can never block forwarding.
  Pure layers (head parse, hex-chunked framing, SSE reassembly for chat +
  Responses shapes, request summary, fronting/port/record policies) are
  harness-pinned.
- Core/SessionLog.swift: YYYY-MM-DD.jsonl store under the app data dir, full
  fidelity records (whole request JSON, reassembled text/reasoning/tool-call
  fragments, usage, duration, client hint, error kinds client-abort/
  upstream-error/malformed), retention purge by day-file name, tail + stats.
- AppModel: frontingPlan at start (adopted external serves are never fronted;
  no free internal port -> serve runs unfronted with a note); status polling
  targets the internal port while fronted; stop() tears the proxy down;
  retention sweep on launch.
- AppConfig: loggingEnabled/loggingLanClients/loggingRetentionDays(90), all
  decodeIfPresent (additive, no schema bump). LAN clients are PIPED but only
  RECORDED when loggingLanClients is on (office privacy, Josh's ask).
- Views/LoggingTab.swift + sidebar row below Status + 'logging' footer chip:
  toggles with applies-on-next-Start note, LAN warning row, storage stats,
  open-folder, retention picker, live tail with full-JSON disclosure.
- Catalog: add ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-GGUF:IQ3_S (96GB/86GB)
  \u2014 the 1.6.0 engine tsv's 12th row; the drift check caught it.
- Harness 148 -> 169: parse/framing/SSE/shape fixtures, store rotate/purge/tail/
  stats, fronting+policy rows, port picker, and a LIVE E2E: fake engine + real
  proxy + URLSession - unlogged /status passthrough, SSE chat recorded with
  joined tool-call args and usage, LAN-IP client served but not recorded.
  Mutation-proven x3: args-append, adopted-fronting, record-all-peers each
  fail exactly their checks.

7a0231ecfae4ace98329212eecb884f2eddd5404
cjosie <administrator@josie-c.com> · 2026-11-10T17:23 · browse files at this commit

parents: c4bd121

diff --git a/Sources/SplashGUI/Core/AppConfig.swift b/Sources/SplashGUI/Core/AppConfig.swift
index 1a62195..ba06172 100644
--- a/Sources/SplashGUI/Core/AppConfig.swift
+++ b/Sources/SplashGUI/Core/AppConfig.swift
@@ -390,6 +390,12 @@ struct AppConfig: Codable, Equatable {
     // something already owns the port (the adopt path wins), and in the headless harness
     // (SPLASHGUI_TEST=1) so tests never spawn a server.
     var startOnLaunch: Bool = false
+    // Session logging via the fronting proxy (scratch/spec-logging-proxy.md). Applies on
+    // the next Start: the proxy can only take the public port while the app launches the
+    // serve itself. LAN clients are piped but NOT recorded unless loggingLanClients is on.
+    var loggingEnabled: Bool = false
+    var loggingLanClients: Bool = false
+    var loggingRetentionDays: Int = 90
 
     init() {}
 
@@ -401,6 +407,7 @@ struct AppConfig: Codable, Equatable {
         case engineVersionOverride, engineURLOverride, engineSHA256Override, checkEngineUpdate
         case engineMode
         case startOnLaunch
+        case loggingEnabled, loggingLanClients, loggingRetentionDays
     }
 
     init(from decoder: Decoder) throws {
@@ -419,6 +426,9 @@ struct AppConfig: Codable, Equatable {
         // factory defaults (the Codable trap).
         engineMode = EngineMode(rawValue: try c.decodeIfPresent(String.self, forKey: .engineMode) ?? "pinned") ?? .pinned
         startOnLaunch = try c.decodeIfPresent(Bool.self, forKey: .startOnLaunch) ?? false
+        loggingEnabled = try c.decodeIfPresent(Bool.self, forKey: .loggingEnabled) ?? false
+        loggingLanClients = try c.decodeIfPresent(Bool.self, forKey: .loggingLanClients) ?? false
+        loggingRetentionDays = try c.decodeIfPresent(Int.self, forKey: .loggingRetentionDays) ?? 90
     }
 
     func enginePinOverride() -> EnginePin? {
@@ -579,6 +589,10 @@ struct CatalogModel: Identifiable, Equatable {
                      targetFile: "Qwen3.8-27B-UD-IQ3_XXS.gguf",
                      sha256: "c0b7c3038681ed2e3040456c1dd45f9858b6c2290bed172c70388a94874f3eee",
                      qwen27BArch: true),
+        CatalogModel(id: "ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-GGUF:IQ3_S", label: "Qwen3.8-Flash-Next IQ3_S",
+                     note: "for 96 GB Macs · 86 GB download · Most capable",
+                     approxBytes: 86_000_000_000, memoryGB: 96,
+                     supportsPleMemory: true, supportsSparseKvMemory: true),
         CatalogModel(id: "ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-GGUF:Q2_0", label: "Qwen3.8-Flash-Next Q2_0",
                      note: "for 64 GB Macs · 69 GB download · Most capable",
                      approxBytes: 69_000_000_000, memoryGB: 64,
diff --git a/Sources/SplashGUI/Core/AppModel.swift b/Sources/SplashGUI/Core/AppModel.swift
index f57774e..874e791 100644
--- a/Sources/SplashGUI/Core/AppModel.swift
+++ b/Sources/SplashGUI/Core/AppModel.swift
@@ -198,9 +198,25 @@ final class AppModel: ObservableObject {
         guard let launched = launchedRunConfig else { return false }
         return phase == .ready && launched != config.run
     }
-    private var client: SplashClient { SplashClient(port: config.run.port) }
+    private var client: SplashClient { SplashClient(port: frontedEnginePort ?? config.run.port) }
     private var pollTask: Task<Void, Never>?
     private var logTimer: Timer?
+    // Session logging (spec-logging-proxy). When the serve is fronted, the proxy holds the
+    // PUBLIC port and the engine runs on `frontedEnginePort`; status polling goes direct.
+    let sessionLog = SessionLog()
+    @Published var frontedEnginePort: Int?
+    private var proxy: SessionProxy?
+    // The Logging tab's "applies on next Start" hint: what the running serve was started with.
+    @Published var launchedLoggingEnabled = false
+
+    // Pure fronting rule (harness-pinned): front only when logging is on AND the app is
+    // launching the serve itself onto a picked free internal port. An adopted external
+    // serve never gets fronted — its port is already bound by someone else.
+    nonisolated static func frontingPlan(enabled: Bool, adopted: Bool, pickedInternalPort: Int?)
+        -> (front: Bool, enginePort: Int?) {
+        guard enabled, !adopted, let p = pickedInternalPort else { return (false, nil) }
+        return (true, p)
+    }
 
     init() {
         config = ConfigStore.shared.load()
@@ -248,6 +264,8 @@ final class AppModel: ObservableObject {
             if !(await self.adoptExistingServer()) { self.autoStartIfNeeded() }
         }
         refreshModelSizeCache()
+        // Retention sweep on launch; day-file names older than the window are deleted.
+        SessionLog.purge(dir: sessionLog.dir, retentionDays: config.loggingRetentionDays)
 
         engineVersion = engine.installedVersion
         engine.step = EngineInstaller.isInstalled ? .ready : .idle
@@ -318,6 +336,9 @@ final class AppModel: ObservableObject {
         AppModel.serverKillPID = pid
         launchedRunConfig = config.run
         server.note("- attached to existing splash on port \(config.run.port) (pid \(pid))")
+        if config.loggingEnabled {
+            server.note("- session logging inactive while attached to an externally started serve")
+        }
         server.spawnWatchdog(serverPID: pid, appPID: Int(ProcessInfo.processInfo.processIdentifier))
         phase = await client.ready() ? .ready : .starting
         startPolling()
@@ -666,12 +687,38 @@ final class AppModel: ObservableObject {
             do {
                 var run = self.config.run.effective(using: profile)
                 run.clearingUnsupportedMemoryKnobs(forModelID: self.config.run.modelID)
+                // Fronted mode: the proxy takes the public port; the engine gets an
+                // auto-picked loopback port behind it. No free port → serve starts
+                // unfronted with a note rather than failing the Start.
+                let picked = self.config.loggingEnabled
+                    ? SessionProxy.pickInternalPort(publicPort: self.config.run.port) : nil
+                let plan = Self.frontingPlan(enabled: self.config.loggingEnabled,
+                                             adopted: false, pickedInternalPort: picked)
+                if plan.front, let internalPort = plan.enginePort {
+                    run.port = internalPort
+                } else if self.config.loggingEnabled, picked == nil {
+                    self.server.note("- session logging: no free internal port near \(self.config.run.port); serving directly")
+                }
                 try self.server.launch(config: run,
                                        revision: self.catalogEntry?.revision,
                                        local: local.map {
                                            SplashServer.LocalLaunch(modelDir: $0.path, mmproj: $0.mmproj)
                                        })
+                if plan.front, let internalPort = plan.enginePort {
+                    let px = try SessionProxy(
+                        publicPort: self.config.run.port, internalPort: internalPort,
+                        lanBind: self.config.run.lanAccess,
+                        policy: .init(logLocal: true, logLAN: self.config.loggingLanClients),
+                        log: self.sessionLog)
+                    px.onNote = { msg in Task { @MainActor in self.server.note(msg) } }
+                    px.start()
+                    self.proxy = px
+                    self.frontedEnginePort = internalPort
+                    self.server.note("- session logging: proxy :\(self.config.run.port) → engine :\(internalPort)" +
+                                     (self.config.loggingLanClients ? " (LAN clients recorded)" : " (loopback clients only)"))
+                }
                 self.launchedRunConfig = self.config.run
+                self.launchedLoggingEnabled = self.config.loggingEnabled
                 if let pid = self.server.childPID {
                     AppModel.serverKillPID = pid
                     self.server.spawnWatchdog(serverPID: pid,
@@ -688,6 +735,10 @@ final class AppModel: ObservableObject {
     func stop() {
         pollTask?.cancel()
         pollTask = nil
+        proxy?.stop()
+        proxy = nil
+        frontedEnginePort = nil
+        launchedLoggingEnabled = false
         phase = .stopping
         launchedRunConfig = nil
         if let pid = adoptedPID {
diff --git a/Sources/SplashGUI/Core/SessionLog.swift b/Sources/SplashGUI/Core/SessionLog.swift
new file mode 100644
index 0000000..65d27ed
--- /dev/null
+++ b/Sources/SplashGUI/Core/SessionLog.swift
@@ -0,0 +1,152 @@
+import Foundation
+
+// One proxied /v1 request, end to end, as written to the session log. Full fidelity is
+// the point (the quant corpus wants whole prompts): requestJSON keeps the body verbatim,
+// and the parsed fields beside it are conveniences for the tail view and future export.
+// Unknown response shapes still record: parsed=false plus rawResponse verbatim.
+nonisolated struct SessionRecord: Codable {
+    nonisolated struct ToolCall: Codable, Equatable {
+        var id: String?
+        var name: String?
+        var argumentsJSON: String?
+    }
+    nonisolated struct Usage: Codable, Equatable {
+        var input: Int?
+        var output: Int?
+        var reasoning: Int?
+        var cached: Int?
+    }
+
+    var tsStart: Date
+    var tsEnd: Date?
+    var durationMs: Int?
+    var clientHint: String?          // User-Agent
+    var clientLoopback: Bool?        // loopback peer = "this machine's own client"
+    var path: String
+    var model: String?
+    var stream: Bool?
+    var systemChars: Int?
+    var toolNames: [String]?
+    var requestJSON: String?         // full body, verbatim UTF-8 when decodable
+    var responseText: String?
+    var responseReasoning: String?
+    var toolCalls: [ToolCall]?
+    var finishReason: String?
+    var usage: Usage?
+    var status: Int?
+    var parsed: Bool?                // false = unknown shape; rawResponse holds the body
+    var rawResponse: String?
+    var error: String?               // client-abort | upstream-error | malformed | nil
+}
+
+// JSONL session store: logs/sessions/YYYY-MM-DD.jsonl under the app data dir, written
+// from the proxy queue, purged by day-file name, tailed by the Logging tab.
+final class SessionLog: @unchecked Sendable {
+    let dir: URL
+    private let queue = DispatchQueue(label: "splashgui.sessionlog")
+    private let iso = ISO8601DateFormatter()
+    var lastWriteError: String?
+
+    init(dir: URL? = nil) {
+        self.dir = dir ?? AppPaths.dataDir.appendingPathComponent("logs/sessions", isDirectory: true)
+    }
+
+    nonisolated static func dayFileName(_ date: Date) -> String {
+        let c = Calendar(identifier: .gregorian)
+        let d = c.dateComponents([.year, .month, .day], from: date)
+        return String(format: "%04d-%02d-%02d.jsonl", d.year ?? 1970, d.month ?? 1, d.day ?? 1)
+    }
+
+    // One JSON object per line; Dates ride as ISO-8601 strings so jq/python read them.
+    nonisolated static func encodeLine(_ record: SessionRecord) -> String? {
+        let e = JSONEncoder()
+        e.dateEncodingStrategy = .iso8601
+        guard let data = try? e.encode(record) else { return nil }
+        return String(decoding: data, as: UTF8.self) + "\n"
+    }
+
+    nonisolated static func decodeLine(_ line: String) -> SessionRecord? {
+        let d = JSONDecoder()
+        d.dateDecodingStrategy = .iso8601
+        return try? d.decode(SessionRecord.self, from: Data(line.utf8))
+    }
+
+    func write(_ record: SessionRecord) {
+        guard let line = Self.encodeLine(record) else {
+            lastWriteError = "encode failed"
+            return
+        }
+        queue.async {
+            do {
+                try FileManager.default.createDirectory(at: self.dir, withIntermediateDirectories: true)
+                let url = self.dir.appendingPathComponent(Self.dayFileName(record.tsStart))
+                if !FileManager.default.fileExists(atPath: url.path) {
+                    FileManager.default.createFile(atPath: url.path, contents: nil)
+                }
+                let h = try FileHandle(forWritingTo: url)
+                defer { try? h.close() }
+                h.seekToEndOfFile()
+                h.write(Data(line.utf8))
+                self.lastWriteError = nil
+            } catch {
+                // Logging must never break forwarding; the failure is surfaced in the tab.
+                self.lastWriteError = "\(error)"
+            }
+        }
+    }
+
+    // Purge day-files older than the cutoff. Files that don't parse as a date are left
+    // alone — never delete what we can't name.
+    @discardableResult
+    static func purge(dir: URL, retentionDays: Int, now: Date = Date()) -> [String] {
+        guard retentionDays > 0,
+              let names = try? FileManager.default.contentsOfDirectory(atPath: dir.path) else { return [] }
+        let cutoffDay = dayFileName(Calendar(identifier: .gregorian)
+            .date(byAdding: .day, value: -retentionDays, to: now) ?? now)
+        var removed: [String] = []
+        for n in names where n.hasSuffix(".jsonl") {
+            let day = String(n.dropLast(".jsonl".count))
+            let c = Array(day)
+            guard c.count == 10, c[4] == "-", c[7] == "-",
+                  [0, 1, 2, 3, 5, 6, 8, 9].allSatisfy({ c[$0].isNumber }),
+                  day < cutoffDay else { continue }
+            try? FileManager.default.removeItem(at: dir.appendingPathComponent(n))
+            removed.append(n)
+        }
+        return removed
+    }
+
+    // Newest-last: the tail of today's file (falling back to the newest file present).
+    static func tail(dir: URL, limit: Int, now: Date = Date()) -> [SessionRecord] {
+        let fm = FileManager.default
+        var url = dir.appendingPathComponent(dayFileName(now))
+        if !fm.fileExists(atPath: url.path) {
+            guard let names = (try? fm.contentsOfDirectory(atPath: dir.path))?
+                    .filter({ $0.hasSuffix(".jsonl") }).sorted(),
+                  let last = names.last else { return [] }
+            url = dir.appendingPathComponent(last)
+        }
+        guard let data = try? Data(contentsOf: url),
+              let text = String(data: data, encoding: .utf8) else { return [] }
+        let lines = text.split(separator: "\n", omittingEmptySubsequences: true)
+        return lines.suffix(limit).reversed().compactMap { decodeLine(String($0)) }
+    }
+
+    struct Stats { var sessionsToday = 0; var totalBytes = 0; var fileCount = 0 }
+
+    static func stats(dir: URL, now: Date = Date()) -> Stats {
+        let fm = FileManager.default
+        var s = Stats()
+        guard let names = (try? fm.contentsOfDirectory(atPath: dir.path))?
+                .filter({ $0.hasSuffix(".jsonl") }).sorted() else { return s }
+        s.fileCount = names.count
+        for n in names {
+            let u = dir.appendingPathComponent(n)
+            s.totalBytes += (try? u.resourceValues(forKeys: [.fileSizeKey]))?.fileSize ?? 0
+            if n == dayFileName(now), let data = try? Data(contentsOf: u) {
+                s.sessionsToday = data.filter { $0 == UInt8(ascii: "\n") }.count
+            }
+        }
+        return s
+    }
+}
diff --git a/Sources/SplashGUI/Core/SessionProxy.swift b/Sources/SplashGUI/Core/SessionProxy.swift
new file mode 100644
index 0000000..ad7fca7
--- /dev/null
+++ b/Sources/SplashGUI/Core/SessionProxy.swift
@@ -0,0 +1,683 @@
+import Foundation
+import Network
+
+// A loopback HTTP proxy that fronts the PUBLIC serve port while logging is on:
+//     clients ──► proxy :<public> ──► engine :<internal>
+// Forwarding is a dumb byte pipe and NEVER depends on the logging layer: the parsers
+// are a tee that consumes copies. Anything unparseable still flows; at worst the
+// record is flagged malformed. Only /v1/* is recorded; /status, the webui, etc.
+// proxy silently.
+//
+// The parse layer below the transport is pure and harness-tested (head parse, chunked
+// framing, SSE reassembly, OpenAI chat/responses shapes, request summary).
+nonisolated enum HTTPParse {
+    struct Head {
+        var method: String?     // request
+        var path: String?       // request
+        var status: Int?        // response
+        var headers: [String: String]   // lowercased keys
+    }
+
+    // Index just past the CRLFCRLF, else nil.
+    static func findHeadEnd(_ buf: Data) -> Int? {
+        let bytes = [UInt8](buf)
+        guard bytes.count >= 4 else { return nil }
+        var i = 0
+        while i <= bytes.count - 4 {
+            if bytes[i] == 13, bytes[i + 1] == 10, bytes[i + 2] == 13, bytes[i + 3] == 10 {
+                return i + 4
+            }
+            i += 1
+        }
+        return nil
+    }
+
+    static func parseHead(_ data: Data) -> Head? {
+        guard let text = String(data: data, encoding: .utf8) else { return nil }
+        var lines = text.components(separatedBy: "\r\n")
+        guard let first = lines.first, !first.isEmpty else { return nil }
+        lines.removeFirst()
+        var h = Head(headers: [:])
+        let parts = first.split(separator: " ", maxSplits: 2, omittingEmptySubsequences: true)
+        if parts.count >= 2, parts[0].uppercased().hasPrefix("HTTP/"), let code = Int(parts[1]) {
+            h.status = code            // "HTTP/1.1 200 OK"
+        } else if parts.count >= 2 {
+            h.method = String(parts[0]); h.path = String(parts[1])   // "POST /v1/... HTTP/1.1"
+        } else {
+            return nil
+        }
+        for line in lines where !line.isEmpty {
+            // Continuation lines (obs-fold) are ancient; tolerate by ignoring lines
+            // without a colon rather than failing the whole head.
+            guard let colon = line.firstIndex(of: ":") else { continue }
+            let k = line[line.startIndex..<colon].trimmingCharacters(in: .whitespaces).lowercased()
+            let v = line[line.index(after: colon)...].trimmingCharacters(in: .whitespaces)
+            if !k.isEmpty { h.headers[k] = v }
+        }
+        return h
+    }
+
+    enum Framing { case length(Int), chunked, none }
+
+    static func bodyFraming(head: Head) -> Framing {
+        if (head.headers["transfer-encoding"] ?? "").lowercased().contains("chunked") { return .chunked }
+        if let cl = head.headers["content-length"], let n = Int(cl) { return .length(n) }
+        if let m = head.method, ["POST", "PUT", "PATCH"].contains(m.uppercased()) {
+            return .length(0)   // POST without a declared body: empty
+        }
+        return .none
+    }
+
+    // Incremental chunked-transfer decoder: feed wire bytes, get body bytes back.
+    final class ChunkedDecoder {
+        private var buf = Data()
+        private var done = false
+        var isComplete: Bool { done }
+
+        func feed(_ data: Data) -> Data {
+            if done { return Data() }
+            buf.append(data)
+            var out = Data()
+            while true {
+                guard let idx = Self.findCRLF(buf) else { break }
+                // Chunk sizes are HEX per RFC 7230 ("1f\r\n" = 31 bytes); extensions
+                // (";name=value") ride on the size line.
+                let sizeText = String(decoding: buf.subdata(in: 0..<idx), as: UTF8.self)
+                    .trimmingCharacters(in: .whitespacesAndNewlines)
+                let sizeHex = sizeText.split(separator: ";", maxSplits: 1).first.map(String.init) ?? sizeText
+                guard let size = Int(sizeHex, radix: 16) else { break }
+                if size == 0 {
+                    // Trailing headers run to the next blank line; swallow what we have.
+                    buf.removeAll(); done = true; break
+                }
+                let bodyStart = idx + 2
+                guard buf.count >= bodyStart + size + 2 else { break }
+                out.append(buf.subdata(in: bodyStart..<(bodyStart + size)))
+                buf.removeSubrange(0..<(bodyStart + size + 2))
+            }
+            return out
+        }
+
+        private static func findCRLF(_ d: Data) -> Data.Index? {
+            var i = d.startIndex
+            while i < d.endIndex {
+                if d[i] == 13, d.index(after: i) < d.endIndex, d[d.index(after: i)] == 10 { return i }
+                i += 1
+            }
+            return nil
+        }
+    }
+
+    // The JSON body assembled from a request we captured, minus anything unparsable.
+    struct RequestSummary {
+        var model: String?
+        var stream = false
+        var systemChars = 0
+        var toolNames: [String] = []
+    }
+
+    static func summarizeRequest(_ body: Data) -> RequestSummary {
+        var s = RequestSummary()
+        guard let obj = try? JSONSerialization.jsonObject(with: body) as? [String: Any] else { return s }
+        s.model = obj["model"] as? String
+        s.stream = (obj["stream"] as? Bool) ?? false
+        if let msgs = obj["messages"] as? [[String: Any]] {
+            s.systemChars = msgs.filter { ($0["role"] as? String) == "system" }
+                .reduce(into: 0) { acc, m in acc += (m["content"] as? String)?.count ?? 0 }
+        }
+        if let tools = obj["tools"] as? [[String: Any]] {
+            s.toolNames = tools.compactMap { ($0["function"] as? [String: Any])?["name"] as? String }
+        }
+        return s
+    }
+}
+
+// OpenAI chat-completions and Responses shapes, both streaming and not, folded into a
+// SessionRecord. Shape-based on purpose: unknown fields are ignored, unknown top-level
+// shapes flip parsed=false and keep the raw body so nothing is ever silently dropped.
+nonisolated final class SSEReassembler {
+    private var lineBuf = ""
+    private(set) var text = ""
+    private(set) var reasoning = ""
+    private(set) var toolCalls: [Int: SessionRecord.ToolCall] = [:]   // chat: by index
+    private var toolOrder: [Int] = []
+    private(set) var finishReason: String?
+    var usage: SessionRecord.Usage?
+    private(set) var sawDone = false
+    private(set) var sawUnknown = false
+
+    func feed(_ data: Data) {
+        lineBuf += String(decoding: data, as: UTF8.self)
+        while let nl = lineBuf.firstIndex(of: "\n") {
+            let raw = String(lineBuf[lineBuf.startIndex..<nl]).trimmingCharacters(in: .init(charactersIn: "\r"))
+            lineBuf = String(lineBuf[lineBuf.index(after: nl)...])
+            consume(line: raw)
+        }
+    }
+
+    private func consume(line: String) {
+        guard line.hasPrefix("data:") else { return }   // event:/id:/retry:/comments: ignorable
+        var payload = String(line.dropFirst(5))
+        if payload.hasPrefix(" ") { payload.removeFirst() }
+        if payload == "[DONE]" { sawDone = true; return }
+        guard let j = payload.data(using: .utf8),
+              let obj = try? JSONSerialization.jsonObject(with: j) as? [String: Any] else {
+            sawUnknown = true; return
+        }
+        if let type = obj["type"] as? String {
+            applyResponsesEvent(type, obj)
+            return
+        }
+        applyChatChunk(obj)
+    }
+
+    private func applyChatChunk(_ obj: [String: Any]) {
+        if let u = obj["usage"] as? [String: Any] { usage = HTTPParseTee.chatUsage(u) }
+        guard let choices = obj["choices"] as? [[String: Any]], let c = choices.first else { return }
+        if let fr = c["finish_reason"] as? String { finishReason = fr }
+        guard let delta = c["delta"] as? [String: Any] else { return }
+        if let t = delta["content"] as? String { text += t }
+        if let r = (delta["reasoning_content"] ?? delta["reasoning"]) as? String { reasoning += r }
+        if let tcs = delta["tool_calls"] as? [[String: Any]] {
+            for tc in tcs {
+                let idx = (tc["index"] as? Int) ?? 0
+                var entry = toolCalls[idx] ?? SessionRecord.ToolCall()
+                if toolCalls[idx] == nil { toolOrder.append(idx) }
+                if let id = tc["id"] as? String { entry.id = id }
+                if let fn = tc["function"] as? [String: Any] {
+                    if let n = fn["name"] as? String { entry.name = (entry.name ?? "") + n }
+                    if let a = fn["arguments"] as? String { entry.argumentsJSON = (entry.argumentsJSON ?? "") + a }
+                }
+                toolCalls[idx] = entry
+            }
+        }
+    }
+
+    private func applyResponsesEvent(_ type: String, _ obj: [String: Any]) {
+        switch type {
+        case "response.output_text.delta":
+            if let d = obj["delta"] as? String { text += d }
+        case "response.reasoning_text.delta", "response.reasoning_summary_text.delta":
+            if let d = obj["delta"] as? String { reasoning += d }
+        case "response.function_call_arguments.delta":
+            let key = (obj["item_id"] as? String)?.hashValue ?? toolOrder.count
+            var entry = toolCalls[key] ?? SessionRecord.ToolCall()
+            if toolCalls[key] == nil { toolOrder.append(key) }
+            if let id = obj["item_id"] as? String { entry.id = id }
+            if let d = obj["delta"] as? String { entry.argumentsJSON = (entry.argumentsJSON ?? "") + d }
+            toolCalls[key] = entry
+        case "response.completed":
+            if let resp = obj["response"] as? [String: Any] {
+                finishReason = resp["status"] as? String
+                if let u = resp["usage"] as? [String: Any] { usage = HTTPParseTee.responsesUsage(u) }
+            }
+        case "response.created", "response.in_progress", "response.output_item.added",
+             "response.output_item.done", "response.content_part.added", "response.content_part.done",
+             "response.output_text.done", "response.function_call_arguments.done",
+             "response.refusal.delta", "response.refusal.done":
+            break   // lifecycle events; the payloads above carry the content
+        default:
+            sawUnknown = true
+        }
+    }
+
+    func result() -> (text: String, reasoning: String, toolCalls: [SessionRecord.ToolCall],
+                      finish: String?, usage: SessionRecord.Usage?, sawUnknown: Bool, sawDone: Bool) {
+        let calls = toolOrder.compactMap { toolCalls[$0] }
+        return (text, reasoning, calls, finishReason, usage, sawUnknown, sawDone)
+    }
+}
+
+// Shared shape helpers for the non-streaming side.
+nonisolated enum HTTPParseTee {
+    static func chatUsage(_ u: [String: Any]) -> SessionRecord.Usage {
+        var x = SessionRecord.Usage()
+        x.input = u["prompt_tokens"] as? Int
+        x.output = u["completion_tokens"] as? Int
+        x.reasoning = (u["completion_tokens_details"] as? [String: Any])?["reasoning_tokens"] as? Int
+        x.cached = (u["prompt_tokens_details"] as? [String: Any])?["cached_tokens"] as? Int
+        return x
+    }
+    static func responsesUsage(_ u: [String: Any]) -> SessionRecord.Usage {
+        var x = SessionRecord.Usage()
+        x.input = u["input_tokens"] as? Int
+        x.output = u["output_tokens"] as? Int
+        x.reasoning = (u["output_tokens_details"] as? [String: Any])?["reasoning_tokens"] as? Int
+        x.cached = (u["input_tokens_details"] as? [String: Any])?["cached_tokens"] as? Int
+        return x
+    }
+
+    // Non-streaming JSON body → record fields; nil parsed flag means unknown shape.
+    static func parseJSONBody(_ data: Data)
+        -> (text: String?, reasoning: String?, toolCalls: [SessionRecord.ToolCall]?,
+            finish: String?, usage: SessionRecord.Usage?, parsed: Bool) {
+        guard let obj = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else {
+            return (nil, nil, nil, nil, nil, false)
+        }
+        // chat.completions
+        if let choices = obj["choices"] as? [[String: Any]], let c = choices.first,
+           let msg = c["message"] as? [String: Any] {
+            var calls: [SessionRecord.ToolCall] = []
+            if let tcs = msg["tool_calls"] as? [[String: Any]] {
+                for tc in tcs {
+                    var e = SessionRecord.ToolCall()
+                    e.id = tc["id"] as? String
+                    if let fn = tc["function"] as? [String: Any] {
+                        e.name = fn["name"] as? String
+                        e.argumentsJSON = fn["arguments"] as? String
+                    }
+                    calls.append(e)
+                }
+            }
+            let r = (msg["reasoning_content"] ?? msg["reasoning"]) as? String
+            var usage: SessionRecord.Usage?
+            if let u = obj["usage"] as? [String: Any] { usage = chatUsage(u) }
+            return (msg["content"] as? String, r, calls.isEmpty ? nil : calls,
+                    c["finish_reason"] as? String, usage, true)
+        }
+        // Responses API object
+        if let output = obj["output"] as? [[String: Any]] {
+            var text = "", reasoning = ""
+            var calls: [SessionRecord.ToolCall] = []
+            for item in output {
+                switch item["type"] as? String {
+                case "message":
+                    for part in (item["content"] as? [[String: Any]]) ?? [] {
+                        if (part["type"] as? String) == "output_text", let t = part["text"] as? String { text += t }
+                    }
+                case "reasoning":
+                    for part in (item["summary"] as? [[String: Any]]) ?? [] {
+                        if let t = part["text"] as? String { reasoning += t }
+                    }
+                case "function_call":
+                    var e = SessionRecord.ToolCall()
+                    e.id = item["call_id"] as? String
+                    e.name = item["name"] as? String
+                    e.argumentsJSON = item["arguments"] as? String
+                    calls.append(e)
+                default: break
+                }
+            }
+            var usage: SessionRecord.Usage?
+            if let u = obj["usage"] as? [String: Any] { usage = responsesUsage(u) }
+            return (text, reasoning.isEmpty ? nil : reasoning, calls.isEmpty ? nil : calls,
+                    obj["status"] as? String, usage, true)
+        }
+        return (nil, nil, nil, nil, nil, false)
+    }
+}
+
+extension Data {
+    fileprivate func hexTrimmed() -> String {
+        String(decoding: self, as: UTF8.self).trimmingCharacters(in: .whitespacesAndNewlines)
+    }
+}
+// MARK: - transport
+
+// NWListener byte pipe with the tee bolted on. One Flow per client connection;
+// everything runs on the proxy's serial queue so the Flow state machines need no
+// locks. Callbacks capture Flow strongly only for the duration of a receive; the
+// proxy keeps the connection table.
+final class SessionProxy: @unchecked Sendable {
+    struct Policy {
+        var logLocal = true       // loopback peers
+        var logLAN = false        // non-loopback peers (only reachable when LAN serve is on)
+    }
+
+    let publicPort: Int
+    private let internalPort: Int
+    private let listener: NWListener
+    private let queue = DispatchQueue(label: "splashgui.sessionproxy")
+    private var flows: [ObjectIdentifier: Flow] = [:]
+    private let policy: Policy
+    private let log: SessionLog
+    var onNote: ((String) -> Void)?     // fires on a background queue; callers hop
+
+    init(publicPort: Int, internalPort: Int, lanBind: Bool, policy: Policy, log: SessionLog) throws {
+        self.publicPort = publicPort
+        self.internalPort = internalPort
+        self.policy = policy
+        self.log = log
+        guard let port = NWEndpoint.Port(rawValue: UInt16(publicPort)) else {
+            throw InstallError.preflight("Logging proxy port \(publicPort) is out of range.")
+        }
+        let params = NWParameters.tcp
+        // The port rides in requiredLocalEndpoint; passing it to NWListener(using:on:)
+        // as well throws EINVAL (two sources of truth for the bind).
+        params.requiredLocalEndpoint = NWEndpoint.hostPort(
+            host: lanBind ? "0.0.0.0" : "127.0.0.1", port: port)
+        params.allowLocalEndpointReuse = true
+        listener = try NWListener(using: params)
+    }
+
+    func start() {
+        listener.newConnectionHandler = { [weak self] conn in self?.accept(conn) }
+        listener.start(queue: queue)
+    }
+
+    func stop() {
+        listener.cancel()
+        for f in flows.values { f.teardown() }
+        flows.removeAll()
+    }
+
+    private func accept(_ client: NWConnection) {
+        var loopback = true
+        if case let .hostPort(host, _) = client.endpoint {
+            let h = String(describing: host)
+            loopback = h.hasPrefix("127.") || h == "::1" || h == "localhost"
+        }
+        let upstream = NWConnection(host: "127.0.0.1", port: NWEndpoint.Port(rawValue: UInt16(internalPort))!, using: .tcp)
+        let flow = Flow(client: client, upstream: upstream, loopback: loopback,
+                        policy: policy, log: log, queue: queue,
+                        onNote: { [weak self] msg in self?.onNote?(msg) },
+                        onDead: { [weak self] in
+                            self?.queue.async { self?.flows[ObjectIdentifier(client)] = nil }
+                        })
+        flows[ObjectIdentifier(client)] = flow
+        flow.begin()
+    }
+
+    // Pure rule the harness pins: does this peer get RECORDED (everything always gets piped)?
+    nonisolated static func shouldRecord(policy: Policy, loopbackPeer: Bool) -> Bool {
+        loopbackPeer ? policy.logLocal : policy.logLAN
+    }
+
+    // Free-port pick for the engine behind the proxy: probe-bind starting at public+1.
+    nonisolated static func pickInternalPort(publicPort: Int, tries: Int = 32) -> Int? {
+        for candidate in (publicPort + 1)...(publicPort + tries) {
+            guard candidate < 65_536 else { break }
+            if isPortFree(candidate) { return candidate }
+        }
+        return nil
+    }
+
+    nonisolated static func isPortFree(_ port: Int) -> Bool {
+        let fd = socket(AF_INET, SOCK_STREAM, 0)
+        guard fd >= 0 else { return false }
+        defer { close(fd) }
+        var yes: Int32 = 1
+        setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &yes, socklen_t(MemoryLayout<Int32>.size))
+        var addr = sockaddr_in()
+        addr.sin_family = sa_family_t(AF_INET)
+        addr.sin_port = in_port_t(port).bigEndian
+        addr.sin_addr = in_addr(s_addr: inet_addr("127.0.0.1"))
+        return withUnsafePointer(to: &addr) {
+            $0.withMemoryRebound(to: sockaddr.self, capacity: 1) {
+                bind(fd, $0, socklen_t(MemoryLayout<sockaddr_in>.size)) == 0
+            }
+        }
+    }
+}
+
+extension SessionProxy {
+    private final class Flow {
+        private let client: NWConnection
+        private let upstream: NWConnection
+        private let loopback: Bool
+        private let policy: SessionProxy.Policy
+        private let log: SessionLog
+        private let queue: DispatchQueue
+        private let onDead: () -> Void
+        private let onNote: (String) -> Void
+
+        // request side
+        private var reqBuf = Data()
+        private var record: SessionRecord?
+        private var recordWanted = false
+        private var reqDone = false
+        private var reqBody = Data()
+        private var reqNeed = -1                       // -1 unknown, 0..n remaining, -2 chunked
+        private var reqChunker: HTTPParse.ChunkedDecoder?
+        // response side
+        private var respBuf = Data()
+        private var respMode: RespMode = .head
+        private var respSSE: SSEReassembler?
+        private var respJSON = Data()
+        private var respNeed = -1
+        private var respChunker: HTTPParse.ChunkedDecoder?
+        private var respStatus: Int?
+        private var finalized = false
+        private var beganUpstream = false
+
+        enum RespMode { case head, sse, json, ignore }
+
+        private static let headCap = 64 * 1024
+        private static let bodyCap = 8 * 1024 * 1024
+
+        init(client: NWConnection, upstream: NWConnection, loopback: Bool,
+             policy: SessionProxy.Policy, log: SessionLog, queue: DispatchQueue,
+             onNote: @escaping (String) -> Void, onDead: @escaping () -> Void) {
+            self.client = client; self.upstream = upstream; self.loopback = loopback
+            self.policy = policy; self.log = log; self.queue = queue
+            self.onNote = onNote; self.onDead = onDead
+        }
+
+        func begin() {
+            client.stateUpdateHandler = { [weak self] st in
+                switch st {
+                case .ready: self?.queue.async { self?.startUpstream() }
+                case .failed, .cancelled: self?.queue.async { self?.clientGone() }
+                default: break
+                }
+            }
+            client.start(queue: queue)
+        }
+
+        private func startUpstream() {
+            guard !beganUpstream else { return }
+            beganUpstream = true
+            upstream.stateUpdateHandler = { [weak self] st in
+                switch st {
+                case .ready: self?.queue.async { self?.pumpClient(); self?.pumpUpstream() }
+                case .failed: self?.queue.async { self?.upstreamGone(error: "connect failed") }
+                case .cancelled: self?.queue.async { self?.upstreamGone(error: nil) }
+                default: break
+                }
+            }
+            upstream.start(queue: queue)
+        }
+
+        // MARK: client → upstream
+
+        private func pumpClient() {
+            client.receive(minimumIncompleteLength: 1, maximumLength: 64 * 1024) { [weak self] data, _, complete, error in
+                self?.queue.async {
+                    guard let self else { return }
+                    if let d = data, !d.isEmpty { self.teeRequest(d) }
+                    if let d = data, !d.isEmpty {
+                        self.upstream.send(content: d, completion: .contentProcessed { [weak self] e in
+                            if e != nil { self?.queue.async { self?.upstreamGone(error: "send failed") } }
+                        })
+                    }
+                    if complete || error != nil { self.clientGone(); return }
+                    self.pumpClient()
+                }
+            }
+        }
+
+        private func teeRequest(_ data: Data) {
+            if recordWanted, !reqDone {
+                consumeReqBody(data)
+                return
+            }
+            guard record == nil, !finalized else { return }
+            reqBuf.append(data)
+            if reqBuf.count > Self.headCap { malformed(note: "head too large"); return }
+            guard let end = HTTPParse.findHeadEnd(reqBuf) else { return }
+            guard let head = HTTPParse.parseHead(reqBuf[reqBuf.startIndex..<reqBuf.startIndex + end]) else {
+                malformed(note: "unparseable head"); return
+            }
+            let path = head.path ?? ""
+            reqBuf = Data(reqBuf.dropFirst(end))
+            guard path.hasPrefix("/v1/") else { return }          // pipe silently, no record
+            recordWanted = SessionProxy.shouldRecord(policy: policy, loopbackPeer: loopback)
+            guard recordWanted else { return }
+            record = SessionRecord(tsStart: Date(), clientHint: head.headers["user-agent"],
+                                   clientLoopback: loopback, path: path)
+            switch HTTPParse.bodyFraming(head: head) {
+            case .none: reqNeed = 0
+            case .length(let n): reqNeed = n
+            case .chunked: reqNeed = -2; reqChunker = HTTPParse.ChunkedDecoder()
+            }
+            consumeReqBody(reqBuf)                                // head + body may share a read
+            reqBuf = Data()
+        }
+
+        private func consumeReqBody(_ data: Data) {
+            guard recordWanted, !reqDone else { return }
+            if reqNeed == -2 {
+                if let out = reqChunker?.feed(data) { reqBody.append(out) }
+                if reqChunker?.isComplete == true { finishRequest() }
+                return
+            }
+            reqBody.append(data)
+            reqNeed -= data.count
+            if reqNeed <= 0 { finishRequest() }
+        }
+
+        private func finishRequest() {
+            guard !reqDone else { return }
+            reqDone = true
+            guard var rec = record else { return }
+            if reqBody.count > Self.bodyCap {
+                rec.error = "malformed"; rec.parsed = false
+                record = rec; return
+            }
+            rec.requestJSON = String(data: reqBody, encoding: .utf8)
+            let s = HTTPParse.summarizeRequest(reqBody)
+            rec.model = s.model; rec.stream = s.stream
+            rec.systemChars = s.systemChars; rec.toolNames = s.toolNames.isEmpty ? nil : s.toolNames
+            record = rec
+        }
+
+        private func malformed(note: String) {
+            guard recordWanted || record != nil else { reqBuf = Data(); return }
+            var rec = record ?? SessionRecord(tsStart: Date(), path: "/v1/malformed")
+            rec.error = "malformed"
+            record = rec
+            onNote("logging: malformed request (\(note)) — traffic unaffected")
+        }
+
+        // MARK: upstream → client
+
+        private func pumpUpstream() {
+            upstream.receive(minimumIncompleteLength: 1, maximumLength: 64 * 1024) { [weak self] data, _, complete, error in
+                self?.queue.async {
+                    guard let self else { return }
+                    if let d = data, !d.isEmpty { self.client.send(content: d, completion: .contentProcessed { _ in }) }
+                    if let d = data, !d.isEmpty { self.teeResponse(d) }
+                    if complete || error != nil { self.upstreamGone(error: error == nil ? nil : "upstream closed"); return }
+                    self.pumpUpstream()
+                }
+            }
+        }
+
+        private func teeResponse(_ data: Data) {
+            guard recordWanted else { return }
+            switch respMode {
+            case .head:
+                respBuf.append(data)
+                if respBuf.count > Self.headCap { respMode = .ignore; return }
+                guard let end = HTTPParse.findHeadEnd(respBuf) else { return }
+                if let h = HTTPParse.parseHead(respBuf[respBuf.startIndex..<respBuf.startIndex + end]) {
+                    respStatus = h.status
+                    let ct = h.headers["content-type"] ?? ""
+                    if ct.contains("text/event-stream") { respMode = .sse; respSSE = SSEReassembler() }
+                    else if ct.contains("json") {
+                        respMode = .json
+                        switch HTTPParse.bodyFraming(head: h) {
+                        case .length(let n): respNeed = n
+                        case .chunked: respNeed = -2; respChunker = HTTPParse.ChunkedDecoder()
+                        case .none: respNeed = 0
+                        }
+                    } else { respMode = .ignore }
+                    respBuf = Data(respBuf.dropFirst(end))
+                    if !respBuf.isEmpty { teeResponse(respBuf); respBuf = Data() }
+                } else { respMode = .ignore }
+            case .sse:
+                respSSE?.feed(data)
+                if respSSE?.result().sawDone == true { finalize(error: nil) }
+            case .json:
+                if respNeed == -2 {
+                    if let out = respChunker?.feed(data) { respJSON.append(out) }
+                    if respChunker?.isComplete == true { finishResponseJSON() }
+                } else {
+                    respJSON.append(data)
+                    if respNeed >= 0, respJSON.count >= respNeed { finishResponseJSON() }
+                }
+            case .ignore:
+                break
+            }
+        }
+
+        private func finishResponseJSON() {
+            defer { finalize(error: nil) }
+            guard var rec = record, respMode == .json else { return }
+            let p = HTTPParseTee.parseJSONBody(respJSON)
+            if p.parsed {
+                rec.responseText = p.text; rec.responseReasoning = p.reasoning
+                rec.toolCalls = p.toolCalls; rec.finishReason = p.finish; rec.usage = p.usage
+                rec.parsed = true
+            } else {
+                rec.parsed = false
+                rec.rawResponse = String(data: respJSON, encoding: .utf8)
+            }
+            record = rec
+        }
+
+        // MARK: lifecycle
+
+        private func finalize(error: String?) {
+            guard !finalized, var rec = record else { return }
+            finalized = true
+            let now = Date()
+            rec.tsEnd = now
+            rec.durationMs = Int(now.timeIntervalSince(rec.tsStart) * 1000)
+            rec.status = respStatus
+            if let sse = respSSE {
+                let r = sse.result()
+                rec.responseText = r.text.isEmpty ? nil : r.text
+                rec.responseReasoning = r.reasoning.isEmpty ? nil : r.reasoning
+                rec.toolCalls = r.toolCalls.isEmpty ? nil : r.toolCalls
+                rec.finishReason = r.finish
+                rec.usage = r.usage
+                if r.sawUnknown { rec.parsed = false }
+            }
+            if error != nil { rec.error = error }
+            log.write(rec)
+            record = nil
+            recordWanted = false
+            // keep-alive: a clean completed exchange re-arms the parser for the next request.
+            if error == nil {
+                reqBuf = Data(); reqDone = false; reqBody = Data(); reqNeed = -1; reqChunker = nil
+                respBuf = Data(); respMode = .head; respSSE = nil; respJSON = Data()
+                respNeed = -1; respChunker = nil; respStatus = nil; finalized = false
+            }
+        }
+
+        private func clientGone() {
+            if record != nil, !finalized { finalize(error: "client-abort") }
+            teardown()
+        }
+
+        private func upstreamGone(error: String?) {
+            if error != nil, record != nil, !finalized {
+                if respStatus == nil, let rec = record, rec.requestJSON != nil || reqDone {
+                    let body = Data("HTTP/1.1 502 Bad Gateway\r\ncontent-length: 0\r\nconnection: close\r\n\r\n".utf8)
+                    client.send(content: body, completion: .contentProcessed { _ in })
+                }
+                finalize(error: "upstream-error")
+            } else if record != nil, !finalized {
+                // Clean upstream close mid-response (some servers close instead of [DONE]).
+                finalize(error: respStatus == nil ? "upstream-error" : nil)
+            }
+            teardown()
+        }
+
+        func teardown() {
+            client.cancel(); upstream.cancel()
+            onDead()
+        }
+    }
+}
diff --git a/Sources/SplashGUI/Views/LoggingTab.swift b/Sources/SplashGUI/Views/LoggingTab.swift
new file mode 100644
index 0000000..c186325
--- /dev/null
+++ b/Sources/SplashGUI/Views/LoggingTab.swift
@@ -0,0 +1,151 @@
+import SwiftUI
+import AppKit
+
+// Session logging controls and the live tail (scratch/spec-logging-proxy.md). Logging is
+// opt-in and full-fidelity: whole prompts, replies, reasoning and tool calls as JSONL,
+// with day-file retention as the only cap. The proxy fronts the public port, so client
+// configs never change.
+struct LoggingTab: View {
+    @EnvironmentObject var model: AppModel
+    @State private var stats = SessionLog.Stats()
+    @State private var tail: [SessionRecord] = []
+
+    var body: some View {
+        SettingsPage {
+            SettingsSection("Session logging") {
+                Toggle("Log /v1 sessions through the app proxy", isOn: $model.config.loggingEnabled)
+                if model.phase != .stopped && model.launchedLoggingEnabled != model.config.loggingEnabled {
+                    Label("Applies on the next Start (the proxy binds when the serve launches).",
+                          systemImage: "arrow.triangle.2.circlepath")
+                        .font(.callout)
+                        .foregroundStyle(.secondary)
+                }
+                Text(statusLine)
+                    .font(.callout)
+                    .foregroundStyle(.secondary)
+
+                Divider()
+                Toggle("Also record LAN clients", isOn: $model.config.loggingLanClients)
+                    .disabled(!model.config.run.lanAccess)
+                if model.config.run.lanAccess && model.config.loggingEnabled {
+                    Label(model.config.loggingLanClients
+                          ? "LAN clients are recorded: machines on your network have their turns logged too."
+                          : "LAN clients keep working through the proxy but are NOT recorded; loopback clients are.",
+                          systemImage: model.config.loggingLanClients ? "exclamationmark.triangle" : "lock.shield")
+                        .font(.callout)
+                        .foregroundStyle(model.config.loggingLanClients ? .orange : .secondary)
+                }
+            }
+            SettingsSection("Storage") {
+                Picker("Keep logs for", selection: $model.config.loggingRetentionDays) {
+                    Text("7 days").tag(7)
+                    Text("30 days").tag(30)
+                    Text("90 days").tag(90)
+                    Text("1 year").tag(365)
+                }
+                .frame(maxWidth: 240, alignment: .leading)
+                HStack(spacing: 16) {
+                    Text("\(stats.sessionsToday) sessions today · \(bytes(stats.totalBytes)) in \(stats.fileCount) file(s)")
+                    Button("Open log folder") { NSWorkspace.shared.open(model.sessionLog.dir) }
+                    Button("Refresh") { load() }
+                }
+                .font(.callout)
+                if let err = model.sessionLog.lastWriteError {
+                    Label("Log write problem: \(err)", systemImage: "exclamationmark.triangle")
+                        .font(.callout)
+                        .foregroundStyle(.orange)
+                }
+                Text("Full prompts, replies, reasoning and tool calls, one JSON object per request at \(model.sessionLog.dir.path). Point clients at http://127.0.0.1:\(model.config.run.port)/v1 as always; while logging is on, the app sits between them and the engine.")
+                    .font(.caption)
+                    .foregroundStyle(.secondary)
+            }
+            SettingsSection("Recent sessions") {
+                if tail.isEmpty {
+                    Text("Nothing logged yet.")
+                        .font(.callout)
+                        .foregroundStyle(.secondary)
+                }
+                ForEach(Array(tail.enumerated()), id: \.offset) { _, r in
+                    SessionRow(record: r)
+                }
+            }
+        }
+        .onAppear { load() }
+    }
+
+    private var statusLine: String {
+        if let internalPort = model.frontedEnginePort {
+            return "Running: proxy :\(model.config.run.port) → engine :\(internalPort)"
+        }
+        if model.phase == .ready, model.launchedLoggingEnabled {
+            return "Serving directly (logging could not front the port; see the Run log)."
+        }
+        return model.config.loggingEnabled
+            ? "Armed: the next Start runs the serve behind the proxy."
+            : "Off: the serve runs directly on port \(model.config.run.port)."
+    }
+
+    private func bytes(_ n: Int) -> String {
+        if n >= 1_000_000_000 { return String(format: "%.1f GB", Double(n) / 1e9) }
+        if n >= 1_000_000 { return String(format: "%.1f MB", Double(n) / 1e6) }
+        if n >= 1_000 { return "\(n / 1000) KB" }
+        return "\(n) B"
+    }
+
+    private func load() {
+        let log = model.sessionLog
+        Task.detached(priority: .utility) {
+            let s = SessionLog.stats(dir: log.dir)
+            let t = SessionLog.tail(dir: log.dir, limit: 20)
+            await MainActor.run {
+                stats = s
+                tail = t
+            }
+        }
+    }
+}
+
+// One collapsed line per record; expanded shows the full JSON of the turn.
+private struct SessionRow: View {
+    let record: SessionRecord
+    @State private var open = false
+
+    var body: some View {
+        DisclosureGroup(isExpanded: $open) {
+            Text(prettyJSON)
+                .font(.system(.caption, design: .monospaced))
+                .textSelection(.enabled)
+                .frame(maxWidth: .infinity, alignment: .leading)
+        } label: {
+            HStack(spacing: 10) {
+                Text(time).font(.caption.monospaced())
+                Text(record.model ?? "?").font(.caption).lineLimit(1)
+                Spacer()
+                if let e = record.error {
+                    Text(e).font(.caption).foregroundStyle(.red)
+                }
+                if let u = record.usage {
+                    Text("\(u.input ?? 0)→\(u.output ?? 0)t").font(.caption).foregroundStyle(.secondary)
+                }
+                Text(record.finishReason ?? (record.status.map { "\($0)" } ?? ""))
+                    .font(.caption).foregroundStyle(.secondary)
+            }
+        }
+    }
+
+    private var time: String {
+        let f = DateFormatter()
+        f.dateFormat = "HH:mm:ss"
+        return f.string(from: record.tsStart)
+    }
+
+    private var prettyJSON: String {
+        let e = JSONEncoder()
+        e.dateEncodingStrategy = .iso8601
+        e.outputFormatting = [.prettyPrinted, .withoutEscapingSlashes]
+        guard let d = try? e.encode(record) else { return "(encode failed)" }
+        let s = String(decoding: d, as: UTF8.self)
+        // A 128K-context prompt is a wall of text; the row shows the head, the file has all.
+        return s.count > 20_000 ? s.prefix(20_000) + "\n… truncated view (the log file keeps the full record)" : s
+    }
+}
diff --git a/Sources/SplashGUI/Views/RootView.swift b/Sources/SplashGUI/Views/RootView.swift
index 9444469..854d054 100644
--- a/Sources/SplashGUI/Views/RootView.swift
+++ b/Sources/SplashGUI/Views/RootView.swift
@@ -44,6 +44,7 @@ struct RootView: View {
         case run = "Run"
         case provider = "Provider"
         case status = "Status"
+        case logging = "Logging"
 
         var id: String { rawValue }
 
@@ -52,6 +53,7 @@ struct RootView: View {
             case .run: return "server.rack"
             case .provider: return "powerplug"
             case .status: return "gauge"
+            case .logging: return "doc.text.magnifyingglass"
             }
         }
     }
@@ -77,6 +79,7 @@ struct RootView: View {
                     case .run: RunTab()
                     case .provider: ProviderTab()
                     case .status: StatusTab()
+                    case .logging: LoggingTab()
                     }
                 }
                 .safeAreaInset(edge: .bottom) { phaseFooter }
@@ -147,6 +150,7 @@ struct RootView: View {
                 let host = launched.lanAccess
                     ? (MachineInfo.lanIPv4Address ?? "127.0.0.1") : "127.0.0.1"
                 return "Ready · \(m) on " + host + ":" + String(launched.port)
+                    + (model.frontedEnginePort != nil ? " · logging" : "")
             }
             return "Ready · \(m)"
         case .stopping: return "Stopping…"
diff --git a/scripts/profile-test/main.swift b/scripts/profile-test/main.swift
index 86cc1ed..7418726 100644
--- a/scripts/profile-test/main.swift
+++ b/scripts/profile-test/main.swift
@@ -2,6 +2,7 @@
 // Run via ./run.sh (it handles the config.json backup/fixture dance). Exits non-zero on any failure.
 import Foundation
 import SwiftUI
+import Network
 
 let A = "unsloth/Qwen3.8-27B-GGUF:UD-IQ3_XXS"
 let B = "prism-ml/Ternary-Bonsai-2-27B-gguf:PQ2_0"
@@ -830,7 +831,311 @@ func runTests() {
             && m.modelPickerSelection.wrappedValue == "custom")
     m.selectModelID(A)
 
+    checkLoggingParses()
+    checkLoggingStore()
+    checkLoggingPlanning()
+    checkLoggingE2E()
+
     exit(failures == 0 ? 0 : 1)
 }
 
 MainActor.assumeIsolated { runTests() }
+
+// MARK: - session logging checks (pure parses, store, planning, live pipe)
+
+func lgWaitUntil(_ seconds: TimeInterval = 4, _ cond: () -> Bool) -> Bool {
+    let deadline = Date().addingTimeInterval(seconds)
+    while Date() < deadline {
+        if cond() { return true }
+        usleep(40_000)
+    }
+    return cond()
+}
+
+func lgRequest(_ url: String, post: String? = nil) -> Int? {
+    guard let u = URL(string: url) else { return nil }
+    var req = URLRequest(url: u, timeoutInterval: 5)
+    if let post {
+        req.httpMethod = "POST"
+        req.setValue("application/json", forHTTPHeaderField: "content-type")
+        req.httpBody = Data(post.utf8)
+    }
+    let sem = DispatchSemaphore(value: 0)
+    var code: Int?
+    URLSession.shared.dataTask(with: req) { _, resp, _ in
+        code = (resp as? HTTPURLResponse)?.statusCode
+        sem.signal()
+    }.resume()
+    if sem.wait(timeout: .now() + 6) == .timedOut { return nil }
+    return code
+}
+
+final class FakeEngine {
+    let listener: NWListener
+    let queue = DispatchQueue(label: "fake.engine")
+    init(port: Int) throws {
+        listener = try NWListener(using: .tcp, on: NWEndpoint.Port(rawValue: UInt16(port))!)
+        listener.newConnectionHandler = { [queue] conn in FakeEngine.serve(conn, on: queue) }
+    }
+    func start() { listener.start(queue: queue) }
+    func stop() { listener.cancel() }
+
+    static func serve(_ conn: NWConnection, on queue: DispatchQueue) {
+        conn.start(queue: queue)
+        var buf = Data()
+        func read() {
+            conn.receive(minimumIncompleteLength: 1, maximumLength: 65536) { d, _, complete, _ in
+                if let d { buf.append(d) }
+                guard let range = buf.range(of: Data("\r\n\r\n".utf8)) else {
+                    if complete { conn.cancel(); return }
+                    read(); return
+                }
+                let headS = String(decoding: buf[buf.startIndex..<range.lowerBound], as: UTF8.self)
+                var cl = 0
+                for line in headS.components(separatedBy: "\r\n")
+                where line.lowercased().hasPrefix("content-length:") {
+                    cl = Int(line.split(separator: ":", maxSplits: 1).last?
+                        .trimmingCharacters(in: .whitespaces) ?? "") ?? 0
+                }
+                if buf.count - range.upperBound < cl {
+                    if complete { conn.cancel(); return }
+                    read(); return
+                }
+                respond(conn, firstLine: headS.components(separatedBy: "\r\n").first ?? "")
+            }
+        }
+        read()
+    }
+
+    static func respond(_ conn: NWConnection, firstLine: String) {
+        let out: Data
+        if firstLine.contains("/v1/chat/completions") {
+            let c1 = "data: " + lgJSON(["choices": [["delta": ["content": "hel"]]]])
+            let c2 = "data: " + lgJSON(["choices": [["delta": ["content": "lo", "reasoning_content": "thin",
+                "tool_calls": [["index": 0, "id": "c1", "function": ["name": "read", "arguments": "{\"a\""]]]]]]])
+            let c3 = "data: " + lgJSON(["choices": [["delta": ["tool_calls": [["index": 0, "function": ["arguments": ":1}"]]]],
+                "finish_reason": "stop"]], "usage": ["prompt_tokens": 7, "completion_tokens": 3,
+                "completion_tokens_details": ["reasoning_tokens": 2], "prompt_tokens_details": ["cached_tokens": 1]]])
+            let body = c1 + "\n\n" + c2 + "\n\n" + c3 + "\n\ndata: [DONE]\n\n"
+            out = Data(("HTTP/1.1 200 OK\r\ncontent-type: text/event-stream\r\n\r\n" + body).utf8)
+        } else if firstLine.contains("/v1/models") {
+            let body = #"{"object":"list","data":[{"id":"m1"}]}"#
+            out = Data("HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: \(body.count)\r\n\r\n\(body)".utf8)
+        } else {
+            out = Data("HTTP/1.1 200 OK\r\ncontent-length: 2\r\n\r\nok".utf8)
+        }
+        conn.send(content: out, completion: .contentProcessed { _ in conn.cancel() })
+    }
+}
+
+// Build fixture JSON via JSONSerialization so hand-counted braces can never silently
+// produce a malformed chunk the reassembler rightly refuses.
+func lgJSON(_ o: Any) -> String {
+    let d = (try? JSONSerialization.data(withJSONObject: o)) ?? Data("{}".utf8)
+    return String(decoding: d, as: UTF8.self)
+}
+
+func checkLoggingParses() {
+    let reqHead = Data("POST /v1/chat/completions HTTP/1.1\r\ncontent-type: application/json\r\nContent-Length: 12\r\nuser-agent: tester\r\n\r\n".utf8)
+    let h = HTTPParse.parseHead(reqHead[reqHead.startIndex..<reqHead.endIndex - 2])
+    check("request head parses method/path/lowered headers",
+          h?.method == "POST" && h?.path == "/v1/chat/completions"
+            && h?.headers["content-length"] == "12" && h?.headers["user-agent"] == "tester")
+    let resHead = HTTPParse.parseHead(Data("HTTP/1.1 200 OK\r\ncontent-type: text/event-stream\r\n\r\n".utf8))
+    check("response head parses status + content-type",
+          resHead?.status == 200 && resHead?.headers["content-type"] == "text/event-stream")
+    check("framing: GET none / chunked / content-length", { () -> Bool in
+        guard let g = HTTPParse.parseHead(Data("GET /m HTTP/1.1\r\n\r\n".utf8)),
+              let c = HTTPParse.parseHead(Data("POST /m HTTP/1.1\r\nTransfer-Encoding: chunked\r\n\r\n".utf8)),
+              let l = HTTPParse.parseHead(Data("POST /m HTTP/1.1\r\ncontent-length: 9\r\n\r\n".utf8))
+        else { return false }
+        if case .none = HTTPParse.bodyFraming(head: g),
+           case .chunked = HTTPParse.bodyFraming(head: c),
+           case .length(9) = HTTPParse.bodyFraming(head: l) { return true }
+        return false
+    }())
+
+    let dec = HTTPParse.ChunkedDecoder()
+    var body = Data()
+    body.append(dec.feed(Data("5\r\nhel".utf8)))
+    body.append(dec.feed(Data("lo\r\n16;ext=1\r\n01234567890123456789".utf8)))   // 0x16 = 22
+    body.append(dec.feed(Data("01\r\n0\r\n\r\n".utf8)))
+    check("chunked decoder: hex sizes, extensions, split feeds",
+          body == Data("hello0123456789012345678901".utf8) && dec.isComplete, "\(body.count)")
+
+    let summary = HTTPParse.summarizeRequest(Data(#"{"model":"test-model","stream":true,"messages":[{"role":"system","content":"sys"},{"role":"user","content":"hi"}],"tools":[{"function":{"name":"read"}}]}"#.utf8))
+    check("request summary pulls model/stream/system/tools",
+          summary.model == "test-model" && summary.stream
+            && summary.systemChars == 3 && summary.toolNames == ["read"])
+
+    let sse = SSEReassembler()
+    let d1 = lgJSON(["choices": [["delta": ["content": "a"]]]])
+    let d2 = lgJSON(["choices": [["delta": ["content": "b", "tool_calls": [["index": 0, "id": "c1", "function": ["name": "read", "arguments": "{\"a\""]]]]]]])
+    let d3 = lgJSON(["choices": [["delta": ["tool_calls": [["index": 0, "function": ["arguments": ":1}"]]]], "finish_reason": "stop"]], "usage": ["prompt_tokens": 7, "completion_tokens": 3]])
+    sse.feed(Data("event: x\ndata: \(d1)\n\ndata: \(d2)\n\ndata: \(d3)\n\ndata: [DONE]\n\n".utf8))
+    let r = sse.result()
+    check("SSE reassembly joins split deltas and tool-call fragments",
+          r.text == "ab" && r.finish == "stop" && r.sawDone
+            && r.toolCalls.count == 1 && r.toolCalls.first?.argumentsJSON == "{\"a\":1}"
+            && r.usage?.input == 7 && r.usage?.output == 3, "\(r.text) \(r.toolCalls)")
+
+    let resp = SSEReassembler()
+    let r1 = lgJSON(["type": "response.output_text.delta", "delta": "hey"])
+    let r2 = lgJSON(["type": "response.function_call_arguments.delta", "item_id": "fc1", "delta": "{\"x\":1}"])
+    let r3 = lgJSON(["type": "response.completed", "response": ["status": "completed", "usage": ["input_tokens": 5, "output_tokens": 2]]])
+    resp.feed(Data("data: \(r1)\n\ndata: \(r2)\n\ndata: \(r3)\n\n".utf8))
+    let rr = resp.result()
+    check("Responses-API events fold into the same record",
+          rr.text == "hey" && rr.finish == "completed"
+            && rr.toolCalls.first?.argumentsJSON == "{\"x\":1}" && rr.usage?.input == 5)
+
+    let chat = HTTPParseTee.parseJSONBody(Data(#"{"choices":[{"message":{"content":"hi","tool_calls":[{"id":"t","function":{"name":"f","arguments":"{}"}}]},"finish_reason":"tool_calls"}],"usage":{"prompt_tokens":1,"completion_tokens":2}}"#.utf8))
+    check("non-streaming chat body parses",
+          chat.parsed && chat.text == "hi" && chat.finish == "tool_calls"
+            && chat.toolCalls?.first?.name == "f" && chat.usage?.output == 2)
+    let respObj = HTTPParseTee.parseJSONBody(Data(#"{"status":"completed","output":[{"type":"message","content":[{"type":"output_text","text":"yo"}]},{"type":"function_call","call_id":"c","name":"g","arguments":"{}"}],"usage":{"input_tokens":3,"output_tokens":4}}"#.utf8))
+    check("Responses object body parses",
+          respObj.parsed && respObj.text == "yo" && respObj.toolCalls?.first?.name == "g"
+            && respObj.usage?.input == 3)
+    check("unknown JSON shape keeps parsed=false",
+          HTTPParseTee.parseJSONBody(Data(#"{"ok":true}"#.utf8)).parsed == false)
+}
+
+func checkLoggingStore() {
+    let tmp = URL(fileURLWithPath: NSTemporaryDirectory(), isDirectory: true)
+        .appendingPathComponent("splash-log-\(UUID().uuidString)", isDirectory: true)
+    var rec = SessionRecord(tsStart: Date(), clientHint: "ua", clientLoopback: true, path: "/v1/chat/completions")
+    rec.model = "m"; rec.requestJSON = #"{"model":"m"}"#
+    rec.responseText = "hi"; rec.parsed = true
+    let line = SessionLog.encodeLine(rec)
+    check("record round-trips through JSONL",
+          line != nil && SessionLog.decodeLine(line!)?.model == "m"
+            && SessionLog.decodeLine(line!)?.responseText == "hi")
+    check("day file name is YYYY-MM-DD.jsonl",
+          SessionLog.dayFileName(Date()).count == 16
+            && SessionLog.dayFileName(Date()).hasSuffix(".jsonl"))
+
+    let log = SessionLog(dir: tmp)
+    log.write(rec)
+    var old = SessionRecord(tsStart: Date().addingTimeInterval(-100 * 86400), path: "/v1/old")
+    old.model = "old"
+    log.write(old)
+    check("both day files land and tail reads the newest",
+          lgWaitUntil(4) { (try? FileManager.default.contentsOfDirectory(atPath: tmp.path).count) == 2 }
+            && SessionLog.tail(dir: tmp, limit: 5).first?.path == "/v1/chat/completions")
+    let removed = SessionLog.purge(dir: tmp, retentionDays: 90, now: Date())
+    let stats = SessionLog.stats(dir: tmp, now: Date())
+    check("retention purges only out-of-window day files",
+          removed.count == 1 && stats.fileCount == 1 && stats.sessionsToday == 1
+            && stats.totalBytes > 0, "\(removed) \(stats.sessionsToday)")
+    try? FileManager.default.removeItem(at: tmp)
+}
+
+func checkLoggingPlanning() {
+    let p = AppModel.frontingPlan(enabled: true, adopted: false, pickedInternalPort: 8199)
+    check("fronting only when enabled, app-launched and a port was picked",
+          p.front && p.enginePort == 8199
+            && AppModel.frontingPlan(enabled: true, adopted: true, pickedInternalPort: 8199).front == false
+            && AppModel.frontingPlan(enabled: false, adopted: false, pickedInternalPort: 8199).front == false
+            && AppModel.frontingPlan(enabled: true, adopted: false, pickedInternalPort: nil).front == false)
+    let pol = SessionProxy.Policy(logLocal: true, logLAN: false)
+    check("LAN clients pipe but are not recorded by default",
+          SessionProxy.shouldRecord(policy: pol, loopbackPeer: true)
+            && !SessionProxy.shouldRecord(policy: pol, loopbackPeer: false)
+            && SessionProxy.shouldRecord(policy: .init(logLocal: true, logLAN: true), loopbackPeer: false))
+
+    let occupied = (41000 + Int.random(in: 0..<9000))
+    if SessionProxy.isPortFree(occupied) {
+        let fd = socket(AF_INET, SOCK_STREAM, 0)
+        var yes: Int32 = 1
+        setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &yes, socklen_t(MemoryLayout<Int32>.size))
+        var addr = sockaddr_in()
+        addr.sin_family = sa_family_t(AF_INET)
+        addr.sin_port = in_port_t(occupied).bigEndian
+        addr.sin_addr = in_addr(s_addr: inet_addr("127.0.0.1"))
+        let bound = withUnsafePointer(to: &addr) {
+            $0.withMemoryRebound(to: sockaddr.self, capacity: 1) {
+                bind(fd, $0, socklen_t(MemoryLayout<sockaddr_in>.size))
+            }
+        }
+        if bound == 0 {
+            let picked = SessionProxy.pickInternalPort(publicPort: occupied - 1)
+            check("internal port pick skips occupied ports",
+                  picked != occupied - 1 && picked != occupied && picked != nil
+                    && (picked ?? 0) > occupied - 1, "\(picked ?? -1)")
+        } else {
+            check("internal port pick skips occupied ports", true, "bind raced, skipped")
+        }
+        close(fd)
+    } else {
+        check("internal port pick skips occupied ports", true, "port raced, skipped")
+    }
+}
+
+func checkLoggingE2E() {
+    guard let pub = SessionProxy.pickInternalPort(publicPort: 40000 + Int.random(in: 0..<1000)),
+          let internalPort = SessionProxy.pickInternalPort(publicPort: pub) else {
+        check("E2E proxy pipe", false, "no free test ports"); return
+    }
+    let engine = try? FakeEngine(port: internalPort)
+    engine?.start()
+    let tmp = URL(fileURLWithPath: NSTemporaryDirectory(), isDirectory: true)
+        .appendingPathComponent("splash-e2e-\(UUID().uuidString)", isDirectory: true)
+    let log = SessionLog(dir: tmp)
+    guard let proxy = try? SessionProxy(publicPort: pub, internalPort: internalPort,
+                                        lanBind: false,
+                                        policy: .init(logLocal: true, logLAN: false), log: log)
+    else {
+        check("E2E proxy pipe", false, "proxy init failed"); return
+    }
+    proxy.start()
+    _ = lgWaitUntil(3) { lgRequest("http://127.0.0.1:\(pub)/status") == 200 }
+
+    check("proxy forwards non-/v1 traffic unlogged", {
+        usleep(300_000)
+        let files = (try? FileManager.default.contentsOfDirectory(atPath: tmp.path)) ?? []
+        let lines = files.flatMap { name -> [Substring] in
+            guard let d = try? Data(contentsOf: tmp.appendingPathComponent(name)),
+                  let s = String(data: d, encoding: .utf8) else { return [] }
+            return s.split(separator: "\n")
+        }
+        return lines.isEmpty
+    }())
+
+    let chatBody = #"{"model":"test-model","stream":true,"messages":[{"role":"system","content":"sys prompt"},{"role":"user","content":"hi"}]}"#
+    let code = lgRequest("http://127.0.0.1:\(pub)/v1/chat/completions", post: chatBody)
+    let gotRecord = lgWaitUntil(5) { SessionLog.tail(dir: tmp, limit: 10).count >= 1 }
+    check("chat through the proxy returns 200 and records one turn",
+          code == 200 && gotRecord, "code \(code ?? -1)")
+    let rec = SessionLog.tail(dir: tmp, limit: 1).first
+    check("record holds the full request and the reassembled SSE reply",
+          rec?.model == "test-model" && rec?.stream == true
+            && rec?.requestJSON?.contains("sys prompt") == true
+            && rec?.systemChars == 10
+            && rec?.responseText == "hello" && rec?.responseReasoning == "thin"
+            && rec?.toolCalls?.first?.argumentsJSON == "{\"a\":1}"
+            && rec?.finishReason == "stop" && rec?.status == 200
+            && rec?.usage?.input == 7 && rec?.usage?.reasoning == 2 && rec?.usage?.cached == 1,
+          "\(rec?.responseText ?? "nil") \(rec?.error ?? "ok")")
+
+    if let lan = MachineInfo.lanIPv4Address,
+       let pub2 = SessionProxy.pickInternalPort(publicPort: pub + 100),
+       let proxy2 = try? SessionProxy(publicPort: pub2, internalPort: internalPort,
+                                      lanBind: true, policy: .init(logLocal: true, logLAN: false),
+                                      log: log) {
+        proxy2.start()
+        let lanCode = lgWaitUntil(3) { lgRequest("http://\(lan):\(pub2)/v1/models") == 200 }
+        usleep(400_000)
+        let stillOne = SessionLog.tail(dir: tmp, limit: 10).count == 1
+        proxy2.stop()
+        check("a LAN-facing bind serves remote-IP clients without recording them (LAN off)",
+              lanCode && stillOne)
+    } else {
+        check("a LAN-facing bind serves remote-IP clients without recording them (LAN off)",
+              true, "no LAN IPv4 leased, skipped")
+    }
+
+    proxy.stop()
+    engine?.stop()
+    try? FileManager.default.removeItem(at: tmp)
+}
diff --git a/scripts/profile-test/run.sh b/scripts/profile-test/run.sh
index 1105b5b..65b64e7 100755
--- a/scripts/profile-test/run.sh
+++ b/scripts/profile-test/run.sh
@@ -41,6 +41,7 @@ EOF
 swiftc -swift-version 5 -o /tmp/splashgui-profiletest \
   "$CORE"/AppConfig.swift "$CORE"/AppModel.swift "$CORE"/ClientConfigs.swift \
   "$CORE"/EngineInstaller.swift "$CORE"/EngineResolver.swift \
-  "$CORE"/MachineInfo.swift "$CORE"/SplashClient.swift "$CORE"/SplashServer.swift main.swift
+  "$CORE"/MachineInfo.swift "$CORE"/SessionLog.swift "$CORE"/SessionProxy.swift \
+  "$CORE"/SplashClient.swift "$CORE"/SplashServer.swift main.swift
 
 /tmp/splashgui-profiletest