Skip to content

Commit 874c131

Browse files
fix(server): OpenCode 2 continuations replay only their own background reply
OpenCode runs the parent's reply to a background subagent on its own, and the adapter holds it for the continuation turn it offers. That turn replayed whichever held reply was oldest. When a continuation was cancelled while queued, or dropped before it started, its reply stayed at the head of the queue, and the next continuation showed it under its own notification while its own reply stayed held. Each held reply now gets the message id its continuation run starts from. The continuation request carries it, and `ProviderContinuationService` dispatches under it instead of allocating one. The continuation turn replays the reply its message names, and drops older ones whose continuation will never run. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
1 parent 9b2c03e commit 874c131

5 files changed

Lines changed: 178 additions & 35 deletions

File tree

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

Lines changed: 125 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -610,6 +610,28 @@ describe("OpenCode2 adapter", () => {
610610
lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId },
611611
} as OrchestrationV2AppThread,
612612
});
613+
/**
614+
* The continuation turn the orchestrator starts for an offered wake: its
615+
* message is the one the offer named, as `ProviderContinuationService` dispatches it.
616+
*/
617+
const continuationTurn = (
618+
thread: OrchestrationV2ProviderThread,
619+
offer: ProviderContinuationRequest,
620+
suffix = "wake",
621+
) => ({
622+
...withLineage(thread),
623+
runId: RunId.make(`run:opencode2-adapter:${suffix}`),
624+
runOrdinal: 2,
625+
providerTurnOrdinal: 2,
626+
attemptId: RunAttemptId.make(`attempt:opencode2-adapter:${suffix}`),
627+
message: {
628+
...turnInput(thread).message,
629+
messageId: offer.messageId!,
630+
text: offer.detail ?? "",
631+
createdBy: "agent" as const,
632+
creationSource: "provider" as const,
633+
},
634+
});
613635
const CHILD = "ses_f1485c529ffea4URrYruwEg0Ja";
614636
/**
615637
* The single reader of the runtime's events: resolves `attached` once the
@@ -3762,19 +3784,7 @@ describe("OpenCode2 adapter", () => {
37623784
yield* Effect.gen(function* () {
37633785
while (offers.length === 0) yield* Effect.yieldNow;
37643786
}).pipe(Effect.timeout("2 seconds"), Effect.orDie);
3765-
yield* runtime.startTurn({
3766-
...withLineage(thread),
3767-
runId: RunId.make("run:opencode2-adapter:wake"),
3768-
runOrdinal: 2,
3769-
providerTurnOrdinal: 2,
3770-
attemptId: RunAttemptId.make("attempt:opencode2-adapter:wake"),
3771-
message: {
3772-
...turnInput(thread).message,
3773-
messageId: MessageId.make("message:opencode2-adapter:wake"),
3774-
createdBy: "agent" as const,
3775-
creationSource: "provider" as const,
3776-
},
3777-
});
3787+
yield* runtime.startTurn(continuationTurn(thread, offers[0]!));
37783788
yield* Deferred.await(bothEnded);
37793789
const [first, second] = turns;
37803790
return { runtime, thread, first: first!, second: second! };
@@ -3841,6 +3851,107 @@ describe("OpenCode2 adapter", () => {
38413851
}).pipe(Effect.scoped),
38423852
);
38433853

3854+
it.effect("replays only its own background reply into a continuation turn", () =>
3855+
Effect.gen(function* () {
3856+
const CHILD_B = "ses_f1485c529ffeBBBBBBBBBBBBBB";
3857+
const toolB = { sessionID: SESSION, assistantMessageID: "msg_assistant", id: "call-b" };
3858+
const report = (inboxID: string, child: string, text: string) =>
3859+
event("session.inbox.enqueued", {
3860+
inboxID,
3861+
sessionID: SESSION,
3862+
item: {
3863+
type: "synthetic",
3864+
payload: {
3865+
text: `<subagent sessionID="${child}" state="completed" description="Sleep">\n${text}\n</subagent>`,
3866+
description: "Sleep",
3867+
metadata: {
3868+
source: "subagent",
3869+
childID: child,
3870+
agent: "General",
3871+
state: "completed",
3872+
},
3873+
},
3874+
delivery: "steer",
3875+
},
3876+
});
3877+
const reply = (assistantMessageID: string, text: string) =>
3878+
event("session.text.ended", { sessionID: SESSION, assistantMessageID, ordinal: 0, text });
3879+
const offers: Array<ProviderContinuationRequest> = [];
3880+
const { runtime, thread } = yield* resumed([
3881+
...backgroundLaunch(CHILD),
3882+
// The same turn starts a second background subagent.
3883+
event("session.tool.input.started", { ...toolB, name: "subagent" }),
3884+
event("session.tool.called", {
3885+
...toolB,
3886+
name: "subagent",
3887+
input: { description: "Sleep", prompt: "sleep", background: true },
3888+
executed: false,
3889+
}),
3890+
event("session.created", { ...childCreated(CHILD_B), sessionID: CHILD_B }),
3891+
event("session.tool.progress", {
3892+
...toolB,
3893+
metadata: { sessionID: CHILD_B, status: "running" },
3894+
}),
3895+
event("session.execution.succeeded", { sessionID: SESSION }),
3896+
// Each subagent's report wakes the parent into a reply OpenCode runs on its own.
3897+
event("session.execution.succeeded", { sessionID: CHILD }),
3898+
report("msg_report_a", CHILD, "A_OK"),
3899+
event("session.execution.started", { sessionID: SESSION }),
3900+
event("session.inbox.delivered", { sessionID: SESSION, inboxID: "msg_report_a" }),
3901+
reply("msg_reply_a", "REPLY_A"),
3902+
event("session.execution.succeeded", { sessionID: SESSION }),
3903+
event("session.execution.succeeded", { sessionID: CHILD_B }),
3904+
report("msg_report_b", CHILD_B, "B_OK"),
3905+
event("session.execution.started", { sessionID: SESSION }),
3906+
event("session.inbox.delivered", { sessionID: SESSION, inboxID: "msg_report_b" }),
3907+
reply("msg_reply_b", "REPLY_B"),
3908+
event("session.execution.succeeded", { sessionID: SESSION }),
3909+
]).pipe(
3910+
Effect.provideService(ProviderContinuationRequests.ProviderContinuationRequests, {
3911+
offer: (request) => Effect.sync(() => void offers.push(request)),
3912+
take: Effect.never,
3913+
}),
3914+
);
3915+
const collected: Array<ProviderAdapterV2Event> = [];
3916+
const ended = yield* Deferred.make<void>();
3917+
yield* runtime.events.pipe(
3918+
Stream.tap((event) =>
3919+
Effect.gen(function* () {
3920+
collected.push(event);
3921+
if (collected.filter((entry) => entry.type === "turn.terminal").length === 2) {
3922+
yield* Deferred.succeed(ended, undefined);
3923+
}
3924+
}),
3925+
),
3926+
Stream.runDrain,
3927+
Effect.forkScoped,
3928+
);
3929+
yield* runtime.startTurn(withLineage(thread));
3930+
yield* Effect.gen(function* () {
3931+
while (offers.length < 2) yield* Effect.yieldNow;
3932+
}).pipe(Effect.timeout("2 seconds"), Effect.orDie);
3933+
// A's continuation was cancelled before it started; B's runs.
3934+
yield* runtime.startTurn(continuationTurn(thread, offers[1]!, "wake-b"));
3935+
yield* Deferred.await(ended);
3936+
const continuationId = (yield* IdAllocator.IdAllocatorV2).derive.providerTurn({
3937+
driver: OPENCODE_PROVIDER,
3938+
nativeTurnId: `${SESSION}:attempt:attempt:opencode2-adapter:wake-b`,
3939+
});
3940+
assert.deepEqual(
3941+
collected.flatMap((event) =>
3942+
event.type === "turn_item.updated" &&
3943+
event.turnItem.type === "assistant_message" &&
3944+
event.turnItem.providerTurnId === continuationId
3945+
? [event.turnItem.text]
3946+
: [],
3947+
),
3948+
["REPLY_B"],
3949+
);
3950+
// Nothing is left held for a continuation that will never run.
3951+
assert.isFalse(yield* runtime.hasPendingBackgroundWork!);
3952+
}).pipe(Effect.scoped, Effect.provide(IdAllocator.layer)),
3953+
);
3954+
38443955
it.effect("ends a follow-up turn a steer joined exactly once", () =>
38453956
Effect.gen(function* () {
38463957
const reportText = `<subagent sessionID="${CHILD}" state="completed" description="Sleep">\nCHILD_OK\n</subagent>`;
@@ -3918,19 +4029,7 @@ describe("OpenCode2 adapter", () => {
39184029
yield* Effect.gen(function* () {
39194030
while (offers.length === 0) yield* Effect.yieldNow;
39204031
}).pipe(Effect.timeout("2 seconds"), Effect.orDie);
3921-
const followUp = {
3922-
...withLineage(thread),
3923-
runId: RunId.make("run:opencode2-adapter:wake"),
3924-
runOrdinal: 2,
3925-
providerTurnOrdinal: 2,
3926-
attemptId: RunAttemptId.make("attempt:opencode2-adapter:wake"),
3927-
message: {
3928-
...turnInput(thread).message,
3929-
messageId: MessageId.make("message:opencode2-adapter:wake"),
3930-
createdBy: "agent" as const,
3931-
creationSource: "provider" as const,
3932-
},
3933-
};
4032+
const followUp = continuationTurn(thread, offers[0]!);
39344033
yield* runtime.startTurn(followUp);
39354034
const followUpTurnId = (yield* IdAllocator.IdAllocatorV2).derive.providerTurn({
39364035
driver: OPENCODE_PROVIDER,

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

Lines changed: 22 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,7 @@ import {
4949
type OrchestrationV2Subagent,
5050
type OrchestrationV2TurnItem,
5151
type OrchestrationV2UserInputQuestion,
52+
type MessageId,
5253
type ModelSelection,
5354
type ProviderApprovalDecision,
5455
type ProviderInstanceId,
@@ -303,6 +304,8 @@ interface SubagentCall {
303304
* the continuation turn T3 opens for it takes them.
304305
*/
305306
interface Wake {
307+
/** The message its continuation run starts from, which names the wake in that turn's input. */
308+
readonly messageId: MessageId | undefined;
306309
readonly events: Array<OpenCode2StreamEvent>;
307310
running: boolean;
308311
/** The background subagents whose end it answers, as its turn's notification names them. */
@@ -1658,13 +1661,14 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
16581661
*/
16591662
const offerWake = Effect.fnUntraced(function* (state: ThreadState, wake: Wake) {
16601663
const route = state.providerThread.appThreadId;
1661-
if (route === null) return;
1664+
if (route === null || wake.messageId === undefined) return;
16621665
const notification = backgroundWorkNotification(wake.reports);
16631666
yield* continuationRequests.offer({
16641667
threadId: route,
16651668
providerThreadId: state.providerThread.id,
16661669
driver,
16671670
detail: wake.detail,
1671+
messageId: wake.messageId,
16681672
...(notification === null ? {} : { notification }),
16691673
dispatchIfCurrent: (dispatch) =>
16701674
wake.dropped ? Effect.succeed(Option.none()) : Effect.map(dispatch, Option.some),
@@ -2343,7 +2347,13 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
23432347
const onWake = Effect.fnUntraced(function* (state: ThreadState) {
23442348
const { delivered, stopped } = yield* takeReports(state);
23452349
if (stopped) return;
2350+
const route = state.providerThread.appThreadId;
23462351
const wake: Wake = {
2352+
// Only a thread's wake is offered a continuation; the ordinal is display metadata.
2353+
messageId:
2354+
route === null
2355+
? undefined
2356+
: yield* idAllocator.allocate.message({ threadId: route, ordinal: 0 }),
23472357
events: [],
23482358
running: true,
23492359
reports: delivered.map((entry) => entry.report),
@@ -3377,8 +3387,11 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
33773387

33783388
/**
33793389
* The continuation turn for an execution OpenCode started on its own: it
3380-
* takes the oldest one held and ends with it. One already taken (a user
3381-
* turn joined it) leaves nothing to run, so the turn ends at once.
3390+
* takes the wake it was dispatched for, named by its message, and ends
3391+
* with it. Wakes held before that one had their continuation cancelled or
3392+
* dropped before it started, so nothing will replay them: they are
3393+
* dropped. One already taken (a user turn joined it) leaves nothing to
3394+
* run, so the turn ends at once.
33823395
*/
33833396
const runWake = Effect.fnUntraced(function* (
33843397
state: ThreadState,
@@ -3387,8 +3400,12 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
33873400
yield* beginTurn(state, turnInput, false);
33883401
yield* lock.withPermit(
33893402
Effect.gen(function* () {
3390-
const wake = state.wakes.shift();
3391-
if (wake === undefined) return yield* finishTurn(state, { status: "completed" });
3403+
const index = state.wakes.findIndex(
3404+
(held) => held.messageId === turnInput.message.messageId,
3405+
);
3406+
if (index < 0) return yield* finishTurn(state, { status: "completed" });
3407+
for (const skipped of state.wakes.splice(0, index)) skipped.dropped = true;
3408+
const wake = state.wakes.shift()!;
33923409
const turn = state.active;
33933410
if (turn !== undefined && wake.after !== undefined) turn.before = wake.after;
33943411
// Its first report is where its history begins, so fork and rollback cut there.

‎apps/server/src/orchestration-v2/ProviderContinuationRequests.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,12 @@ export interface ProviderContinuationRequest {
4141
* reach the provider as a real prompt.
4242
*/
4343
readonly delivery?: "adapter_buffered" | "message_text";
44+
/**
45+
* The message the continuation run starts from, when the adapter picks it:
46+
* its turn input carries this id, so the adapter can tell which of its held
47+
* wakes a run was dispatched for. Otherwise the service allocates one.
48+
*/
49+
readonly messageId?: MessageId;
4450
readonly dispatchIfCurrent?: <A, E, R>(
4551
effect: Effect.Effect<A, E, R>,
4652
) => Effect.Effect<Option.Option<A>, E, R>;

‎apps/server/src/orchestration-v2/ProviderContinuationService.test.ts‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -180,6 +180,25 @@ describe("ProviderContinuationService", () => {
180180
});
181181
});
182182

183+
it.effect("dispatches a wake under the message its adapter named", () => {
184+
return Effect.gen(function* () {
185+
const dispatched = yield* Queue.unbounded<unknown>();
186+
const messageId = MessageId.make("message-provider-continuation-adapter-named");
187+
yield* Effect.gen(function* () {
188+
const requests = yield* ProviderContinuationRequests.ProviderContinuationRequests;
189+
yield* requests.offer({ ...request(), messageId });
190+
const command = (yield* Queue.take(dispatched)) as { readonly messageId: MessageId };
191+
// The adapter matches the continuation run's message to the wake it holds.
192+
assert.equal(command.messageId, messageId);
193+
}).pipe(
194+
Effect.provide(
195+
layerTest({ dispatched, getThreadRecords: () => Effect.succeed(projection) }),
196+
),
197+
Effect.scoped,
198+
);
199+
});
200+
});
201+
183202
it.effect("delivers a message_text wake as a real prompt, not a buffered wake", () => {
184203
return Effect.gen(function* () {
185204
const dispatched = yield* Queue.unbounded<unknown>();

‎apps/server/src/orchestration-v2/ProviderContinuationService.ts‎

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -147,10 +147,12 @@ export const layer = Layer.effectDiscard(
147147
}
148148
// The ordinal is display metadata only: allocate.message appends a
149149
// random UUID, so a stale projection read here cannot collide ids.
150-
const messageId = yield* ids.allocate.message({
151-
threadId: request.threadId,
152-
ordinal: projection.messages.length + 1,
153-
});
150+
const messageId =
151+
request.messageId ??
152+
(yield* ids.allocate.message({
153+
threadId: request.threadId,
154+
ordinal: projection.messages.length + 1,
155+
}));
154156
const commandId = CommandId.make(`provider-continuation:${messageId}`);
155157
const dispatch = threads.dispatch({
156158
type: "message.dispatch",

0 commit comments

Comments
 (0)