feat(mentor): per-surface engine lifecycle (#137)
CI / ci (push) Canceled after 0s

Profiles S4: passes run on their OWN one-shot engines —
`hermes acp -p museion-passN` spawns per pass run and tears down at
the verdict, so a model switch costs nothing (the next spawn reads
fresh config). The verdict streams into a TRANSIENT unrostered
transcript (#129's ruling: one Sessions surface over the chat
engine; a rostered pass session would be unresumable by the chat
engine). `beginPassSession` died with it — passes never mint
sessions; the #28 roster pins flipped to the transient posture.

The chat engine stays resident (adopted museion profile): a Chat
model change in Settings fires onChatSurfaceWrite after a
successful chat-surface write only, wired to requestRestart —
re-spawn in place when idle (resuming the pre-restart active
session), deferred to turn end while any turn streams (#129).

Missing-key posture (#132): refreshPassReadiness reads both pass
profiles' providers and their .env keys at pane entry; Run Pass
disables naming the provider with an Open Settings link, .unknown
never blocks, and the guard refuses before anything touches disk.

Finish-audit (ponytail/security/general fanout) applied: the
general reviewer's Medium — a session/new/load/fork completing
mid-pass stole the active surface and lost the Cancel to the wrong
engine — fixed with ONE claimActive gate across the post-await
activation writers, pinned deterministically via the fake's
loadReplayHold park + a mode-file flip (flip-verified: guard off
fails on the steal observables and the misrouted-cancel hang).
Also fixed: a spawn-window cancel loss in stopStreaming (keyed on
the transient entry, not the late-arriving wire id), and a
PRE-EXISTING rescan bug where a stale scan snapshot "vanished" a
just-opened piece and killed its session, cancelling the edit
debounce — the vanish-kill now re-checks disk and the watched
home. Ponytail cut ~59 lines of test duplication; the app target's
only force-unwrap is gone.

Suite 477 (was 472): EngineLifecycleTests new (own-engine
end-to-end, held-pass cancel, idle + deferred restart ordering,
readiness, steal pin), +3 Settings hook pins, one duplicate pin
deduplicated. swiftformat clean, swiftlint at HEAD baseline.

Closes #137
This commit is contained in:
AlexKucera committed 2026-10-28 17:26:40 +01:00
1 parent a4ea914690
commit 1c697440d8
19 files changed
+1034 -162

No files matched your search

+366 -56
View File
@@ -8,8 +8,17 @@
// (session/new, session/load, session/fork, /compress on the wire), one
// transcript per session, and the same-named ACTIVE surface (rows, buffers,
// sendPrompt, stop) so the pane and every existing test read unchanged.
// #137 (S4): per-surface engines — passes run on their own one-shot
// engine and stream into a transient unrostered transcript; the chat
// engine gains the model-change restart posture (requestRestart).
//
// swiftlint:disable file_length
// One model, one lifecycle story: the class body (state + session rail) and
// the same-file turn-core/engine-lifecycle extension read together; the pass
// engine's stored state can't live in another file (private, MainActor).
// Extraction ticket follows PostsModel's precedent if the file keeps growing.
import Foundation
import Observation
import os
@@ -204,6 +213,20 @@ final class MentorSessionModel {
private var client: ACPEngineClient?
private var lastPrompt: String?
/// #137 (S4): the TRANSIENT pass engine — spawned per pass run on its
/// own profile, torn down at the verdict, never rostered (#129: passes
/// are one-shot; only the chat engine's sessions are rostered).
private var passClient: ACPEngineClient?
private var passWireId: String?
private var passCancelRequested = false
/// #137: a model-change restart requested mid-turn — fires at turn end
/// (firePendingRestartIfRequested), whichever engine streamed.
private var pendingRestart = false
/// #137 (S4): per-pass readiness (refreshPassReadiness, same-file #137
/// extension) + the injectable read seam (tests). Stored in the class
/// body — extensions carry no stored state.
private(set) var passReadiness: [PassKind: PassReadiness] = [:]
var passReadinessWriter: (any SettingsWriting)?
/// The gate's winning binary path (no re-probe — map decision). Set by the
/// app when the gate passes; tests inject directly.
@@ -241,8 +264,9 @@ final class MentorSessionModel {
client?.childProcessIdentifier
}
/// App-quit teardown (#14): close the engine child cleanly. Idempotent.
/// App-quit teardown (#14): close the engine children cleanly. Idempotent.
func shutdown() {
teardownPassEngine()
shutdownClientDirectly()
client = nil
clientRef = nil
@@ -250,9 +274,11 @@ final class MentorSessionModel {
}
/// nonisolated deinit + MainActor shutdown share this: client.close() is
/// thread-safe (its own serial queue) and idempotent.
/// thread-safe (its own serial queue) and idempotent. The pass child
/// rides the same rail (#137) — deinit must close it too.
private nonisolated func shutdownClientDirectly() {
clientRef?.close()
passClientRef?.close()
}
/// ponytail: a deinit can't touch MainActor state — the client reference is
@@ -260,6 +286,9 @@ final class MentorSessionModel {
/// wherever `client` is assigned.
private nonisolated(unsafe) var clientRef: ACPEngineClient?
/// The pass engine's deinit mirror (clientRef pattern, #137).
private nonisolated(unsafe) var passClientRef: ACPEngineClient?
/// Lazy spawn on first session open. Idempotent per lifecycle. Ensures
/// ONE session exists: the default freeform 'Mentor' session on first
/// open, otherwise the newest rostered entry activated with a FRESH
@@ -277,17 +306,7 @@ final class MentorSessionModel {
/// remembers the last prompt so the writer can resend it.
func restart() async {
guard case .crashed = phase else { return }
client?.close()
client = nil
clientRef = nil
for sid in transcripts.keys {
transcripts[sid]?.streamingText = ""
transcripts[sid]?.streamingThought = ""
}
phase = .starting
await startEngine()
guard case .starting = phase else { return }
await ensureDefaultSession()
await respawn()
}
private func startEngine() async {
@@ -373,6 +392,13 @@ final class MentorSessionModel {
/// against unloaded state; a first open creates the default freeform
/// 'Mentor' session.
private func ensureDefaultSession() async {
// #137 audit fix: a restart completing while a pass runs (crash →
// Restart mid-pass) — the engine is up, mark ready and leave the
// pass surface alone; the newest entry activates on the next open.
guard !isStreaming else {
phase = .ready
return
}
if let newest = roster.first {
activate(newest)
// The resume REPLAYS, unconditionally (finish-audit): the deleted
@@ -398,15 +424,6 @@ final class MentorSessionModel {
return await createSession(name: name, pieceTitle: pieceTitle)
}
/// The pass's own session (#28): wire session/new + roster
/// 'Pass N · <title>' + activate, so the pass prompt streams into ITS
/// transcript. Nil when the engine isn't ready or refuses.
@discardableResult
func beginPassSession(kind: PassKind, pieceTitle: String) async -> SessionEntry? {
guard phase.isReady, client != nil else { return nil }
return await createSession(name: "\(kind.rawValue) · \(pieceTitle)", pieceTitle: pieceTitle)
}
/// #30 (S2.7): the brainstorm flavor — a plain freeform session whose
/// first turn is the brainstorm prompt (PRD S2.8: no new machinery).
/// Nil when the session couldn't be created; the opener rides the
@@ -424,7 +441,8 @@ final class MentorSessionModel {
+ "and angles for what I want to write — keep replies short and generative, "
+ "and don't draft prose unless I ask."
/// The shared creation rail behind newSession/beginPassSession.
/// The shared creation rail behind newSession (#137: beginPassSession
/// died with per-surface engines — passes never mint sessions).
private func createSession(name: String, pieceTitle: String?) async -> SessionEntry? {
// Finish-audit backstop: fork guards !isStreaming; the views disable
// these controls mid-turn. A programmatic caller must not switch the
@@ -454,10 +472,14 @@ final class MentorSessionModel {
return nil
}
let entry = SessionEntry(sessionId: sid, name: name, pieceTitle: pieceTitle, createdAt: Date())
// #137 audit fix: the session/new await above is a suspension —
// a pass may have started under it. Re-check ownership before
// rostering/activating (the entry guard at the top can't see
// this window); claimActive refuses with this function's voice.
guard claimActive(entry, refusedNote: "Session refused — the mentor is mid-turn.") else {
return nil
}
roster.insert(entry, at: 0)
transcripts[sid] = SessionTranscript()
activeEntry = entry
phase = .ready
saveRoster()
return entry
} catch {
@@ -532,8 +554,13 @@ final class MentorSessionModel {
}
// Activate WITHOUT resetting the transcript — activate() is for
// fresh-transcript activations; the replay already filled this one.
activeEntry = entry
phase = .ready
// #137 audit fix: the session/load await can span a whole pass —
// a resume completing mid-turn must not steal the pass surface
// (a lost Cancel reopens the #124 hole); the replayed rows stay
// in the entry's store for its next click.
guard claimActive(entry, freshTranscript: false, refusedNote: "Resume refused — the mentor is mid-turn.") else {
return false
}
return true
} catch {
replayingSessionId = nil
@@ -571,10 +598,12 @@ final class MentorSessionModel {
pieceTitle: source.pieceTitle,
createdAt: Date(),
)
// #137 audit fix: same post-await ownership re-check as
// createSession/resumeSession — the fork await is a suspension.
guard claimActive(entry, refusedNote: "Fork refused — the mentor is mid-turn.") else {
return nil
}
roster.insert(entry, at: 0)
transcripts[sid] = SessionTranscript()
activeEntry = entry
phase = .ready
saveRoster()
return entry
} catch {
@@ -604,9 +633,104 @@ final class MentorSessionModel {
phase = .ready
}
/// #137 audit fix: the ONE activation gate every post-await writer routes
/// through — a session/new/load/fork completing while ANY turn streams
/// (a pass holds the surface for its whole run) must not steal the active
/// entry: Cancel would misroute to the wrong engine (#124 class) and the
/// pane would flip mid-run. Refuses with the caller's row, activates
/// (fresh or replay-filled transcript) otherwise.
private func claimActive(_ entry: SessionEntry, freshTranscript: Bool = true, refusedNote: String) -> Bool {
guard !isStreaming else {
appendRow(.text(refusedNote), to: activeEntry?.sessionId)
return false
}
if freshTranscript {
transcripts[entry.sessionId] = SessionTranscript()
}
activeEntry = entry
phase = .ready
return true
}
private func saveRoster() {
SessionRoster.save(roster, directory: rosterDirectory)
}
}
// MARK: Turn core + per-surface engine lifecycle (#137, S4)
/// Same-file extension — type_body_length posture (MentorPaneView precedent);
/// the turn pipeline and the #137 engine lifecycle read as one unit.
extension MentorSessionModel {
/// #137: the transient pass transcript's key. A pass never mints a
/// roster entry (#129: passes run on their own one-shot engines) — the
/// pass entry lives under this key only for the run; the view layer
/// hides the session chip on it (next slice).
nonisolated static let passTranscriptKey = "pass"
/// The pass engine's pid — internal test observable (teardown pins).
var passEngineChildPid: pid_t? {
passClient?.childProcessIdentifier
}
/// True while a pass engine is resident (spawn → verdict).
var isPassEngineRunning: Bool {
passClient != nil
}
/// #137 (S4): the Run Pass posture — is the pass profile's provider
/// keyed? .unknown NEVER blocks (our own read failure — the spawn's
/// honest failure row owns that path); .missingKey names the provider
/// so the pane can say what's missing and link to Settings.
enum PassReadiness: Equatable {
case ready
case missingKey(providerLabel: String)
case unknown
}
// Per-pass readiness (stored in the class body), refreshed at pane
// entry (re-entry re-fires the pane's .task — the key-added-in-
// Settings re-enable path). `passReadinessWriter` is the injectable
// read seam; nil at refresh time → an ad-hoc HermesSettingsWriter
// over the gate's binary (profileRoot default).
func readiness(for kind: PassKind) -> PassReadiness {
passReadiness[kind] ?? .unknown
}
/// Read each pass profile's provider (readSurface, one task group),
/// then each DISTINCT provider's key (readProviderKey). A surface we
/// can't read maps .unknown; a non-empty key maps .ready; no key maps
/// .missingKey with the provider's label. No binaryPath and no
/// injected writer → readiness stays empty (.unknown everywhere).
func refreshPassReadiness() async {
guard let writer = passReadinessWriter ?? binaryPath.map({ HermesSettingsWriter(hermesBinary: $0) }) else { return }
var providers: [ProfileSurface: ModelProvider] = [:]
await withTaskGroup(of: (ProfileSurface, (config: SurfaceModelConfig, baseURL: String?)?).self) { group in
for surface in [ProfileSurface.pass1, .pass2] {
group.addTask { await (surface, try? writer.readSurface(surface)) }
}
for await (surface, read) in group {
providers[surface] = read?.config.provider
}
}
var keys: [ModelProvider: String] = [:]
for provider in Set(providers.values.compactMap(\.self)) {
keys[provider] = await (try? writer.readProviderKey(provider: provider)) ?? ""
}
for surface in [ProfileSurface.pass1, .pass2] {
let kind: PassKind = surface == .pass1 ? .pass1 : .pass2
guard let provider = providers[surface] else {
passReadiness[kind] = .unknown
continue
}
if let key = keys[provider], !key.isEmpty {
passReadiness[kind] = .ready
} else {
passReadiness[kind] = .missingKey(providerLabel: provider.label)
}
}
}
/// Send a prompt and stream the reply into the ACTIVE session's
/// transcript. Appends the user row first — a non-nil `label` renders
@@ -632,30 +756,60 @@ final class MentorSessionModel {
guard !prompt.isEmpty, phase.isReady, !isStreaming, let sid = activeEntry?.sessionId else {
return .failed
}
// #137: the transient pass transcript is surface-only — the pass
// engine is gone after teardown, so the composer must refuse with
// the words visible, never silently drop the text.
guard sid != Self.passTranscriptKey else {
appendRow(.text("Pick or start a session to chat — the pass transcript is read-only."), to: sid)
return .failed
}
guard let client else { return .failed }
isStreaming = true
defer {
isStreaming = false
// #137: a model-change restart requested mid-turn fires now.
firePendingRestartIfRequested()
}
return await turnCore(
client: client,
wireSid: sid,
key: sid,
prompt: prompt,
label: label ?? "You: \(prompt)",
)
}
/// The ONE turn pipeline behind sendPrompt and the pass run (#137): the
/// label row, session/prompt, stopReason mapping, and the streaming-
/// buffer flush — one implementation, two engines.
private func turnCore(
client: ACPEngineClient,
wireSid: String,
key: String,
prompt: String,
label: String,
) async -> TurnOutcome {
lastPrompt = prompt
appendRow(.text(label ?? "You: \(prompt)"), to: sid)
appendRow(.text(label), to: key)
isStreaming = true
defer {
// Flush the thinking first (it preceded the message), collapsed.
if let pending = transcripts[sid], !pending.streamingThought.isEmpty {
appendRow(.thought(pending.streamingThought), to: sid)
transcripts[sid]?.streamingThought = ""
if let pending = transcripts[key], !pending.streamingThought.isEmpty {
appendRow(.thought(pending.streamingThought), to: key)
transcripts[key]?.streamingThought = ""
}
// Flush any streamed-but-unfinished agent text into a row.
if let pending = transcripts[sid], !pending.streamingText.isEmpty {
appendRow(.text("Mentor: \(pending.streamingText)"), to: sid)
transcripts[sid]?.streamingText = ""
if let pending = transcripts[key], !pending.streamingText.isEmpty {
appendRow(.text("Mentor: \(pending.streamingText)"), to: key)
transcripts[key]?.streamingText = ""
}
isStreaming = false
}
// Parity with the phase guard above: never lean on two invariants
// (.ready ⇒ client) where one guard suffices.
guard let client else { return .failed }
do {
let result = try await client.request(
"session/prompt",
params: .object([
"sessionId": .string(sid),
"sessionId": .string(wireSid),
"prompt": .array([.object(["type": .string("text"), "text": .string(prompt)])]),
]),
timeout: Self.promptTimeout,
@@ -666,7 +820,7 @@ final class MentorSessionModel {
// must not advance on a maybe (review: empty-stopReason bug).
guard !stopReason.isEmpty else { return .failed }
if stopReason == "refusal" {
appendRow(.text("Mentor: (refused the prompt)"), to: sid)
appendRow(.text("Mentor: (refused the prompt)"), to: key)
}
if stopReason == "cancelled" {
return .cancelled
@@ -678,20 +832,171 @@ final class MentorSessionModel {
if case .crashed = phase {
// Crash card already owns the failure surface.
} else {
appendRow(.text("Mentor: connection lost — \(error.localizedDescription)"), to: sid)
appendRow(.text("Mentor: connection lost — \(error.localizedDescription)"), to: key)
}
return .failed
}
}
/// #137 (S4, ADR-0014): run one pass on its OWN one-shot engine —
/// spawn `hermes acp -p museion-passN`, stream the verdict into the
/// transient pass transcript, tear the engine down at the verdict.
/// The pass entry is never rostered (#129); the chat engine keeps
/// running untouched.
@discardableResult
func runPass(kind: PassKind, stub: String, pieceTitle: String) async -> TurnOutcome {
guard phase.isReady, !isStreaming, passClient == nil, let binaryPath else { return .failed }
let label = "\(kind.rawValue) · \(pieceTitle)"
// The transient surface: a fresh transcript under the pass key and a
// pass entry that lives only for this run — never rostered, never
// saved (#129: passes are one-shot, the chat engine owns sessions).
transcripts[Self.passTranscriptKey] = SessionTranscript()
activeEntry = SessionEntry(
sessionId: Self.passTranscriptKey, name: label, pieceTitle: pieceTitle, createdAt: Date(),
)
isStreaming = true
defer {
isStreaming = false
teardownPassEngine()
firePendingRestartIfRequested()
}
// #137 audit: no force-unwrap — the map is total over today's two
// kinds, but a future PassKind case must refuse, not trap.
guard let surface = ProfileSurface(passKind: kind) else { return .failed }
let pass = ACPEngineClient(binaryPath: binaryPath, profile: surface.profileName)
passClient = pass
passClientRef = pass
// KNOWN EDGE (#137, accepted v1): a CHAT-engine crash mid-pass flips
// the pane to the crash card while the pass keeps streaming — the
// pass turn still completes and advances state. Symmetrically, a
// pass-engine crash must NOT flip the pane: onCrash stays nil here —
// the failed pending request lands the honest row below instead.
do {
// Same routing as the chat client (DispatchQueue.main.async keeps
// wire order — see startEngine).
try pass.start { [weak self] method, params in
DispatchQueue.main.async {
self?.handleNotification(method: method, params: params)
}
}
// Slim initialize — engineVersion/versionNote display the CHAT
// engine and must not be overwritten by the pass engine's answer.
_ = try await pass.request("initialize", params: .object([
"protocolVersion": .number(1),
"clientCapabilities": .object([:]),
"clientInfo": .object([
"name": .string("Museion"),
"title": .string("Museion"),
"version": .string("0.1"),
]),
]))
let result = try await pass.request("session/new", params: .object([
"cwd": .string(cwdProvider()),
"mcpServers": .array([]),
]))
guard let sid = result?.objectValue?["sessionId"]?.stringValue, !sid.isEmpty else {
appendRow(.text("Pass failed — the engine refused a session."), to: Self.passTranscriptKey)
return .failed
}
passWireId = sid
} catch {
appendRow(.text("Pass failed — \(error.localizedDescription)"), to: Self.passTranscriptKey)
return .failed
}
// Cancel clicked while the engine was spawning: stop before the
// prompt — the run ends cancelled, nothing streams.
if passCancelRequested {
appendRow(.text("\(kind.rawValue) cancelled."), to: Self.passTranscriptKey)
return .cancelled
}
return await turnCore(client: pass, wireSid: passWireId ?? "", key: Self.passTranscriptKey, prompt: stub, label: label)
}
/// Kill the pass engine and clear its rail — at the verdict (the defer
/// above) and at shutdown. Idempotent.
private func teardownPassEngine() {
passClient?.close()
passClient = nil
passClientRef = nil
passWireId = nil
passCancelRequested = false
}
/// Stop button while a turn streams (map decision: cancel wired to
/// session/cancel, a notification — no response expected). The engine
/// ends the turn (PromptResponse) as its acknowledgement.
/// ends the turn (PromptResponse) as its acknowledgement. #137: while a
/// pass runs, the PASS engine owns the live turn — Cancel must reach it.
func stopStreaming() {
guard isStreaming, let sid = activeEntry?.sessionId else { return }
guard isStreaming else { return }
// #137 fix: key the branch on the TRANSIENT ENTRY, not passWireId —
// the wire id is nil until session/new lands, so a Cancel clicked in
// the spawn window fell through to the chat engine and was LOST (the
// pass then held until promptTimeout). The pass entry owns the active
// surface for the run's WHOLE span, and sendPrompt refuses chat turns
// under it — no chat stream can race this branch.
if activeEntry?.sessionId == Self.passTranscriptKey {
passCancelRequested = true
if let passSid = passWireId {
passClient?.notify("session/cancel", params: .object(["sessionId": .string(passSid)]))
}
return
}
guard let sid = activeEntry?.sessionId else { return }
client?.notify("session/cancel", params: .object(["sessionId": .string(sid)]))
}
/// #137 (S4): the model-change restart posture — Settings fires this
/// when the Chat model changes (the next slice wires the UI). Re-spawns
/// the resident chat engine in place when idle; while a turn streams
/// (either engine), the restart defers to turn end so a reply is never
/// cut mid-stream. .idle/.starting are ignored — a future spawn reads
/// fresh config anyway.
func requestRestart() {
switch phase {
case .ready, .crashed:
break
case .idle, .starting:
return
}
if isStreaming {
pendingRestart = true
} else {
Task { await respawn() }
}
}
/// The restart body behind crash-restart and requestRestart (#137):
/// teardown, fresh spawn, then resume the PRE-restart active session
/// when it is rostered — the writer stays where they were, not jumped
/// to the newest entry (strictly better UX; the single-session crash
/// tests keep passing because active == newest there).
private func respawn() async {
client?.close()
client = nil
clientRef = nil
for sid in transcripts.keys {
transcripts[sid]?.streamingText = ""
transcripts[sid]?.streamingThought = ""
}
phase = .starting
await startEngine()
guard case .starting = phase else { return } // startEngine crashed instead
if let active = activeEntry, roster.contains(active) {
phase = .ready
_ = await resumeSession(active)
} else {
await ensureDefaultSession()
}
}
/// A deferred restart fires at turn end — from BOTH turn-end defers
/// (chat sendPrompt and the pass run), whichever engine streamed (#137).
private func firePendingRestartIfRequested() {
guard pendingRestart else { return }
pendingRestart = false
Task { await respawn() }
}
/// Base version of a version string — the part before `+` build metadata
/// (PEP 440 local version segment). `0.21.5+2177.g735e426` → `0.21.5`.
nonisolated static func baseVersion(of version: String) -> String {
@@ -724,14 +1029,19 @@ extension MentorSessionModel {
/// Route by the session id FROM THE PARAMS (#28) — a replay for a
/// background session lands in ITS transcript, never the active one's.
/// #137: the pass engine's wire sid maps onto the transient pass key —
/// everything downstream addresses transcripts by that key (passWireId
/// is Optional; nil never equals a real sid).
private func handleNotification(method: String, params: JSONValue?) {
guard method == "session/update",
let params,
let sid = params.objectValue?["sessionId"]?.stringValue,
transcripts[sid] != nil,
let update = params.objectValue?["update"]?.objectValue else { return }
let update = params.objectValue?["update"]?.objectValue
else { return }
let key = sid == passWireId ? Self.passTranscriptKey : sid
guard transcripts[key] != nil else { return }
let kind = update["sessionUpdate"]?.stringValue ?? "unknown"
let replaying = sid == replayingSessionId
let replaying = key == replayingSessionId
switch kind {
case "agent_message_chunk":
let text = update["content"]?.objectValue?["text"]?.stringValue ?? ""
@@ -739,16 +1049,16 @@ extension MentorSessionModel {
// ponytail: one row per replayed chunk — a chunked engine message
// renders as several rows; wire order stays faithful. Coalesce
// only if a real adapter chunks replayed turns.
appendRow(.text("Mentor: \(text)"), to: sid)
appendRow(.text("Mentor: \(text)"), to: key)
} else {
transcripts[sid]?.streamingText += text
transcripts[key]?.streamingText += text
}
case "agent_thought_chunk":
let text = update["content"]?.objectValue?["text"]?.stringValue ?? ""
if replaying {
appendRow(.thought(text), to: sid)
appendRow(.thought(text), to: key)
} else {
transcripts[sid]?.streamingThought += text
transcripts[key]?.streamingThought += text
}
case "user_message_chunk":
// Live: the engine echoes the user message; the label row already
@@ -756,15 +1066,15 @@ extension MentorSessionModel {
// owns the turn, so it renders (#28: user turns included).
if replaying {
let text = update["content"]?.objectValue?["text"]?.stringValue ?? ""
appendRow(.text("You: \(text)"), to: sid)
appendRow(.text("You: \(text)"), to: key)
}
case "tool_call":
appendToolCall(update, to: sid)
appendToolCall(update, to: key)
default:
// Every other update type: collapsible raw-JSON row (map decision).
let object = params.objectValue?.mapValues { $0.any } ?? [:]
let json = (try? JSONSerialization.data(withJSONObject: object, options: [.sortedKeys])) ?? Data()
appendRow(.raw(kind: kind, json: String(bytes: json, encoding: .utf8) ?? ""), to: sid)
appendRow(.raw(kind: kind, json: String(bytes: json, encoding: .utf8) ?? ""), to: key)
}
}