feat(desktop): add verified install rollback and paged inspection

This commit is contained in:
Agent Workbench Dev
2026-10-31 11:17:11 +08:00
parent 5354d95e54
commit f7a5969fa4
143 changed files with 178736 additions and 30 deletions
+1
View File
@@ -9,3 +9,4 @@
@media(max-width:620px){.modal:has(.model-center){width:100vw;height:100dvh;max-height:100dvh;border-radius:0}.modal:has(.model-center)>.modal-heading{padding:17px 16px}.mc-overview{padding:17px 16px;display:block}.mc-overview h2{font-size:21px}.mc-current{padding:10px 12px;margin:13px 0 0;min-width:0}.mc-current strong{font-size:13px}.mc-tabs{padding:0 8px}.mc-tabs button{padding:12px 10px;min-height:48px;font-size:12px}.mc-content{padding:18px 15px 28px}.mc-section-title{gap:12px;align-items:flex-start;flex-direction:column}.mc-form-grid{grid-template-columns:1fr}.mc-form-grid .mc-full{grid-column:auto}.mc-editor{padding:18px 14px}.mc-connection{padding:16px 13px}.mc-card-heading{gap:9px}.mc-service-icon{width:34px;height:34px}.mc-card-heading h4{font-size:14px}.mc-connection dl{grid-template-columns:72px minmax(0,1fr)}.mc-notice{padding:12px 16px}.model-center button{min-height:44px}.mc-state{font-size:10px}.mc-attempts time{margin-left:0}.mc-import-source{gap:9px}.mc-member-choice input[type=number]{min-height:44px}.mc-form-grid input,.mc-form-grid select{min-height:44px}}
@media(max-width:620px){.modal:has(.model-center)>.modal-heading>.icon-button{min-width:44px;min-height:44px}}
.mc-checks article>div{min-width:0;flex:1}.mc-checks p,.mc-operations-pages p{overflow-wrap:anywhere}.mc-operations-pages .mc-row-actions{display:flex;gap:8px;flex-wrap:wrap;margin:12px 0}.mc-operations-pages{border-top:1px solid #cbd6e2;margin-top:18px;padding-top:12px}.mc-operations-pages .error{color:#a23731}
+4 -3
View File
@@ -10,7 +10,8 @@ type Pool = { id?: string; name: string; members: { connectionId: string; weight
type Attempt = { id: string; connectionId: string; poolId: string | null; model: string; status: string; startedAt: string; ordinal: number; usageStatus: string; reason?: string; taskId?: string; runId: string; requestArtifactId?: string; usage?: { prompt_tokens?: number; completion_tokens?: number } };
type ImportRecord = { id: string; source: string; path: string; enabled: boolean; lastCheckedAt?: string; lastSyncedAt?: string; lastError?: string; lastResult?: { imported?: number; conflicts?: string[] } };
type Center = { revision: number; selected: { type: string; id: string }; connections: Connection[]; pools: Pool[]; imports: ImportRecord[]; attempts: Attempt[]; waiting: number };
type Operations = { checkedAt: string; version: string; scope: string; activeTasks: number; queue: number; checks: { id: string; title: string; status: string; detail: string }[] };
type Operations = { checkedAt: string; version: string; scope: string; activeTasks: number; queue: number; checks: { id: string; title: string; status: string; detail: string }[];
artifacts?: { offset: number; checked: number; total: number; remaining: number; olderOffset: number | null; newerOffset: number | null; results: { id: string; passed: boolean; error?: string }[] } };
type SavedCredential = { id: string; name: string; revision: number; status: string; enabled?: boolean; savedAt?: string; message: string };
type CredentialView = { supported: boolean; unavailable: boolean; connections: SavedCredential[]; scope: string };
const savedStates: Record<string, string> = { not_saved: '仅本次内存', saved: '本机加密保存', disabled: '关闭自动加载', source_changed: '配置已变化', decrypt_failed: '无法解密', user_mismatch: '用户不匹配', directory_mismatch: '目录不匹配', unavailable: '保存登记不可用' };
@@ -39,7 +40,7 @@ export function ModelCenter({ onConfig, onLegacy, busy }: { onConfig: (value: Co
catch (cause) { if (alive.current) setNotice(cause instanceof Error ? cause.message : '操作未完成,请刷新核对。'); }
finally { if (alive.current) setWorking(false); }
}
async function inspect() { const value = await api<Operations>('/operations'); if (alive.current) setOperations(value); }
async function inspect(offset?: number) { const value = await api<Operations>('/operations' + (offset === undefined ? '' : '?artifactOffset=' + offset)); if (alive.current) setOperations(value); }
async function refreshCredentials() { const value = await api<CredentialView>('/model-center/credentials'); if (alive.current) setCredentialView(value); }
useEffect(() => { alive.current = true; void refresh().catch(error => { if (alive.current) setNotice(error.message); }); return () => { alive.current = false; generation.current++; }; }, []);
useEffect(() => { if (!autoInspect || tab !== 'operations') return; const timer = window.setInterval(() => { void inspect().catch(error => { if (alive.current) setNotice(error.message); }); }, 30000); return () => window.clearInterval(timer); }, [autoInspect, tab]);
@@ -133,7 +134,7 @@ export function ModelCenter({ onConfig, onLegacy, busy }: { onConfig: (value: Co
<div className="mc-editor"><div className="mc-form-grid"><label>配置格式<select value={importSource} onChange={event => setImportSource(event.target.value)}><option value="ccswitch">CCSwitch SQLite</option><option value="workbench-json">工作台连接 JSON</option></select></label><label>本地文件路径<input value={importPath} onChange={event => { setImportPath(event.target.value); setPreview(null); }} /></label></div><button className="button secondary" disabled={locked || !importPath} onClick={() => void act(async () => { const value = await api<typeof preview>('/model-center/import-preview', { source: importSource, path: importPath }); if (alive.current) setPreview(value); })}>预览可导入连接</button></div>
{preview && <div className="mc-editor"><h3>本次预览</h3>{preview.entries.map(value => <p key={value.id}>{value.name} · {value.model} · {value.baseUrl} · {value.hasKey ? '含临时凭据' : '无凭据'}</p>)}{preview.notices.map((value, index) => <p className="mc-help" key={index}>{value}</p>)}<label className="mc-checkbox"><input type="checkbox" checked={persistImports} onChange={event => setPersistImports(event.target.checked)} />本机加密保存本次确认导入的凭据</label><button className="button primary" disabled={locked || !preview.entries.length} onClick={() => void act(async () => { await api('/model-center/import-apply', { previewId: preview.id, persistCredentials: persistImports }); if (alive.current) { setPreview(null); setNotice(persistImports ? '连接与本次确认导入的加密凭据已共同保存。' : '已导入可支持的连接。临时凭据只在本次宿主内存中。'); } })}>导入这些连接</button></div>}
</>}
{tab === 'operations' && <><div className="mc-section-title"><div><h3>运行巡检</h3><p>核对真实宿主、数据与近期工件,不发送模型请求。</p></div><button className="button primary" disabled={working} onClick={() => void act(inspect)}><Activity size={15} />开始本地巡检</button></div><label className="mc-checkbox"><input type="checkbox" checked={autoInspect} onChange={event => setAutoInspect(event.target.checked)} />在此页面每30秒检查,离开即停止</label>{operations ? <><p className="mc-help">{new Date(operations.checkedAt).toLocaleString()} · v{operations.version} · {operations.activeTasks} 活动任务 · {operations.queue} 排队</p><div className="mc-checks">{operations.checks.map(value => <article key={value.id}><span className={'mc-state mc-state-' + value.status}>{states[value.status] || value.status}</span><div><h4>{value.title}</h4><p>{value.detail}</p></div></article>)}</div><p className="mc-help">{operations.scope}</p></> : <p className="mc-empty">执行一次本地检查,查看实际结果与检查范围。</p>}</>}
{tab === 'operations' && <><div className="mc-section-title"><div><h3>运行巡检</h3><p>核对宿主、任务、来源与数据,按页检查历史工件。</p></div><button className="button primary" disabled={working} onClick={() => void act(() => inspect())}><Activity size={15} />开始本地巡检</button></div><label className="mc-checkbox"><input type="checkbox" checked={autoInspect} onChange={event => setAutoInspect(event.target.checked)} />在此页面每30秒检查,离开即停止</label>{operations ? <><p className="mc-help">{new Date(operations.checkedAt).toLocaleString()} · v{operations.version} · {operations.activeTasks} 活动任务 · {operations.queue} 排队</p><div className="mc-checks">{operations.checks.map(value => <article key={value.id}><span className={'mc-state mc-state-' + value.status}>{states[value.status] || value.status}</span><div><h4>{value.title}</h4><p>{value.detail}</p></div></article>)}</div>{operations.artifacts && <div className="mc-operations-pages" aria-label="历史工件巡检分页"><p className="mc-help">本页核对 {operations.artifacts.checked} 项 · 全部 {operations.artifacts.total} 项 · 本页未覆盖 {operations.artifacts.remaining} 项</p><div className="mc-row-actions"><button className="button" disabled={working || operations.artifacts.olderOffset === null} onClick={() => void act(() => inspect(operations.artifacts!.olderOffset!))}>检查更早工件</button><button className="button" disabled={working || operations.artifacts.newerOffset === null} onClick={() => void act(() => inspect(operations.artifacts!.newerOffset!))}>检查较新工件</button></div>{operations.artifacts.results.filter(value => !value.passed).map(value => <p className="mc-help error" key={value.id}>工件 {value.id}:{value.error}</p>)}</div>}<p className="mc-help">{operations.scope}</p></> : <p className="mc-empty">执行一次本地检查,查看实际结果与检查范围。</p>}</>}
</div>}
</section>;
}
+2 -1
View File
@@ -16,6 +16,7 @@ export function inspectHostInstallation(directory, { full = false } = {}) {
if (typeof version !== 'string' || !/^\d+\.\d+\.\d+$/.test(version)) throw hostError('宿主安装版本无效。');
const files = new Set(['dist-server/server.mjs', 'dist-server/hot-upgrade.mjs', 'dist-client/index.html']);
if (!manifest || fs.existsSync(path.join(root, 'dist-server/host-launcher.mjs'))) files.add('dist-server/host-launcher.mjs');
if (fs.existsSync(path.join(root, 'dist-server/install-manager.mjs'))) files.add('dist-server/install-manager.mjs');
for (const relative of ['dist-desktop/main.cjs', 'dist-desktop/preload.cjs']) if (fs.existsSync(path.join(root, relative))) files.add(relative);
const names = new Map();
for (const row of manifest?.files ?? []) {
@@ -38,7 +39,7 @@ export function inspectHostInstallation(directory, { full = false } = {}) {
export function desktopExecutableIdentity(directory) {
const root = fs.realpathSync.native(directory), packaged = path.join(root, 'desktop/AgentWorkbench.exe');
const relative = fs.existsSync(packaged) ? 'desktop/AgentWorkbench.exe' : 'node_modules/electron/dist/electron.exe';
const relative = fs.existsSync(packaged) ? 'desktop/AgentWorkbench.exe' : fs.existsSync(path.join(root, 'runtime/electron/electron.exe')) ? 'runtime/electron/electron.exe' : 'node_modules/electron/dist/electron.exe';
const executable = binaryIdentity(ownedChild(root, relative));
const manifestFile = path.join(root, 'MANIFEST.json');
if (fs.existsSync(manifestFile)) {
+228
View File
@@ -0,0 +1,228 @@
import fs from 'node:fs';
import path from 'node:path';
import { randomUUID, createHash } from 'node:crypto';
import { DatabaseSync } from 'node:sqlite';
import net from 'node:net';
import { isDeepStrictEqual } from 'node:util';
import { HostController } from './host-controller.mjs';
import { inspectHostInstallation } from './app-installation.mjs';
import { observeWindowsProcess, protectUserDirectory, binaryIdentity } from './process-identity.mjs';
import { ownedChild, readState, writeState, samePath, assertLocalTree } from './file-state.mjs';
import { upgradeRunning } from '../../../scripts/upgrade-running.mjs';
import { canonicalHost, hostError } from '../../shared/contracts/desktop-host.mjs';
const digest = value => createHash('sha256').update(value).digest('hex');
const inside = (root, value) => samePath(root, value) || path.resolve(value).toLowerCase().startsWith(path.resolve(root).toLowerCase() + path.sep);
const fail = message => hostError(message, 'INSTALLATION_REJECTED', 409);
export function validateInstalledVersion(directory) {
const installation = inspectHostInstallation(directory, { full: true });
if (installation.kind !== 'portable') throw fail('安装候选需要完整便携发行清单。');
const manifest = readState(path.join(installation.root, 'MANIFEST.json'), 16 * 1024 * 1024), actual = [];
const walk = relative => { for (const entry of fs.readdirSync(path.join(installation.root, relative), { withFileTypes: true })) {
const next = path.posix.join(relative, entry.name); ownedChild(installation.root, next);
if (entry.isDirectory()) walk(next); else if (entry.isFile()) actual.push(next); else throw fail('安装候选含有链接或非常规文件。');
} }; walk('');
const declared = manifest.files.map(value => value.path).concat('MANIFEST.json').sort();
if (!isDeepStrictEqual(actual.sort(), declared)) throw fail('安装候选的实际文件范围与清单不同。');
for (const relative of ['AgentWorkbench.exe', 'runtime/node.exe', 'desktop/AgentWorkbench.exe', 'desktop/resources/app/main.cjs', 'desktop/resources/app/package.json', 'dist-desktop/main.cjs', 'dist-desktop/preload.cjs', 'dist-server/install-manager.mjs']) if (!declared.includes(relative)) throw fail('桌面安装缺少必要运行文件。');
// Full-manifest verification covers all shipped bytes; the host identity is
// deliberately the same narrower loaded-input identity used by HostController.
return inspectHostInstallation(directory);
}
export function snapshotPersistentData(dataRoot) {
assertLocalTree(dataRoot); const databaseFile = path.join(dataRoot, 'workbench.sqlite'), tables = {};
if (fs.existsSync(databaseFile)) {
ownedChild(dataRoot, 'workbench.sqlite'); const database = new DatabaseSync(databaseFile, { readOnly: true });
try {
for (const { name } of database.prepare("SELECT name FROM sqlite_schema WHERE type='table' AND name NOT LIKE 'sqlite_%' ORDER BY name").all()) {
if (!/^[a-z_]+$/.test(name)) throw fail('原数据库包含无法核对的表名。');
const rows = database.prepare('SELECT * FROM "' + name + '"').all().filter(row => !(name === 'metadata' && row.key === 'runtimeOwner'));
const hashes = rows.map(row => digest(JSON.stringify(canonicalHost(row)))).sort(); tables[name] = { count: hashes.length, hashes };
}
} finally { database.close(); }
}
const artifacts = [], artifactRoot = path.join(dataRoot, 'artifacts');
if (fs.existsSync(artifactRoot)) {
const walk = relative => { for (const entry of fs.readdirSync(path.join(artifactRoot, relative), { withFileTypes: true })) {
const next = path.posix.join(relative, entry.name), file = ownedChild(dataRoot, 'artifacts/' + next);
if (entry.isDirectory()) walk(next); else if (entry.isFile()) { const bytes = fs.readFileSync(file); artifacts.push({ path: next, bytes: bytes.length, sha256: digest(bytes) }); } else throw fail('原工件目录包含非常规文件。');
} }; walk('');
}
const files = ['config.json', 'projects.json'].filter(relative => fs.existsSync(path.join(dataRoot, relative))).map(relative => ({ path: relative, sha256: digest(fs.readFileSync(ownedChild(dataRoot, relative))) }));
return { tables, artifacts: artifacts.sort((a, b) => a.path.localeCompare(b.path)), files, scope: 'Every persistent database row except runtimeOwner, every original artifact byte and existing public config/project files; no credential is decrypted or returned.' };
}
export class InstallationManager {
constructor({ installRoot, dataRoot, port = 4318, candidateRoot = null, timeoutMs = 60000 }) {
for (const value of [installRoot, dataRoot]) if (typeof value !== 'string' || !path.isAbsolute(value)) throw fail('安装和数据目录必须为本机绝对路径。');
if (inside(installRoot, dataRoot) || inside(dataRoot, installRoot) || !Number.isInteger(port) || port < 1 || port > 65535) throw fail('程序与用户数据需要独立目录及有效本机端口。');
assertLocalTree(installRoot, { missing: true }); assertLocalTree(dataRoot, { missing: true });
fs.mkdirSync(installRoot, { recursive: true }); fs.mkdirSync(dataRoot, { recursive: true });
this.installRoot = fs.realpathSync.native(installRoot); this.dataRoot = fs.realpathSync.native(dataRoot); this.port = port; this.timeoutMs = timeoutMs;
this.candidateRoot = candidateRoot ? fs.realpathSync.native(candidateRoot) : null;
this.recordFile = ownedChild(this.installRoot, 'current.json', { missing: true });
this.stateRoot = ownedChild(this.installRoot, '.installation', { missing: true }); fs.mkdirSync(this.stateRoot, { recursive: true }); protectUserDirectory(this.stateRoot);
}
current() {
if (!fs.existsSync(this.recordFile)) return null;
const value = readState(this.recordFile, 16384);
if (value.schema !== 1 || value.app !== 'agent-workbench-installation' || !/^[a-f0-9-]{36}$/.test(value.installId ?? '') || !Number.isSafeInteger(value.revision)
|| value.revision < 1 || !samePath(value.dataRoot ?? '', this.dataRoot) || value.port !== this.port) throw fail('当前安装登记无法核对,保留原记录。');
const root = this.versionRoot(value.active), actual = validateInstalledVersion(root);
if (actual.version !== value.active.version || actual.manifestSha256 !== value.active.manifestSha256 || actual.identitySha256 !== value.active.runtimeIdentity) throw fail('当前活动版本的实际程序与原登记不同。');
if (value.previous) this.versionRoot(value.previous);
return value;
}
versionRoot(version) {
if (!version || !/^[A-Za-z0-9][A-Za-z0-9._-]{0,159}$/.test(version.directory ?? '') || !/^\d+\.\d+\.\d+$/.test(version.version ?? '')
|| !/^[a-f0-9]{64}$/.test(version.manifestSha256 ?? '') || !/^[a-f0-9]{64}$/.test(version.runtimeIdentity ?? '')) throw fail('原活动版本登记无效。');
return ownedChild(this.installRoot, 'versions/' + version.directory);
}
candidate() {
if (!this.candidateRoot) throw fail('没有指定独立安装候选。');
const expected = path.join(this.installRoot, 'versions', path.basename(this.candidateRoot));
if (!samePath(expected, this.candidateRoot)) throw fail('新版本只能位于当前安装的独立versions目录。');
const identity = validateInstalledVersion(this.candidateRoot);
return { directory: path.basename(identity.root), version: identity.version, manifestSha256: identity.manifestSha256, runtimeIdentity: identity.identitySha256 };
}
async host() {
const infoFile = ownedChild(this.dataRoot, 'service-info.json', { missing: true });
if (!fs.existsSync(infoFile)) { await this.assertFreePort(); return null; }
const info = readState(infoFile), actual = observeWindowsProcess(info.pid);
if (!actual || info.createdAt && info.createdAt !== actual.createdAt) {
await this.assertFreePort();
return null;
}
if (!info.instanceId || !info.createdAt || !info.runtimeIdentity || !info.runtimeRoot || info.port !== this.port || !samePath(info.dataRoot ?? '', this.dataRoot)) throw fail('旧执行宿主没有可核验的桌面身份。可先暂存安装候选,再通过保留状态的升级流程接入。');
const controller = new HostController({ appRoot: info.runtimeRoot, dataRoot: this.dataRoot, port: this.port, nodePath: process.execPath, timeoutMs: this.timeoutMs });
const connected = await controller.connect(); if (!connected) throw fail('原执行进程仍活动,接口尚不可核对。');
const status = await controller.status();
if (status.state !== 'ready' || status.activity.active || status.desktopWindows.count) throw fail('先等待原任务、审批、工具或模型请求结束,并关闭桌面窗口;后台宿主可保持运行。');
return { controller, identity: connected.identity, status };
}
async assertFreePort() {
await new Promise((resolve, reject) => {
const socket = net.createConnection({ host: '127.0.0.1', port: this.port });
socket.setTimeout(1500);
socket.once('connect', () => { socket.destroy(); reject(fail('本机端口被未知或未登记服务占用,保留原安装。')); });
socket.once('timeout', () => { socket.destroy(); reject(fail('原端口状态无法核对。')); });
socket.once('error', error => { socket.destroy(); error.code === 'ECONNREFUSED' ? resolve() : reject(fail('原端口状态无法核对。')); });
});
}
async lock(action) {
const directory = ownedChild(this.stateRoot, 'operation.lock', { missing: true }), nonce = randomUUID(), observed = observeWindowsProcess(process.pid);
try { fs.mkdirSync(directory); } catch (error) {
if (error.code !== 'EEXIST') throw error;
const owner = readState(ownedChild(directory, 'owner.json'), 16384), actual = observeWindowsProcess(owner.pid);
if (actual && actual.createdAt === owner.createdAt) throw fail('原安装操作仍在运行。');
const archive = ownedChild(this.stateRoot, 'stale-lock-' + randomUUID(), { missing: true }); fs.renameSync(directory, archive); fs.mkdirSync(directory);
}
protectUserDirectory(directory);
const file = path.join(directory, 'owner.json'); writeState(file, { nonce, pid: process.pid, createdAt: observed.createdAt, userSid: observed.userSid });
try { return await action(); } finally { if (fs.existsSync(file) && readState(file).nonce === nonce) { fs.unlinkSync(file); fs.rmdirSync(directory); } }
}
async preflight({ stageOnly = false } = {}) {
const current = this.current(); this.inspectRoot(current); const host = stageOnly ? null : await this.host();
return { allowed: true, phase: stageOnly ? 'stage-only' : 'preflight', current: current?.active ?? null,
host: host ? { pid: host.identity.pid, instanceId: host.identity.instanceId, unresolvedTools: host.status.activity.unresolvedTools } : null,
dataRoot: this.dataRoot, dataPolicy: 'preserve-original-data' };
}
inspectRoot(current) {
for (const entry of fs.readdirSync(this.installRoot, { withFileTypes: true })) {
ownedChild(this.installRoot, entry.name);
if (!((entry.isDirectory() && ['.installation', 'versions'].includes(entry.name)) || (entry.isFile() && (['current.json', 'AgentWorkbench.exe'].includes(entry.name) || /^unins\d{3}\.(exe|dat|msg)$/.test(entry.name))))) throw fail('程序根目录存在未登记内容,不覆盖原目录。');
}
const bootstrap = ownedChild(this.installRoot, 'AgentWorkbench.exe', { missing: true });
if (fs.existsSync(bootstrap)) {
const root = current ? this.versionRoot(current.active) : this.candidateRoot;
if (!root || binaryIdentity(bootstrap).sha256 !== binaryIdentity(ownedChild(root, 'AgentWorkbench.exe')).sha256) throw fail('原根启动器与所属发行不一致,不复用或覆盖未知程序。');
}
}
async activate({ stageOnly = false, beforePointer = null, afterPointer = null } = {}) {
return this.lock(async () => {
const candidate = this.candidate(), old = this.current(); this.inspectRoot(old); const priorHost = stageOnly ? null : await this.host();
const snapshot = snapshotPersistentData(this.dataRoot), id = randomUUID(), receiptFile = path.join(this.stateRoot, 'operation-' + id + '.json');
const receipt = { schema: 1, id, state: 'prepared', candidate, original: old?.active ?? null, dataRoot: this.dataRoot, snapshot, stageOnly, startedAt: new Date().toISOString() };
writeState(receiptFile, receipt);
if (stageOnly) { writeState(receiptFile, { ...receipt, state: 'staged' }); return { phase: 'staged', candidate, receiptFile, activated: false }; }
let upgraded = false, next = null, pointerPublished = false;
const originalPointer = old ? fs.readFileSync(this.recordFile) : null;
const bootstrapFile = ownedChild(this.installRoot, 'AgentWorkbench.exe', { missing: true });
const originalBootstrap = fs.existsSync(bootstrapFile) ? fs.readFileSync(bootstrapFile) : null;
const candidateBootstrap = fs.readFileSync(ownedChild(this.candidateRoot, 'AgentWorkbench.exe'));
let bootstrapPublished = false;
const replaceBootstrap = bytes => {
const temporary = ownedChild(this.stateRoot, 'bootstrap-' + randomUUID() + '.tmp', { missing: true });
const descriptor = fs.openSync(temporary, 'wx', 0o600);
try { fs.writeFileSync(descriptor, bytes); fs.fsyncSync(descriptor); } finally { fs.closeSync(descriptor); }
try { fs.renameSync(temporary, bootstrapFile); } finally { if (fs.existsSync(temporary)) fs.unlinkSync(temporary); }
};
try {
if (priorHost && !samePath(priorHost.identity.runtimeRoot, this.candidateRoot)) {
await upgradeRunning({ url: priorHost.controller.url, pid: priorHost.identity.pid, currentRoot: priorHost.identity.appRoot, handlerRoot: priorHost.identity.runtimeRoot, newRoot: this.candidateRoot }); upgraded = true;
const nextHost = await this.host();
if (!nextHost || nextHost.identity.pid !== priorHost.identity.pid || nextHost.identity.instanceId !== priorHost.identity.instanceId || nextHost.identity.runtimeIdentity !== candidate.runtimeIdentity) throw fail('新处理器没有保持原宿主实例。');
}
const after = snapshotPersistentData(this.dataRoot); if (!isDeepStrictEqual(snapshot, after)) throw fail('安装更新改变了原持久行或工件。');
if (beforePointer) await beforePointer();
if (!isDeepStrictEqual(old, this.current())) throw fail('原安装指针已发生变化,停止发布候选。');
if (!isDeepStrictEqual(candidate, this.candidate())) throw fail('新候选在预检后发生变化,停止发布候选。');
const actualBootstrap = fs.existsSync(bootstrapFile) ? fs.readFileSync(bootstrapFile) : null;
if (!isDeepStrictEqual(actualBootstrap, originalBootstrap)) throw fail('原启动器在预检后发生变化,停止发布候选。');
if (!isDeepStrictEqual(originalBootstrap, candidateBootstrap)) { replaceBootstrap(candidateBootstrap); bootstrapPublished = true; }
next = { schema: 1, app: 'agent-workbench-installation', installId: old?.installId ?? randomUUID(), revision: (old?.revision ?? 0) + 1,
dataRoot: this.dataRoot, port: this.port, active: candidate, previous: old?.active ?? null, activatedAt: new Date().toISOString() };
writeState(this.recordFile, next);
pointerPublished = true;
if (afterPointer) await afterPointer(); // Explicit in-process QA fault fixture, never exposed by the CLI.
this.inspectRoot(next);
writeState(receiptFile, { ...receipt, state: 'activated', hostRetained: upgraded, finishedAt: new Date().toISOString() });
return { phase: 'activated', active: candidate, receiptFile, hostRetained: upgraded, dataPreserved: true };
} catch (error) {
let rollback = 'pointer-preserved';
try {
if (pointerPublished && fs.existsSync(this.recordFile)) {
if (!isDeepStrictEqual(readState(this.recordFile), next)) throw fail('发布后的指针被其他操作改变,不能覆盖未知记录。');
if (originalPointer) {
const temporary = ownedChild(this.installRoot, '.rollback-' + id + '.json', { missing: true });
fs.writeFileSync(temporary, originalPointer, { flag: 'wx' }); fs.renameSync(temporary, this.recordFile);
} else fs.unlinkSync(this.recordFile);
} else if (pointerPublished && old) throw fail('发布后的指针已丢失,回退需要核对。');
if (bootstrapPublished) {
if (!fs.existsSync(bootstrapFile) || !fs.readFileSync(bootstrapFile).equals(candidateBootstrap)) throw fail('发布后的启动器被其他操作改变,不能覆盖未知程序。');
if (originalBootstrap) replaceBootstrap(originalBootstrap); else fs.unlinkSync(bootstrapFile);
}
if (upgraded) {
await upgradeRunning({ url: priorHost.controller.url, pid: priorHost.identity.pid, currentRoot: priorHost.identity.appRoot, handlerRoot: this.candidateRoot, newRoot: priorHost.identity.runtimeRoot });
const restored = await priorHost.controller.connect(); if (!restored || restored.identity.instanceId !== priorHost.identity.instanceId || restored.identity.pid !== priorHost.identity.pid) throw fail('原宿主回退仍需核对。');
rollback = 'original-host-and-pointer-restored';
}
if (!isDeepStrictEqual(snapshot, snapshotPersistentData(this.dataRoot)) || (old && !fs.readFileSync(this.recordFile).equals(originalPointer))) throw fail('原持久数据或安装指针回退仍需核对。');
if (!isDeepStrictEqual(fs.existsSync(bootstrapFile) ? fs.readFileSync(bootstrapFile) : null, originalBootstrap)) throw fail('原启动器回退仍需核对。');
} catch (rollbackError) {
try { writeState(receiptFile, { ...receipt, state: 'rollback-unverified', error: error.message, rollbackError: rollbackError.message }); } catch {}
throw fail('安装失败,原宿主或指针回退尚待核对。请保留原操作记录,不重新执行任务。');
}
try { writeState(receiptFile, { ...receipt, state: 'failed', error: error.message, rollback }); } catch {}
throw error;
}
});
}
async prepareUninstall() {
return this.lock(async () => {
const current = this.current(); if (!current) throw fail('没有可核对的本产品安装登记。');
this.inspectRoot(current);
const snapshot = snapshotPersistentData(this.dataRoot), host = await this.host();
if (host) await host.controller.stop();
if (!isDeepStrictEqual(snapshot, snapshotPersistentData(this.dataRoot))) throw fail('停止后原持久数据变化,卸载仍需核对。');
const receiptFile = path.join(this.stateRoot, 'uninstall-' + randomUUID() + '.json');
const result = { allowed: true, phase: 'uninstall-ready', dataRoot: this.dataRoot, dataPolicy: 'preserve-original-data', hostExited: !!host, active: current.active, snapshot };
writeState(receiptFile, result);
if (!isDeepStrictEqual(current, this.current())) throw fail('卸载期间原指针发生变化,保留原记录。');
fs.renameSync(this.recordFile, ownedChild(this.stateRoot, 'uninstalled-' + current.installId + '-' + current.revision + '.json', { missing: true }));
return { ...result, snapshot: undefined, receiptFile };
});
}
}
+24
View File
@@ -0,0 +1,24 @@
import fs from 'node:fs';
import path from 'node:path';
import { randomUUID } from 'node:crypto';
import { ownedChild, samePath } from './desktop/file-state.mjs';
// A starter project is user data. Versioned program directories remain immutable,
// and opening a new runtime version never inserts or reorders existing projects.
export function initializeExampleProject(store, appDirectory) {
const destination = path.join(store.directory, 'projects', 'starter-project');
if (store.projects.length) return store.projects.find(value => samePath(value.root, destination) || value.root.replaceAll('\\', '/').endsWith('/examples/starter-project')) ?? null;
if (!fs.existsSync(path.join(appDirectory, 'examples/starter-project'))) return null;
const source = ownedChild(appDirectory, 'examples/starter-project');
const parent = ownedChild(store.directory, 'projects', { missing: true }); fs.mkdirSync(parent, { recursive: true });
const target = ownedChild(store.directory, 'projects/starter-project', { missing: true });
if (!fs.existsSync(target)) {
const temporary = ownedChild(parent, '.starter-project-' + randomUUID(), { missing: true });
// A failed copy remains in its exclusive temporary directory for inspection;
// an existing destination is never merged with or overwritten by a template.
fs.cpSync(source, temporary, { recursive: true, errorOnExist: true, force: false });
if (fs.existsSync(target)) throw Error('示例目标目录已被另一个操作创建,保留原文件。');
fs.renameSync(temporary, target);
}
return store.addProject(target, { name: '示例工程' });
}
+86
View File
@@ -0,0 +1,86 @@
using System;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Security.Cryptography;
using System.Web.Script.Serialization;
using System.Windows.Forms;
// A fixed, user-level bootstrap. The independent Node host retains task state;
// this program only validates an immutable release and starts its desktop client.
internal static class Launcher {
static bool hidden;
static string Full(string value) { return Path.GetFullPath(value).TrimEnd(Path.DirectorySeparatorChar); }
static bool Same(string a, string b) { return String.Equals(Full(a), Full(b), StringComparison.OrdinalIgnoreCase); }
static bool Inside(string root, string file) { return Full(file).StartsWith(Full(root) + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase); }
static void Local(string file) {
string full = Full(file), current = Path.GetPathRoot(full);
if (current.StartsWith("\\\\")) throw new Exception("程序需要本机目录。");
foreach (string part in full.Substring(current.Length).Split(Path.DirectorySeparatorChar)) {
if (part.IndexOf(':') >= 0) throw new Exception("路径包含无效文件名。");
current = Path.Combine(current, part);
if ((File.Exists(current) || Directory.Exists(current)) && (File.GetAttributes(current) & FileAttributes.ReparsePoint) != 0) throw new Exception("程序路径不能使用链接或重解析目录。");
}
}
static Dictionary<string, object> Json(string file) {
Local(file); if (new FileInfo(file).Length > 16 * 1024 * 1024) throw new Exception("安装清单过大。");
JavaScriptSerializer reader = new JavaScriptSerializer(); reader.MaxJsonLength = 16 * 1024 * 1024;
return reader.Deserialize<Dictionary<string, object>>(File.ReadAllText(file, Encoding.UTF8));
}
static string Str(Dictionary<string, object> value, string key) { object result; if (!value.TryGetValue(key, out result) || !(result is string)) throw new Exception("安装登记缺少 " + key); return (string)result; }
static string Hash(string file) { Local(file); using (SHA256 hash = SHA256.Create()) using (FileStream input = File.OpenRead(file)) return BitConverter.ToString(hash.ComputeHash(input)).Replace("-", "").ToLowerInvariant(); }
static string Quote(string value) { if (value.IndexOf('"') >= 0 || value.EndsWith("\\")) throw new Exception("启动参数无效。"); return "\"" + value + "\""; }
static void Verify(string root, string expected, string version) {
string file = Path.Combine(root, "MANIFEST.json"); Dictionary<string, object> manifest = Json(file);
if (Str(manifest, "app") != "agent-workbench" || Str(manifest, "kind") != "portable" || Str(manifest, "platform") != "win32-x64") throw new Exception("需要完整 Windows 桌面发行。");
if (version != null && Str(manifest, "version") != version) throw new Exception("安装版本登记不一致。");
if (expected != null && Hash(file) != expected) throw new Exception("原安装清单发生变化。");
HashSet<string> declared = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
foreach (object item in (IEnumerable)manifest["files"]) {
Dictionary<string, object> row = (Dictionary<string, object>)item; string relative = Str(row, "path");
if (relative.IndexOf('\\') >= 0 || relative.IndexOf(':') >= 0 || relative.StartsWith("/") || Array.IndexOf(relative.Split('/'), "..") >= 0 || !declared.Add(relative) || declared.Count > 60000) throw new Exception("清单包含重复或越界文件。");
string source = Path.Combine(root, relative.Replace('/', Path.DirectorySeparatorChar));
if (!Inside(root, source) || !File.Exists(source) || new FileInfo(source).Length != Convert.ToInt64(row["bytes"]) || Hash(source) != Str(row, "sha256")) throw new Exception("发行文件与原清单不同:" + relative);
}
foreach (string required in new string[] { "runtime/node.exe", "desktop/AgentWorkbench.exe", "dist-server/server.mjs", "dist-server/install-manager.mjs", "dist-desktop/main.cjs", "dist-desktop/preload.cjs" }) if (!declared.Contains(required)) throw new Exception("桌面发行缺少 " + required);
string[] actual = Directory.GetFiles(root, "*", SearchOption.AllDirectories);
if (actual.Length != declared.Count + 1) throw new Exception("发行目录包含未登记文件。");
foreach (string value in actual) { Local(value); string relative = Full(value).Substring(Full(root).Length + 1).Replace('\\', '/'); if (relative != "MANIFEST.json" && !declared.Contains(relative)) throw new Exception("发行目录包含未登记文件。"); }
}
[STAThread] static int Main(string[] args) {
try {
string root = Full(Path.GetDirectoryName(Application.ExecutablePath)), data = Full(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "AgentWorkbench")); int port = 4318;
string selectedData = null; int? selectedPort = null; bool uninstall = false;
for (int i = 0; i < args.Length; i++) {
if (args[i] == "--hidden-window" && !hidden) { hidden = true; continue; }
if (args[i] == "--uninstall-preflight" && !uninstall) { uninstall = true; continue; }
if (args[i] == "--data-root" && selectedData == null && ++i < args.Length) { selectedData = Full(args[i]); continue; }
if (args[i] == "--port" && !selectedPort.HasValue && ++i < args.Length) { selectedPort = Int32.Parse(args[i]); continue; }
throw new Exception("不支持的桌面启动参数。");
}
string recordFile = Path.Combine(root, "current.json"), expected = null, version = null, release = root;
if (File.Exists(recordFile)) {
Dictionary<string, object> record = Json(recordFile), active = (Dictionary<string, object>)record["active"];
if (Convert.ToInt32(record["schema"]) != 1 || Str(record, "app") != "agent-workbench-installation" || !Regex.IsMatch(Str(record, "installId"), "^[a-f0-9-]{36}$") || Convert.ToInt64(record["revision"]) < 1) throw new Exception("安装登记无效。");
string directory = Str(active, "directory"); if (!Regex.IsMatch(directory, "^[A-Za-z0-9][A-Za-z0-9._-]{0,159}$")) throw new Exception("活动版本目录无效。");
release = Full(Path.Combine(root, "versions", directory)); if (!Inside(Path.Combine(root, "versions"), release)) throw new Exception("活动版本越界。");
expected = Str(active, "manifestSha256"); version = Str(active, "version");
if (!Regex.IsMatch(expected, "^[a-f0-9]{64}$") || !Regex.IsMatch(Str(active, "runtimeIdentity"), "^[a-f0-9]{64}$") || !Regex.IsMatch(version, "^\\d+\\.\\d+\\.\\d+$")) throw new Exception("原版本身份无效。");
data = Full(Str(record, "dataRoot")); port = Convert.ToInt32(record["port"]);
if ((selectedData != null && !Same(selectedData, data)) || (selectedPort.HasValue && selectedPort.Value != port)) throw new Exception("已安装应用使用登记的数据目录及端口。");
} else { if (uninstall) throw new Exception("没有可核对的安装登记。"); if (selectedData != null) data = selectedData; if (selectedPort.HasValue) port = selectedPort.Value; }
if (port < 1 || port > 65535 || Same(root, data) || Inside(root, data) || Inside(data, root)) throw new Exception("程序与用户数据需要独立目录及有效端口。");
Local(root); Local(data); Local(release); Verify(release, expected, version);
ProcessStartInfo launch = new ProcessStartInfo(uninstall ? Path.Combine(release, "runtime", "node.exe") : Path.Combine(release, "desktop", "AgentWorkbench.exe"));
launch.Arguments = uninstall ? Quote(Path.Combine(release, "dist-server", "install-manager.mjs")) + " uninstall --install-root " + Quote(root) + " --data-root " + Quote(data) + " --port " + port : "--app-root " + Quote(release) + " --data-root " + Quote(data) + " --port " + port + (hidden ? " --hidden-window" : "");
launch.WorkingDirectory = release; launch.UseShellExecute = false; launch.CreateNoWindow = true;
List<string> keys = new List<string>(); foreach (string key in launch.EnvironmentVariables.Keys) keys.Add(key);
Regex allowed = new Regex("^(path|pathext|systemroot|systemdrive|windir|comspec|temp|tmp|userprofile|homedrive|homepath|appdata|localappdata|programfiles(?:\\(x86\\))?|commonprogramfiles(?:\\(x86\\))?|lang|lc_all|AGENT_WORKBENCH_(?:DEEPSEEK_ROOT|PURGE_ROOT|PYTHON_PATH|TEST_PYTHON))$", RegexOptions.IgnoreCase);
foreach (string key in keys) if (!allowed.IsMatch(key)) launch.EnvironmentVariables.Remove(key);
using (Process child = Process.Start(launch)) { if (uninstall) { child.WaitForExit(); return child.ExitCode; } } return 0;
} catch (Exception error) { if (!hidden) MessageBox.Show(error.Message, "Agent Workbench 无法打开", MessageBoxButtons.OK, MessageBoxIcon.Error); return 1; }
}
}
+14
View File
@@ -0,0 +1,14 @@
import { InstallationManager } from '../core/desktop/install-manager.mjs';
const args = process.argv.slice(2), command = args.shift(), options = {};
if (!['preflight', 'activate', 'uninstall'].includes(command)) throw new Error('Unsupported installation operation.');
while (args.length) {
const flag = args.shift();
if (flag === '--stage-only' && !options.stageOnly) { options.stageOnly = true; continue; }
if (!['--install-root', '--data-root', '--candidate-root', '--port'].includes(flag) || !args.length || options[flag] !== undefined) throw new Error('Unsupported or repeated installation field.');
options[flag] = args.shift();
}
try {
const manager = new InstallationManager({ installRoot: options['--install-root'], dataRoot: options['--data-root'], candidateRoot: options['--candidate-root'], port: Number(options['--port'] || 4318) });
const result = command === 'preflight' ? await manager.preflight({ stageOnly: !!options.stageOnly }) : command === 'activate' ? await manager.activate({ stageOnly: !!options.stageOnly }) : await manager.prepareUninstall();
console.log(JSON.stringify(result));
} catch (error) { console.error(JSON.stringify({ success: false, code: error.code || 'INSTALLATION_FAILED', message: error.message })); process.exitCode = 1; }
+101
View File
@@ -0,0 +1,101 @@
[Setup]
AppId={{E914E883-46F9-4B82-B27F-BDB2B40DCC90}
AppName=Agent Workbench
AppVersion={#Version}
DefaultDirName={localappdata}\Programs\AgentWorkbench
DefaultGroupName=Agent Workbench
PrivilegesRequired=lowest
ArchitecturesAllowed=x64compatible
ArchitecturesInstallIn64BitMode=x64compatible
DisableProgramGroupPage=yes
UsePreviousAppDir=yes
OutputDir={#OutputRoot}
OutputBaseFilename={#OutputName}
SetupIconFile={#PortableRoot}\public\workbench-icon.ico
UninstallDisplayIcon={app}\AgentWorkbench.exe
Compression=lzma2/fast
SolidCompression=yes
CloseApplications=no
RestartApplications=no
ChangesAssociations=no
WizardStyle=modern
Uninstallable=yes
[Files]
Source: "{#PortableRoot}\runtime\node.exe"; DestName: "awb-install-node.exe"; Flags: dontcopy
Source: "{#PortableRoot}\dist-server\install-manager.mjs"; DestName: "awb-install-manager.mjs"; Flags: dontcopy
Source: "{#PortableRoot}\*"; DestDir: "{app}\versions\{#VersionDirectory}"; Flags: ignoreversion recursesubdirs createallsubdirs
Source: "{#PortableRoot}\AgentWorkbench.exe"; DestDir: "{app}"; Flags: onlyifdoesntexist
[Icons]
Name: "{group}\Agent Workbench"; Filename: "{app}\AgentWorkbench.exe"
Name: "{userdesktop}\Agent Workbench"; Filename: "{app}\AgentWorkbench.exe"; Tasks: desktopicon
[Tasks]
Name: "desktopicon"; Description: "创建桌面快捷方式"; Flags: unchecked
[Run]
Filename: "{app}\AgentWorkbench.exe"; Description: "打开 Agent Workbench"; Flags: nowait postinstall skipifsilent; Check: WasActivated
[Code]
var DataRoot: String; Port: String; StageOnly: Boolean; Activated: Boolean; ActivationFailed: Boolean;
function Quoted(Value: String): String;
begin
if (Pos('"', Value) > 0) or (Pos(#13, Value) > 0) or (Pos(#10, Value) > 0) then RaiseException('安装路径无效。');
Result := '"' + Value + '"';
end;
procedure LoadOptions;
begin
DataRoot := ExpandConstant('{param:DATA_ROOT|{localappdata}\AgentWorkbench}');
Port := ExpandConstant('{param:PORT|4318}');
StageOnly := ExpandConstant('{param:STAGE_ONLY|0}') = '1';
end;
function RunManager(Command: String; Candidate: Boolean): Boolean;
var Parameters: String; ExitCode: Integer;
begin
Parameters := Quoted(ExpandConstant('{tmp}\awb-install-manager.mjs')) + ' ' + Command +
' --install-root ' + Quoted(ExpandConstant('{app}')) + ' --data-root ' + Quoted(DataRoot) + ' --port ' + Quoted(Port);
if Candidate then Parameters := Parameters + ' --candidate-root ' + Quoted(ExpandConstant('{app}\versions\{#VersionDirectory}'));
if StageOnly then Parameters := Parameters + ' --stage-only';
Result := Exec(ExpandConstant('{tmp}\awb-install-node.exe'), Parameters, ExpandConstant('{tmp}'), SW_HIDE, ewWaitUntilTerminated, ExitCode) and (ExitCode = 0);
end;
function PrepareToInstall(var NeedsRestart: Boolean): String;
begin
LoadOptions;
ExtractTemporaryFile('awb-install-node.exe'); ExtractTemporaryFile('awb-install-manager.mjs');
if DirExists(ExpandConstant('{app}\versions\{#VersionDirectory}')) then begin
Result := '该独立版本目录已经存在。请保留原版本,使用新的安装候选。'; exit;
end;
if not RunManager('preflight', False) then Result := '安装预检未通过。请等待任务、审批与工具结束并关闭桌面窗口,保留后台执行宿主及原数据;端口和安装身份仍需核对。';
end;
procedure CurStepChanged(CurStep: TSetupStep);
begin
if CurStep = ssPostInstall then begin
ActivationFailed := True;
if not RunManager('activate', True) then RaiseException('候选激活失败;已尝试恢复原安装指针和执行宿主。请保留 .installation 操作收据核对结果。');
ActivationFailed := False;
Activated := not StageOnly;
end;
end;
function GetCustomSetupExitCode: Integer;
begin
if ActivationFailed then Result := 8 else Result := 0;
end;
function WasActivated: Boolean;
begin Result := Activated; end;
function InitializeUninstall: Boolean;
var ExitCode: Integer;
begin
{ The native bootstrap verifies the entire registered immutable release before
invoking its fixed uninstall manager. No installed script is executed first. }
Result := Exec(ExpandConstant('{app}\AgentWorkbench.exe'), '--hidden-window --uninstall-preflight', ExpandConstant('{app}'), SW_HIDE, ewWaitUntilTerminated, ExitCode) and (ExitCode = 0);
if not Result then MsgBox('卸载预检未通过。请先关闭桌面窗口并等待活动结束;原程序和用户数据保留。', mbError, MB_OK);
end;
+2 -9
View File
@@ -14,6 +14,7 @@ import { ConfigImporter } from '../core/models/config-import.mjs';
import { ProjectMemoryManager } from '../core/memory/project-memory.mjs';
import { workerForProject, workerConflict, assertWorkersResolved } from '../shared/contracts/workers.mjs';
import { hostAuthority } from '../core/desktop/host-authority.mjs';
import { inspectOperations } from './operations.mjs';
export function createSessionPublisher(clients) {
return session => {
@@ -170,15 +171,7 @@ return async (request, response) => {
}
}
if (method === 'GET' && route === '/api/operations') {
const checks = [];
const inspect = (id, title, action) => { try { checks.push({ id, title, status: 'passed', detail: action() }); } catch (cause) { checks.push({ id, title, status: 'failed', detail: provider.redact(cause.message) }); } };
inspect('node', '执行宿主', () => { if (Number(process.versions.node.split('.')[0]) < 24) throw new Error('需要Node.js24或以上。'); return process.version + ' · PID ' + process.pid; });
inspect('database', '任务数据库', () => { const rows = store.storage.database.prepare('PRAGMA quick_check').all(); if (rows.some(row => Object.values(row)[0] !== 'ok')) throw new Error('数据库一致性检查未通过。'); return 'SQLite quick_check通过;' + store.sessions.size + '个会话。'; });
inspect('artifacts', '最近执行工件', () => { const values = [...store.core.artifact.values()].slice(-50); for (const value of values) store.artifactStore.readBytes(value); return '逐字节核对最近' + values.length + '个工件;更早记录未在本次范围内。'; });
const center = provider.modelHub(store).view();
checks.push({ id: 'models', title: '模型连接', status: center.connections.some(value => value.status === 'configured' && value.model) ? 'configured' : 'attention', detail: center.connections.filter(value => value.enabled).length + '个启用连接;配置状态与真实模型响应分别记录。' });
return json(response, { version: APP_VERSION, checkedAt: new Date().toISOString(), checks, activeTasks: runtime.active.size,
queue: center.waiting, modelAttempts: center.attempts.length, modelRequests: 0, scope: '本地只读巡检;不发送模型请求、不执行项目命令。' });
return json(response, inspectOperations({ store, provider, runtime, server, appDirectory, version: APP_VERSION, parameters: url.searchParams }));
}
if (method === 'GET' && route === '/api/bootstrap') return json(response, {
token, version: APP_VERSION, config: { ...store.config, hasKey: provider.hasKey() },
+2 -2
View File
@@ -11,6 +11,7 @@ import { createRequestHandler, createSessionPublisher } from './app.mjs';
import { APP_VERSION } from './diagnostics.mjs';
import { ConfigImporter } from '../core/models/config-import.mjs';
import { hostAuthority } from '../core/desktop/host-authority.mjs';
import { initializeExampleProject } from '../core/initial-example-project.mjs';
const appDirectory = process.env.AGENT_WORKBENCH_APP_DIR || path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const dataDirectory = process.env.AGENT_WORKBENCH_DATA_DIR || path.join(process.env.LOCALAPPDATA || path.join(os.homedir(), '.local', 'share'), 'AgentWorkbench');
@@ -34,8 +35,7 @@ const modelImportSync = setInterval(() => {
}, 60000);
modelImportSync.unref();
try {
const exampleRoot = path.join(appDirectory, 'examples', 'starter-project');
if (fs.existsSync(exampleRoot)) exampleProject = store.addProject(exampleRoot);
exampleProject = initializeExampleProject(store, appDirectory);
} catch {}
store.on('update', createSessionPublisher(clients));
+57
View File
@@ -0,0 +1,57 @@
import fs from 'node:fs';
import path from 'node:path';
import { inspectHostInstallation } from '../core/desktop/app-installation.mjs';
import { binaryIdentity } from '../core/desktop/process-identity.mjs';
import { canonicalHost } from '../shared/contracts/desktop-host.mjs';
export function inspectOperations({ store, provider, runtime, server, appDirectory, version, parameters = new URLSearchParams() }) {
for (const key of parameters.keys()) if (!['artifactOffset', 'artifactLimit'].includes(key) || parameters.getAll(key).length !== 1) throw Object.assign(Error('巡检分页字段无效。'), { status: 400 });
const number = (key, fallback, minimum, maximum) => {
const raw = parameters.get(key); if (raw === null) return fallback;
if (!/^(0|[1-9]\d*)$/.test(raw) || !Number.isSafeInteger(Number(raw)) || Number(raw) < minimum || Number(raw) > maximum) throw Object.assign(Error('巡检分页范围无效。'), { status: 400 });
return Number(raw);
};
const all = [...store.core.artifact.values()], limit = number('artifactLimit', 50, 1, 100), offset = number('artifactOffset', Math.max(0, all.length - limit), 0, all.length);
const checks = [], check = (id, title, action) => { try { const result = action(); checks.push({ id, title, status: 'passed', ...(typeof result === 'string' ? { detail: result } : result) }); } catch (error) { checks.push({ id, title, status: 'failed', detail: provider.redact(error.message) }); } };
check('node', '执行宿主', () => { if (Number(process.versions.node.split('.')[0]) < 24) throw Error('需要Node.js24或以上。'); return process.version + ' · PID ' + process.pid; });
check('database', '任务数据库', () => { const rows = store.storage.database.prepare('PRAGMA quick_check').all(); if (rows.some(row => Object.values(row)[0] !== 'ok')) throw Error('数据库一致性检查未通过。'); return 'SQLite quick_check通过;' + store.sessions.size + '个会话。'; });
const inspected = [];
for (const value of all.slice(offset, offset + limit)) { try { store.artifactStore.readBytes(value); inspected.push({ id: value.id, sha256: value.sha256, bytes: value.bytes, passed: true }); } catch (error) { inspected.push({ id: value.id, passed: false, error: provider.redact(error.message) }); } }
const artifacts = { offset, limit, checked: inspected.length, total: all.length, olderOffset: offset > 0 ? Math.max(0, offset - limit) : null,
newerOffset: offset + inspected.length < all.length ? offset + inspected.length : null, remaining: all.length - inspected.length, results: inspected };
checks.push({ id: 'artifacts', title: '原执行工件', status: inspected.every(value => value.passed) ? 'passed' : 'failed', detail: '本次逐字节核对第' + (all.length ? offset + 1 : 0) + '至' + (offset + inspected.length) + '项,共' + all.length + '项;未覆盖' + artifacts.remaining + '项。' });
const center = provider.modelHub(store).view();
checks.push({ id: 'models', title: '模型连接', status: center.connections.some(value => value.status === 'configured' && value.model) ? 'configured' : 'attention', detail: center.connections.filter(value => value.enabled).length + '个启用连接;配置状态与真实模型响应分别记录。' });
const activity = server?.workbenchHostAuthority?.activity() ?? { counts: { tasks: runtime.active.size, approvals: runtime.waiters.size, workers: runtime.workers?.active.size ?? 0, controlledEngines: runtime.controlledEngines?.drivers.size ?? 0, mcp: runtime.mcp?.active.size ?? 0, checks: runtime.checks?.active.size ?? 0 }, scope: '现有内存管理器数量;本次没有初始化或登记桌面宿主。' };
const titles = { tasks: '任务', approvals: '审批', workers: '子任务', controlledEngines: '原生引擎', mcp: 'MCP', checks: '工程检查', deliveries: 'Git交付', fileBatches: '文件审查', workspaces: '工作区', research: '研究', engines: '引擎探测', browsers: '浏览器', plans: '计划', modelRequests: '模型请求', modelQueue: '模型排队', modelLeases: '模型占用' };
checks.push({ id: 'managers', title: '所属执行管理器', status: 'passed', detail: Object.entries(activity.counts).map(([key, count]) => (titles[key] ?? key) + ':' + count).join(' · ') });
const unknown = [];
for (const kind of ['tool', 'worker', 'engine_run', 'mcp_job', 'check_job', 'collaboration']) for (const value of store.core[kind]?.values() ?? []) if (value.requiresVerification) unknown.push({ kind, id: value.id, sessionId: value.sessionId, taskId: value.taskId, runId: value.runId, status: value.state ?? value.status });
checks.push({ id: 'unknown', title: '原结果待核对', status: unknown.length ? 'attention' : 'passed', detail: unknown.length + '项原结果需要显式核对;本次只列出归属,不重放工具或解除状态。' });
check('installation', '当前程序来源', () => { const value = inspectHostInstallation(appDirectory); return { detail: 'v' + value.version + ' · ' + value.inputs.length + '份实际宿主/客户端输入 · ' + value.root, runtimeIdentity: value.identitySha256, checked: value.inputs.length, scope: value.verification }; });
const sources = [];
for (const [id, driver] of runtime.controlledEngines?.drivers ?? []) {
try { driver.assertInput(); driver.native?.verifyLaunch?.(); sources.push({ kind: 'controlled-engine', id, taskId: driver.run?.taskId, status: 'passed', scope: 'Original active driver input/source binding; no prompt or process is started.' }); }
catch (error) { sources.push({ kind: 'controlled-engine', id, status: 'failed', error: provider.redact(error.message) }); }
}
check('sources', '引擎与MCP来源', () => {
const registrations = store.storage.meta('projectMcpRegistry', { registrations: [] }).registrations;
if (!Array.isArray(registrations)) throw Error('原MCP登记格式无法核对。');
for (const value of registrations) {
try {
for (const identity of [value.launch?.executable, value.launch?.entry].filter(Boolean)) if (JSON.stringify(canonicalHost(binaryIdentity(identity.path))) !== JSON.stringify(canonicalHost(identity))) throw Error('原登记MCP程序发生变化。');
if (runtime.mcp && value.contract) runtime.mcp.contract(value);
sources.push({ kind: 'mcp', id: value.id, projectId: value.projectId, status: 'passed', scope: runtime.mcp && value.contract ? 'Registered program and original handshake bytes.' : 'Registered program bytes; no new handshake or tool call.' });
} catch (error) { sources.push({ kind: 'mcp', id: value.id, status: 'failed', error: provider.redact(error.message) }); }
}
return { status: sources.some(value => value.status === 'failed') ? 'failed' : 'passed', detail: sources.length + '项活动原生执行/已登记MCP来源;未接入引擎和未记录的进程创建身份不在本次范围内。', checked: sources.length };
});
const disk = [];
check('disk', '程序与数据磁盘', () => {
for (const directory of [...new Set([path.resolve(appDirectory), path.resolve(store.directory)])]) { const value = fs.statfsSync(directory, { bigint: true }), bytes = value.bavail * value.bsize; disk.push({ directory, freeBytes: bytes.toString(), status: bytes < 64n * 1024n * 1024n ? 'attention' : 'passed' }); }
return { status: disk.some(value => value.status === 'attention') ? 'attention' : 'passed', detail: disk.map(value => value.directory + ' · 剩余' + Number(BigInt(value.freeBytes) / (1024n * 1024n)).toLocaleString() + ' MB').join(';') };
});
return { version, checkedAt: new Date().toISOString(), checks, activeTasks: runtime.active.size, queue: center.waiting, modelAttempts: center.attempts.length, modelRequests: 0,
artifacts, activity, unknown: { total: unknown.length, items: unknown.slice(0, 100), omitted: Math.max(0, unknown.length - 100) }, sources, disk,
scope: '本地只读巡检:数据库quick_check、明确分页的原工件、现有管理器与待核对归属、当前程序/已登记来源及磁盘余量;不发送模型请求、不执行项目命令或自动修复。一次分页通过不代表全部历史工件已核对。' };
}