@devries-cameron20 / t3code-1 / commits / e68d4f053b
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

fix(opencode): show background replies after a turn settles (#36887)

Co-authored-by: Grok 4.7 <noreply@x.ai> Co-authored-by: Julius Marminge <julius0216@outlook.com>

Wout Stiens committed Nov 14, 2026 at 22:19 UTC e68d4f053bb0e76962e9cb323b596dbfd59c2f42
8 files changed +2261 -208
apps/server/src/orchestration-v2/testkit/fixtures/index.ts
+18
@@ -100,6 +100,7 @@ import { assertOpenCodeChildApprovalOutput } from "./opencode_child_approval/out
100 import { openCodeRunningChildApprovalInput } from "./opencode_running_child_approval/input.ts";
101 import { assertOpenCodeRunningChildApprovalOutput } from "./opencode_running_child_approval/output.ts";
102 import { openCodeSubagentInput } from "./opencode_subagent/input.ts";
103 +import { openCodeBackgroundWakeInput } from "./opencode_background_wake/input.ts";
104 import { openCode2InboxInput } from "./opencode2_inbox/input.ts";
105 import { openCode2RevertInput } from "./opencode2_revert/input.ts";
106 import { assertOpenCode2RevertOutput } from "./opencode2_revert/output.ts";
@@ -131,6 +132,7 @@ import { assertCodexModelRerouteOutput } from "./codex_model_reroute/output.ts";
132 import { openCode2ToolCallInput } from "./opencode2_tool_call/input.ts";
133 import { assertOpenCode2ToolCallOutput } from "./opencode2_tool_call/output.ts";
134 import { assertOpenCodeSubagentOutput } from "./opencode_subagent/output.ts";
135 +import { assertOpenCodeBackgroundWakeOutput } from "./opencode_background_wake/output.ts";
136 import {
137 assertCodexPlanQuestionsOutput,
138 assertPlanQuestionsOutput,
@@ -1173,6 +1175,22 @@ export const ORCHESTRATOR_REPLAY_FIXTURES: ReadonlyArray<OrchestratorReplayFixtu
1175 },
1176 ],
1177 },
1178 + {
1179 + name: "opencode_background_wake",
1180 + buildInput: openCodeBackgroundWakeInput,
1181 + providers: [
1182 + {
1183 + driver: ProviderDriverKind.make("opencode"),
1184 + transcriptFile: new URL(
1185 + "./opencode_background_wake/opencode_transcript.ndjson",
1186 + import.meta.url,
1187 + ),
1188 + modelSelection: OPENCODE_MODEL_SELECTION,
1189 + runContinuationWorker: true,
1190 + assertOutput: assertOpenCodeBackgroundWakeOutput,
1191 + },
1192 + ],
1193 + },
1194 {
1195 name: "opencode2_simple",
1196 buildInput: openCode2SimpleInput,
apps/server/src/orchestration-v2/testkit/fixtures/opencode_background_wake/input.ts new
+10
@@ -0,0 +1,10 @@
1 +import { OPENCODE_BACKGROUND_WAKE_PROMPT, type OrchestratorFixtureInput } from "../shared.ts";
2 +
3 +export function openCodeBackgroundWakeInput(): OrchestratorFixtureInput {
4 + return {
5 + steps: [
6 + { type: "message", text: OPENCODE_BACKGROUND_WAKE_PROMPT },
7 + { type: "await_run_status", targetRunIndex: 2, status: "completed" },
8 + ],
9 + };
10 +}
apps/server/src/orchestration-v2/testkit/fixtures/opencode_background_wake/opencode_transcript.ndjson new
+44
@@ -0,0 +1,44 @@
1 +{"type":"transcript_start","provider":"opencode","protocol":"opencode-sdk.sse","version":"1.19.5","scenario":"opencode_background_wake","metadata":{"source":"source-derived from anomalyco/opencode v1.19.5 (810c0eba1a7348036f8bdf61e6632d0c36c6876c), not a native capture","producer":"tool/task.ts injects the background result as a synthetic root prompt; session/prompt.ts saves it, then status.set busy; session/status.ts publishes idle then session.idle","requires":"OPENCODE_EXPERIMENTAL_BACKGROUND_SUBAGENTS or OPENCODE_EXPERIMENTAL in the OpenCode server environment; T3 sets neither","nativeSessionId":"ses_1a0b5c3d4e5ffBgWakeRoot0001","nativeChildSessionId":"ses_1a0b5c3d4e5ffBgWakeChild001","model":"openai/gpt-5.4-mini"}}
2 +{"type":"expect_outbound","label":"event.subscribe","frame":{"type":"event.subscribe"}}
3 +{"type":"expect_outbound","label":"session.create","frame":{"type":"session.create","input":{"title":"<any>","permission":"<any>"}}}
4 +{"type":"emit_inbound","label":"session.created","frame":{"type":"sdk.response","operation":"session.create","data":{"id":"ses_1a0b5c3d4e5ffBgWakeRoot0001","slug":"wake-fixture","version":"1.19.5","projectID":"global","directory":"/tmp/t3-opencode-wake","path":"tmp/t3-opencode-wake","title":"T3 OpenCode background wake","time":{"created":1794000000000,"updated":1794000000000}}}}
5 +{"type":"expect_outbound","label":"session.promptAsync","frame":{"type":"session.promptAsync","input":{"sessionID":"ses_1a0b5c3d4e5ffBgWakeRoot0001","model":{"providerID":"openai","modelID":"gpt-5.4-mini"},"agent":"build","parts":[{"type":"text","text":"Use the task tool once with background set to true to delegate to the general subagent with the prompt: Respond exactly CHILD_OK. As soon as it is launched, reply exactly PARENT_OK and end your turn without waiting for it."}],"messageID":"msg_1a0b5c3d4e5fRootPrompt0001"}}}
6 +{"type":"emit_inbound","label":"session.promptAsync.response","frame":{"type":"sdk.response","operation":"session.promptAsync","data":null}}
7 +{"type":"emit_inbound","label":"root.user","frame":{"type":"sdk.event","event":{"id":"evt_1a0b5c3d4e5f0001WakeFixture","type":"message.updated","properties":{"sessionID":"ses_1a0b5c3d4e5ffBgWakeRoot0001","info":{"id":"msg_1a0b5c3d4e5fRootPrompt0001","role":"user","sessionID":"ses_1a0b5c3d4e5ffBgWakeRoot0001","time":{"created":1794000000001},"agent":"build","model":{"providerID":"openai","modelID":"gpt-5.4-mini"}}}}}}
8 +{"type":"emit_inbound","label":"root.user.text","frame":{"type":"sdk.event","event":{"id":"evt_1a0b5c3d4e5f0002WakeFixture","type":"message.part.updated","properties":{"sessionID":"ses_1a0b5c3d4e5ffBgWakeRoot0001","part":{"id":"prt_1a0b5c3d4e5fRootPromptTxt1","messageID":"msg_1a0b5c3d4e5fRootPrompt0001","sessionID":"ses_1a0b5c3d4e5ffBgWakeRoot0001","type":"text","text":"Use the task tool once with background set to true to delegate to the general subagent with the prompt: Respond exactly CHILD_OK. As soon as it is launched, reply exactly PARENT_OK and end your turn without waiting for it."},"time":1794000000001}}}}
9 +{"type":"emit_inbound","label":"root.busy","frame":{"type":"sdk.event","event":{"id":"evt_1a0b5c3d4e5f0003WakeFixture","type":"session.status","properties":{"sessionID":"ses_1a0b5c3d4e5ffBgWakeRoot0001","status":{"type":"busy"}}}}}
10 +{"type":"emit_inbound","label":"root.assistant.tool-step","frame":{"type":"sdk.event","event":{"id":"evt_1a0b5c3d4e5f0004WakeFixture","type":"message.updated","properties":{"sessionID":"ses_1a0b5c3d4e5ffBgWakeRoot0001","info":{"id":"msg_1a0b5c3d4e5fRootToolStep001","parentID":"msg_1a0b5c3d4e5fRootPrompt0001","role":"assistant","mode":"build","agent":"build","path":{"cwd":"/tmp/t3-opencode-wake","root":"/"},"cost":0,"tokens":{"input":0,"output":0,"reasoning":0,"cache":{"read":0,"write":0}},"modelID":"gpt-5.4-mini","providerID":"openai","time":{"created":1794000000002},"sessionID":"ses_1a0b5c3d4e5ffBgWakeRoot0001"}}}}}
11 +{"type":"emit_inbound","label":"child.created","frame":{"type":"sdk.event","event":{"id":"evt_1a0b5c3d4e5f0005WakeFixture","type":"session.created","properties":{"sessionID":"ses_1a0b5c3d4e5ffBgWakeChild001","info":{"id":"ses_1a0b5c3d4e5ffBgWakeChild001","slug":"wake-fixture","version":"1.19.5","projectID":"global","directory":"/tmp/t3-opencode-wake","path":"tmp/t3-opencode-wake","title":"Return CHILD_OK (@general subagent)","time":{"created":1794000000000,"updated":1794000000000},"parentID":"ses_1a0b5c3d4e5ffBgWakeRoot0001"}}}}}
12 +{"type":"emit_inbound","label":"task.running","frame":{"type":"sdk.event","event":{"id":"evt_1a0b5c3d4e5f0006WakeFixture","type":"message.part.updated","properties":{"sessionID":"ses_1a0b5c3d4e5ffBgWakeRoot0001","part":{"id":"prt_1a0b5c3d4e5fTaskPart00001","messageID":"msg_1a0b5c3d4e5fRootToolStep001","sessionID":"ses_1a0b5c3d4e5ffBgWakeRoot0001","type":"tool","tool":"task","callID":"call_wake_fixture_task","state":{"status":"running","input":{"description":"Return CHILD_OK","prompt":"Respond exactly CHILD_OK.","subagent_type":"general","background":true},"title":"Return CHILD_OK","metadata":{"sessionId":"ses_1a0b5c3d4e5ffBgWakeChild001","model":{"providerID":"openai","modelID":"gpt-5.4-mini"},"background":true,"jobId":"ses_1a0b5c3d4e5ffBgWakeChild001"},"time":{"start":1794000000003}}},"time":1794000000003}}}}
13 +{"type":"expect_outbound","label":"session.get.child-policy","frame":{"type":"session.get","input":{"sessionID":"ses_1a0b5c3d4e5ffBgWakeChild001"}}}
14 +{"type":"emit_inbound","label":"session.get.child-policy.response","frame":{"type":"sdk.response","operation":"session.get","data":{"id":"ses_1a0b5c3d4e5ffBgWakeChild001","slug":"wake-fixture","version":"1.19.5","projectID":"global","directory":"/tmp/t3-opencode-wake","path":"tmp/t3-opencode-wake","title":"Return CHILD_OK (@general subagent)","time":{"created":1794000000000,"updated":1794000000000},"parentID":"ses_1a0b5c3d4e5ffBgWakeRoot0001"}}}
15 +{"type":"expect_outbound","label":"session.update.child-policy","frame":{"type":"session.update","input":{"sessionID":"ses_1a0b5c3d4e5ffBgWakeChild001","permission":"<any>"}}}
16 +{"type":"emit_inbound","label":"session.update.child-policy.response","frame":{"type":"sdk.response","operation":"session.update","data":{"id":"ses_1a0b5c3d4e5ffBgWakeChild001","permission":[{"permission":"*","pattern":"*","action":"allow"},{"permission":"task","pattern":"*","action":"deny"}]}}}
17 +{"type":"emit_inbound","label":"child.user","frame":{"type":"sdk.event","event":{"id":"evt_1a0b5c3d4e5f0007WakeFixture","type":"message.updated","properties":{"sessionID":"ses_1a0b5c3d4e5ffBgWakeChild001","info":{"id":"msg_1a0b5c3d4e5fChildPrompt001","role":"user","sessionID":"ses_1a0b5c3d4e5ffBgWakeChild001","time":{"created":1794000000004},"agent":"general","model":{"providerID":"openai","modelID":"gpt-5.4-mini"}}}}}}
18 +{"type":"emit_inbound","label":"child.user.text","frame":{"type":"sdk.event","event":{"id":"evt_1a0b5c3d4e5f0008WakeFixture","type":"message.part.updated","properties":{"sessionID":"ses_1a0b5c3d4e5ffBgWakeChild001","part":{"id":"prt_1a0b5c3d4e5fChildPromptTx1","messageID":"msg_1a0b5c3d4e5fChildPrompt001","sessionID":"ses_1a0b5c3d4e5ffBgWakeChild001","type":"text","text":"Respond exactly CHILD_OK."},"time":1794000000004}}}}
19 +{"type":"emit_inbound","label":"task.completed","frame":{"type":"sdk.event","event":{"id":"evt_1a0b5c3d4e5f0009WakeFixture","type":"message.part.updated","properties":{"sessionID":"ses_1a0b5c3d4e5ffBgWakeRoot0001","part":{"id":"prt_1a0b5c3d4e5fTaskPart00001","messageID":"msg_1a0b5c3d4e5fRootToolStep001","sessionID":"ses_1a0b5c3d4e5ffBgWakeRoot0001","type":"tool","tool":"task","callID":"call_wake_fixture_task","state":{"status":"completed","input":{"description":"Return CHILD_OK","prompt":"Respond exactly CHILD_OK.","subagent_type":"general","background":true},"title":"Return CHILD_OK","metadata":{"sessionId":"ses_1a0b5c3d4e5ffBgWakeChild001","model":{"providerID":"openai","modelID":"gpt-5.4-mini"},"background":true,"jobId":"ses_1a0b5c3d4e5ffBgWakeChild001"},"time":{"start":1794000000004,"end":1794000000005},"output":"<task id=\"ses_1a0b5c3d4e5ffBgWakeChild001\" state=\"running\">\n<summary>Background task started</summary>\n<task_result>\nBackground task started\n</task_result>\n</task>"}},"time":1794000000004}}}}
20 +{"type":"emit_inbound","label":"child.busy","frame":{"type":"sdk.event","event":{"id":"evt_1a0b5c3d4e5f0010WakeFixture","type":"session.status","properties":{"sessionID":"ses_1a0b5c3d4e5ffBgWakeChild001","status":{"type":"busy"}}}}}
21 +{"type":"emit_inbound","label":"root.assistant.tool-step.completed","frame":{"type":"sdk.event","event":{"id":"evt_1a0b5c3d4e5f0011WakeFixture","type":"message.updated","properties":{"sessionID":"ses_1a0b5c3d4e5ffBgWakeRoot0001","info":{"id":"msg_1a0b5c3d4e5fRootToolStep001","parentID":"msg_1a0b5c3d4e5fRootPrompt0001","role":"assistant","mode":"build","agent":"build","path":{"cwd":"/tmp/t3-opencode-wake","root":"/"},"cost":0,"tokens":{"input":0,"output":0,"reasoning":0,"cache":{"read":0,"write":0}},"modelID":"gpt-5.4-mini","providerID":"openai","time":{"created":1794000000002,"completed":1794000000005},"sessionID":"ses_1a0b5c3d4e5ffBgWakeRoot0001","finish":"tool-calls"}}}}}
22 +{"type":"emit_inbound","label":"root.assistant.final-step","frame":{"type":"sdk.event","event":{"id":"evt_1a0b5c3d4e5f0012WakeFixture","type":"message.updated","properties":{"sessionID":"ses_1a0b5c3d4e5ffBgWakeRoot0001","info":{"id":"msg_1a0b5c3d4e5fRootFinal00001","parentID":"msg_1a0b5c3d4e5fRootPrompt0001","role":"assistant","mode":"build","agent":"build","path":{"cwd":"/tmp/t3-opencode-wake","root":"/"},"cost":0,"tokens":{"input":0,"output":0,"reasoning":0,"cache":{"read":0,"write":0}},"modelID":"gpt-5.4-mini","providerID":"openai","time":{"created":1794000000005},"sessionID":"ses_1a0b5c3d4e5ffBgWakeRoot0001"}}}}}
23 +{"type":"emit_inbound","label":"root.assistant.text","frame":{"type":"sdk.event","event":{"id":"evt_1a0b5c3d4e5f0013WakeFixture","type":"message.part.updated","properties":{"sessionID":"ses_1a0b5c3d4e5ffBgWakeRoot0001","part":{"id":"prt_1a0b5c3d4e5fRootFinalText1","messageID":"msg_1a0b5c3d4e5fRootFinal00001","sessionID":"ses_1a0b5c3d4e5ffBgWakeRoot0001","type":"text","text":"PARENT_OK","time":{"start":1794000000006,"end":1794000000007}},"time":1794000000006}}}}
24 +{"type":"emit_inbound","label":"root.assistant.completed","frame":{"type":"sdk.event","event":{"id":"evt_1a0b5c3d4e5f0014WakeFixture","type":"message.updated","properties":{"sessionID":"ses_1a0b5c3d4e5ffBgWakeRoot0001","info":{"id":"msg_1a0b5c3d4e5fRootFinal00001","parentID":"msg_1a0b5c3d4e5fRootPrompt0001","role":"assistant","mode":"build","agent":"build","path":{"cwd":"/tmp/t3-opencode-wake","root":"/"},"cost":0,"tokens":{"input":0,"output":0,"reasoning":0,"cache":{"read":0,"write":0}},"modelID":"gpt-5.4-mini","providerID":"openai","time":{"created":1794000000005,"completed":1794000000007},"sessionID":"ses_1a0b5c3d4e5ffBgWakeRoot0001","finish":"stop"}}}}}
25 +{"type":"emit_inbound","label":"root.idle","frame":{"type":"sdk.event","event":{"id":"evt_1a0b5c3d4e5f0015WakeFixture","type":"session.status","properties":{"sessionID":"ses_1a0b5c3d4e5ffBgWakeRoot0001","status":{"type":"idle"}}}}}
26 +{"type":"emit_inbound","label":"root.session.idle","frame":{"type":"sdk.event","event":{"id":"evt_1a0b5c3d4e5f0016WakeFixture","type":"session.idle","properties":{"sessionID":"ses_1a0b5c3d4e5ffBgWakeRoot0001"}}}}
27 +{"type":"emit_inbound","label":"child.assistant","frame":{"type":"sdk.event","event":{"id":"evt_1a0b5c3d4e5f0017WakeFixture","type":"message.updated","properties":{"sessionID":"ses_1a0b5c3d4e5ffBgWakeChild001","info":{"id":"msg_1a0b5c3d4e5fChildAnswer001","parentID":"msg_1a0b5c3d4e5fChildPrompt001","role":"assistant","mode":"general","agent":"general","path":{"cwd":"/tmp/t3-opencode-wake","root":"/"},"cost":0,"tokens":{"input":0,"output":0,"reasoning":0,"cache":{"read":0,"write":0}},"modelID":"gpt-5.4-mini","providerID":"openai","time":{"created":1794000000008},"sessionID":"ses_1a0b5c3d4e5ffBgWakeChild001"}}}}}
28 +{"type":"emit_inbound","label":"child.assistant.text","frame":{"type":"sdk.event","event":{"id":"evt_1a0b5c3d4e5f0018WakeFixture","type":"message.part.updated","properties":{"sessionID":"ses_1a0b5c3d4e5ffBgWakeChild001","part":{"id":"prt_1a0b5c3d4e5fChildAnswerTx1","messageID":"msg_1a0b5c3d4e5fChildAnswer001","sessionID":"ses_1a0b5c3d4e5ffBgWakeChild001","type":"text","text":"CHILD_OK","time":{"start":1794000000009,"end":1794000000010}},"time":1794000000009}}}}
29 +{"type":"emit_inbound","label":"child.assistant.completed","frame":{"type":"sdk.event","event":{"id":"evt_1a0b5c3d4e5f0019WakeFixture","type":"message.updated","properties":{"sessionID":"ses_1a0b5c3d4e5ffBgWakeChild001","info":{"id":"msg_1a0b5c3d4e5fChildAnswer001","parentID":"msg_1a0b5c3d4e5fChildPrompt001","role":"assistant","mode":"general","agent":"general","path":{"cwd":"/tmp/t3-opencode-wake","root":"/"},"cost":0,"tokens":{"input":0,"output":0,"reasoning":0,"cache":{"read":0,"write":0}},"modelID":"gpt-5.4-mini","providerID":"openai","time":{"created":1794000000008,"completed":1794000000010},"sessionID":"ses_1a0b5c3d4e5ffBgWakeChild001","finish":"stop"}}}}}
30 +{"type":"emit_inbound","label":"child.idle","frame":{"type":"sdk.event","event":{"id":"evt_1a0b5c3d4e5f0020WakeFixture","type":"session.status","properties":{"sessionID":"ses_1a0b5c3d4e5ffBgWakeChild001","status":{"type":"idle"}}}}}
31 +{"type":"emit_inbound","label":"child.session.idle","frame":{"type":"sdk.event","event":{"id":"evt_1a0b5c3d4e5f0021WakeFixture","type":"session.idle","properties":{"sessionID":"ses_1a0b5c3d4e5ffBgWakeChild001"}}}}
32 +{"type":"emit_inbound","label":"wake.user","frame":{"type":"sdk.event","event":{"id":"evt_1a0b5c3d4e5f0022WakeFixture","type":"message.updated","properties":{"sessionID":"ses_1a0b5c3d4e5ffBgWakeRoot0001","info":{"id":"msg_1a0b5c3d4e5fWakeResult0001","role":"user","sessionID":"ses_1a0b5c3d4e5ffBgWakeRoot0001","time":{"created":1794000000011},"agent":"build","model":{"providerID":"openai","modelID":"gpt-5.4-mini"}}}}}}
33 +{"type":"emit_inbound","label":"wake.user.result","frame":{"type":"sdk.event","event":{"id":"evt_1a0b5c3d4e5f0023WakeFixture","type":"message.part.updated","properties":{"sessionID":"ses_1a0b5c3d4e5ffBgWakeRoot0001","part":{"id":"prt_1a0b5c3d4e5fWakeResultTxt1","messageID":"msg_1a0b5c3d4e5fWakeResult0001","sessionID":"ses_1a0b5c3d4e5ffBgWakeRoot0001","type":"text","text":"<task id=\"ses_1a0b5c3d4e5ffBgWakeChild001\" state=\"completed\">\n<summary>Background task completed: Return CHILD_OK</summary>\n<task_result>\nCHILD_OK\n</task_result>\n</task>","synthetic":true},"time":1794000000011}}}}
34 +{"type":"emit_inbound","label":"wake.busy","frame":{"type":"sdk.event","event":{"id":"evt_1a0b5c3d4e5f0024WakeFixture","type":"session.status","properties":{"sessionID":"ses_1a0b5c3d4e5ffBgWakeRoot0001","status":{"type":"busy"}}}}}
35 +{"type":"emit_inbound","label":"wake.assistant","frame":{"type":"sdk.event","event":{"id":"evt_1a0b5c3d4e5f0025WakeFixture","type":"message.updated","properties":{"sessionID":"ses_1a0b5c3d4e5ffBgWakeRoot0001","info":{"id":"msg_1a0b5c3d4e5fWakeAnswer0001","parentID":"msg_1a0b5c3d4e5fWakeResult0001","role":"assistant","mode":"build","agent":"build","path":{"cwd":"/tmp/t3-opencode-wake","root":"/"},"cost":0,"tokens":{"input":0,"output":0,"reasoning":0,"cache":{"read":0,"write":0}},"modelID":"gpt-5.4-mini","providerID":"openai","time":{"created":1794000000012},"sessionID":"ses_1a0b5c3d4e5ffBgWakeRoot0001"}}}}}
36 +{"type":"emit_inbound","label":"wake.assistant.text","frame":{"type":"sdk.event","event":{"id":"evt_1a0b5c3d4e5f0026WakeFixture","type":"message.part.updated","properties":{"sessionID":"ses_1a0b5c3d4e5ffBgWakeRoot0001","part":{"id":"prt_1a0b5c3d4e5fWakeAnswerTxt1","messageID":"msg_1a0b5c3d4e5fWakeAnswer0001","sessionID":"ses_1a0b5c3d4e5ffBgWakeRoot0001","type":"text","text":"The background task returned CHILD_OK.","time":{"start":1794000000013,"end":1794000000014}},"time":1794000000013}}}}
37 +{"type":"emit_inbound","label":"wake.assistant.completed","frame":{"type":"sdk.event","event":{"id":"evt_1a0b5c3d4e5f0027WakeFixture","type":"message.updated","properties":{"sessionID":"ses_1a0b5c3d4e5ffBgWakeRoot0001","info":{"id":"msg_1a0b5c3d4e5fWakeAnswer0001","parentID":"msg_1a0b5c3d4e5fWakeResult0001","role":"assistant","mode":"build","agent":"build","path":{"cwd":"/tmp/t3-opencode-wake","root":"/"},"cost":0,"tokens":{"input":0,"output":0,"reasoning":0,"cache":{"read":0,"write":0}},"modelID":"gpt-5.4-mini","providerID":"openai","time":{"created":1794000000012,"completed":1794000000014},"sessionID":"ses_1a0b5c3d4e5ffBgWakeRoot0001","finish":"stop"}}}}}
38 +{"type":"emit_inbound","label":"wake.idle","frame":{"type":"sdk.event","event":{"id":"evt_1a0b5c3d4e5f0028WakeFixture","type":"session.status","properties":{"sessionID":"ses_1a0b5c3d4e5ffBgWakeRoot0001","status":{"type":"idle"}}}}}
39 +{"type":"emit_inbound","label":"wake.session.idle","frame":{"type":"sdk.event","event":{"id":"evt_1a0b5c3d4e5f0029WakeFixture","type":"session.idle","properties":{"sessionID":"ses_1a0b5c3d4e5ffBgWakeRoot0001"}}}}
40 +{"type":"expect_outbound","label":"session.abort.cleanup","frame":{"type":"session.abort","input":{"sessionID":"ses_1a0b5c3d4e5ffBgWakeRoot0001"}}}
41 +{"type":"emit_inbound","label":"session.abort.cleanup.response","frame":{"type":"sdk.response","operation":"session.abort","data":true}}
42 +{"type":"expect_outbound","label":"session.children.cleanup","frame":{"type":"session.children","input":{"sessionID":"ses_1a0b5c3d4e5ffBgWakeRoot0001"}}}
43 +{"type":"emit_inbound","label":"session.children.cleanup.response","frame":{"type":"sdk.response","operation":"session.children","data":[]}}
44 +{"type":"runtime_exit","status":"success"}
apps/server/src/orchestration-v2/testkit/fixtures/opencode_background_wake/output.ts new
+54
@@ -0,0 +1,54 @@
1 +import { assert } from "@effect/vitest";
2 +import type { OrchestrationV2ThreadProjection, ProviderReplayTranscript } from "@t3tools/contracts";
3 +
4 +import type { OrchestratorV2ScenarioResult } from "../../OrchestratorScenario.ts";
5 +import {
6 + assertBaseProjection,
7 + assertSemanticProjectionIntegrity,
8 + assertUserMessagesInclude,
9 + OPENCODE_BACKGROUND_WAKE_PROMPT,
10 + projectionFor,
11 +} from "../shared.ts";
12 +
13 +const runTexts = (projection: OrchestrationV2ThreadProjection, runId: string | undefined) =>
14 + projection.turnItems.flatMap((item) =>
15 + item.runId === runId && item.type === "assistant_message" ? [item.text.trim()] : [],
16 + );
17 +
18 +export function assertOpenCodeBackgroundWakeOutput(
19 + result: OrchestratorV2ScenarioResult,
20 + transcript: ProviderReplayTranscript,
21 +) {
22 + assertBaseProjection({
23 + result,
24 + transcript,
25 + runCount: 2,
26 + runStatuses: ["completed", "completed"],
27 + });
28 + const projection = projectionFor(result, transcript.scenario);
29 + assertSemanticProjectionIntegrity(projection);
30 + assertUserMessagesInclude(projection, [OPENCODE_BACKGROUND_WAKE_PROMPT]);
31 + const [rootRun, wakeRun] = projection.runs;
32 +
33 + assert.lengthOf(projection.subagents, 1);
34 + const subagent = projection.subagents[0]!;
35 + assert.deepInclude(subagent, {
36 + origin: "provider_native",
37 + status: "completed",
38 + runId: rootRun!.id,
39 + });
40 + const child = result.projections.get(subagent.childThreadId!);
41 + assert.isTrue(
42 + child?.turnItems.some((item) => item.type === "assistant_message" && item.text === "CHILD_OK"),
43 + "the child's answer stays on the child thread",
44 + );
45 +
46 + const wakeMessage = projection.messages.find((message) => message.id === wakeRun?.userMessageId);
47 + assert.equal(`${wakeMessage?.createdBy}:${wakeMessage?.creationSource}`, "agent:provider");
48 + assert.deepEqual(runTexts(projection, rootRun?.id), ["PARENT_OK"]);
49 + assert.deepEqual(
50 + runTexts(projection, wakeRun?.id),
51 + ["The background task returned CHILD_OK."],
52 + "OpenCode's own turn lands on the run that admitted it",
53 + );
54 +}
apps/server/src/orchestration-v2/testkit/fixtures/shared.ts
+2
@@ -60,6 +60,8 @@ export const SUBAGENT_V2_NESTED_APPROVAL_PROMPT =
60 "Do not run any commands yourself. Spawn one subagent and tell it not to run any commands itself but to spawn its own subagent, whose only task is to run this exact shell command: printf 'nested approval fixture' > nested-approval.txt and then reply with exactly: Written. Each agent waits for its child and replies with exactly what the child said. Wait for your subagent, then reply with exactly what it said.";
61 export const OPENCODE_SUBAGENT_PROMPT =
62 "Use the task tool exactly once. Delegate to the general subagent with this prompt: Respond exactly CHILD_OK. After the task completes, respond exactly PARENT_OK.";
63 +export const OPENCODE_BACKGROUND_WAKE_PROMPT =
64 + "Use the task tool once with background set to true to delegate to the general subagent with the prompt: Respond exactly CHILD_OK. As soon as it is launched, reply exactly PARENT_OK and end your turn without waiting for it.";
65 export const SUBAGENT_CONTINUE_PROMPT =
66 "Spawn one subagent and have it reply exactly: initial subagent response";
67 export const SUBAGENT_CONTINUE_PARENT_PROMPT =
packages/provider-opencode/src/server/adapter.test.ts
+1295 -17
@@ -35,6 +35,7 @@ import * as Layer from "effect/Layer";
35 import * as Option from "effect/Option";
36 import * as Schema from "effect/Schema";
37 import * as Stream from "effect/Stream";
38 +import * as Scope from "effect/Scope";
39 import * as TestClock from "effect/testing/TestClock";
40
41 import * as ProviderHost from "@t3tools/provider-core/server/ProviderHost";
@@ -42,6 +43,7 @@ import * as TestProviderHost from "@t3tools/provider-testing/TestProviderHost";
43 import type * as ProviderEventLoggers from "@t3tools/provider-core/server/ProviderEventLoggers";
44 import * as OpenCodeRuntime from "./OpenCodeRuntime.ts";
45 import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
46 +import * as ProviderContinuationRequests from "@t3tools/provider-core/server/ProviderContinuationRequests";
47 import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions";
48
49 import {
@@ -156,6 +158,7 @@ const makeOpenCodeRuntimeHarness = Effect.fn("makeOpenCodeRuntimeHarness")(funct
158 host: Partial<ProviderHost.ProviderHost["Service"]> = {},
159 turnSettings: {
160 readonly model?: string;
161 + readonly exitCode?: Effect.Effect<number>;
162 readonly options?: ReadonlyArray<ProviderOptionSelection>;
163 readonly interactionMode?: ProviderAdapter.ProviderAdapterV2RuntimePolicy["interactionMode"];
164 } = {},
@@ -177,7 +180,12 @@ const makeOpenCodeRuntimeHarness = Effect.fn("makeOpenCodeRuntimeHarness")(funct
180 environment: {},
181 }).pipe(
182 Effect.provideService(OpenCodeRuntime.OpenCodeRuntime, {
180 - connectToOpenCodeServer: () => Effect.succeed({ url: "http://test.invalid", external: true }),
183 + connectToOpenCodeServer: () =>
184 + Effect.succeed({
185 + url: "http://test.invalid",
186 + external: turnSettings.exitCode === undefined,
187 + exitCode: turnSettings.exitCode ?? null,
188 + }),
189 createOpenCodeSdkClient: () => client,
190 } as unknown as OpenCodeRuntime.OpenCodeRuntime["Service"]),
191 Effect.provideService(ProviderHost.ProviderHost, {
@@ -203,6 +211,8 @@ const makeOpenCodeRuntimeHarness = Effect.fn("makeOpenCodeRuntimeHarness")(funct
211 startProviderThread: OrchestrationV2ProviderThread = providerThread,
212 turnPolicy: ProviderAdapter.ProviderAdapterV2RuntimePolicy = policy,
213 resume = false,
214 + turnKey = suffix,
215 + continuation?: { model?: string },
216 ) =>
217 runtime.startTurn({
218 appThread: {
@@ -229,21 +239,21 @@ const makeOpenCodeRuntimeHarness = Effect.fn("makeOpenCodeRuntimeHarness")(funct
239 deletedAt: null,
240 },
241 threadId,
232 - runId: RunId.make(`run-opencode-${suffix}`),
242 + runId: RunId.make(`run-opencode-${turnKey}`),
243 runOrdinal: 1,
244 providerTurnOrdinal: 1,
235 - attemptId: RunAttemptId.make(`attempt-opencode-${suffix}`),
236 - rootNodeId: NodeId.make(`node-opencode-${suffix}`),
245 + attemptId: RunAttemptId.make(`attempt-opencode-${turnKey}`),
246 + rootNodeId: NodeId.make(`node-opencode-${turnKey}`),
247 providerThread: startProviderThread,
248 ...(resume ? { resume: true as const } : {}),
249 message: {
240 - createdBy: "user",
241 - creationSource: "web",
242 - messageId: MessageId.make(`message-opencode-${suffix}`),
250 + createdBy: continuation === undefined ? "user" : "agent",
251 + creationSource: continuation === undefined ? "web" : "provider",
252 + messageId: MessageId.make(`message-opencode-${turnKey}`),
253 text,
254 attachments: [],
255 },
246 - modelSelection,
256 + modelSelection: { ...modelSelection, model: continuation?.model ?? modelSelection.model },
257 runtimePolicy: turnPolicy,
258 });
259 return {
@@ -259,6 +269,50 @@ const makeOpenCodeRuntimeHarness = Effect.fn("makeOpenCodeRuntimeHarness")(funct
269 });
270
271 describe("OpenCodeAdapterV2", () => {
272 + it.effect("cleans abandoned native descendants before registering their root thread", () =>
273 + Effect.gen(function* () {
274 + const aborted: string[] = [];
275 + const harness = yield* makeOpenCodeRuntimeHarness("abandoned-root", "ses_other", {
276 + event: { subscribe: async () => ({ stream: asyncEventStream().stream }) },
277 + session: {
278 + create: async () => ({ data: { id: "ses_other", time: { created: 1, updated: 1 } } }),
279 + children: async (input: { sessionID: string }) => ({
280 + data: input.sessionID === "ses_abandoned" ? [{ id: "ses_abandoned_child" }] : [],
281 + }),
282 + abort: async (input: { sessionID: string }) => {
283 + aborted.push(input.sessionID);
284 + return { data: true };
285 + },
286 + },
287 + });
288 + yield* harness.runtime.interruptTurn({
289 + providerThread: {
290 + ...harness.providerThread,
291 + nativeThreadRef: {
292 + driver: OPENCODE_PROVIDER,
293 + nativeId: "ses_abandoned",
294 + strength: "strong",
295 + },
296 + },
297 + providerTurnId: ProviderTurnId.make("provider-turn:abandoned"),
298 + requestRuntimeRestart: true,
299 + });
300 + assert.deepEqual(aborted, ["ses_abandoned_child"]);
301 + // The same runtime session remains usable for another registered thread.
302 + assert.isTrue(
303 + Exit.isSuccess(
304 + yield* harness.runtime
305 + .interruptTurn({
306 + providerThread: harness.providerThread,
307 + providerTurnId: ProviderTurnId.make("provider-turn:none"),
308 + requestRuntimeRestart: true,
309 + })
310 + .pipe(Effect.exit),
311 + ),
312 + );
313 + }).pipe(Effect.provide(Layer.merge(IdAllocator.layer, McpProviderSessions.layer))),
314 + );
315 +
316 it.effect.each([
317 ["empty", "prompt"],
318 ["unsupported", "command"],
@@ -1395,6 +1449,1203 @@ describe("OpenCodeAdapterV2", () => {
1449 }).pipe(Effect.provide(Layer.merge(IdAllocator.layer, McpProviderSessions.layer))),
1450 );
1451
1452 + it.effect.each([
1453 + { state: "active", end: null },
1454 + { state: "settled", end: "stop" },
1455 + { state: "settled", end: "stop-before-busy" },
1456 + { state: "settled", end: "stop-before-busy-timeout" },
1457 + { state: "settled", end: "foreground-before-status-idle" },
1458 + { state: "settled", end: "foreground-before-session-idle" },
1459 + { state: "settled", end: "foreground-before-error" },
1460 + { state: "settled", end: "stop-before-idle" },
1461 + { state: "settled", end: "stop-before-error" },
1462 + { state: "settled", end: "foreground-error" },
1463 + { state: "settled", end: "foreground-overflow" },
1464 + { state: "settled", end: "catalog-live" },
1465 + { state: "settled", end: "catalog-replay" },
1466 + { state: "settled", end: "retry-registration" },
1467 + { state: "settled", end: "held-requests" },
1468 + { state: "settled", end: "compact-takeover" },
1469 + { state: "settled", end: "no-wake-continuation" },
1470 + { state: "settled", end: "idle-during-abort-failure" },
1471 + { state: "settled", end: "overflow-during-abort-failure" },
1472 + { state: "settled", end: "foreground-before-busy" },
1473 + { state: "settled", end: "foreground-before-busy-timeout" },
1474 + { state: "settled", end: "cancelled" },
1475 + { state: "settled", end: "stop-failure" },
1476 + { state: "settled", end: "cancelled-failure" },
1477 + { state: "settled", end: "stop-busy-failure" },
1478 + { state: "settled", end: "cancelled-busy-failure" },
1479 + { state: "settled", end: "foreground" },
1480 + { state: "settled", end: "foreground-buffered" },
1481 + { state: "settled", end: "foreground-buffered-error" },
1482 + { state: "settled", end: "foreground-stop" },
1483 + { state: "settled", end: "foreground-eof" },
1484 + { state: "settled", end: "invalid-continuation" },
1485 + { state: "settled", end: "policy-failure" },
1486 + { state: "settled", end: "closed" },
1487 + { state: "settled", end: "owned-exit" },
1488 + { state: "settled", end: "failed-stream" },
1489 + { state: "settled", end: "sequential" },
1490 + { state: "settled", end: "sequential-buffered" },
1491 + { state: "settled", end: "foreground-second-busy" },
1492 + { state: "settled", end: "foreground-second-saved" },
1493 + { state: "settled", end: "foreground-reemitted" },
1494 + { state: "settled", end: "idle-only" },
1495 + { state: "settled", end: "error-only" },
1496 + { state: "settled", end: "routing-stalled" },
1497 + { state: "settled", end: "replay-continuation-timeout" },
1498 + { state: "settled", end: "replay-foreground-timeout" },
1499 + ] as const)(
1500 + "routes the OpenCode 1.19.5 root background prompt while $state, ending by $end",
1501 + ({ state, end }) =>
1502 + Effect.gen(function* () {
1503 + const nativeEvents = asyncEventStream();
1504 + const push = (event: unknown) => Effect.promise(() => nativeEvents.push(event));
1505 + const root = "ses_root";
1506 + const promptIds: Array<string> = [];
1507 + const aborted: Array<string> = [];
1508 + const nativeExit = yield* Deferred.make<number>();
1509 + const routeStarted = promiseGate<void>();
1510 + const routeFinished = promiseGate<void>();
1511 + const abortStarted = promiseGate<void>();
1512 + const abortFinished = promiseGate<void>();
1513 + let aborting = false;
1514 + let submittedWhileAborting = false;
1515 + const replies: unknown[] = [];
1516 + let summaries = 0;
1517 + const offers: Array<ProviderContinuationRequests.ProviderContinuationRequest> = [];
1518 + const sessionScope = yield* Scope.make();
1519 + yield* Effect.addFinalizer(() => Scope.close(sessionScope, Exit.void));
1520 + const harness = yield* makeOpenCodeRuntimeHarness(
1521 + "root-background-wake",
1522 + root,
1523 + {
1524 + event: { subscribe: async () => ({ stream: nativeEvents.stream }) },
1525 + permission: {
1526 + reply: async (input: unknown) => {
1527 + replies.push(input);
1528 + return { data: true };
1529 + },
1530 + },
1531 + question: {
1532 + reply: async (input: unknown) => {
1533 + replies.push(input);
1534 + return { data: true };
1535 + },
1536 + },
1537 + provider: {
1538 + list: async () => {
1539 + routeStarted.resolve();
1540 + await routeFinished.promise;
1541 + return { data: { all: [] } };
1542 + },
1543 + },
1544 + session: {
1545 + create: async () => ({ data: { id: root, time: { created: 1, updated: 1 } } }),
1546 + get: async (input: { sessionID: string }) => {
1547 + if (input.sessionID === "ses_unrelated" || input.sessionID === "ses_replay_child") {
1548 + routeStarted.resolve();
1549 + await routeFinished.promise;
1550 + }
1551 + return {
1552 + data: {
1553 + id: input.sessionID,
1554 + ...(input.sessionID === "ses_held_child" ? { parentID: root } : {}),
1555 + time: { created: 1, updated: 1 },
1556 + },
1557 + };
1558 + },
1559 + summarize: async () => {
1560 + summaries++;
1561 + return { data: true };
1562 + },
1563 + promptAsync: async (input: { messageID: string }) => {
1564 + submittedWhileAborting ||= aborting;
1565 + promptIds.push(input.messageID);
1566 + return { data: true };
1567 + },
1568 + messages: async () => ({ data: [] }),
1569 + children: async (input: { sessionID: string }) => ({
1570 + data: input.sessionID === root ? [{ id: "ses_descendant" }] : [],
1571 + }),
1572 + update: async () => {
1573 + if (end === "policy-failure") throw new Error("permission update failed");
1574 + return { data: { id: root } };
1575 + },
1576 + abort: async (input: { sessionID: string }) => {
1577 + aborted.push(input.sessionID);
1578 + if (
1579 + input.sessionID === root &&
1580 + (end === "stop" ||
1581 + end === "cancelled" ||
1582 + end === "stop-failure" ||
1583 + end === "cancelled-failure" ||
1584 + end === "stop-busy-failure" ||
1585 + end === "cancelled-busy-failure" ||
1586 + end === "idle-during-abort-failure" ||
1587 + end === "overflow-during-abort-failure")
1588 + ) {
1589 + aborting = true;
1590 + abortStarted.resolve();
1591 + await abortFinished.promise;
1592 + aborting = false;
1593 + if (end?.endsWith("failure")) throw new Error("root abort failed");
1594 + }
1595 + return { data: true };
1596 + },
1597 + },
1598 + },
1599 + {},
1600 + end === "owned-exit" ? { exitCode: Deferred.await(nativeExit) } : {},
1601 + ).pipe(
1602 + Effect.provideService(Scope.Scope, sessionScope),
1603 + Effect.provideService(ProviderContinuationRequests.ProviderContinuationRequests, {
1604 + offer: (offer) =>
1605 + Effect.sync(() => {
1606 + offers.push(offer);
1607 + }),
1608 + take: Effect.never,
1609 + }),
1610 + );
1611 + const user = (id: string) => ({
1612 + type: "message.updated",
1613 + properties: {
1614 + sessionID: root,
1615 + info: { id, sessionID: root, role: "user", time: { created: 1 } },
1616 + },
1617 + });
1618 + const status = (type: "busy" | "idle") => ({
1619 + type: "session.status",
1620 + properties: { sessionID: root, status: { type } },
1621 + });
1622 + const assistant = (completed: boolean) => ({
1623 + type: "message.updated",
1624 + properties: {
1625 + sessionID: root,
1626 + info: {
1627 + id: "msg_wake_assistant",
1628 + sessionID: root,
1629 + role: "assistant",
1630 + parentID: "msg_background_result",
1631 + time: completed ? { created: 2, completed: 3 } : { created: 2 },
1632 + },
1633 + },
1634 + });
1635 + const awaitTerminal = harness.runtime.events.pipe(
1636 + Stream.filter((event) => event.type === "turn.terminal"),
1637 + Stream.take(1),
1638 + Stream.runDrain,
1639 + );
1640 + yield* harness.startTurn();
1641 + yield* push(user(promptIds[0]!));
1642 + yield* push(status("busy"));
1643 + if (state === "settled") {
1644 + yield* push(status("idle"));
1645 + yield* awaitTerminal;
1646 + }
1647 + assert.equal(offers.length, 0, "foreground admission must not offer a continuation");
1648 + const before = yield* harness.runtime.readThreadSnapshot({
1649 + providerThread: harness.providerThread,
1650 + });
1651 + assert.equal(before.providerTurns.length, 1);
1652 + assert.equal(
1653 + before.providerTurns[0]?.status,
1654 + state === "settled" ? "completed" : "running",
1655 + );
1656 +
1657 + // Pinned task.ts injects a synthetic root prompt; prompt.ts saves it before starting its loop.
1658 + yield* push(user("msg_background_result"));
1659 + yield* push({
1660 + type: "message.part.updated",
1661 + properties: {
1662 + sessionID: root,
1663 + time: 2,
1664 + part: {
1665 + id: "prt_result",
1666 + sessionID: root,
1667 + messageID: "msg_background_result",
1668 + type: "text",
1669 + synthetic: true,
1670 + text: '<task id="ses_child" state="completed">\n<summary>Background task completed: Sleep and reply</summary>\n<task_result>\nCHILD_OK\n</task_result>\n</task>',
1671 + },
1672 + },
1673 + });
1674 + const nativeError = (name = "UnknownError") => ({
1675 + type: "session.error",
1676 + properties: { sessionID: root, error: { name, data: { message: "wake failed" } } },
1677 + });
1678 + if (
1679 + end === "foreground-before-status-idle" ||
1680 + end === "foreground-before-session-idle" ||
1681 + end === "foreground-before-error" ||
1682 + end === "stop-before-idle" ||
1683 + end === "stop-before-error"
1684 + ) {
1685 + const stopping = end.startsWith("stop");
1686 + const starting = yield* (
1687 + stopping
1688 + ? harness.runtime.interruptTurn({
1689 + providerThread: harness.providerThread,
1690 + providerTurnId: ProviderTurnId.make("provider-turn:settled"),
1691 + requestRuntimeRestart: true,
1692 + })
1693 + : harness.startTurn("follow up")
1694 + ).pipe(Effect.exit, Effect.forkScoped);
1695 + yield* TestClock.adjust(0);
1696 + yield* push(
1697 + end.endsWith("error")
1698 + ? nativeError()
1699 + : end.endsWith("status-idle")
1700 + ? status("idle")
1701 + : { type: "session.idle", properties: { sessionID: root } },
1702 + );
1703 + // A missing admission signal used to poison the session at this deadline.
1704 + yield* TestClock.adjust("10 seconds");
1705 + assert.isTrue(Exit.isSuccess(yield* Fiber.join(starting)));
1706 + assert.equal(promptIds.length, stopping ? 1 : 2);
1707 + return;
1708 + }
1709 + if (end === "foreground-before-busy" || end === "foreground-before-busy-timeout") {
1710 + let returned = false;
1711 + const starting = yield* harness.startTurn("follow up").pipe(
1712 + Effect.exit,
1713 + Effect.tap(() =>
1714 + Effect.sync(() => {
1715 + returned = true;
1716 + }),
1717 + ),
1718 + Effect.forkScoped,
1719 + );
1720 + yield* TestClock.adjust(0);
1721 + assert.equal(promptIds.length, 1, "foreground waits for native registration");
1722 + if (end === "foreground-before-busy") {
1723 + yield* push(status("busy"));
1724 + assert.equal(promptIds.length, 1, "foreground cannot join a registering wake");
1725 + yield* push(status("idle"));
1726 + assert.isTrue(Exit.isSuccess(yield* Fiber.join(starting)));
1727 + assert.equal(promptIds.length, 2);
1728 + } else {
1729 + // A noReply prompt saves a user message and never reports busy or idle.
1730 + yield* TestClock.adjust("10 seconds");
1731 + assert.isTrue(
1732 + returned,
1733 + "a lone reemitted user message cannot block foreground forever",
1734 + );
1735 + assert.isTrue(Exit.isSuccess(yield* Fiber.join(starting)));
1736 + assert.equal(promptIds.length, 2, "the foreground prompt submits normally");
1737 + }
1738 + return;
1739 + }
1740 + if (end === "stop-before-busy-timeout") {
1741 + const stopping = yield* harness.runtime
1742 + .interruptTurn({
1743 + providerThread: harness.providerThread,
1744 + providerTurnId: ProviderTurnId.make("provider-turn:settled"),
1745 + requestRuntimeRestart: true,
1746 + })
1747 + .pipe(Effect.exit, Effect.forkScoped);
1748 + yield* TestClock.adjust("10 seconds");
1749 + assert.isTrue(Exit.isSuccess(yield* Fiber.join(stopping)));
1750 + assert.deepEqual(
1751 + aborted,
1752 + [root, "ses_descendant"],
1753 + "uncertain registration still attempts native cleanup",
1754 + );
1755 + assert.isFalse(yield* harness.runtime.hasPendingBackgroundWork!);
1756 + yield* harness.startTurn("after uncertain cancellation");
1757 + assert.equal(promptIds.length, 2, "a never-run saved message does not break the session");
1758 + return;
1759 + }
1760 + if (end === "stop-before-busy") {
1761 + const stopping = yield* harness.runtime
1762 + .interruptTurn({
1763 + providerThread: harness.providerThread,
1764 + providerTurnId: ProviderTurnId.make("provider-turn:settled"),
1765 + requestRuntimeRestart: true,
1766 + })
1767 + .pipe(Effect.forkScoped);
1768 + yield* TestClock.adjust(0);
1769 + assert.deepEqual(aborted, [], "abort waits for native prompt registration");
1770 + yield* push(status("busy"));
1771 + yield* Fiber.join(stopping);
1772 + assert.deepEqual(aborted, [root, "ses_descendant"]);
1773 + assert.equal(offers.length, 0, "a stopped registering prompt must not offer a wake");
1774 + assert.isFalse(yield* harness.runtime.hasPendingBackgroundWork!);
1775 + return;
1776 + }
1777 + if (end === "idle-only" || end === "error-only") {
1778 + yield* push(
1779 + end === "idle-only"
1780 + ? { type: "session.idle", properties: { sessionID: root } }
1781 + : {
1782 + type: "session.error",
1783 + properties: {
1784 + sessionID: root,
1785 + error: { name: "UnknownError", data: { message: "failed before busy" } },
1786 + },
1787 + },
1788 + );
1789 + assert.isFalse(yield* harness.runtime.hasPendingBackgroundWork!);
1790 + yield* push(status("busy"));
1791 + assert.equal(offers.length, 0, "a terminal-only update cannot offer a wake");
1792 + return;
1793 + }
1794 + yield* push(
1795 + end === "retry-registration"
1796 + ? {
1797 + type: "session.status",
1798 + properties: {
1799 + sessionID: root,
1800 + status: { type: "retry", attempt: 1, message: "retry", next: 100 },
1801 + },
1802 + }
1803 + : status("busy"),
1804 + );
1805 + if (end === "retry-registration") {
1806 + yield* push(status("busy"));
1807 + yield* push(status("busy"));
1808 + }
1809 + if (end === "foreground-error" || end === "foreground-overflow") {
1810 + const starting = yield* harness.startTurn("follow up").pipe(Effect.forkScoped);
1811 + yield* TestClock.adjust(0);
1812 + yield* push(
1813 + nativeError(end === "foreground-overflow" ? "ContextOverflowError" : "UnknownError"),
1814 + );
1815 + yield* push(status("idle"));
1816 + yield* Fiber.join(starting);
1817 + assert.equal(promptIds.length, 1, "failed waiting foreground cannot submit");
1818 + const snapshot = yield* harness.runtime.readThreadSnapshot({
1819 + providerThread: harness.providerThread,
1820 + });
1821 + assert.equal(snapshot.providerTurns.at(-1)?.status, "failed");
1822 + return;
1823 + }
1824 + if (end === "catalog-live" || end === "catalog-replay") {
1825 + yield* push(assistant(false));
1826 + yield* push({
1827 + type: "message.part.updated",
1828 + properties: {
1829 + part: {
1830 + type: "step-finish",
1831 + id: "step-wake",
1832 + sessionID: root,
1833 + messageID: "msg_wake_assistant",
1834 + reason: "stop",
1835 + cost: 0,
1836 + tokens: { input: 1, output: 1, reasoning: 0, cache: { read: 0, write: 0 } },
1837 + },
1838 + },
1839 + });
1840 + if (end === "catalog-replay") yield* push(status("idle"));
1841 + const starting = yield* harness
1842 + .startTurn("", undefined, undefined, false, "catalog", {})
1843 + .pipe(Effect.exit, Effect.forkScoped);
1844 + if (end === "catalog-live") yield* Fiber.join(starting);
1845 + const idle =
1846 + end === "catalog-live" ? yield* push(status("idle")).pipe(Effect.forkScoped) : null;
1847 + yield* Effect.promise(() => routeStarted.promise);
1848 + yield* TestClock.adjust("10 seconds");
1849 + if (idle !== null) yield* Fiber.join(idle);
1850 + else yield* Fiber.join(starting);
1851 + const events = yield* harness.runtime.events.pipe(
1852 + Stream.takeUntil((event) => event.type === "turn.terminal"),
1853 + Stream.runCollect,
1854 + );
1855 + assert.equal(events.find((event) => event.type === "turn.terminal")?.status, "completed");
1856 + const snapshot = yield* harness.runtime.readThreadSnapshot({
1857 + providerThread: harness.providerThread,
1858 + });
1859 + assert.equal(snapshot.providerTurns.at(-1)?.status, "completed");
1860 + return;
1861 + }
1862 + assert.equal(offers.length, state === "settled" ? 1 : 0, "only a settled root needs a run");
1863 + if (end === "no-wake-continuation") {
1864 + yield* offers[0]!.onRunEndedWithoutStarting!();
1865 + yield* harness.startTurn("", undefined, undefined, false, "no-wake", {});
1866 + yield* awaitTerminal;
1867 + const snapshot = yield* harness.runtime.readThreadSnapshot({
1868 + providerThread: harness.providerThread,
1869 + });
1870 + assert.equal(snapshot.providerTurns.at(-1)?.status, "completed");
1871 + assert.equal(promptIds.length, 1);
1872 + return;
1873 + }
1874 + if (end === "compact-takeover") {
1875 + const starting = yield* harness.startTurn("/compact").pipe(Effect.forkScoped);
1876 + yield* TestClock.adjust(0);
1877 + assert.equal(summaries, 0);
1878 + yield* push(status("idle"));
1879 + yield* Fiber.join(starting);
1880 + yield* awaitTerminal;
1881 + assert.equal(summaries, 1);
1882 + assert.equal(promptIds.length, 1);
1883 + return;
1884 + }
1885 + if (end === "idle-during-abort-failure" || end === "overflow-during-abort-failure") {
1886 + const stopping = yield* harness.runtime
1887 + .interruptTurn({
1888 + providerThread: harness.providerThread,
1889 + providerTurnId: ProviderTurnId.make("provider-turn:settled"),
1890 + requestRuntimeRestart: true,
1891 + })
1892 + .pipe(Effect.exit, Effect.forkScoped);
1893 + yield* Effect.promise(() => abortStarted.promise);
1894 + // OpenCode stays busy and auto-compacts after an overflow, so it proves nothing stopped.
1895 + yield* push(
1896 + end === "idle-during-abort-failure"
1897 + ? status("idle")
1898 + : nativeError("ContextOverflowError"),
1899 + );
1900 + abortFinished.resolve();
1901 + assert.isTrue(Exit.isFailure(yield* Fiber.join(stopping)));
1902 + const next = yield* harness.startTurn("after native idle").pipe(Effect.exit);
1903 + assert.equal(Exit.isSuccess(next), end === "idle-during-abort-failure");
1904 + assert.equal(promptIds.length, end === "idle-during-abort-failure" ? 2 : 1);
1905 + return;
1906 + }
1907 + if (end === "held-requests") {
1908 + yield* push({
1909 + type: "session.created",
1910 + properties: {
1911 + info: { id: "ses_held_child", parentID: root, time: { created: 1, updated: 1 } },
1912 + },
1913 + });
1914 + yield* push({
1915 + type: "message.part.updated",
1916 + properties: {
1917 + part: {
1918 + id: "held-task",
1919 + sessionID: root,
1920 + messageID: "msg_wake_assistant",
1921 + type: "tool",
1922 + callID: "held-call",
1923 + tool: "task",
1924 + state: {
1925 + status: "completed",
1926 + input: { description: "Child", prompt: "Work", subagent_type: "general" },
1927 + output: "launched",
1928 + title: "Child",
1929 + metadata: { sessionId: "ses_held_child", background: true },
1930 + time: { start: 1, end: 2 },
1931 + },
1932 + },
1933 + },
1934 + });
1935 + yield* push({
1936 + type: "message.updated",
1937 + properties: {
1938 + sessionID: "ses_held_child",
1939 + info: {
1940 + id: "held-child-user",
1941 + sessionID: "ses_held_child",
1942 + role: "user",
1943 + time: { created: 1 },
1944 + },
1945 + },
1946 + });
1947 + yield* push({
1948 + type: "message.updated",
1949 + properties: {
1950 + sessionID: "ses_held_child",
1951 + info: {
1952 + id: "held-child-message",
1953 + sessionID: "ses_held_child",
1954 + role: "assistant",
1955 + parentID: "held-child-user",
1956 + time: { created: 2 },
1957 + },
1958 + },
1959 + });
1960 + yield* push({
1961 + type: "message.part.updated",
1962 + properties: {
1963 + part: {
1964 + id: "held-child-text",
1965 + sessionID: "ses_held_child",
1966 + messageID: "held-child-message",
1967 + type: "text",
1968 + text: "HELD_CHILD_OK",
1969 + time: { start: 2, end: 3 },
1970 + },
1971 + },
1972 + });
1973 + yield* push({
1974 + type: "message.part.updated",
1975 + properties: {
1976 + part: {
1977 + id: "held-text",
1978 + sessionID: root,
1979 + messageID: "msg_wake_assistant",
1980 + type: "text",
1981 + text: "HELD",
1982 + time: { start: 2 },
1983 + },
1984 + },
1985 + });
1986 + yield* push({
1987 + type: "message.part.delta",
1988 + properties: {
1989 + sessionID: root,
1990 + messageID: "msg_wake_assistant",
1991 + partID: "held-text",
1992 + field: "text",
1993 + delta: "_DELTA",
1994 + },
1995 + });
1996 + yield* push({
1997 + type: "todo.updated",
1998 + properties: {
1999 + sessionID: root,
2000 + todos: [{ content: "Wake task", status: "in_progress", priority: "high" }],
2001 + },
2002 + });
2003 + yield* push({ type: "session.compacted", properties: { sessionID: root } });
2004 + yield* push({
2005 + type: "permission.asked",
2006 + properties: {
2007 + id: "wake-permission",
2008 + sessionID: root,
2009 + permission: "external_directory",
2010 + patterns: ["/outside/*"],
2011 + always: [],
2012 + metadata: {},
2013 + },
2014 + });
2015 + yield* push({
2016 + type: "question.asked",
2017 + properties: {
2018 + id: "wake-question",
2019 + sessionID: root,
2020 + questions: [
2021 + {
2022 + header: "Drinks",
2023 + question: "Which drink?",
2024 + options: [{ label: "Tea", description: "Hot" }],
2025 + },
2026 + ],
2027 + },
2028 + });
2029 + const beforeAdmission = yield* harness.runtime.readThreadSnapshot({
2030 + providerThread: harness.providerThread,
2031 + });
2032 + assert.equal(beforeAdmission.runtimeRequests.length, 0);
2033 + yield* harness.startTurn("", undefined, undefined, false, "held", {});
2034 + const events = yield* harness.runtime.events.pipe(
2035 + Stream.takeUntil(
2036 + (event) =>
2037 + event.type === "runtime_request.updated" &&
2038 + event.runtimeRequest.kind === "user_input",
2039 + ),
2040 + Stream.runCollect,
2041 + );
2042 + assert.isTrue(
2043 + events.some(
2044 + (event) =>
2045 + event.type === "turn_item.updated" &&
2046 + event.turnItem.type === "assistant_message" &&
2047 + event.turnItem.text === "HELD_CHILD_OK",
2048 + ),
2049 + );
2050 + assert.isTrue(
2051 + events.some(
2052 + (event) =>
2053 + event.type === "turn_item.updated" &&
2054 + event.turnItem.type === "assistant_message" &&
2055 + event.turnItem.text === "HELD_DELTA",
2056 + ),
2057 + );
2058 + assert.isTrue(events.some((event) => event.type === "plan.updated"));
2059 + assert.isTrue(
2060 + events.some(
2061 + (event) => event.type === "turn_item.updated" && event.turnItem.type === "compaction",
2062 + ),
2063 + );
2064 + for (const event of events) {
2065 + if (event.type !== "runtime_request.updated") continue;
2066 + yield* harness.runtime.respondToRuntimeRequest(
2067 + event.runtimeRequest.kind === "user_input"
2068 + ? { requestId: event.runtimeRequest.id, answers: { "question-0-drinks": ["Tea"] } }
2069 + : { requestId: event.runtimeRequest.id, decision: "accept" },
2070 + );
2071 + }
2072 + assert.equal(replies.length, 2);
2073 + yield* push(status("idle"));
2074 + yield* awaitTerminal;
2075 + assert.equal(promptIds.length, 1);
2076 + return;
2077 + }
2078 + if (end === "retry-registration") {
2079 + assert.equal(offers.length, 1);
2080 + yield* push(status("idle"));
2081 + yield* harness.startTurn("", undefined, undefined, false, "retry-wake", {});
2082 + yield* awaitTerminal;
2083 + assert.equal(promptIds.length, 1);
2084 + return;
2085 + }
2086 + if (end === "invalid-continuation" || end === "policy-failure") {
2087 + const failed = yield* harness
2088 + .startTurn(
2089 + "",
2090 + undefined,
2091 + end === "policy-failure"
2092 + ? runtimePolicy("approval-required", { cwd: "/workspace" })
2093 + : undefined,
2094 + false,
2095 + "continuation",
2096 + { model: end === "invalid-continuation" ? "invalid" : "anthropic/claude-sonnet" },
2097 + )
2098 + .pipe(Effect.exit);
2099 + assert.isTrue(Exit.isFailure(failed));
2100 + assert.isFalse(yield* harness.runtime.hasPendingBackgroundWork!);
2101 + assert.deepEqual(aborted, [root, "ses_descendant"]);
2102 + assert.isTrue(
2103 + Option.isNone(yield* offers[0]!.dispatchIfCurrent!(Effect.succeed("stale"))),
2104 + );
2105 + return;
2106 + }
2107 + if (end === "stop-busy-failure" || end === "cancelled-busy-failure") {
2108 + const stopping = yield* (
2109 + end === "stop-busy-failure"
2110 + ? harness.runtime.interruptTurn({
2111 + providerThread: harness.providerThread,
2112 + providerTurnId: ProviderTurnId.make("provider-turn:settled"),
2113 + requestRuntimeRestart: true,
2114 + })
2115 + : offers[0]!.onRunEndedWithoutStarting!()
2116 + ).pipe(Effect.exit, Effect.forkScoped);
2117 + yield* Effect.promise(() => abortStarted.promise);
2118 + abortFinished.resolve();
2119 + const stopped = yield* Fiber.join(stopping);
2120 + assert.equal(Exit.isFailure(stopped), end === "stop-busy-failure");
2121 + const replacement = yield* harness
2122 + .startTurn("replacement", undefined, undefined, false, "replacement")
2123 + .pipe(Effect.exit);
2124 + assert.isTrue(Exit.isFailure(replacement), "uncertain native work requires reconnect");
2125 + assert.equal(promptIds.length, 1, "replacement cannot join the surviving native loop");
2126 + assert.deepEqual(aborted, [root, "ses_descendant"]);
2127 + const events = yield* harness.runtime.events.pipe(
2128 + Stream.takeUntil(
2129 + (event) =>
2130 + event.type === "provider_session.updated" &&
2131 + event.providerSession.status === "error",
2132 + ),
2133 + Stream.runCollect,
2134 + );
2135 + assert.isTrue(
2136 + events.some(
2137 + (event) =>
2138 + event.type === "provider_session.updated" &&
2139 + event.providerSession.status === "error" &&
2140 + event.providerSession.lastError?.includes("reconnect"),
2141 + ),
2142 + );
2143 + assert.isFalse(yield* harness.runtime.hasPendingBackgroundWork!);
2144 + return;
2145 + }
2146 + if (end === "replay-continuation-timeout" || end === "replay-foreground-timeout") {
2147 + yield* push({
2148 + type: "message.part.updated",
2149 + properties: {
2150 + sessionID: root,
2151 + part: {
2152 + id: "prt_replay_task",
2153 + sessionID: root,
2154 + messageID: "msg_wake_assistant",
2155 + type: "tool",
2156 + tool: "task",
2157 + callID: "call_replay_task",
2158 + state: {
2159 + status: "running",
2160 + input: { description: "Child", prompt: "Continue", subagent_type: "general" },
2161 + title: "Child",
2162 + metadata: { sessionId: "ses_replay_child", background: true },
2163 + time: { start: 3 },
2164 + },
2165 + },
2166 + },
2167 + });
2168 + const starting = yield* harness
2169 + .startTurn(
2170 + end === "replay-foreground-timeout" ? "follow up" : "",
2171 + undefined,
2172 + undefined,
2173 + false,
2174 + "replay",
2175 + end === "replay-continuation-timeout" ? {} : undefined,
2176 + )
2177 + .pipe(Effect.exit, Effect.forkScoped);
2178 + yield* Effect.promise(() => routeStarted.promise);
2179 + yield* TestClock.adjust("10 seconds");
2180 + assert.isTrue(Exit.isFailure(yield* Fiber.join(starting)));
2181 + const snapshot = yield* harness.runtime.readThreadSnapshot({
2182 + providerThread: harness.providerThread,
2183 + });
2184 + assert.equal(
2185 + snapshot.providerTurns.at(-1)?.status,
2186 + "failed",
2187 + "the installed turn must be finalized",
2188 + );
2189 + assert.deepEqual(aborted, [root, "ses_descendant"]);
2190 + const replacement = yield* harness.startTurn("replacement").pipe(Effect.exit);
2191 + assert.isTrue(Exit.isFailure(replacement), "incomplete replay requires reconnect");
2192 + assert.equal(promptIds.length, 1, "failed replay cannot submit a foreground prompt");
2193 + const events = yield* harness.runtime.events.pipe(
2194 + Stream.takeUntil((event) => event.type === "turn.terminal"),
2195 + Stream.runCollect,
2196 + );
2197 + assert.isTrue(
2198 + events.some(
2199 + (event) =>
2200 + event.type === "provider_session.updated" &&
2201 + event.providerSession.status === "error" &&
2202 + event.providerSession.lastError?.includes("reconnect"),
2203 + ),
2204 + );
2205 + assert.isTrue(
2206 + events.some(
2207 + (event) =>
2208 + event.type === "turn.terminal" &&
2209 + event.status === "failed" &&
2210 + event.threadDisposition === "broken",
2211 + ),
2212 + );
2213 + routeFinished.resolve();
2214 + yield* offers[0]!.onRunEndedWithoutStarting!();
2215 + assert.deepEqual(
2216 + aborted,
2217 + [root, "ses_descendant"],
2218 + "stale callbacks cannot repeat cleanup",
2219 + );
2220 + return;
2221 + }
2222 + if (end === "routing-stalled") {
2223 + const routing = yield* push({
2224 + type: "question.asked",
2225 + properties: {
2226 + id: "question_unrelated",
2227 + sessionID: "ses_unrelated",
2228 + questions: [
2229 + {
2230 + header: "Choice",
2231 + question: "Choose",
2232 + options: [{ label: "Yes", description: "Continue" }],
2233 + },
2234 + ],
2235 + },
2236 + }).pipe(Effect.forkScoped);
2237 + yield* Effect.promise(() => routeStarted.promise);
2238 + const stopping = yield* offers[0]!.onRunEndedWithoutStarting!().pipe(Effect.forkScoped);
2239 + yield* TestClock.adjust(0);
2240 + const cleanedBeforeRoutingCompleted = [...aborted];
2241 + let foregroundReturned = false;
2242 + const foreground = yield* harness
2243 + .startTurn("after Stop", undefined, undefined, false, "after-stop")
2244 + .pipe(
2245 + Effect.exit,
2246 + Effect.ensuring(
2247 + Effect.sync(() => {
2248 + foregroundReturned = true;
2249 + }),
2250 + ),
2251 + Effect.forkScoped,
2252 + );
2253 + yield* TestClock.adjust("10 seconds");
2254 + assert.isFalse(foregroundReturned, "foreground installation waits for routing");
2255 + routeFinished.resolve();
2256 + yield* Fiber.join(stopping);
2257 + yield* Fiber.join(routing);
2258 + assert.isTrue(Exit.isSuccess(yield* Fiber.join(foreground)));
2259 + assert.deepEqual(
2260 + cleanedBeforeRoutingCompleted,
2261 + [root, "ses_descendant"],
2262 + "Stop bypasses stalled event I/O",
2263 + );
2264 + assert.equal(
2265 + promptIds.length,
2266 + 2,
2267 + "slow routing delays events without breaking the session",
2268 + );
2269 + assert.isFalse(yield* harness.runtime.hasPendingBackgroundWork!);
2270 + return;
2271 + }
2272 + if (end === "owned-exit" || end === "failed-stream") {
2273 + if (end === "owned-exit") yield* Deferred.succeed(nativeExit, 1);
2274 + else nativeEvents.close();
2275 + yield* harness.runtime.events.pipe(
2276 + Stream.filter(
2277 + (event) =>
2278 + event.type === "provider_session.updated" &&
2279 + event.providerSession.status === "error",
2280 + ),
2281 + Stream.take(1),
2282 + Stream.runDrain,
2283 + );
2284 + yield* TestClock.adjust(0);
2285 + assert.isFalse(yield* harness.runtime.hasPendingBackgroundWork!);
2286 + yield* offers[0]!.onRunEndedWithoutStarting!();
2287 + assert.deepEqual(aborted, [], "failed-session callbacks cannot abort a replacement");
2288 + assert.isTrue(
2289 + Option.isNone(yield* offers[0]!.dispatchIfCurrent!(Effect.succeed("stale"))),
2290 + );
2291 + return;
2292 + }
2293 + if (end === "closed") {
2294 + yield* Scope.close(sessionScope, Exit.void);
2295 + const replacementEvents = asyncEventStream();
2296 + const replacementAborts: string[] = [];
2297 + const replacementOffers: ProviderContinuationRequests.ProviderContinuationRequest[] = [];
2298 + const replacement = yield* makeOpenCodeRuntimeHarness(
2299 + "replacement-root",
2300 + "ses_replacement",
2301 + {
2302 + event: { subscribe: async () => ({ stream: replacementEvents.stream }) },
2303 + session: {
2304 + create: async () => ({
2305 + data: { id: "ses_replacement", time: { created: 1, updated: 1 } },
2306 + }),
2307 + get: async () => ({ data: { id: root, time: { created: 1, updated: 1 } } }),
2308 + messages: async () => ({
2309 + data: [
2310 + {
2311 + info: {
2312 + id: "msg_background_result",
2313 + sessionID: root,
2314 + role: "user",
2315 + time: { created: 1 },
2316 + },
2317 + parts: [],
2318 + },
2319 + ],
2320 + }),
2321 + update: async () => ({ data: { id: root } }),
2322 + promptAsync: async () => ({ data: true }),
2323 + children: async () => ({ data: [] }),
2324 + abort: async (input: { sessionID: string }) => {
2325 + replacementAborts.push(input.sessionID);
2326 + return { data: true };
2327 + },
2328 + },
2329 + },
2330 + ).pipe(
2331 + Effect.provideService(ProviderContinuationRequests.ProviderContinuationRequests, {
2332 + offer: (offer) =>
2333 + Effect.sync(() => {
2334 + replacementOffers.push(offer);
2335 + }),
2336 + take: Effect.never,
2337 + }),
2338 + );
2339 + const resumed = yield* replacement.runtime.resumeThread({
2340 + providerThread: harness.providerThread,
2341 + });
2342 + yield* replacement.startTurn("replacement", resumed);
2343 + yield* Effect.promise(() => replacementEvents.push(user("msg_background_result")));
2344 + yield* Effect.promise(() => replacementEvents.push(status("busy")));
2345 + assert.equal(
2346 + replacementOffers.length,
2347 + 0,
2348 + "old root frames cannot offer during replacement work",
2349 + );
2350 + const beforeCallback = [...aborted];
2351 + yield* offers[0]!.onRunEndedWithoutStarting!();
2352 + assert.deepEqual(
2353 + aborted,
2354 + beforeCallback,
2355 + "a closed session callback cannot abort replacement work",
2356 + );
2357 + assert.isFalse(yield* harness.runtime.hasPendingBackgroundWork!);
2358 + assert.deepEqual(
2359 + replacementAborts,
2360 + [],
2361 + "old callbacks cannot abort the installed runtime",
2362 + );
2363 + const replacementSnapshot = yield* replacement.runtime.readThreadSnapshot({
2364 + providerThread: resumed,
2365 + });
2366 + assert.equal(replacementSnapshot.providerTurns.at(-1)?.status, "running");
2367 + return;
2368 + }
2369 + const foreground =
2370 + end === "foreground" || end === "foreground-stop" || end === "foreground-eof"
2371 + ? yield* harness
2372 + .startTurn("follow up", undefined, undefined, false, "next")
2373 + .pipe(Effect.forkScoped)
2374 + : null;
2375 + if (foreground !== null) {
2376 + yield* TestClock.adjust(0);
2377 + assert.equal(promptIds.length, 1, "foreground prompt waits for the old native loop");
2378 + }
2379 + yield* push(assistant(false));
2380 + yield* push({
2381 + type: "message.part.updated",
2382 + properties: {
2383 + sessionID: root,
2384 + time: 2,
2385 + part: {
2386 + id: "prt_wake",
2387 + sessionID: root,
2388 + messageID: "msg_wake_assistant",
2389 + type: "text",
2390 + text: "WAKE_OK",
2391 + time: { start: 2, end: 3 },
2392 + },
2393 + },
2394 + });
2395 + yield* push(assistant(true));
2396 + if (end === "foreground-stop" || end === "foreground-eof") {
2397 + if (end === "foreground-eof") nativeEvents.close();
2398 + else {
2399 + const snapshot = yield* harness.runtime.readThreadSnapshot({
2400 + providerThread: harness.providerThread,
2401 + });
2402 + yield* harness.runtime.interruptTurn({
2403 + providerThread: harness.providerThread,
2404 + providerTurnId: snapshot.providerTurns.at(-1)!.id,
2405 + requestRuntimeRestart: true,
2406 + });
2407 + }
2408 + if (foreground !== null) yield* Fiber.join(foreground);
2409 + assert.equal(
2410 + promptIds.length,
2411 + 1,
2412 + "cancelled or failed waiting foreground must never submit",
2413 + );
2414 + return;
2415 + }
2416 + if (end === "foreground-buffered-error") yield* push(nativeError());
2417 + yield* push(status("idle"));
2418 + yield* push({ type: "session.idle", properties: { sessionID: root } });
2419 + if (foreground !== null) yield* Fiber.join(foreground);
2420 + if (end === "foreground-reemitted") {
2421 + yield* push(user("msg_background_result"));
2422 + yield* harness.startTurn("follow up", undefined, undefined, false, "next");
2423 + assert.equal(promptIds.length, 2, "a re-sent saved message is not a later execution");
2424 + return;
2425 + }
2426 + if (end === "foreground-second-busy" || end === "foreground-second-saved") {
2427 + yield* push(user("msg_second_background_result"));
2428 + // A saved user message registers before OpenCode reports busy.
2429 + if (end === "foreground-second-busy") yield* push(status("busy"));
2430 + const starting = yield* harness
2431 + .startTurn("follow up", undefined, undefined, false, "next")
2432 + .pipe(Effect.forkScoped);
2433 + yield* TestClock.adjust(0);
2434 + assert.equal(promptIds.length, 1, "foreground waits for the later buffered execution");
2435 + if (end === "foreground-second-saved") {
2436 + yield* push(status("busy"));
2437 + yield* push({
2438 + type: "message.updated",
2439 + properties: {
2440 + sessionID: root,
2441 + info: {
2442 + id: "msg_second_wake_assistant",
2443 + sessionID: root,
2444 + role: "assistant",
2445 + parentID: "msg_second_background_result",
2446 + time: { created: 4, completed: 5 },
2447 + },
2448 + },
2449 + });
2450 + assert.equal(promptIds.length, 1, "the later execution's reply cannot release it");
2451 + }
2452 + yield* push(status("idle"));
2453 + yield* Fiber.join(starting);
2454 + assert.equal(promptIds.length, 2);
2455 + if (end === "foreground-second-saved") {
2456 + yield* push({ type: "session.idle", properties: { sessionID: root } });
2457 + const snapshot = yield* harness.runtime.readThreadSnapshot({
2458 + providerThread: harness.providerThread,
2459 + });
2460 + assert.equal(
2461 + snapshot.providerTurns.at(-1)?.status,
2462 + "running",
2463 + "an earlier reply cannot admit the foreground prompt",
2464 + );
2465 + }
2466 + return;
2467 + }
2468 + if (end === "sequential" || end === "sequential-buffered") {
2469 + const secondResult = Effect.gen(function* () {
2470 + yield* push(user("msg_second_background_result"));
2471 + yield* push(status("busy"));
2472 + yield* push({
2473 + type: "message.part.updated",
2474 + properties: {
2475 + sessionID: root,
2476 + time: 4,
2477 + part: {
2478 + id: "prt_second_wake",
2479 + sessionID: root,
2480 + messageID: "msg_second_wake_assistant",
2481 + type: "text",
2482 + text: "SECOND_WAKE_OK",
2483 + time: { start: 4, end: 5 },
2484 + },
2485 + },
2486 + });
2487 + yield* push(status("idle"));
2488 + });
2489 + // Both results can settle before the first continuation is admitted.
2490 + if (end === "sequential-buffered") yield* secondResult;
2491 + yield* harness.startTurn("", undefined, undefined, false, "wake-one", {});
2492 + yield* awaitTerminal;
2493 + if (end === "sequential") yield* secondResult;
2494 + assert.equal(offers.length, 2, "completed sequential wakes each offer once");
2495 + yield* harness.startTurn("", undefined, undefined, false, "wake-two", {});
2496 + const events = yield* harness.runtime.events.pipe(
2497 + Stream.takeUntil((event) => event.type === "turn.terminal"),
2498 + Stream.runCollect,
2499 + );
2500 + const terminal = events.find((event) => event.type === "turn.terminal");
2501 + assert.isTrue(
2502 + events.some(
2503 + (event) =>
2504 + event.type === "turn_item.updated" &&
2505 + event.turnItem.type === "assistant_message" &&
2506 + event.turnItem.text === "SECOND_WAKE_OK" &&
2507 + event.turnItem.providerTurnId === terminal?.providerTurnId,
2508 + ),
2509 + );
2510 + assert.equal(promptIds.length, 1, "continuations never submit another prompt");
2511 + const snapshot = yield* harness.runtime.readThreadSnapshot({
2512 + providerThread: harness.providerThread,
2513 + });
2514 + assert.deepEqual(
2515 + snapshot.providerTurns.map((turn) => turn.status),
2516 + ["completed", "completed", "completed"],
2517 + );
2518 + return;
2519 + }
2520 + if (
2521 + end === "foreground-buffered" ||
2522 + end === "foreground-buffered-error" ||
2523 + end === "foreground"
2524 + ) {
2525 + if (end === "foreground-buffered" || end === "foreground-buffered-error")
2526 + yield* harness.startTurn("follow up", undefined, undefined, false, "next");
2527 + assert.equal(promptIds.length, 2, "the foreground prompt is submitted");
2528 + const snapshot = yield* harness.runtime.readThreadSnapshot({
2529 + providerThread: harness.providerThread,
2530 + });
2531 + assert.equal(snapshot.providerTurns.at(-1)?.status, "running");
2532 + yield* push(user(promptIds[1]!));
2533 + yield* push({
2534 + type: "message.part.updated",
2535 + properties: {
2536 + sessionID: root,
2537 + time: 4,
2538 + part: {
2539 + id: "prt_foreground",
2540 + sessionID: root,
2541 + messageID: "msg_foreground_assistant",
2542 + type: "text",
2543 + text: "FOREGROUND_OK",
2544 + time: { start: 4, end: 5 },
2545 + },
2546 + },
2547 + });
2548 + yield* push({
2549 + type: "message.updated",
2550 + properties: {
2551 + sessionID: root,
2552 + info: {
2553 + id: "msg_foreground_assistant",
2554 + sessionID: root,
2555 + role: "assistant",
2556 + parentID: promptIds[1]!,
2557 + time: { created: 4, completed: 5 },
2558 + },
2559 + },
2560 + });
2561 + yield* push(status("idle"));
2562 + }
2563 + if (
2564 + end === "foreground" ||
2565 + end === "foreground-buffered" ||
2566 + end === "foreground-buffered-error"
2567 + ) {
2568 + const events = yield* harness.runtime.events.pipe(
2569 + Stream.takeUntil((event) => event.type === "turn.terminal"),
2570 + Stream.runCollect,
2571 + );
2572 + const terminal = Array.from(events).find((event) => event.type === "turn.terminal");
2573 + assert.equal(terminal?.status, "completed");
2574 + assert.isTrue(
2575 + Array.from(events).some(
2576 + (event) =>
2577 + event.type === "turn_item.updated" &&
2578 + event.turnItem.type === "assistant_message" &&
2579 + event.turnItem.providerTurnId === terminal?.providerTurnId &&
2580 + event.turnItem.text === "WAKE_OK",
2581 + ),
2582 + "the foreground turn carries the wake's output",
2583 + );
2584 + assert.isTrue(
2585 + Array.from(events).some(
2586 + (event) =>
2587 + event.type === "turn_item.updated" &&
2588 + event.turnItem.type === "assistant_message" &&
2589 + event.turnItem.providerTurnId === terminal?.providerTurnId &&
2590 + event.turnItem.text === "FOREGROUND_OK",
2591 + ),
2592 + "the foreground prompt retains its own output",
2593 + );
2594 + } else {
2595 + yield* push(user("msg_background_result"));
2596 + yield* push(status("idle"));
2597 + yield* push({ type: "session.idle", properties: { sessionID: root } });
2598 + }
2599 + assert.equal(
2600 + offers.length,
2601 + state === "settled" ? 1 : 0,
2602 + "duplicate message and idle events must not offer twice",
2603 + );
2604 + const offer = offers[0];
2605 + if (offer?.dispatchIfCurrent === undefined) return;
2606 + if (
2607 + end === "stop" ||
2608 + end === "cancelled" ||
2609 + end === "stop-failure" ||
2610 + end === "cancelled-failure"
2611 + ) {
2612 + const stopping = yield* (
2613 + end === "stop" || end === "stop-failure"
2614 + ? harness.runtime.interruptTurn({
2615 + providerThread: harness.providerThread,
2616 + providerTurnId: ProviderTurnId.make("provider-turn:settled"),
2617 + requestRuntimeRestart: true,
2618 + })
2619 + : offer.onRunEndedWithoutStarting!()
2620 + ).pipe(Effect.exit, Effect.forkScoped);
2621 + yield* Effect.promise(() => abortStarted.promise);
2622 + const replacement = yield* harness
2623 + .startTurn("replacement", undefined, undefined, false, "replacement")
2624 + .pipe(Effect.exit, Effect.forkScoped);
2625 + const submittedDuringAbort = yield* TestClock.adjust(0).pipe(
2626 + Effect.andThen(Effect.sync(() => promptIds.length)),
2627 + Effect.ensuring(Effect.sync(() => abortFinished.resolve())),
2628 + );
2629 + const stopped = yield* Fiber.join(stopping);
2630 + assert.equal(Exit.isFailure(stopped), end === "stop-failure");
2631 + assert.isTrue(Exit.isSuccess(yield* Fiber.join(replacement)));
2632 + assert.isFalse(submittedWhileAborting, "old abort cannot target replacement work");
2633 + assert.equal(submittedDuringAbort, 1, "replacement waits for native cleanup");
2634 + }
2635 + assert.deepEqual(
2636 + aborted,
2637 + end === "foreground" ||
2638 + end === "foreground-buffered" ||
2639 + end === "foreground-buffered-error"
2640 + ? []
2641 + : [root, "ses_descendant"],
2642 + "an unadmitted wake cleans up its root and descendants",
2643 + );
2644 + const dispatched = yield* offer.dispatchIfCurrent(Effect.succeed("run"));
2645 + assert.isTrue(Option.isNone(dispatched), "an ended or taken wake must not start a run");
2646 + }).pipe(Effect.provide(Layer.merge(IdAllocator.layer, McpProviderSessions.layer))),
2647 + );
2648 +
2649 // OpenCode 1.18.32 background tasks complete at launch; children stay busy after root settlement.
2650 // Event order from a live 1.19.5 run: the child reports busy only after the launch completes.
2651 it.effect.each([
@@ -1402,6 +2653,11 @@ describe("OpenCodeAdapterV2", () => {
2653 { case: "is aborted", ending: "abort", outcome: "interrupted" },
2654 { case: "fails before its first turn", ending: "error", outcome: "failed" },
2655 { case: "never starts and the thread is stopped", ending: "stop", outcome: "interrupted" },
2656 + {
2657 + case: "is stopped despite a failed root abort",
2658 + ending: "stop-failure",
2659 + outcome: "interrupted",
2660 + },
2661 ])("keeps a background task's subagent running until its child $case", ({ ending, outcome }) =>
2662 Effect.gen(function* () {
2663 const nativeEvents = asyncEventStream();
@@ -1409,6 +2665,7 @@ describe("OpenCodeAdapterV2", () => {
2665 const root = "ses_root";
2666 const child = "ses_child";
2667 let promptId = "";
2668 + const aborted: Array<string> = [];
2669 const harness = yield* makeOpenCodeRuntimeHarness("background-child", root, {
2670 event: { subscribe: async () => ({ stream: nativeEvents.stream }) },
2671 session: {
@@ -1421,8 +2678,15 @@ describe("OpenCodeAdapterV2", () => {
2678 promptId = input.messageID;
2679 return { data: true };
2680 },
1424 - abort: async () => ({ data: true }),
1425 - children: async () => ({ data: [] }),
2681 + abort: async (input: { sessionID: string }) => {
2682 + aborted.push(input.sessionID);
2683 + if (ending === "stop-failure" && input.sessionID === root)
2684 + throw new Error("root abort failed");
2685 + return { data: true };
2686 + },
2687 + children: async (input: { sessionID: string }) => ({
2688 + data: input.sessionID === root ? [{ id: child }] : [],
2689 + }),
2690 },
2691 });
2692 const hasPendingBackgroundWork = harness.runtime.hasPendingBackgroundWork;
@@ -1487,7 +2751,7 @@ describe("OpenCodeAdapterV2", () => {
2751 },
2752 });
2753 yield* push(taskPart("running"));
1490 - const starts = ending !== "stop" && ending !== "error";
2754 + const starts = ending !== "stop" && ending !== "stop-failure" && ending !== "error";
2755 if (starts) {
2756 yield* push({
2757 type: "message.updated",
@@ -1502,12 +2766,26 @@ describe("OpenCodeAdapterV2", () => {
2766 yield* push(status(root, "idle"));
2767 assert.equal(yield* hasPendingBackgroundWork, starts, "a running child pins idle release");
2768
1505 - if (ending === "stop") {
1506 - yield* harness.runtime.interruptTurn({
1507 - providerThread: harness.providerThread,
1508 - providerTurnId: ProviderTurnId.make("provider-turn:settled"),
1509 - requestRuntimeRestart: true,
1510 - });
2769 + if (ending === "stop" || ending === "stop-failure") {
2770 + if (ending === "stop-failure") {
2771 + yield* push({
2772 + type: "message.updated",
2773 + properties: {
2774 + sessionID: root,
2775 + info: { id: "msg_wake", sessionID: root, role: "user", time: { created: 4 } },
2776 + },
2777 + });
2778 + yield* push(status(root, "busy"));
2779 + }
2780 + const stopped = yield* harness.runtime
2781 + .interruptTurn({
2782 + providerThread: harness.providerThread,
2783 + providerTurnId: ProviderTurnId.make("provider-turn:settled"),
2784 + requestRuntimeRestart: true,
2785 + })
2786 + .pipe(Effect.exit);
2787 + assert.equal(Exit.isFailure(stopped), ending === "stop-failure");
2788 + assert.include(aborted, child, "root abort failure must not skip native child cleanup");
2789 } else {
2790 if (ending !== "idle") {
2791 yield* push({
packages/provider-opencode/src/server/adapter.ts
+589 -191
@@ -68,6 +68,7 @@ import { buildRuntimeInstructions } from "@t3tools/provider-core/server/runtimeI
68 import * as OpenCodeRuntime from "./OpenCodeRuntime.ts";
69 import { readableProviderErrorMessage } from "./providerErrorMessage.ts";
70 import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
71 +import * as ProviderContinuationRequests from "@t3tools/provider-core/server/ProviderContinuationRequests";
72 import { makeProviderFailure } from "@t3tools/provider-core/server/failure";
73 import { turnScopedSelectionTransition } from "@t3tools/provider-core/server/selectionTransition";
74 import { providerMessageTextWithAttachmentPaths } from "@t3tools/provider-core/server/attachmentPrompt";
@@ -304,6 +305,8 @@ interface ActiveOpenCodeTurn {
305 nextItemOrdinal: number;
306 nativeUserMessageId: string | null;
307 admissionMessageId: string | null;
308 + readonly priorWakePromptIds: Set<string>;
309 + priorWakeSettled: Deferred.Deferred<void> | null;
310 interrupted: boolean;
311 finalized: boolean;
312 contextOverflow: OrchestrationV2ProviderFailure | null;
@@ -400,6 +403,16 @@ interface OpenCodeSubagentContext {
403 launch: ToolPart | null;
404 }
405
406 +/** Root work OpenCode began with no T3 turn, such as a background task's result; held until a run admits it. */
407 +interface OpenCodeWake {
408 + readonly events: Array<OpenCodeEvent>;
409 + // A user message alone can be a late update; only a busy root is work worth a run.
410 + offered: boolean;
411 + cancelling: boolean;
412 + readonly admission: Deferred.Deferred<boolean>;
413 + settled: Deferred.Deferred<void>;
414 +}
415 +
416 interface OpenCodeThreadState {
417 readonly nativeSessionId: string;
418 providerThread: OrchestrationV2ProviderThread;
@@ -413,6 +426,8 @@ interface OpenCodeThreadState {
426 // null: a child resumed after a restart, whose next ordinal is recovered from OpenCode.
427 nextChildTurnOrdinal: number | null;
428 nextAdmissionGeneration: number;
429 + wake: OpenCodeWake | null;
430 + readonly lifecyclePermit: Semaphore.Semaphore;
431 permission: PermissionRuleset;
432 /** Parent rules last written into this child's `permission`; empty for root sessions. */
433 inheritedPermission: PermissionRuleset;
@@ -907,6 +922,26 @@ function terminalStatusForError(
922 return turn.interrupted || isMessageAbortedError(event) ? "interrupted" : "failed";
923 }
924
925 +// Events of one session's work; other events update adapter bookkeeping and are never held.
926 +function sessionWorkEventSessionId(event: OpenCodeEvent): string | undefined {
927 + switch (event.type) {
928 + case "message.part.updated":
929 + return event.properties.part.sessionID;
930 + case "message.updated":
931 + case "message.part.delta":
932 + case "todo.updated":
933 + case "session.compacted":
934 + case "session.status":
935 + case "session.idle":
936 + case "session.error":
937 + case "permission.asked":
938 + case "question.asked":
939 + return event.properties.sessionID;
940 + default:
941 + return undefined;
942 + }
943 +}
944 +
945 function isMessageAbortedError(event: Extract<OpenCodeEvent, { type: "session.error" }>): boolean {
946 return event.properties.error?.name === "MessageAbortedError";
947 }
@@ -990,6 +1025,7 @@ export const makeOpenCodeAdapterV2 = Effect.fn("makeOpenCodeAdapterV2")(function
1025 const idAllocator = yield* IdAllocator.IdAllocatorV2;
1026 const host = yield* ProviderHost.ProviderHost;
1027 const mcpSessions = yield* McpProviderSessions.McpProviderSessions;
1028 + const continuationRequests = yield* ProviderContinuationRequests.ProviderContinuationRequests;
1029 const messageIdClock = yield* Ref.make({ epochMillis: -1, counter: 0 });
1030
1031 return ProviderAdapter.ProviderAdapterV2.of({
@@ -1083,6 +1119,8 @@ export const makeOpenCodeAdapterV2 = Effect.fn("makeOpenCodeAdapterV2")(function
1119 const abortController = new AbortController();
1120 let closing = false;
1121 let hasConnected = false;
1122 + // Orders native events with turn installation, so a held wake replays before later events.
1123 + const eventPermit = Semaphore.makeUnsafe(1);
1124
1125 const emitProviderEvent = (event: ProviderAdapter.ProviderAdapterV2Event) =>
1126 Queue.offer(events, event).pipe(Effect.asVoid);
@@ -1519,6 +1557,8 @@ export const makeOpenCodeAdapterV2 = Effect.fn("makeOpenCodeAdapterV2")(function
1557 parentSubagent: context,
1558 nextChildTurnOrdinal,
1559 nextAdmissionGeneration: 1,
1560 + wake: null,
1561 + lifecyclePermit: Semaphore.makeUnsafe(1),
1562 permission: childPermission,
1563 inheritedPermission: openCodePermissionRules(turn.runtimePolicy),
1564 });
@@ -2195,114 +2235,130 @@ export const makeOpenCodeAdapterV2 = Effect.fn("makeOpenCodeAdapterV2")(function
2235 readonly threadDisposition?: "reusable" | "broken";
2236 },
2237 ) {
2198 - if (turn.finalized) return;
2199 - if (nativeStreamFailure !== null) {
2200 - status = "failed";
2201 - terminal = { failure: nativeStreamFailure, threadDisposition: "broken" };
2202 - }
2203 - let lastError = sessionEntity.lastError;
2204 - if (status === "completed" && turn.contextOverflow !== null) {
2205 - status = "failed";
2206 - terminal = { failure: turn.contextOverflow };
2207 - lastError = turn.contextOverflow.message;
2208 - }
2209 - turn.finalized = true;
2210 - const completedAt = yield* DateTime.now;
2211 - for (const part of turn.parts.values()) {
2212 - if (part.type === "text" || part.type === "reasoning") {
2213 - yield* emitTextPart(state, turn, part, true);
2214 - }
2215 - }
2216 - for (const pending of Array.from(pendingRequests.values())) {
2217 - if (
2218 - pending.turn.providerTurnId === turn.providerTurnId ||
2219 - pending.nativeSessionId === state.nativeSessionId
2220 - ) {
2221 - yield* resolveRuntimeRequest(pending.nativeRequestId, "cancelled");
2222 - }
2223 - }
2224 - // Prompts read the catalog only for variants; a completed turn needs its context window.
2225 - const parsedModel = OpenCodeRuntime.parseOpenCodeModelSlug(turn.modelSelection.model);
2226 - if (status === "completed" && turn.usage.lastStep !== null && parsedModel !== null) {
2227 - yield* OpenCodeRuntime.readOpenCodeCatalogModel(
2228 - client,
2229 - parsedModel,
2230 - undefined,
2231 - variantCache,
2232 - );
2233 - }
2234 - yield* emitProviderTurn(state, turn, status, completedAt);
2235 - const threadDisposition = terminal?.threadDisposition ?? "reusable";
2236 - yield* updateProviderThread(state, {
2237 - status: turn.isRoot ? "active" : threadDisposition === "broken" ? "error" : "idle",
2238 - nativeConversationHeadRef:
2239 - turn.nativeUserMessageId === null
2240 - ? state.providerThread.nativeConversationHeadRef
2241 - : providerRef(turn.nativeUserMessageId, "weak"),
2242 - });
2243 - state.activeTurn = null;
2244 - if (!turn.isRoot) {
2245 - yield* emitProviderEvent({
2246 - type: "node.updated",
2247 - driver: OPENCODE_PROVIDER,
2248 - node: {
2249 - id: turn.rootNodeId,
2250 - threadId: turn.threadId,
2251 - runId: null,
2252 - parentNodeId: null,
2253 - rootNodeId: turn.rootNodeId,
2254 - kind: "root_turn",
2255 - status,
2256 - countsForRun: false,
2257 - providerThreadId: state.providerThread.id,
2258 - providerTurnId: turn.providerTurnId,
2259 - nativeItemRef: providerRef(state.nativeSessionId),
2260 - runtimeRequestId: null,
2261 - checkpointScopeId: null,
2262 - startedAt: turn.startedAt,
2263 - completedAt,
2264 - },
2265 - });
2266 - return;
2267 - }
2268 - const anotherTurnIsActive = Array.from(threads.values()).some(
2269 - (candidate) => candidate.activeTurn?.isRoot === true,
2270 - );
2271 - yield* updateProviderSession(
2272 - anotherTurnIsActive ? "running" : status === "failed" ? "error" : "ready",
2273 - status === "failed" ? lastError : null,
2274 - );
2275 - yield* emitProviderEvent(
2276 - status === "failed"
2277 - ? {
2278 - type: "turn.terminal",
2279 - driver: OPENCODE_PROVIDER,
2280 - providerThreadId: turn.providerThreadId,
2281 - providerTurnId: turn.providerTurnId,
2282 - runOrdinal: turn.runOrdinal,
2283 - failureItemOrdinal: itemOrdinal(turn, `terminal-failure:${turn.providerTurnId}`),
2284 - status,
2285 - failure:
2286 - terminal?.failure ??
2287 - makeProviderFailure({
2288 - message: sessionEntity.lastError ?? undefined,
2289 - class: "provider_error",
2290 - }),
2291 - threadDisposition,
2238 + // Once claimed, terminal publication must finish even if the routing budget expires.
2239 + return yield* Effect.uninterruptibleMask((restore) =>
2240 + Effect.gen(function* () {
2241 + if (turn.finalized) return;
2242 + if (nativeStreamFailure !== null) {
2243 + status = "failed";
2244 + terminal = { failure: nativeStreamFailure, threadDisposition: "broken" };
2245 + }
2246 + let lastError = sessionEntity.lastError;
2247 + if (status === "completed" && turn.contextOverflow !== null) {
2248 + status = "failed";
2249 + terminal = { failure: turn.contextOverflow };
2250 + lastError = turn.contextOverflow.message;
2251 + }
2252 + turn.finalized = true;
2253 + if (turn.priorWakeSettled !== null)
2254 + yield* Deferred.succeed(turn.priorWakeSettled, undefined);
2255 + const completedAt = yield* DateTime.now;
2256 + for (const part of turn.parts.values()) {
2257 + if (part.type === "text" || part.type === "reasoning") {
2258 + yield* emitTextPart(state, turn, part, true);
2259 }
2293 - : {
2294 - type: "turn.terminal",
2260 + }
2261 + for (const pending of Array.from(pendingRequests.values())) {
2262 + if (
2263 + pending.turn.providerTurnId === turn.providerTurnId ||
2264 + pending.nativeSessionId === state.nativeSessionId
2265 + ) {
2266 + yield* resolveRuntimeRequest(pending.nativeRequestId, "cancelled");
2267 + }
2268 + }
2269 + // Prompts read the catalog only for variants; a completed turn needs its context window.
2270 + const parsedModel = OpenCodeRuntime.parseOpenCodeModelSlug(turn.modelSelection.model);
2271 + if (status === "completed" && turn.usage.lastStep !== null && parsedModel !== null) {
2272 + yield* restore(
2273 + OpenCodeRuntime.readOpenCodeCatalogModel(
2274 + client,
2275 + parsedModel,
2276 + undefined,
2277 + variantCache,
2278 + ),
2279 + ).pipe(Effect.exit);
2280 + }
2281 + yield* emitProviderTurn(state, turn, status, completedAt);
2282 + const threadDisposition = terminal?.threadDisposition ?? "reusable";
2283 + yield* updateProviderThread(state, {
2284 + status: turn.isRoot ? "active" : threadDisposition === "broken" ? "error" : "idle",
2285 + nativeConversationHeadRef:
2286 + turn.nativeUserMessageId === null
2287 + ? state.providerThread.nativeConversationHeadRef
2288 + : providerRef(turn.nativeUserMessageId, "weak"),
2289 + });
2290 + state.activeTurn = null;
2291 + if (!turn.isRoot) {
2292 + yield* emitProviderEvent({
2293 + type: "node.updated",
2294 driver: OPENCODE_PROVIDER,
2296 - providerThreadId: turn.providerThreadId,
2297 - providerTurnId: turn.providerTurnId,
2298 - runOrdinal: turn.runOrdinal,
2299 - status,
2300 - failure: null,
2301 - threadDisposition,
2302 - },
2295 + node: {
2296 + id: turn.rootNodeId,
2297 + threadId: turn.threadId,
2298 + runId: null,
2299 + parentNodeId: null,
2300 + rootNodeId: turn.rootNodeId,
2301 + kind: "root_turn",
2302 + status,
2303 + countsForRun: false,
2304 + providerThreadId: state.providerThread.id,
2305 + providerTurnId: turn.providerTurnId,
2306 + nativeItemRef: providerRef(state.nativeSessionId),
2307 + runtimeRequestId: null,
2308 + checkpointScopeId: null,
2309 + startedAt: turn.startedAt,
2310 + completedAt,
2311 + },
2312 + });
2313 + return;
2314 + }
2315 + const anotherTurnIsActive = Array.from(threads.values()).some(
2316 + (candidate) => candidate.activeTurn?.isRoot === true,
2317 + );
2318 + yield* updateProviderSession(
2319 + anotherTurnIsActive ? "running" : status === "failed" ? "error" : "ready",
2320 + status === "failed" ? lastError : null,
2321 + );
2322 + yield* emitProviderEvent(
2323 + status === "failed"
2324 + ? {
2325 + type: "turn.terminal",
2326 + driver: OPENCODE_PROVIDER,
2327 + providerThreadId: turn.providerThreadId,
2328 + providerTurnId: turn.providerTurnId,
2329 + runOrdinal: turn.runOrdinal,
2330 + failureItemOrdinal: itemOrdinal(
2331 + turn,
2332 + `terminal-failure:${turn.providerTurnId}`,
2333 + ),
2334 + status,
2335 + failure:
2336 + terminal?.failure ??
2337 + makeProviderFailure({
2338 + message: sessionEntity.lastError ?? undefined,
2339 + class: "provider_error",
2340 + }),
2341 + threadDisposition,
2342 + }
2343 + : {
2344 + type: "turn.terminal",
2345 + driver: OPENCODE_PROVIDER,
2346 + providerThreadId: turn.providerThreadId,
2347 + providerTurnId: turn.providerTurnId,
2348 + runOrdinal: turn.runOrdinal,
2349 + status,
2350 + failure: null,
2351 + threadDisposition,
2352 + },
2353 + );
2354 + }),
2355 );
2356 });
2357
2358 + // A call, not inline checks: TS keeps earlier narrowing of these mutable fields across yields.
2359 + const turnIsLive = (state: OpenCodeThreadState, turn: ActiveOpenCodeTurn) =>
2360 + state.activeTurn === turn && !turn.finalized && !turn.interrupted;
2361 +
2362 const promptAdmissionIsCurrent = (
2363 state: OpenCodeThreadState,
2364 turn: ActiveOpenCodeTurn,
@@ -2438,6 +2494,8 @@ export const makeOpenCodeAdapterV2 = Effect.fn("makeOpenCodeAdapterV2")(function
2494 nextItemOrdinal: 1,
2495 nativeUserMessageId: message.id,
2496 admissionMessageId: null,
2497 + priorWakePromptIds: new Set(),
2498 + priorWakeSettled: null,
2499 interrupted: false,
2500 finalized: false,
2501 contextOverflow: null,
@@ -2701,6 +2759,7 @@ export const makeOpenCodeAdapterV2 = Effect.fn("makeOpenCodeAdapterV2")(function
2759
2760 const handleAssistantCompleted = Effect.fnUntraced(function* (
2761 event: Extract<OpenCodeEvent, { type: "message.updated" }>,
2762 + admitsPrompt = true,
2763 ) {
2764 const message = event.properties.info;
2765 if (message.role !== "assistant" || message.time.completed === undefined) return;
@@ -2708,7 +2767,9 @@ export const makeOpenCodeAdapterV2 = Effect.fn("makeOpenCodeAdapterV2")(function
2767 const turn = state?.activeTurn;
2768 if (state === undefined || turn === null || turn === undefined) return;
2769 // Versions may ignore supplied message IDs; completed assistant output admits settlement on idle.
2711 - advanceOpenCodePromptAdmission(turn, "assistant-completed");
2770 + if (admitsPrompt && !turn.priorWakePromptIds.has(message.parentID ?? "")) {
2771 + advanceOpenCodePromptAdmission(turn, "assistant-completed");
2772 + }
2773 for (const partId of turn.partIdsByMessage.get(message.id) ?? []) {
2774 const part = turn.parts.get(partId);
2775 if (part?.type === "text" || part?.type === "reasoning") {
@@ -2717,6 +2778,185 @@ export const makeOpenCodeAdapterV2 = Effect.fn("makeOpenCodeAdapterV2")(function
2778 }
2779 });
2780
2781 + const abortRootSession = (state: OpenCodeThreadState) =>
2782 + sdkCall("session.abort", { sessionID: state.nativeSessionId }, (signal) =>
2783 + client.session.abort({ sessionID: state.nativeSessionId }, { signal }),
2784 + ).pipe(Effect.timeout("10 seconds"));
2785 +
2786 + // Native aborts target the whole session, so replacement admission waits for all cleanup.
2787 + const cleanupSessionWork = Effect.fn("OpencodeAdapter.cleanupSessionWork")(function* (
2788 + state: OpenCodeThreadState,
2789 + rootAbort: Effect.Effect<unknown, Effect.Error<ReturnType<typeof abortRootSession>>>,
2790 + ) {
2791 + const root = yield* rootAbort.pipe(Effect.result);
2792 + const descendants = yield* abortDescendants(state.nativeSessionId).pipe(Effect.result);
2793 + yield* interruptLaunchedSubagents(state.nativeSessionId);
2794 + if (root._tag === "Failure") return yield* root.failure;
2795 + if (descendants._tag === "Failure") return yield* descendants.failure;
2796 + });
2797 +
2798 + const cancelWake = Effect.fn("OpencodeAdapter.cancelWake")(
2799 + function* (state: OpenCodeThreadState, wake: OpenCodeWake) {
2800 + if (closing || nativeStreamFailure !== null || state.wake !== wake) return;
2801 + wake.cancelling = true;
2802 + // prompt.ts publishes its user message before run-state.ts registers a cancellable runner.
2803 + // A noReply prompt saves one and never runs, so an undecided wake is aborted anyway.
2804 + const running =
2805 + wake.offered ||
2806 + (yield* Deferred.await(wake.admission).pipe(
2807 + Effect.timeoutOption("10 seconds"),
2808 + Effect.map(Option.getOrElse(() => true)),
2809 + ));
2810 + yield* cleanupSessionWork(state, running ? abortRootSession(state) : Effect.void).pipe(
2811 + Effect.tapError(() =>
2812 + Effect.gen(function* () {
2813 + if (yield* Deferred.isDone(wake.settled)) return;
2814 + nativeStreamFailure = makeProviderFailure({
2815 + message:
2816 + "OpenCode cancellation failed before native idle; reconnect the provider session.",
2817 + class: "transport_error",
2818 + });
2819 + yield* updateProviderSession("error", nativeStreamFailure.message);
2820 + }),
2821 + ),
2822 + );
2823 + },
2824 + (effect, state, wake) =>
2825 + effect.pipe(
2826 + Effect.ensuring(
2827 + Effect.sync(() => {
2828 + if (state.wake === wake) state.wake = null;
2829 + }),
2830 + ),
2831 + ),
2832 + );
2833 +
2834 + const stopWake = (state: OpenCodeThreadState, wake: OpenCodeWake) =>
2835 + state.lifecyclePermit.withPermit(
2836 + cancelWake(state, wake).pipe(Effect.ignore({ log: true })),
2837 + );
2838 +
2839 + const offerWake = (state: OpenCodeThreadState, wake: OpenCodeWake, threadId: ThreadId) =>
2840 + continuationRequests.offer({
2841 + threadId,
2842 + providerThreadId: state.providerThread.id,
2843 + driver: OPENCODE_PROVIDER,
2844 + detail: null,
2845 + delivery: "adapter_buffered",
2846 + dispatchIfCurrent: (dispatch) =>
2847 + eventPermit.withPermit(
2848 + Effect.suspend(() =>
2849 + state.wake === wake &&
2850 + !wake.cancelling &&
2851 + !closing &&
2852 + nativeStreamFailure === null
2853 + ? Effect.asSome(dispatch)
2854 + : Effect.succeedNone,
2855 + ),
2856 + ),
2857 + clearIfCurrent: () => stopWake(state, wake),
2858 + onRunEndedWithoutStarting: () => stopWake(state, wake),
2859 + });
2860 +
2861 + // Callers hold eventPermit. A root user message with no T3 turn starts a wake; its work stays
2862 + // held, with that of children no turn has claimed yet, until startTurn takes it.
2863 + const acceptEvent = Effect.fnUntraced(function* (event: OpenCodeEvent) {
2864 + const sessionId = sessionWorkEventSessionId(event);
2865 + const owner =
2866 + sessionId === undefined
2867 + ? undefined
2868 + : (threads.get(sessionId) ?? relatedSessionOwners.get(sessionId));
2869 + if (owner === undefined || sessionId === undefined) return yield* routeEvent(event);
2870 + const wake = owner.wake;
2871 + const isRoot = sessionId === owner.nativeSessionId;
2872 + const rootStatus =
2873 + isRoot && event.type === "session.status" ? event.properties.status.type : undefined;
2874 + // A later execution buffered into the same wake is unsettled until its own idle. Its new
2875 + // user message comes before busy, while prompt.ts may still be registering it.
2876 + const newRootUserMessage =
2877 + wake !== null &&
2878 + isRoot &&
2879 + event.type === "message.updated" &&
2880 + event.properties.info.role === "user" &&
2881 + !wake.events.some(
2882 + (held) =>
2883 + held.type === "message.updated" &&
2884 + held.properties.info.id === event.properties.info.id,
2885 + );
2886 + if (
2887 + wake !== null &&
2888 + (rootStatus === "busy" || rootStatus === "retry" || newRootUserMessage) &&
2889 + (yield* Deferred.isDone(wake.settled))
2890 + ) {
2891 + wake.settled = Deferred.makeUnsafe<void>();
2892 + }
2893 + if (wake?.cancelling) {
2894 + if (!isRoot) return yield* routeEvent(event);
2895 + wake.events.push(event);
2896 + if (isRoot && (rootStatus === "busy" || rootStatus === "retry")) {
2897 + wake.offered = true;
2898 + yield* Deferred.succeed(wake.admission, true);
2899 + } else if (
2900 + isRoot &&
2901 + (rootStatus === "idle" ||
2902 + event.type === "session.idle" ||
2903 + // OpenCode stays busy and auto-compacts after an overflow.
2904 + (event.type === "session.error" &&
2905 + event.properties.error?.name !== "ContextOverflowError"))
2906 + ) {
2907 + yield* Deferred.succeed(wake.admission, false);
2908 + yield* Deferred.succeed(wake.settled, undefined);
2909 + }
2910 + return;
2911 + }
2912 + if (wake !== null && isRoot && (rootStatus === "idle" || event.type === "session.idle")) {
2913 + yield* Deferred.succeed(wake.settled, undefined);
2914 + }
2915 + // Idle before busy: nothing ran, so the held user message was only an update.
2916 + if (
2917 + wake !== null &&
2918 + !wake.offered &&
2919 + isRoot &&
2920 + (rootStatus === "idle" ||
2921 + event.type === "session.idle" ||
2922 + event.type === "session.error")
2923 + ) {
2924 + yield* Deferred.succeed(wake.admission, false);
2925 + owner.wake = null;
2926 + } else if (wake !== null && (wake.offered || isRoot)) {
2927 + wake.events.push(event);
2928 + if (!wake.offered && (rootStatus === "busy" || rootStatus === "retry")) {
2929 + wake.offered = true;
2930 + yield* Deferred.succeed(wake.admission, true);
2931 + const threadId = owner.providerThread.appThreadId;
2932 + if (threadId !== null) yield* offerWake(owner, wake, threadId);
2933 + }
2934 + return;
2935 + }
2936 + if (
2937 + event.type === "message.updated" &&
2938 + event.properties.info.role === "user" &&
2939 + isRoot &&
2940 + owner.parentSubagent === null &&
2941 + owner.activeTurn === null &&
2942 + owner.providerThread.appThreadId !== null &&
2943 + !owner.userMessageIds.includes(event.properties.info.id) &&
2944 + !closing &&
2945 + nativeStreamFailure === null
2946 + ) {
2947 + owner.userMessageIds.push(event.properties.info.id);
2948 + owner.wake = {
2949 + events: [event],
2950 + offered: false,
2951 + cancelling: false,
2952 + admission: Deferred.makeUnsafe<boolean>(),
2953 + settled: Deferred.makeUnsafe<void>(),
2954 + };
2955 + return;
2956 + }
2957 + yield* routeEvent(event);
2958 + });
2959 +
2960 const handleEvent = Effect.fnUntraced(function* (event: OpenCodeEvent) {
2961 yield* logProtocolEvent({
2962 direction: "incoming",
@@ -2724,6 +2964,25 @@ export const makeOpenCodeAdapterV2 = Effect.fn("makeOpenCodeAdapterV2")(function
2964 method: event.type,
2965 payload: event,
2966 });
2967 + // A slow native call only delays events, as on main; Stop goes through lifecyclePermit.
2968 + yield* eventPermit.withPermit(acceptEvent(event));
2969 + });
2970 +
2971 + const routeEvent = Effect.fnUntraced(function* (
2972 + event: OpenCodeEvent,
2973 + historicalRootSessionId?: string,
2974 + ) {
2975 + const historicalRoot =
2976 + historicalRootSessionId !== undefined &&
2977 + sessionWorkEventSessionId(event) === historicalRootSessionId;
2978 + // A foreground prompt inherits held output, but has not submitted its own native work yet.
2979 + if (
2980 + historicalRoot &&
2981 + (event.type === "session.status" ||
2982 + event.type === "session.idle" ||
2983 + event.type === "session.error")
2984 + )
2985 + return;
2986 switch (event.type) {
2987 case "server.connected":
2988 if (hasConnected) {
@@ -2735,7 +2994,7 @@ export const makeOpenCodeAdapterV2 = Effect.fn("makeOpenCodeAdapterV2")(function
2994 return;
2995 case "message.updated":
2996 yield* handleMessageUpdated(event);
2738 - yield* handleAssistantCompleted(event);
2997 + yield* handleAssistantCompleted(event, !historicalRoot);
2998 return;
2999 case "session.compacted": {
3000 const state = threads.get(event.properties.sessionID);
@@ -2823,6 +3082,12 @@ export const makeOpenCodeAdapterV2 = Effect.fn("makeOpenCodeAdapterV2")(function
3082 return;
3083 }
3084 if (event.properties.status.type === "idle" && state.activeTurn !== null) {
3085 + if (state.activeTurn.priorWakeSettled !== null) {
3086 + if (state.activeTurn.contextOverflow !== null) {
3087 + yield* finalizeTurn(state, state.activeTurn, "completed");
3088 + } else yield* Deferred.succeed(state.activeTurn.priorWakeSettled, undefined);
3089 + return;
3090 + }
3091 if (state.activeTurn.admissionPending) {
3092 advanceOpenCodePromptAdmission(state.activeTurn, "idle");
3093 return;
@@ -2843,6 +3108,12 @@ export const makeOpenCodeAdapterV2 = Effect.fn("makeOpenCodeAdapterV2")(function
3108 unstartedSessionIds.delete(event.properties.sessionID);
3109 const state = threads.get(event.properties.sessionID);
3110 if (state?.activeTurn !== null && state?.activeTurn !== undefined) {
3111 + if (state.activeTurn.priorWakeSettled !== null) {
3112 + if (state.activeTurn.contextOverflow !== null) {
3113 + yield* finalizeTurn(state, state.activeTurn, "completed");
3114 + } else yield* Deferred.succeed(state.activeTurn.priorWakeSettled, undefined);
3115 + return;
3116 + }
3117 if (state.activeTurn.admissionPending) {
3118 state.activeTurn.admissionStatusSequence++;
3119 advanceOpenCodePromptAdmission(state.activeTurn, "idle");
@@ -2954,6 +3225,8 @@ export const makeOpenCodeAdapterV2 = Effect.fn("makeOpenCodeAdapterV2")(function
3225 });
3226 yield* updateProviderSession("error", detail);
3227 for (const state of threads.values()) {
3228 + // No continuation can admit a wake this stream will never finish.
3229 + state.wake = null;
3230 if (state.activeTurn !== null)
3231 yield* finalizeTurn(state, state.activeTurn, "failed", {
3232 failure: makeProviderFailure({ message: detail, class: "transport_error" }),
@@ -2974,8 +3247,13 @@ export const makeOpenCodeAdapterV2 = Effect.fn("makeOpenCodeAdapterV2")(function
3247 ? Effect.void
3248 : Effect.gen(function* () {
3249 const detail = `OpenCode server exited unexpectedly (${code}).`;
3250 + nativeStreamFailure = makeProviderFailure({
3251 + message: detail,
3252 + class: "transport_error",
3253 + });
3254 yield* updateProviderSession("error", detail);
3255 for (const state of threads.values()) {
3256 + state.wake = null;
3257 if (state.activeTurn !== null) {
3258 yield* finalizeTurn(state, state.activeTurn, "failed", {
3259 failure: makeProviderFailure({
@@ -3021,6 +3299,7 @@ export const makeOpenCodeAdapterV2 = Effect.fn("makeOpenCodeAdapterV2")(function
3299 scope,
3300 Effect.sync(() => {
3301 closing = true;
3302 + for (const state of threads.values()) state.wake = null;
3303 }),
3304 );
3305
@@ -3050,6 +3329,8 @@ export const makeOpenCodeAdapterV2 = Effect.fn("makeOpenCodeAdapterV2")(function
3329 parentSubagent,
3330 nextChildTurnOrdinal: 1,
3331 nextAdmissionGeneration: 1,
3332 + wake: null,
3333 + lifecyclePermit: Semaphore.makeUnsafe(1),
3334 permission: nativeSession.permission ?? [],
3335 inheritedPermission: parentSubagent?.parentState.permission ?? [],
3336 };
@@ -3307,7 +3588,11 @@ export const makeOpenCodeAdapterV2 = Effect.fn("makeOpenCodeAdapterV2")(function
3588 providerSessionId: input.providerSessionId,
3589 providerSession: sessionEntity,
3590 events: Stream.fromEffectRepeat(Queue.take(events)),
3310 - hasPendingBackgroundWork: Effect.sync(() => busySessionIds.size > 0),
3591 + hasPendingBackgroundWork: Effect.sync(
3592 + () =>
3593 + busySessionIds.size > 0 ||
3594 + Array.from(threads.values()).some((state) => state.wake?.offered === true),
3595 + ),
3596 ensureThread: Effect.fn("OpencodeAdapter.ensureThread")(
3597 function* (threadInput) {
3598 if (threadInput.existingProviderThread?.nativeThreadRef != null) {
@@ -3398,7 +3683,7 @@ export const makeOpenCodeAdapterV2 = Effect.fn("makeOpenCodeAdapterV2")(function
3683 resumeTurn: (input) => runtimeSession.startTurn(ProviderAdapter.resumeTurnInput(input)),
3684 startTurn: Effect.fn("OpencodeAdapter.startTurn")(
3685 function* (turnInput) {
3401 - if (nativeStreamFailure !== null) {
3686 + if (closing || nativeStreamFailure !== null) {
3687 return yield* protocolError(
3688 "OpenCode event stream has ended; reconnect the provider session before starting another turn.",
3689 );
@@ -3415,6 +3700,9 @@ export const makeOpenCodeAdapterV2 = Effect.fn("makeOpenCodeAdapterV2")(function
3700 reason: "previous_turn_active",
3701 });
3702 }
3703 + const continuation =
3704 + turnInput.message.createdBy === "agent" &&
3705 + turnInput.message.creationSource === "provider";
3706 const parsedModel = OpenCodeRuntime.parseOpenCodeModelSlug(
3707 turnInput.modelSelection.model,
3708 );
@@ -3424,10 +3712,13 @@ export const makeOpenCodeAdapterV2 = Effect.fn("makeOpenCodeAdapterV2")(function
3712 );
3713 }
3714 yield* applyPermissionRules(state, turnInput.runtimePolicy);
3715 + // A continuation admits a wake OpenCode is already running, so it sends no prompt.
3716 const isCompaction =
3717 + !continuation &&
3718 turnInput.message.text.trim() === "/compact" &&
3719 turnInput.message.attachments.length === 0;
3430 - const parts = isCompaction ? [] : yield* resolvePromptParts(turnInput);
3720 + const parts =
3721 + isCompaction || continuation ? [] : yield* resolvePromptParts(turnInput);
3722 const startedAt = yield* DateTime.now;
3723 const syntheticNativeTurnId = `${sessionId}:attempt:${turnInput.attemptId}`;
3724 const providerTurnId = idAllocator.derive.providerTurn({
@@ -3445,20 +3736,9 @@ export const makeOpenCodeAdapterV2 = Effect.fn("makeOpenCodeAdapterV2")(function
3736 startedAt,
3737 completedAt: null,
3738 };
3448 - const admissionMessageId = yield* makeOpenCodeMessageId(messageIdClock);
3449 - // Do not yield before turn installation; EOF may otherwise finish scanning before registration.
3450 - if (nativeStreamFailure !== null) {
3451 - return yield* protocolError(
3452 - "OpenCode event stream has ended; reconnect the provider session before starting another turn.",
3453 - );
3454 - }
3455 - if (state.activeTurn !== null) {
3456 - return yield* new ProviderAdapter.ProviderAdapterProtocolError({
3457 - driver: OPENCODE_PROVIDER,
3458 - detail: `OpenCode provider thread ${turnInput.providerThread.id} already has an active turn`,
3459 - reason: "previous_turn_active",
3460 - });
3461 - }
3739 + const admissionMessageId = continuation
3740 + ? null
3741 + : yield* makeOpenCodeMessageId(messageIdClock);
3742 const turn: ActiveOpenCodeTurn = {
3743 isRoot: true,
3744 threadId: turnInput.threadId,
@@ -3480,36 +3760,125 @@ export const makeOpenCodeAdapterV2 = Effect.fn("makeOpenCodeAdapterV2")(function
3760 nextItemOrdinal: turnInput.providerTurnOrdinal * 100 + 1,
3761 nativeUserMessageId: null,
3762 admissionMessageId,
3763 + priorWakePromptIds: new Set(),
3764 + priorWakeSettled: null,
3765 interrupted: false,
3766 finalized: false,
3767 contextOverflow: null,
3768 planId: null,
3769 admissionGeneration: state.nextAdmissionGeneration++,
3770 admissionReconciliationGeneration: null,
3489 - admissionPending: !isCompaction,
3490 - admissionAccepted: isCompaction,
3771 + admissionPending: !isCompaction && !continuation,
3772 + admissionAccepted: isCompaction || continuation,
3773 admissionMessageObserved: false,
3774 idleDuringAdmission: false,
3775 admissionUncertain: false,
3776 admissionStatusSequence: 0,
3777 admissionSettled: Deferred.makeUnsafe<void>(),
3496 - // @effect-diagnostics-next-line abortControllerInEffect:off - Turn interruption owns prompt admission cancellation.
3497 - admissionAbortController: new AbortController(),
3778 + admissionAbortController: continuation
3779 + ? null
3780 + : // @effect-diagnostics-next-line abortControllerInEffect:off - Turn interruption owns prompt admission cancellation.
3781 + new AbortController(),
3782 };
3783 if (turn.admissionMessageId !== null)
3784 turn.usage.promptMessageIds.add(turn.admissionMessageId);
3785 const admissionSettled = turn.admissionSettled;
3786 const admissionAbortController = turn.admissionAbortController;
3503 - state.appThread = turnInput.appThread;
3504 - state.activeTurn = turn;
3505 - state.providerTurns.set(String(providerTurnId), providerTurn);
3506 - yield* emitProviderTurn(state, turn, "running", null);
3507 - yield* updateProviderThread(state, {
3508 - status: "active",
3509 - firstRunOrdinal: state.providerThread.firstRunOrdinal ?? turnInput.runOrdinal,
3510 - lastRunOrdinal: turnInput.runOrdinal,
3511 - });
3512 - yield* updateProviderSession("running", null);
3787 + yield* state.lifecyclePermit.withPermit(
3788 + Effect.gen(function* () {
3789 + const candidate = state.wake;
3790 + if (!continuation && candidate !== null && !candidate.offered) {
3791 + // A noReply prompt saves a user message and never runs; OpenCode queues a
3792 + // prompt behind a loop that did start, so the foreground submits either way.
3793 + const admission = yield* Deferred.await(candidate.admission).pipe(
3794 + Effect.timeoutOption("10 seconds"),
3795 + );
3796 + if (Option.isNone(admission) && state.wake === candidate) state.wake = null;
3797 + }
3798 + yield* eventPermit.withPermit(
3799 + Effect.gen(function* () {
3800 + // Do not yield before turn installation; EOF may otherwise finish scanning before registration.
3801 + if (closing || nativeStreamFailure !== null) {
3802 + return yield* protocolError(
3803 + "OpenCode event stream has ended; reconnect the provider session before starting another turn.",
3804 + );
3805 + }
3806 + if (state.activeTurn !== null) {
3807 + return yield* new ProviderAdapter.ProviderAdapterProtocolError({
3808 + driver: OPENCODE_PROVIDER,
3809 + detail: `OpenCode provider thread ${turnInput.providerThread.id} already has an active turn`,
3810 + reason: "previous_turn_active",
3811 + });
3812 + }
3813 + const wake = state.wake;
3814 + if (!continuation) turn.priorWakeSettled = wake?.settled ?? null;
3815 + state.wake = null;
3816 + state.appThread = turnInput.appThread;
3817 + state.activeTurn = turn;
3818 + state.providerTurns.set(String(providerTurnId), providerTurn);
3819 + yield* emitProviderTurn(state, turn, "running", null);
3820 + yield* updateProviderThread(state, {
3821 + status: "active",
3822 + firstRunOrdinal:
3823 + state.providerThread.firstRunOrdinal ?? turnInput.runOrdinal,
3824 + lastRunOrdinal: turnInput.runOrdinal,
3825 + });
3826 + yield* updateProviderSession("running", null);
3827 + if (!continuation) {
3828 + for (const event of wake?.events ?? []) {
3829 + if (
3830 + event.type === "message.updated" &&
3831 + event.properties.sessionID === sessionId &&
3832 + event.properties.info.role === "user"
3833 + ) {
3834 + turn.priorWakePromptIds.add(event.properties.info.id);
3835 + }
3836 + }
3837 + }
3838 + // Work held after this turn settles is a later result; it starts its own wake.
3839 + yield* Effect.forEach(wake?.events ?? [], (event) =>
3840 + (state.activeTurn === turn
3841 + ? routeEvent(event, continuation ? undefined : sessionId)
3842 + : acceptEvent(event)
3843 + ).pipe(Effect.timeout("10 seconds")),
3844 + ).pipe(
3845 + Effect.onError(() =>
3846 + Effect.gen(function* () {
3847 + if (state.activeTurn !== turn) return;
3848 + nativeStreamFailure = makeProviderFailure({
3849 + message:
3850 + "OpenCode buffered replay failed; reconnect the provider session.",
3851 + class: "transport_error",
3852 + });
3853 + turn.admissionAbortController?.abort();
3854 + yield* Deferred.succeed(admissionSettled, undefined);
3855 + yield* updateProviderSession("error", nativeStreamFailure.message);
3856 + yield* cleanupSessionWork(state, abortRootSession(state)).pipe(
3857 + Effect.ignore({ log: true }),
3858 + );
3859 + yield* finalizeTurn(state, turn, "failed", {
3860 + failure: nativeStreamFailure,
3861 + threadDisposition: "broken",
3862 + });
3863 + }),
3864 + ),
3865 + );
3866 + // Stop or a newer turn took the wake first; nothing is left to run.
3867 + if (continuation && wake === null)
3868 + yield* finalizeTurn(state, turn, "completed");
3869 + }),
3870 + );
3871 + }),
3872 + );
3873 + if (continuation) return;
3874 + if (turn.priorWakeSettled !== null) {
3875 + yield* Deferred.await(turn.priorWakeSettled);
3876 + turn.priorWakeSettled = null;
3877 + if (!turnIsLive(state, turn)) {
3878 + yield* Deferred.succeed(admissionSettled, undefined);
3879 + return;
3880 + }
3881 + }
3882 if (isCompaction) {
3883 yield* sdkCall(
3884 "session.summarize",
@@ -3573,7 +3942,7 @@ export const makeOpenCodeAdapterV2 = Effect.fn("makeOpenCodeAdapterV2")(function
3942 ]).pipe(Effect.asVoid),
3943 ),
3944 );
3576 - if (state.activeTurn === turn && !turn.finalized && !turn.interrupted) {
3945 + if (turnIsLive(state, turn)) {
3946 const admissionAction = advanceOpenCodePromptAdmission(turn, "accepted");
3947 if (admissionAction === "reconcile-idle") {
3948 yield* reconcilePromptAdmission(state, turn);
@@ -3581,18 +3950,29 @@ export const makeOpenCodeAdapterV2 = Effect.fn("makeOpenCodeAdapterV2")(function
3950 }
3951 },
3952 (effect, turnInput) =>
3584 - effect.pipe(
3585 - Effect.mapError(
3586 - (cause) =>
3587 - new ProviderAdapter.ProviderAdapterTurnStartError({
3588 - driver: OPENCODE_PROVIDER,
3589 - threadId: turnInput.threadId,
3590 - providerThreadId: turnInput.providerThread.id,
3591 - runId: turnInput.runId,
3592 - cause,
3593 - }),
3594 - ),
3595 - ),
3953 + Effect.suspend(() => {
3954 + const state = threads.get(nativeThreadId(turnInput.providerThread));
3955 + const wake =
3956 + turnInput.message.createdBy === "agent" &&
3957 + turnInput.message.creationSource === "provider"
3958 + ? state?.wake
3959 + : null;
3960 + return effect.pipe(
3961 + Effect.onError(() =>
3962 + state !== undefined && wake != null ? stopWake(state, wake) : Effect.void,
3963 + ),
3964 + Effect.mapError(
3965 + (cause) =>
3966 + new ProviderAdapter.ProviderAdapterTurnStartError({
3967 + driver: OPENCODE_PROVIDER,
3968 + threadId: turnInput.threadId,
3969 + providerThreadId: turnInput.providerThread.id,
3970 + runId: turnInput.runId,
3971 + cause,
3972 + }),
3973 + ),
3974 + );
3975 + }),
3976 ),
3977 steerTurn: Effect.fn("OpencodeAdapter.steerTurn")(
3978 function* (steerInput) {
@@ -3725,54 +4105,72 @@ export const makeOpenCodeAdapterV2 = Effect.fn("makeOpenCodeAdapterV2")(function
4105 function* (interruptInput) {
4106 const sessionId = nativeThreadId(interruptInput.providerThread);
4107 const state = threads.get(sessionId);
3728 - const turn = state?.activeTurn;
3729 - if (
3730 - (turn === undefined || turn === null) &&
3731 - interruptInput.requestRuntimeRestart === true
3732 - ) {
4108 + if (state === undefined) {
4109 + if (interruptInput.requestRuntimeRestart !== true)
4110 + return yield* protocolError(`OpenCode session ${sessionId} is not registered`);
4111 for (const controller of commandControllers.get(sessionId) ?? [])
4112 controller.abort();
3735 - yield* abortDescendants(sessionId);
4113 + const descendants = yield* abortDescendants(sessionId).pipe(Effect.result);
4114 yield* interruptLaunchedSubagents(sessionId);
4115 + if (descendants._tag === "Failure") return yield* descendants.failure;
4116 return;
4117 }
3739 - if (
3740 - turn === undefined ||
3741 - turn === null ||
3742 - turn.providerTurnId !== interruptInput.providerTurnId
3743 - ) {
3744 - return yield* protocolError(
3745 - `OpenCode turn ${interruptInput.providerTurnId} is not active`,
3746 - );
3747 - }
3748 - turn.interrupted = true;
3749 - for (const controller of commandControllers.get(sessionId) ?? []) controller.abort();
3750 - const admissionWasPending = turn.admissionPending;
3751 - cancelOpenCodePromptAdmission(turn, state!.nextAdmissionGeneration++);
3752 - turn.admissionAbortController?.abort();
3753 - if (admissionWasPending) {
3754 - // Local admission timeout must not block the server-side abort.
3755 - yield* Deferred.await(turn.admissionSettled).pipe(
3756 - Effect.timeout("10 seconds"),
3757 - Effect.ignore,
3758 - );
3759 - }
3760 - yield* sdkCall("session.abort", { sessionID: sessionId }, (signal) =>
3761 - client.session.abort({ sessionID: sessionId }, { signal }),
3762 - ).pipe(
3763 - Effect.timeout("10 seconds"),
3764 - Effect.catch((cause) =>
3765 - turn.finalized
3766 - ? Effect.void
3767 - : Effect.suspend(() => {
3768 - turn.interrupted = false;
3769 - return Effect.fail(cause);
3770 - }),
3771 - ),
4118 + return yield* state.lifecyclePermit.withPermit(
4119 + Effect.gen(function* () {
4120 + const turn = state.activeTurn;
4121 + if (
4122 + (turn === undefined || turn === null) &&
4123 + interruptInput.requestRuntimeRestart === true
4124 + ) {
4125 + for (const controller of commandControllers.get(sessionId) ?? [])
4126 + controller.abort();
4127 + const wake = state.wake;
4128 + if (wake !== null) yield* cancelWake(state, wake);
4129 + else yield* cleanupSessionWork(state, Effect.void);
4130 + return;
4131 + }
4132 + if (
4133 + turn === undefined ||
4134 + turn === null ||
4135 + turn.providerTurnId !== interruptInput.providerTurnId
4136 + ) {
4137 + return yield* protocolError(
4138 + `OpenCode turn ${interruptInput.providerTurnId} is not active`,
4139 + );
4140 + }
4141 + turn.interrupted = true;
4142 + for (const controller of commandControllers.get(sessionId) ?? [])
4143 + controller.abort();
4144 + const admissionWasPending = turn.admissionPending;
4145 + cancelOpenCodePromptAdmission(turn, state!.nextAdmissionGeneration++);
4146 + turn.admissionAbortController?.abort();
4147 + if (turn.priorWakeSettled !== null)
4148 + yield* Deferred.succeed(turn.priorWakeSettled, undefined);
4149 + if (admissionWasPending) {
4150 + // Local admission timeout must not block the server-side abort.
4151 + yield* Deferred.await(turn.admissionSettled).pipe(
4152 + Effect.timeout("10 seconds"),
4153 + Effect.ignore,
4154 + );
4155 + }
4156 + yield* cleanupSessionWork(
4157 + state,
4158 + sdkCall("session.abort", { sessionID: sessionId }, (signal) =>
4159 + client.session.abort({ sessionID: sessionId }, { signal }),
4160 + ).pipe(
4161 + Effect.timeout("10 seconds"),
4162 + Effect.catch((cause) =>
4163 + turn.finalized
4164 + ? Effect.void
4165 + : Effect.suspend(() => {
4166 + turn.interrupted = false;
4167 + return Effect.fail(cause);
4168 + }),
4169 + ),
4170 + ),
4171 + );
4172 + }),
4173 );
3773 - // Root abort leaves children running; report incomplete cleanup even after root termination.
3774 - yield* abortDescendants(sessionId);
3775 - yield* interruptLaunchedSubagents(sessionId);
4174 },
4175 (effect, interruptInput) =>
4176 effect.pipe(
scripts/scenarios/opencode-background-result-wakes-thread.e2e.ts new
+249
@@ -0,0 +1,249 @@
1 +// @effect-diagnostics nodeBuiltinImport:off - a plain Node server streams the fake OpenCode SSE feed.
2 +import * as NodeFSP from "node:fs/promises";
3 +import * as NodeHttp from "node:http";
4 +import type * as NodeNet from "node:net";
5 +import * as NodePath from "node:path";
6 +
7 +import { expect } from "e2e";
8 +
9 +import { T3_HOME } from "../e2e.config.ts";
10 +import { makeState, runPromise, test, WEB } from "./t3.ts";
11 +
12 +// An OpenCode 1.19.5 server with background subagents on (OPENCODE_EXPERIMENTAL_BACKGROUND_SUBAGENTS,
13 +// which T3 never sets). Frames follow v1.19.5 source: tool/task.ts injects a finished background
14 +// task's result as a synthetic prompt on the parent session; session/prompt.ts saves it, then
15 +// reports busy; session/status.ts reports idle, then session.idle.
16 +const ROOT = "ses_scenario_root";
17 +const CHILD = "ses_scenario_child";
18 +const MODEL = { providerID: "openai", modelID: "gpt-5.4-mini" };
19 +const WAKE_TEXT = "The background task returned CHILD_OK.";
20 +
21 +function fakeOpenCode() {
22 + const streams = new Set<NodeHttp.ServerResponse>();
23 + let sequence = 0;
24 + const emit = (type: string, properties: unknown) => {
25 + const frame = `data: ${JSON.stringify({ id: `evt_${++sequence}`, type, properties })}\n\n`;
26 + for (const stream of streams) stream.write(frame);
27 + };
28 + const session = (id: string) => ({
29 + id,
30 + slug: id,
31 + version: "1.19.5",
32 + projectID: "global",
33 + directory: "/tmp",
34 + title: id,
35 + time: { created: 1, updated: 1 },
36 + ...(id === CHILD ? { parentID: ROOT } : {}),
37 + });
38 + const user = (sessionID: string, id: string) =>
39 + emit("message.updated", {
40 + sessionID,
41 + info: { id, sessionID, role: "user", time: { created: 1 }, agent: "build", model: MODEL },
42 + });
43 + const answer = (sessionID: string, id: string, parentID: string, text: string) => {
44 + const info = {
45 + id,
46 + parentID,
47 + sessionID,
48 + role: "assistant",
49 + mode: "build",
50 + agent: "build",
51 + path: { cwd: "/tmp", root: "/" },
52 + cost: 0,
53 + tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
54 + ...MODEL,
55 + };
56 + emit("message.updated", { sessionID, info: { ...info, time: { created: 2 } } });
57 + emit("message.part.updated", {
58 + sessionID,
59 + part: { id: `prt_${id}`, messageID: id, sessionID, type: "text", text },
60 + time: 2,
61 + });
62 + emit("message.updated", {
63 + sessionID,
64 + info: { ...info, time: { created: 2, completed: 3 }, finish: "stop" },
65 + });
66 + };
67 + const status = (sessionID: string, type: "busy" | "idle") => {
68 + emit("session.status", { sessionID, status: { type } });
69 + if (type === "idle") emit("session.idle", { sessionID });
70 + };
71 + const task = (state: "running" | "completed") =>
72 + emit("message.part.updated", {
73 + sessionID: ROOT,
74 + part: {
75 + id: "prt_task",
76 + messageID: "msg_tool_step",
77 + sessionID: ROOT,
78 + type: "tool",
79 + tool: "task",
80 + callID: "call_task",
81 + state: {
82 + status: state,
83 + title: "Return CHILD_OK",
84 + input: {
85 + description: "Return CHILD_OK",
86 + prompt: "Respond exactly CHILD_OK.",
87 + subagent_type: "general",
88 + background: true,
89 + },
90 + metadata: { sessionId: CHILD, background: true, jobId: CHILD },
91 + time: { start: 1, ...(state === "completed" ? { end: 2 } : {}) },
92 + ...(state === "completed" ? { output: "Background task started" } : {}),
93 + },
94 + },
95 + time: 1,
96 + });
97 +
98 + // The foreground turn launches the task in the background and settles before it finishes.
99 + const runPrompt = (messageID: string) => {
100 + user(ROOT, messageID);
101 + status(ROOT, "busy");
102 + emit("session.created", { sessionID: CHILD, info: session(CHILD) });
103 + task("running");
104 + user(CHILD, "msg_child_prompt");
105 + task("completed");
106 + emit("session.status", { sessionID: CHILD, status: { type: "busy" } });
107 + answer(ROOT, "msg_root_answer", messageID, "PARENT_OK");
108 + status(ROOT, "idle");
109 + };
110 + const finishBackgroundTask = () => {
111 + answer(CHILD, "msg_child_answer", "msg_child_prompt", "CHILD_OK");
112 + status(CHILD, "idle");
113 + user(ROOT, "msg_background_result");
114 + emit("message.part.updated", {
115 + sessionID: ROOT,
116 + part: {
117 + id: "prt_background_result",
118 + messageID: "msg_background_result",
119 + sessionID: ROOT,
120 + type: "text",
121 + synthetic: true,
122 + text: `<task id="${CHILD}" state="completed">\n<summary>Background task completed: Return CHILD_OK</summary>\n<task_result>\nCHILD_OK\n</task_result>\n</task>`,
123 + },
124 + time: 3,
125 + });
126 + status(ROOT, "busy");
127 + answer(ROOT, "msg_wake_answer", "msg_background_result", WAKE_TEXT);
128 + status(ROOT, "idle");
129 + };
130 +
131 + const server = NodeHttp.createServer(async (request, response) => {
132 + const path = new URL(request.url ?? "/", "http://opencode").pathname;
133 + let body = "";
134 + for await (const chunk of request) body += chunk;
135 + const json = (value: unknown) => {
136 + response.writeHead(200, { "content-type": "application/json" });
137 + response.end(JSON.stringify(value));
138 + };
139 + if (path === "/event") {
140 + response.writeHead(200, { "content-type": "text/event-stream", "cache-control": "no-cache" });
141 + response.write(`data: ${JSON.stringify({ type: "server.connected", properties: {} })}\n\n`);
142 + streams.add(response);
143 + request.on("close", () => streams.delete(response));
144 + return;
145 + }
146 + if (path === "/api/info") {
147 + response.writeHead(200, { "content-type": "text/html" });
148 + return response.end("<!doctype html>");
149 + }
150 + if (path === "/global/health") return json({ healthy: true, version: "1.19.5" });
151 + if (path === "/provider") {
152 + const model = { id: MODEL.modelID, name: "GPT-5.4 mini", release_date: "2026-01-01" };
153 + return json({
154 + all: [{ id: MODEL.providerID, name: "OpenAI", models: { [model.id]: model } }],
155 + default: { [MODEL.providerID]: model.id },
156 + connected: [MODEL.providerID],
157 + });
158 + }
159 + if (path === "/agent") return json([{ name: "build", mode: "primary" }]);
160 + if (path === "/command" || path === "/skill") return json([]);
161 + if (path === "/session/status") return json({});
162 + if (path === "/session" && request.method === "POST") return json(session(ROOT));
163 + const match = /^\/session\/([^/]+)(?:\/([a-z_]+))?$/.exec(path);
164 + if (match !== null) {
165 + const [, id = ROOT, action] = match;
166 + if (action === undefined) return json(session(id));
167 + if (action === "children") return json([]);
168 + if (action === "abort") return json(true);
169 + if (action === "prompt_async") {
170 + response.writeHead(204).end();
171 + return runPrompt(JSON.parse(body).messageID);
172 + }
173 + }
174 + response.writeHead(404, { "content-type": "application/json" });
175 + response.end("{}");
176 + });
177 + return { server, finishBackgroundTask };
178 +}
179 +
180 +test(
181 + "An OpenCode 1.x background task's result wakes its settled thread",
182 + WEB,
183 + async ({ t3, app, screen }) => {
184 + const opencode = fakeOpenCode();
185 + await new Promise<void>((resolve) => opencode.server.listen(0, "127.0.0.1", resolve));
186 + try {
187 + const { port } = opencode.server.address() as NodeNet.AddressInfo;
188 + const settingsPath = NodePath.join(T3_HOME, "userdata/settings.json");
189 + const settings = JSON.parse(await NodeFSP.readFile(settingsPath, "utf8"));
190 + settings.providerInstances.opencode = {
191 + driver: "opencode",
192 + enabled: true,
193 + config: { serverUrl: `http://127.0.0.1:${port}` },
194 + };
195 + await NodeFSP.writeFile(settingsPath, JSON.stringify(settings));
196 +
197 + const project = await t3.project("demo");
198 + const { cli } = makeState(T3_HOME);
199 + const start = [
200 + "thread",
201 + "start",
202 + project,
203 + "Delegate a background task, then reply PARENT_OK.",
204 + "--title",
205 + "Background wake",
206 + "--provider",
207 + "opencode",
208 + "--model",
209 + `${MODEL.providerID}/${MODEL.modelID}`,
210 + "--json",
211 + ];
212 + // The settings watcher enables OpenCode a moment after the write.
213 + let started = "";
214 + await expect
215 + .poll(
216 + async () => {
217 + const result = await runPromise(cli(start, [0, 1])).catch(() => undefined);
218 + if (result?.stdout.includes("threadId")) started = result.stdout;
219 + return started.length > 0;
220 + },
221 + { timeout: 60_000 },
222 + )
223 + .toBe(true);
224 + const { threadId } = JSON.parse(started) as { threadId: string };
225 + await t3.open({ threadId });
226 +
227 + await expect(screen.getByText("PARENT_OK")).toBeVisible({ timeout: 60_000 });
228 + opencode.finishBackgroundTask();
229 + await expect(screen.getByText(WAKE_TEXT)).toBeVisible({ timeout: 30_000 });
230 + // OpenCode's own turn is a second run, and it settles.
231 + await expect
232 + .poll(
233 + async () => {
234 + const shown = await runPromise(cli(["thread", "show", threadId, "--json"]));
235 + const { thread } = JSON.parse(shown.stdout) as {
236 + thread: { runCount: number; status: string };
237 + };
238 + return `${thread.runCount} runs, ${thread.status}`;
239 + },
240 + { timeout: 30_000 },
241 + )
242 + .toBe("2 runs, completed");
243 + await app.screenshot("background-result");
244 + } finally {
245 + opencode.server.closeAllConnections();
246 + opencode.server.close();
247 + }
248 + },
249 +);