Skip to content

Commit 70559ad

Browse files
committed
fix(opencode): bind recovered shell activity to its owning run
1 parent 481bb3a commit 70559ad

2 files changed

Lines changed: 100 additions & 52 deletions

File tree

‎apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts‎

Lines changed: 69 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,7 @@ import {
4949
t3McpServerName,
5050
} from "@t3tools/provider-opencode/testing";
5151
import { resolveAttachmentPath } from "../../attachmentStore.ts";
52+
import { makeProviderEventRoutingState, routeProviderEvent } from "../RunExecutionService.ts";
5253
import { openCode2ReplayRuntime } from "./OpenCode2AdapterV2.testkit.ts";
5354
import {
5455
makeProviderReplayGate,
@@ -1030,15 +1031,16 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
10301031
}).pipe(Effect.scoped),
10311032
);
10321033

1033-
it.effect.each(["shell", "job", "fallback", "descendant"] as const)(
1034+
it.effect.each(["shell", "job", "fallback", "descendant", "settled"] as const)(
10341035
"recovers only owned native shells using %s inventory",
10351036
(discovery) =>
10361037
Effect.gen(function* () {
10371038
const id = "sh_recovered";
10381039
const info = {
10391040
id,
10401041
command: "sleep 600",
1041-
status: "running",
1042+
status: discovery === "settled" ? "exited" : "running",
1043+
...(discovery === "settled" ? { exit: 0 } : {}),
10421044
cwd: WORK,
10431045
shell: "/bin/sh",
10441046
file: "/remote/output",
@@ -1062,7 +1064,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
10621064
shellID: id,
10631065
sessionID: discovery === "descendant" ? "ses_descendant" : SESSION,
10641066
command: info.command,
1065-
status: "running",
1067+
status: discovery === "settled" ? "completed" : "running",
10661068
},
10671069
],
10681070
},
@@ -1087,52 +1089,97 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
10871089
);
10881090
const { runtime, thread } = yield* resumed(
10891091
[
1090-
out("shell.output", { id, cursor: "8" }),
1091-
reply("shell.output", response({ output: "", cursor: 8, size: 8, truncated: false })),
1092-
out("shell.remove", { id }),
1093-
reply("shell.remove", null),
1092+
out("session.prompt", { sessionID: SESSION, text: "<any>" }),
1093+
promptAccepted,
1094+
event("session.execution.started", { sessionID: SESSION }),
1095+
event("session.execution.succeeded", { sessionID: SESSION }),
1096+
...(discovery === "settled"
1097+
? []
1098+
: [
1099+
out("shell.output", { id, cursor: "8" }),
1100+
reply(
1101+
"shell.output",
1102+
response({ output: "", cursor: 8, size: 8, truncated: false }),
1103+
),
1104+
out("shell.remove", { id }),
1105+
reply("shell.remove", null),
1106+
]),
10941107
],
10951108
{
10961109
version: discovery === "shell" ? "2.2.1" : "2.2.6",
10971110
shellRecovery: inventory,
10981111
external: true,
10991112
},
11001113
);
1101-
const recovered = yield* runtime.events.pipe(
1102-
Stream.filter(
1103-
(e) => e.type === "turn_item.updated" && e.turnItem.type === "command_execution",
1104-
),
1105-
Stream.takeUntil(
1106-
(e) => e.type === "turn_item.updated" && e.turnItem.status === "interrupted",
1114+
const items: Array<ProviderAdapter.ProviderAdapterV2Event> = [];
1115+
const rootEnded = yield* Deferred.make<void>();
1116+
const shellEnded = yield* Deferred.make<void>();
1117+
yield* runtime.events.pipe(
1118+
Stream.runForEach((event) =>
1119+
Effect.gen(function* () {
1120+
if (event.type === "turn.terminal") yield* Deferred.succeed(rootEnded, undefined);
1121+
if (event.type !== "turn_item.updated" || event.turnItem.type !== "command_execution")
1122+
return;
1123+
items.push(event);
1124+
if (event.turnItem.status !== "running")
1125+
yield* Deferred.succeed(shellEnded, undefined);
1126+
}),
11071127
),
1108-
Stream.runCollect,
11091128
Effect.forkScoped,
11101129
);
1111-
assert.deepEqual(thread.pendingBackgroundTasks, [
1112-
{ taskId: id, kind: "command", description: info.command },
1113-
]);
1114-
assert.isTrue(yield* runtime.hasPendingBackgroundWorkForThread!(thread));
1130+
assert.deepEqual(
1131+
thread.pendingBackgroundTasks ?? [],
1132+
discovery === "settled"
1133+
? []
1134+
: [{ taskId: id, kind: "command", description: info.command }],
1135+
);
1136+
assert.equal(
1137+
yield* runtime.hasPendingBackgroundWorkForThread!(thread),
1138+
discovery !== "settled",
1139+
);
1140+
yield* runtime.startTurn(withLineage(thread));
1141+
yield* Deferred.await(rootEnded);
11151142
yield* runtime.stopTask!({ providerThread: thread, taskId: "sh_other" });
1116-
assert.isTrue(yield* runtime.hasPendingBackgroundWorkForThread!(thread));
1143+
assert.equal(
1144+
yield* runtime.hasPendingBackgroundWorkForThread!(thread),
1145+
discovery !== "settled",
1146+
);
11171147
yield* runtime.stopTask!({ providerThread: thread, taskId: id });
11181148
assert.isFalse(yield* runtime.hasPendingBackgroundWorkForThread!(thread));
1119-
const item = yield* Fiber.join(recovered);
1149+
yield* Deferred.await(shellEnded);
1150+
const item = items;
11201151
const projected = item.at(0);
11211152
const stopped = item.at(-1);
11221153
if (stopped?.type === "turn_item.updated") {
1123-
assert.equal(stopped.turnItem.status, "interrupted");
1154+
assert.equal(
1155+
stopped.turnItem.status,
1156+
discovery === "settled" ? "completed" : "interrupted",
1157+
);
11241158
assert.equal(
11251159
stopped.turnItem.id,
11261160
projected?.type === "turn_item.updated" ? projected.turnItem.id : undefined,
11271161
);
11281162
}
11291163
assert.equal(projected?.type, "turn_item.updated");
1130-
if (projected?.type === "turn_item.updated")
1164+
if (projected?.type === "turn_item.updated") {
1165+
const input = turnInput(thread);
1166+
const identity = {
1167+
threadId: input.threadId,
1168+
runId: input.runId,
1169+
attemptId: input.attemptId,
1170+
providerThreadId: thread.id,
1171+
};
1172+
const routing = makeProviderEventRoutingState({ identity, providerTurnId: null });
1173+
assert.isTrue(
1174+
item.every((event) => routeProviderEvent(event, identity, routing)[0]),
1175+
"recovered output and terminal state must pass server event routing",
1176+
);
11311177
assert.deepInclude(projected.turnItem, {
11321178
type: "command_execution",
11331179
input: info.command,
11341180
output: "retained",
11351181
});
1182+
}
11361183
}).pipe(Effect.scoped),
11371184
);
11381185

‎packages/provider-opencode/src/server/v2/adapter.ts‎

Lines changed: 31 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -904,6 +904,8 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
904904
output: string;
905905
cursor: number;
906906
startedAt?: DateTime.Utc;
907+
projectionState?: ThreadState;
908+
settlement?: { status: "completed" | "failed" | "interrupted"; exit: number | undefined };
907909
}
908910
>();
909911

@@ -1589,42 +1591,35 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
15891591
const shell = shells.get(id);
15901592
if (shell === undefined) return;
15911593
if (shell.turn === undefined || shell.toolId === undefined || shell.tool === undefined) {
1592-
const updatedAt = yield* DateTime.now;
1593-
yield* emit({
1594-
type: "turn_item.updated",
1595-
driver,
1596-
turnItem: {
1597-
id: idAllocator.derive.turnItemFromProviderItem({ driver, nativeItemId: id }),
1598-
threadId: shell.state.providerThread.appThreadId ?? input.threadId,
1599-
runId: null,
1600-
nodeId: null,
1601-
providerThreadId: shell.state.providerThread.id,
1602-
providerTurnId: null,
1603-
nativeItemRef: ref(id),
1604-
parentItemId: null,
1605-
ordinal: 0,
1606-
status,
1607-
title: null,
1608-
startedAt: shell.startedAt ?? updatedAt,
1609-
completedAt: status === "running" ? null : updatedAt,
1610-
updatedAt,
1611-
type: "command_execution",
1612-
input: shell.command,
1613-
output: shell.output,
1614-
...(exit === undefined ? {} : { exitCode: exit }),
1615-
},
1616-
});
1594+
if (status !== "running") shell.settlement = { status, exit };
16171595
return;
16181596
}
16191597
shell.turn.tools.set(shell.toolId, shell.tool);
1620-
yield* emitTool(shell.state, shell.turn, shell.toolId, status, {
1598+
yield* emitTool(shell.projectionState ?? shell.state, shell.turn, shell.toolId, status, {
16211599
output: shell.output,
16221600
nativeTaskId: id,
16231601
metadata: { shellID: id, exit },
16241602
});
16251603
shell.turn.tools.delete(shell.toolId);
16261604
});
16271605

1606+
const bindRecoveredShells = Effect.fn("OpenCode2Adapter.bindRecoveredShells")(function* (
1607+
state: ThreadState,
1608+
turn: ActiveTurn,
1609+
) {
1610+
for (const [id, shell] of shells) {
1611+
if (shell.turn !== undefined || !sessionsOf(state).includes(shell.state)) continue;
1612+
// Root command events need a real run owner to pass server routing.
1613+
shell.turn = turn;
1614+
shell.projectionState = state;
1615+
shell.toolId = id;
1616+
shell.tool = { name: "shell", input: { command: shell.command } };
1617+
turn.startedAt.set(id, shell.startedAt ?? (yield* DateTime.now));
1618+
yield* emitShell(id, shell.settlement?.status ?? "running", shell.settlement?.exit);
1619+
if (shell.settlement !== undefined) shells.delete(id);
1620+
}
1621+
});
1622+
16281623
const stopShell = Effect.fn("OpenCode2Adapter.stopShell")(function* (id: string) {
16291624
const shell = shells.get(id);
16301625
if (shell === undefined || !shell.running) return;
@@ -1647,7 +1642,7 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
16471642
shell.running = false;
16481643
shell.state.stoppedChildren.add(id);
16491644
yield* emitShell(id, "interrupted");
1650-
shells.delete(id);
1645+
if (shell.turn !== undefined) shells.delete(id);
16511646
shellInfo.delete(id);
16521647
yield* syncRosterAncestors(shell.state);
16531648
});
@@ -1730,7 +1725,12 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
17301725
lock.withPermit(
17311726
effect.pipe(
17321727
Effect.timeout(INVENTORY_TIMEOUT),
1733-
Effect.ensuring(syncRosterAncestors(state)),
1728+
Effect.ensuring(
1729+
Effect.gen(function* () {
1730+
if (state.active !== undefined) yield* bindRecoveredShells(state, state.active);
1731+
yield* syncRosterAncestors(state);
1732+
}),
1733+
),
17341734
),
17351735
),
17361736
);
@@ -2830,7 +2830,7 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
28302830
: "completed",
28312831
);
28322832
}
2833-
shells.delete(id);
2833+
if (shell?.turn !== undefined) shells.delete(id);
28342834
shellInfo.delete(id);
28352835
}
28362836
return;
@@ -2928,7 +2928,7 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
29282928
: "failed",
29292929
"exit" in event.data ? event.data.exit : undefined,
29302930
);
2931-
shells.delete(event.data.id);
2931+
if (shell.turn !== undefined) shells.delete(event.data.id);
29322932
shellInfo.delete(event.data.id);
29332933
yield* syncRosterAncestors(shell.state);
29342934
return;
@@ -3961,6 +3961,7 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
39613961
};
39623962
yield* emitProviderThread(state);
39633963
yield* setSessionStatus("running", null);
3964+
yield* lock.withPermit(bindRecoveredShells(state, turn));
39643965
return turn;
39653966
});
39663967

0 commit comments

Comments
 (0)