Skip to content

Commit 975c081

Browse files
fix(opencode): Stop waits for every interrupted session before its last shell sweep
Stop waited for the foreground turn's execution to end before its final shell sweep, but not for the background subagents and follow-up sessions it interrupted, and it interrupted a running autonomous wake only after that sweep. A shell one of them launched after acknowledging the interrupt outlived Stop. Every execution Stop interrupts now goes through the same step: interrupt it, then wait (bounded by the interrupt timeout, concurrently) for its end before the next sweep. The running wake is interrupted there too, after the foreground stop, instead of inside the settle step. Shell removes in one pass run concurrently, so stalled removes cost one timeout. Steering is unchanged. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent c88510a commit 975c081

2 files changed

Lines changed: 125 additions & 33 deletions

File tree

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

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1353,6 +1353,77 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
13531353
}).pipe(Effect.scoped),
13541354
);
13551355

1356+
it.effect("removes a shell a background subagent launched while Stop interrupted it", () =>
1357+
Effect.gen(function* () {
1358+
const launch = shellLaunched(CHILD, "sh_late");
1359+
const { runtime, thread } = yield* resumed([
1360+
...backgroundLaunch(CHILD),
1361+
returnedRunning("call-background"),
1362+
event("session.execution.started", { sessionID: CHILD }),
1363+
...launch.slice(0, -1),
1364+
event("session.execution.succeeded", { sessionID: SESSION }),
1365+
out("session.interrupt", { sessionID: CHILD }),
1366+
reply("session.interrupt", { interrupted: true }),
1367+
// The child's shell starts after the interrupt returns, before its execution ends.
1368+
launch.at(-1)!,
1369+
event("session.execution.interrupted", { sessionID: CHILD }),
1370+
removeShell("sh_late"),
1371+
shellReport(CHILD, "sh_late", "error", "Shell.NotFoundError"),
1372+
reply("shell.remove", null),
1373+
drained,
1374+
]);
1375+
const watch = yield* watchCalls(runtime, thread);
1376+
yield* runtime.startTurn(withLineage(thread));
1377+
yield* watch.until(() => watch.terminals.length > 0);
1378+
yield* runtime.interruptTurn({
1379+
providerThread: thread,
1380+
providerTurnId: yield* providerTurnId,
1381+
requestRuntimeRestart: true,
1382+
});
1383+
assert.isFalse(yield* runtime.hasPendingBackgroundWork!);
1384+
yield* watch.until(() => watch.state.variant === "drained");
1385+
assert.deepEqual(watch.state.roster, []);
1386+
}).pipe(Effect.scoped),
1387+
);
1388+
1389+
it.effect("removes a shell a held wake launched while Stop interrupted it", () =>
1390+
Effect.gen(function* () {
1391+
const launch = shellLaunched(SESSION, "sh_late");
1392+
const { runtime, thread } = yield* resumed([
1393+
event("session.execution.started", { sessionID: SESSION }),
1394+
...shellLaunched(SESSION, "sh_first"),
1395+
...launch.slice(0, -1),
1396+
removeShell("sh_first"),
1397+
shellReport(SESSION, "sh_first", "error", "Shell.NotFoundError"),
1398+
reply("shell.remove", null),
1399+
out("session.interrupt", { sessionID: SESSION }),
1400+
reply("session.interrupt", { interrupted: true }),
1401+
// The wake's shell starts after the interrupt returns, before its execution ends.
1402+
launch.at(-1)!,
1403+
event("session.execution.interrupted", { sessionID: SESSION }),
1404+
removeShell("sh_late"),
1405+
shellReport(SESSION, "sh_late", "error", "Shell.NotFoundError"),
1406+
reply("shell.remove", null),
1407+
drained,
1408+
]).pipe(
1409+
Effect.provideService(ProviderContinuationRequests.ProviderContinuationRequests, {
1410+
offer: () => Effect.void,
1411+
take: Effect.never,
1412+
}),
1413+
);
1414+
const watch = yield* watchCalls(runtime, thread);
1415+
yield* watch.until(() => watch.state.roster?.length === 1);
1416+
yield* runtime.interruptTurn({
1417+
providerThread: thread,
1418+
providerTurnId: yield* providerTurnId,
1419+
requestRuntimeRestart: true,
1420+
});
1421+
assert.isFalse(yield* runtime.hasPendingBackgroundWork!);
1422+
yield* watch.until(() => watch.state.variant === "drained");
1423+
assert.deepEqual(watch.state.roster, []);
1424+
}).pipe(Effect.scoped),
1425+
);
1426+
13561427
it.effect("stops a subagent launched while Stop removes a shell", () =>
13571428
Effect.gen(function* () {
13581429
const { runtime, thread } = yield* resumed([

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

Lines changed: 54 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -3469,11 +3469,16 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
34693469
);
34703470
const childrenOf = (call: SubagentCall) =>
34713471
call.child === undefined ? announcedTo(call.state) : [call.child.sessionId];
3472-
const interrupted = new Set<string>();
3473-
const unstopped = () =>
3472+
// Keyed by session, or by wake since each wake is its own execution of the thread's session.
3473+
const interrupted = new Set<string | Wake>();
3474+
const unstopped = (wakes: boolean) =>
34743475
[
34753476
...backgroundCalls().flatMap((call) =>
3476-
childrenOf(call).map((sessionId) => ({ sessionId, caller: call.state })),
3477+
childrenOf(call).map((sessionId) => ({
3478+
key: sessionId,
3479+
sessionId,
3480+
caller: call.state,
3481+
})),
34773482
),
34783483
// Ended subagent calls can run again to answer their own background reports.
34793484
...sessionsOf(state)
@@ -3483,30 +3488,44 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
34833488
busy.has(caller.sessionId) &&
34843489
!isOrchestrationV2WorkActive(caller.subagent.call.status),
34853490
)
3486-
.map((caller) => ({ sessionId: caller.sessionId, caller: undefined })),
3487-
].filter(({ sessionId }) => !interrupted.has(sessionId));
3491+
.map((caller) => ({
3492+
key: caller.sessionId,
3493+
sessionId: caller.sessionId,
3494+
caller: undefined,
3495+
})),
3496+
...(wakes ? state.wakes : [])
3497+
.filter((wake) => wake.running)
3498+
.map((wake) => ({ key: wake, sessionId: state.sessionId, caller: undefined })),
3499+
].filter(({ key }) => !interrupted.has(key));
34883500
const unreached = new Set<string>();
3489-
const stopSessions = Effect.fnUntraced(function* () {
3490-
for (let sessions = unstopped(); sessions.length > 0; sessions = unstopped()) {
3491-
for (const { sessionId, caller } of sessions) {
3492-
if (interrupted.has(sessionId)) continue;
3493-
interrupted.add(sessionId);
3501+
// Succeeds with the sessions it interrupted.
3502+
const stopSessions = Effect.fnUntraced(function* (wakes: boolean) {
3503+
const stopped = new Set<string>();
3504+
for (let sessions = unstopped(wakes); sessions.length > 0; sessions = unstopped(wakes)) {
3505+
for (const { key, sessionId, caller } of sessions) {
3506+
if (interrupted.has(key)) continue;
3507+
interrupted.add(key);
3508+
stopped.add(sessionId);
34943509
caller?.stopped.add(sessionId);
34953510
const reached = yield* client.session
34963511
.interrupt({ sessionID: Session.ID.make(sessionId) })
34973512
.pipe(
34983513
Effect.catchTags({ SessionNotFoundError: () => Effect.void }),
34993514
Effect.timeout(INTERRUPT_TIMEOUT),
35003515
Effect.tapCause((cause) =>
3501-
Effect.logWarning("Could not stop an OpenCode subagent.", cause),
3516+
Effect.logWarning("Could not stop an OpenCode session.", cause),
35023517
),
35033518
Effect.exit,
35043519
Effect.map(Exit.isSuccess),
35053520
);
35063521
if (!reached && caller !== undefined) unreached.add(sessionId);
35073522
}
35083523
}
3524+
return stopped;
35093525
});
3526+
// An interrupted execution can launch work until it ends; its end means all of it has been seen.
3527+
const awaitEnds = (sessionIds: Iterable<string>) =>
3528+
Effect.forEach(sessionIds, awaitIdle, { concurrency: "unbounded", discard: true });
35103529
const attempted = new Set<string>();
35113530
const unremoved = () =>
35123531
sessionsOf(state)
@@ -3528,32 +3547,39 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
35283547
attempted.add(id);
35293548
caller.stopped.add(id);
35303549
}
3531-
const reached = yield* Effect.filter(shells, ({ id, directory }) =>
3532-
client.shell.remove({ id: Shell.ID.make(id), location: { directory } }).pipe(
3533-
// OpenCode declares no not-found error for remove; only the directory can be gone.
3534-
Effect.catchTags({ LocationNotFoundError: () => Effect.void }),
3535-
Effect.timeout(INTERRUPT_TIMEOUT),
3536-
Effect.tapCause((cause) =>
3537-
Effect.logWarning("Could not stop an OpenCode background shell.", cause),
3550+
const reached = yield* Effect.filter(
3551+
shells,
3552+
({ id, directory }) =>
3553+
client.shell.remove({ id: Shell.ID.make(id), location: { directory } }).pipe(
3554+
// OpenCode declares no not-found error for remove; only the directory can be gone.
3555+
Effect.catchTags({ LocationNotFoundError: () => Effect.void }),
3556+
Effect.timeout(INTERRUPT_TIMEOUT),
3557+
Effect.tapCause((cause) =>
3558+
Effect.logWarning("Could not stop an OpenCode background shell.", cause),
3559+
),
3560+
Effect.exit,
3561+
Effect.map(Exit.isSuccess),
35383562
),
3539-
Effect.exit,
3540-
Effect.map(Exit.isSuccess),
3541-
),
3563+
{ concurrency: "unbounded" },
35423564
);
35433565
removed.push(...reached);
35443566
}
35453567
});
35463568
yield* removeShells();
3547-
yield* stopSessions();
3569+
// Wakes wait for the foreground stop, which may end the same execution of the thread's session.
3570+
const stopped = yield* stopSessions(false);
35483571
const foreground = yield* Effect.exit(stopForeground);
3549-
if (Exit.isSuccess(foreground) && foreground.value) yield* awaitIdle(state.sessionId);
3550-
// Checked under the lock, so no shell launched before Stop settles outlives it.
3572+
if (Exit.isSuccess(foreground) && foreground.value) stopped.add(state.sessionId);
3573+
yield* awaitEnds(stopped);
3574+
// Checked under the lock, so no shell launched before Stop settles outlives it. A pass that does
3575+
// not settle found a shell or execution it had not stopped yet; both sets only grow, and stopped
3576+
// executions launch nothing after the end awaited here, so the loop ends.
35513577
for (let settled = false; !settled;) {
35523578
yield* removeShells();
3553-
yield* stopSessions();
3579+
yield* awaitEnds(yield* stopSessions(true));
35543580
settled = yield* lock.withPermit(
35553581
Effect.gen(function* () {
3556-
if (unremoved().length > 0 || unstopped().length > 0) return false;
3582+
if (unremoved().length > 0 || unstopped(true).length > 0) return false;
35573583
for (const call of backgroundCalls()) {
35583584
if (childrenOf(call).some((childId) => unreached.has(childId))) continue;
35593585
yield* settleCall(call, "interrupted");
@@ -3565,15 +3591,10 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
35653591
for (const caller of new Set(removed.map(({ caller }) => caller))) {
35663592
yield* syncRosterAncestors(caller);
35673593
}
3568-
const running = state.wakes.some((wake) => wake.running);
3594+
// Interrupted above but not yet ended: its end must not finish the thread's next turn.
3595+
if (state.wakes.some((wake) => wake.running)) markUnsettled(state);
35693596
discardWakes(state, state.wakes.splice(0));
35703597
yield* syncRosterAncestors(state);
3571-
if (running) {
3572-
markUnsettled(state);
3573-
yield* client.session
3574-
.interrupt({ sessionID: Session.ID.make(state.sessionId) })
3575-
.pipe(Effect.timeout(INTERRUPT_TIMEOUT), Effect.ignore({ log: true }));
3576-
}
35773598
return true;
35783599
}),
35793600
);

0 commit comments

Comments
 (0)