Skip to content

Commit 4b1c14f

Browse files
committed
fix(opencode): refresh uncertain goals and trust connected capabilities
1 parent 476d7fe commit 4b1c14f

4 files changed

Lines changed: 191 additions & 7 deletions

File tree

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

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5399,6 +5399,72 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
53995399
}).pipe(Effect.scoped),
54005400
);
54015401

5402+
it.effect.each([
5403+
{ initial: "active", recovered: "paused" },
5404+
{ initial: "paused", recovered: "active" },
5405+
{ initial: "active", recovered: "unreadable" },
5406+
] as const)(
5407+
"recovers unreadable native goal updates when cached goal is $initial and RPC returns $recovered",
5408+
({ initial, recovered }) =>
5409+
Effect.gen(function* () {
5410+
const { runtime, thread } = yield* resumed(
5411+
[
5412+
out("session.prompt", { sessionID: SESSION, id: PROMPT_ID, text: "<any>" }),
5413+
promptAccepted,
5414+
event("rpc.opencode.goal.changed", { sessionID: SESSION, goal: nativeGoal(initial) }),
5415+
event("rpc.opencode.goal.changed", {
5416+
sessionID: SESSION,
5417+
goal: { ...nativeGoal(initial), status: "unknown" },
5418+
}),
5419+
event("session.execution.succeeded", { sessionID: SESSION }),
5420+
out("rpc.call", "<any>"),
5421+
reply("rpc.call", { output: recovered === "unreadable" ? {} : nativeGoal(recovered) }),
5422+
...(recovered === "active"
5423+
? [
5424+
event("session.execution.started", { sessionID: SESSION }),
5425+
event("session.text.ended", {
5426+
sessionID: SESSION,
5427+
assistantMessageID: "msg_recovered_goal",
5428+
ordinal: 0,
5429+
text: "Continued work",
5430+
}),
5431+
event("rpc.opencode.goal.changed", {
5432+
sessionID: SESSION,
5433+
goal: nativeGoal("complete"),
5434+
}),
5435+
event("session.execution.succeeded", { sessionID: SESSION }),
5436+
]
5437+
: []),
5438+
],
5439+
{ version: "2.2.5" },
5440+
);
5441+
const events = yield* runtime.events.pipe(
5442+
Stream.takeUntil((e) => e.type === "turn.terminal"),
5443+
Stream.runCollect,
5444+
Effect.forkScoped,
5445+
);
5446+
yield* runtime.startTurn(turnInput(thread));
5447+
const collected = yield* Fiber.join(events);
5448+
const updated = collected.findLast((e) => e.type === "provider_thread.updated");
5449+
assert.equal(
5450+
updated?.type === "provider_thread.updated"
5451+
? updated.providerThread.goal?.status
5452+
: undefined,
5453+
recovered === "active" ? "complete" : recovered === "paused" ? "paused" : "active",
5454+
);
5455+
if (recovered === "active")
5456+
assert.isTrue(
5457+
collected.some(
5458+
(e) =>
5459+
e.type === "turn_item.updated" &&
5460+
e.turnItem.type === "assistant_message" &&
5461+
e.turnItem.text === "Continued work",
5462+
),
5463+
);
5464+
assert.deepInclude(collected.at(-1), { type: "turn.terminal", status: "completed" });
5465+
}).pipe(Effect.scoped),
5466+
);
5467+
54025468
it.effect.each(["show", "pause", "clear"] as const)(
54035469
"a delayed /goal %s response cannot finish its replacement turn",
54045470
(control) =>

‎packages/provider-opencode/src/server/driver.test.ts‎

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -258,6 +258,81 @@ it.layer(layer)("OpenCodeDriver runtime selection", (it) => {
258258
}).pipe(Effect.scoped),
259259
);
260260

261+
it.effect("uses the connected OpenCode version for goal support after an upgrade", () =>
262+
Effect.gen(function* () {
263+
const fs = yield* FileSystem.FileSystem;
264+
const root = yield* fs.makeTempDirectoryScoped({ prefix: "opencode-upgraded-goals-" });
265+
const binaryPath = NodePath.join(
266+
root,
267+
"lib",
268+
"node_modules",
269+
"@opencode",
270+
"cli",
271+
"bin",
272+
"opencode",
273+
);
274+
yield* fs.makeDirectory(NodePath.dirname(binaryPath), { recursive: true });
275+
yield* fs.writeFileString(binaryPath, "");
276+
const http = HttpClient.make((request) => {
277+
const path = new URL(request.url).pathname;
278+
if (path === "/api/info")
279+
return Effect.succeed(
280+
HttpClientResponse.fromWeb(
281+
request,
282+
Response.json({
283+
...JSON.parse(OPENCODE_2_RESPONSES["/api/info"].body),
284+
version: "2.2.5",
285+
}),
286+
),
287+
);
288+
if (path === "/api/model")
289+
return Effect.succeed(
290+
HttpClientResponse.fromWeb(
291+
request,
292+
Response.json({ location: { directory: "/work" }, data: [] }),
293+
),
294+
);
295+
if (path === "/api/event")
296+
return Effect.succeed(
297+
HttpClientResponse.fromWeb(
298+
request,
299+
new Response(new ReadableStream(), {
300+
headers: { "content-type": "text/event-stream" },
301+
}),
302+
),
303+
);
304+
return Effect.die(`Unexpected request: ${path}`);
305+
});
306+
const instance = yield* create({ binaryPath }, http).pipe(
307+
Effect.provideService(OpenCodeRuntime.OpenCodeRuntime, {
308+
...openCode2Runtime,
309+
runOpenCodeCommand: () =>
310+
Effect.succeed({ stdout: "opencode v2.2.4", stderr: "", code: 0 }),
311+
startOpenCodeServerProcess: ({ verify }) =>
312+
Effect.gen(function* () {
313+
const url = "http://127.0.0.1:4096";
314+
const version = verify ? yield* verify(url) : "2.2.5";
315+
return { url, version, isRunning: Effect.succeed(true), exitCode: Effect.never };
316+
}),
317+
}),
318+
);
319+
yield* instance.snapshot.resolveMaintenance({ fresh: true });
320+
assert.isFalse(
321+
(yield* instance.orchestrationAdapter.getCapabilities()).turns.supportsNativeGoals,
322+
);
323+
const session = yield* instance.orchestrationAdapter.openSession({
324+
threadId: ThreadId.make("upgraded-goal"),
325+
providerSessionId: ProviderSessionId.make("upgraded-goal"),
326+
modelSelection: { instanceId: instance.instanceId, model: "opencode/big-pickle" },
327+
runtimePolicy: { runtimeMode: "full-access", interactionMode: "default", cwd: null },
328+
});
329+
assert.isTrue(session.providerSession.capabilities.turns.supportsNativeGoals);
330+
assert.isTrue(
331+
(yield* instance.orchestrationAdapter.getCapabilities()).turns.supportsNativeGoals,
332+
);
333+
}).pipe(Effect.scoped),
334+
);
335+
261336
it.effect("answers capability reads without waiting on an unreachable server", () =>
262337
Effect.gen(function* () {
263338
const hang = HttpClient.make(() => Effect.never);

‎packages/provider-opencode/src/server/driver.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -130,7 +130,8 @@ function selectOpenCodeRuntimeAdapter(input: {
130130
turns: {
131131
...capabilities.turns,
132132
supportsNativeGoals:
133-
probed?.generation === "v2" && compareSemverVersions(probed.version, "2.2.5") >= 0,
133+
capabilities.turns.supportsNativeGoals ??
134+
(probed?.generation === "v2" && compareSemverVersions(probed.version, "2.2.5") >= 0),
134135
},
135136
};
136137
}),

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

Lines changed: 48 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -293,6 +293,7 @@ interface ThreadState {
293293
publishedBackgroundWork?: boolean;
294294
goalRevision: number;
295295
goalFresh: boolean;
296+
goalRefreshing: boolean;
296297
readonly providerTurns: Map<string, OrchestrationV2ProviderTurn>;
297298
active: ActiveTurn | undefined;
298299
model: ModelRef | undefined;
@@ -687,6 +688,7 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
687688
const continuationRequests = yield* ProviderContinuationRequests.ProviderContinuationRequests;
688689
const crypto = yield* Digest.Digest;
689690
const driver = OPENCODE_PROVIDER;
691+
let nativeGoalSupport: boolean | undefined;
690692
const mcpServerNameFor = (threadId: string) =>
691693
t3McpServerName(threadId).pipe(Effect.provideService(Digest.Digest, crypto));
692694

@@ -715,8 +717,10 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
715717
) {
716718
let connection = initial.connection;
717719
const supportsNativeGoals = () => compareSemverVersions(connection.version, "2.2.5") >= 0;
718-
const hasActiveGoal = (state: ThreadState) =>
719-
supportsNativeGoals() && state.goalFresh && state.providerThread.goal?.status === "active";
720+
nativeGoalSupport = supportsNativeGoals();
721+
const goalHoldsTurn = (state: ThreadState) =>
722+
supportsNativeGoals() &&
723+
(state.goalRefreshing || (state.goalFresh && state.providerThread.goal?.status === "active"));
720724
let client = connection.client;
721725
const sessionScope = yield* Effect.scope;
722726
// Project config changes model limits; key by directory because this runtime serves all instance threads.
@@ -779,6 +783,7 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
779783
providerThread,
780784
goalRevision: 0,
781785
goalFresh: false,
786+
goalRefreshing: false,
782787
providerTurns: new Map(),
783788
active: undefined,
784789
model: undefined,
@@ -877,6 +882,7 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
877882
) {
878883
state.goalRevision += 1;
879884
state.goalFresh = true;
885+
state.goalRefreshing = false;
880886
state.providerThread = {
881887
...state.providerThread,
882888
goal:
@@ -2348,15 +2354,15 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
23482354
turn: ActiveTurn,
23492355
end: TurnTerminal,
23502356
) {
2351-
if (end.status === "completed" && (turn.steers.size > 0 || hasActiveGoal(state))) {
2357+
if (end.status === "completed" && (turn.steers.size > 0 || goalHoldsTurn(state))) {
23522358
turn.heldEnd = end;
23532359
return;
23542360
}
23552361
yield* finishTurn(state, end);
23562362
});
23572363

23582364
const endIfSettled = (state: ThreadState, turn: ActiveTurn) =>
2359-
turn.heldEnd !== undefined && turn.steers.size === 0 && !hasActiveGoal(state)
2365+
turn.heldEnd !== undefined && turn.steers.size === 0 && !goalHoldsTurn(state)
23602366
? finishTurn(state, turn.heldEnd)
23612367
: Effect.void;
23622368

@@ -2484,7 +2490,35 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
24842490
if (event.type === "rpc.opencode.goal.changed") {
24852491
if (!supportsNativeGoals()) return;
24862492
const goal = yield* decodeGoal(event.data["goal"]).pipe(Effect.result);
2487-
if (goal._tag === "Failure") return;
2493+
if (goal._tag === "Failure") {
2494+
state.goalFresh = false;
2495+
state.goalRefreshing = true;
2496+
state.goalRevision += 1;
2497+
const revision = state.goalRevision;
2498+
yield* Effect.logWarning(
2499+
"Could not decode an OpenCode goal update; refreshing its state.",
2500+
);
2501+
yield* Effect.forkIn(
2502+
readGoal(state).pipe(
2503+
Effect.timeout(INVENTORY_TIMEOUT),
2504+
Effect.catch(() =>
2505+
Effect.logWarning(
2506+
"Could not refresh OpenCode goal state after an unreadable update.",
2507+
),
2508+
),
2509+
Effect.ensuring(
2510+
lock.withPermit(
2511+
Effect.gen(function* () {
2512+
if (state.goalRevision === revision) state.goalRefreshing = false;
2513+
if (state.active !== undefined) yield* endIfSettled(state, state.active);
2514+
}),
2515+
),
2516+
),
2517+
),
2518+
sessionScope,
2519+
);
2520+
return;
2521+
}
24882522
yield* updateGoal(state, goal.success);
24892523
if (state.active !== undefined) yield* endIfSettled(state, state.active);
24902524
return;
@@ -2761,6 +2795,7 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
27612795
const previous = currentScope;
27622796
connection = next;
27632797
client = next.client;
2798+
nativeGoalSupport = supportsNativeGoals();
27642799
session = {
27652800
...session,
27662801
capabilities: {
@@ -2774,6 +2809,7 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
27742809
for (const state of threads.values()) {
27752810
state.mcp = undefined;
27762811
state.goalFresh = false;
2812+
state.goalRefreshing = false;
27772813
state.goalRevision += 1;
27782814
}
27792815
if (supportsNativeGoals()) {
@@ -4251,7 +4287,13 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
42514287
instanceId,
42524288
driver,
42534289
getCapabilities: Effect.fn("OpencodeAdapter.getCapabilities")(function () {
4254-
return Effect.succeed(OpenCode2ProviderCapabilities);
4290+
return Effect.succeed({
4291+
...OpenCode2ProviderCapabilities,
4292+
turns: {
4293+
...OpenCode2ProviderCapabilities.turns,
4294+
...(nativeGoalSupport === undefined ? {} : { supportsNativeGoals: nativeGoalSupport }),
4295+
},
4296+
});
42554297
}),
42564298
planSelectionTransition: Effect.fn("OpencodeAdapter.planSelectionTransition")(function () {
42574299
return Effect.succeed(turnScopedSelectionTransition());

0 commit comments

Comments
 (0)