feat(sessions): session lifecycle UI (S2.3) (#28)
CI / ci (push) Canceled after 0s
CI / ci (push) Canceled after 0s
Each Session is a conversation Museion UIs, never owns. The mentor bridge hosts multiple engine-owned sessions: per-session transcripts keyed by wire sessionId behind same-named proxies (every existing caller compiles unchanged), a names-only roster at Application Support/sessions.json (0600; id/name/pieceTitle/date — the words stay engine-owned per ADR-0007), and the standard affordances over the wire: session/new, session/load, session/fork, compact as the /compress slash prompt, session/cancel as the Stop rail. The Sessions pane replaces its placeholder: roster list (piece- associated by name when Posts has an open piece), row-click resume with the engine's full-history replay (user turns included), Fork · Compact, live streaming with Stop; every pass auto-creates its rostered session and streams into it; the transcript renderer is shared with the mentor pane. Notification hops ride the main queue (FIFO with the continuation resume) so the adapter's replay-before- response contract is guaranteed, not probabilistic. Resume refusals are honest and entry-attributed (an engine-unknown session never fabricates history); concurrent replays refuse instead of interleaving; restart replays from the engine rather than trusting a diverging local copy. Finish-audit (three reviewers) surfaced the concurrent-resume race, the dead restart branch, the runPass guard window, the 15 s session/load default, and the missing createSession backstop — all fixed and pinned (12 lifecycle pins; 359 tests green). Closes #28
This commit is contained in:
1 parent
78c8844184
commit
9895614b7e
15 files changed
+1523
-245
No files matched your search
@@ -3,7 +3,11 @@
|
||||
// Museion
|
||||
//
|
||||
// M0 ACP bridge (#14): the pane's @Observable model — lazy bridge lifecycle,
|
||||
// one session, prompt streaming, fix-card render, crash → restart prompt.
|
||||
// prompt streaming, fix-card render, crash → restart prompt.
|
||||
// #28 (S2.3): multi-session — a persisted roster of engine-owned sessions
|
||||
// (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.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
@@ -50,16 +54,66 @@ enum TurnOutcome: Equatable {
|
||||
case failed
|
||||
}
|
||||
|
||||
/// One rostered mentor session (#28, S2.3). Piece association is by
|
||||
/// convention — the entry's `pieceTitle` field only, no filesystem linkage.
|
||||
/// History is engine-owned; only these four fields persist.
|
||||
nonisolated struct SessionEntry: Identifiable, Equatable, Codable {
|
||||
let sessionId: String
|
||||
let name: String
|
||||
var pieceTitle: String?
|
||||
let createdAt: Date
|
||||
|
||||
var id: String {
|
||||
sessionId
|
||||
}
|
||||
}
|
||||
|
||||
/// The persisted roster (#28) — a JSON array of entries at a
|
||||
/// caller-injectable directory, default `~/Library/Application
|
||||
/// Support/Museion/sessions.json`. EngineGate's state.json posture: wholesale
|
||||
/// replace, atomic, a write failure must never crash the app.
|
||||
nonisolated enum SessionRoster {
|
||||
static func load(directory: String? = nil) -> [SessionEntry] {
|
||||
guard let data = try? Data(contentsOf: rosterURL(directory)) else { return [] }
|
||||
return (try? JSONDecoder().decode([SessionEntry].self, from: data)) ?? []
|
||||
}
|
||||
|
||||
static func save(_ entries: [SessionEntry], directory: String? = nil) {
|
||||
let dir = directory ?? defaultDirectory
|
||||
do {
|
||||
try FileManager.default.createDirectory(atPath: dir, withIntermediateDirectories: true)
|
||||
try JSONEncoder().encode(entries).write(
|
||||
to: URL(fileURLWithPath: dir).appendingPathComponent("sessions.json"),
|
||||
options: .atomic,
|
||||
)
|
||||
// Finish-audit: names+ids only, but piece titles are the writer's
|
||||
// business — the default umask would hand them to every local user.
|
||||
try? FileManager.default.setAttributes([.posixPermissions: 0o600], ofItemAtPath: URL(fileURLWithPath: dir).appendingPathComponent("sessions.json").path)
|
||||
} catch {
|
||||
// ponytail: the roster is a convenience index; a write failure must not crash the gate.
|
||||
}
|
||||
}
|
||||
|
||||
private static var defaultDirectory: String {
|
||||
("~/Library/Application Support/Museion" as NSString).expandingTildeInPath
|
||||
}
|
||||
|
||||
private static func rosterURL(_ directory: String?) -> URL {
|
||||
URL(fileURLWithPath: directory ?? defaultDirectory).appendingPathComponent("sessions.json")
|
||||
}
|
||||
}
|
||||
|
||||
/// Pane + bridge state machine. Lazy lifecycle: the engine spawns when the
|
||||
/// pane opens its first session and stays alive for the app's life (map
|
||||
/// decision: child lifecycle).
|
||||
/// decision: child lifecycle). The engine bridge is session-agnostic —
|
||||
/// session ids live in the roster (#28), the phase only says the engine is up.
|
||||
@MainActor
|
||||
@Observable
|
||||
final class MentorSessionModel {
|
||||
enum Phase: Equatable {
|
||||
case idle
|
||||
case starting
|
||||
case ready(sessionId: String)
|
||||
case ready
|
||||
case crashed(lastPrompt: String?)
|
||||
|
||||
var isReady: Bool {
|
||||
@@ -70,16 +124,49 @@ final class MentorSessionModel {
|
||||
}
|
||||
}
|
||||
|
||||
/// Per-session transcript state (#28) — the model used to hold ONE
|
||||
/// session's rows and streaming buffers; now keyed by sessionId. The
|
||||
/// active session's entries surface through the same-named proxies below.
|
||||
private struct SessionTranscript {
|
||||
var rows: [SessionRow] = []
|
||||
var streamingText = ""
|
||||
var streamingThought = ""
|
||||
}
|
||||
|
||||
private(set) var phase: Phase = .idle
|
||||
/// True while a turn streams — the Stop button's target.
|
||||
/// True while a turn streams — the Stop button's target. One engine
|
||||
/// child, so at most one turn streams at a time across all sessions.
|
||||
private(set) var isStreaming = false
|
||||
private(set) var rows: [SessionRow] = []
|
||||
/// Streaming buffer for the in-flight agent message; flushed to a row on completion.
|
||||
private(set) var streamingText = ""
|
||||
/// The roster, newest-first (#28). Persisted via SessionRoster.
|
||||
private(set) var roster: [SessionEntry] = []
|
||||
/// The session the pane reads and new prompts target (#28).
|
||||
private(set) var activeEntry: SessionEntry?
|
||||
|
||||
/// The ACTIVE session's transcript — the same-named pane surface over
|
||||
/// the per-session store (#28). MentorPaneView and every existing test
|
||||
/// keep reading these untouched.
|
||||
var rows: [SessionRow] {
|
||||
activeTranscript?.rows ?? []
|
||||
}
|
||||
|
||||
/// Streaming buffer for the in-flight agent message of the ACTIVE
|
||||
/// session; flushed to a row on completion.
|
||||
var streamingText: String {
|
||||
activeTranscript?.streamingText ?? ""
|
||||
}
|
||||
|
||||
/// #24 fix: streaming buffer for the engine's THINKING — kept out of the
|
||||
/// critique stream. A pass runs to hundreds of thought lines; conflating
|
||||
/// them with `agent_message_chunk` made the transcript one giant blob.
|
||||
private(set) var streamingThought = ""
|
||||
var streamingThought: String {
|
||||
activeTranscript?.streamingThought ?? ""
|
||||
}
|
||||
|
||||
/// A new session may start: engine up, no turn in flight (#28).
|
||||
var canStartSession: Bool {
|
||||
phase.isReady && !isStreaming
|
||||
}
|
||||
|
||||
/// Advisory engine-version verdict (map decision: advisory, never blocks).
|
||||
private(set) var versionNote: String?
|
||||
/// The running engine's version, from the initialize handshake (always visible).
|
||||
@@ -87,8 +174,16 @@ final class MentorSessionModel {
|
||||
/// Last stderr lines from the engine — the restart prompt's technical details.
|
||||
private(set) var stderrTail: [String] = []
|
||||
|
||||
private var transcripts: [String: SessionTranscript] = [:]
|
||||
/// While a session/load is in flight, its replayed updates render as rows
|
||||
/// instead of feeding the streaming buffers (#28).
|
||||
private var replayingSessionId: String?
|
||||
/// The resolved roster directory (nil = SessionRoster's default). Under
|
||||
/// hosted tests a unique temp dir keeps suites off the real roster
|
||||
/// (ponytail: redirect here instead of making every rig inject a directory).
|
||||
private let rosterDirectory: String?
|
||||
|
||||
private var client: ACPEngineClient?
|
||||
private var sessionId: String?
|
||||
private var lastPrompt: String?
|
||||
|
||||
/// The gate's winning binary path (no re-probe — map decision). Set by the
|
||||
@@ -100,8 +195,20 @@ final class MentorSessionModel {
|
||||
/// The gate's recorded engine version (state.json) — injectable for tests.
|
||||
var recordedVersionProvider: () -> String? = { EngineProbe.readStateRecord()?.engineVersion }
|
||||
|
||||
init(binaryPath: String? = nil) {
|
||||
init(binaryPath: String? = nil, rosterDirectory: String? = nil) {
|
||||
self.binaryPath = binaryPath
|
||||
if let rosterDirectory {
|
||||
self.rosterDirectory = rosterDirectory
|
||||
} else if ProcessInfo.processInfo.environment["XCTestConfigurationFilePath"] != nil {
|
||||
self.rosterDirectory = NSTemporaryDirectory() + "museion-roster-\(UUID().uuidString)"
|
||||
} else {
|
||||
self.rosterDirectory = nil
|
||||
}
|
||||
roster = SessionRoster.load(directory: self.rosterDirectory)
|
||||
}
|
||||
|
||||
private var activeTranscript: SessionTranscript? {
|
||||
activeEntry.flatMap { transcripts[$0.sessionId] }
|
||||
}
|
||||
|
||||
deinit {
|
||||
@@ -109,6 +216,12 @@ final class MentorSessionModel {
|
||||
shutdownClientDirectly()
|
||||
}
|
||||
|
||||
/// The engine child's pid — internal observation surface for the
|
||||
/// finish-audit restart pin (kills the child to drive a real crash).
|
||||
var childProcessIdentifier: pid_t? {
|
||||
client?.childProcessIdentifier
|
||||
}
|
||||
|
||||
/// App-quit teardown (#14): close the engine child cleanly. Idempotent.
|
||||
func shutdown() {
|
||||
shutdownClientDirectly()
|
||||
@@ -128,25 +241,34 @@ final class MentorSessionModel {
|
||||
/// wherever `client` is assigned.
|
||||
private nonisolated(unsafe) var clientRef: ACPEngineClient?
|
||||
|
||||
/// Lazy spawn on first session open. Idempotent per lifecycle.
|
||||
/// 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
|
||||
/// transcript — history is engine-owned and comes back on resume (#28).
|
||||
func openSession() async {
|
||||
guard phase == .idle else { return }
|
||||
phase = .starting
|
||||
await startEngine()
|
||||
guard case .starting = phase else { return } // startEngine crashed instead
|
||||
await ensureDefaultSession()
|
||||
}
|
||||
|
||||
/// Restart after a crash — keeps the transcript (never data loss) and
|
||||
/// Restart after a crash — re-spawns the engine and REPLAYS every
|
||||
/// transcript from it (ADR-0007: the engine owns the words), and
|
||||
/// 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
|
||||
sessionId = nil
|
||||
streamingText = ""
|
||||
streamingThought = ""
|
||||
for sid in transcripts.keys {
|
||||
transcripts[sid]?.streamingText = ""
|
||||
transcripts[sid]?.streamingThought = ""
|
||||
}
|
||||
phase = .starting
|
||||
await startEngine()
|
||||
guard case .starting = phase else { return }
|
||||
await ensureDefaultSession()
|
||||
}
|
||||
|
||||
private func startEngine() async {
|
||||
@@ -158,19 +280,24 @@ final class MentorSessionModel {
|
||||
let client = ACPEngineClient(binaryPath: binaryPath)
|
||||
self.client = client
|
||||
clientRef = client
|
||||
// All three hops ride DispatchQueue.main.async, NOT Task { @MainActor }:
|
||||
// a Task must first win cooperative-pool time, which hundreds of
|
||||
// parallel jobs can starve for seconds (#28 test finding); the main
|
||||
// queue is FIFO with the continuation resume, so wire order — replay
|
||||
// updates before the load response — is guaranteed, not probable.
|
||||
client.onCrash = { [weak self] in
|
||||
Task { @MainActor in
|
||||
DispatchQueue.main.async {
|
||||
self?.handleCrash()
|
||||
}
|
||||
}
|
||||
client.onStderrLine = { [weak self] line in
|
||||
Task { @MainActor in
|
||||
DispatchQueue.main.async {
|
||||
self?.appendStderr(line)
|
||||
}
|
||||
}
|
||||
do {
|
||||
try client.start { [weak self] method, params in
|
||||
Task { @MainActor in
|
||||
DispatchQueue.main.async {
|
||||
self?.handleNotification(method: method, params: params)
|
||||
}
|
||||
}
|
||||
@@ -188,7 +315,8 @@ final class MentorSessionModel {
|
||||
}
|
||||
}
|
||||
|
||||
/// initialize + session/new (map decisions: advisory version verify; cwd ~).
|
||||
/// initialize (map decisions: advisory version verify). Sessions are
|
||||
/// created separately (#28) — the bridge is session-agnostic.
|
||||
private func handshake(_ client: ACPEngineClient) async throws {
|
||||
let params: JSONValue = .object([
|
||||
"protocolVersion": .number(1),
|
||||
@@ -218,35 +346,233 @@ final class MentorSessionModel {
|
||||
}
|
||||
}
|
||||
versionNote = note
|
||||
|
||||
// New session — cwd ~ (map decision). Adapter ≥0.21.5 requires mcpServers
|
||||
// (ACP SDK NewSessionRequest); Museion ships none, so the honest empty list.
|
||||
let newResult = try await client.request(
|
||||
"session/new",
|
||||
params: .object([
|
||||
"cwd": .string(cwdProvider()),
|
||||
"mcpServers": .array([]),
|
||||
]),
|
||||
)
|
||||
guard let sid = newResult?.objectValue?["sessionId"]?.stringValue else {
|
||||
throw ACPEngineClient.TransportError(message: "session/new returned no sessionId")
|
||||
}
|
||||
sessionId = sid
|
||||
phase = .ready(sessionId: sid)
|
||||
}
|
||||
|
||||
/// Send a prompt and stream the reply. Appends the user row first — a
|
||||
/// non-nil `label` renders verbatim INSTEAD of the raw prompt (pass prompts
|
||||
/// are long wire stubs that must not land in the transcript); the
|
||||
/// stop_reason response ends the turn (refusal maps to a plain note —
|
||||
/// wire-verified edge semantics). Returns how the turn ended (#24 seam):
|
||||
/// a pass advances only on a completed turn, never on cancel/crash.
|
||||
/// session/prompt's response arrives only when the TURN ends — a pass
|
||||
/// legitimately runs minutes of tool work between prompt and stop reason.
|
||||
/// The client's 15 s request default would abandon the wait mid-stream
|
||||
/// (observed live, #23 dogfood: "connection lost" while the engine kept
|
||||
/// working, Stop vanished with isStreaming). Long-but-finite so a truly
|
||||
/// stuck engine still surfaces; Stop is the live-turn exit.
|
||||
/// After an engine start: exactly one active session (#28). The newest
|
||||
/// rostered entry activates and RESUMES — session/load replays its
|
||||
/// history (user turns included), so prompt/fork/compact never run
|
||||
/// against unloaded state; a first open creates the default freeform
|
||||
/// 'Mentor' session.
|
||||
private func ensureDefaultSession() async {
|
||||
if let newest = roster.first {
|
||||
activate(newest)
|
||||
// The resume REPLAYS, unconditionally (finish-audit): the deleted
|
||||
// rows.isEmpty skip was dead — activate() resets the store one
|
||||
// line above it — and restart()'s kept rows are intentionally
|
||||
// replaced by the engine's replay (ADR-0007: the engine owns the
|
||||
// words; a diverging local copy would lie). An engine-unknown id
|
||||
// lands the honest refusal row; the entry stays rostered.
|
||||
_ = await resumeSession(newest)
|
||||
return
|
||||
}
|
||||
if await createSession(name: "Mentor", pieceTitle: nil) == nil {
|
||||
phase = .crashed(lastPrompt: nil)
|
||||
stderrTail = ["no session — the engine refused session/new"]
|
||||
}
|
||||
}
|
||||
|
||||
/// A fresh freeform session (#28): wire session/new, roster it
|
||||
/// newest-first, activate. Nil when the engine isn't ready or refuses.
|
||||
@discardableResult
|
||||
func newSession(name: String, pieceTitle: String?) async -> SessionEntry? {
|
||||
guard phase.isReady, client != nil else { return nil }
|
||||
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)
|
||||
}
|
||||
|
||||
/// The shared creation rail behind newSession/beginPassSession.
|
||||
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
|
||||
// active session out from under a live turn — Stop would then cancel
|
||||
// the wrong session.
|
||||
guard !isStreaming else {
|
||||
appendRow(.text("Session refused — the mentor is mid-turn."), to: activeEntry?.sessionId)
|
||||
return nil
|
||||
}
|
||||
guard let client else { return nil }
|
||||
do {
|
||||
// Adapter ≥0.21.5 requires mcpServers on every session/new (#44
|
||||
// invariant); Museion ships none, so the honest empty list.
|
||||
let result = try await client.request(
|
||||
"session/new",
|
||||
params: .object([
|
||||
"cwd": .string(cwdProvider()),
|
||||
"mcpServers": .array([]),
|
||||
]),
|
||||
)
|
||||
guard let sid = result?.objectValue?["sessionId"]?.stringValue, !sid.isEmpty else {
|
||||
// #28 review fix: a refused session speaks like its siblings —
|
||||
// resume/fork append honest rows; New Session must never be a
|
||||
// silent nil. (Nothing active yet → the row drops; the crash
|
||||
// posture owns that path in ensureDefaultSession.)
|
||||
appendRow(.text("Session refused — the engine returned no id."), to: activeEntry?.sessionId)
|
||||
return nil
|
||||
}
|
||||
let entry = SessionEntry(sessionId: sid, name: name, pieceTitle: pieceTitle, createdAt: Date())
|
||||
roster.insert(entry, at: 0)
|
||||
transcripts[sid] = SessionTranscript()
|
||||
activeEntry = entry
|
||||
phase = .ready
|
||||
saveRoster()
|
||||
return entry
|
||||
} catch {
|
||||
appendRow(.text("Session refused — \(error.localizedDescription)"), to: activeEntry?.sessionId)
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
/// Resume a rostered session (#28): session/load, the engine replays its
|
||||
/// history into the transcript (user turns included), Museion owns none
|
||||
/// of it. A session the engine does NOT know returns false honestly —
|
||||
/// the entry stays and an explanatory row lands; never a fabricated
|
||||
/// empty session.
|
||||
func resumeSession(_ entry: SessionEntry) async -> Bool {
|
||||
guard phase.isReady, let client else { return false }
|
||||
guard !isStreaming else {
|
||||
// "Not now" refusals target the ACTIVE session — they are about
|
||||
// the writer's action right now, not the entry's state.
|
||||
appendRow(.text("Resume refused — the mentor is mid-turn."), to: activeEntry?.sessionId)
|
||||
return false
|
||||
}
|
||||
guard replayingSessionId == nil else {
|
||||
// Finish-audit (converged, 3 reviewers): one replay slot — a
|
||||
// second session/load in flight would divert the first's replayed
|
||||
// chunks into live streaming buffers. Refuse; the winner's
|
||||
// completion frees the slot and the next click just works.
|
||||
appendRow(.text("Resume refused — another session is loading."), to: activeEntry?.sessionId)
|
||||
return false
|
||||
}
|
||||
do {
|
||||
// Replay fills this fresh store; a failed resume leaves nothing fabricated.
|
||||
transcripts[entry.sessionId] = SessionTranscript()
|
||||
replayingSessionId = entry.sessionId
|
||||
// Replay ordering: the adapter writes the history notifications
|
||||
// BEFORE the load response, and the MainActor Task pipeline
|
||||
// preserves that order — same reliance as live streaming.
|
||||
let result = try await client.request(
|
||||
"session/load",
|
||||
params: .object([
|
||||
"cwd": .string(cwdProvider()),
|
||||
"sessionId": .string(entry.sessionId),
|
||||
"mcpServers": .array([]),
|
||||
]),
|
||||
// Finish-audit: the adapter replays the FULL history before
|
||||
// responding — #23's exact shape (response arrives when the
|
||||
// work ends). The client's 15 s default would abort a long
|
||||
// session's resume mid-replay.
|
||||
timeout: Self.promptTimeout,
|
||||
)
|
||||
replayingSessionId = nil
|
||||
// null/absent (or empty) sessionId in the result = the engine does not know it.
|
||||
guard let sid = result?.objectValue?["sessionId"]?.stringValue, !sid.isEmpty else {
|
||||
// The refusal belongs to the ENTRY — attributed, and visible
|
||||
// on its next row click (the store is kept, not discarded).
|
||||
appendRow(
|
||||
.text("The engine does not know “\(entry.name)” — its history is no longer on the engine."),
|
||||
to: entry.sessionId,
|
||||
)
|
||||
return false
|
||||
}
|
||||
// Activate WITHOUT resetting the transcript — activate() is for
|
||||
// fresh-transcript activations; the replay already filled this one.
|
||||
activeEntry = entry
|
||||
phase = .ready
|
||||
return true
|
||||
} catch {
|
||||
replayingSessionId = nil
|
||||
// Partial replay rows (if any) + the failure row stay in the
|
||||
// ENTRY's store — attributed, visible on its next row click.
|
||||
appendRow(.text("Resume failed — \(error.localizedDescription)"), to: entry.sessionId)
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
/// Fork the active session (#28): the engine copies its history to a NEW
|
||||
/// sessionId (session/fork); Museion rosters '<name> (fork)' with the
|
||||
/// same pieceTitle and activates it with a FRESH transcript — the
|
||||
/// original entry and transcript stay untouched. An empty-string
|
||||
/// sessionId from the wire is a refusal (honest row, nil return).
|
||||
@discardableResult
|
||||
func forkActiveSession() async -> SessionEntry? {
|
||||
guard phase.isReady, let client, let source = activeEntry, !isStreaming else { return nil }
|
||||
do {
|
||||
let result = try await client.request(
|
||||
"session/fork",
|
||||
params: .object([
|
||||
"cwd": .string(cwdProvider()),
|
||||
"sessionId": .string(source.sessionId),
|
||||
"mcpServers": .array([]),
|
||||
]),
|
||||
)
|
||||
guard let sid = result?.objectValue?["sessionId"]?.stringValue, !sid.isEmpty else {
|
||||
appendRow(.text("Fork refused — the engine returned no new session."), to: source.sessionId)
|
||||
return nil
|
||||
}
|
||||
let entry = SessionEntry(
|
||||
sessionId: sid,
|
||||
name: "\(source.name) (fork)",
|
||||
pieceTitle: source.pieceTitle,
|
||||
createdAt: Date(),
|
||||
)
|
||||
roster.insert(entry, at: 0)
|
||||
transcripts[sid] = SessionTranscript()
|
||||
activeEntry = entry
|
||||
phase = .ready
|
||||
saveRoster()
|
||||
return entry
|
||||
} catch {
|
||||
appendRow(.text("Fork failed — \(error.localizedDescription)"), to: source.sessionId)
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
/// Compact the active idle session (#28): the engine's /compress dispatch
|
||||
/// rides the existing prompt rail; the label keeps the raw slash command
|
||||
/// out of the transcript and the summary streams back as ordinary chunks.
|
||||
/// Refused while a turn streams (idle-only engine-side, too).
|
||||
func compactActiveSession() async {
|
||||
guard canStartSession, activeEntry != nil else { return }
|
||||
_ = await sendPrompt("/compress", label: "Compact…")
|
||||
}
|
||||
|
||||
/// Read-only transcript of ANY rostered session (#28) — the Sessions pane
|
||||
/// and tests read without activating.
|
||||
func transcriptRows(of entry: SessionEntry) -> [SessionRow] {
|
||||
transcripts[entry.sessionId]?.rows ?? []
|
||||
}
|
||||
|
||||
private func activate(_ entry: SessionEntry) {
|
||||
transcripts[entry.sessionId] = SessionTranscript()
|
||||
activeEntry = entry
|
||||
phase = .ready
|
||||
}
|
||||
|
||||
private func saveRoster() {
|
||||
SessionRoster.save(roster, directory: rosterDirectory)
|
||||
}
|
||||
|
||||
/// Send a prompt and stream the reply into the ACTIVE session's
|
||||
/// transcript. Appends the user row first — a non-nil `label` renders
|
||||
/// verbatim INSTEAD of the raw prompt (pass prompts are long wire stubs
|
||||
/// that must not land in the transcript); the stop_reason response ends
|
||||
/// the turn (refusal maps to a plain note — wire-verified edge
|
||||
/// semantics). Returns how the turn ended (#24 seam): a pass advances
|
||||
/// only on a completed turn, never on cancel/crash. session/prompt's
|
||||
/// response arrives only when the TURN ends — a pass legitimately runs
|
||||
/// minutes of tool work between prompt and stop reason. The client's
|
||||
/// 15 s request default would abandon the wait mid-stream (observed
|
||||
/// live, #23 dogfood: "connection lost" while the engine kept working,
|
||||
/// Stop vanished with isStreaming). Long-but-finite so a truly stuck
|
||||
/// engine still surfaces; Stop is the live-turn exit.
|
||||
nonisolated static let promptTimeout: TimeInterval = 1800
|
||||
|
||||
@discardableResult
|
||||
@@ -255,20 +581,22 @@ final class MentorSessionModel {
|
||||
// Guard refusal: the turn never ran — .failed is the closest of the
|
||||
// three buckets (the seam has no "never started" case; callers that
|
||||
// check phase before prompting never land here).
|
||||
guard !prompt.isEmpty, case let .ready(sid) = phase, !isStreaming else { return .failed }
|
||||
guard !prompt.isEmpty, phase.isReady, !isStreaming, let sid = activeEntry?.sessionId else {
|
||||
return .failed
|
||||
}
|
||||
lastPrompt = prompt
|
||||
rows.append(SessionRow(content: .text(label ?? "You: \(prompt)")))
|
||||
appendRow(.text(label ?? "You: \(prompt)"), to: sid)
|
||||
isStreaming = true
|
||||
defer {
|
||||
// Flush the thinking first (it preceded the message), collapsed.
|
||||
if !streamingThought.isEmpty {
|
||||
rows.append(SessionRow(content: .thought(streamingThought)))
|
||||
streamingThought = ""
|
||||
if let pending = transcripts[sid], !pending.streamingThought.isEmpty {
|
||||
appendRow(.thought(pending.streamingThought), to: sid)
|
||||
transcripts[sid]?.streamingThought = ""
|
||||
}
|
||||
// Flush any streamed-but-unfinished agent text into a row.
|
||||
if !streamingText.isEmpty {
|
||||
rows.append(SessionRow(content: .text("Mentor: \(streamingText)")))
|
||||
streamingText = ""
|
||||
if let pending = transcripts[sid], !pending.streamingText.isEmpty {
|
||||
appendRow(.text("Mentor: \(pending.streamingText)"), to: sid)
|
||||
transcripts[sid]?.streamingText = ""
|
||||
}
|
||||
isStreaming = false
|
||||
}
|
||||
@@ -290,7 +618,7 @@ final class MentorSessionModel {
|
||||
// must not advance on a maybe (review: empty-stopReason bug).
|
||||
guard !stopReason.isEmpty else { return .failed }
|
||||
if stopReason == "refusal" {
|
||||
rows.append(SessionRow(content: .text("Mentor: (refused the prompt)")))
|
||||
appendRow(.text("Mentor: (refused the prompt)"), to: sid)
|
||||
}
|
||||
if stopReason == "cancelled" {
|
||||
return .cancelled
|
||||
@@ -302,7 +630,7 @@ final class MentorSessionModel {
|
||||
if case .crashed = phase {
|
||||
// Crash card already owns the failure surface.
|
||||
} else {
|
||||
rows.append(SessionRow(content: .text("Mentor: connection lost — \(error.localizedDescription)")))
|
||||
appendRow(.text("Mentor: connection lost — \(error.localizedDescription)"), to: sid)
|
||||
}
|
||||
return .failed
|
||||
}
|
||||
@@ -312,10 +640,22 @@ final class MentorSessionModel {
|
||||
/// session/cancel, a notification — no response expected). The engine
|
||||
/// ends the turn (PromptResponse) as its acknowledgement.
|
||||
func stopStreaming() {
|
||||
guard isStreaming, let sid = sessionId else { return }
|
||||
guard isStreaming, let sid = activeEntry?.sessionId else { return }
|
||||
client?.notify("session/cancel", params: .object(["sessionId": .string(sid)]))
|
||||
}
|
||||
|
||||
/// 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 {
|
||||
version.split(separator: "+", maxSplits: 1, omittingEmptySubsequences: false).first.map(String.init) ?? version
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Crash, stderr, and notification decoding (same-file extension —
|
||||
|
||||
// the class body keeps lifecycle + turn operations)
|
||||
|
||||
extension MentorSessionModel {
|
||||
private func handleCrash() {
|
||||
guard case .ready = phase else {
|
||||
// A crash during startup also lands in the restart prompt.
|
||||
@@ -334,53 +674,70 @@ final class MentorSessionModel {
|
||||
}
|
||||
}
|
||||
|
||||
/// 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 {
|
||||
version.split(separator: "+", maxSplits: 1, omittingEmptySubsequences: false).first.map(String.init) ?? version
|
||||
}
|
||||
|
||||
// MARK: - Notification decoding
|
||||
|
||||
/// Route by the session id FROM THE PARAMS (#28) — a replay for a
|
||||
/// background session lands in ITS transcript, never the active one's.
|
||||
private func handleNotification(method: String, params: JSONValue?) {
|
||||
guard method == "session/update",
|
||||
let params,
|
||||
let sessionId = params.objectValue?["sessionId"]?.stringValue,
|
||||
sessionId == self.sessionId else { return }
|
||||
let sid = params.objectValue?["sessionId"]?.stringValue,
|
||||
transcripts[sid] != nil else { return }
|
||||
guard let update = params.objectValue?["update"]?.objectValue else { return }
|
||||
let kind = update["sessionUpdate"]?.stringValue ?? "unknown"
|
||||
let replaying = sid == replayingSessionId
|
||||
switch kind {
|
||||
case "agent_message_chunk":
|
||||
let text = update["content"]?.objectValue?["text"]?.stringValue ?? ""
|
||||
streamingText += text
|
||||
if replaying {
|
||||
// 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)
|
||||
} else {
|
||||
transcripts[sid]?.streamingText += text
|
||||
}
|
||||
case "agent_thought_chunk":
|
||||
let text = update["content"]?.objectValue?["text"]?.stringValue ?? ""
|
||||
streamingThought += text
|
||||
if replaying {
|
||||
appendRow(.thought(text), to: sid)
|
||||
} else {
|
||||
transcripts[sid]?.streamingThought += text
|
||||
}
|
||||
case "user_message_chunk":
|
||||
// The engine echoes the user message; we already rendered it.
|
||||
break
|
||||
// Live: the engine echoes the user message; the label row already
|
||||
// rendered. During replay there IS no rendered row — the engine
|
||||
// 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)
|
||||
}
|
||||
case "tool_call":
|
||||
appendToolCall(update)
|
||||
appendToolCall(update, to: sid)
|
||||
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()
|
||||
rows.append(SessionRow(content: .raw(kind: kind, json: String(bytes: json, encoding: .utf8) ?? "")))
|
||||
appendRow(.raw(kind: kind, json: String(bytes: json, encoding: .utf8) ?? ""), to: sid)
|
||||
}
|
||||
}
|
||||
|
||||
/// Tool-call decoding — the fix-card rail (ADR-0006): a tool call whose
|
||||
/// `rawInput` decodes to fix-card fields renders as a card; any other tool
|
||||
/// call renders as a raw row.
|
||||
private func appendToolCall(_ update: [String: JSONValue]) {
|
||||
private func appendToolCall(_ update: [String: JSONValue], to sid: String) {
|
||||
let title = update["title"]?.stringValue ?? "tool call"
|
||||
let rawInput = update["rawInput"]
|
||||
if let card = FixCard(rawInput: rawInput) {
|
||||
rows.append(SessionRow(content: .fixCard(card)))
|
||||
appendRow(.fixCard(card), to: sid)
|
||||
return
|
||||
}
|
||||
let json = (try? JSONSerialization.data(withJSONObject: rawInput?.any ?? [:], options: [.sortedKeys])) ?? Data()
|
||||
rows.append(SessionRow(content: .raw(kind: title, json: String(bytes: json, encoding: .utf8) ?? "")))
|
||||
appendRow(.raw(kind: title, json: String(bytes: json, encoding: .utf8) ?? ""), to: sid)
|
||||
}
|
||||
|
||||
/// Append one row to a session's transcript; nil targets the ACTIVE one.
|
||||
private func appendRow(_ content: SessionRow.Content, to sid: String?) {
|
||||
guard let sid else { return }
|
||||
transcripts[sid, default: SessionTranscript()].rows.append(SessionRow(content: content))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user