The best way to control Claude Code, Codex and more from any computer or phone
fix(opencode): a resumed task subagent's turn no longer collides with its first (#34961)
Julius Marminge committed
Nov 13, 2026 at 09:22 UTC
8bf0dc47537d5edf1fef6ec1484ba63af06fd7d0
2 files changed
+155
-5
packages/provider-opencode/src/server/adapter.test.ts
+120
@@ -1462,6 +1462,126 @@ describe("OpenCodeAdapterV2", () => {
1462
}).pipe(Effect.provide(Layer.merge(IdAllocator.layer, McpProviderSessions.layer))),
1463
);
1464
1465
+ // After a restart the adapter no longer holds the child, so its earlier turns come from OpenCode.
1466
+ it.effect.each([
1467
+ { case: "in memory", restarted: false },
1468
+ { case: "after a restart", restarted: true },
1469
+ ])("appends a resumed task child's turn after its earlier turns ($case)", ({ restarted }) =>
1470
+ Effect.gen(function* () {
1471
+ const nativeEvents = asyncEventStream();
1472
+ const push = (event: unknown) => Effect.promise(() => nativeEvents.push(event));
1473
+ const root = "ses_root";
1474
+ const child = "ses_child";
1475
+ let promptId = "";
1476
+ const harness = yield* makeOpenCodeRuntimeHarness("resumed-child", root, {
1477
+ event: { subscribe: async () => ({ stream: nativeEvents.stream }) },
1478
+ session: {
1479
+ create: async () => ({ data: { id: root, time: { created: 1, updated: 1 } } }),
1480
+ get: async () => ({
1481
+ data: { id: child, parentID: root, permission: [], time: { created: 2, updated: 2 } },
1482
+ }),
1483
+ update: async () => ({ data: { id: child, parentID: root } }),
1484
+ promptAsync: async (input: { messageID: string }) => {
1485
+ promptId = input.messageID;
1486
+ return { data: true };
1487
+ },
1488
+ abort: async () => ({ data: true }),
1489
+ children: async () => ({ data: [] }),
1490
+ // OpenCode may have stored the resume prompt before its event reaches the adapter.
1491
+ messages: async () => ({
1492
+ data: [
1493
+ { info: { id: "msg_child_first", role: "user" }, parts: [] },
1494
+ { info: { id: "msg_child_resume", role: "user" }, parts: [] },
1495
+ ],
1496
+ }),
1497
+ },
1498
+ });
1499
+ yield* harness.startTurn();
1500
+ const childTurns = yield* harness.runtime.events.pipe(
1501
+ Stream.filter(
1502
+ (event) =>
1503
+ event.type === "provider_turn.updated" &&
1504
+ event.providerTurn.status === "running" &&
1505
+ event.providerTurn.providerThreadId.includes(child),
1506
+ ),
1507
+ Stream.take(restarted ? 1 : 2),
1508
+ Stream.runCollect,
1509
+ Effect.forkScoped,
1510
+ );
1511
+ const taskPart = (partId: string, status: "running" | "completed", taskId?: string) => ({
1512
+ type: "message.part.updated",
1513
+ properties: {
1514
+ sessionID: root,
1515
+ part: {
1516
+ id: partId,
1517
+ sessionID: root,
1518
+ messageID: "msg_root_assistant",
1519
+ type: "tool",
1520
+ tool: "task",
1521
+ callID: `call_${partId}`,
1522
+ state: {
1523
+ status,
1524
+ input: {
1525
+ description: "Explore",
1526
+ prompt: "look around",
1527
+ subagent_type: "general",
1528
+ ...(taskId === undefined ? {} : { task_id: taskId }),
1529
+ },
1530
+ title: "Explore",
1531
+ metadata: { parentSessionId: root, sessionId: child },
1532
+ time: { start: 3, ...(status === "completed" ? { end: 4 } : {}) },
1533
+ ...(status === "completed" ? { output: "done" } : {}),
1534
+ },
1535
+ },
1536
+ },
1537
+ });
1538
+ const childPrompt = (id: string, created: number) => ({
1539
+ type: "message.updated",
1540
+ properties: {
1541
+ sessionID: child,
1542
+ info: { id, sessionID: child, role: "user", time: { created } },
1543
+ },
1544
+ });
1545
+ const status = (sessionID: string, type: "busy" | "idle") => ({
1546
+ type: "session.status",
1547
+ properties: { sessionID, status: { type } },
1548
+ });
1549
+
1550
+ yield* push({
1551
+ type: "message.updated",
1552
+ properties: {
1553
+ sessionID: root,
1554
+ info: { id: promptId, sessionID: root, role: "user", time: { created: 1 } },
1555
+ },
1556
+ });
1557
+ yield* push(status(root, "busy"));
1558
+ if (!restarted) {
1559
+ yield* push(taskPart("prt_task_first", "running"));
1560
+ yield* push(childPrompt("msg_child_first", 3));
1561
+ yield* push(status(child, "busy"));
1562
+ yield* push(status(child, "idle"));
1563
+ yield* push({ type: "session.idle", properties: { sessionID: child } });
1564
+ yield* push(taskPart("prt_task_first", "completed"));
1565
+ }
1566
+ // The lead resumes the same child session by passing its task_id.
1567
+ yield* push(taskPart("prt_task_resume", "running", child));
1568
+ yield* push(childPrompt("msg_child_resume", 5));
1569
+ yield* push(status(child, "busy"));
1570
+
1571
+ const turns = Array.from(yield* Fiber.join(childTurns)).flatMap((event) =>
1572
+ event.type === "provider_turn.updated" ? [event.providerTurn] : [],
1573
+ );
1574
+ assert.equal(new Set(turns.map((turn) => turn.providerThreadId)).size, 1);
1575
+ assert.deepEqual(
1576
+ turns.map((turn) => turn.ordinal),
1577
+ restarted ? [2] : [1, 2],
1578
+ );
1579
+ }).pipe(
1580
+ Effect.provide(Layer.merge(IdAllocator.layer, McpProviderSessions.layer)),
1581
+ Effect.scoped,
1582
+ ),
1583
+ );
1584
+
1585
it.effect("projects OpenCode read output and search titles from native tool calls", () =>
1586
Effect.gen(function* () {
1587
const directoryOutput =
packages/provider-opencode/src/server/adapter.ts
+35
-5
@@ -378,7 +378,8 @@ interface OpenCodeThreadState {
378
readonly messageRoles: Map<string, "user" | "assistant">;
379
readonly userMessageIds: Array<string>;
380
parentSubagent: OpenCodeSubagentContext | null;
381
- nextChildTurnOrdinal: number;
381
+ // null: a child resumed after a restart, whose next ordinal is recovered from OpenCode.
382
+ nextChildTurnOrdinal: number | null;
383
nextAdmissionGeneration: number;
384
permission: PermissionRuleset;
385
/** Parent rules last written into this child's `permission`; empty for root sessions. */
@@ -1308,6 +1309,22 @@ export const makeOpenCodeAdapterV2 = Effect.fn("makeOpenCodeAdapterV2")(function
1309
});
1310
});
1311
1312
+ // A child turn's ordinal never exceeds its user message's position in the session, and that
1313
+ // position survives restarts, so it stays above every ordinal allocated before.
1314
+ const storedUserMessagePosition = Effect.fnUntraced(function* (
1315
+ childSessionId: string,
1316
+ messageId: string,
1317
+ ) {
1318
+ const response = yield* sdkCall("session.messages", { sessionID: childSessionId }, () =>
1319
+ client.session.messages({ sessionID: childSessionId }),
1320
+ );
1321
+ const userMessageIds = unwrapData("session.messages", response).flatMap((entry) =>
1322
+ entry.info.role === "user" ? [entry.info.id] : [],
1323
+ );
1324
+ const index = userMessageIds.indexOf(messageId);
1325
+ return (index === -1 ? userMessageIds.length : index) + 1;
1326
+ });
1327
+
1328
const emitSubagent = Effect.fnUntraced(function* (
1329
state: OpenCodeThreadState,
1330
turn: ActiveOpenCodeTurn,
@@ -1416,6 +1433,15 @@ export const makeOpenCodeAdapterV2 = Effect.fn("makeOpenCodeAdapterV2")(function
1433
permission: childPermission,
1434
}),
1435
);
1436
+ // A Task call with task_id resumes the child, whose earlier turns already hold ordinals.
1437
+ const knownChild = threads.get(childSessionId);
1438
+ const resumedChild = knownChild?.parentSubagent == null ? undefined : knownChild;
1439
+ const nextChildTurnOrdinal =
1440
+ resumedChild === undefined
1441
+ ? recordString(input, "task_id") === childSessionId
1442
+ ? null
1443
+ : 1
1444
+ : resumedChild.nextChildTurnOrdinal;
1445
threads.set(childSessionId, {
1446
nativeSessionId: childSessionId,
1447
providerThread: childProviderThread,
@@ -1423,10 +1449,10 @@ export const makeOpenCodeAdapterV2 = Effect.fn("makeOpenCodeAdapterV2")(function
1449
activeTurn: null,
1450
providerTurns: new Map(),
1451
runtimeRequests: new Map(),
1426
- messageRoles: new Map(),
1427
- userMessageIds: [],
1452
+ messageRoles: resumedChild?.messageRoles ?? new Map(),
1453
+ userMessageIds: resumedChild?.userMessageIds ?? [],
1454
parentSubagent: context,
1429
- nextChildTurnOrdinal: 1,
1455
+ nextChildTurnOrdinal,
1456
nextAdmissionGeneration: 1,
1457
permission: childPermission,
1458
inheritedPermission: openCodePermissionRules(turn.runtimePolicy),
@@ -2222,6 +2248,10 @@ export const makeOpenCodeAdapterV2 = Effect.fn("makeOpenCodeAdapterV2")(function
2248
message: Extract<OpenCodeMessage, { role: "user" }>,
2249
) {
2250
if (state.appThread === null || state.parentSubagent === null) return null;
2251
+ const ordinal =
2252
+ state.nextChildTurnOrdinal ??
2253
+ (yield* storedUserMessagePosition(state.nativeSessionId, message.id));
2254
+ state.nextChildTurnOrdinal = ordinal + 1;
2255
const now = yield* DateTime.now;
2256
const startedAt = dateTimeFromEpoch(message.time.created, now);
2257
const rootNodeId = idAllocator.derive.nodeFromProviderItem({
@@ -2238,7 +2268,7 @@ export const makeOpenCodeAdapterV2 = Effect.fn("makeOpenCodeAdapterV2")(function
2268
nodeId: rootNodeId,
2269
runAttemptId: null,
2270
nativeTurnRef: providerRef(message.id, "weak"),
2241
- ordinal: state.nextChildTurnOrdinal++,
2271
+ ordinal,
2272
status: "running",
2273
startedAt,
2274
completedAt: null,