Skip to content

Commit e2d5c2f

Browse files
Harden OpenCode adapter and surface provider
- Keep event pumping alive when native event logging fails - Aggregate shutdown failures across multiple OpenCode sessions - Resolve OpenCode binaries from absolute paths or PATH - Add OpenCode to provider selection fixtures and availability
1 parent d5c083b commit e2d5c2f

6 files changed

Lines changed: 153 additions & 19 deletions

File tree

‎apps/server/src/provider/Layers/OpenCodeAdapter.test.ts‎

Lines changed: 60 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -230,7 +230,11 @@ it.layer(OpenCodeAdapterTestLayer)("OpenCodeAdapterLive", (it) => {
230230
const sessions = yield* adapter.listSessions();
231231

232232
assert.equal(error._tag, "ProviderAdapterProcessError");
233-
assert.equal(error.detail, "close failed");
233+
assert.equal(error.detail, "Failed to stop 2 OpenCode sessions.");
234+
assert.deepEqual(runtimeMock.state.closeCalls, [
235+
"http://127.0.0.1:9999",
236+
"http://127.0.0.1:9999",
237+
]);
234238
assert.deepEqual(sessions, []);
235239
}),
236240
);
@@ -424,4 +428,59 @@ it.layer(OpenCodeAdapterTestLayer)("OpenCodeAdapterLive", (it) => {
424428
);
425429
}),
426430
);
431+
432+
it.effect("keeps the event pump alive when native event logging fails", () =>
433+
Effect.gen(function* () {
434+
runtimeMock.state.subscribedEvents = [
435+
{
436+
type: "message.updated",
437+
properties: {
438+
sessionID: "http://127.0.0.1:9999/session",
439+
info: {
440+
id: "msg-native-log-failure",
441+
role: "assistant",
442+
},
443+
},
444+
},
445+
];
446+
447+
const nativeEventLogger = {
448+
filePath: "memory://opencode-native-events",
449+
write: () => Effect.die(new Error("native log write failed")),
450+
close: () => Effect.void,
451+
};
452+
453+
const adapterLayer = makeOpenCodeAdapterLive({ nativeEventLogger }).pipe(
454+
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
455+
Layer.provideMerge(
456+
ServerSettingsService.layerTest({
457+
providers: {
458+
opencode: {
459+
binaryPath: "fake-opencode",
460+
serverUrl: "http://127.0.0.1:9999",
461+
serverPassword: "secret-password",
462+
},
463+
},
464+
}),
465+
),
466+
Layer.provideMerge(providerSessionDirectoryTestLayer),
467+
Layer.provideMerge(NodeServices.layer),
468+
);
469+
470+
const sessions = yield* Effect.gen(function* () {
471+
const adapter = yield* OpenCodeAdapter;
472+
yield* adapter.startSession({
473+
provider: "opencode",
474+
threadId: asThreadId("thread-native-log-failure"),
475+
runtimeMode: "full-access",
476+
});
477+
yield* sleep(10);
478+
return yield* adapter.listSessions();
479+
}).pipe(Effect.provide(adapterLayer));
480+
481+
assert.equal(sessions.length, 1);
482+
assert.equal(sessions[0]?.threadId, "thread-native-log-failure");
483+
assert.deepEqual(runtimeMock.state.closeCalls, []);
484+
}),
485+
);
427486
});

‎apps/server/src/provider/Layers/OpenCodeAdapter.ts‎

Lines changed: 23 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -411,6 +411,13 @@ export function makeOpenCodeAdapterLive(_options?: OpenCodeAdapterLiveOptions) {
411411
(nativeEventLogger ? nativeEventLogger.write(event, threadId) : Effect.void).pipe(
412412
Effect.runPromiseWith(services),
413413
);
414+
const writeNativeEventBestEffort = (
415+
threadId: ThreadId,
416+
event: {
417+
readonly observedAt: string;
418+
readonly event: Record<string, unknown>;
419+
},
420+
) => writeNativeEventPromise(threadId, event).catch(() => undefined);
414421

415422
const emitUnexpectedExit = (context: OpenCodeSessionContext, message: string) => {
416423
if (context.stopped) {
@@ -523,7 +530,7 @@ export function makeOpenCodeAdapterLive(_options?: OpenCodeAdapterLiveOptions) {
523530
}
524531

525532
const turnId = context.activeTurnId;
526-
await writeNativeEventPromise(context.session.threadId, {
533+
await writeNativeEventBestEffort(context.session.threadId, {
527534
observedAt: nowIso(),
528535
event: {
529536
provider: PROVIDER,
@@ -1285,7 +1292,21 @@ export function makeOpenCodeAdapterLive(_options?: OpenCodeAdapterLiveOptions) {
12851292
try: async () => {
12861293
const contexts = [...sessions.values()];
12871294
sessions.clear();
1288-
await Promise.all(contexts.map((context) => stopOpenCodeContext(context)));
1295+
const results = await Promise.allSettled(
1296+
contexts.map((context) => stopOpenCodeContext(context)),
1297+
);
1298+
const errors = results
1299+
.filter((result): result is PromiseRejectedResult => result.status === "rejected")
1300+
.map((result) => result.reason);
1301+
if (errors.length === 1) {
1302+
throw errors[0];
1303+
}
1304+
if (errors.length > 1) {
1305+
throw new AggregateError(
1306+
errors,
1307+
`Failed to stop ${errors.length} OpenCode sessions.`,
1308+
);
1309+
}
12891310
},
12901311
catch: (cause) =>
12911312
new ProviderAdapterProcessError({
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
import assert from "node:assert/strict";
2+
3+
import { describe, it, vi } from "vitest";
4+
5+
const childProcessMock = vi.hoisted(() => ({
6+
execFileSync: vi.fn((command: string, args: ReadonlyArray<string>) => {
7+
if (command === "which" && args[0] === "opencode") {
8+
return "/opt/homebrew/bin/opencode\n";
9+
}
10+
return "";
11+
}),
12+
spawn: vi.fn(),
13+
}));
14+
15+
vi.mock("node:child_process", () => childProcessMock);
16+
17+
describe("resolveOpenCodeBinaryPath", () => {
18+
it("returns absolute binary paths without PATH lookup", async () => {
19+
const { resolveOpenCodeBinaryPath } = await import("./opencodeRuntime.ts");
20+
21+
assert.equal(resolveOpenCodeBinaryPath("/usr/local/bin/opencode"), "/usr/local/bin/opencode");
22+
assert.equal(childProcessMock.execFileSync.mock.calls.length, 0);
23+
});
24+
25+
it("resolves command names through PATH", async () => {
26+
const { resolveOpenCodeBinaryPath } = await import("./opencodeRuntime.ts");
27+
28+
assert.equal(resolveOpenCodeBinaryPath("opencode"), "/opt/homebrew/bin/opencode");
29+
assert.deepEqual(childProcessMock.execFileSync.mock.calls[0], [
30+
"which",
31+
["opencode"],
32+
{
33+
encoding: "utf8",
34+
timeout: 3_000,
35+
},
36+
]);
37+
});
38+
});

‎apps/server/src/provider/opencodeRuntime.ts‎

Lines changed: 16 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -300,13 +300,20 @@ export async function findAvailablePort(): Promise<number> {
300300
return port;
301301
}
302302

303-
function detectMacosSigkillHint(binaryPath: string): string | null {
303+
export function resolveOpenCodeBinaryPath(binaryPath: string): string {
304+
if (Path.isAbsolute(binaryPath)) {
305+
return binaryPath;
306+
}
307+
return execFileSync("which", [binaryPath], {
308+
encoding: "utf8",
309+
timeout: 3_000,
310+
}).trim();
311+
}
312+
313+
export function detectMacosSigkillHint(binaryPath: string): string | null {
304314
try {
305315
// Check for quarantine xattr first.
306-
const resolvedPath = execFileSync("which", [binaryPath], {
307-
encoding: "utf8",
308-
timeout: 3_000,
309-
}).trim();
316+
const resolvedPath = resolveOpenCodeBinaryPath(binaryPath);
310317
const xattr = execFileSync("xattr", ["-l", resolvedPath], {
311318
encoding: "utf8",
312319
timeout: 3_000,
@@ -319,15 +326,12 @@ function detectMacosSigkillHint(binaryPath: string): string | null {
319326
}
320327

321328
// Look for a recent crash report with the termination reason.
322-
const crashDir = Path.join(
323-
OS.homedir(),
324-
"Library/Logs/DiagnosticReports",
325-
);
329+
const crashDir = Path.join(OS.homedir(), "Library/Logs/DiagnosticReports");
326330
const binaryName = Path.basename(resolvedPath);
327331
const recentReports = FS.readdirSync(crashDir)
328332
.filter((f) => f.startsWith(binaryName) && f.endsWith(".ips"))
329-
.sort()
330-
.reverse()
333+
.toSorted()
334+
.toReversed()
331335
.slice(0, 1);
332336

333337
for (const report of recentReports) {
@@ -412,9 +416,7 @@ export async function startOpenCodeServerProcess(input: {
412416

413417
const onClose = (code: number | null, signal: NodeJS.Signals | null) => {
414418
cleanup();
415-
const exitReason = signal
416-
? `signal: ${signal}`
417-
: `code: ${code ?? "unknown"}`;
419+
const exitReason = signal ? `signal: ${signal}` : `code: ${code ?? "unknown"}`;
418420
const hint =
419421
signal === "SIGKILL" && process.platform === "darwin"
420422
? detectMacosSigkillHint(input.binaryPath)

‎apps/web/src/components/chat/TraitsPicker.browser.tsx‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -159,6 +159,13 @@ const TEST_PROVIDERS: ReadonlyArray<ServerProvider> = [
159159
],
160160
},
161161
];
162+
const findTestProvider = (provider: ServerProvider["provider"]) => {
163+
const testProvider = TEST_PROVIDERS.find((candidate) => candidate.provider === provider);
164+
if (!testProvider) {
165+
throw new Error(`Missing test provider fixture: ${provider}`);
166+
}
167+
return testProvider;
168+
};
162169

163170
function ClaudeTraitsPickerHarness(props: {
164171
model: string;
@@ -573,7 +580,7 @@ async function mountOpenCodePicker(props: { model?: string; options?: OpenCodeMo
573580
const screen = await render(
574581
<TraitsPicker
575582
provider="opencode"
576-
models={TEST_PROVIDERS[1]!.models}
583+
models={findTestProvider("opencode").models}
577584
threadRef={threadRef}
578585
model={model}
579586
prompt=""

‎apps/web/src/session-logic.test.ts‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1326,19 +1326,26 @@ describe("deriveActiveWorkStartedAt", () => {
13261326
});
13271327

13281328
describe("PROVIDER_OPTIONS", () => {
1329-
it("advertises Claude as available while keeping Cursor as a placeholder", () => {
1329+
it("advertises available providers while keeping Cursor as a placeholder", () => {
13301330
const claude = PROVIDER_OPTIONS.find((option) => option.value === "claudeAgent");
1331+
const opencode = PROVIDER_OPTIONS.find((option) => option.value === "opencode");
13311332
const cursor = PROVIDER_OPTIONS.find((option) => option.value === "cursor");
13321333
expect(PROVIDER_OPTIONS).toEqual([
13331334
{ value: "codex", label: "Codex", available: true },
13341335
{ value: "claudeAgent", label: "Claude", available: true },
1336+
{ value: "opencode", label: "OpenCode", available: true },
13351337
{ value: "cursor", label: "Cursor", available: false },
13361338
]);
13371339
expect(claude).toEqual({
13381340
value: "claudeAgent",
13391341
label: "Claude",
13401342
available: true,
13411343
});
1344+
expect(opencode).toEqual({
1345+
value: "opencode",
1346+
label: "OpenCode",
1347+
available: true,
1348+
});
13421349
expect(cursor).toEqual({
13431350
value: "cursor",
13441351
label: "Cursor",

0 commit comments

Comments
 (0)