Skip to content

Commit c88510a

Browse files
fix(opencode): Stop ends work launched while it runs
A user Stop drained background shells and stopped subagents before it interrupted the foreground turn, and stopped only the subagents it saw when it began. A shell the turn launched while its interrupt was in flight, or a subagent launched while a shell remove waited, outlived Stop. Stop now interrupts the foreground turn before its final drain, waits for that execution to end so every launch it made has been seen, and re-derives the subagent sessions to stop on each pass until no new shell or session appears. Steering interrupts are unchanged. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent c9bdd13 commit c88510a

2 files changed

Lines changed: 179 additions & 78 deletions

File tree

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

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1320,6 +1320,73 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
13201320
}).pipe(Effect.scoped),
13211321
);
13221322

1323+
it.effect("removes a shell launched while Stop interrupts the turn", () =>
1324+
Effect.gen(function* () {
1325+
const { runtime, thread } = yield* resumed([
1326+
...backgroundShell("sh_1"),
1327+
removeShell("sh_1"),
1328+
shellReport(SESSION, "sh_1", "error", "Shell.NotFoundError"),
1329+
reply("shell.remove", null),
1330+
out("session.interrupt", { sessionID: SESSION }),
1331+
// The turn launches another shell before the interrupt returns.
1332+
...shellLaunched(SESSION, "sh_2"),
1333+
reply("session.interrupt", { interrupted: true }),
1334+
event("session.execution.interrupted", { sessionID: SESSION }),
1335+
removeShell("sh_2"),
1336+
shellReport(SESSION, "sh_2", "error", "Shell.NotFoundError"),
1337+
reply("shell.remove", null),
1338+
drained,
1339+
]);
1340+
const watch = yield* watchCalls(runtime, thread);
1341+
yield* runtime.startTurn(turnInput(thread));
1342+
yield* watch.until(() => watch.state.roster?.length === 1);
1343+
yield* runtime.interruptTurn({
1344+
providerThread: thread,
1345+
providerTurnId: yield* providerTurnId,
1346+
requestRuntimeRestart: true,
1347+
});
1348+
yield* watch.until(() => watch.terminals.length > 0);
1349+
assert.deepEqual(watch.terminals, ["interrupted"]);
1350+
assert.isFalse(yield* runtime.hasPendingBackgroundWork!);
1351+
yield* watch.until(() => watch.state.variant === "drained");
1352+
assert.deepEqual(watch.state.roster, []);
1353+
}).pipe(Effect.scoped),
1354+
);
1355+
1356+
it.effect("stops a subagent launched while Stop removes a shell", () =>
1357+
Effect.gen(function* () {
1358+
const { runtime, thread } = yield* resumed([
1359+
...backgroundShell("sh_1"),
1360+
removeShell("sh_1"),
1361+
shellReport(SESSION, "sh_1", "error", "Shell.NotFoundError"),
1362+
// The turn launches a background subagent before the remove returns.
1363+
...backgroundLaunch(CHILD).slice(3),
1364+
returnedRunning("call-background"),
1365+
event("session.execution.started", { sessionID: CHILD }),
1366+
reply("shell.remove", null),
1367+
out("session.interrupt", { sessionID: CHILD }),
1368+
reply("session.interrupt", { interrupted: true }),
1369+
event("session.execution.interrupted", { sessionID: CHILD }),
1370+
out("session.interrupt", { sessionID: SESSION }),
1371+
reply("session.interrupt", { interrupted: true }),
1372+
event("session.execution.interrupted", { sessionID: SESSION }),
1373+
drained,
1374+
]);
1375+
const watch = yield* watchCalls(runtime, thread);
1376+
yield* runtime.startTurn(withLineage(thread));
1377+
yield* watch.until(() => watch.state.roster?.length === 1);
1378+
yield* runtime.interruptTurn({
1379+
providerThread: thread,
1380+
providerTurnId: yield* providerTurnId,
1381+
requestRuntimeRestart: true,
1382+
});
1383+
yield* watch.until(() => watch.state.variant === "drained");
1384+
assert.deepEqual(watch.terminals, ["interrupted"]);
1385+
assert.deepEqual(watch.state.roster, []);
1386+
assert.isFalse(yield* runtime.hasPendingBackgroundWork!);
1387+
}).pipe(Effect.scoped),
1388+
);
1389+
13231390
it.effect("continues a wake that a stopped shell shares with a finished one", () =>
13241391
Effect.gen(function* () {
13251392
const offers: Array<ProviderContinuationRequests.ProviderContinuationRequest> = [];

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

Lines changed: 112 additions & 78 deletions
Original file line numberDiff line numberDiff line change
@@ -739,6 +739,7 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
739739
const untracked = new WeakSet<OpenCode2Client.OpenCode2StreamEvent>();
740740
const strays = new Map<string, ThreadState>();
741741
const busy = new Set<string>();
742+
const idleWaiters = new Map<string, Deferred.Deferred<void>>();
742743
const pending = new Map<RuntimeRequestId, PendingRequest>();
743744
const lock = yield* Semaphore.make(1);
744745
const clearing = new Map<string, Deferred.Deferred<void>>();
@@ -754,6 +755,19 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
754755
const emit = (event: ProviderAdapter.ProviderAdapterV2Event) =>
755756
Queue.offer(events, event).pipe(Effect.asVoid);
756757
const ownerOf = (sessionId: string) => childOwners.get(sessionId) ?? threads.get(sessionId);
758+
const markIdle = Effect.fnUntraced(function* (sessionId: string) {
759+
busy.delete(sessionId);
760+
const waiter = idleWaiters.get(sessionId);
761+
idleWaiters.delete(sessionId);
762+
if (waiter !== undefined) yield* Deferred.succeed(waiter, undefined);
763+
});
764+
// An execution's events precede its end, so once it ends everything it launched has been seen.
765+
const awaitIdle = Effect.fnUntraced(function* (sessionId: string) {
766+
if (!busy.has(sessionId)) return;
767+
const waiter = idleWaiters.get(sessionId) ?? (yield* Deferred.make<void>());
768+
idleWaiters.set(sessionId, waiter);
769+
yield* Deferred.await(waiter).pipe(Effect.timeout(INTERRUPT_TIMEOUT), Effect.ignore);
770+
});
757771
const markUnsettled = (state: ThreadState) => {
758772
state.unsettled = true;
759773
state.unsettledStarted = busy.has(state.sessionId);
@@ -2416,7 +2430,7 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
24162430
}
24172431
busy.add(sessionId);
24182432
} else if (event.type === "unreadable.execution.ended" || executionEnd(event.type)) {
2419-
busy.delete(sessionId);
2433+
yield* markIdle(sessionId);
24202434
}
24212435
}
24222436
const tracked = threads.get(sessionId ?? "");
@@ -2704,7 +2718,7 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
27042718
return;
27052719
}
27062720
const active = yield* client.session.active();
2707-
for (const sessionId of busy) if (!(sessionId in active)) busy.delete(sessionId);
2721+
for (const sessionId of busy) if (!(sessionId in active)) yield* markIdle(sessionId);
27082722
for (const state of threads.values()) {
27092723
if (state.unsettled && !(state.sessionId in active)) state.unsettledStarted = true;
27102724
}
@@ -3441,26 +3455,58 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
34413455
);
34423456
});
34433457

3444-
const stopBackground = Effect.fnUntraced(function* (state: ThreadState) {
3445-
const calls = runningCalls(state).filter((call) => call.background);
3446-
const callers = sessionsOf(state);
3447-
// Ended subagent calls can run again to answer their own background reports.
3448-
const followUps = callers.filter(
3449-
(caller) =>
3450-
caller.subagent !== undefined &&
3451-
busy.has(caller.sessionId) &&
3452-
!isOrchestrationV2WorkActive(caller.subagent.call.status),
3453-
);
3458+
// The foreground stop runs before the final drain and succeeds with whether it interrupted a run,
3459+
// which can launch more work until it ends.
3460+
const stopBackground = Effect.fnUntraced(function* <E>(
3461+
state: ThreadState,
3462+
stopForeground: Effect.Effect<boolean, E>,
3463+
) {
3464+
const backgroundCalls = () => runningCalls(state).filter((call) => call.background);
34543465
// Child sessions are announced before call progress names them; use announcements to stop unnamed children.
34553466
const announcedTo = (caller: ThreadState) =>
34563467
[...announced.values()].flatMap((info) =>
34573468
info.parentID === caller.sessionId ? [info.sessionID] : [],
34583469
);
34593470
const childrenOf = (call: SubagentCall) =>
34603471
call.child === undefined ? announcedTo(call.state) : [call.child.sessionId];
3461-
const children = new Map(
3462-
calls.flatMap((call) => childrenOf(call).map((childId) => [childId, call.state] as const)),
3463-
);
3472+
const interrupted = new Set<string>();
3473+
const unstopped = () =>
3474+
[
3475+
...backgroundCalls().flatMap((call) =>
3476+
childrenOf(call).map((sessionId) => ({ sessionId, caller: call.state })),
3477+
),
3478+
// Ended subagent calls can run again to answer their own background reports.
3479+
...sessionsOf(state)
3480+
.filter(
3481+
(caller) =>
3482+
caller.subagent !== undefined &&
3483+
busy.has(caller.sessionId) &&
3484+
!isOrchestrationV2WorkActive(caller.subagent.call.status),
3485+
)
3486+
.map((caller) => ({ sessionId: caller.sessionId, caller: undefined })),
3487+
].filter(({ sessionId }) => !interrupted.has(sessionId));
3488+
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);
3494+
caller?.stopped.add(sessionId);
3495+
const reached = yield* client.session
3496+
.interrupt({ sessionID: Session.ID.make(sessionId) })
3497+
.pipe(
3498+
Effect.catchTags({ SessionNotFoundError: () => Effect.void }),
3499+
Effect.timeout(INTERRUPT_TIMEOUT),
3500+
Effect.tapCause((cause) =>
3501+
Effect.logWarning("Could not stop an OpenCode subagent.", cause),
3502+
),
3503+
Effect.exit,
3504+
Effect.map(Exit.isSuccess),
3505+
);
3506+
if (!reached && caller !== undefined) unreached.add(sessionId);
3507+
}
3508+
}
3509+
});
34643510
const attempted = new Set<string>();
34653511
const unremoved = () =>
34663512
sessionsOf(state)
@@ -3498,42 +3544,21 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
34983544
}
34993545
});
35003546
yield* removeShells();
3501-
const unreached = new Set<string>();
3502-
for (const [childId, caller] of children) {
3503-
caller.stopped.add(childId);
3504-
const reached = yield* client.session
3505-
.interrupt({ sessionID: Session.ID.make(childId) })
3506-
.pipe(
3507-
Effect.catchTags({ SessionNotFoundError: () => Effect.void }),
3508-
Effect.timeout(INTERRUPT_TIMEOUT),
3509-
Effect.tapCause((cause) =>
3510-
Effect.logWarning("Could not stop an OpenCode subagent.", cause),
3511-
),
3512-
Effect.exit,
3513-
Effect.map(Exit.isSuccess),
3514-
);
3515-
if (!reached) unreached.add(childId);
3516-
}
3517-
for (const followUp of followUps) {
3518-
yield* client.session
3519-
.interrupt({ sessionID: Session.ID.make(followUp.sessionId) })
3520-
.pipe(
3521-
Effect.catchTags({ SessionNotFoundError: () => Effect.void }),
3522-
Effect.timeout(INTERRUPT_TIMEOUT),
3523-
Effect.ignore({ log: true }),
3524-
);
3525-
}
3547+
yield* stopSessions();
3548+
const foreground = yield* Effect.exit(stopForeground);
3549+
if (Exit.isSuccess(foreground) && foreground.value) yield* awaitIdle(state.sessionId);
35263550
// Checked under the lock, so no shell launched before Stop settles outlives it.
35273551
for (let settled = false; !settled;) {
35283552
yield* removeShells();
3553+
yield* stopSessions();
35293554
settled = yield* lock.withPermit(
35303555
Effect.gen(function* () {
3531-
if (unremoved().length > 0) return false;
3532-
for (const call of calls) {
3556+
if (unremoved().length > 0 || unstopped().length > 0) return false;
3557+
for (const call of backgroundCalls()) {
35333558
if (childrenOf(call).some((childId) => unreached.has(childId))) continue;
35343559
yield* settleCall(call, "interrupted");
35353560
}
3536-
for (const caller of callers) {
3561+
for (const caller of sessionsOf(state)) {
35373562
for (const report of caller.reports.values()) caller.stopped.add(report.sourceId);
35383563
}
35393564
for (const { caller, id } of removed) caller.shells.delete(id);
@@ -3554,6 +3579,7 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
35543579
);
35553580
}
35563581
yield* stopStrays(state);
3582+
yield* foreground;
35573583
});
35583584

35593585
const listSkills = (location: { readonly directory: string }) =>
@@ -4024,42 +4050,50 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
40244050
const state = threads.get(sessionId);
40254051
if (state === undefined) return;
40264052
const turn = state.active;
4053+
const stopTurn = Effect.gen(function* () {
4054+
if (turn === undefined || turn.providerTurn.id !== interruptInput.providerTurnId) {
4055+
return false;
4056+
}
4057+
turn.interrupted = true;
4058+
const reply = yield* client.session
4059+
.interrupt({ sessionID: Session.ID.make(sessionId) })
4060+
.pipe(
4061+
Effect.timeoutOption(INTERRUPT_TIMEOUT),
4062+
Effect.tapError(() =>
4063+
Effect.sync(() => {
4064+
turn.interrupted = false;
4065+
}),
4066+
),
4067+
);
4068+
if (reply._tag === "None") {
4069+
markUnsettled(state);
4070+
yield* lock.withPermit(finishTurn(state, { status: "interrupted" }));
4071+
return false;
4072+
}
4073+
// Stop between steer executions retracts pending steers and skips any run they already started.
4074+
if (!reply.value.interrupted && state.active === turn && turn.heldEnd !== undefined) {
4075+
markUnsettled(state);
4076+
yield* lock.withPermit(finishTurn(state, { status: "interrupted" }));
4077+
yield* cancelStrandedSteers(state);
4078+
return false;
4079+
}
4080+
if (!reply.value.interrupted && state.active === turn && turn.unsent) {
4081+
yield* lock.withPermit(finishTurn(state, { status: "interrupted" }));
4082+
return false;
4083+
}
4084+
if (!reply.value.interrupted && state.active === turn) {
4085+
turn.interrupted = false;
4086+
return yield* new ProviderAdapter.ProviderAdapterProtocolError({
4087+
driver: OPENCODE_PROVIDER,
4088+
detail: `OpenCode session ${sessionId} had nothing running to stop`,
4089+
});
4090+
}
4091+
return reply.value.interrupted;
4092+
});
40274093
// User Stop must end background children and their report execution; steering leaves them running.
4028-
if (interruptInput.requestRuntimeRestart === true) yield* stopBackground(state);
4029-
if (turn === undefined || turn.providerTurn.id !== interruptInput.providerTurnId) {
4030-
return;
4031-
}
4032-
turn.interrupted = true;
4033-
const reply = yield* client.session
4034-
.interrupt({ sessionID: Session.ID.make(sessionId) })
4035-
.pipe(
4036-
Effect.timeoutOption(INTERRUPT_TIMEOUT),
4037-
Effect.tapError(() =>
4038-
Effect.sync(() => {
4039-
turn.interrupted = false;
4040-
}),
4041-
),
4042-
);
4043-
if (reply._tag === "None") {
4044-
markUnsettled(state);
4045-
return yield* lock.withPermit(finishTurn(state, { status: "interrupted" }));
4046-
}
4047-
// Stop between steer executions retracts pending steers and skips any run they already started.
4048-
if (!reply.value.interrupted && state.active === turn && turn.heldEnd !== undefined) {
4049-
markUnsettled(state);
4050-
yield* lock.withPermit(finishTurn(state, { status: "interrupted" }));
4051-
return yield* cancelStrandedSteers(state);
4052-
}
4053-
if (!reply.value.interrupted && state.active === turn && turn.unsent) {
4054-
return yield* lock.withPermit(finishTurn(state, { status: "interrupted" }));
4055-
}
4056-
if (!reply.value.interrupted && state.active === turn) {
4057-
turn.interrupted = false;
4058-
return yield* new ProviderAdapter.ProviderAdapterProtocolError({
4059-
driver: OPENCODE_PROVIDER,
4060-
detail: `OpenCode session ${sessionId} had nothing running to stop`,
4061-
});
4062-
}
4094+
return yield* interruptInput.requestRuntimeRestart === true
4095+
? stopBackground(state, stopTurn)
4096+
: Effect.asVoid(stopTurn);
40634097
},
40644098
(effect, interruptInput) =>
40654099
effect.pipe(

0 commit comments

Comments
 (0)