Files
Agent-Workbench/tests/desktop-host.test.mjs
2026-10-31 11:50:51 +08:00

91 lines
7.3 KiB
JavaScript

import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import path from 'node:path';
import { randomBytes, createHash } from 'node:crypto';
import { fixture, workspace, until } from './helpers.mjs';
import { hostProof, verifyHostProof, assertHostStop } from '../src/shared/contracts/desktop-host.mjs';
import { ownedChild, writeState, readState } from '../src/core/desktop/file-state.mjs';
import { HostAuthority } from '../src/core/desktop/host-authority.mjs';
import { Provider } from '../src/server/provider.mjs';
import { inspectHostInstallation } from '../src/core/desktop/app-installation.mjs';
test('a rebuilt source archive binds actual generated client assets and retains its original running identity after disk changes', t => {
const f = fixture(t), root = path.join(f.root, 'owned-source-build'); fs.mkdirSync(root);
for (const directory of ['dist-client', 'dist-server', 'dist-desktop']) fs.cpSync(path.join(workspace, directory), path.join(root, directory), { recursive: true });
const packageBytes = fs.readFileSync(path.join(workspace, 'package.json')); fs.writeFileSync(path.join(root, 'package.json'), packageBytes);
fs.writeFileSync(path.join(root, 'MANIFEST.json'), JSON.stringify({ app: 'agent-workbench', kind: 'source', version: JSON.parse(packageBytes).version,
files: [{ path: 'package.json', bytes: packageBytes.length, sha256: createHash('sha256').update(packageBytes).digest('hex') }] }));
const authority = new HostAuthority({ appDirectory: root, store: f.store, provider: new Provider(), runtime: { appDirectory: root, active: new Map(), waiters: new Map() }, server: { address: () => ({ port: 49998 }) } });
const running = authority.identity(), asset = 'dist-client/assets/' + fs.readdirSync(path.join(root, 'dist-client/assets')).find(name => name.endsWith('.js'));
assert.ok(inspectHostInstallation(root).inputs.some(value => value.path === asset));
fs.appendFileSync(path.join(root, asset), '\n// owned source-archive disk change\n');
assert.equal(authority.identity().runtimeIdentity, running.runtimeIdentity);
assert.notEqual(inspectHostInstallation(root).identitySha256, running.runtimeIdentity);
});
test('host challenge proof rejects a stale challenge, changed identity and changed signature', () => {
const identity = { instanceId: 'owned', pid: 123, createdAt: 'fixed', runtimeIdentity: 'fixed-input' }, secret = randomBytes(32), challenge = randomBytes(32).toString('hex');
const reply = { identity, challenge, proof: hostProof(identity, challenge, secret) };
assert.deepEqual(verifyHostProof(reply, challenge, secret), identity);
assert.throws(() => verifyHostProof(reply, randomBytes(32).toString('hex'), secret));
assert.throws(() => verifyHostProof({ ...reply, identity: { ...identity, pid: 124 } }, challenge, secret));
assert.throws(() => verifyHostProof(reply, challenge, randomBytes(32)));
assert.throws(() => hostProof(identity, 'short', secret));
});
test('stop confirmation binds the original instance, creation and loaded runtime', () => {
const identity = { instanceId: 'owned', createdAt: 'fixed', runtimeIdentity: 'fixed-input' }, input = { ...identity, confirmation: 'stop-owned-host' };
assertHostStop(input, identity);
for (const key of ['instanceId', 'createdAt', 'runtimeIdentity', 'confirmation']) assert.throws(() => assertHostStop({ ...input, [key]: 'changed' }, identity));
});
test('state paths reject escaping, linked ancestors, ambiguous hardlinks and damaged JSON', t => {
const f = fixture(t), owned = path.join(f.root, 'owned'); fs.mkdirSync(owned);
assert.throws(() => ownedChild(owned, '../outside', { missing: true }));
assert.throws(() => ownedChild(owned, 'file:stream', { missing: true }));
fs.symlinkSync(f.projectRoot, path.join(owned, 'linked'), 'junction');
assert.throws(() => ownedChild(owned, 'linked/README.md'));
const original = path.join(owned, 'original.json'); writeState(original, { original: true });
fs.linkSync(original, path.join(owned, 'second.json')); assert.throws(() => readState(original));
const damaged = path.join(owned, 'damaged.json'); fs.writeFileSync(damaged, '{'); assert.throws(() => writeState(damaged, {}));
const valid = path.join(owned, 'valid.json'); writeState(valid, { revision: 1 }); writeState(valid, { revision: 2 }); assert.deepEqual(readState(valid), { revision: 2 });
});
test('failed registration publishes no initialized memory and can complete after its actual inputs are supplied', { timeout: 30000 }, t => {
const f = fixture(t); f.store.claimRuntime();
const app = path.join(f.root, 'app'); fs.mkdirSync(app); fs.writeFileSync(path.join(app, 'package.json'), fs.readFileSync(path.join(workspace, 'package.json')));
const authority = new HostAuthority({ appDirectory: app, server: { address: () => ({ port: 12345 }) }, store: f.store, runtime: { appDirectory: app } });
assert.throws(() => authority.initialize()); assert.equal(authority.registration, undefined);
for (const directory of ['dist-server', 'dist-client']) fs.cpSync(path.join(workspace, directory), path.join(app, directory), { recursive: true });
authority.initialize(); const identity = authority.identity();
assert.equal(identity.pid, process.pid); assert.equal(identity.ownerId, f.store.ownerId);
assert.equal(readState(path.join(f.data, 'service-info.json')).instanceId, identity.instanceId);
assert.equal(JSON.stringify(authority.attest(randomBytes(32).toString('hex'))).includes(authority.registration.secret), false);
});
test('host shutdown cancels an un-signalled HTTP model request and refuses later requests until recovered', async () => {
let received;
const provider = new Provider({ fetch: async (_url, options) => new Promise((_resolve, reject) => {
received = options; options.signal.addEventListener('abort', () => reject(options.signal.reason), { once: true });
}) }); provider.setKey('owned-request-key');
const request = provider.models({ baseUrl: 'http://127.0.0.1:1/v1', model: 'owned' }).catch(error => error);
await until(() => received);
await provider.abortRequests(); const error = await request;
assert.equal(error instanceof Error, true); assert.equal(received.signal.aborted, true);
assert.equal(provider.activeRequests, 0); assert.equal(provider.requestControllers.size, 0); assert.equal(provider.lastRequest.status, 'interrupted');
await assert.rejects(provider.models({ baseUrl: 'http://127.0.0.1:1/v1' }), /停止/);
provider.resumeRequests(); assert.equal(provider.requestsClosing, false);
});
test('host shutdown cancels model-pool acquisition and releases queue ownership without inventing attempts', async t => {
const f = fixture(t), provider = new Provider(), hub = provider.modelHub(f.store);
const connection = hub.upsert({ name: 'owned', model: 'owned', baseUrl: 'http://127.0.0.1:1/v1', apiKey: 'owned-pool-key' });
hub.select({ type: 'connection', id: connection.id }); const config = hub.prepare(f.store.config);
hub.leases.set(connection.id, 1);
const request = hub.complete(config, { messages: [] }, undefined, null, null, () => { throw new Error('Queued request must not dispatch.'); }).catch(error => error);
await until(() => hub.waiting === 1); await provider.abortRequests(); const failure = await request;
assert.equal(failure instanceof Error, true); assert.equal(hub.waiting, 0); assert.equal(hub.attempts.length, 0); assert.equal(hub.leases.get(connection.id), 1);
hub.leases.clear();
});