import fs from 'node:fs'; import path from 'node:path'; import net from 'node:net'; import assert from 'node:assert/strict'; import { execFileSync, spawn } from 'node:child_process'; import { fixture, launchWorkbench } from '../tests/helpers.mjs'; import { InstallationManager, snapshotPersistentData } from '../src/core/desktop/install-manager.mjs'; import { publicSnapshot, compareOriginalState, hash, digest } from './retained-host-state.mjs'; // Explicit, write-once release operations. No model requests, credential access, // task continuation, process restart or automatic installer retry. const mode = process.argv[2], version = '1.25.11'; assert.ok(['register', 'install', 'before', 'upgrade', 'final'].includes(mode)); const root = path.resolve(process.env.EXPERIENCE_RELEASE_ROOT ?? '.qa/experience-drafts-1.25.11'), url = 'http://127.0.0.1:4318'; const read = file => JSON.parse(fs.readFileSync(file, 'utf8').replace(/^\uFEFF/, '')); const save = (name, value) => { const file = path.join(root, name); fs.mkdirSync(path.dirname(file), { recursive: true }); fs.writeFileSync(file, JSON.stringify(value, null, 2) + '\n', { flag: 'wx' }); }; fs.mkdirSync(root, { recursive: true }); save(mode + '-started.json', { mode, startedAt: new Date().toISOString() }); const disposers = [], t = { after: dispose => disposers.push(dispose) }; async function api(route) { const boot = await (await fetch(url + '/api/bootstrap', { signal: AbortSignal.timeout(20000) })).json(); const response = await fetch(url + '/api' + route, { headers: { 'X-Workbench-Token': boot.token, Connection: 'close' }, signal: AbortSignal.timeout(20000) }); assert.equal(response.status, 200, route); return response.json(); } async function inspectorClosed() { await new Promise((resolve, reject) => { const socket = net.createConnection({ host: '127.0.0.1', port: 9229 }); socket.setTimeout(1500); socket.once('connect', () => { socket.destroy(); reject(Error('Inspector already open.')); }); socket.once('error', error => { socket.destroy(); error.code === 'ECONNREFUSED' ? resolve() : reject(error); }); socket.once('timeout', () => { socket.destroy(); reject(Error('Inspector state unknown.')); }); }); } function compareRetained(before, after) { return compareOriginalState(before, after); } async function retainedSnapshot(dataRoot) { const snapshot = await publicSnapshot(url, dataRoot); const { config } = await api('/model-center/selection'); assert.equal(digest(config), snapshot.configSha256, 'Public config changed during the read-only snapshot.'); return { ...snapshot, publicConfig: config }; } let result; try { if (mode === 'register') { assert.equal(execFileSync('git', ['status', '--porcelain'], { encoding: 'utf8', windowsHide: true }).trim(), ''); const release = read('releases/latest.json'), manifest = read(path.join(release.portableRoot, 'MANIFEST.json')); const source = read(process.env.AGENT_WORKBENCH_SOURCE_RELEASE); const commit = execFileSync('git', ['rev-parse', 'HEAD'], { encoding: 'utf8', windowsHide: true }).trim(); assert.equal(manifest.version, version); assert.equal(source.version, version); assert.equal(source.sourceCommit, commit); assert.equal(release.documentation.sourceCommit, commit); assert.equal(hash(fs.readFileSync(source.path)), source.sha256); assert.equal(hash(fs.readFileSync(release.installer.path)), release.installer.sha256); save('candidate.json', release); save('source.json', source); result = { success: true, version, sourceCommit: commit, candidate: release.portableRoot }; } else { const release = read(path.join(root, 'candidate.json')), registration = read(path.join(root, 'register.json')); assert.equal(registration.success, true); assert.equal(hash(fs.readFileSync(release.installer.path)), release.installer.sha256); assert.equal(read(path.join(release.portableRoot, 'MANIFEST.json')).version, version); if (mode === 'install') { const f = fixture(t, { modernDefaults: true }); f.store.close(); const installRoot = path.join(root, 'installed', 'program'), target = path.join(installRoot, 'versions', path.basename(release.portableRoot)); assert.equal(fs.existsSync(target), false); fs.mkdirSync(path.dirname(target), { recursive: true }); fs.cpSync(release.portableRoot, target, { recursive: true, errorOnExist: true, force: false }); const before = snapshotPersistentData(f.data); const manager = new InstallationManager({ installRoot, candidateRoot: target, dataRoot: f.data, port: 49997 }); const preflight = await manager.preflight({ stageOnly: true }), staged = await manager.activate({ stageOnly: true }); const activation = await manager.activate(); assert.equal(activation.phase, 'activated'); assert.deepEqual(snapshotPersistentData(f.data), before); const host = await launchWorkbench(t, f.data, {}, { appRoot: target, nodePath: path.join(target, 'runtime/node.exe') }); const health = await (await fetch(host.url + '/api/health')).json(); assert.equal(health.version, version); assert.notEqual(new URL(host.url).port, '4318'); await host.close(); result = { success: true, version, target, preflight: preflight.phase, staged: staged.phase, activation: activation.phase, originalData: 'exact', sourceCommit: registration.sourceCommit, scope: 'Actual isolated stage/activate/start. UI verification uses this installed program with separate owned data.' }; } else { await inspectorClosed(); const host = await api('/host/status'); assert.equal(host.activity.active, false); assert.equal(host.desktopWindows.count, 0); const current = await retainedSnapshot(host.identity.dataRoot); assert.deepEqual(current.active, []); const installRoot = path.dirname(path.dirname(host.identity.runtimeRoot)); assert.equal(path.basename(path.dirname(host.identity.runtimeRoot)), 'versions'); if (mode === 'before') { assert.equal(current.version, '1.25.10'); save('formal/state-before.json', current); save('formal/host-before.json', host); save('formal/pointer-before.json', read(path.join(installRoot, 'current.json'))); result = { success: true, version: current.version, pid: current.pid, projects: current.projects, sessions: current.database.sessionIds.length }; } else { assert.equal(read(path.join(root, 'install.json')).success, true); const before = read(path.join(root, 'formal/state-before.json')), originalHost = read(path.join(root, 'formal/host-before.json')); compareRetained(before, current); assert.equal(host.identity.instanceId, originalHost.identity.instanceId); if (mode === 'upgrade') { // Explicitly select a new receipt after a fixture failure; the original // failed receipt is never overwritten or counted as a success. const cross = read(process.env.EXPERIENCE_CROSS_VERSION_RECEIPT ?? path.join(root, 'cross-version-upgrade.json')); assert.equal(cross.success, true); assert.equal(cross.from, '1.25.10'); assert.equal(cross.to, version); assert.equal(cross.realModelRequests, 0); assert.equal(cross.officialServiceTouched, false); assert.equal(fs.realpathSync.native(cross.next), fs.realpathSync.native(read(path.join(root, 'install.json')).target)); for (const file of ['archive-verification.json', 'rebuild-result.json', 'installed-web/result.json', 'installed-electron/result.json']) { const receipt = read(path.join(root, file)); assert.equal(receipt.success, true, file); if (file.startsWith('installed-')) { const target = read(path.join(root, 'install.json')).target; assert.equal(fs.realpathSync.native(receipt.appRoot), fs.realpathSync.native(target)); assert.equal(receipt.actualElectron, file.startsWith('installed-electron/')); assert.equal(receipt.serverSha256, read(path.join(target, 'MANIFEST.json')).files.find(row => row.path === 'dist-server/server.mjs').sha256); assert.equal(receipt.passed?.length, 7); assert.deepEqual(receipt.errors, []); assert.equal(receipt.realModelRequests, 0); assert.equal(receipt.officialServiceTouched, false); } else assert.equal(receipt.sourceCommit, registration.sourceCommit); } assert.equal(current.version, '1.25.10'); assert.deepEqual(read(path.join(installRoot, 'current.json')), read(path.join(root, 'formal/pointer-before.json'))); const log = fs.openSync(path.join(root, 'formal/installer-process.log'), 'wx'), started = Date.now(); let code; try { code = await new Promise((resolve, reject) => { const child = spawn(release.installer.path, ['/VERYSILENT', '/SUPPRESSMSGBOXES', '/NORESTART', '/LOG=' + path.join(root, 'formal/installer.log'), '/DIR=' + installRoot, '/DATA_ROOT=' + host.identity.dataRoot, '/PORT=4318'], { windowsHide: true, stdio: ['ignore', log, log] }); child.once('error', reject); child.once('close', resolve); }); } finally { fs.closeSync(log); } save('formal/installer-exit.json', { code, elapsedMs: Date.now() - started }); assert.equal(code, 0, 'Preserve this failed/unknown installation; do not replay.'); } else assert.equal(read(path.join(root, 'upgrade.json')).success, true); const after = await retainedSnapshot(host.identity.dataRoot), finalHost = await api('/host/status'); const retention = compareRetained(before, after); assert.equal(after.version, version); assert.equal(finalHost.identity.instanceId, originalHost.identity.instanceId); assert.equal(finalHost.identity.pid, originalHost.identity.pid); const target = path.join(installRoot, 'versions', path.basename(release.portableRoot)); assert.equal(fs.realpathSync.native(after.runtimeRoot), fs.realpathSync.native(target)); assert.equal(read(path.join(installRoot, 'current.json')).active.directory, path.basename(target)); await inspectorClosed(); save('formal/' + mode + '-state-after.json', after); result = { success: true, version, pid: after.pid, instanceId: finalHost.identity.instanceId, runtimeRoot: after.runtimeRoot, retention, projects: after.projects, sessions: after.database.sessionIds.length, sourceCommit: registration.sourceCommit, inspectorClosed: true }; } } } } catch (error) { result = { success: false, error: error.stack }; process.exitCode = 1; } finally { for (const dispose of disposers.reverse()) await dispose(); } result = { ...result, mode, finishedAt: new Date().toISOString(), realModelRequests: 0, keyReadOrResaved: false }; save(mode + '.json', result); console.log(JSON.stringify(result));