Files
PaperClipAI/packages/adapters/opencode-local/src/server/models.test.ts
T
dmndbrp-ossandTest 7ef75f5636 fix(opencode-local): retry models preflight during transient contention (#9225)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Local CLI adapters are responsible for starting agent runtimes and
validating that their configured models are usable before a run starts.
> - The OpenCode local adapter checks `opencode models` during model
discovery and preflight validation.
> - On hosts with a shared Ollama daemon, that lightweight metadata call
can transiently queue behind an active generation and time out or return
a short failure.
> - Treating that transient contention as a hard adapter failure
prevents otherwise valid local OpenCode runs from starting.
> - This pull request adds a small bounded retry/backoff around OpenCode
model discovery while keeping the existing per-attempt timeout and
surfacing a final failure when retries are exhausted.
> - The benefit is fewer false adapter failures during local Ollama
contention without changing shared Ollama configuration or hiding
genuinely stuck model discovery.

## Linked Issues or Issue Description

No public GitHub issue exists for this adapter reliability bug.

Bug description:
- What happened: `opencode models` can transiently time out or fail
while a shared local Ollama daemon is busy serving another OpenCode
generation, causing the adapter preflight to fail before the actual run
starts.
- Expected behavior: transient model-list contention should be retried
briefly before declaring the adapter unavailable.
- Steps to reproduce: run an OpenCode local adapter using an
Ollama-backed model while another `opencode run` is actively generating
against the same daemon, then trigger model discovery/preflight during
that contention window.
- Paperclip version/commit: observed on the current Paperclip
master-line OpenCode local adapter before this change.
- Deployment mode: local trusted / local CLI adapter execution with a
shared local Ollama daemon.

Related search:
- Searched public GitHub issues for `opencode models preflight retry`;
no matching issue found.
- Searched public GitHub PRs for `opencode models preflight retry`; no
matching PR found. The only search hit was unrelated OpenClaw gateway
authentication work (#6121).

## What Changed

- Added bounded retry/backoff to OpenCode model discovery: three total
attempts with 2s and 4s waits between failures.
- Preserved the existing 20s per-attempt `opencode models` timeout.
- Retry covers timeout and non-zero process exits, while spawn-level
failures still surface immediately.
- Added unit coverage for transient fail -> timeout -> success behavior
and exhausted retry behavior.
- Updated existing OpenCode environment diagnostic tests with explicit
timeouts for the intentional retry/backoff path.

## Verification

- `pnpm --filter @paperclipai/adapter-opencode-local exec vitest run
src/server/models.test.ts src/server/execute.test.ts` -> 2 files passed,
13 tests passed.
- `pnpm --filter @paperclipai/adapter-opencode-local typecheck` ->
passed.
- `pnpm vitest run
server/src/__tests__/opencode-local-adapter-environment.test.ts` -> 1
file passed, 3 tests passed.
- Branch diff against current `upstream/master` is limited to
`packages/adapters/opencode-local/src/server/models.ts`,
`packages/adapters/opencode-local/src/server/models.test.ts`, and
`server/src/__tests__/opencode-local-adapter-environment.test.ts`.

## Risks

Low risk. This only changes OpenCode model discovery behavior and keeps
the preflight bounded. A genuinely unavailable `opencode models` call
still fails after three attempts, and command spawn failures are not
masked.

## Model Used

OpenAI Codex, GPT-5.5 coding agent, tool-enabled repository editing and
shell verification in a local Paperclip workspace.

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [x] All Paperclip CI gates are green
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

Co-authored-by: Test <test@paperclip.ing>
2026-08-17 14:02:30 -07:00

146 lines
4.9 KiB
TypeScript

import { afterEach, describe, expect, it, vi } from "vitest";
import * as serverUtils from "@paperclipai/adapter-utils/server-utils";
import {
discoverOpenCodeModels,
ensureOpenCodeModelConfiguredAndAvailable,
listOpenCodeModels,
requireOpenCodeModelId,
resetOpenCodeModelsCacheForTests,
} from "./models.js";
describe("openCode models", () => {
afterEach(() => {
delete process.env.PAPERCLIP_OPENCODE_COMMAND;
delete process.env.OPENCODE_ALLOW_ALL_MODELS;
resetOpenCodeModelsCacheForTests();
vi.restoreAllMocks();
vi.useRealTimers();
});
it("returns an empty list when discovery command is unavailable", async () => {
process.env.PAPERCLIP_OPENCODE_COMMAND = "__paperclip_missing_opencode_command__";
await expect(listOpenCodeModels()).resolves.toEqual([]);
});
it("rejects when model is missing", async () => {
await expect(
ensureOpenCodeModelConfiguredAndAvailable({ model: "" }),
).rejects.toThrow("OpenCode requires `adapterConfig.model`");
});
it("accepts a provider/model id without running discovery", () => {
expect(requireOpenCodeModelId("openai/gpt-5.2-codex")).toBe("openai/gpt-5.2-codex");
});
it("rejects malformed provider/model ids before discovery", () => {
expect(() => requireOpenCodeModelId("gpt-5.2-codex")).toThrow(
"OpenCode requires `adapterConfig.model`",
);
expect(() => requireOpenCodeModelId("openai/")).toThrow(
"OpenCode requires `adapterConfig.model`",
);
});
it("proceeds with the configured model when discovery cannot run (probe is best-effort, never fatal)", async () => {
process.env.PAPERCLIP_OPENCODE_COMMAND = "__paperclip_missing_opencode_command__";
await expect(
ensureOpenCodeModelConfiguredAndAvailable({
model: "openai/gpt-5",
}),
).resolves.toEqual([{ id: "openai/gpt-5", label: "openai/gpt-5" }]);
});
it("skips the availability check when OPENCODE_ALLOW_ALL_MODELS is set in the run env", async () => {
process.env.PAPERCLIP_OPENCODE_COMMAND = "__paperclip_missing_opencode_command__";
await expect(
ensureOpenCodeModelConfiguredAndAvailable({
model: "anthropic/tensorix/deepseek/deepseek-chat-v3.1",
env: { OPENCODE_ALLOW_ALL_MODELS: "true" },
}),
).resolves.toEqual([
{ id: "anthropic/tensorix/deepseek/deepseek-chat-v3.1", label: "anthropic/tensorix/deepseek/deepseek-chat-v3.1" },
]);
});
it("honours OPENCODE_ALLOW_ALL_MODELS from the process env", async () => {
process.env.PAPERCLIP_OPENCODE_COMMAND = "__paperclip_missing_opencode_command__";
process.env.OPENCODE_ALLOW_ALL_MODELS = "1";
await expect(
ensureOpenCodeModelConfiguredAndAvailable({ model: "anthropic/gateway/some-model" }),
).resolves.toEqual([{ id: "anthropic/gateway/some-model", label: "anthropic/gateway/some-model" }]);
});
it("still enforces provider/model format when OPENCODE_ALLOW_ALL_MODELS is set", async () => {
await expect(
ensureOpenCodeModelConfiguredAndAvailable({
model: "not-a-valid-id",
env: { OPENCODE_ALLOW_ALL_MODELS: "true" },
}),
).rejects.toThrow("OpenCode requires `adapterConfig.model`");
});
it("retries a transient `opencode models` failure with backoff before succeeding", async () => {
vi.useFakeTimers();
const spy = vi
.spyOn(serverUtils, "runChildProcess")
.mockResolvedValueOnce({
exitCode: 1,
signal: null,
timedOut: false,
stdout: "",
stderr: "queued behind another opencode run",
pid: 1,
startedAt: new Date().toISOString(),
})
.mockResolvedValueOnce({
exitCode: null,
signal: null,
timedOut: true,
stdout: "",
stderr: "",
pid: 1,
startedAt: new Date().toISOString(),
})
.mockResolvedValueOnce({
exitCode: 0,
signal: null,
timedOut: false,
stdout: "ollama/qwen2.5-coder:7b\n",
stderr: "",
pid: 1,
startedAt: new Date().toISOString(),
});
const promise = discoverOpenCodeModels();
await vi.runAllTimersAsync();
await expect(promise).resolves.toEqual([
{ id: "ollama/qwen2.5-coder:7b", label: "ollama/qwen2.5-coder:7b" },
]);
expect(spy).toHaveBeenCalledTimes(3);
});
it("surfaces the last error once retries are exhausted", async () => {
vi.useFakeTimers();
const spy = vi
.spyOn(serverUtils, "runChildProcess")
.mockResolvedValue({
exitCode: 1,
signal: null,
timedOut: false,
stdout: "",
stderr: "queued behind another opencode run",
pid: 1,
startedAt: new Date().toISOString(),
});
const promise = discoverOpenCodeModels();
const assertion = expect(promise).rejects.toThrow(
"`opencode models` failed: queued behind another opencode run",
);
await vi.runAllTimersAsync();
await assertion;
expect(spy).toHaveBeenCalledTimes(3);
});
});