Files
Netcatty/electron/bridges/aiBridge/sdk/opencodeDriver.startup.test.cjs
T
5be4731c4d feat(ai): support OpenCode 2.x while keeping 1.x working (#3802)
* feat(ai): support OpenCode 2.x while keeping the 1.x driver

Detect the installed opencode major version. 1.x stays on the bundled SDK and the old startup banner. 2.x uses the new serve banner, HTTP Basic auth, and the session API so model lists and chat turns work.

Fixes #3799

Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com>

* fix(ai): stop the OpenCode 2 event stream when a prompt is rejected

A rejected prompt does not emit a terminal SSE event. Abort that stream and close the server before waiting, and keep HTTP "not found" responses from being reported as a missing CLI.

Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com>

* fix(ai): select OpenCode 2 catalog ids and keep context optional

Aliases expose provider/catalog id rather than the provider API model id. A rejected instruction entry warns and still sends the user prompt. The entry value stays the system-prompt string, which is valid JSON for that endpoint.

Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com>

* fix(ai): post OpenCode 2 prompts after the event stream is open

The live /api/event stream does not replay. Wait until the server accepts the subscriber and start reading it before sending the user prompt.

Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com>

* fix(ai): refresh OpenCode version and catalog after startup races

Key the version cache by the resolved PATH binary and its mtime, so an in-place upgrade is not stuck on the previous major. While listing 2.x models, refetch after model.updated or provider.updated until the snapshot stays quiet.

Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com>

* fix(ai): refetch the OpenCode catalog when it changes during the first read

An update that arrives while the initial model list is in flight belongs to a newer snapshot. Record the event count before that request and fetch again when it moves.

Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com>

* fix(ai): refetch the OpenCode catalog when the settlement budget elapses during a read

A catalog read that outlasts the quiet-window budget still has to fetch the snapshot announced by an in-flight model or provider update.

Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com>

* fix(ai): localize OpenCode 2 failures when the server dies mid-turn

A killed event stream was surfacing undici's raw "terminated" text. Map that disconnect, a closed socket, and an SSE stream that ends before the turn finishes to the existing session-failed message.

Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com>

* fix(ai): ignore Bun version banners and hide undici transport errors

A crashed Bun binary was cached as OpenCode 1.x, and fetch or JSON-body failures still showed raw undici text. Skip Bun and Node.js runtime versions, and map those transport errors to the existing unavailable message.

Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com>

* fix(ai): keep the OpenCode 2 config model as a qualified string

The selected provider/model stays the original string in OPENCODE_CONFIG_CONTENT. Session create still sends Model.Ref with id and providerID.

Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com>

* fix(ai): keep caller OpenCode config and hide transport session errors

A profile's OPENCODE_CONFIG_CONTENT is merged under Netcatty's generated settings, and a server-reported fetch failure no longer reaches the chat as raw transport text.

Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com>

* fix(ai): drop undici transport text from OpenCode 2 details

HTTP error bodies and tool failures share the same sanitizer as session errors, so fetch failed, terminated, and other side closed never reach the chat.

Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com>

* fix(ai): keep OpenCode transport mapping to mid-stream failures

Server-authored tool and session messages are no longer rewritten just because they match a transport string. A dead reply stream still reports the localized session-failed key.

Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com>

* fix(ai): restore the OpenCode 2 server username

The transport-sanitizer edit replaced the opencode username constant, so a real 2.x spawn threw ReferenceError before Basic auth. Put the constant back and lock the default client username.

Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com>

---------

Co-authored-by: Cursor Agent <cursoragent@cursor.com>
Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com>
2026-10-20 22:03:54 +08:00

88 lines
4.0 KiB
JavaScript

const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const { getTempFilePath } = require('../../tempDirBridge.cjs');
const { listOpenCodeModels, resetOpenCodeListServerPool } = require('./opencodeDriver.cjs');
test('OpenCode releases the process-env gate after spawning separate catalog profiles', {
skip: process.platform === 'win32' && 'fixture executable uses a POSIX shebang',
timeout: 15000,
}, async (t) => {
try { await import('@opencode-ai/sdk'); } catch (error) {
if (error.code !== 'ERR_MODULE_NOT_FOUND') throw error;
t.skip('optional OpenCode SDK is not installed');
return;
}
const root = fs.mkdtempSync(`${getTempFilePath('opencode-startup-test')}-`);
const binPath = path.join(root, 'opencode');
const startedPath = path.join(root, 'started');
const readyPath = path.join(root, 'ready');
const originalHome = process.env.HOME;
fs.writeFileSync(binPath, `#!${process.execPath}
const fs = require('node:fs');
const http = require('node:http');
const path = require('node:path');
const root = ${JSON.stringify(root)};
if (process.argv.includes('--version')) {
console.log('1.19.3');
process.exit(0);
}
const profile = path.basename(process.env.HOME);
fs.appendFileSync(path.join(root, 'started'), profile + '\\n');
if (profile === 'profile-failed') process.exit(7);
const port = Number(process.argv.find(arg => arg.startsWith('--port=')).split('=')[1]);
const server = http.createServer((_req, res) => {
res.setHeader('content-type', 'application/json');
res.end(JSON.stringify({ providers: [], default: { fixture: profile } }));
});
const poll = setInterval(() => {
if (!fs.existsSync(path.join(root, 'ready'))) return;
clearInterval(poll);
server.listen(port, '127.0.0.1', () => console.log('opencode server listening on http://127.0.0.1:' + port));
}, 10);
`, { mode: 0o755 });
const loads = ['profile-a', 'profile-b'].map(profile => listOpenCodeModels({
binPath,
env: { PATH: process.env.PATH, HOME: path.join(root, profile) },
}));
// Observe every rejection immediately, including failures during cleanup.
const settled = Promise.allSettled(loads);
try {
const deadline = Date.now() + 5000;
let profiles = [];
while (Date.now() < deadline) {
profiles = fs.existsSync(startedPath) ? fs.readFileSync(startedPath, 'utf8').trim().split('\n') : [];
if (profiles.length === 2) break;
await new Promise(resolve => setTimeout(resolve, 20));
}
assert.deepEqual(profiles.sort(), ['profile-a', 'profile-b'], 'both profiles must spawn without waiting for either server to become ready');
assert.equal(process.env.HOME, originalHome, 'the parent environment must be restored while servers start');
fs.writeFileSync(readyPath, 'ready');
const results = await settled;
assert.deepEqual(results.map(result => result.status), ['fulfilled', 'fulfilled']);
assert.deepEqual(results.map(result => result.value.currentModelId), ['fixture/profile-a', 'fixture/profile-b']);
// A rejected startup must restore the environment and release the gate
// as well, so a subsequent profile still starts with its own HOME.
resetOpenCodeListServerPool();
const failed = await listOpenCodeModels({
binPath, env: { PATH: process.env.PATH, HOME: path.join(root, 'profile-failed') },
}).catch(error => {
assert.match(error.message, /Server exited with code 7/);
return { models: [] };
});
assert.equal(failed.models.length, 0);
assert.equal(process.env.HOME, originalHome);
const retry = await listOpenCodeModels({
binPath, env: { PATH: process.env.PATH, HOME: path.join(root, 'profile-retry') },
});
assert.equal(retry.currentModelId, 'fixture/profile-retry');
assert.equal(process.env.HOME, originalHome);
} finally {
fs.writeFileSync(readyPath, 'ready');
await settled;
resetOpenCodeListServerPool();
fs.rmSync(root, { recursive: true, force: true });
}
});