Files
museion/MuseionTests/ACPClientTests.swift
T
AlexKucera 154bb8a114
CI / ci (push) Canceled after 0s
test(mentor): cancel-ack fake + deferred teardown
The fake ACP engine's hangOnPrompt mode slept oblivious to
session/cancel, so a cancelled turn was only observable through
teardown and the pass bar's Cancel rail was never individually
discriminated. hangOnPrompt now holds the turn reading: session/cancel
answers the hanging prompt with stopReason "cancelled" (the real
engine's contract); stdin EOF without a cancel answers end_turn so
the child exits.

New pin 'cancelling a held pass ends the turn cancelled with no
advance' (RED->GREEN; bounded polls, so an emptied cancelPass fails
the pin instead of hanging the suite). Every fake-spawning test (27
rigs across ACPClientTests + PassRunTests) tears down via defer at
rig creation — a cancelled or interrupted test cannot leak the child;
trailing happy-path teardowns removed, mechanism/bound teardowns kept
and commented. Harness docs updated to match; 316 tests green.

Closes #124
2026-10-20 19:35:17 +02:00

502 lines
21 KiB
Swift

//
// ACPClientTests.swift
// MuseionTests
//
// M0 ACP bridge (#14): the fake ACP server test double — a zsh script
// speaking real NDJSON JSON-RPC on stdio (map decision: extends the
// fake-binary Process pattern from EngineGateTests). Exercises the client
// and model against the real Process path: handshake, prompt + streamed
// updates + fix-card tool call, crash, teardown.
// #124: hangOnPrompt now acknowledges session/cancel (stopReason
// "cancelled") — a sleep-oblivious hold can't pin the Cancel rail.
//
// swiftlint:disable file_length
// One file: the shared fake harness (makeFakeACP/acpTempDir — other test
// files build rigs on it) + the client/model suites that pin its contract.
import Foundation
@testable import Museion
import Testing
// MARK: - Fake ACP server + helpers
// swiftlint:disable function_body_length
/// Builds a fake engine binary that speaks enough ACP for the M0 client.
/// `mode`: `full` answers everything; `crashAfterHandshake` exits 1 right
/// after answering initialize; `hangOnPrompt` streams, then HOLDS the turn
/// open reading — session/cancel answers the hanging prompt with stopReason
/// "cancelled" (the real engine's contract, #124), stdin EOF without a
/// cancel (teardown) answers end_turn, and during the hold ONLY
/// 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).
/// 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.
/// Internal (not private) so later test files can reuse the fake (#24).
/// One contiguous zsh program — splitting the script string would break the
/// wire-line inspectability the script's own comment pins.
func makeFakeACP(at dir: String, name: String = "hermes-acp", mode: String = "full") -> String {
let path = (dir as NSString).appendingPathComponent(name)
let modeFile = (dir as NSString).appendingPathComponent("\(name)-mode")
let fixCardB64 = fixCardPayloadB64()
// ponytail: one echo per wire message — long payloads ride shell vars so
// each line stays under the lint cap and inspectable against the schema.
let script = """
#!/bin/zsh
mode="full"
[[ -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
[[ -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")')
if [[ "$method" == "initialize" ]]; then
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"}}'
elif [[ "$method" == "session/prompt" ]]; then
if [[ "$mode" == "refuseOnPrompt" ]]; then
echo $framing"$rid",'"result":{"stopReason":"refusal"}}'
continue
fi
echo $notify'{"sessionUpdate":"user_message_chunk","content":{"type":"text","text":"echo"},"messageId":"u1"}}}'
echo $notify'{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"weighing the structure"},"messageId":"t1"}}}'
echo $notify'{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"Hello "},"messageId":"m1"}}}'
if [[ "$mode" == "cancelOnPrompt" ]]; then
echo $framing"$rid",'"result":{"stopReason":"cancelled"}}'
continue
fi
if [[ "$mode" == "noStopReason" ]]; then
echo $framing"$rid",'"result":{"sessionId":"sess-1"}}'
continue
fi
echo $notify'{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"mentor."},"messageId":"m1"}}}'
echo $notify'{"sessionUpdate":"tool_call","toolCallId":"tc1","title":"submit_fix_cards","rawInput":'"$card"'}}}'
if [[ "$mode" == "hangOnPrompt" ]]; then
# #124: the cancel-acknowledging hold — the real engine answers its
# hanging prompt with stopReason "cancelled" the moment session/cancel
# arrives; a sleep-oblivious fake can't pin the Cancel rail. EOF with
# no cancel (teardown closed stdin) ends the turn so the child exits.
while IFS= read -r held; do
[[ -z "$held" ]] && continue
hm=$(print -r -- "$held" | /usr/bin/python3 -c 'import json,sys; print(json.load(sys.stdin).get("method",""))')
if [[ "$hm" == "session/cancel" ]]; then
echo $framing"$rid",'"result":{"stopReason":"cancelled"}}'
continue 2
fi
done
fi
echo $framing"$rid",'"result":{"stopReason":"end_turn"}}'
elif [[ "$method" == "session/cancel" ]]; then
print -u2 -- "cancel received"
fi
done
exit 0
"""
try? FileManager.default.createDirectory(atPath: dir, withIntermediateDirectories: true)
try? mode.write(toFile: modeFile, atomically: true, encoding: .utf8)
try? script.write(toFile: path, atomically: true, encoding: .utf8)
_ = try? FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: path)
return path
}
// swiftlint:enable function_body_length
/// The fix-card payload for the fake's tool call, base64-encoded so shell
/// quoting can never break the wire JSON. The REAL submit_fix_cards
/// argument shape (snake_case, anchor as object) — pins the nested parse;
/// the flat #14-era shape was a regression the parser never matched the
/// live rail (review).
private func fixCardPayloadB64() -> String {
let card = #"{"pattern":"Blame tense","problem":"Never pivots to choice","# +
#""diagnostic_question":"What tense?","fix":"Pivot on the hinge","# +
#""anchor":{"quote":"We should stop listening.","occurrence":1}}"#
let json = #"{"piece_path":"/tmp/piece","cards":["# + card + #"]}"#
return Data(json.utf8).base64EncodedString()
}
func acpTempDir(_ label: String) -> String {
let dir = NSTemporaryDirectory() + "museion-acp-\(label)-\(UUID().uuidString)"
try? FileManager.default.createDirectory(atPath: dir, withIntermediateDirectories: true)
return dir
}
/// A strict `session/new` guard, mirroring the ACP SDK's required mcpServers
/// (adapter ≥0.21.5 rejects the field's absence with -32602). The lenient
/// fake above accepts anything and can't catch this bug class.
private func makeStrictFakeACP(at dir: String, name: String = "hermes-acp-strict") -> String {
let path = (dir as NSString).appendingPathComponent(name)
let script = """
#!/bin/zsh
framing='{"jsonrpc":"2.0","id":'
jq=/usr/bin/python3
while IFS= read -r line; do
[[ -z "$line" ]] && continue
method=$(echo "$line" | $jq -c 'import json,sys; print(json.load(sys.stdin).get("method",""))')
rid=$(echo "$line" | $jq -c 'import json,sys; d=json.load(sys.stdin).get("id"); print(d if d is not None else "x")')
if [[ "$method" == "initialize" ]]; then
echo $framing"$rid",'"result":{"protocolVersion":1,"agentInfo":{"name":"hermes-agent","title":"Hermes","version":"9.9.9"}}}'
elif [[ "$method" == "session/new" ]]; then
ok=$(echo "$line" | $jq -c 'import json,sys; print("1" if "mcpServers" in json.load(sys.stdin).get("params",{}) else "0")')
if [[ "$ok" == "1" ]]; then
echo $framing"$rid",'"result":{"sessionId":"sess-1"}}'
else
echo $framing"$rid",'"error":{"code":-32602,"message":"Invalid params: mcpServers required"}}'
fi
fi
done
exit 0
"""
try? FileManager.default.createDirectory(atPath: dir, withIntermediateDirectories: true)
try? script.write(toFile: path, atomically: true, encoding: .utf8)
_ = try? FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: path)
return path
}
// MARK: - Client tests
@Suite("ACPClientTests")
struct ACPClientTests {
@Test func `handshake returns agent version`() async throws {
let fake = makeFakeACP(at: acpTempDir("handshake"))
let client = ACPEngineClient(binaryPath: fake)
defer { client.close() } // #124: at rig creation — the child dies with the test, however it exits
try client.start { _, _ in }
let result = try await client.request("initialize", params: .object([
"protocolVersion": .number(1),
"clientCapabilities": .object([:]),
"clientInfo": .object(["name": .string("Museion"), "title": .string("Museion"), "version": .string("0.1")]),
]))
#expect(result?.objectValue?["agentInfo"]?.objectValue?["version"]?.stringValue == "9.9.9")
}
@Test func `crash after handshake fires onCrash`() async throws {
let fake = makeFakeACP(at: acpTempDir("crash"), mode: "crashAfterHandshake")
let client = ACPEngineClient(binaryPath: fake)
defer { client.close() } // #124: at rig creation — the child dies with the test, however it exits
try client.start { _, _ in }
// Hook FIRST, then trigger: the fake exits right after answering
// initialize, so the crash can beat a hook attached after the request.
await confirmation("onCrash fires once") { crashed in
client.onCrash = { crashed() }
_ = try? await client.request("initialize", params: nil)
try? await Task.sleep(for: .milliseconds(500))
}
}
@Test func `cancel is fire-and-forget`() async throws {
let fake = makeFakeACP(at: acpTempDir("cancel"), mode: "hangOnPrompt")
let client = ACPEngineClient(binaryPath: fake)
defer { client.close() } // #124: at rig creation — the child dies with the test, however it exits
try client.start { _, _ in }
_ = try? await client.request("session/new", params: .object(["cwd": .string("/tmp")]))
// The prompt holds — drive it in the background, then cancel.
let promptTask = Task { try? await client.request("session/prompt", params: .object([
"sessionId": .string("sess-1"),
"prompt": .array([.object(["type": .string("text"), "text": .string("hello")])]),
])) }
try await Task.sleep(for: .milliseconds(300))
client.notify("session/cancel", params: .object(["sessionId": .string("sess-1")]))
try await Task.sleep(for: .milliseconds(200))
client.close() // bound only — the fake answers the prompt on cancel
_ = await promptTask.value
// ponytail: reaching here without deadlock IS the cancel test — a
// notification produces no response and the client never waits for one.
#expect(true)
}
@Test func `teardown kills a hung child and fails pending requests`() async throws {
let fake = makeFakeACP(at: acpTempDir("teardown"), mode: "hangOnPrompt")
let client = ACPEngineClient(binaryPath: fake)
defer { client.close() } // #124: at rig creation — the child dies with the test, however it exits
try client.start { _, _ in }
_ = try? await client.request("session/new", params: .object(["cwd": .string("/tmp")]))
let promptTask = Task { try? await client.request("session/prompt", params: .object([
"sessionId": .string("sess-1"),
"prompt": .array([.object(["type": .string("text"), "text": .string("hello")])]),
])) }
try await Task.sleep(for: .milliseconds(300))
let pid = client.childProcessIdentifier
client.close()
_ = await promptTask.value
var gone = false
for _ in 0 ..< 50 where kill(pid, 0) != 0 {
try await Task.sleep(for: .milliseconds(100))
}
if kill(pid, 0) != 0 {
gone = true
}
#expect(gone)
}
// MARK: - Turn outcome seam (#24 S3.1: sendPrompt → TurnOutcome)
// The suite hosts these model tests (not free functions like the model
// tests below) so the suite-name test filter runs them.
@MainActor
@Test func `sendPrompt returns ended end_turn and streams text`() async {
let fake = makeFakeACP(at: acpTempDir("outcome-ended"))
let model = MentorSessionModel(binaryPath: fake)
defer { model.shutdown() }
await model.openSession()
let outcome = await model.sendPrompt("hello mentor")
#expect(outcome == .ended(stopReason: "end_turn"))
let streamed = model.rows.contains { row in
if case let .text(text) = row.content {
return text.contains("Hello mentor.")
}
return false
}
#expect(streamed)
}
@MainActor
@Test func `labeled prompt renders the label not the wire stub`() async {
let fake = makeFakeACP(at: acpTempDir("outcome-label"))
let model = MentorSessionModel(binaryPath: fake)
defer { model.shutdown() }
await model.openSession()
// The pass orchestrator sends a long wire stub; only the label may land.
await model.sendPrompt("STUB-WIRE-PROMPT that must never surface", label: "Pass 1 · My Post")
var texts: [String] = []
for row in model.rows {
if case let .text(text) = row.content {
texts.append(text)
}
}
#expect(texts.contains("Pass 1 · My Post"))
#expect(!texts.contains { $0.contains("STUB-WIRE-PROMPT") })
}
@MainActor
@Test func `cancelled stopReason maps to TurnOutcome cancelled`() async {
let fake = makeFakeACP(at: acpTempDir("outcome-cancel"), mode: "cancelOnPrompt")
let model = MentorSessionModel(binaryPath: fake)
defer { model.shutdown() }
await model.openSession()
let outcome = await model.sendPrompt("hello mentor")
#expect(outcome == .cancelled)
}
/// Review pin: a prompt response without stopReason is NOT a completed
/// turn — .failed, so a pass never advances on a maybe.
@MainActor
@Test func `missing stopReason maps to failed`() async {
let fake = makeFakeACP(at: acpTempDir("outcome-nostop"), mode: "noStopReason")
let model = MentorSessionModel(binaryPath: fake)
defer { model.shutdown() }
await model.openSession()
let outcome = await model.sendPrompt("hello mentor")
#expect(outcome == .failed)
}
/// #23 dogfood regression pin: session/prompt's response arrives when the
/// TURN ends — minutes into a pass. The client's 15 s request default
/// abandoned live turns ("connection lost" while the engine kept working,
/// Stop vanished with isStreaming). sendPrompt must wait pass-length.
@Test func `prompt deadline is pass length not the request default`() {
#expect(MentorSessionModel.promptTimeout >= 600)
}
/// #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(
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: "{}"))))
}
@MainActor
@Test func `refusal maps to ended refusal and still renders the refusal row`() async {
let fake = makeFakeACP(at: acpTempDir("outcome-refusal"), mode: "refuseOnPrompt")
let model = MentorSessionModel(binaryPath: fake)
defer { model.shutdown() }
await model.openSession()
let outcome = await model.sendPrompt("hello mentor")
#expect(outcome == .ended(stopReason: "refusal"))
let refused = model.rows.contains { row in
if case let .text(text) = row.content {
return text.contains("(refused the prompt)")
}
return false
}
#expect(refused)
}
@MainActor
@Test func `thought chunks land in a collapsed thought row not the critique`() async {
let fake = makeFakeACP(at: acpTempDir("thought-lane"))
let model = MentorSessionModel(binaryPath: fake)
defer { model.shutdown() }
await model.openSession()
// The fake streams a thought chunk BEFORE the message chunks — the
// live shape of a pass turn (long thinking, then the critique).
let outcome = await model.sendPrompt("hello mentor")
#expect(outcome == .ended(stopReason: "end_turn"))
let thought = model.rows.contains { row in
if case let .thought(text) = row.content {
return text == "weighing the structure"
}
return false
}
#expect(thought)
// The critique text stays clean — thinking never bleeds into it.
let critique = model.rows.contains { row in
if case let .text(text) = row.content {
return text == "Mentor: Hello mentor."
}
return false
}
#expect(critique)
#expect(!model.rows.contains { row in
if case let .text(text) = row.content {
return text.contains("weighing")
}
return false
})
}
@MainActor
@Test func `transport failure mid-turn maps to TurnOutcome failed`() async throws {
let fake = makeFakeACP(at: acpTempDir("outcome-failed"), mode: "hangOnPrompt")
let model = MentorSessionModel(binaryPath: fake)
defer { model.shutdown() }
await model.openSession()
// Deterministic transport failure through the model: hangOnPrompt keeps
// the turn pending, then shutdown() closes the client — the in-flight
// session/prompt fails with a transport error, the same route a mid-turn
// engine error takes. crashAfterHandshake can't pin this: after the crash
// the phase is .crashed and sendPrompt's guard refuses before any request.
let promptTask = Task { await model.sendPrompt("hello mentor") }
for _ in 0 ..< 100 where !model.isStreaming {
try await Task.sleep(for: .milliseconds(50))
}
model.shutdown()
let outcome = await promptTask.value
#expect(outcome == .failed)
}
}
// MARK: - Model tests
@MainActor
@Test func `model handshake renders version and streams fix card`() async {
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 {
Issue.record("expected ready, got \(model.phase)")
return
}
#expect(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"
}
return false
}
#expect(hasCard)
let hasText = model.rows.contains { row in
if case let .text(text) = row.content {
return text.contains("Hello mentor.")
}
return false
}
#expect(hasText)
}
@MainActor
@Test func `model surfaces advisory version drift note`() async {
let fake = makeFakeACP(at: acpTempDir("drift"))
let model = MentorSessionModel(binaryPath: fake)
defer { model.shutdown() }
// Running 9.9.9 vs recorded 0.20.6 → the advisory note fires, never blocks.
model.recordedVersionProvider = { "0.20.6" }
await model.openSession()
guard case .ready = model.phase else {
Issue.record("expected ready despite drift, got \(model.phase)")
return
}
#expect(model.versionNote?.contains("9.9.9") == true)
#expect(model.versionNote?.contains("0.20.6") == true)
}
@MainActor
@Test func `build metadata does not fabricate version drift`() async {
let fake = makeFakeACP(at: acpTempDir("metadata-drift"))
let model = MentorSessionModel(binaryPath: fake)
defer { model.shutdown() }
// The gate records the derived version; the handshake answers the base —
// same engine, strings differ only in +build metadata → no note.
model.recordedVersionProvider = { "9.9.9+2177.g735e426" }
await model.openSession()
guard case .ready = model.phase else {
Issue.record("expected ready, got \(model.phase)")
return
}
#expect(model.versionNote == nil)
}
@MainActor
@Test func `real base-version drift still fires the note`() {
#expect(MentorSessionModel.baseVersion(of: "0.21.5+2177.g735e426") == "0.21.5")
#expect(MentorSessionModel.baseVersion(of: "0.21.5") == "0.21.5")
#expect(MentorSessionModel.baseVersion(of: "unknown") == "unknown")
#expect(MentorSessionModel.baseVersion(of: "0.20.6") != MentorSessionModel.baseVersion(of: "0.21.5"))
}
@MainActor
@Test func `session new against strict mcpServers schema reaches ready`() async {
let fake = makeStrictFakeACP(at: acpTempDir("strict"))
let model = MentorSessionModel(binaryPath: fake)
defer { model.shutdown() }
await model.openSession()
guard case let .ready(sessionId) = model.phase else {
Issue.record("expected ready against strict engine, got \(model.phase); stderr: \(model.stderrTail)")
return
}
#expect(sessionId == "sess-1")
}
@MainActor
@Test func `model crash surfaces restart prompt and fresh engine recovers`() async throws {
let dir = acpTempDir("restart")
let crashing = makeFakeACP(at: dir, name: "hermes-acp-crash", mode: "crashAfterHandshake")
let model = MentorSessionModel(binaryPath: crashing)
defer { model.shutdown() }
await model.openSession()
for _ in 0 ..< 100 {
if case .crashed = model.phase {
break
}
try await Task.sleep(for: .milliseconds(50))
}
guard case .crashed = model.phase else {
Issue.record("expected crashed after engine exit, got \(model.phase)")
return
}
// A fresh model against a healthy fake at a different path stands in for
// restart recovery (the pane's Restart button drives model.restart()).
let healthy = makeFakeACP(at: dir, name: "hermes-acp-ok")
let model2 = MentorSessionModel(binaryPath: healthy)
defer { model2.shutdown() }
await model2.openSession()
guard case .ready = model2.phase else {
Issue.record("expected ready on healthy engine, got \(model2.phase)")
return
}
}