The best way to control Claude Code, Codex and more from any computer or phone
fix(opencode): publish ordered pending-work snapshots (#21460)
Co-authored-by: Exotic209093 <134711311+Exotic209093@users.noreply.github.com> Co-authored-by: Issue triage verification <triage@localhost> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Julius Marminge committed
Nov 2, 2026 at 19:00 UTC
c3e1e0a4e9c38af7383b3b85406daab31e695fa7
4 files changed
+473
-76
apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts
+256
-43
@@ -72,11 +72,18 @@ const event = (
72
type: string,
73
data: Record<string, unknown>,
74
label?: string,
75
+ version = 1,
76
): ProviderReplayEntry => ({
77
type: "emit_inbound",
78
frame: {
79
type: "sdk.event",
79
- event: { id: `evt_${type.replaceAll(".", "")}0000`, created: 1, type, data, ...durable },
80
+ event: {
81
+ id: `evt_${type.replaceAll(".", "")}0000`,
82
+ created: 1,
83
+ type,
84
+ data,
85
+ durable: { ...durable.durable, version },
86
+ },
87
},
88
...(label === undefined ? {} : { label }),
89
});
@@ -943,47 +950,85 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
950
}).pipe(Effect.scoped),
951
);
952
946
- it.effect("keeps a finished background subagent's queued report as pending work", () =>
947
- Effect.gen(function* () {
948
- const { runtime, thread } = yield* resumed([
949
- ...backgroundLaunch(CHILD),
950
- event("session.execution.succeeded", { sessionID: SESSION }),
951
- event("session.execution.succeeded", { sessionID: CHILD }),
952
- event("session.inbox.enqueued", {
953
- inboxID: "msg_report",
954
- sessionID: SESSION,
955
- item: {
956
- type: "synthetic",
957
- payload: {
958
- text: `<subagent sessionID="${CHILD}" state="completed" description="Sleep">\nCHILD_OK\n</subagent>`,
959
- description: "Sleep",
960
- metadata: {
961
- source: "subagent",
962
- childID: CHILD,
963
- agent: "General",
964
- state: "completed",
965
- },
966
- },
967
- delivery: "steer",
968
- },
969
- }),
970
- event("session.usage.updated", { sessionID: SESSION }),
971
- ]);
972
- const reported = yield* Deferred.make<void>();
973
- yield* runtime.events.pipe(
974
- Stream.tap((event) =>
975
- event.type === "subagent.updated" && event.subagent.status === "completed"
976
- ? Deferred.succeed(reported, undefined)
977
- : Effect.void,
978
- ),
979
- Stream.runDrain,
980
- Effect.forkScoped,
981
- );
982
- yield* runtime.startTurn(withLineage(thread));
983
- yield* Deferred.await(reported);
984
- assert.isTrue(yield* runtime.hasPendingBackgroundWork!);
985
- assert.isTrue(yield* runtime.hasPendingBackgroundWorkForThread!(thread));
986
- }).pipe(Effect.scoped),
953
+ it.effect(
954
+ "keeps a finished background subagent's queued report pending until its native continuation ends",
955
+ () =>
956
+ Effect.gen(function* () {
957
+ const gate = makeProviderReplayGate(["continue"]);
958
+ const { runtime, thread } = yield* resumed(
959
+ [
960
+ ...nestedLaunch,
961
+ event("session.execution.succeeded", { sessionID: DEEP }),
962
+ deepReport("completed"),
963
+ event("session.model.selected", {
964
+ sessionID: SESSION,
965
+ model: { providerID: "opencode", id: "big-pickle", variant: "thinking" },
966
+ }),
967
+ event("session.execution.started", { sessionID: MIDDLE }, "continue"),
968
+ event("session.inbox.delivered", { sessionID: MIDDLE, inboxID: "msg_deep_report" }),
969
+ event("session.text.ended", {
970
+ sessionID: MIDDLE,
971
+ assistantMessageID: "msg_native_continuation",
972
+ ordinal: 0,
973
+ text: "GRANDCHILD_OK",
974
+ }),
975
+ event("session.execution.succeeded", { sessionID: MIDDLE }),
976
+ event("session.model.selected", {
977
+ sessionID: SESSION,
978
+ model: { providerID: "opencode", id: "big-pickle", variant: "none" },
979
+ }),
980
+ ],
981
+ { replayGate: gate },
982
+ );
983
+ const queued = yield* Deferred.make<void>();
984
+ const drained = yield* Deferred.make<void>();
985
+ const timeline: Array<boolean | string> = [];
986
+ yield* runtime.events.pipe(
987
+ Stream.runForEach((event) =>
988
+ Effect.gen(function* () {
989
+ if (event.type === "provider_thread.updated") {
990
+ if (
991
+ event.providerThread.nativeThreadRef?.nativeId === MIDDLE &&
992
+ event.pendingBackgroundWork !== undefined
993
+ ) {
994
+ timeline.push(event.pendingBackgroundWork);
995
+ }
996
+ if (event.providerThread.id === thread.id) {
997
+ const variant =
998
+ event.providerThread.nativeMetadata?.modelSelection?.options?.[0]?.value;
999
+ if (variant === "thinking") yield* Deferred.succeed(queued, undefined);
1000
+ if (variant === "none") yield* Deferred.succeed(drained, undefined);
1001
+ }
1002
+ }
1003
+ if (
1004
+ event.type === "provider_turn.updated" &&
1005
+ event.providerTurn.nativeTurnRef?.nativeId === `${MIDDLE}:turn:2`
1006
+ ) {
1007
+ timeline.push(event.providerTurn.status);
1008
+ }
1009
+ if (event.type === "message.updated" && event.message.text === "GRANDCHILD_OK") {
1010
+ timeline.push(event.message.text);
1011
+ }
1012
+ }),
1013
+ ),
1014
+ Effect.forkScoped,
1015
+ );
1016
+ yield* runtime.startTurn(withLineage(thread));
1017
+ yield* Deferred.await(queued);
1018
+ assert.isTrue(yield* runtime.hasPendingBackgroundWork!);
1019
+ assert.isTrue(yield* runtime.hasPendingBackgroundWorkForThread!(thread));
1020
+ assert.strictEqual(timeline.at(-1), true);
1021
+ timeline.length = 0;
1022
+ gate.release("continue");
1023
+ yield* Deferred.await(drained);
1024
+ assert.deepEqual(
1025
+ timeline.filter((entry) => typeof entry === "string"),
1026
+ ["running", "GRANDCHILD_OK", "completed"],
1027
+ );
1028
+ assert.isAbove(timeline.indexOf(false), timeline.indexOf("completed"));
1029
+ assert.strictEqual(timeline.at(-1), false);
1030
+ assert.isFalse(yield* runtime.hasPendingBackgroundWorkForThread!(thread));
1031
+ }).pipe(Effect.scoped),
1032
);
1033
1034
const returnedRunning = (id: string): ProviderReplayEntry => ({
@@ -1283,6 +1328,9 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
1328
Effect.gen(function* () {
1329
const deep: Array<string> = [];
1330
const middleTurns = new Map<string, string>();
1331
+ const pendingSnapshots = new Map<string, boolean>();
1332
+ const variants = new Map<string, unknown>();
1333
+ let rootVariant: unknown;
1334
const terminals: Array<string> = [];
1335
const changed = yield* Deferred.make<void>();
1336
let wake = changed;
@@ -1290,6 +1338,16 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
1338
Stream.tap((event) =>
1339
Effect.gen(function* () {
1340
if (event.type === "turn.terminal") terminals.push(event.status);
1341
+ if (event.type === "provider_thread.updated") {
1342
+ const nativeId = event.providerThread.nativeThreadRef?.nativeId;
1343
+ if (nativeId != null && event.pendingBackgroundWork !== undefined) {
1344
+ pendingSnapshots.set(nativeId, event.pendingBackgroundWork);
1345
+ }
1346
+ const variant =
1347
+ event.providerThread.nativeMetadata?.modelSelection?.options?.[0]?.value;
1348
+ if (nativeId != null) variants.set(nativeId, variant);
1349
+ if (nativeId === SESSION) rootVariant = variant;
1350
+ }
1351
if (event.type === "subagent.updated" && event.subagent.title === "Deep") {
1352
deep.push(event.subagent.status);
1353
}
@@ -1314,9 +1372,164 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
1372
yield* until(check);
1373
});
1374
});
1317
- return { deep, middleTurns, terminals, until };
1375
+ return {
1376
+ deep,
1377
+ middleTurns,
1378
+ terminals,
1379
+ pendingSnapshots,
1380
+ variants,
1381
+ get rootVariant() {
1382
+ return rootVariant;
1383
+ },
1384
+ until,
1385
+ };
1386
});
1387
1388
+ it.effect("clears a nested report cancelled during a held wake", () =>
1389
+ Effect.gen(function* () {
1390
+ const offers: Array<ProviderContinuationRequests.ProviderContinuationRequest> = [];
1391
+ const gate = makeProviderReplayGate(["drained"]);
1392
+ const { runtime, thread } = yield* resumed(
1393
+ [
1394
+ ...backgroundLaunch(CHILD),
1395
+ event("session.execution.succeeded", { sessionID: SESSION }),
1396
+ event("session.execution.succeeded", { sessionID: CHILD }),
1397
+ childReport("msg_report", "CHILD_OK"),
1398
+ event("session.execution.started", { sessionID: SESSION }),
1399
+ ...nestedLaunch.slice(3, -2),
1400
+ event(
1401
+ "session.tool.success",
1402
+ {
1403
+ ...toolOf(SESSION, "call-middle"),
1404
+ content: [{ type: "text", text: "MIDDLE_OK" }],
1405
+ metadata: { sessionID: MIDDLE, status: "completed", truncated: false },
1406
+ executed: false,
1407
+ },
1408
+ undefined,
1409
+ 2,
1410
+ ),
1411
+ event("session.execution.succeeded", { sessionID: DEEP }),
1412
+ deepReport("completed"),
1413
+ event("session.inbox.cancelled", { sessionID: MIDDLE, inboxID: "msg_deep_report" }),
1414
+ event("session.execution.succeeded", { sessionID: SESSION }),
1415
+ event("session.model.selected", {
1416
+ sessionID: SESSION,
1417
+ model: { providerID: "opencode", id: "big-pickle", variant: "thinking" },
1418
+ }),
1419
+ event(
1420
+ "session.model.selected",
1421
+ {
1422
+ sessionID: SESSION,
1423
+ model: { providerID: "opencode", id: "big-pickle", variant: "none" },
1424
+ },
1425
+ "drained",
1426
+ ),
1427
+ ],
1428
+ { replayGate: gate },
1429
+ ).pipe(
1430
+ Effect.provideService(ProviderContinuationRequests.ProviderContinuationRequests, {
1431
+ offer: (request) =>
1432
+ Effect.sync(() => {
1433
+ offers.push(request);
1434
+ }),
1435
+ take: Effect.never,
1436
+ }),
1437
+ );
1438
+ const watch = yield* watchNested(runtime);
1439
+ yield* runtime.startTurn(withLineage(thread));
1440
+ assert.isTrue(yield* Effect.promise(() => gate.waitForReached("drained")));
1441
+ yield* watch.until(() => watch.rootVariant === "thinking");
1442
+ assert.lengthOf(offers, 1);
1443
+ yield* runtime.startTurn(continuationTurn(thread, offers[0]!));
1444
+ gate.release("drained");
1445
+ yield* watch.until(() => watch.rootVariant === "none");
1446
+ assert.isFalse(yield* runtime.hasPendingBackgroundWork!);
1447
+ assert.strictEqual(watch.pendingSnapshots.get(MIDDLE), false);
1448
+ }).pipe(Effect.scoped),
1449
+ );
1450
+
1451
+ it.effect("clears the caller's pending work when a called session's held wake runs", () =>
1452
+ Effect.gen(function* () {
1453
+ const OTHER = "ses_other00000000000000000000";
1454
+ const offers: Array<ProviderContinuationRequests.ProviderContinuationRequest> = [];
1455
+ const gate = makeProviderReplayGate(["drained"]);
1456
+ const { runtime, thread } = yield* resumed(
1457
+ [
1458
+ out("session.get", { sessionID: OTHER }),
1459
+ replyData("session.get", sessionInfo({ id: OTHER })),
1460
+ out("permission.list", { sessionID: OTHER }),
1461
+ replyData("permission.list", []),
1462
+ out("session.form.list", { sessionID: OTHER }),
1463
+ replyData("session.form.list", []),
1464
+ event("session.execution.started", { sessionID: OTHER }),
1465
+ event("session.execution.succeeded", { sessionID: OTHER }),
1466
+ out("session.prompt", { sessionID: SESSION, text: "<any>" }),
1467
+ promptAccepted,
1468
+ event("session.execution.started", { sessionID: SESSION }),
1469
+ event("session.tool.input.started", {
1470
+ ...toolOf(SESSION, "call-other"),
1471
+ name: "subagent",
1472
+ }),
1473
+ event("session.tool.called", {
1474
+ ...toolOf(SESSION, "call-other"),
1475
+ name: "subagent",
1476
+ input: { description: "Other", prompt: "again" },
1477
+ executed: false,
1478
+ }),
1479
+ event("session.tool.progress", {
1480
+ ...toolOf(SESSION, "call-other"),
1481
+ metadata: { sessionID: OTHER, status: "running" },
1482
+ }),
1483
+ event("session.tool.success", {
1484
+ ...toolOf(SESSION, "call-other"),
1485
+ content: [{ type: "text", text: "OTHER_OK" }],
1486
+ metadata: { sessionID: OTHER, status: "completed", truncated: false },
1487
+ executed: false,
1488
+ }),
1489
+ event("session.execution.succeeded", { sessionID: SESSION }),
1490
+ event(
1491
+ "session.model.selected",
1492
+ {
1493
+ sessionID: OTHER,
1494
+ model: { providerID: "opencode", id: "big-pickle", variant: "none" },
1495
+ },
1496
+ "drained",
1497
+ ),
1498
+ ],
1499
+ { replayGate: gate },
1500
+ ).pipe(
1501
+ Effect.provideService(ProviderContinuationRequests.ProviderContinuationRequests, {
1502
+ offer: (request) =>
1503
+ Effect.sync(() => {
1504
+ offers.push(request);
1505
+ }),
1506
+ take: Effect.never,
1507
+ }),
1508
+ );
1509
+ const other = yield* runtime.resumeThread({
1510
+ providerThread: {
1511
+ ...thread,
1512
+ id: ProviderThreadId.make("provider-thread:opencode2-adapter:other"),
1513
+ nativeThreadRef: { driver: OPENCODE_PROVIDER, nativeId: OTHER, strength: "strong" },
1514
+ },
1515
+ threadId,
1516
+ modelSelection: bigPickle,
1517
+ runtimePolicy: policy(),
1518
+ });
1519
+ const watch = yield* watchNested(runtime);
1520
+ yield* watch.until(() => offers.length === 1);
1521
+ yield* runtime.startTurn(withLineage(thread));
1522
+ assert.isTrue(yield* Effect.promise(() => gate.waitForReached("drained")));
1523
+ // The called session's held wake is its caller's pending work too.
1524
+ yield* watch.until(() => watch.pendingSnapshots.get(SESSION) === true);
1525
+ yield* runtime.startTurn(continuationTurn(other, offers[0]!));
1526
+ gate.release("drained");
1527
+ yield* watch.until(() => watch.variants.get(OTHER) === "none");
1528
+ assert.isFalse(watch.pendingSnapshots.get(OTHER));
1529
+ assert.isFalse(watch.pendingSnapshots.get(SESSION));
1530
+ }).pipe(Effect.scoped),
1531
+ );
1532
+
1533
it.effect("stops a foreground subagent's background subagent after the turn ended", () =>
1534
Effect.gen(function* () {
1535
const offered = yield* Deferred.make<void>();
apps/server/src/orchestration-v2/testkit/OpenCode2PendingSnapshots.evidence.test.ts
new
+159
@@ -0,0 +1,159 @@
1
+import { assert, describe, it } from "@effect/vitest";
2
+import type { ProviderInstanceId } from "@t3tools/contracts";
3
+import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
4
+import * as NodeServices from "@effect/platform-node/NodeServices";
5
+import * as Config from "effect/Config";
6
+import * as Effect from "effect/Effect";
7
+import * as FileSystem from "effect/FileSystem";
8
+import * as Layer from "effect/Layer";
9
+import * as Stream from "effect/Stream";
10
+
11
+import { OpenCode2OrchestratorReplayHarness } from "../Adapters/OpenCode2AdapterV2.testkit.ts";
12
+import * as ProviderAdapterRegistry from "../ProviderAdapterRegistry.ts";
13
+import { findReplayFixture, runReplayFixture } from "./ProviderReplayFixtures.ts";
14
+
15
+// Evidence driver: replays recorded OpenCode 2 fixtures through
16
+// OrchestratorV2 and records the adapter's own event stream, because the
17
+// `pendingBackgroundWork` flag is dropped before it reaches domain events.
18
+// Set EV_TRANSCRIPT to a file path to append the transcript there.
19
+
20
+type Row = {
21
+ readonly id: string;
22
+ readonly fixture: string;
23
+ /** True when every native thread must end on a `pendingBackgroundWork: false` snapshot. */
24
+ readonly requireSettledSnapshots: boolean;
25
+};
26
+
27
+const ROWS: ReadonlyArray<Row> = [
28
+ { id: "R1", fixture: "opencode2_nested_background", requireSettledSnapshots: true },
29
+ { id: "R1-compat", fixture: "opencode2_background", requireSettledSnapshots: true },
30
+ { id: "R2c-compat", fixture: "opencode2_resume_after_restart", requireSettledSnapshots: false },
31
+ { id: "R2c-compat", fixture: "opencode2_interrupt", requireSettledSnapshots: false },
32
+ { id: "R3", fixture: "opencode2_simple", requireSettledSnapshots: false },
33
+ { id: "R3", fixture: "opencode2_tool_call", requireSettledSnapshots: false },
34
+];
35
+
36
+const tasksOf = (tasks: ReadonlyArray<{ readonly taskId: string }> | undefined) =>
37
+ `[${(tasks ?? []).map((task) => task.taskId).join(",")}]`;
38
+
39
+const describeEvent = (event: ProviderAdapter.ProviderAdapterV2Event): string | undefined => {
40
+ switch (event.type) {
41
+ case "provider_thread.updated":
42
+ return `provider_thread.updated native=${event.providerThread.nativeThreadRef?.nativeId ?? "?"} pendingBackgroundWork=${String(event.pendingBackgroundWork)} pendingBackgroundTasks=${tasksOf(event.providerThread.pendingBackgroundTasks)}`;
43
+ case "provider_turn.updated":
44
+ return `provider_turn.updated native=${event.providerTurn.nativeTurnRef?.nativeId ?? "?"} status=${event.providerTurn.status}`;
45
+ case "subagent.updated":
46
+ return `subagent.updated title=${event.subagent.title ?? "?"} status=${event.subagent.status}`;
47
+ case "turn.terminal":
48
+ return `turn.terminal status=${event.status}`;
49
+ default:
50
+ return undefined;
51
+ }
52
+};
53
+
54
+const tappedHarness = (
55
+ record: (event: ProviderAdapter.ProviderAdapterV2Event) => void,
56
+): typeof OpenCode2OrchestratorReplayHarness => ({
57
+ ...OpenCode2OrchestratorReplayHarness,
58
+ makeProviderAdapterRegistryLayer: (
59
+ ...args: Parameters<typeof OpenCode2OrchestratorReplayHarness.makeProviderAdapterRegistryLayer>
60
+ ) =>
61
+ Layer.effect(
62
+ ProviderAdapterRegistry.ProviderAdapterRegistryV2,
63
+ Effect.gen(function* () {
64
+ const registry = yield* ProviderAdapterRegistry.ProviderAdapterRegistryV2;
65
+ return ProviderAdapterRegistry.ProviderAdapterRegistryV2.of({
66
+ ...registry,
67
+ get: (instanceId: ProviderInstanceId) =>
68
+ registry.get(instanceId).pipe(
69
+ Effect.map((adapter) =>
70
+ ProviderAdapter.ProviderAdapterV2.of({
71
+ ...adapter,
72
+ openSession: (input) =>
73
+ adapter.openSession(input).pipe(
74
+ Effect.map((runtime) => ({
75
+ ...runtime,
76
+ events: runtime.events.pipe(
77
+ Stream.tap((event) => Effect.sync(() => record(event))),
78
+ ),
79
+ })),
80
+ ),
81
+ }),
82
+ ),
83
+ ),
84
+ });
85
+ }),
86
+ ).pipe(
87
+ Layer.provide(OpenCode2OrchestratorReplayHarness.makeProviderAdapterRegistryLayer(...args)),
88
+ ),
89
+});
90
+
91
+const runRow = (row: Row) =>
92
+ Effect.gen(function* () {
93
+ const fixture = findReplayFixture(row.fixture);
94
+ const driver = fixture?.providers.find((provider) => provider.driver === "opencode");
95
+ assert.isDefined(fixture);
96
+ assert.isDefined(driver);
97
+ const events: Array<ProviderAdapter.ProviderAdapterV2Event> = [];
98
+ const lines: Array<string> = [];
99
+ const emit = (line: string) => lines.push(line);
100
+ emit(`== ${row.id} ${row.fixture} (recorded fixture) ==`);
101
+ const exit = yield* runReplayFixture({
102
+ fixtureName: row.fixture,
103
+ buildInput: fixture.buildInput,
104
+ driver,
105
+ harness: tappedHarness((event) => events.push(event)),
106
+ }).pipe(Effect.exit);
107
+ let index = 0;
108
+ for (const event of events) {
109
+ const line = describeEvent(event);
110
+ if (line !== undefined) emit(` adapter[${index}] ${line}`);
111
+ index += 1;
112
+ }
113
+ const lastSnapshot = new Map<string, boolean | undefined>();
114
+ let everPending = false;
115
+ for (const event of events) {
116
+ if (event.type !== "provider_thread.updated") continue;
117
+ const nativeId = event.providerThread.nativeThreadRef?.nativeId ?? "?";
118
+ lastSnapshot.set(nativeId, event.pendingBackgroundWork);
119
+ if (event.pendingBackgroundWork === true) everPending = true;
120
+ }
121
+ const finals = [...lastSnapshot].map(([id, flag]) => `${id}=${String(flag)}`).join(" ");
122
+ emit(` final snapshot per native thread: ${finals}`);
123
+ if (exit._tag === "Success") {
124
+ for (const domain of exit.value.domainEvents) {
125
+ if (domain.type !== "provider-thread.updated") continue;
126
+ emit(
127
+ ` domain provider-thread.updated native=${domain.payload.nativeThreadRef?.nativeId ?? "?"} pendingBackgroundTasks=${tasksOf(domain.payload.pendingBackgroundTasks)}`,
128
+ );
129
+ }
130
+ }
131
+ const failures: Array<string> = [];
132
+ if (exit._tag === "Failure") failures.push("fixture output assertions failed");
133
+ if (row.requireSettledSnapshots) {
134
+ if (!everPending) failures.push("no pendingBackgroundWork=true snapshot was published");
135
+ for (const [id, flag] of lastSnapshot) {
136
+ if (flag !== false) failures.push(`${id} ended on pendingBackgroundWork=${String(flag)}`);
137
+ }
138
+ } else if ([...lastSnapshot.values()].includes(true)) {
139
+ failures.push("a native thread ended with pending work");
140
+ }
141
+ emit(
142
+ ` ${row.id} ${row.fixture}: ${failures.length === 0 ? "PASS" : `FAIL (${failures.join("; ")})`}`,
143
+ );
144
+ const transcript = yield* Config.String("EV_TRANSCRIPT").pipe(Config.withDefault(""));
145
+ if (transcript !== "") {
146
+ const fs = yield* FileSystem.FileSystem;
147
+ yield* fs.writeFileString(transcript, `${lines.join("\n")}\n`, { flag: "a" });
148
+ }
149
+ return failures;
150
+ }).pipe(Effect.provide(NodeServices.layer));
151
+
152
+describe("OpenCode 2 pending-work snapshots (#19228 evidence)", () => {
153
+ it.effect.each(ROWS.map((row) => [`${row.id} ${row.fixture}`, row] as const))("%s", ([, row]) =>
154
+ runRow(row).pipe(
155
+ Effect.map((failures) => assert.deepEqual(failures, [])),
156
+ Effect.scoped,
157
+ ),
158
+ );
159
+});
packages/provider-core/src/server/ProviderAdapter.ts
+2
@@ -96,6 +96,8 @@ export const ProviderAdapterV2Event = Schema.Union([
96
type: Schema.Literal("provider_thread.updated"),
97
driver: ProviderDriverKind,
98
providerThread: OrchestrationV2ProviderThread,
99
+ /** Work remaining at this point in the event stream, including native continuations. */
100
+ pendingBackgroundWork: Schema.optional(Schema.Boolean),
101
retainedNativeTurnIds: Schema.optional(Schema.Array(Schema.String)),
102
}),
103
Schema.Struct({
packages/provider-opencode/src/server/v2/adapter.ts
+56
-33
@@ -278,6 +278,7 @@ interface OpenBlock {
278
interface ThreadState {
279
readonly sessionId: string;
280
providerThread: OrchestrationV2ProviderThread;
281
+ publishedBackgroundWork?: boolean;
282
readonly providerTurns: Map<string, OrchestrationV2ProviderTurn>;
283
active: ActiveTurn | undefined;
284
model: ModelRef | undefined;
@@ -833,6 +834,17 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
834
835
const hasBackground = (thread: ThreadState) => sessionsOf(thread).some(owesWork);
836
837
+ const emitProviderThread = Effect.fnUntraced(function* (state: ThreadState) {
838
+ const pendingBackgroundWork = hasBackground(state);
839
+ state.publishedBackgroundWork = pendingBackgroundWork;
840
+ yield* emit({
841
+ type: "provider_thread.updated",
842
+ driver,
843
+ providerThread: state.providerThread,
844
+ pendingBackgroundWork,
845
+ });
846
+ });
847
+
848
const setSessionStatus =
849
/* Provider events include streaming deltas; avoid a span for each update. */
850
Effect.fnUntraced(function* (
@@ -1232,7 +1244,7 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
1244
result: call.result,
1245
},
1246
});
1235
- yield* syncRoster(rootOf(call.state));
1247
+ yield* syncRosterAncestors(call.state);
1248
});
1249
1250
const syncRoster = Effect.fnUntraced(function* (state: ThreadState) {
@@ -1248,6 +1260,7 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
1260
}));
1261
const current = state.providerThread.pendingBackgroundTasks ?? [];
1262
if (
1263
+ state.publishedBackgroundWork === hasBackground(state) &&
1264
current.length === roster.length &&
1265
current.every(
1266
(task, index) =>
@@ -1264,11 +1277,15 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
1277
pendingBackgroundTasks: roster,
1278
updatedAt: yield* DateTime.now,
1279
};
1267
- yield* emit({
1268
- type: "provider_thread.updated",
1269
- driver,
1270
- providerThread: state.providerThread,
1271
- });
1280
+ yield* emitProviderThread(state);
1281
+ });
1282
+
1283
+ const syncRosterAncestors = Effect.fnUntraced(function* (state: ThreadState) {
1284
+ let current: ThreadState | undefined = state;
1285
+ while (current !== undefined) {
1286
+ yield* syncRoster(current);
1287
+ current = current.subagent?.call.state;
1288
+ }
1289
});
1290
1291
const withReportedModel = (
@@ -1378,11 +1395,7 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
1395
childOwners.set(childId, rootOf(call.state));
1396
call.child = child;
1397
yield* emit({ type: "app_thread.created", driver, appThread });
1381
- yield* emit({
1382
- type: "provider_thread.updated",
1383
- driver,
1384
- providerThread: child.providerThread,
1385
- });
1398
+ yield* emitProviderThread(child);
1399
yield* emitSubagent(call);
1400
// Reused child sessions may retain old mode rules; refresh policy as soon as the call identifies them.
1401
if (info === undefined) {
@@ -1417,11 +1430,7 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
1430
status: "idle",
1431
updatedAt: call.completedAt,
1432
};
1420
- yield* emit({
1421
- type: "provider_thread.updated",
1422
- driver,
1423
- providerThread: child.providerThread,
1424
- });
1433
+ yield* emitProviderThread(child);
1434
}
1435
yield* emitSubagent(call);
1436
});
@@ -1635,11 +1644,7 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
1644
status: threadDisposition === "broken" ? "error" : "idle",
1645
updatedAt: completedAt,
1646
};
1638
- yield* emit({
1639
- type: "provider_thread.updated",
1640
- driver,
1641
- providerThread: state.providerThread,
1642
- });
1647
+ yield* emitProviderThread(state);
1648
const anyActive = [...threads.values()].some(
1649
(candidate) => candidate.subagent === undefined && candidate.active !== undefined,
1650
);
@@ -2406,11 +2411,7 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
2411
const providerThread = withReportedModel(state.providerThread, event.data.model);
2412
if (providerThread !== state.providerThread) {
2413
state.providerThread = { ...providerThread, updatedAt: yield* DateTime.now };
2409
- yield* emit({
2410
- type: "provider_thread.updated",
2411
- driver,
2412
- providerThread: state.providerThread,
2413
- });
2414
+ yield* emitProviderThread(state);
2415
}
2416
}
2417
if (
@@ -2621,10 +2622,12 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
2622
yield* settleCall(call, "interrupted", LOST_BACKGROUND);
2623
}
2624
}
2624
- for (const session of sessionsOf(state)) {
2625
+ const sessions = sessionsOf(state);
2626
+ for (const session of sessions) {
2627
discardWakes(session, session.wakes.splice(0));
2628
session.reports.clear();
2629
}
2630
+ for (const session of sessions.toReversed()) yield* syncRoster(session);
2631
}
2632
// Stopped off the lock this reconcile holds; one still running waits for a Stop.
2633
for (const thread of new Set([...strays.values()].map(rootOf))) {
@@ -2680,7 +2683,26 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
2683
stream: Stream.Stream<OpenCode2Client.OpenCode2StreamEvent, unknown>,
2684
): Effect.Effect<void> =>
2685
stream.pipe(
2683
- Stream.runForEach((event) => lock.withPermit(handleEvent(event))),
2686
+ Stream.runForEach((event) =>
2687
+ lock.withPermit(
2688
+ Effect.gen(function* () {
2689
+ yield* handleEvent(event);
2690
+ if (
2691
+ event.type === "session.execution.started" ||
2692
+ event.type === "unreadable.execution.started" ||
2693
+ executionEnd(event.type) ||
2694
+ event.type === "unreadable.execution.ended" ||
2695
+ event.type === "session.inbox.enqueued" ||
2696
+ event.type === "session.inbox.delivered" ||
2697
+ event.type === "session.inbox.cancelled"
2698
+ ) {
2699
+ const sessionId = sessionOfEvent(event);
2700
+ const state = sessionId === undefined ? undefined : threads.get(sessionId);
2701
+ if (state !== undefined) yield* syncRosterAncestors(state);
2702
+ }
2703
+ }),
2704
+ ),
2705
+ ),
2706
Effect.exit,
2707
Effect.flatMap(() =>
2708
Effect.gen(function* () {
@@ -3158,11 +3180,7 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
3180
lastRunOrdinal: turnInput.runOrdinal,
3181
updatedAt: startedAt,
3182
};
3161
- yield* emit({
3162
- type: "provider_thread.updated",
3163
- driver,
3164
- providerThread: state.providerThread,
3165
- });
3183
+ yield* emitProviderThread(state);
3184
yield* setSessionStatus("running", null);
3185
return turn;
3186
});
@@ -3218,6 +3236,8 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
3236
if (wake?.running !== true) return;
3237
state.wakes.pop();
3238
yield* replay(wake);
3239
+ for (const session of sessionsOf(state).toReversed()) yield* syncRoster(session);
3240
+ yield* syncRosterAncestors(state);
3241
});
3242
3243
const runWake = Effect.fnUntraced(function* (
@@ -3243,6 +3263,8 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
3263
}
3264
if (wake.running) state.unsettled = false;
3265
yield* replay(wake);
3266
+ for (const session of sessionsOf(state).toReversed()) yield* syncRoster(session);
3267
+ yield* syncRosterAncestors(state);
3268
}),
3269
);
3270
});
@@ -3305,6 +3327,7 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
3327
}
3328
const running = state.wakes.some((wake) => wake.running);
3329
discardWakes(state, state.wakes.splice(0));
3330
+ yield* syncRosterAncestors(state);
3331
if (running) {
3332
markUnsettled(state);
3333
yield* client.session