feat(sessions): session lifecycle UI (S2.3) (#28)
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:
AlexKucera committed 2026-10-22 12:21:12 +02:00
1 parent 78c8844184
commit 9895614b7e
15 files changed
+1523 -245

No files matched your search

+93 -18
View File
@@ -31,7 +31,17 @@ import Testing
/// session/cancel is answered — any other request waits until teardown;
/// `cancelOnPrompt` streams one chunk then answers stopReason "cancelled"
/// with no cancel needed; `refuseOnPrompt` answers stopReason "refusal" (no
/// chunks).
/// chunks); `loadReplay` (#28) adds the lifecycle wire: session/new/load/fork
/// all require `mcpServers` (-32602 without, the #44 invariant), session ids
/// are minted uniquely (sess-1, sess-2, …), session/load replays
/// user+thought+message chunks for ANY minted sess-* id then answers its id
/// (a relaunch default-open resumes the newest rostered entry, #28 review
/// fix; any other id answers with NO sessionId = unknown), and session/fork
/// of sess-1 returns a fresh F-<n> (any other source id returns ""). load/fork
/// log "load <id>" / "fork <id>" to stderr so tests can pin the wire call.
/// Mode `loadReplayHold` = loadReplay with session/load PARKED (after a
/// "hold-load" stderr line) until a `load-go` file lands beside the fake —
/// the finish-audit interleaving pin's in-flight observable.
/// The mode travels in a file next to the fake (self-locating — race-free
/// under parallel suites, same convention as ProfileProvisionerTests).
/// The fix-card payload travels base64-encoded so shell quoting can't break.
@@ -50,8 +60,10 @@ func makeFakeACP(at dir: String, name: String = "hermes-acp", mode: String = "fu
[[ -f "${0:h}/\(name)-mode" ]] && mode=$(<"${0:h}/\(name)-mode")
card=$(print -- '\(fixCardB64)' | base64 -d)
framing='{"jsonrpc":"2.0","id":'
notify='{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"sess-1","update":'
while IFS= read -r line; do # print -r below, never echo — zsh's echo eats the JSON \n escapes of multi-line prompts
sessn=0
forkn=0
mcpcheck='import json,sys; print("1" if "mcpServers" in json.load(sys.stdin).get("params",{}) else "0")'
while IFS= read -r line; do # print -r below, never echo — zsh's echo eats the JSON \\n escapes of multi-line prompts
[[ -z "$line" ]] && continue
method=$(print -r -- "$line" | /usr/bin/python3 -c 'import json,sys; print(json.load(sys.stdin).get("method",""))')
rid=$(print -r -- "$line" | /usr/bin/python3 -c 'import json,sys; d=json.load(sys.stdin).get("id"); print(d if d is not None else "x")')
@@ -59,8 +71,18 @@ func makeFakeACP(at dir: String, name: String = "hermes-acp", mode: String = "fu
echo $framing"$rid",'"result":{"protocolVersion":1,"agentInfo":{"name":"hermes-agent","title":"Hermes","version":"9.9.9"}}}'
[[ "$mode" == "crashAfterHandshake" ]] && exit 1
elif [[ "$method" == "session/new" ]]; then
echo $framing"$rid",'"result":{"sessionId":"sess-1"}}'
if [[ "$mode" == "loadReplay" ]]; then # #44 invariant: mcpServers required
ok=$(print -r -- "$line" | /usr/bin/python3 -c "$mcpcheck")
if [[ "$ok" == "0" ]]; then
echo $framing"$rid",'{"error":{"code":-32602,"message":"Invalid params: mcpServers required"}}}'
continue
fi
fi
sessn=$((sessn+1)) # #28: unique id per new — multi-session rosters need distinct ids
echo $framing"$rid",'"result":{"sessionId":"sess-'"$sessn"'"}}'
elif [[ "$method" == "session/prompt" ]]; then
psid=$(print -r -- "$line" | /usr/bin/python3 -c 'import json,sys; print(json.load(sys.stdin).get("params",{}).get("sessionId",""))')
notify='{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"'"$psid"'","update":'
if [[ "$mode" == "refuseOnPrompt" ]]; then
echo $framing"$rid",'"result":{"stopReason":"refusal"}}'
continue
@@ -93,6 +115,51 @@ func makeFakeACP(at dir: String, name: String = "hermes-acp", mode: String = "fu
done
fi
echo $framing"$rid",'"result":{"stopReason":"end_turn"}}'
elif [[ "$method" == "session/load" ]]; then
if [[ "$mode" != loadReplay* ]]; then continue; fi
ok=$(print -r -- "$line" | /usr/bin/python3 -c "$mcpcheck")
if [[ "$ok" == "0" ]]; then
echo $framing"$rid",'{"error":{"code":-32602,"message":"Invalid params: mcpServers required"}}}'
continue
fi
lsid=$(print -r -- "$line" | /usr/bin/python3 -c 'import json,sys; print(json.load(sys.stdin).get("params",{}).get("sessionId",""))')
print -u2 -- "load $lsid" # the wire call, visible in model.stderrTail
if [[ "$mode" == "loadReplayHold" ]]; then
# Finish-audit pin support: park the replay until `load-go` lands
# beside the fake; the pre-hold stderr line above is the observable
# that the load (and the model's replay slot) is in flight.
print -u2 -- "hold-load"
while [[ ! -f "${0:h}/load-go" ]]; do sleep 0.05; done
fi
# Any MINTED id replays: a relaunch default-open resumes the newest
# rostered session (review fix), so load answers every id session/new
# ever issued, not one planted id.
rnot='{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"'"$lsid"'","update":'
if [[ "$lsid" == sess-* ]]; then
# Full history replay, wire order, BEFORE the load response — the
# real adapter's contract (#28).
echo $rnot'{"sessionUpdate":"user_message_chunk","content":{"type":"text","text":"earlier ask"}}}}'
echo $rnot'{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"old thinking"}}}}'
echo $rnot'{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"earlier verdict"}}}}'
echo $framing"$rid",'"result":{"sessionId":"'"$lsid"'"}}'
else
echo $framing"$rid",'"result":{}}' # unknown session — no sessionId
fi
elif [[ "$method" == "session/fork" ]]; then
if [[ "$mode" != "loadReplay" ]]; then continue; fi
ok=$(print -r -- "$line" | /usr/bin/python3 -c "$mcpcheck")
if [[ "$ok" == "0" ]]; then
echo $framing"$rid",'{"error":{"code":-32602,"message":"Invalid params: mcpServers required"}}}'
continue
fi
fsid=$(print -r -- "$line" | /usr/bin/python3 -c 'import json,sys; print(json.load(sys.stdin).get("params",{}).get("sessionId",""))')
print -u2 -- "fork $fsid"
if [[ "$fsid" == "sess-1" ]]; then
forkn=$((forkn+1))
echo $framing"$rid",'"result":{"sessionId":"F-'"$forkn"'"}}'
else
echo $framing"$rid",'"result":{"sessionId":""}}' # empty = fork refused
fi
elif [[ "$method" == "session/cancel" ]]; then
print -u2 -- "cancel received"
fi
@@ -308,12 +375,12 @@ struct ACPClientTests {
/// #23 dogfood: the writing-session filter — prose + card events stay,
/// raw session/tool rows and thinking are debug-only.
@Test func `writing-session filter keeps prose and cards, hides raw and thought`() {
#expect(MentorPaneView.isWritingRow(SessionRow(content: .text("Pass 1 · The piece"))))
#expect(MentorPaneView.isWritingRow(SessionRow(content: .fixCard(
#expect(SessionTranscriptView.isWritingRow(SessionRow(content: .text("Pass 1 · The piece"))))
#expect(SessionTranscriptView.isWritingRow(SessionRow(content: .fixCard(
FixCard(pattern: "p", problem: "q", diagnosticQuestion: "", fix: "", anchor: "", provenance: "", status: ""),
))))
#expect(!MentorPaneView.isWritingRow(SessionRow(content: .thought("thinking…"))))
#expect(!MentorPaneView.isWritingRow(SessionRow(content: .raw(kind: "tool_call_update", json: "{}"))))
#expect(!SessionTranscriptView.isWritingRow(SessionRow(content: .thought("thinking…"))))
#expect(!SessionTranscriptView.isWritingRow(SessionRow(content: .raw(kind: "tool_call_update", json: "{}"))))
}
@MainActor
@@ -389,24 +456,32 @@ struct ACPClientTests {
// MARK: - Model tests
@MainActor
@Test func `model handshake renders version and streams fix card`() async {
@Test @MainActor func `model handshake renders version and streams fix card`() async throws {
let fake = makeFakeACP(at: acpTempDir("model"))
let model = MentorSessionModel(binaryPath: fake)
defer { model.shutdown() } // #124: at rig creation — the child dies with the test, however it exits
await model.openSession()
guard case let .ready(sessionId) = model.phase else {
guard case .ready = model.phase else {
Issue.record("expected ready, got \(model.phase)")
return
}
#expect(sessionId == "sess-1")
#expect(model.activeEntry?.sessionId == "sess-1")
#expect(model.engineVersion == "9.9.9")
await model.sendPrompt("hello mentor")
let hasCard = model.rows.contains { row in
if case let .fixCard(card) = row.content {
return card.pattern == "Blame tense"
// The card row lands via a client notification Task that can settle just
// after the response resumes this test under full-suite load — bounded
// settle (house poll pattern); the pin itself is unchanged.
var hasCard = false
for _ in 0 ..< 250 where !hasCard {
hasCard = model.rows.contains { row in
if case let .fixCard(card) = row.content {
return card.pattern == "Blame tense"
}
return false
}
if !hasCard {
try await Task.sleep(nanoseconds: 20_000_000)
}
return false
}
#expect(hasCard)
let hasText = model.rows.contains { row in
@@ -464,11 +539,11 @@ struct ACPClientTests {
let model = MentorSessionModel(binaryPath: fake)
defer { model.shutdown() }
await model.openSession()
guard case let .ready(sessionId) = model.phase else {
guard case .ready = model.phase else {
Issue.record("expected ready against strict engine, got \(model.phase); stderr: \(model.stderrTail)")
return
}
#expect(sessionId == "sess-1")
#expect(model.activeEntry?.sessionId == "sess-1")
}
@MainActor