feat(desktop): attest and manage the owned Windows host lifecycle
This commit is contained in:
+14
-51
@@ -1,56 +1,19 @@
|
||||
[CmdletBinding()]
|
||||
param([int]$Port = 0, [switch]$NoBrowser)
|
||||
|
||||
param([int]$Port = 0, [switch]$NoBrowser, [string]$DataRoot = '', [string]$NodePath = '')
|
||||
$ErrorActionPreference = 'Stop'
|
||||
[Console]::OutputEncoding = [Text.UTF8Encoding]::new($false)
|
||||
$appRoot = [IO.Path]::GetFullPath((Split-Path -Parent $PSScriptRoot))
|
||||
if ($Port -eq 0) { $Port = if ($env:AGENT_WORKBENCH_PORT) { [int]$env:AGENT_WORKBENCH_PORT } else { 4318 } }
|
||||
if ($Port -lt 1 -or $Port -gt 65535) { throw 'Please use a port between 1 and 65535.' }
|
||||
$workbenchUrl = "http://127.0.0.1:$Port"
|
||||
|
||||
function Read-WorkbenchHealth {
|
||||
try { return Invoke-RestMethod -Uri "$workbenchUrl/api/health" -TimeoutSec 2 }
|
||||
catch { return $null }
|
||||
}
|
||||
|
||||
$health = Read-WorkbenchHealth
|
||||
if ($health) {
|
||||
if ($health.app -ne 'agent-workbench' -or -not $health.ready) { throw "The port is in use by another service: $Port" }
|
||||
Write-Output "Agent Workbench is already running: $workbenchUrl"
|
||||
if (-not $NoBrowser) { Start-Process -FilePath $workbenchUrl }
|
||||
exit 0
|
||||
}
|
||||
|
||||
$serverFile = Join-Path $appRoot 'dist-server\server.mjs'
|
||||
if (-not (Test-Path -LiteralPath $serverFile)) { throw 'Build the source first with npm.cmd run build, or use the portable package.' }
|
||||
$nodeFile = Join-Path $appRoot 'runtime\node.exe'
|
||||
if (-not (Test-Path -LiteralPath $nodeFile)) {
|
||||
$installedNode = Get-Command node.exe -ErrorAction SilentlyContinue
|
||||
if (-not $installedNode) { throw 'Node.js 24 was not found. Use the portable package with its bundled runtime.' }
|
||||
$nodeFile = $installedNode.Source
|
||||
}
|
||||
$dataRoot = if ($env:AGENT_WORKBENCH_DATA_DIR) { [IO.Path]::GetFullPath($env:AGENT_WORKBENCH_DATA_DIR) } else { Join-Path $env:LOCALAPPDATA 'AgentWorkbench' }
|
||||
$logsRoot = Join-Path $dataRoot 'logs'
|
||||
[IO.Directory]::CreateDirectory($logsRoot) | Out-Null
|
||||
$stdoutFile = Join-Path $logsRoot 'service.stdout.log'
|
||||
$stderrFile = Join-Path $logsRoot 'service.stderr.log'
|
||||
$env:AGENT_WORKBENCH_APP_DIR = $appRoot
|
||||
$env:AGENT_WORKBENCH_DATA_DIR = $dataRoot
|
||||
$env:AGENT_WORKBENCH_PORT = [string]$Port
|
||||
$childProcess = Start-Process -FilePath $nodeFile -ArgumentList ('"' + $serverFile + '"') -WorkingDirectory $appRoot -WindowStyle Hidden -PassThru -RedirectStandardOutput $stdoutFile -RedirectStandardError $stderrFile
|
||||
$deadline = [DateTime]::UtcNow.AddSeconds(15)
|
||||
do {
|
||||
Start-Sleep -Milliseconds 200
|
||||
$childProcess.Refresh()
|
||||
if ($childProcess.HasExited) {
|
||||
$diagnostic = if (Test-Path -LiteralPath $stderrFile) { (Get-Content -LiteralPath $stderrFile -Tail 8) -join "`n" } else { '' }
|
||||
throw "Agent Workbench could not start. $diagnostic"
|
||||
}
|
||||
$health = Read-WorkbenchHealth
|
||||
} while ((-not $health -or -not $health.ready) -and [DateTime]::UtcNow -lt $deadline)
|
||||
if (-not $health -or $health.app -ne 'agent-workbench' -or -not $health.ready) { throw "Service did not become ready. See $stderrFile" }
|
||||
$serviceInfo = @{ app = 'agent-workbench'; pid = $childProcess.Id; port = $Port; appRoot = $appRoot; dataRoot = $dataRoot; startedAt = [DateTime]::UtcNow.ToString('o') } | ConvertTo-Json
|
||||
[IO.File]::WriteAllText((Join-Path $dataRoot 'service-info.json'), $serviceInfo, [Text.UTF8Encoding]::new($false))
|
||||
Write-Output "Agent Workbench is ready: $workbenchUrl"
|
||||
Write-Output "Data: $dataRoot"
|
||||
if (-not $NoBrowser) { Start-Process -FilePath $workbenchUrl }
|
||||
if (-not $DataRoot) { $DataRoot = if ($env:AGENT_WORKBENCH_DATA_DIR) { $env:AGENT_WORKBENCH_DATA_DIR } else { Join-Path $env:LOCALAPPDATA 'AgentWorkbench' } }
|
||||
$DataRoot = [IO.Path]::GetFullPath($DataRoot)
|
||||
if (-not $NodePath) { $NodePath = Join-Path $appRoot 'runtime\node.exe' }
|
||||
if (-not (Test-Path -LiteralPath $NodePath)) { $NodePath = (Get-Command node.exe -ErrorAction Stop).Source }
|
||||
$launcher = Join-Path $appRoot 'dist-server\host-launcher.mjs'
|
||||
if (-not (Test-Path -LiteralPath $launcher)) { throw 'Build the source first, or use the complete portable package.' }
|
||||
$output = & $NodePath $launcher start --app-root $appRoot --data-root $DataRoot --node $NodePath --port ([string]$Port)
|
||||
if ($LASTEXITCODE -ne 0) { throw 'The host could not be verified. See the original diagnostic above.' }
|
||||
$result = $output | ConvertFrom-Json
|
||||
Write-Output ('Agent Workbench is ready: ' + $result.url)
|
||||
Write-Output ('Data: ' + $DataRoot)
|
||||
Write-Output ('Verified host PID: ' + $result.identity.pid + ' · Instance: ' + $result.identity.instanceId)
|
||||
if (-not $NoBrowser) { Start-Process -FilePath $result.url }
|
||||
+10
-10
@@ -1,14 +1,14 @@
|
||||
[CmdletBinding()]
|
||||
param([int]$Port = 0)
|
||||
|
||||
param([int]$Port = 0, [string]$DataRoot = '', [string]$NodePath = '')
|
||||
$ErrorActionPreference = 'Stop'
|
||||
[Console]::OutputEncoding = [Text.UTF8Encoding]::new($false)
|
||||
$appRoot = [IO.Path]::GetFullPath((Split-Path -Parent $PSScriptRoot))
|
||||
if ($Port -eq 0) { $Port = if ($env:AGENT_WORKBENCH_PORT) { [int]$env:AGENT_WORKBENCH_PORT } else { 4318 } }
|
||||
if ($Port -lt 1 -or $Port -gt 65535) { throw 'Please use a port between 1 and 65535.' }
|
||||
$workbenchUrl = "http://127.0.0.1:$Port"
|
||||
try { $health = Invoke-RestMethod -Uri "$workbenchUrl/api/health" -TimeoutSec 2 }
|
||||
catch { Write-Output "Agent Workbench is not running on port $Port."; exit 0 }
|
||||
if ($health.app -ne 'agent-workbench' -or -not $health.ready) { throw "This port is occupied by another service: $Port" }
|
||||
$bootstrap = Invoke-RestMethod -Uri "$workbenchUrl/api/bootstrap" -TimeoutSec 3
|
||||
Invoke-RestMethod -Uri "$workbenchUrl/api/shutdown" -Method Post -ContentType 'application/json' -Body '{}' -Headers @{ 'X-Workbench-Token' = $bootstrap.token } -TimeoutSec 15 | Out-Null
|
||||
Write-Output "Agent Workbench is stopping: $workbenchUrl"
|
||||
if (-not $DataRoot) { $DataRoot = if ($env:AGENT_WORKBENCH_DATA_DIR) { $env:AGENT_WORKBENCH_DATA_DIR } else { Join-Path $env:LOCALAPPDATA 'AgentWorkbench' } }
|
||||
$DataRoot = [IO.Path]::GetFullPath($DataRoot)
|
||||
if (-not $NodePath) { $NodePath = Join-Path $appRoot 'runtime\node.exe' }
|
||||
if (-not (Test-Path -LiteralPath $NodePath)) { $NodePath = (Get-Command node.exe -ErrorAction Stop).Source }
|
||||
$output = & $NodePath (Join-Path $appRoot 'dist-server\host-launcher.mjs') stop --app-root $appRoot --data-root $DataRoot --node $NodePath --port ([string]$Port)
|
||||
if ($LASTEXITCODE -ne 0) { throw 'The original host stop remains unverified. See the diagnostic above.' }
|
||||
$result = $output | ConvertFrom-Json
|
||||
Write-Output ('Agent Workbench host: ' + $result.state)
|
||||
@@ -5,4 +5,6 @@ await build({ entryPoints: ['src/server/index.mjs'], outfile: 'dist-server/serve
|
||||
platform: 'node', target: 'node24', format: 'esm', sourcemap: false, legalComments: 'eof' });
|
||||
await build({ entryPoints: ['src/server/hot-upgrade.mjs'], outfile: 'dist-server/hot-upgrade.mjs', bundle: true,
|
||||
platform: 'node', target: 'node24', format: 'esm', sourcemap: false, legalComments: 'eof' });
|
||||
await build({ entryPoints: ['src/desktop/host-cli.mjs'], outfile: 'dist-server/host-launcher.mjs', bundle: true,
|
||||
platform: 'node', target: 'node24', format: 'esm', sourcemap: false, legalComments: 'eof' });
|
||||
console.log('Server bundle built.');
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import http from 'node:http';
|
||||
import net from 'node:net';
|
||||
import { randomUUID, randomBytes, createHash } from 'node:crypto';
|
||||
import { DatabaseSync } from 'node:sqlite';
|
||||
import { HostController } from '../src/core/desktop/host-controller.mjs';
|
||||
import { ownedChild, readState, writeState } from '../src/core/desktop/file-state.mjs';
|
||||
import { observeWindowsProcess } from '../src/core/desktop/process-identity.mjs';
|
||||
import { HOST_REGISTRATION_FILE } from '../src/shared/contracts/desktop-host.mjs';
|
||||
|
||||
if (process.argv.includes('--help')) { console.log('node scripts/verify-desktop-host.mjs - real Windows isolated host identity, concurrent start, request stop and restart acceptance.'); process.exit(0); }
|
||||
if (process.argv.length > 2) throw new Error('Use --help.');
|
||||
const root = path.resolve('.qa', 'desktop-host-' + randomUUID()), appRoot = path.join(root, 'app'), dataRoot = path.join(root, 'data');
|
||||
fs.mkdirSync(appRoot, { recursive: true });
|
||||
for (const directory of ['dist-server', 'dist-client']) fs.cpSync(path.resolve(directory), path.join(appRoot, directory), { recursive: true });
|
||||
fs.copyFileSync('package.json', path.join(appRoot, 'package.json'));
|
||||
const freePort = async () => { const server = net.createServer(); await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)); const port = server.address().port; await new Promise(resolve => server.close(resolve)); return port; };
|
||||
const port = await freePort(), options = { appRoot, dataRoot, port, nodePath: process.execPath, timeoutMs: 60000 };
|
||||
const controller = new HostController(options), results = []; let stage = 'concurrent start', started = false, fixture;
|
||||
const record = (name, detail = {}) => { results.push({ name, passed: true, ...detail }); console.log(name + ': passed'); };
|
||||
const until = async action => { const end = Date.now() + 20000; while (!await action()) { if (Date.now() > end) throw new Error('Timed out: ' + stage); await new Promise(resolve => setTimeout(resolve, 100)); } };
|
||||
const save = result => { fs.writeFileSync(path.join(root, 'result.json'), JSON.stringify(result, null, 2)); fs.writeFileSync('.qa/desktop-host-latest.json', JSON.stringify(result, null, 2)); };
|
||||
const completedTools = id => {
|
||||
const db = new DatabaseSync(path.join(dataRoot, 'workbench.sqlite'), { readOnly: true });
|
||||
try { return db.prepare("SELECT payload FROM records WHERE kind='tool' AND session_id=? ORDER BY id").all(id).map(row => JSON.parse(row.payload)).filter(value => value.state === 'completed'); }
|
||||
finally { db.close(); }
|
||||
};
|
||||
try {
|
||||
const starts = await Promise.all([controller.start(), new HostController(options).start()]); started = true;
|
||||
assert.equal(starts[0].identity.pid, starts[1].identity.pid); assert.equal(starts[0].identity.instanceId, starts[1].identity.instanceId);
|
||||
assert.equal(starts.filter(value => !value.reused).length, 1); record(stage, { pid: starts[0].identity.pid, instanceId: starts[0].identity.instanceId });
|
||||
const original = starts[0].identity;
|
||||
stage = 'independent creation and user observation'; const observed = observeWindowsProcess(original.pid); assert.equal(observed.createdAt, original.createdAt); assert.equal(observed.userSid, original.userSid); record(stage);
|
||||
const status = await controller.status(); assert.equal(status.state, 'ready'); assert.equal(status.windowClose, 'keep-host-running');
|
||||
stage = 'wrong data root and installation rejected'; await assert.rejects(new HostController({ ...options, dataRoot: path.join(root, 'wrong-data') }).start());
|
||||
const other = path.join(root, 'other-app'); fs.cpSync(appRoot, other, { recursive: true }); await assert.rejects(new HostController({ ...options, appRoot: other }).start()); record(stage);
|
||||
stage = 'stale registration and creation rejected'; const registrationFile = ownedChild(dataRoot, '.secrets/' + HOST_REGISTRATION_FILE), registration = readState(registrationFile);
|
||||
for (const changed of [{ createdAt: '2000-01-01T00:00:00.000Z' }, { instanceId: randomUUID() }, { userSid: 'S-1-5-21-1-2-3-1000' }, { secret: randomBytes(32).toString('base64') }]) {
|
||||
writeState(registrationFile, { ...registration, ...changed }); await assert.rejects(new HostController(options).connect()); writeState(registrationFile, registration);
|
||||
} record(stage);
|
||||
stage = 'damaged service index rejected'; const infoFile = ownedChild(dataRoot, 'service-info.json'), info = readState(infoFile); writeState(infoFile, { ...info, runtimeRoot: other }); await assert.rejects(new HostController(options).connect()); writeState(infoFile, info); record(stage);
|
||||
stage = 'running input binding does not silently change'; const serverFile = ownedChild(appRoot, 'dist-server/server.mjs'), bytes = fs.readFileSync(serverFile); fs.appendFileSync(serverFile, '\n// owned changed-on-disk fixture\n');
|
||||
assert.equal((await controller.connect()).identity.runtimeIdentity, original.runtimeIdentity); await assert.rejects(new HostController(options).connect()); fs.writeFileSync(serverFile, bytes); record(stage);
|
||||
stage = 'foreign health service rejected'; const foreignPort = await freePort(), foreign = http.createServer((_req, res) => { res.setHeader('Content-Type', 'application/json'); res.end(JSON.stringify({ app: 'agent-workbench', ready: true, pid: process.pid })); });
|
||||
await new Promise(resolve => foreign.listen(foreignPort, '127.0.0.1', resolve));
|
||||
try { await assert.rejects(new HostController({ ...options, port: foreignPort, dataRoot: path.join(root, 'foreign-data') }).start()); } finally { await new Promise(resolve => foreign.close(resolve)); } record(stage);
|
||||
stage = 'completed tools and approvals retained on stop and restart'; const projectRoot = path.join(root, 'project'); fs.mkdirSync(projectRoot); fs.writeFileSync(path.join(projectRoot, 'README.md'), '# Owned desktop lifecycle fixture\n');
|
||||
const project = await controller.api('/projects', { method: 'POST', input: { root: projectRoot } });
|
||||
const session = await controller.api('/sessions', { method: 'POST', input: { projectId: project.id } });
|
||||
await controller.api('/sessions/' + session.id + '/messages', { method: 'POST', input: { content: 'Run the offline demonstration in this owned project.' } });
|
||||
await until(async () => (await controller.api('/sessions/' + session.id)).approvals.some(value => value.status === 'pending'));
|
||||
const before = await controller.api('/sessions/' + session.id + '/export'), completed = completedTools(session.id); assert.ok(completed.length >= 3);
|
||||
const completedHash = createHash('sha256').update(JSON.stringify(completed)).digest('hex');
|
||||
const firstStop = await controller.stop(); started = false; assert.equal(firstStop.processExited, true); assert.equal(observeWindowsProcess(original.pid), null);
|
||||
const second = await controller.start(); started = true; assert.notEqual(second.identity.instanceId, original.instanceId);
|
||||
const restored = await controller.api('/sessions/' + session.id + '/export');
|
||||
assert.equal(createHash('sha256').update(JSON.stringify(completedTools(session.id))).digest('hex'), completedHash);
|
||||
assert.equal(restored.session.events.filter(value => value.kind === 'tool').length, before.session.events.filter(value => value.kind === 'tool').length);
|
||||
assert.equal(restored.session.status, 'paused'); record(stage, { completedTools: completed.length, originalEventSeq: before.session.eventSeq, restoredEventSeq: restored.session.eventSeq });
|
||||
stage = 'actual model HTTP request abort and verified process exit'; let requests = 0, disconnected = false;
|
||||
fixture = http.createServer((req, res) => { requests++; res.on('close', () => { disconnected = true; }); req.resume(); }); await new Promise(resolve => fixture.listen(0, '127.0.0.1', resolve));
|
||||
const pending = controller.api('/config/models', { method: 'POST', input: { baseUrl: 'http://127.0.0.1:' + fixture.address().port + '/v1', apiKey: 'owned-desktop-http-key' }, timeoutMs: 60000 }).catch(error => error);
|
||||
await until(() => requests === 1); const stopped = await controller.stop(); started = false; await pending;
|
||||
assert.equal(stopped.processExited, true); await until(() => disconnected); assert.equal(requests, 1); record(stage, { requests, disconnected, pid: stopped.identity.pid });
|
||||
save({ success: true, root, appRoot, dataRoot, port, results, inference: 'Owned local HTTP fixtures only; no existing model credential is read or persisted.' });
|
||||
} catch (cause) { save({ success: false, root, stage, results, message: cause.message, stack: cause.stack }); throw cause; }
|
||||
finally {
|
||||
if (fixture) { fixture.closeAllConnections(); await new Promise(resolve => fixture.close(resolve)); }
|
||||
if (started) await controller.stop();
|
||||
}
|
||||
Reference in New Issue
Block a user