Files
openbot/scripts/opencode-service-failure-e2e.ts
Aleksander DygońandClaude Opus 5.5 190b012cfe Start OpenCode when its plugins need more time to load (#14567)
* Start OpenCode when its plugins need more time to load

OpenCode waits 5 seconds for the plugins of a folder to load. When they
take longer, it answers the session/new request that OpenBot sends to
list the models with -32603 "Internal error: Internal service failure"
and data.errorName "ServiceUnavailableError". OpenBot counted this as a
failed start, so each start failed after about 10 seconds, and after
three starts OpenBot stopped trying. The status showed only the raw
OpenCode text.

Now the model check asks again each second while OpenCode answers that
it is still loading, inside the existing discovery deadline. A cold
start, a slow sign-in refresh or many plugins now finish in the first
start. When OpenCode still cannot finish, the status says "OpenCode did
not finish loading in time. OpenBot will try again." The start keeps the
existing automatic restart, and the CLI update check accepts the new
text as it accepts the raw one, so a new OpenCode copy is not removed
(#6746).

The approach follows t3code (#30263) and the OpenCode app, which both
retry this 503 while OpenCode loads its plugins.

scripts/opencode-service-failure-e2e.ts, which CI already runs, now
starts a fake OpenCode that fails session/new with the same error: two
failures then success, and failures that never end. Without the fix the
first case ends in "error". Checked by hand against the real OpenCode
2.3.2 with a plugin that needs 12 seconds: the provider is available
after 14 seconds on the first start.

Fixes #13248

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Stop the OpenCode model retry before an attempt can pass the deadline

The smoke test found that, with an OpenCode plugin that never finishes
loading, the start ran for its full window and ended as a timeout. A
real failed attempt takes about 10 seconds, but the retry only checked
that 1 second was left before the deadline. So the last attempt ran past
the discovery timeout, the start took the timeout path, the new text did
not show, and each later start waited longer (up to 6 minutes seen).

Now the model check asks again only while the longest attempt so far,
plus the 1 second pause, still fits before the deadline. The time is
kept for each run, because the resume fallback runs the same check
again. The last error then stays OpenCode's error, so the start shows
"OpenCode did not finish loading in time. OpenBot will try again." and
uses the normal restarts, with no longer waits.

The fake OpenCode now waits before each failure, and the stuck case of
scripts/opencode-service-failure-e2e.ts uses a 6 second window with a
1.5 second wait. With the old check it fails as the smoke test did (a
timeout after 6 s and "did not answer in time"); with this change it
ends after 4 s with the new text.

Fixes #13248

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Say in the release note that OpenBot still stops after three OpenCode starts that cannot finish

The local review found that the note could be read as if OpenBot no
longer stops after three starts. That stop is still there for OpenCode
that never finishes loading its plugins, as the smoke test shows.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 12:29:59 +01:00

164 lines
6.2 KiB
TypeScript

import assert from "node:assert/strict";
import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join, resolve } from "node:path";
import { sourceText } from "@openbot/i18n/source";
import { Effect } from "effect";
import { ConversationRuntime } from "../src/backend/agent/conversation-runtime";
import { ProviderRuntime } from "../src/backend/agent/provider-runtime";
import type { AgentClient } from "../src/backend/agent-client";
import { AgentStore } from "../src/backend/agent-store";
import type { AgentCliInfo } from "../src/backend/cli";
import { runCauseEffect } from "../src/backend/effect-boundary";
import { OpenBotDatabase } from "../src/backend/openbot-database";
import {
BUILT_IN_PROVIDER_DRIVERS,
NO_PROVIDER_CREDENTIALS,
requireProviderDriver,
} from "../src/backend/provider-drivers";
import { installFakeAgent, readJsonl, runTurn, startThread, stopClients } from "./provider-fakes/host";
const OUT = resolve(import.meta.dirname, "../.openbot-build/opencode-service-failure-e2e");
const WAIT_MS = 30_000;
interface StartReport {
state: string | undefined;
message: string | null | undefined;
starts: number;
activationFailures: number;
}
interface Report {
passed: boolean;
turn?: { error: string };
slowPlugins?: StartReport;
stuckPlugins?: StartReport;
}
const root = await mkdtemp(join(tmpdir(), "openbot-opencode-service-failure-e2e-"));
const report: Report = { passed: false };
const clients: AgentClient[] = [];
async function waitFor(label: string, check: () => boolean): Promise<void> {
const deadline = Date.now() + WAIT_MS;
while (!check()) {
if (Date.now() > deadline) throw new Error(`Timed out waiting for ${label}.`);
await new Promise((resume) => setTimeout(resume, 50));
}
}
async function startWithActivationFailures(
name: string,
activationFailures: number,
requestTimeoutMs: number,
activationDelayMs: number,
settled: (row: { state: string; message: string | null } | undefined) => boolean,
): Promise<StartReport> {
const folder = join(root, name);
const log = join(folder, "fake.jsonl");
const executable = join(folder, "runtime", "opencode", "bin", "opencode");
await installFakeAgent(executable, "opencode-plugin-activation", {
FAKE_LOG: log,
FAKE_OPENCODE_ACTIVATION_FAILURES: String(activationFailures),
FAKE_OPENCODE_ACTIVATION_DELAY_MS: String(activationDelayMs),
});
const store = new AgentStore(
join(folder, "profile"),
join(folder, "home"),
new OpenBotDatabase(join(folder, "profile")),
);
const providers = new ProviderRuntime({
offProviders: BUILT_IN_PROVIDER_DRIVERS.map((driver) => driver.id).filter((id) => id !== "opencode"),
conversation: new ConversationRuntime(
store,
() => undefined,
() => store.list(),
),
hooks: {
bindClient: () => undefined,
onProvidersReady: () => Effect.void,
onProviderLost: () => undefined,
onClientStopped: () => Effect.void,
isStopping: () => false,
isProviderBusy: () => false,
isAgentBusy: () => false,
isProviderAssigned: () => true,
onAgentClientLost: () => Effect.void,
sharedRoot: () => join(folder, "shared"),
onProviderResumed: () => undefined,
onProviderActivated: () => Effect.void,
captureConfigRevision: () => 0,
},
emit: () => undefined,
emitError: () => undefined,
requestTimeoutMs,
preferredProvider: "opencode",
clientFactory: null,
bundledExecutables: { opencode: executable },
saveInstalledCliChoice: () => Effect.void,
credentials: { ...NO_PROVIDER_CREDENTIALS, providerTempDirectory: join(folder, "temp") },
redactMcp: (text) => text,
});
const row = () => providers.status().providers?.find((candidate) => candidate.id === "opencode");
try {
await runCauseEffect(providers.ensureProvider("opencode").pipe(Effect.ignore));
await waitFor(`${name} to settle`, () => settled(row()));
const entries = await readJsonl<{ event: string }>(log);
return {
state: row()?.state,
message: row()?.message,
starts: entries.filter((entry) => entry.event === "start").length,
activationFailures: entries.filter((entry) => entry.event === "plugins-activating").length,
};
} finally {
for (const client of await runCauseEffect(providers.dispose())) await runCauseEffect(client.stop());
}
}
try {
const workspace = join(root, "workspace");
await mkdir(workspace);
const executable = join(root, "opencode", "bin", "opencode");
await installFakeAgent(executable, "opencode-service-failure");
const cli: AgentCliInfo = { executable, version: "2.1.3", source: "managed" };
const client = requireProviderDriver("opencode").createClient(cli, 10_000, NO_PROVIDER_CREDENTIALS);
clients.push(client);
client.start();
const { error } = await runTurn(client, await startThread(client, { cwd: workspace }));
assert.equal(error, sourceText("error.provider.opencodeServiceFailure"), "A failed turn names OpenCode's service.");
report.turn = { error };
report.slowPlugins = await startWithActivationFailures(
"slow-plugins",
2,
10_000,
0,
(row) => row?.state !== "starting",
);
assert.equal(report.slowPlugins.state, "available", "OpenCode starts once its plugins finish loading.");
assert.equal(report.slowPlugins.starts, 1, "The first start waits for the plugins; it does not fail.");
assert.equal(report.slowPlugins.activationFailures, 2);
report.stuckPlugins = await startWithActivationFailures(
"stuck-plugins",
-1,
6_000,
1_500,
(row) => row?.state === "error",
);
assert.equal(
report.stuckPlugins.message,
sourceText("error.provider.opencodeStillStarting"),
"A start that OpenCode's plugins never let finish shows plain text.",
);
assert.equal(report.stuckPlugins.starts, 1, "The model list is asked again inside the same start.");
assert.ok(report.stuckPlugins.activationFailures > 1, "The start asks again before it gives up.");
report.passed = true;
} finally {
await stopClients(clients);
await mkdir(OUT, { recursive: true });
await writeFile(join(OUT, "report.json"), `${JSON.stringify(report, null, 2)}\n`);
await rm(root, { recursive: true, force: true });
}
process.stdout.write(`${JSON.stringify(report, null, 2)}\n`);