Files
Agent-Workbench/tests/upgrade.test.mjs
T

104 lines
9.7 KiB
JavaScript

import test from 'node:test';
import assert from 'node:assert/strict';
import path from 'node:path';
import fs from 'node:fs';
import { spawn } from 'node:child_process';
import { fixture, compatibleFixture, until, workspace, launchWorkbench } from './helpers.mjs';
import { upgradeRunning } from '../scripts/upgrade-running.mjs';
import { APP_VERSION } from '../src/server/diagnostics.mjs';
test('a directly started compiled host upgrades twice with the same PID, sessions, applied bytes and volatile provider', { timeout: 30000 }, async t => {
const f = fixture(t), host = await launchWorkbench(t, f.data);
const model = await compatibleFixture(t, () => ({ data: [{ id: 'direct-upgrade-fixture' }] }));
await host.api('/config', { mode: 'compatible', model: 'direct-upgrade-fixture', baseUrl: model.baseUrl, apiKey: 'fixture-direct-memory-key' });
await host.api('/sessions/' + f.session.id + '/proposals', { path: 'DIRECT-UPGRADE.md', content: '# Preserve applied source\n' });
const proposed = await host.api('/sessions/' + f.session.id);
await host.api('/sessions/' + f.session.id + '/changes/' + proposed.changes.at(-1).id + '/apply', {});
const before = await host.api('/sessions/' + f.session.id), bootstrap = await host.api('/bootstrap');
const beforeBytes = fs.readFileSync(path.join(f.projectRoot, 'DIRECT-UPGRADE.md'));
let previousRoot;
for (const label of ['first', 'second']) {
const nextRoot = path.join(f.root, 'compiled-upgrade-' + label); fs.mkdirSync(nextRoot);
for (const name of ['dist-server', 'dist-client']) fs.cpSync(path.join(workspace, name), path.join(nextRoot, name), { recursive: true });
fs.copyFileSync(path.join(workspace, 'package.json'), path.join(nextRoot, 'package.json'));
const result = await upgradeRunning({ url: host.url, pid: host.child.pid, currentRoot: workspace, handlerRoot: previousRoot, newRoot: nextRoot });
assert.equal(result.version, APP_VERSION); assert.equal(result.pid, host.child.pid); assert.equal(result.verified, true); assert.equal(result.hasKey, true);
const afterBootstrap = await host.api('/bootstrap');
assert.equal(afterBootstrap.runtimeRoot, nextRoot); assert.deepEqual(afterBootstrap.projects, bootstrap.projects); assert.deepEqual(afterBootstrap.sessions, bootstrap.sessions);
assert.deepEqual(await host.api('/sessions/' + f.session.id), before);
assert.deepEqual(fs.readFileSync(path.join(f.projectRoot, 'DIRECT-UPGRADE.md')), beforeBytes);
assert.deepEqual((await host.api('/config/models', {})).models, ['direct-upgrade-fixture']);
assert.equal(model.requests.at(-1).headers.authorization, 'Bearer fixture-direct-memory-key');
assert.ok(!fs.readFileSync(path.join(f.data, 'config.json'), 'utf8').includes('fixture-direct-memory-key'));
await assert.rejects(fetch('http://127.0.0.1:9229/json/list', { signal: AbortSignal.timeout(500) }));
previousRoot = nextRoot;
}
});
test('the running 0.1.0 process upgrades in place and retains its project, session, files and volatile model connection', { timeout: 60000 }, async t => {
const f = fixture(t);
const legacyData = path.join(f.root, 'legacy-data'); f.store.exportLegacyData(legacyData);
const oldRoot = path.join(workspace, 'tests', 'fixtures', 'legacy-workbench-0.1');
fs.writeFileSync(path.join(f.projectRoot, 'package.json'), '{"type":"module","scripts":{"test":"node --test case.test.mjs"}}');
fs.writeFileSync(path.join(f.projectRoot, 'case.test.mjs'), "import test from 'node:test'; import assert from 'node:assert/strict'; test('upgraded runtime npm check', () => assert.equal(1, 1));");
const isolatedNode = path.join(f.root, 'old-runtime', 'node.exe'); fs.mkdirSync(path.dirname(isolatedNode)); fs.copyFileSync(process.execPath, isolatedNode);
const env = { ...process.env, AGENT_WORKBENCH_APP_DIR: oldRoot, AGENT_WORKBENCH_DATA_DIR: legacyData, AGENT_WORKBENCH_PORT: '0' };
delete env.AGENT_WORKBENCH_API_KEY;
const child = spawn(process.platform === 'win32' ? isolatedNode : process.execPath, [path.join(oldRoot, 'dist-server', 'server.mjs')], { cwd: oldRoot, env, windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] });
let url = '', output = '', stderr = '';
child.stdout.on('data', bytes => { output += bytes.toString('utf8'); for (const line of output.split('\n')) { try { const result = JSON.parse(line); if (result.ready) url = result.url; } catch {} } });
child.stderr.on('data', bytes => { stderr += bytes.toString('utf8'); });
await until(() => url || child.exitCode !== null); assert.ok(url, stderr);
let bootstrap = await (await fetch(url + '/api/bootstrap', { headers: { Connection: 'close' } })).json();
const api = async (route, input) => {
const response = await fetch(url + '/api' + route, { method: input === undefined ? 'GET' : 'POST',
headers: { 'Content-Type': 'application/json', 'X-Workbench-Token': bootstrap.token, Connection: 'close' }, ...(input === undefined ? {} : { body: JSON.stringify(input) }) });
const value = await response.json(); assert.ok(response.ok, value.error); return value;
};
f.onCleanup(async () => { try { if (child.exitCode === null && child.signalCode === null) { await api('/shutdown', {}); await until(() => child.exitCode !== null, 5000); } } finally { if (child.exitCode === null && child.signalCode === null) child.kill(); } });
const model = await compatibleFixture(t, () => ({ data: [{ id: 'upgrade-fixture' }] }));
await api('/config', { mode: 'compatible', model: 'upgrade-fixture', baseUrl: model.baseUrl, apiKey: 'fixture-upgrade-memory-key' });
await api('/sessions/' + f.session.id + '/proposals', { path: 'UPGRADE-NOTE.md', content: '# Preserve this verified change\n', reason: 'Fixture before in-place upgrade' });
const proposed = await api('/sessions/' + f.session.id); await api('/sessions/' + f.session.id + '/changes/' + proposed.changes[0].id + '/apply', {});
const beforeBytes = fs.readFileSync(path.join(f.projectRoot, 'UPGRADE-NOTE.md'));
const legacyHotRoot = path.join(f.root, 'legacy-hot-1.0');
fs.mkdirSync(legacyHotRoot);
fs.cpSync(path.join(workspace, 'tests/fixtures/legacy-hot-1.0/dist-server'), path.join(legacyHotRoot, 'dist-server'), { recursive: true });
fs.cpSync(path.join(workspace, 'dist-client'), path.join(legacyHotRoot, 'dist-client'), { recursive: true });
const warm = await upgradeRunning({ url, pid: child.pid, currentRoot: oldRoot, newRoot: legacyHotRoot });
assert.equal(warm.version, '1.0.0'); assert.equal(warm.hasKey, true);
const result = await upgradeRunning({ url, pid: child.pid, currentRoot: oldRoot, handlerRoot: legacyHotRoot, newRoot: workspace });
assert.equal(result.version, APP_VERSION); assert.equal(result.pid, child.pid); assert.equal(result.verified, true);
assert.equal(result.hasKey, true); bootstrap = await (await fetch(url + '/api/bootstrap', { headers: { Connection: 'close' } })).json();
assert.equal(bootstrap.config.hasKey, true); assert.equal(bootstrap.config.model, 'upgrade-fixture');
assert.deepEqual(fs.readFileSync(path.join(f.projectRoot, 'UPGRADE-NOTE.md')), beforeBytes);
assert.equal((await api('/sessions/' + f.session.id)).changes[0].status, 'applied');
assert.equal((await api('/diagnostics?session=' + f.session.id)).version, APP_VERSION);
assert.deepEqual((await api('/config/models', {})).models, ['upgrade-fixture']);
assert.equal(model.requests[0].headers.authorization, 'Bearer fixture-upgrade-memory-key');
assert.ok(!fs.readFileSync(path.join(legacyData, 'config.json'), 'utf8').includes('fixture-upgrade-memory-key'));
assert.equal(bootstrap.storage.engine, 'sqlite');
assert.equal((await api('/sessions/' + f.session.id)).execution.task.origin, 'legacy-import');
const health = await (await fetch(url + '/api/health', { headers: { Connection: 'close' } })).json(); assert.equal(health.pid, child.pid);
await assert.rejects(fetch('http://127.0.0.1:9229/json/list', { signal: AbortSignal.timeout(500) }));
const secondRoot = path.join(f.root, 'upgrade-second');
fs.mkdirSync(secondRoot);
for (const name of ['dist-server', 'dist-client']) fs.cpSync(path.join(workspace, name), path.join(secondRoot, name), { recursive: true });
fs.copyFileSync(path.join(workspace, 'package.json'), path.join(secondRoot, 'package.json'));
fs.mkdirSync(path.join(secondRoot, 'runtime/node_modules'), { recursive: true });
fs.cpSync(path.join(path.dirname(process.execPath), 'node_modules/npm'), path.join(secondRoot, 'runtime/node_modules/npm'), { recursive: true });
const second = await upgradeRunning({ url, pid: child.pid, currentRoot: oldRoot, handlerRoot: workspace, newRoot: secondRoot });
assert.equal(second.verified, true); assert.equal(second.pid, child.pid); assert.equal(second.hasKey, true);
bootstrap = await (await fetch(url + '/api/bootstrap', { headers: { Connection: 'close' } })).json(); assert.equal(bootstrap.runtimeRoot, secondRoot);
assert.deepEqual((await api('/config/models', {})).models, ['upgrade-fixture']);
const planned = await api('/sessions/' + f.session.id + '/check-plans', {}), plan = planned.execution.plans.at(-1);
const accepted = await api('/sessions/' + f.session.id + '/check-jobs', { planId: plan.id }), jobId = accepted.execution.checks.at(-1).id;
await until(async () => !['queued', 'running'].includes((await api('/sessions/' + f.session.id + '/check-jobs/' + jobId)).status), 10000);
assert.equal((await api('/sessions/' + f.session.id + '/check-jobs/' + jobId)).status, 'passed');
await api('/shutdown', {}); await until(() => child.exitCode !== null, 5000);
const { DatabaseSync } = await import('node:sqlite');
const database = new DatabaseSync(path.join(legacyData, 'workbench.sqlite'), { readOnly: true });
try { assert.equal(JSON.parse(database.prepare('SELECT value FROM metadata WHERE key = ?').get('runtimeOwner').value), null); }
finally { database.close(); }
});