From f4bd0ad8dcff98e11f5f3ad7fb411765306ee185 Mon Sep 17 00:00:00 2001 From: Agent Workbench Dev Date: Fri, 30 Oct 2026 23:01:19 +0800 Subject: [PATCH] fix: preserve model state, isolate commands and harden local HTTP in 1.12.1 --- package-lock.json | 4 +- package.json | 2 +- scripts/qa-evidence.mjs | 1 + scripts/upgrade-running.mjs | 2 +- scripts/verify-all-ui.mjs | 20 +++++---- scripts/verify-archives.py | 6 +++ scripts/verify-change-sets-ui.mjs | 2 +- scripts/verify-context-ui.mjs | 2 +- scripts/verify-release.mjs | 9 ++-- scripts/verify-source-package.mjs | 9 ++-- src/core/check-runner.mjs | 9 +--- src/core/models/config-import.mjs | 40 +++++++++-------- src/core/models/model-hub.mjs | 47 ++++++++++++++++---- src/core/process-environment.mjs | 11 +++++ src/core/python-runtime.mjs | 5 +-- src/server/app.mjs | 10 ++++- src/server/diagnostics.mjs | 2 +- src/server/hot-upgrade.mjs | 11 +++++ src/server/provider.mjs | 2 + src/server/runtime.mjs | 9 ++-- src/server/store.mjs | 4 +- tests/api.test.mjs | 19 ++++++++ tests/config-transaction-api.test.mjs | 40 +++++++++++++++++ tests/model-center.test.mjs | 63 +++++++++++++++++++++++++++ tests/process-environment.test.mjs | 57 ++++++++++++++++++++++++ tests/upgrade-model-center.test.mjs | 55 +++++++++++++++++++++++ 26 files changed, 373 insertions(+), 68 deletions(-) create mode 100644 src/core/process-environment.mjs create mode 100644 tests/config-transaction-api.test.mjs create mode 100644 tests/process-environment.test.mjs create mode 100644 tests/upgrade-model-center.test.mjs diff --git a/package-lock.json b/package-lock.json index 3e61a96f..ad0f9113 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "local-agent-workbench", - "version": "1.12.0", + "version": "1.12.1", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "local-agent-workbench", - "version": "1.12.0", + "version": "1.12.1", "dependencies": { "@babel/parser": "7.29.11", "diff": "^8.0.2", diff --git a/package.json b/package.json index 524cfeb4..211a3dfa 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "local-agent-workbench", - "version": "1.12.0", + "version": "1.12.1", "private": true, "type": "module", "description": "A local coding workbench with explicit tool execution, reviewable changes and recoverable sessions.", diff --git a/scripts/qa-evidence.mjs b/scripts/qa-evidence.mjs index f83bd9bb..dbe9d526 100644 --- a/scripts/qa-evidence.mjs +++ b/scripts/qa-evidence.mjs @@ -4,6 +4,7 @@ const prefixes = Object.freeze({ '1.6.1': 'working-context', '1.6.2': 'working-retention', '1.7.0': 'python-engine', '1.8.0': 'rea-engine', '1.9.0': 'external-engines', '1.10.0': 'browser-engine', '1.10.1': 'browser-hotfix', '1.11.0': 'task-plans', '1.12.0': 'model-center', + '1.12.1': 'milestone-audit', }); export function releaseEvidencePrefix(version) { const prefix = prefixes[version]; diff --git a/scripts/upgrade-running.mjs b/scripts/upgrade-running.mjs index 7daef999..40b31e89 100644 --- a/scripts/upgrade-running.mjs +++ b/scripts/upgrade-running.mjs @@ -64,7 +64,7 @@ export async function upgradeRunning({ url, pid, currentRoot, newRoot, handlerRo if (!fs.existsSync(originalScript) || !fs.existsSync(upgradeScript) || !fs.existsSync(path.join(next, 'dist-client', 'index.html'))) throw new Error('Upgrade bundles are incomplete.'); if (!Number.isInteger(pid) || pid < 1 || pid === process.pid) throw new Error('Invalid target process.'); const before = await readUpgradeJson(origin + '/api/bootstrap', 5000, 'Read original Workbench'); - if (!before.token || !['0.1.0', '1.0.0', '1.1.0', '1.2.0', '1.3.0', '1.4.0', '1.5.0', '1.5.1', '1.6.0', '1.6.1', '1.6.2', '1.7.0', '1.8.0', '1.9.0', '1.10.0', '1.10.1', '1.11.0', '1.12.0'].includes(before.version)) throw new Error('This migration accepts a supported existing Workbench.'); + if (!before.token || !['0.1.0', '1.0.0', '1.1.0', '1.2.0', '1.3.0', '1.4.0', '1.5.0', '1.5.1', '1.6.0', '1.6.1', '1.6.2', '1.7.0', '1.8.0', '1.9.0', '1.10.0', '1.10.1', '1.11.0', '1.12.0', '1.12.1'].includes(before.version)) throw new Error('This migration accepts a supported existing Workbench.'); if (before.sessions.some(session => ['running', 'awaiting_approval', 'stopping'].includes(session.status))) throw new Error('Wait for existing tasks and approvals before upgrading.'); let protocol, socket, enabledHere = false, paused = false; const breakpoints = []; diff --git a/scripts/verify-all-ui.mjs b/scripts/verify-all-ui.mjs index 6a72a3ce..45a0383d 100644 --- a/scripts/verify-all-ui.mjs +++ b/scripts/verify-all-ui.mjs @@ -7,21 +7,23 @@ import { gitEnvironment } from '../src/core/git-process.mjs'; import { randomUUID } from 'node:crypto'; const version = JSON.parse(fs.readFileSync('package.json', 'utf8')).version; -assert.ok(['1.6.0', '1.6.1', '1.6.2', '1.7.0', '1.8.0', '1.9.0', '1.10.0', '1.10.1', '1.11.0', '1.12.0'].includes(version), 'Review evidence paths when introducing the next release.'); +assert.ok(['1.6.0', '1.6.1', '1.6.2', '1.7.0', '1.8.0', '1.9.0', '1.10.0', '1.10.1', '1.11.0', '1.12.0', '1.12.1'].includes(version), 'Review evidence paths when introducing the next release.'); const prefix = releaseEvidencePrefix(version), resultFile = `.qa/${prefix}-all-ui-validation.json`, results = []; +const qaEnvironment = process.env.AGENT_WORKBENCH_TEST_PYTHON ? { AGENT_WORKBENCH_TEST_PYTHON: process.env.AGENT_WORKBENCH_TEST_PYTHON } : {}; +if (qaEnvironment.AGENT_WORKBENCH_TEST_PYTHON) assert.ok(path.isAbsolute(qaEnvironment.AGENT_WORKBENCH_TEST_PYTHON) && fs.existsSync(qaEnvironment.AGENT_WORKBENCH_TEST_PYTHON), 'Use an existing absolute QA Python interpreter.'); const cases = [ - ...(['1.11.0', '1.12.0'].includes(version) ? [['verify-task-plans-ui.mjs', `docs/${prefix}-task-ui-validation.json`]] : []), - ...(['1.10.0', '1.10.1', '1.11.0', '1.12.0'].includes(version) ? [['verify-browser-ui.mjs', `docs/${prefix}-browser-ui-validation.json`]] : []), + ...(['1.11.0', '1.12.0', '1.12.1'].includes(version) ? [['verify-task-plans-ui.mjs', `docs/${prefix}-task-ui-validation.json`]] : []), + ...(['1.10.0', '1.10.1', '1.11.0', '1.12.0', '1.12.1'].includes(version) ? [['verify-browser-ui.mjs', `docs/${prefix}-browser-ui-validation.json`]] : []), ['verify-ui.mjs', '.qa/ui-validation.json'], ['verify-diagnostics-ui.mjs', '.qa/diagnostics-ui-validation.json'], ['verify-execution-ui.mjs', '.qa/execution-ui-validation.json'], ['verify-delivery-ui.mjs', '.qa/delivery-ui-validation.json'], ['verify-index-ui.mjs', '.qa/index-ui-result.json'], ['verify-change-sets-ui.mjs', `docs/${prefix}-batch-ui-validation.json`], ['verify-context-ui.mjs', `.qa/${version === '1.6.0' ? 'workspaces-context' : prefix}-ui-validation.json`], ['verify-workspaces-ui.mjs', `docs/${prefix === 'workspaces' ? prefix : prefix + '-workspaces'}-ui-validation.json`], - ...(['1.7.0', '1.8.0', '1.9.0', '1.10.0', '1.10.1', '1.11.0', '1.12.0'].includes(version) ? [['verify-python-ui.mjs', `docs/${prefix}-python-ui-validation.json`]] : []), - ...(['1.7.0', '1.8.0', '1.9.0', '1.10.0', '1.10.1', '1.11.0', '1.12.0'].includes(version) ? [['verify-react-delivery.mjs', version === '1.7.0' ? 'docs/react-engine-delivery-validation.json' : `docs/${prefix}-react-delivery-validation.json`]] : []), - ...(['1.8.0', '1.9.0', '1.10.0', '1.10.1', '1.11.0', '1.12.0'].includes(version) ? [['verify-research-ui.mjs', `docs/${prefix}-research-ui-validation.json`]] : []), - ...(['1.9.0', '1.10.0', '1.10.1', '1.11.0', '1.12.0'].includes(version) ? [['verify-engines-ui.mjs', version === '1.9.0' ? 'docs/engines-ui-validation.json' : `docs/${prefix}-engines-ui-validation.json`]] : []), - ...(version === '1.12.0' ? ['model-center', 'project-memory', 'task-checkpoints', 'skills', 'mcp', 'mcp-recovery'].map(name => [`verify-${name}-ui.mjs`, null]) : []), + ...(['1.7.0', '1.8.0', '1.9.0', '1.10.0', '1.10.1', '1.11.0', '1.12.0', '1.12.1'].includes(version) ? [['verify-python-ui.mjs', `docs/${prefix}-python-ui-validation.json`]] : []), + ...(['1.7.0', '1.8.0', '1.9.0', '1.10.0', '1.10.1', '1.11.0', '1.12.0', '1.12.1'].includes(version) ? [['verify-react-delivery.mjs', version === '1.7.0' ? 'docs/react-engine-delivery-validation.json' : `docs/${prefix}-react-delivery-validation.json`]] : []), + ...(['1.8.0', '1.9.0', '1.10.0', '1.10.1', '1.11.0', '1.12.0', '1.12.1'].includes(version) ? [['verify-research-ui.mjs', `docs/${prefix}-research-ui-validation.json`]] : []), + ...(['1.9.0', '1.10.0', '1.10.1', '1.11.0', '1.12.0', '1.12.1'].includes(version) ? [['verify-engines-ui.mjs', version === '1.9.0' ? 'docs/engines-ui-validation.json' : `docs/${prefix}-engines-ui-validation.json`]] : []), + ...(['1.12.0', '1.12.1'].includes(version) ? ['model-center', 'project-memory', 'task-checkpoints', 'skills', 'mcp', 'mcp-recovery'].map(name => [`verify-${name}-ui.mjs`, null]) : []), ]; fs.mkdirSync('.qa', { recursive: true }); const externalHost = new Set(['verify-ui.mjs', 'verify-diagnostics-ui.mjs', 'verify-execution-ui.mjs', 'verify-index-ui.mjs']); @@ -53,7 +55,7 @@ for (const [script, fixedProof] of cases) { try { if (externalHost.has(script)) host = await startHost(script); const output = await new Promise((resolve, reject) => { - const child = spawn(process.execPath, [path.join('scripts', script)], { cwd: process.cwd(), env: { ...gitEnvironment(), ...(host ? { AGENT_WORKBENCH_URL: host.url } : {}) }, windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] }); + const child = spawn(process.execPath, [path.join('scripts', script)], { cwd: process.cwd(), env: { ...gitEnvironment(), ...qaEnvironment, ...(host ? { AGENT_WORKBENCH_URL: host.url } : {}) }, windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] }); let tail = ''; const capture = bytes => { stream.write(bytes); tail = (tail + bytes.toString('utf8')).slice(-10000); }; child.stdout.on('data', capture); child.stderr.on('data', capture); let timedOut = false; diff --git a/scripts/verify-archives.py b/scripts/verify-archives.py index 160fa865..8aaf83c1 100644 --- a/scripts/verify-archives.py +++ b/scripts/verify-archives.py @@ -8,6 +8,12 @@ import sys import uuid import zipfile +if '--help' in sys.argv: + print('python scripts/verify-archives.py [--extract-source] - verify current immutable ZIPs; AGENT_WORKBENCH_ARCHIVE_QA_ROOT selects the extraction root.') + sys.exit(0) +if any(value != '--extract-source' for value in sys.argv[1:]): + raise SystemExit('Unsupported argument; use --help.') + workspace = Path(__file__).resolve().parent.parent release_dir = (workspace / 'releases').resolve() release = json.loads((release_dir / 'latest.json').read_text(encoding='utf-8')) diff --git a/scripts/verify-change-sets-ui.mjs b/scripts/verify-change-sets-ui.mjs index 45771d70..6165520f 100644 --- a/scripts/verify-change-sets-ui.mjs +++ b/scripts/verify-change-sets-ui.mjs @@ -34,7 +34,7 @@ child.stdout.on('data', value => { output += value; for (const line of output.sp child.stderr.on('data', value => { errors += value; }); const wait = async predicate => { const deadline = Date.now() + 15000; while (!await predicate()) { if (Date.now() > deadline) throw new Error('UI fixture timed out: ' + errors); await new Promise(resolve => setTimeout(resolve, 40)); } }; await wait(() => url); const bootstrap = await (await fetch(url + '/api/bootstrap')).json(); -assert.ok(['1.4.0', '1.5.0', '1.5.1', '1.6.0', '1.6.1', '1.6.2', '1.7.0', '1.8.0', '1.9.0', '1.10.0', '1.10.1', '1.11.0', '1.12.0'].includes(bootstrap.version)); assert.equal(bootstrap.config.mode, 'demo'); assert.equal(bootstrap.config.hasKey, false); +assert.ok(['1.4.0', '1.5.0', '1.5.1', '1.6.0', '1.6.1', '1.6.2', '1.7.0', '1.8.0', '1.9.0', '1.10.0', '1.10.1', '1.11.0', '1.12.0', '1.12.1'].includes(bootstrap.version)); assert.equal(bootstrap.config.mode, 'demo'); assert.equal(bootstrap.config.hasKey, false); const proofPrefix = releaseEvidencePrefix(bootstrap.version) + '-batch'; const screenshotPrefix = bootstrap.version === '1.4.0' ? '1.4-batch' : proofPrefix; 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' }, diff --git a/scripts/verify-context-ui.mjs b/scripts/verify-context-ui.mjs index 369f346f..041c854e 100644 --- a/scripts/verify-context-ui.mjs +++ b/scripts/verify-context-ui.mjs @@ -77,7 +77,7 @@ child.stderr.on('data', bytes => { errors += bytes.toString('utf8'); }); const until = async predicate => { const deadline = Date.now() + 20000; while (!await predicate()) { if (Date.now() > deadline) throw new Error('Context UI fixture timeout: ' + errors); await new Promise(resolve => setTimeout(resolve, 40)); } }; await until(() => url || child.exitCode !== null); assert.ok(url, errors); const bootstrap = await (await fetch(url + '/api/bootstrap', { headers: { Connection: 'close' } })).json(); -assert.ok(['1.5.0', '1.5.1', '1.6.0', '1.6.1', '1.6.2', '1.7.0', '1.8.0', '1.9.0', '1.10.0', '1.10.1', '1.11.0', '1.12.0'].includes(bootstrap.version)); assert.equal(bootstrap.config.mode, 'demo'); assert.equal(bootstrap.config.hasKey, false); +assert.ok(['1.5.0', '1.5.1', '1.6.0', '1.6.1', '1.6.2', '1.7.0', '1.8.0', '1.9.0', '1.10.0', '1.10.1', '1.11.0', '1.12.0', '1.12.1'].includes(bootstrap.version)); assert.equal(bootstrap.config.mode, 'demo'); assert.equal(bootstrap.config.hasKey, false); const api = async route => { const response = await fetch(url + '/api' + route, { headers: { 'X-Workbench-Token': bootstrap.token, Connection: 'close' } }); const value = await response.json(); assert.ok(response.ok, value.error); return value; }; const proofPrefix = bootstrap.version === '1.6.0' ? 'workspaces-context' : releaseEvidencePrefix(bootstrap.version); const browser = await chromium.launch({ channel: 'msedge', headless: true }), page = await browser.newPage({ viewport: { width: 1440, height: 1000 } }); diff --git a/scripts/verify-release.mjs b/scripts/verify-release.mjs index ac3b5b6a..1ea27b19 100644 --- a/scripts/verify-release.mjs +++ b/scripts/verify-release.mjs @@ -7,6 +7,9 @@ import net from 'node:net'; import { createResearchSamples } from './research-fixtures.mjs'; import { verifyBrowserApi } from './verify-browser.mjs'; +if (process.argv.includes('--help')) { console.log('node scripts/verify-release.mjs [--native-engines] - validate the latest immutable portable release in an isolated host.'); process.exit(0); } +if (process.argv.slice(2).some(value => value !== '--native-engines')) throw new Error('Unsupported argument; use --help.'); + const release = JSON.parse(fs.readFileSync('releases/latest.json', 'utf8')); const appRoot = release.portableRoot; const manifest = JSON.parse(fs.readFileSync(path.join(appRoot, 'MANIFEST.json'), 'utf8')); @@ -92,7 +95,7 @@ try { const checkLog = await api('/artifacts/' + checked.results[0].logArtifactId + '?session=' + session.id); assert.match(checkLog.content, /tests 4/); assert.ok(fs.existsSync(path.join(appRoot, 'runtime/node_modules/npm/bin/npm-cli.js'))); const actualRea = []; - if (['1.8.0', '1.9.0', '1.10.0', '1.10.1', '1.11.0', '1.12.0'].includes(manifest.version)) { + if (['1.8.0', '1.9.0', '1.10.0', '1.10.1', '1.11.0', '1.12.0', '1.12.1'].includes(manifest.version)) { const installation = await api('/research/availability'); assert.equal(installation.status, 'available'); assert.equal(installation.version, '6.8.0'); assert.equal(fs.realpathSync.native(installation.packageRoot), fs.realpathSync.native(path.join(appRoot, 'runtime/node_modules/rea-agents'))); assert.equal(fs.realpathSync.native(installation.node.path), fs.realpathSync.native(path.join(appRoot, 'runtime/node.exe'))); @@ -124,7 +127,7 @@ try { console.log('PASS actual contained REA: ASAR, PE imports and PE resources; zero target execution/model requests'); } let actualEngine = null; - if (['1.9.0', '1.10.0', '1.10.1', '1.11.0', '1.12.0'].includes(manifest.version) && process.argv.includes('--native-engines')) { + if (['1.9.0', '1.10.0', '1.10.1', '1.11.0', '1.12.0', '1.12.1'].includes(manifest.version) && process.argv.includes('--native-engines')) { const installation = await api('/engines/deepseek/availability'); assert.equal(installation.status, 'available', installation.message); assert.equal(fs.realpathSync.native(installation.node.path), fs.realpathSync.native(path.join(appRoot, 'runtime/node.exe'))); const engineRoot = path.join(data, 'engine-project'); fs.mkdirSync(engineRoot); fs.writeFileSync(path.join(engineRoot, 'README.md'), '# Owned portable engine connection\n'); @@ -144,7 +147,7 @@ try { assert.equal((await api('/research')).length, 4); const page = await fetch(url); assert.equal(page.status, 200); assert.match(await page.text(), /Agent Workbench/); - const actualBrowser = ['1.10.0', '1.10.1', '1.11.0', '1.12.0'].includes(manifest.version) ? await verifyBrowserApi({ api, url, token: bootstrap.token, directory: data, appRoot, contained: true }) : null; + const actualBrowser = ['1.10.0', '1.10.1', '1.11.0', '1.12.0', '1.12.1'].includes(manifest.version) ? await verifyBrowserApi({ api, url, token: bootstrap.token, directory: data, appRoot, contained: true }) : null; console.log((await stop()).trim()); started = false; await until(async () => { try { await fetch(url + '/api/health'); return false; } catch { return true; } }); const result = { success: true, date: new Date().toISOString(), appRoot, version: manifest.version, nodeVersion: manifest.nodeVersion, diff --git a/scripts/verify-source-package.mjs b/scripts/verify-source-package.mjs index 78ac2d0e..18b90302 100644 --- a/scripts/verify-source-package.mjs +++ b/scripts/verify-source-package.mjs @@ -4,6 +4,9 @@ import assert from 'node:assert/strict'; import { createHash, randomUUID } from 'node:crypto'; import { spawn, execFileSync } from 'node:child_process'; +if (process.argv.includes('--help')) { console.log('node scripts/verify-source-package.mjs [--native-engines] - validate independently extracted source after verify-archives.py --extract-source; set the absolute QA Python and archive root.'); process.exit(0); } +if (process.argv.slice(2).some(value => value !== '--native-engines')) throw new Error('Unsupported argument; use --help.'); + const workspace = process.cwd(); const evidence = JSON.parse(fs.readFileSync('.qa/archives-validation.json', 'utf8')); assert.equal(evidence.success, true); @@ -79,7 +82,7 @@ try { assert.deepEqual(actualFiles.slice().sort(), Object.keys(expected).sort()); for (const [relative, sha256] of Object.entries(expected)) assert.equal(digest(path.join(sourceRoot, relative)), sha256, relative); let actualRea = null; - if (['1.8.0', '1.9.0', '1.10.0', '1.10.1', '1.11.0', '1.12.0'].includes(evidence.version)) { + if (['1.8.0', '1.9.0', '1.10.0', '1.10.1', '1.11.0', '1.12.0', '1.12.1'].includes(evidence.version)) { stage = 'contained REA'; const reaOutput = await run(['scripts/verify-rea.mjs', '--app-root', sourceRoot, '--contained'], 'rea.log'); actualRea = JSON.parse(reaOutput.trim().split('\n').at(-1)); @@ -87,7 +90,7 @@ try { assert.ok(actualRea.results.every(item => item.rootExited === true)); } let actualEngine = null; - if (['1.9.0', '1.10.0', '1.10.1', '1.11.0', '1.12.0'].includes(evidence.version) && process.argv.includes('--native-engines')) { + if (['1.9.0', '1.10.0', '1.10.1', '1.11.0', '1.12.0', '1.12.1'].includes(evidence.version) && process.argv.includes('--native-engines')) { stage = 'native DeepSeek SDK'; const output = await run(['scripts/verify-engines.mjs'], 'engines.log'); actualEngine = JSON.parse(output.trim().split('\n').at(-1)); @@ -95,7 +98,7 @@ try { assert.equal(actualEngine.modelRequests, 0); assert.equal(actualEngine.rootExited, true); assert.equal(actualEngine.nativeMethods.length, 6); } let actualBrowser = null; - if (['1.10.0', '1.10.1', '1.11.0', '1.12.0'].includes(evidence.version)) { + if (['1.10.0', '1.10.1', '1.11.0', '1.12.0', '1.12.1'].includes(evidence.version)) { stage = 'contained browser runtime'; const output = await run(['scripts/verify-browser.mjs', '--app-root', sourceRoot, '--contained'], 'browser.log'); actualBrowser = JSON.parse(output.trim().split('\n').at(-1)); diff --git a/src/core/check-runner.mjs b/src/core/check-runner.mjs index 8037a0f2..24cfc9ad 100644 --- a/src/core/check-runner.mjs +++ b/src/core/check-runner.mjs @@ -10,6 +10,7 @@ import { assertWorkspacesResolved } from '../shared/contracts/workspaces.mjs'; import { verifyWorkspaceProject } from './workspaces/git-workspaces.mjs'; import { assertMcpResolved } from './tools/mcp-contract.mjs'; import { bindPythonChecks, preparePythonInvocation, pythonEnvironment, readPythonEvidence, pythonResultBinding } from './python-runtime.mjs'; +import { projectEnvironment } from './process-environment.mjs'; const at = () => new Date().toISOString(); const conflict = message => Object.assign(new Error(message), { status: 409 }); @@ -189,13 +190,7 @@ export class CheckRunner { try { invocation = isPython ? await preparePythonInvocation(check, project, { signal }) : npmInvocation(check.name, this.runtimeDirectory); } catch (error) { return { status: signal.aborted ? 'cancelled' : error.status === 409 ? 'stale' : 'failed', exitCode: null, durationMs: Date.now() - started, tests: null, stdout: '', stderr: error.message, reason: error.message }; } return new Promise(resolve => { - const env = isPython ? pythonEnvironment() : { ...process.env, NO_COLOR: '1', CI: '1' }; - delete env.FORCE_COLOR; - delete env.AGENT_WORKBENCH_API_KEY; - delete env.NODE_TEST_CONTEXT; - const priorPath = process.env.PATH || ''; - for (const key of Object.keys(env)) if (key.toLowerCase() === 'path') delete env[key]; - env.PATH = path.dirname(process.execPath) + path.delimiter + priorPath; + const env = isPython ? pythonEnvironment() : projectEnvironment({ NO_COLOR: '1', CI: '1' }); const child = spawn(invocation.executable, invocation.args, { cwd: safePath(project), env, windowsHide: true, detached: process.platform !== 'win32', stdio: [isPython ? 'pipe' : 'ignore', 'pipe', 'pipe'] }); const streams = { stdout: { head: '', tail: '', characters: 0, decoder: new StringDecoder('utf8') }, stderr: { head: '', tail: '', characters: 0, decoder: new StringDecoder('utf8') } }; let settled = false, timedOut = false, terminating = false, killTimer; diff --git a/src/core/models/config-import.mjs b/src/core/models/config-import.mjs index edf6e1dd..0794e3bb 100644 --- a/src/core/models/config-import.mjs +++ b/src/core/models/config-import.mjs @@ -72,23 +72,27 @@ export class ConfigImporter { if (!preview || Date.now() - preview.created > 300000) throw new Error('导入预览已过期,请重新预览。'); const current = this.read(preview.source, preview.path); if (current.fingerprint !== preview.fingerprint) { this.previews.delete(id); throw new Error('来源配置已变化,请重新预览再导入。'); } - const imported = [], conflicts = []; - const sourceId = digest({ source: preview.source, path: preview.path }); - for (const item of current.entries) { - const previous = this.hub.state.connections.find(value => value.importOrigin === item.origin); - if (previous && previous.importRevision !== previous.revision) { conflicts.push(previous.name); continue; } - const value = this.hub.upsert({ ...(previous ?? {}), ...item, id: previous?.id, revision: previous?.revision, enabled: previous ? previous.enabled : true, - ...(item.apiKey ? { apiKey: item.apiKey } : { apiKey: '' }) }); - const stored = this.hub.connection(value.id); stored.source = preview.source; stored.importOrigin = item.origin; stored.importRevision = stored.revision; - imported.push(value.id); - } - const previousSource = this.hub.state.imports[sourceId]; - const checkedAt = new Date().toISOString(); - this.hub.state.imports[sourceId] = { source: preview.source, path: preview.path, enabled: autoSync === undefined ? previousSource?.enabled === true : autoSync === true, - lastFingerprint: current.fingerprint, lastCheckedAt: checkedAt, lastSyncedAt: imported.length ? checkedAt : previousSource?.lastSyncedAt ?? null, - lastResult: { imported: imported.length, conflicts } }; - this.hub.save(); this.previews.delete(id); - return { imported, conflicts, sourceId }; + const result = this.hub.editRegistry(() => { + const imported = [], conflicts = []; + const sourceId = digest({ source: preview.source, path: preview.path }); + for (const item of current.entries) { + const previous = this.hub.state.connections.find(value => value.importOrigin === item.origin); + if (previous && previous.importRevision !== previous.revision) { conflicts.push(previous.name); continue; } + const value = this.hub.upsert({ ...(previous ?? {}), ...item, id: previous?.id, revision: previous?.revision, enabled: previous ? previous.enabled : true, + ...(item.apiKey ? { apiKey: item.apiKey } : { apiKey: '' }) }); + const stored = this.hub.connection(value.id); stored.source = preview.source; stored.importOrigin = item.origin; stored.importRevision = stored.revision; + imported.push(value.id); + } + const previousSource = this.hub.state.imports[sourceId]; + const checkedAt = new Date().toISOString(); + this.hub.state.imports[sourceId] = { source: preview.source, path: preview.path, enabled: autoSync === undefined ? previousSource?.enabled === true : autoSync === true, + lastFingerprint: current.fingerprint, lastCheckedAt: checkedAt, lastSyncedAt: imported.length ? checkedAt : previousSource?.lastSyncedAt ?? null, + lastResult: { imported: imported.length, conflicts } }; + this.hub.save(); + return { imported, conflicts, sourceId }; + }); + this.previews.delete(id); + return result; } toggle(id, enabled) { const source = this.hub.state.imports[id]; if (!source) throw new Error('导入来源不存在。'); @@ -104,7 +108,7 @@ export class ConfigImporter { if (read.fingerprint === source.lastFingerprint) { this.hub.save(); continue; } const preview = this.preview(source.source, source.path); reports.push(this.apply(preview.id, true)); - } catch (cause) { source.lastError = '来源暂不可读取或格式变化,请重新预览核对。'; source.lastCheckedAt = new Date().toISOString(); this.hub.save(); reports.push({ id, error: source.lastError }); } + } catch (cause) { const current = this.hub.state.imports[id]; current.lastError = '来源暂不可读取或格式变化,请重新预览核对。'; current.lastCheckedAt = new Date().toISOString(); this.hub.save(); reports.push({ id, error: current.lastError }); } } return reports; } diff --git a/src/core/models/model-hub.mjs b/src/core/models/model-hub.mjs index 2519b38b..20da90de 100644 --- a/src/core/models/model-hub.mjs +++ b/src/core/models/model-hub.mjs @@ -26,7 +26,40 @@ export class ModelHub { if (recovered) this.saveAttempts(); provider.credentials ??= new Map(); } - save() { this.state.revision++; this.store.storage.transaction(() => this.store.storage.setMeta('modelRegistry', this.state)); } + save(config = null) { + this.state.revision++; + if (this.editingRegistry) { + if (config) throw error('批量连接导入不能修改当前运行模式。'); + return; + } + const persist = () => this.store.storage.setMeta('modelRegistry', this.state); + try { + if (config) this.store.saveConfig(config, { beforeSave: persist }); + else this.store.storage.transaction(persist); + } catch (cause) { + // Keep runtime routing consistent with the authoritative committed state. + this.state = this.store.storage.meta('modelRegistry', { schema: 1, revision: 0, + selected: { type: 'legacy', id: legacyId }, connections: [], pools: [], imports: {} }); + throw cause; + } + } + editRegistry(action) { + if (this.editingRegistry) return action(); + const before = structuredClone(this.state), credentials = new Map(this.provider.credentials); + this.editingRegistry = true; + try { + return this.store.storage.transaction(() => { + const result = action(); + this.store.storage.setMeta('modelRegistry', this.state); + return result; + }); + } catch (cause) { + this.state = before; + this.provider.credentials.clear(); + for (const [id, value] of credentials) this.provider.credentials.set(id, value); + throw cause; + } finally { this.editingRegistry = false; } + } saveAttempts() { this.attempts = this.attempts.slice(-1000); this.store.storage.transaction(() => this.store.storage.setMeta('modelAttempts', this.attempts)); } connections() { return [{ id: legacyId, name: '原模型连接', brand: '兼容服务', protocol: 'chat-completions', baseUrl: this.store.config.baseUrl, @@ -90,16 +123,14 @@ export class ModelHub { maxAttempts: bounded(input.maxAttempts, 3, 1, 8), queueTimeoutMs: bounded(input.queueTimeoutMs, 15000, 100, 60000), revision: (previous?.revision ?? 0) + 1 }; this.state.pools = [...this.state.pools.filter(item => item.id !== value.id), value]; this.save(); return value; } - select(input) { + select(input, config = null) { if (input.type === 'connection') this.connection(input.id); else if (input.type === 'pool') { if (!this.state.pools.some(item => item.id === input.id)) throw error('模型池不存在。'); } else if (input.type !== 'legacy') throw error('模型选择无效。'); - this.state.selected = { type: input.type, id: input.type === 'legacy' ? legacyId : input.id }; this.save(); - if (input.type !== 'legacy') { - // Keep the original endpoint/key pair intact. Only a Run's immutable - // routing snapshot receives the selected member's endpoint and model. - this.store.saveConfig({ mode: 'compatible' }); - } + this.state.selected = { type: input.type, id: input.type === 'legacy' ? legacyId : input.id }; + // Selection and mode must commit together; the original endpoint/key pair + // stays intact and a Run alone receives its immutable routing snapshot. + this.save(config ?? (input.type !== 'legacy' ? { mode: 'compatible' } : null)); return this.view(); } prepare(config) { diff --git a/src/core/process-environment.mjs b/src/core/process-environment.mjs new file mode 100644 index 00000000..d6d961f9 --- /dev/null +++ b/src/core/process-environment.mjs @@ -0,0 +1,11 @@ +import path from 'node:path'; + +// Project commands receive system/runtime paths, never arbitrary host settings +// or provider credentials. Additional fields are explicit internal policy. +export function projectEnvironment(extra = {}) { + const allowed = /^(path|pathext|systemroot|systemdrive|windir|comspec|temp|tmp|userprofile|homedrive|homepath|home|appdata|localappdata|programfiles(?:\(x86\))?|commonprogramfiles(?:\(x86\))?|lang|lc_all)$/i; + const environment = Object.fromEntries(Object.entries(process.env).filter(([name]) => allowed.test(name))); + const inheritedPath = Object.entries(environment).find(([name]) => name.toLowerCase() === 'path')?.[1] || ''; + for (const name of Object.keys(environment)) if (name.toLowerCase() === 'path') delete environment[name]; + return { ...environment, PATH: [path.dirname(process.execPath), inheritedPath].filter(Boolean).join(path.delimiter), ...extra }; +} diff --git a/src/core/python-runtime.mjs b/src/core/python-runtime.mjs index 4045f4f2..f37a709e 100644 --- a/src/core/python-runtime.mjs +++ b/src/core/python-runtime.mjs @@ -4,6 +4,7 @@ import os from 'node:os'; import { createHash, randomUUID } from 'node:crypto'; import { execFile } from 'node:child_process'; import { promisify } from 'node:util'; +import { projectEnvironment } from './process-environment.mjs'; const executeFile = promisify(execFile); const digest = bytes => createHash('sha256').update(bytes).digest('hex'); @@ -15,9 +16,7 @@ const fileIdentity = file => { return { path: resolved, sha256: digest(fs.readFileSync(resolved)) }; }; export function pythonEnvironment() { - const environment = { ...process.env, NO_COLOR: '1', CI: '1', PYTEST_DISABLE_PLUGIN_AUTOLOAD: '1', PYTHONDONTWRITEBYTECODE: '1' }; - for (const key of ['AGENT_WORKBENCH_API_KEY', 'NODE_TEST_CONTEXT', 'PYTEST_ADDOPTS', 'PYTEST_PLUGINS', 'PYTHONPATH', 'PYTHONHOME', 'PYTHONSTARTUP', 'FORCE_COLOR']) delete environment[key]; - return environment; + return projectEnvironment({ NO_COLOR: '1', CI: '1', PYTEST_DISABLE_PLUGIN_AUTOLOAD: '1', PYTHONDONTWRITEBYTECODE: '1' }); } function configurationFor(executable) { for (const file of [path.join(path.dirname(executable), 'pyvenv.cfg'), path.join(path.dirname(executable), '..', 'pyvenv.cfg')]) { diff --git a/src/server/app.mjs b/src/server/app.mjs index 1164ed67..9be44d02 100644 --- a/src/server/app.mjs +++ b/src/server/app.mjs @@ -67,6 +67,11 @@ function allowRequest(request, url) { } return async (request, response) => { try { + response.setHeader('Referrer-Policy', 'no-referrer'); + response.setHeader('X-Frame-Options', 'DENY'); + // Scripts and API requests belong to this workbench origin. Inline styles + // are limited to the existing React layout; model text never becomes HTML. + response.setHeader('Content-Security-Policy', "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; connect-src 'self'; object-src 'none'; base-uri 'none'; frame-ancestors 'none'; form-action 'self'"); const actualPort = getPort(); if (server && (!server.listening || server.address().port !== actualPort)) throw new Error('本地执行宿主已经变化,请重新连接工作台。'); const url = new URL(request.url, 'http://127.0.0.1:' + actualPort); @@ -562,9 +567,10 @@ return async (request, response) => { maxTaskTokens: Math.trunc(Math.max(1000, Math.min(10000000, Number(input.maxTaskTokens) || store.config.maxTaskTokens))), }; provider.validate(config); + if (Object.hasOwn(input, 'apiKey') && (typeof input.apiKey !== 'string' || input.apiKey.length > 16000)) throw new Error('模型凭据格式无效。'); + if (provider.hub) provider.hub.select({ type: 'legacy' }, config); + else store.saveConfig(config); if (Object.hasOwn(input, 'apiKey')) provider.setKey(input.apiKey); - if (provider.hub) provider.hub.select({ type: 'legacy' }); - store.saveConfig(config); return json(response, { ...store.config, hasKey: provider.hasKey() }); } if (method === 'POST' && route === '/api/config/models') { diff --git a/src/server/diagnostics.mjs b/src/server/diagnostics.mjs index 04e6c976..92e1ddac 100644 --- a/src/server/diagnostics.mjs +++ b/src/server/diagnostics.mjs @@ -1,6 +1,6 @@ import { randomUUID, createHash } from 'node:crypto'; -export const APP_VERSION = '1.12.0'; +export const APP_VERSION = '1.12.1'; export function executionEnvironment() { const windows = process.platform === 'win32'; diff --git a/src/server/hot-upgrade.mjs b/src/server/hot-upgrade.mjs index f1ce66b9..47c78c72 100644 --- a/src/server/hot-upgrade.mjs +++ b/src/server/hot-upgrade.mjs @@ -4,6 +4,8 @@ import { Provider } from './provider.mjs'; import { Runtime } from './runtime.mjs'; import { Store, atomicJson, readJson } from './store.mjs'; import { ArtifactStore } from '../core/storage/artifact-store.mjs'; +import { ModelHub } from '../core/models/model-hub.mjs'; +import { ConfigImporter } from '../core/models/config-import.mjs'; import { createRequestHandler, createSessionPublisher } from './app.mjs'; import { APP_VERSION } from './diagnostics.mjs'; @@ -13,10 +15,13 @@ export function installUpgrade(context, { appDirectory, updateServiceInfo = true const { server, store, provider, runtime, token, clients, started, exampleProject, shutdown } = context; if (!server?.listening || !store || !provider || !runtime || !clients || !token) throw new Error('The existing Workbench context is incomplete.'); if (runtime.active.size || runtime.waiters.size || runtime.checks?.active.size || runtime.deliveries?.active.size || runtime.changeSets?.projects.size || runtime.workspaces?.projects.size || runtime.workspaces?.pending.size || runtime.research?.active.size || runtime.engines?.active.size || runtime.browser?.active.size || runtime.taskPlans?.active.size) throw new Error('Wait for active tasks, checks, Git deliveries, file batches, workspaces, research, engines, browsers, task plans and approvals to finish before upgrading.'); + if (provider.activeRequests || provider.hub?.waiting || [...(provider.hub?.leases.values() ?? [])].some(count => count > 0)) throw new Error('Wait for active model requests and probes before upgrading.'); const root = fs.realpathSync.native(path.resolve(appDirectory)); if (!fs.existsSync(path.join(root, 'dist-client', 'index.html'))) throw new Error('The new client bundle is missing.'); const oldHandlers = server.listeners('request'); const oldPrototypes = [Object.getPrototypeOf(store), Object.getPrototypeOf(provider), Object.getPrototypeOf(runtime)]; + const oldModelPrototypes = { hub: provider.hub ? Object.getPrototypeOf(provider.hub) : null, + importer: provider.hub?.importer ? Object.getPrototypeOf(provider.hub.importer) : null }; const oldStoreProperties = { ...store }; const oldRuntimeProperties = { appDirectory: runtime.appDirectory, checks: runtime.checks, deliveries: runtime.deliveries, codeIndex: runtime.codeIndex, changeSets: runtime.changeSets, contextPlans: runtime.contextPlans, workspaces: runtime.workspaces, research: runtime.research, engines: runtime.engines, browser: runtime.browser, taskPlans: runtime.taskPlans, projectMemories: runtime.projectMemories, taskCheckpoints: runtime.taskCheckpoints, skills: runtime.skills, mcp: runtime.mcp }; const oldUpdates = store.listeners('update'); @@ -28,6 +33,10 @@ export function installUpgrade(context, { appDirectory, updateServiceInfo = true Object.setPrototypeOf(store, Store.prototype); Object.setPrototypeOf(provider, Provider.prototype); Object.setPrototypeOf(runtime, Runtime.prototype); + if (provider.hub) { + Object.setPrototypeOf(provider.hub, ModelHub.prototype); + if (provider.hub.importer) Object.setPrototypeOf(provider.hub.importer, ConfigImporter.prototype); + } runtime.appDirectory = root; runtime.checks = null; runtime.deliveries = null; runtime.codeIndex = null; runtime.changeSets = null; runtime.contextPlans = null; runtime.workspaces = null; runtime.research = null; runtime.engines = null; runtime.browser = null; runtime.taskPlans = null; runtime.projectMemories = null; runtime.taskCheckpoints = null; runtime.skills = null; runtime.mcp = null; store.ensureStorage(); // A SQLite host can retain an artifact object from an earlier bundle. @@ -56,6 +65,8 @@ export function installUpgrade(context, { appDirectory, updateServiceInfo = true Object.assign(store, oldStoreProperties); Object.assign(runtime, oldRuntimeProperties); Object.setPrototypeOf(store, oldPrototypes[0]); Object.setPrototypeOf(provider, oldPrototypes[1]); Object.setPrototypeOf(runtime, oldPrototypes[2]); + if (oldModelPrototypes.hub) Object.setPrototypeOf(provider.hub, oldModelPrototypes.hub); + if (oldModelPrototypes.importer) Object.setPrototypeOf(provider.hub.importer, oldModelPrototypes.importer); store.removeAllListeners('update'); for (const observer of oldUpdates) store.on('update', observer); server.removeAllListeners('request'); for (const previous of oldHandlers) server.on('request', previous); throw error; diff --git a/src/server/provider.mjs b/src/server/provider.mjs index ddc34397..e887c01c 100644 --- a/src/server/provider.mjs +++ b/src/server/provider.mjs @@ -119,6 +119,7 @@ export class Provider { const deadline = Date.now() + policy.totalTimeoutMs; const startedAt = Date.now(); let attempts = 0; + this.activeRequests = (this.activeRequests ?? 0) + 1; try { for (let attempt = 1; attempt <= policy.attempts; attempt++) { signal?.throwIfAborted(); @@ -166,6 +167,7 @@ export class Provider { } throw new Error('模型请求未能完成。'); } finally { + this.activeRequests--; if (signal?.aborted) this.lastRequest = { source: 'model_connection', stage: 'model_request', endpoint: base, route, model: config.model, status: 'interrupted', attempts, durationMs: Date.now() - startedAt, occurredAt: new Date().toISOString() }; diff --git a/src/server/runtime.mjs b/src/server/runtime.mjs index b5fd5c01..4d95b7f4 100644 --- a/src/server/runtime.mjs +++ b/src/server/runtime.mjs @@ -10,6 +10,7 @@ import { executionEnvironment, sessionContext, sessionSnapshot } from './diagnos import { BudgetExceeded, checkBudget } from '../shared/contracts/execution.mjs'; import { CheckRunner } from '../core/check-runner.mjs'; import { inspectProject } from '../core/project-inspector.mjs'; +import { projectEnvironment } from '../core/process-environment.mjs'; import { GitDelivery } from '../core/git-delivery.mjs'; import { ProjectIndex } from '../core/context/project-index.mjs'; import { RequestPlanner, verifyPlanEvidence } from '../core/context/request-plan.mjs'; @@ -101,7 +102,7 @@ export class Runtime { this.active = new Map(); this.waiters = new Map(); } isActive(id) { return this.active.has(id) || !!this.checks?.isActive(id) || !!this.deliveries?.isActive(id) || !!this.changeSets?.isActive(id) || !!this.workspaces?.isActive(id) || !!this.research?.isActive(id) || !!this.engines?.isActive(id) || !!this.browser?.isActive(id) || !!this.taskPlans?.isActive(id); } - hasActivity() { return this.active.size > 0 || (this.checks?.active.size ?? 0) > 0 || (this.deliveries?.active.size ?? 0) > 0 || (this.changeSets?.projects.size ?? 0) > 0 || (this.workspaces?.projects.size ?? 0) > 0 || (this.workspaces?.pending.size ?? 0) > 0 || (this.research?.active.size ?? 0) > 0 || (this.engines?.active.size ?? 0) > 0 || (this.browser?.active.size ?? 0) > 0 || (this.taskPlans?.active.size ?? 0) > 0; } + hasActivity() { return (this.provider.activeRequests ?? 0) > 0 || (this.provider.hub?.waiting ?? 0) > 0 || this.active.size > 0 || (this.checks?.active.size ?? 0) > 0 || (this.deliveries?.active.size ?? 0) > 0 || (this.changeSets?.projects.size ?? 0) > 0 || (this.workspaces?.projects.size ?? 0) > 0 || (this.workspaces?.pending.size ?? 0) > 0 || (this.research?.active.size ?? 0) > 0 || (this.engines?.active.size ?? 0) > 0 || (this.browser?.active.size ?? 0) > 0 || (this.taskPlans?.active.size ?? 0) > 0; } projectIndexer() { return this.codeIndex ??= new ProjectIndex(); } taskPlanner() { return this.taskPlans ??= new TaskPlanManager(this.store, { redact: value => this.provider.redact(value), projectBusy: (projectId, exceptId) => this.projectHasActivity(projectId, exceptId) }); } @@ -557,11 +558,7 @@ export class Runtime { const executable = windows ? path.join(process.env.SystemRoot || 'C:\\Windows', 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe') : '/bin/sh'; const bootstrap = "$workbenchUtf8 = [Text.UTF8Encoding]::new($false)\n[Console]::InputEncoding = $workbenchUtf8\n[Console]::OutputEncoding = $workbenchUtf8\n$OutputEncoding = $workbenchUtf8\n$workbenchCode = [Console]::In.ReadToEnd()\ntry {\n & ([scriptblock]::Create($workbenchCode))\n $workbenchSucceeded = $?\n if ($null -ne $LASTEXITCODE -and $LASTEXITCODE -ne 0) { exit $LASTEXITCODE }\n if (-not $workbenchSucceeded) { exit 1 }\n} catch { [Console]::Error.WriteLine($_.Exception.Message); [Console]::Error.WriteLine($_.FullyQualifiedErrorId); exit 1 }"; const argumentsList = windows ? ['-NoProfile', '-NonInteractive', '-EncodedCommand', Buffer.from(bootstrap, 'utf16le').toString('base64')] : ['-c', command]; - const childEnv = { ...process.env }; - const priorPath = process.env.PATH || ''; - for (const key of Object.keys(childEnv)) if (key.toLowerCase() === 'path') delete childEnv[key]; - childEnv.PATH = path.dirname(process.execPath) + path.delimiter + priorPath; - delete childEnv.AGENT_WORKBENCH_API_KEY; + const childEnv = projectEnvironment(); const child = spawn(executable, argumentsList, { cwd, windowsHide: true, stdio: [windows ? 'pipe' : 'ignore', 'pipe', 'pipe'], env: childEnv }); if (windows) { child.stdin.on('error', () => {}); child.stdin.end(command, 'utf8'); } const decoders = { stdout: new StringDecoder('utf8'), stderr: new StringDecoder('utf8') }; diff --git a/src/server/store.mjs b/src/server/store.mjs index cbc0daee..413b049f 100644 --- a/src/server/store.mjs +++ b/src/server/store.mjs @@ -318,9 +318,9 @@ export class Store extends EventEmitter { return session; } - saveConfig(config) { + saveConfig(config, { beforeSave } = {}) { const next = cleanConfig({ ...this.config, ...config, configRevision: (this.config.configRevision ?? 0) + 1 }); - this.storage.transaction(() => this.storage.setMeta('config', next)); + this.storage.transaction(() => { beforeSave?.(); this.storage.setMeta('config', next); }); this.config = next; // A compatibility export for old launchers; SQLite is authoritative after migration. try { atomicJson(path.join(this.directory, 'config.json'), this.config); } catch { this.publicationNotice = '配置已保存,兼容JSON导出未更新。'; } diff --git a/tests/api.test.mjs b/tests/api.test.mjs index 70f699f8..28e156fb 100644 --- a/tests/api.test.mjs +++ b/tests/api.test.mjs @@ -17,9 +17,28 @@ test('the bundled local service enforces host, origin, token and JSON object con await assert.rejects(server.api('/sessions', null), { status: 400 }); assert.equal(server.bootstrap.capabilities.commands, 'per-call-approval'); const page = await fetch(server.url); assert.equal(page.status, 200); assert.match(await page.text(), /Agent Workbench/); + assert.equal(page.headers.get('x-frame-options'), 'DENY'); + assert.equal(page.headers.get('referrer-policy'), 'no-referrer'); + assert.match(page.headers.get('content-security-policy'), /script-src 'self'/); + assert.match(page.headers.get('content-security-policy'), /frame-ancestors 'none'/); await server.close(); }); +test('an in-flight connection probe prevents configuration changes and another probe until its actual result returns', async t => { + const f = fixture(t), host = await launchWorkbench(t, f.data); f.onCleanup(host.close); + let release; + const model = await compatibleFixture(t, async () => { await new Promise(resolve => { release = resolve; }); return { choices: [{ message: { role: 'assistant', content: 'OK' } }] }; }); + await host.api('/config', { mode: 'compatible', model: 'owned-probe-model', baseUrl: model.baseUrl, apiKey: 'owned-probe-fixture' }); + const probing = host.api('/config/test', {}); + await until(() => !!release); + await assert.rejects(host.api('/config', { mode: 'demo' }), { status: 409 }); + await assert.rejects(host.api('/config/test', {}), { status: 409 }); + await assert.rejects(host.api('/model-center/connections', { name: 'Blocked', model: 'owned-model', baseUrl: model.baseUrl }), { status: 409 }); + assert.equal(model.requests.length, 1); assert.equal((await host.api('/bootstrap')).config.model, 'owned-probe-model'); + release(); assert.equal((await probing).ok, true); + assert.equal((await host.api('/config', { mode: 'demo', model: 'owned-probe-model', baseUrl: model.baseUrl })).mode, 'demo'); +}); + test('API review applies verified content, detects conflicts, exports sessions and keeps keys in memory', async t => { const f = fixture(t), server = await launchWorkbench(t, f.data); f.onCleanup(server.close); const project = await server.api('/projects', { root: f.projectRoot }); diff --git a/tests/config-transaction-api.test.mjs b/tests/config-transaction-api.test.mjs new file mode 100644 index 00000000..af4293c9 --- /dev/null +++ b/tests/config-transaction-api.test.mjs @@ -0,0 +1,40 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import http from 'node:http'; +import { fixture, compatibleFixture } from './helpers.mjs'; +import { Provider } from '../src/server/provider.mjs'; +import { Runtime } from '../src/server/runtime.mjs'; +import { createRequestHandler } from '../src/server/app.mjs'; + +test('actual config HTTP failure preserves the committed selection, config and volatile credential before a successful retry', async t => { + const f = fixture(t), provider = new Provider(), runtime = new Runtime(f.store, provider), server = http.createServer(); + const token = 'owned-config-transaction-token', clients = new Set(); + const context = { appDirectory: process.cwd(), store: f.store, provider, runtime, server, token, clients, + started: Date.now(), exampleProject: f.project, getPort: () => server.address().port, shutdown: () => {} }; + server.on('request', createRequestHandler(context)); + await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)); + f.onCleanup(async () => { await runtime.stopAll(); server.closeAllConnections(); await new Promise(resolve => server.close(resolve)); }); + const api = async (route, input) => { + const response = await fetch('http://127.0.0.1:' + server.address().port + '/api' + route, { method: input === undefined ? 'GET' : 'POST', + headers: { 'Content-Type': 'application/json', 'X-Workbench-Token': token, Connection: 'close' }, ...(input === undefined ? {} : { body: JSON.stringify(input) }) }); + const value = await response.json(); if (!response.ok) throw Object.assign(new Error(value.error), { status: response.status }); return value; + }; + const model = await compatibleFixture(t, () => ({ data: [{ id: 'owned-config-model' }] })); + const config = { mode: 'compatible', model: 'owned-config-model', baseUrl: model.baseUrl }; + await api('/config', { ...config, apiKey: 'owned-original-config-key' }); + const connection = await api('/model-center/connections', { name: 'Owned selected connection', model: 'owned-reserve', baseUrl: model.baseUrl, apiKey: 'owned-reserve-config-key' }); + await api('/model-center/select', { type: 'connection', id: connection.id }); + const before = structuredClone(f.store.config), registry = structuredClone(provider.hub.state); + f.store.storage.faultInjector = phase => { if (phase === 'before_commit') throw new Error('owned config disk failure'); }; + await assert.rejects(api('/config', { ...config, mode: 'demo', apiKey: 'owned-new-config-key' }), /owned config disk failure/); + assert.deepEqual(f.store.config, before); assert.deepEqual(provider.hub.state, registry); + assert.deepEqual(f.store.storage.meta('config'), before); assert.deepEqual(f.store.storage.meta('modelRegistry'), registry); + assert.equal(provider.apiKey, 'owned-original-config-key'); + f.store.storage.faultInjector = null; + await api('/config/models', {}); assert.equal(model.requests.at(-1).headers.authorization, 'Bearer owned-original-config-key'); + await assert.rejects(api('/config', { ...config, apiKey: 123 }), /凭据格式无效/); + assert.deepEqual(f.store.config, before); assert.deepEqual(provider.hub.state, registry); + await api('/config', { ...config, apiKey: 'owned-new-config-key' }); + assert.equal(provider.hub.state.selected.type, 'legacy'); assert.equal(f.store.config.configRevision, before.configRevision + 1); + await api('/config/models', {}); assert.equal(model.requests.at(-1).headers.authorization, 'Bearer owned-new-config-key'); +}); diff --git a/tests/model-center.test.mjs b/tests/model-center.test.mjs index 1a47aeac..94a08a32 100644 --- a/tests/model-center.test.mjs +++ b/tests/model-center.test.mjs @@ -131,3 +131,66 @@ test('compiled model-center HTTP API persists public profiles, blocks forged ori assert.equal(response.status, 403); assert.equal(fs.readFileSync(path.join(f.data, 'workbench.sqlite')).includes(Buffer.from('owned-http-key')), false); }); + +test('model registry disk failures restore routing, pool profiles and credential references without partial updates', t => { + const f = fixture(t), provider = new Provider(); provider.setKey('owned-original-fixture'); + const hub = provider.modelHub(f.store), connection = add(hub, { baseUrl: 'http://127.0.0.1:12000/v1' }, 'atomic'); + const state = structuredClone(hub.state), credential = provider.credentials.get(connection.id); + const fail = () => { f.store.storage.faultInjector = phase => { if (phase === 'before_commit') throw new Error('fixture failed commit'); }; }; + for (const action of [ + () => hub.toggle(connection.id, false), + () => hub.upsert({ ...connection, name: 'Uncommitted rename', apiKey: 'uncommitted-fixture-key' }), + () => hub.pool({ name: 'Uncommitted pool', members: [{ connectionId: connection.id }] }), + ]) { + fail(); assert.throws(action, /fixture failed commit/); + assert.deepEqual(hub.state, state); assert.deepEqual(f.store.storage.meta('modelRegistry'), state); + assert.equal(provider.credentials.get(connection.id), credential); + assert.equal(provider.apiKey, 'owned-original-fixture'); + } + f.store.storage.faultInjector = null; + const disabled = hub.toggle(connection.id, false); assert.equal(disabled.enabled, false); + assert.deepEqual(f.store.storage.meta('modelRegistry'), hub.state); +}); + +test('model selection and saved configuration commit together and failures preserve the original mode and endpoint', t => { + const f = fixture(t), provider = new Provider(); provider.setKey('owned-legacy-fixture'); + const hub = provider.modelHub(f.store), connection = add(hub, { baseUrl: 'http://127.0.0.1:12000/v1' }, 'selected'); + const state = structuredClone(hub.state), config = structuredClone(f.store.config); + f.store.storage.faultInjector = phase => { if (phase === 'before_commit') throw new Error('fixture selection failure'); }; + assert.throws(() => hub.select({ type: 'connection', id: connection.id }), /fixture selection failure/); + assert.deepEqual(hub.state, state); assert.deepEqual(f.store.config, config); + assert.deepEqual(f.store.storage.meta('modelRegistry'), state); assert.deepEqual(f.store.storage.meta('config'), config); + f.store.storage.faultInjector = null; + hub.select({ type: 'connection', id: connection.id }); + const selected = structuredClone(hub.state), selectedConfig = structuredClone(f.store.config); + f.store.storage.faultInjector = phase => { if (phase === 'before_commit') throw new Error('fixture original config failure'); }; + assert.throws(() => hub.select({ type: 'legacy' }, { mode: 'demo', model: 'uncommitted-model' }), /fixture original config failure/); + assert.deepEqual(hub.state, selected); assert.deepEqual(f.store.config, selectedConfig); + assert.equal(provider.apiKey, 'owned-legacy-fixture'); +}); + +test('configuration imports roll back the entire batch and retain one usable preview after validation or commit failure', t => { + const f = fixture(t), provider = new Provider(), hub = provider.modelHub(f.store), importer = new ConfigImporter(hub); + const existing = add(hub, { baseUrl: 'http://127.0.0.1:12000/v1' }, 'preexisting'); + const before = structuredClone(hub.state), credential = provider.credentials.get(existing.id), filename = path.join(f.root, 'atomic-import.json'); + const entries = [1, 2].map(index => ({ id: index, name: 'Fixture import ' + index, model: 'fixture-model', + baseUrl: 'http://127.0.0.1:12345/v1', apiKey: 'owned-import-key-' + index })); + fs.writeFileSync(filename, JSON.stringify({ schema: 1, connections: entries })); + const preview = importer.preview('workbench-json', filename); + f.store.storage.faultInjector = phase => { if (phase === 'before_commit') throw new Error('fixture import failure'); }; + assert.throws(() => importer.apply(preview.id, true), /fixture import failure/); + assert.deepEqual(hub.state, before); assert.deepEqual(f.store.storage.meta('modelRegistry'), before); + assert.equal(provider.credentials.size, 1); assert.equal(provider.credentials.get(existing.id), credential); + assert.equal(importer.previews.has(preview.id), true); + f.store.storage.faultInjector = null; + const imported = importer.apply(preview.id, true); assert.equal(imported.imported.length, 2); + assert.equal(importer.previews.has(preview.id), false); + assert.deepEqual(f.store.storage.meta('modelRegistry'), hub.state); + const validState = structuredClone(hub.state), validCredentials = new Map(provider.credentials); + entries[1].apiKey = 'x'.repeat(16001); + fs.writeFileSync(filename, JSON.stringify({ schema: 1, connections: entries })); + const invalid = importer.preview('workbench-json', filename); + assert.throws(() => importer.apply(invalid.id), /凭据格式无效/); + assert.deepEqual(hub.state, validState); assert.deepEqual(provider.credentials, validCredentials); + assert.deepEqual(f.store.storage.meta('modelRegistry'), validState); +}); diff --git a/tests/process-environment.test.mjs b/tests/process-environment.test.mjs new file mode 100644 index 00000000..73e5fdc8 --- /dev/null +++ b/tests/process-environment.test.mjs @@ -0,0 +1,57 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import path from 'node:path'; +import { fixture } from './helpers.mjs'; +import { Provider } from '../src/server/provider.mjs'; +import { Runtime } from '../src/server/runtime.mjs'; +import { CheckRunner } from '../src/core/check-runner.mjs'; +import { resolvePythonRuntime } from '../src/core/python-runtime.mjs'; + +const markers = ['AWB_QA_HOST_ONLY_SECRET', 'AWB_QA_UNRELATED_TOKEN']; +function hostMarkers(t) { + for (const name of markers) { assert.equal(Object.hasOwn(process.env, name), false); process.env[name] = 'owned-host-marker'; } + t.after(() => { for (const name of markers) delete process.env[name]; }); +} +function task(f) { + const run = f.store.beginRun(f.session, 'Verify actual project execution environment', false, f.store.config); + f.session.status = 'completed'; f.store.finishRun(f.session, run); +} +async function checks(t, f, options = {}) { + task(f); const runner = new CheckRunner(f.store, options); f.onCleanup(() => runner.stopAll()); + const plan = await runner.plan(f.session); return await (await runner.start(f.session, plan.id)).promise; +} + +test('an actual shell command keeps Node and UTF-8 output while omitting host-only credentials', async t => { + const f = fixture(t); hostMarkers(t); + const filename = path.join(f.projectRoot, 'probe.mjs'); + fs.writeFileSync(filename, 'import assert from "node:assert/strict"; for (const name of ' + JSON.stringify(markers) + ') assert.equal(process.env[name], undefined); console.log("工程终端可用");'); + const quote = value => process.platform === 'win32' ? "'" + value.replaceAll("'", "''") + "'" : "'" + value.replaceAll("'", "'\\''") + "'"; + const result = await new Runtime(f.store, new Provider()).executeCommand((process.platform === 'win32' ? '& ' : '') + + quote(process.execPath) + ' ' + quote(filename), f.projectRoot, new AbortController().signal, () => {}); + assert.equal(result.status, 'completed', result.stderr); assert.equal(result.exit_code, 0); assert.match(result.stdout, /工程终端可用/); +}); + +test('real npm tests and build do not inherit arbitrary host credentials or Node injection settings', async t => { + const f = fixture(t); hostMarkers(t); + fs.writeFileSync(path.join(f.projectRoot, 'package.json'), JSON.stringify({ type: 'module', scripts: { test: 'node --test case.test.mjs', build: 'node build.mjs' } })); + fs.writeFileSync(path.join(f.projectRoot, 'case.test.mjs'), 'import test from "node:test"; import assert from "node:assert/strict"; test("project receives no host credentials", () => { for (const name of ' + + JSON.stringify(markers) + ') assert.equal(process.env[name], undefined); assert.equal(process.env.CI, "1"); assert.equal(process.env.NODE_OPTIONS, undefined); });'); + fs.writeFileSync(path.join(f.projectRoot, 'build.mjs'), 'import assert from "node:assert/strict"; for (const name of ' + JSON.stringify(markers) + ') assert.equal(process.env[name], undefined); console.log("actual build completed");'); + const job = await checks(t, f); assert.equal(job.status, 'passed', job.reason); + assert.equal(job.results.length, 2); assert.equal(job.results[0].tests.total, 1); assert.equal(job.results[0].tests.passed, 1); + assert.equal(job.results[1].exitCode, 0); +}); + +test('real Python tests and compilation keep their sealed inputs without host credentials', async t => { + const f = fixture(t); hostMarkers(t); + const runtime = await resolvePythonRuntime(f.project, { executable: process.env.AGENT_WORKBENCH_TEST_PYTHON }); + assert.equal(runtime.status, 'available', 'Use the independent QA Python interpreter.'); + fs.writeFileSync(path.join(f.projectRoot, 'pyproject.toml'), '[project]\nname="owned-environment"\nversion="0.1.0"\n[tool.agent-workbench.python]\nframework="unittest"\ntest-paths=["tests"]\n'); + fs.mkdirSync(path.join(f.projectRoot, 'tests')); + fs.writeFileSync(path.join(f.projectRoot, 'tests/test_environment.py'), 'import os, unittest\nclass Environment(unittest.TestCase):\n def test_host_credentials_absent(self):\n for name in ' + + JSON.stringify(markers) + ':\n self.assertNotIn(name, os.environ)\n self.assertEqual(os.environ.get("PYTEST_DISABLE_PLUGIN_AUTOLOAD"), "1")\n'); + const job = await checks(t, f, { pythonExecutable: runtime.logicalExecutable }); + assert.equal(job.status, 'passed', job.reason); assert.equal(job.results[0].tests.passed, 1); + assert.ok(job.results.every(result => result.evidenceValidated && result.exitCode === 0)); +}); diff --git a/tests/upgrade-model-center.test.mjs b/tests/upgrade-model-center.test.mjs new file mode 100644 index 00000000..6167e4f9 --- /dev/null +++ b/tests/upgrade-model-center.test.mjs @@ -0,0 +1,55 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import http from 'node:http'; +import { fixture, workspace } from './helpers.mjs'; +import { Provider } from '../src/server/provider.mjs'; +import { Runtime } from '../src/server/runtime.mjs'; +import { ModelHub } from '../src/core/models/model-hub.mjs'; +import { ConfigImporter } from '../src/core/models/config-import.mjs'; +import { installUpgrade } from '../src/server/hot-upgrade.mjs'; + +async function setup(t) { + const f = fixture(t), provider = new Provider(); provider.setKey('owned-upgrade-fixture'); + const runtime = new Runtime(f.store, provider), server = http.createServer((_request, response) => response.end('old-handler')); + await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)); + f.onCleanup(() => new Promise(resolve => { server.closeAllConnections(); server.close(resolve); })); + const hub = provider.modelHub(f.store); hub.importer = new ConfigImporter(hub); + const context = { store: f.store, provider, runtime, server, token: 'owned-upgrade-token', clients: new Set(), + started: Date.now(), exampleProject: f.project, shutdown: () => {} }; + return { ...f, context, provider, hub, runtime, server }; +} + +test('hot upgrade refreshes retained model and importer methods while preserving credential and routing objects', async t => { + const f = await setup(t), credentials = f.provider.credentials, state = f.hub.state; + const oldHub = Object.create(ModelHub.prototype), oldImporter = Object.create(ConfigImporter.prototype); + Object.setPrototypeOf(f.hub, oldHub); Object.setPrototypeOf(f.hub.importer, oldImporter); + f.hub.importer.previews.set('owned-preview', { created: Date.now() }); + const original = f.hub, importer = f.hub.importer; + installUpgrade(f.context, { appDirectory: workspace, updateServiceInfo: false }); + assert.equal(f.provider.hub, original); assert.equal(f.provider.credentials, credentials); + assert.equal(f.hub.state, state); assert.equal(f.provider.apiKey, 'owned-upgrade-fixture'); + assert.equal(f.hub.importer, importer); assert.equal(f.hub.importer.previews.has('owned-preview'), true); + assert.equal(Object.getPrototypeOf(f.hub), ModelHub.prototype); + assert.equal(Object.getPrototypeOf(f.hub.importer), ConfigImporter.prototype); + const response = await fetch('http://127.0.0.1:' + f.server.address().port + '/api/health'); + assert.equal((await response.json()).ready, true); +}); + +test('hot upgrade refuses active probes and restores retained model methods if installation fails', async t => { + const f = await setup(t), handler = f.server.listeners('request')[0]; + for (const [set, clear] of [ + [() => { f.provider.activeRequests = 1; }, () => { f.provider.activeRequests = 0; }], + [() => { f.hub.waiting = 1; }, () => { f.hub.waiting = 0; }], + [() => f.hub.leases.set('owned-connection', 1), () => f.hub.leases.clear()], + ]) { + set(); assert.throws(() => installUpgrade(f.context, { appDirectory: workspace, updateServiceInfo: false }), /model requests and probes/); + assert.equal(f.server.listeners('request')[0], handler); clear(); + } + const oldHub = Object.create(ModelHub.prototype), oldImporter = Object.create(ConfigImporter.prototype); + Object.setPrototypeOf(f.hub, oldHub); Object.setPrototypeOf(f.hub.importer, oldImporter); + f.store.claimRuntime = () => { throw new Error('fixture installation failure'); }; + assert.throws(() => installUpgrade(f.context, { appDirectory: workspace, updateServiceInfo: false }), /fixture installation failure/); + assert.equal(f.server.listeners('request')[0], handler); + assert.equal(Object.getPrototypeOf(f.hub), oldHub); assert.equal(Object.getPrototypeOf(f.hub.importer), oldImporter); + assert.equal(f.provider.apiKey, 'owned-upgrade-fixture'); +});