Where agent teams gather. Cross-platform team chat where AI agents are first-class teammates — with cloud or bring-your-own (Claude Code / Codex) brains.
TypeScript
fix(computer): keep the resumable session when an engine dies mid-turn (#9)
Xialie Zhuangc36d5cccf8ef
diff --git a/server/src/__tests__/agents-computer-session-reset.test.ts b/server/src/__tests__/agents-computer-session-reset.test.tsnew file mode 100644index 0000000..08739fd--- /dev/null+++ b/server/src/__tests__/agents-computer-session-reset.test.ts@@ -0,0 +1,111 @@+/**+ * The BYOA daemon drops an agent's engine session id when — and only when —+ * carrying it forward would keep failing. Getting that verdict wrong is+ * expensive in one direction: a needless reset throws away the `--resume`+ * target that exists to recover the context an interrupted long task was+ * building (see SESSIONS_DIR in daemon.ts).+ *+ * These pin the "stale resume target" half of that verdict against the shape+ * the daemon actually sees: `failurePreview` (engine.ts) embeds the tail of the+ * engine's STDOUT in the error text, and on the Claude path that stdout is+ * stream-json whose every event line carries a `session_id` field.+ *+ * Run: node --import tsx --test server/src/__tests__/agents-computer-session-reset.test.ts+ */+import { test } from 'node:test'+import assert from 'node:assert/strict'+import { engineDiagnosticProse, isStaleResumeError } from '../agents/computer/daemon.js'++/** A mid-turn death exactly as ClaudeSession.die() reports it: the process is+ * gone (OOM / laptop sleep / provider hangup) and the last stream-json lines of+ * the turn ride along as the failure preview. The session on the engine side is+ * intact and resumable — this must NOT be read as a stale resume target. */+const MID_TURN_DEATH = [+ 'local claude failed (exit 137): process exited with code 137',+ '{"type":"system","subtype":"init","session_id":"6f1c2e30-2b77-4a3f-9d51-4c0a1b2e3f44","tools":["Bash"]}',+ '{"type":"assistant","session_id":"6f1c2e30-2b77-4a3f-9d51-4c0a1b2e3f44","message":{"model":"claude-sonnet-4-6","usage":{"input_tokens":812,"output_tokens":64},"content":[{"type":"text","text":"Reading the inbox now."}]}}',+ '{"type":"user","session_id":"6f1c2e30-2b77-4a3f-9d51-4c0a1b2e3f44","message":{"role":"user","content":[{"type":"tool_result","content":"cumora messages conversationId=convo-42 --tail 30"}]}}',+].join('\n')++test('a mid-turn engine death is NOT a stale resume target (session id must survive)', () => {+ // The regression: every stream-json line carries `session_id`, and the agent's+ // own shim commands mention `conversationId` — so a noun-only match reported a+ // dead resume target on every crash and discarded the recoverable session.+ assert.equal(isStaleResumeError(MID_TURN_DEATH), false)+})++test('a mid-turn death whose transcript quotes resume wording still is NOT stale', () => {+ // The agent was writing *about* sessions when the process died. Its transcript+ // is not an engine diagnosis.+ const err = MID_TURN_DEATH ++ '\n{"type":"assistant","session_id":"6f1c2e30","message":{"model":"claude-sonnet-4-6","content":[{"type":"text","text":"No conversation found with session ID — that is the error we should handle."}]}}'+ assert.equal(isStaleResumeError(err), false)+})++test("a successful turn's own answer is never read as an engine diagnosis", () => {+ // `result` is prose only when is_error is true; on a clean turn it is the+ // agent's answer, which may legitimately discuss missing sessions.+ const err = 'local claude failed (exit 1): process exited with code 1\n' ++ '{"type":"result","is_error":false,"session_id":"6f1c2e30","result":"I could not resume the old session, so I started over."}'+ assert.equal(isStaleResumeError(err), false)+})++// ── genuinely stale resume targets still reset ───────────────────────────────++test('Claude: "No conversation found with session ID" IS a stale resume target', () => {+ const err = 'local claude failed (exit 1): process exited with code 1\n' ++ 'No conversation found with session ID: 6f1c2e30-2b77-4a3f-9d51-4c0a1b2e3f44'+ assert.equal(isStaleResumeError(err), true)+})++test('a stale resume target reported inside a FAILED result event still resets', () => {+ // Same verdict whether the engine puts it on stderr or in an error event.+ const err = 'local claude failed (exit 1): process exited with code 1\n' ++ '{"type":"result","subtype":"error","is_error":true,"session_id":"6f1c2e30","result":"No conversation found with session ID: 6f1c2e30"}'+ assert.equal(isStaleResumeError(err), true)+})++test('codex: a thread/resume rejection IS a stale resume target', () => {+ const err = 'local codex failed (exit 1): thread/resume failed (thread not found)'+ assert.equal(isStaleResumeError(err), true)+})++test('other stale-target phrasings are recognized', () => {+ for (const phrase of [+ 'Error: session not found',+ 'Error: invalid session id',+ 'Error: unknown conversation',+ 'Error: could not resume this conversation',+ 'Error: unable to resume — thread has expired',+ 'Error: no such session',+ ]) {+ assert.equal(isStaleResumeError(`local claude failed (exit 1): ${phrase}`), true, phrase)+ }+})++test('an ordinary crash with no session wording is not a stale resume target', () => {+ assert.equal(isStaleResumeError('local claude failed (exit 143): process terminated by SIGTERM'), false)+})++// ── engineDiagnosticProse ────────────────────────────────────────────────────++test('engineDiagnosticProse drops event structure but keeps plain lines', () => {+ const prose = engineDiagnosticProse(MID_TURN_DEATH)+ assert.match(prose, /process exited with code 137/)+ assert.doesNotMatch(prose, /session_id/)+ assert.doesNotMatch(prose, /conversationId/)+})++test('engineDiagnosticProse keeps an error event\'s message', () => {+ const prose = engineDiagnosticProse('{"type":"error","session_id":"abc","error":{"message":"session not found"}}')+ assert.match(prose, /session not found/)+ assert.doesNotMatch(prose, /session_id/)+})++test('engineDiagnosticProse tolerates a truncated JSON line', () => {+ // failurePreview slices at 4000 chars and conciseError at 900 — the last line+ // is routinely cut mid-object.+ const prose = engineDiagnosticProse('process exited with code 1\n{"type":"assistant","session_id":"abc","mess')+ assert.match(prose, /process exited with code 1/)+ assert.doesNotMatch(prose, /session_id/)+})diff --git a/server/src/agents/computer/daemon.ts b/server/src/agents/computer/daemon.tsindex 8c45b52..a30619a 100644--- a/server/src/agents/computer/daemon.ts+++ b/server/src/agents/computer/daemon.ts@@ -432,6 +432,60 @@ const CONTEXT_OVERFLOW_RE = /context window|context length|context_length_exceed// also scrub outgoing text (engine.ts stripLoneSurrogates) so we stop creating it.const POISONED_BODY_RE = /no (?:low|high) surrogate|unpaired surrogate|lone surrogate|surrogate in string|request body is not valid json/i+// A STALE resume target: we passed `--resume <id>` and the engine says it has no+// such session. Dropping the id is the right recovery — the next wake starts a+// fresh session instead of re-failing against a target that no longer exists.+//+// Every branch pairs the noun with FAILURE wording. A bare mention of a session+// or conversation proves nothing: the engine's own event stream is full of them+// (see `engineDiagnosticProse`), so matching the noun alone turned every+// mid-turn engine death into a "stale resume target" and threw away the session+// id that exists to recover the interrupted turn.+const STALE_RESUME_RE = new RegExp([+ // "No conversation found with session ID: …", "no such session"+ String.raw`\bno (?:such )?(?:\w+ )?(?:conversation|session|thread)\b`,+ // "Session not found", "conversation no longer exists", "thread has expired"+ String.raw`\b(?:conversation|session|thread)(?: id)?\b[^\n]{0,24}?\b(?:not found|no longer exists?|does not exist|doesn't exist|has expired|is expired|is invalid|is unknown)\b`,+ // "Invalid session id", "unknown conversation", "expired thread"+ String.raw`\b(?:invalid|unknown|expired|stale|malformed) (?:\w+ )?(?:conversation|session|thread)\b`,+ // "could not resume", "unable to resume this conversation", "failed to resume"+ String.raw`\b(?:could ?n(?:o|')?t|cannot|can't|unable to|failed to)\b[^\n]{0,24}?\bresume\b`,+ // codex app-server's own wording+ String.raw`\bthread/resume failed\b`,+].join('|'), 'i')++/** The human-readable part of an engine failure blob.+ *+ * `failurePreview` (engine.ts) appends the tail of the engine's STDOUT to the+ * error text, and on the Claude path that stdout is stream-json: EVERY event+ * line carries a `"session_id"` field. Those lines are machine structure, not+ * diagnosis, so pattern-matching them as prose is what produced the false+ * "stale resume target" verdict on any mid-turn death. Keep an event line's+ * error text (that IS diagnosis) and drop everything else about it. */+export function engineDiagnosticProse(err: string): string {+ const out: string[] = []+ for (const line of err.split('\n')) {+ const trimmed = line.trim()+ if (!trimmed.startsWith('{')) { out.push(line); continue }+ let ev: { is_error?: unknown; result?: unknown; error?: unknown }+ try { ev = JSON.parse(trimmed) } catch { continue }+ // `result` is prose only on a FAILED turn; on a successful one it's the+ // agent's own answer, which must never be read as an engine diagnosis.+ if (ev.is_error === true && typeof ev.result === 'string') out.push(ev.result)+ if (typeof ev.error === 'string') out.push(ev.error)+ else if (ev.error && typeof ev.error === 'object') {+ const m = (ev.error as { message?: unknown }).message+ if (typeof m === 'string') out.push(m)+ }+ }+ return out.join('\n')+}++/** True when an engine error really says the `--resume` target is gone. */+export function isStaleResumeError(err: string): boolean {+ return STALE_RESUME_RE.test(engineDiagnosticProse(err))+}+function authFailureHint(engine: EngineId, detail: string): string {if (CONTEXT_OVERFLOW_RE.test(detail)) {return 'The agent filled up its context window. Its session has been reset automatically — just wake the agent again and it will start fresh.'@@ -845,11 +899,14 @@ class AgentRunner {* we drop it. This is hadResume-independent: even a single resumed session* that's now too big must be abandoned.* 2. STALE / MISSING resume target — we tried to --resume a session the- * engine no longer has. Only meaningful when we actually passed one. */+ * engine no longer has. Only meaningful when we actually passed one, and+ * only when the engine SAYS SO: a mid-turn crash (OOM, sleep, provider+ * hangup) leaves a resumable session, so it must NOT reset — that would+ * discard the context the interrupted turn was building. */private mustResetSession(err: string, hadResume: boolean): boolean {if (this.isContextOverflow(err)) return trueif (this.isPoisonedTranscript(err)) return true- if (hadResume && /resume|session|conversation/i.test(err)) return true+ if (hadResume && isStaleResumeError(err)) return truereturn false}