Skip to content

Commit dfc152b

Browse files
committed
fix(opencode): persist recovered shell activity while idle
1 parent 70559ad commit dfc152b

5 files changed

Lines changed: 523 additions & 290 deletions

File tree

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

Lines changed: 177 additions & 146 deletions
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,6 @@ import {
4949
t3McpServerName,
5050
} from "@t3tools/provider-opencode/testing";
5151
import { resolveAttachmentPath } from "../../attachmentStore.ts";
52-
import { makeProviderEventRoutingState, routeProviderEvent } from "../RunExecutionService.ts";
5352
import { openCode2ReplayRuntime } from "./OpenCode2AdapterV2.testkit.ts";
5453
import {
5554
makeProviderReplayGate,
@@ -325,6 +324,7 @@ const resumed = (
325324
options?: {
326325
readonly version?: "2.2.1" | "2.2.5" | "2.2.6";
327326
readonly shellRecovery?: ReadonlyArray<ProviderReplayEntry>;
327+
readonly lastRunOrdinal?: number;
328328
readonly goal?: OrchestrationV2ProviderThread["goal"];
329329
readonly external?: boolean;
330330
readonly supervised?: boolean;
@@ -384,6 +384,9 @@ const resumed = (
384384
const thread = yield* runtime.resumeThread({
385385
providerThread: {
386386
...providerThread(yield* DateTime.now),
387+
...(options?.lastRunOrdinal === undefined
388+
? {}
389+
: { lastRunOrdinal: options.lastRunOrdinal }),
387390
...(options?.goal === undefined ? {} : { goal: options.goal }),
388391
},
389392
threadId,
@@ -901,11 +904,11 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
901904
);
902905
return { attached: Deferred.await(attached), terminal: Fiber.join(terminal) };
903906
});
904-
it.effect.each([false, true, "thread", "failed", "burst"] as const)(
907+
it.effect.each([false, true, "thread", "failed", "burst", "poll"] as const)(
905908
"tracks native background shells through launch, retained output, stop=%s",
906909
(stop) =>
907910
Effect.gen(function* () {
908-
const stopped = stop === true || stop === "thread";
911+
const stopped = stop === true || stop === "thread" || stop === "poll";
909912
const exitCode = stop === "failed" ? 7 : 0;
910913
const shellID = "sh_background";
911914
const tool = {
@@ -942,6 +945,9 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
942945
location: { directory: WORK },
943946
data: { output: "retained\n", cursor: 9, size: 9, truncated: false },
944947
}),
948+
...(stop === "poll"
949+
? [out("shell.output", "<any>"), reply("shell.output", "<hang>")]
950+
: []),
945951
event("session.execution.succeeded", { sessionID: SESSION }),
946952
...(stopped
947953
? []
@@ -984,17 +990,25 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
984990
{ replayGate: gate },
985991
);
986992
const items: Array<import("@t3tools/contracts").OrchestrationV2TurnItem> = [];
993+
const shellStarted = yield* Deferred.make<void>();
987994
const terminal = yield* runtime.events.pipe(
988995
Stream.tap((e) =>
989-
Effect.sync(() => {
990-
if (e.type === "turn_item.updated") items.push(e.turnItem);
996+
Effect.gen(function* () {
997+
if (e.type !== "turn_item.updated") return;
998+
items.push(e.turnItem);
999+
if (e.turnItem.type === "command_execution" && e.turnItem.output === "retained\n")
1000+
yield* Deferred.succeed(shellStarted, undefined);
9911001
}),
9921002
),
9931003
Stream.filter((e) => e.type === "turn.terminal"),
9941004
Stream.runHead,
9951005
Effect.forkScoped,
9961006
);
9971007
yield* runtime.startTurn(withLineage(thread));
1008+
if (stop === "poll") {
1009+
yield* Deferred.await(shellStarted);
1010+
yield* TestClock.adjust("2 seconds");
1011+
}
9981012
yield* Fiber.join(terminal);
9991013
assert.isTrue(yield* runtime.hasPendingBackgroundWorkForThread!(thread));
10001014
const settled = yield* runtime.events.pipe(
@@ -1031,156 +1045,173 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
10311045
}).pipe(Effect.scoped),
10321046
);
10331047

1034-
it.effect.each(["shell", "job", "fallback", "descendant", "settled"] as const)(
1035-
"recovers only owned native shells using %s inventory",
1036-
(discovery) =>
1037-
Effect.gen(function* () {
1038-
const id = "sh_recovered";
1039-
const info = {
1040-
id,
1041-
command: "sleep 600",
1042-
status: discovery === "settled" ? "exited" : "running",
1043-
...(discovery === "settled" ? { exit: 0 } : {}),
1044-
cwd: WORK,
1045-
shell: "/bin/sh",
1046-
file: "/remote/output",
1047-
metadata: { sessionID: SESSION },
1048-
time: { started: 1 },
1049-
};
1050-
const response = (data: unknown) => ({ location: { directory: WORK }, data });
1051-
const inventory: Array<ProviderReplayEntry> =
1052-
discovery === "shell"
1053-
? []
1054-
: [
1055-
out("job.list", { sessionID: SESSION, kind: "shell", descendants: "true" }),
1056-
reply(
1057-
"job.list",
1058-
discovery === "fallback"
1059-
? { status: 404, body: {} }
1060-
: {
1061-
data: [
1062-
{
1063-
kind: "shell",
1064-
shellID: id,
1065-
sessionID: discovery === "descendant" ? "ses_descendant" : SESSION,
1066-
command: info.command,
1067-
status: discovery === "settled" ? "completed" : "running",
1068-
},
1069-
],
1070-
},
1071-
),
1072-
];
1073-
if (discovery === "shell" || discovery === "fallback")
1074-
inventory.push(
1075-
out("shell.list", "<any>"),
1076-
reply(
1077-
"shell.list",
1078-
response([info, { ...info, id: "sh_other", metadata: { sessionID: "ses_other" } }]),
1079-
),
1080-
);
1048+
it.effect.each([
1049+
"shell",
1050+
"job",
1051+
"fallback",
1052+
"descendant",
1053+
"settled",
1054+
"exited",
1055+
"anchored",
1056+
] as const)("recovers only owned native shells using %s inventory", (discovery) =>
1057+
Effect.gen(function* () {
1058+
const idAllocator = yield* IdAllocator.IdAllocatorV2.pipe(Effect.provide(IdAllocator.layer));
1059+
const id = "sh_recovered";
1060+
const info = {
1061+
id,
1062+
command: "sleep 600",
1063+
status: discovery === "settled" ? "exited" : "running",
1064+
...(discovery === "settled" ? { exit: 0 } : {}),
1065+
cwd: WORK,
1066+
shell: "/bin/sh",
1067+
file: "/remote/output",
1068+
metadata: { sessionID: SESSION },
1069+
time: { started: 1 },
1070+
};
1071+
const response = (data: unknown) => ({ location: { directory: WORK }, data });
1072+
const inventory: Array<ProviderReplayEntry> =
1073+
discovery === "shell"
1074+
? []
1075+
: [
1076+
out("job.list", { sessionID: SESSION, kind: "shell", descendants: "true" }),
1077+
reply(
1078+
"job.list",
1079+
discovery === "fallback"
1080+
? { status: 404, body: {} }
1081+
: {
1082+
data: [
1083+
{
1084+
kind: "shell",
1085+
shellID: id,
1086+
sessionID: discovery === "descendant" ? "ses_descendant" : SESSION,
1087+
command: info.command,
1088+
status: discovery === "settled" ? "completed" : "running",
1089+
},
1090+
],
1091+
},
1092+
),
1093+
];
1094+
if (discovery === "shell" || discovery === "fallback")
10811095
inventory.push(
1082-
out("shell.get", { id }),
1083-
reply("shell.get", response(info)),
1084-
out("shell.output", { id, cursor: "0" }),
1096+
out("shell.list", "<any>"),
10851097
reply(
1086-
"shell.output",
1087-
response({ output: "retained", cursor: 8, size: 8, truncated: false }),
1098+
"shell.list",
1099+
response([info, { ...info, id: "sh_other", metadata: { sessionID: "ses_other" } }]),
10881100
),
10891101
);
1090-
const { runtime, thread } = yield* resumed(
1091-
[
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-
]),
1107-
],
1108-
{
1109-
version: discovery === "shell" ? "2.2.1" : "2.2.6",
1110-
shellRecovery: inventory,
1111-
external: true,
1112-
},
1113-
);
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-
}),
1127-
),
1128-
Effect.forkScoped,
1129-
);
1130-
assert.deepEqual(
1131-
thread.pendingBackgroundTasks ?? [],
1132-
discovery === "settled"
1133-
? []
1134-
: [{ taskId: id, kind: "command", description: info.command }],
1102+
inventory.push(
1103+
out("shell.get", { id }),
1104+
reply("shell.get", response(info)),
1105+
out("shell.output", { id, cursor: "0" }),
1106+
reply(
1107+
"shell.output",
1108+
response({ output: "retained", cursor: 8, size: 8, truncated: false }),
1109+
),
1110+
);
1111+
const gate = makeProviderReplayGate(["recovered-exit"]);
1112+
const { runtime, thread } = yield* resumed(
1113+
discovery === "settled"
1114+
? []
1115+
: [
1116+
...(discovery === "exited"
1117+
? [event("shell.exited", { id, exit: 0, status: "exited" }, "recovered-exit")]
1118+
: []),
1119+
out("shell.output", { id, cursor: "8" }),
1120+
reply(
1121+
"shell.output",
1122+
response({
1123+
output: discovery === "exited" ? " finished" : "",
1124+
cursor: discovery === "exited" ? 17 : 8,
1125+
size: discovery === "exited" ? 17 : 8,
1126+
truncated: false,
1127+
}),
1128+
),
1129+
...(discovery === "exited"
1130+
? []
1131+
: [out("shell.remove", { id }), reply("shell.remove", null)]),
1132+
],
1133+
{
1134+
version: discovery === "shell" ? "2.2.1" : "2.2.6",
1135+
shellRecovery: inventory,
1136+
external: true,
1137+
...(discovery === "anchored" ? { lastRunOrdinal: 7 } : {}),
1138+
replayGate: gate,
1139+
},
1140+
);
1141+
const items: Array<ProviderAdapter.ProviderAdapterV2Event> = [];
1142+
const shellEnded = yield* Deferred.make<void>();
1143+
const rosterEnded = yield* Deferred.make<void>();
1144+
yield* runtime.events.pipe(
1145+
Stream.runForEach((event) =>
1146+
Effect.gen(function* () {
1147+
if (
1148+
event.type === "provider_thread.updated" &&
1149+
event.sessionScoped === true &&
1150+
event.providerThread.pendingBackgroundTasks?.length === 0
1151+
)
1152+
yield* Deferred.succeed(rosterEnded, undefined);
1153+
if (event.type !== "turn_item.updated" || event.turnItem.type !== "command_execution")
1154+
return;
1155+
items.push(event);
1156+
if (event.turnItem.status !== "running") yield* Deferred.succeed(shellEnded, undefined);
1157+
}),
1158+
),
1159+
Effect.forkScoped,
1160+
);
1161+
assert.deepEqual(
1162+
thread.pendingBackgroundTasks ?? [],
1163+
discovery === "settled" ? [] : [{ taskId: id, kind: "command", description: info.command }],
1164+
);
1165+
assert.equal(
1166+
yield* runtime.hasPendingBackgroundWorkForThread!(thread),
1167+
discovery !== "settled",
1168+
);
1169+
yield* runtime.stopTask!({ providerThread: thread, taskId: "sh_other" });
1170+
assert.equal(
1171+
yield* runtime.hasPendingBackgroundWorkForThread!(thread),
1172+
discovery !== "settled",
1173+
);
1174+
if (discovery === "exited") gate.release("recovered-exit");
1175+
else yield* runtime.stopTask!({ providerThread: thread, taskId: id });
1176+
yield* Deferred.await(shellEnded);
1177+
yield* Deferred.await(rosterEnded);
1178+
assert.isFalse(yield* runtime.hasPendingBackgroundWorkForThread!(thread));
1179+
const item = items;
1180+
const projected = item.at(0);
1181+
const stopped = item.at(-1);
1182+
if (stopped?.type === "turn_item.updated" && stopped.turnItem.type === "command_execution") {
1183+
assert.equal(
1184+
stopped.turnItem.status,
1185+
discovery === "settled" || discovery === "exited" ? "completed" : "interrupted",
11351186
);
11361187
assert.equal(
1137-
yield* runtime.hasPendingBackgroundWorkForThread!(thread),
1138-
discovery !== "settled",
1188+
stopped.turnItem.output,
1189+
discovery === "exited" ? "retained finished" : "retained",
11391190
);
1140-
yield* runtime.startTurn(withLineage(thread));
1141-
yield* Deferred.await(rootEnded);
1142-
yield* runtime.stopTask!({ providerThread: thread, taskId: "sh_other" });
11431191
assert.equal(
1144-
yield* runtime.hasPendingBackgroundWorkForThread!(thread),
1145-
discovery !== "settled",
1192+
stopped.turnItem.id,
1193+
projected?.type === "turn_item.updated" ? projected.turnItem.id : undefined,
11461194
);
1147-
yield* runtime.stopTask!({ providerThread: thread, taskId: id });
1148-
assert.isFalse(yield* runtime.hasPendingBackgroundWorkForThread!(thread));
1149-
yield* Deferred.await(shellEnded);
1150-
const item = items;
1151-
const projected = item.at(0);
1152-
const stopped = item.at(-1);
1153-
if (stopped?.type === "turn_item.updated") {
1154-
assert.equal(
1155-
stopped.turnItem.status,
1156-
discovery === "settled" ? "completed" : "interrupted",
1157-
);
1158-
assert.equal(
1159-
stopped.turnItem.id,
1160-
projected?.type === "turn_item.updated" ? projected.turnItem.id : undefined,
1161-
);
1162-
}
1163-
assert.equal(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-
);
1177-
assert.deepInclude(projected.turnItem, {
1178-
type: "command_execution",
1179-
input: info.command,
1180-
output: "retained",
1181-
});
1182-
}
1183-
}).pipe(Effect.scoped),
1195+
}
1196+
assert.equal(projected?.type, "turn_item.updated");
1197+
if (projected?.type === "turn_item.updated") {
1198+
assert.isTrue(
1199+
item.every(
1200+
(event) =>
1201+
event.type === "turn_item.updated" &&
1202+
event.turnItem.runId ===
1203+
(discovery === "anchored"
1204+
? idAllocator.derive.run({ threadId, ordinal: 7 })
1205+
: null),
1206+
),
1207+
);
1208+
assert.deepInclude(projected.turnItem, {
1209+
type: "command_execution",
1210+
input: info.command,
1211+
output: "retained",
1212+
});
1213+
}
1214+
}).pipe(Effect.scoped),
11841215
);
11851216

11861217
it.effect.each(["remove", "lookup", "output"] as const)(

0 commit comments

Comments
 (0)