Skip to content

Commit 022ae59

Browse files
committed
fix(server): forking a running OpenCode thread no longer fails
A fork's first turn failed with "Cannot fork OpenCode session ... while it is still working" whenever the source thread was running a newer turn, and every retry failed the same way. OpenCode copies only the history before the fork's cut. When the cut is the prompt of a turn after the forked one (or the report a continuation answers) and every execution before it has ended (an `idle` item follows its last output), nothing the running turn writes can reach the fork, so it forks right away. Otherwise it waits up to a minute for the source to go quiet, re-reading the turns, and then says the source is still running and to send the message again. Claude Opus 5.5 in OpenCode
1 parent 3ff452b commit 022ae59

3 files changed

Lines changed: 361 additions & 59 deletions

File tree

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

Lines changed: 248 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,7 @@ import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderS
4343
import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
4444
import * as ProviderContinuationRequests from "@t3tools/provider-core/server/ProviderContinuationRequests";
4545
import {
46+
OPENCODE_2_FORK_SOURCE_RUNNING,
4647
OPENCODE_2_STILL_STOPPING,
4748
OPENCODE_PROVIDER,
4849
t3McpServerName,
@@ -4295,7 +4296,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
42954296
}).pipe(Effect.scoped),
42964297
);
42974298

4298-
it.effect("refuses to fork a session while OpenCode runs a follow-up on it", () =>
4299+
it.effect("waits instead of forking while OpenCode runs a follow-up on the source", () =>
42994300
Effect.gen(function* () {
43004301
// OpenCode starts the thread's session on its own (a background
43014302
// subagent's report). The replay fails on a fork request.
@@ -4309,31 +4310,40 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
43094310
}),
43104311
);
43114312
yield* Deferred.await(offered);
4312-
const refused = yield* runtime
4313+
const fork = yield* runtime
43134314
.forkThread({
43144315
sourceProviderThread: thread,
43154316
targetThreadId: ThreadId.make("thread:opencode2-adapter:fork"),
43164317
})
4317-
.pipe(Effect.flip);
4318-
assert.equal(refused._tag, "ProviderAdapterProtocolError");
4319-
}).pipe(Effect.scoped),
4318+
.pipe(Effect.forkScoped);
4319+
yield* TestClock.adjust("5 seconds");
4320+
assert.isUndefined(fork.pollUnsafe());
4321+
}).pipe(Effect.scoped, Effect.provide(TestClock.layer())),
43204322
);
43214323

4322-
it.effect("asks the server before forking a session this runtime has not loaded", () =>
4324+
it.effect("waits for a run the server reports on a session this runtime has not loaded", () =>
43234325
Effect.gen(function* () {
4326+
const FORK = "ses_f1484db83ffeLGtrRCFimo1H0e";
43244327
const runtime = yield* openCode2ReplayRuntime([
43254328
...opening,
43264329
out("session.active"),
43274330
reply("session.active", { data: { [SESSION]: { type: "running" } } }),
4331+
out("session.active"),
4332+
reply("session.active", { data: {} }),
4333+
out("session.fork", { sessionID: SESSION }),
4334+
replyData("session.fork", sessionInfo({ id: FORK })),
4335+
out("session.update", { sessionID: FORK, permissions: "<any>" }),
4336+
reply("session.update", null),
43284337
]);
4329-
const refused = yield* runtime
4338+
const fork = yield* runtime
43304339
.forkThread({
43314340
sourceProviderThread: providerThread(yield* DateTime.now),
43324341
targetThreadId: ThreadId.make("thread:opencode2-adapter:fork"),
43334342
})
4334-
.pipe(Effect.flip);
4335-
assert.equal(refused._tag, "ProviderAdapterProtocolError");
4336-
}).pipe(Effect.scoped),
4343+
.pipe(Effect.forkScoped);
4344+
yield* TestClock.adjust("1 second");
4345+
assert.equal((yield* Fiber.join(fork)).nativeThreadRef?.nativeId, FORK);
4346+
}).pipe(Effect.scoped, Effect.provide(TestClock.layer())),
43374347
);
43384348

43394349
it.effect("lets the next turn start when a rollback's stage never answers", () =>
@@ -4388,22 +4398,243 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
43884398
}).pipe(Effect.scoped, Effect.provide(TestClock.layer())),
43894399
);
43904400

4391-
it.effect("refuses to fork a session while its turn runs", () =>
4401+
it.effect("tells the user to send again when the source's turn outlasts a fork's wait", () =>
43924402
Effect.gen(function* () {
4393-
// The replay fails on a fork request: only the running turn's prompt is expected.
4403+
// The replay fails on a fork request: the turn runs on past the wait.
43944404
const { runtime, thread } = yield* resumed([
4395-
out("session.prompt", { sessionID: SESSION, text: "<any>" }),
4405+
out("session.prompt", { sessionID: SESSION, id: PROMPT_ID, text: "<any>" }),
43964406
promptAccepted,
4407+
// The quiet stream is reopened after its silence limit.
4408+
...reconnected({ [SESSION]: { type: "running" } }).slice(1),
4409+
...openRequests([]),
43974410
]);
43984411
yield* runtime.startTurn(turnInput(thread));
4399-
const refused = yield* runtime
4412+
const fork = yield* runtime
44004413
.forkThread({
44014414
sourceProviderThread: thread,
44024415
targetThreadId: ThreadId.make("thread:opencode2-adapter:fork"),
44034416
})
4404-
.pipe(Effect.flip);
4405-
assert.equal(refused._tag, "ProviderAdapterProtocolError");
4406-
}).pipe(Effect.scoped),
4417+
.pipe(Effect.flip, Effect.forkScoped);
4418+
yield* TestClock.adjust("61 seconds");
4419+
const refused = yield* Fiber.join(fork);
4420+
assert.equal(refused._tag, "ProviderAdapterForkThreadError");
4421+
assert.equal(
4422+
refused._tag === "ProviderAdapterForkThreadError" ? refused.cause : undefined,
4423+
OPENCODE_2_FORK_SOURCE_RUNNING,
4424+
);
4425+
}).pipe(Effect.scoped, Effect.provide(TestClock.layer())),
4426+
);
4427+
4428+
/** A source thread whose first turn ended and whose second runs now. */
4429+
const FIRST_PROMPT = `msg_t3_turn_${SESSION}:attempt:first`;
4430+
const RUNNING_PROMPT = `msg_t3_turn_${SESSION}:attempt:opencode2-adapter`;
4431+
const sourceTurns = (thread: OrchestrationV2ProviderThread, now: DateTime.Utc) => {
4432+
const recorded = (key: string, ordinal: number, nativeId: string, running: boolean) => ({
4433+
id: ProviderTurnId.make(`provider-turn:${key}`),
4434+
providerThreadId: thread.id,
4435+
nodeId: NodeId.make(`node:${key}`),
4436+
runAttemptId: RunAttemptId.make(`attempt:${key}`),
4437+
nativeTurnRef: { driver: OPENCODE_PROVIDER, nativeId, strength: "weak" as const },
4438+
ordinal,
4439+
status: running ? ("running" as const) : ("completed" as const),
4440+
startedAt: now,
4441+
completedAt: running ? null : now,
4442+
});
4443+
return [
4444+
recorded("first", 1, FIRST_PROMPT, false),
4445+
recorded("second", 2, RUNNING_PROMPT, true),
4446+
] as const;
4447+
};
4448+
const firstTurnItems = [
4449+
{
4450+
id: "msg_first_reply",
4451+
time: { created: 2, completed: 3 },
4452+
type: "assistant",
4453+
agent: "build",
4454+
model: { id: "big-pickle", providerID: "opencode", variant: "default" },
4455+
content: [{ type: "text", text: "first answer" }],
4456+
finish: "stop",
4457+
cost: 0,
4458+
tokens: { input: 1, output: 1, reasoning: 0, cache: { read: 0, write: 0 } },
4459+
},
4460+
{ id: FIRST_PROMPT, time: { created: 1 }, text: "first", type: "user" },
4461+
];
4462+
const idleItem = (id: string, created: number) => ({
4463+
id,
4464+
time: { created },
4465+
type: "idle",
4466+
outcome: "succeeded",
4467+
});
4468+
4469+
it.effect.each([
4470+
["the turns read before it started list it", true],
4471+
["only the adapter knows it", false],
4472+
] as const)(
4473+
"forks a running thread at an earlier turn at once, before the running turn: %s",
4474+
([, listed]) =>
4475+
Effect.gen(function* () {
4476+
const FORK = "ses_f1484db83ffeLGtrRCFimo1H0e";
4477+
const { runtime, thread } = yield* resumed([
4478+
out("session.prompt", { sessionID: SESSION, text: "<any>" }),
4479+
promptAccepted,
4480+
out("message.list", "<any>"),
4481+
reply("message.list", {
4482+
data: [
4483+
{ id: RUNNING_PROMPT, time: { created: 5 }, text: "second", type: "user" },
4484+
idleItem("msg_first_idle", 4),
4485+
...firstTurnItems,
4486+
],
4487+
cursor: {},
4488+
}),
4489+
out("session.fork", { sessionID: SESSION, before: RUNNING_PROMPT }),
4490+
replyData("session.fork", sessionInfo({ id: FORK })),
4491+
out("session.update", { sessionID: FORK, permissions: "<any>" }),
4492+
reply("session.update", null),
4493+
]);
4494+
yield* runtime.startTurn({ ...turnInput(thread), providerTurnOrdinal: 2 });
4495+
const [first, second] = sourceTurns(thread, yield* DateTime.now);
4496+
const forked = yield* runtime.forkThread({
4497+
sourceProviderThread: thread,
4498+
targetThreadId: ThreadId.make("thread:opencode2-adapter:fork"),
4499+
providerTurnId: first.id,
4500+
sourceProviderTurns: listed ? [first, second] : [first],
4501+
});
4502+
assert.equal(forked.nativeThreadRef?.nativeId, FORK);
4503+
}).pipe(Effect.scoped),
4504+
);
4505+
4506+
it.effect.each([
4507+
["before its continuation starts", false],
4508+
["while its continuation runs", true],
4509+
] as const)(
4510+
"forks at the latest turn before a report OpenCode is answering on its own, %s",
4511+
([, continued]) =>
4512+
Effect.gen(function* () {
4513+
const FORK = "ses_f1484db83ffeLGtrRCFimo1H0e";
4514+
const offered =
4515+
yield* Deferred.make<ProviderContinuationRequests.ProviderContinuationRequest>();
4516+
const firstEnded = yield* Deferred.make<OrchestrationV2ProviderTurn>();
4517+
const firstPrompt = `msg_t3_turn_${SESSION}:attempt:opencode2-adapter`;
4518+
// The report wakes the session into an execution with no turn yet.
4519+
const { runtime, thread } = yield* resumed([
4520+
...backgroundLaunch(CHILD),
4521+
event("session.execution.succeeded", { sessionID: SESSION }),
4522+
event("session.execution.succeeded", { sessionID: CHILD }),
4523+
event("session.inbox.enqueued", {
4524+
inboxID: "msg_report",
4525+
sessionID: SESSION,
4526+
item: {
4527+
type: "synthetic",
4528+
payload: {
4529+
text: "report",
4530+
description: "Sleep",
4531+
metadata: {
4532+
source: "subagent",
4533+
childID: CHILD,
4534+
agent: "General",
4535+
state: "completed",
4536+
},
4537+
},
4538+
delivery: "steer",
4539+
},
4540+
}),
4541+
event("session.execution.started", { sessionID: SESSION }),
4542+
event("session.inbox.delivered", { sessionID: SESSION, inboxID: "msg_report" }),
4543+
out("message.list", "<any>"),
4544+
reply("message.list", {
4545+
data: [
4546+
{ ...firstTurnItems[0], id: "msg_followup", time: { created: 5 }, content: [] },
4547+
{ id: "msg_report", time: { created: 4 }, text: "report", type: "synthetic" },
4548+
idleItem("msg_first_idle", 3),
4549+
{ ...firstTurnItems[0], content: [] },
4550+
{ id: firstPrompt, time: { created: 1 }, text: "hi", type: "user" },
4551+
],
4552+
cursor: {},
4553+
}),
4554+
// The replay fails on a fork without this cut.
4555+
out("session.fork", { sessionID: SESSION, before: "msg_report" }),
4556+
replyData("session.fork", sessionInfo({ id: FORK })),
4557+
out("session.update", { sessionID: FORK, permissions: "<any>" }),
4558+
reply("session.update", null),
4559+
]).pipe(
4560+
Effect.provideService(ProviderContinuationRequests.ProviderContinuationRequests, {
4561+
offer: (request) => Deferred.succeed(offered, request).pipe(Effect.asVoid),
4562+
take: Effect.never,
4563+
}),
4564+
);
4565+
yield* runtime.events.pipe(
4566+
Stream.tap((event) =>
4567+
event.type === "provider_turn.updated" && event.providerTurn.status !== "running"
4568+
? Deferred.succeed(firstEnded, event.providerTurn)
4569+
: Effect.void,
4570+
),
4571+
Stream.runDrain,
4572+
Effect.forkScoped,
4573+
);
4574+
yield* runtime.startTurn(withLineage(thread));
4575+
const first = yield* Deferred.await(firstEnded);
4576+
const offer = yield* Deferred.await(offered);
4577+
if (continued) yield* runtime.startTurn(continuationTurn(thread, offer));
4578+
const forked = yield* runtime.forkThread({
4579+
sourceProviderThread: thread,
4580+
targetThreadId: ThreadId.make("thread:opencode2-adapter:fork"),
4581+
providerTurnId: first.id,
4582+
sourceProviderTurns: [first],
4583+
});
4584+
assert.equal(forked.nativeThreadRef?.nativeId, FORK);
4585+
}).pipe(Effect.scoped),
4586+
);
4587+
4588+
it.effect("waits to fork before a running turn whose prompt came in during an earlier run", () =>
4589+
Effect.gen(function* () {
4590+
const FORK = "ses_f1484db83ffeLGtrRCFimo1H0e";
4591+
// The prompt reached the model while a run OpenCode started on its own
4592+
// was writing a step, so the history before it is not settled yet.
4593+
const steeredInto = {
4594+
...firstTurnItems[0],
4595+
id: "msg_wake_reply",
4596+
time: { created: 4 },
4597+
content: [],
4598+
};
4599+
const history = (ended: boolean) => ({
4600+
data: [
4601+
...(ended ? [idleItem("msg_second_idle", 6)] : []),
4602+
{ id: RUNNING_PROMPT, time: { created: 5 }, text: "second", type: "user" },
4603+
ended ? { ...steeredInto, time: { created: 4, completed: 6 } } : steeredInto,
4604+
idleItem("msg_first_idle", 3),
4605+
...firstTurnItems,
4606+
],
4607+
cursor: {},
4608+
});
4609+
const { runtime, thread } = yield* resumed([
4610+
out("session.prompt", { sessionID: SESSION, text: "<any>" }),
4611+
promptAccepted,
4612+
out("message.list", "<any>"),
4613+
reply("message.list", history(false)),
4614+
event("session.execution.started", { sessionID: SESSION }),
4615+
event("session.execution.succeeded", { sessionID: SESSION }),
4616+
out("message.list", "<any>"),
4617+
reply("message.list", history(true)),
4618+
out("session.fork", { sessionID: SESSION, before: RUNNING_PROMPT }),
4619+
replyData("session.fork", sessionInfo({ id: FORK })),
4620+
out("session.update", { sessionID: FORK, permissions: "<any>" }),
4621+
reply("session.update", null),
4622+
]);
4623+
const terminal = yield* terminalOf(runtime).pipe(Effect.forkScoped);
4624+
yield* runtime.startTurn({ ...turnInput(thread), providerTurnOrdinal: 2 });
4625+
const [first, second] = sourceTurns(thread, yield* DateTime.now);
4626+
const fork = yield* runtime
4627+
.forkThread({
4628+
sourceProviderThread: thread,
4629+
targetThreadId: ThreadId.make("thread:opencode2-adapter:fork"),
4630+
providerTurnId: first.id,
4631+
sourceProviderTurns: [first, second],
4632+
})
4633+
.pipe(Effect.forkScoped);
4634+
assert.equal((yield* Fiber.join(terminal))?.status, "completed");
4635+
yield* TestClock.adjust("1 second");
4636+
assert.equal((yield* Fiber.join(fork)).nativeThreadRef?.nativeId, FORK);
4637+
}).pipe(Effect.scoped, Effect.provide(TestClock.layer())),
44074638
);
44084639

44094640
it.effect("moves a fork into its target thread's worktree before the first prompt", () =>

0 commit comments

Comments
 (0)