Skip to content

Commit 881f9db

Browse files
committed
fix(server): set OpenCode turns from live busy status
Read the live OpenCode status before recovery after an idle or error event. Start one active turn when the server reports busy work. Keep user Stop active during recovery. Tests include stale status, duplicate busy events, completion, and Stop during recovery.
1 parent 77bca8b commit 881f9db

2 files changed

Lines changed: 208 additions & 0 deletions

File tree

‎apps/server/src/provider/Layers/OpenCodeAdapter.test.ts‎

Lines changed: 149 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4888,6 +4888,155 @@ it.layer(OpenCodeAdapterTestLayer)("OpenCodeAdapterLive", (it) => {
48884888
}),
48894889
);
48904890

4891+
for (const previousState of ["completed", "failed", "interrupted"] as const) {
4892+
for (const liveStatus of ["busy", "idle", "unknown"] as const) {
4893+
it.effect(
4894+
`checks live status after ${previousState} before ${liveStatus} recovery`,
4895+
() =>
4896+
Effect.gen(function* () {
4897+
const adapter = yield* OpenCodeAdapter;
4898+
const threadId = asThreadId(`thread-adopt-${previousState}-${liveStatus}`);
4899+
const sessionID = "http://127.0.0.1:9999/session";
4900+
const enqueue = makeOpenCodeEventQueue();
4901+
yield* adapter.startSession({
4902+
provider: ProviderDriverKind.make("opencode"),
4903+
threadId,
4904+
runtimeMode: "full-access",
4905+
});
4906+
const turn = yield* adapter.sendTurn({
4907+
threadId,
4908+
input: "Read the synthetic fixture",
4909+
modelSelection: createModelSelection(
4910+
ProviderInstanceId.make("opencode"),
4911+
"opencode/kimi-k3",
4912+
),
4913+
});
4914+
const settled = yield* adapter.streamEvents.pipe(
4915+
Stream.filter(
4916+
(event) =>
4917+
event.threadId === threadId &&
4918+
(event.type === "turn.completed" || event.type === "turn.aborted"),
4919+
),
4920+
Stream.runHead,
4921+
Effect.forkChild,
4922+
);
4923+
if (previousState === "interrupted") {
4924+
yield* adapter.interruptTurn(threadId, turn.turnId);
4925+
} else {
4926+
enqueue(
4927+
previousState === "failed"
4928+
? {
4929+
type: "session.error",
4930+
properties: {
4931+
sessionID,
4932+
error: { name: "UnknownError", data: { message: "Synthetic failure" } },
4933+
},
4934+
}
4935+
: { type: "session.status", properties: { sessionID, status: { type: "idle" } } },
4936+
);
4937+
}
4938+
yield* Fiber.join(settled);
4939+
runtimeMock.state.sessionStatusImplementation = async () => ({
4940+
data: liveStatus === "unknown" ? null : { [sessionID]: { type: liveStatus } },
4941+
});
4942+
const recovered = yield* adapter.streamEvents.pipe(
4943+
Stream.filter((event) => event.threadId === threadId),
4944+
Stream.takeUntil((event) => event.type === "thread.state.changed"),
4945+
Stream.runCollect,
4946+
Effect.forkChild,
4947+
);
4948+
for (let index = 0; index < 2; index += 1) {
4949+
enqueue({
4950+
type: "session.status",
4951+
properties: { sessionID, status: { type: "busy" } },
4952+
});
4953+
}
4954+
enqueue({ type: "session.compacted", properties: { sessionID } });
4955+
const events = yield* Fiber.join(recovered);
4956+
const starts = events.filter((event) => event.type === "turn.started");
4957+
const shouldAdopt = liveStatus === "busy" && previousState !== "interrupted";
4958+
NodeAssert.equal(starts.length, shouldAdopt ? 1 : 0);
4959+
const session = (yield* adapter.listSessions()).find(
4960+
(entry) => entry.threadId === threadId,
4961+
);
4962+
if (shouldAdopt) {
4963+
NodeAssert.equal(session?.status, "running");
4964+
NodeAssert.ok(session?.activeTurnId);
4965+
NodeAssert.notEqual(session.activeTurnId, turn.turnId);
4966+
NodeAssert.equal(starts[0]?.turnId, session.activeTurnId);
4967+
const stopped = yield* adapter.streamEvents.pipe(
4968+
Stream.filter(
4969+
(event) =>
4970+
event.threadId === threadId &&
4971+
event.type ===
4972+
(previousState === "completed" ? "turn.completed" : "turn.aborted"),
4973+
),
4974+
Stream.runHead,
4975+
Effect.forkChild,
4976+
);
4977+
if (previousState === "completed") {
4978+
enqueue({
4979+
type: "session.status",
4980+
properties: { sessionID, status: { type: "idle" } },
4981+
});
4982+
} else {
4983+
yield* adapter.interruptTurn(threadId, session.activeTurnId);
4984+
}
4985+
NodeAssert.equal(
4986+
Option.getOrThrow(yield* Fiber.join(stopped)).turnId,
4987+
session.activeTurnId,
4988+
);
4989+
} else {
4990+
NodeAssert.equal(session?.activeTurnId, undefined);
4991+
NodeAssert.equal(session?.status, previousState === "failed" ? "error" : "ready");
4992+
}
4993+
yield* adapter.stopSession(threadId);
4994+
}),
4995+
);
4996+
}
4997+
}
4998+
4999+
it.effect("keeps Stop active during the busy status request", () =>
5000+
Effect.gen(function* () {
5001+
const adapter = yield* OpenCodeAdapter;
5002+
const threadId = asThreadId("thread-stop-during-busy-recovery");
5003+
const sessionID = "http://127.0.0.1:9999/session";
5004+
const enqueue = makeOpenCodeEventQueue();
5005+
const requested = promiseWithResolvers<void>();
5006+
const statusResponse = promiseWithResolvers<unknown>();
5007+
runtimeMock.state.sessionStatusImplementation = () => {
5008+
requested.resolve(undefined);
5009+
return statusResponse.promise;
5010+
};
5011+
yield* adapter.startSession({
5012+
provider: ProviderDriverKind.make("opencode"),
5013+
threadId,
5014+
runtimeMode: "full-access",
5015+
});
5016+
const eventsFiber = yield* adapter.streamEvents.pipe(
5017+
Stream.filter((event) => event.threadId === threadId),
5018+
Stream.takeUntil((event) => event.type === "thread.state.changed"),
5019+
Stream.runCollect,
5020+
Effect.forkChild,
5021+
);
5022+
enqueue({ type: "session.status", properties: { sessionID, status: { type: "busy" } } });
5023+
yield* Effect.promise(() => requested.promise);
5024+
yield* adapter.interruptTurn(threadId);
5025+
statusResponse.resolve({ data: { [sessionID]: { type: "busy" } } });
5026+
enqueue({ type: "session.compacted", properties: { sessionID } });
5027+
const events = yield* Fiber.join(eventsFiber);
5028+
NodeAssert.equal(
5029+
events.some((event) => event.type === "turn.started"),
5030+
false,
5031+
);
5032+
const session = (yield* adapter.listSessions()).find((entry) => entry.threadId === threadId);
5033+
NodeAssert.equal(session?.activeTurnId, undefined);
5034+
NodeAssert.equal(session?.status, "ready");
5035+
NodeAssert.deepEqual(runtimeMock.state.abortCalls, [sessionID]);
5036+
yield* adapter.stopSession(threadId);
5037+
}),
5038+
);
5039+
48915040
it.effect("ignores late busy and idle status after an interrupted turn", () =>
48925041
Effect.gen(function* () {
48935042
const adapter = yield* OpenCodeAdapter;

‎apps/server/src/provider/Layers/OpenCodeAdapter.ts‎

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2153,6 +2153,58 @@ export function makeOpenCodeAdapter(
21532153
yield* run.pipe(Effect.forkIn(context.sessionScope));
21542154
});
21552155

2156+
const recoverBusyOpenCodeTurn = Effect.fn("recoverBusyOpenCodeTurn")(function* (
2157+
context: OpenCodeSessionContext,
2158+
raw: unknown,
2159+
) {
2160+
const generation = context.promptGeneration;
2161+
const canRecover = () =>
2162+
sessions.get(context.session.threadId) === context &&
2163+
context.activeTurnId === undefined &&
2164+
context.promptGeneration === generation &&
2165+
context.promptAdmission === undefined &&
2166+
context.cancellation === undefined &&
2167+
context.interruptedTurnId === undefined &&
2168+
!context.reconcileIdleStatus &&
2169+
!context.awaitingBusyAfterInterruption;
2170+
if (!canRecover()) {
2171+
return;
2172+
}
2173+
// T3 can get a busy event after its turn ends.
2174+
// Read the live status before recovery from a different client.
2175+
const response = yield* runOpenCodeSdk("session.status", (signal) =>
2176+
context.client.session.status(undefined, { signal }),
2177+
).pipe(Effect.timeout("1 second"), Effect.option);
2178+
const statuses = Option.isSome(response)
2179+
? Option.getOrUndefined(decodeOpenCodeSessionStatusMap(response.value.data))
2180+
: undefined;
2181+
const status = statuses?.[context.openCodeSessionId];
2182+
if (status?.type !== "busy" && status?.type !== "retry") {
2183+
return;
2184+
}
2185+
const turnId = TurnId.make(`opencode-turn-${yield* randomUUIDv4}`);
2186+
const base = yield* buildEventBase({ threadId: context.session.threadId, turnId, raw });
2187+
const stopped = yield* Ref.get(context.stopped);
2188+
if (stopped || !canRecover()) {
2189+
return;
2190+
}
2191+
context.promptGeneration += 1;
2192+
context.activeTurnId = turnId;
2193+
context.turnTokenUsage = makeOpenCodeTurnTokenUsageAccumulator();
2194+
context.turnTokenUsage.complete = false;
2195+
applyProviderSessionUpdate(
2196+
context,
2197+
{ status: "running", activeTurnId: turnId },
2198+
{ clearLastError: true },
2199+
base.createdAt,
2200+
);
2201+
emitUnsafe({
2202+
...base,
2203+
type: "turn.started",
2204+
payload: { model: context.session.model },
2205+
});
2206+
});
2207+
21562208
const handleSubscribedEvent = Effect.fn("handleSubscribedEvent")(function* (
21572209
context: OpenCodeSessionContext,
21582210
event: OpenCodeSubscribedEvent,
@@ -2242,6 +2294,13 @@ export function makeOpenCodeAdapter(
22422294
return;
22432295
}
22442296

2297+
if (
2298+
event.type === "session.status" &&
2299+
(event.properties.status.type === "busy" || event.properties.status.type === "retry") &&
2300+
context.activeTurnId === undefined
2301+
) {
2302+
yield* recoverBusyOpenCodeTurn(context, event);
2303+
}
22452304
const turnId = context.activeTurnId;
22462305
yield* writeNativeEventBestEffort(context.session.threadId, {
22472306
observedAt: yield* nowIso,

0 commit comments

Comments
 (0)