feat: ship lean runtime bundles and attributable update progress
This commit is contained in:
+7
-3
@@ -1,6 +1,8 @@
|
||||
import { EmbeddedBrowserPanel } from './EmbeddedBrowserPanel';
|
||||
import { ProjectDirectoryPicker } from './ProjectDirectoryPicker';
|
||||
import { HtmlFilePreview } from './HtmlFilePreview';
|
||||
import { InstallationStatus } from './InstallationStatus';
|
||||
import { approvalPresentation } from '../shared/approval-presentation.mjs';
|
||||
import { useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { Activity, Brain, ClipboardCheck, RotateCw, ArrowDownToLine, ArrowRight, ArrowUp, BookOpenText, Check, ChevronDown, ChevronRight, Code2, Copy, File, FileCode2, Folder, FolderOpen, GitBranch, Link2, LoaderCircle, Maximize2, MessageSquare, Minimize2, PanelLeftClose, PanelLeftOpen, Pencil, Play, Plus, Puzzle, Search, Server as ModelServer, Settings2, ShieldCheck, Square, SquareTerminal, Trash2, X } from 'lucide-react';
|
||||
import type { Bootstrap, Change, Config, ModelSelection, FileEntry, OpenFile, Project, ResearchDoc, Session, SessionBrief, ToolEvent, RuntimeDiagnostics, RuntimeFailure } from './types';
|
||||
@@ -95,6 +97,7 @@ export default function App() {
|
||||
const [workersOpen, setWorkersOpen] = useState(false);
|
||||
const [evaluationsOpen, setEvaluationsOpen] = useState(false);
|
||||
const [desktopOpen, setDesktopOpen] = useState(false);
|
||||
const [installationOpen, setInstallationOpen] = useState(false);
|
||||
const [companionOpen, setCompanionOpen] = useState(false);
|
||||
const [pickingProject, setPickingProject] = useState(false);
|
||||
const [researchDocs, setResearchDocs] = useState<ResearchDoc[]>([]);
|
||||
@@ -570,7 +573,7 @@ export default function App() {
|
||||
if (file.kind === 'directory') setCollapsed(previous => { const next = new Set(previous); if (next.has(file.path)) next.delete(file.path); else next.add(file.path); return next; }); else loadFile(file.path);
|
||||
}}>{file.kind === 'directory' ? <><span className="tree-chevron">{collapsed.has(file.path) ? <ChevronRight size={11} /> : <ChevronDown size={11} />}</span><Folder size={14} /></> : <><span className="tree-chevron" /><File size={13} /></>}<span>{filter ? file.path : file.name}</span></button>)}{filter && !visibleFiles.length && <p className="sidebar-hint">没有匹配的文件。</p>}</div>
|
||||
</div>
|
||||
<div className="sidebar-footer"><button onClick={openResearch}><BookOpenText size={16} />机制研究与设计<ChevronRight size={13} /></button><button onClick={() => setMemoryOpen(true)} disabled={!selectedProject || restrictedWorker}><Brain size={16} />项目记忆<ChevronRight size={13} /></button><button onClick={() => openDiagnostics()}><Activity size={16} />运行诊断<ChevronRight size={13} /></button><button onClick={openSettings}><Settings2 size={16} />模型连接<ChevronRight size={13} /></button><div className={'connection ' + (ready ? 'connected' : '')}><span />{ready ? '本地服务已连接' : '正在连接本地服务'}<small>v{version}</small></div></div>
|
||||
<div className="sidebar-footer"><button onClick={openResearch}><BookOpenText size={16} />机制研究与设计<ChevronRight size={13} /></button><button onClick={() => setMemoryOpen(true)} disabled={!selectedProject || restrictedWorker}><Brain size={16} />项目记忆<ChevronRight size={13} /></button><button onClick={() => openDiagnostics()}><Activity size={16} />运行诊断<ChevronRight size={13} /></button><button onClick={openSettings}><Settings2 size={16} />模型连接<ChevronRight size={13} /></button><div className={'connection ' + (ready ? 'connected' : '')}><span />{ready ? '本地服务已连接' : '正在连接本地服务'}<button className="version-entry" aria-label="版本与更新" onClick={() => setInstallationOpen(true)}>v{version}</button></div></div>
|
||||
</aside>
|
||||
<main className="task-pane">
|
||||
<header className="work-header"><div className="work-title">{(!sidebarOpen || mobile) && <IconButton label="展开项目栏" onClick={() => setSidebarOpen(true)}><PanelLeftOpen size={18} /></IconButton>}<span className="header-symbol"><Code2 size={17} /></span><div><span className="header-breadcrumb">{selectedProject?.name || '工作空间'} <ChevronRight size={12} /> 任务</span><h1>{session?.title || '让任务走到完成'}</h1></div></div>
|
||||
@@ -599,10 +602,10 @@ export default function App() {
|
||||
{isRunning && !approval && <div className="working-note"><LoaderCircle size={14} className="spin" /><span>{session?.executionMode === 'demo' ? '正在执行演示流程' : '正在处理任务'}</span></div>}
|
||||
</div>}
|
||||
{session&&<BudgetPausePanel key={session.id+session.execution?.run?.id} session={session} config={config} onSession={acceptSession}/>}
|
||||
{approval && <div className="approval-card"><div className="approval-heading"><span><ShieldCheck size={17} /></span><div><strong>{approval.environmentPlanId ? '确认依赖准备' : approval.browserPlanId ? '确认实际页面检查' : approval.checkPlanId ? '确认工程检查' : '确认这次终端执行'}</strong><p>{approval.reason}</p></div></div><pre>{approval.command}</pre>
|
||||
{approval && <div className="approval-card"><div className="approval-heading"><span><ShieldCheck size={17} /></span><div><strong>{approvalPresentation(approval).title}</strong><p>{approval.reason}</p></div></div><pre>{approval.command}</pre>
|
||||
{approval.environmentSummary&&<div className="approval-shell"><p>所属工作区:{approval.environmentSummary.root}</p><p>注册源:{approval.environmentSummary.registry} · {approval.environmentSummary.offline?'只使用缓存':'允许下载'} · {Math.round(approval.environmentSummary.timeoutMs/1000)} 秒</p><strong>{approval.environmentSummary.scripts==='skip'?'跳过全部安装脚本':'允许根工程及依赖安装脚本'}</strong><details><summary>安装脚本范围</summary>{approval.environmentSummary.lifecycle.map(row=><div key={row.name}><strong>{row.name}</strong><pre>{row.script}</pre></div>)}<p>锁文件标记 {approval.environmentSummary.installScriptPackages.length} 个包带安装脚本;下载前无法读取其正文。</p></details><p>准备完成后仍需实际工程检查。停止后保留部分依赖,原计划不会自动重放。</p></div>}
|
||||
{approval.checkScripts?.filter(check => check.python).map(check => <p className="approval-shell" key={check.name}>Python {check.python!.runtime.version || '执行时核对版本'} · {check.python!.runtime.logicalExecutable || check.python!.runtime.executable || '解释器缺失'}</p>)}
|
||||
<div className="approval-path"><Folder size={12} /><span>{approval.cwd}</span></div><p className="approval-shell">{approval.shell || '项目终端'} · UTF-8</p><p className="approval-scope">{approval.browserPlanId ? '按封存步骤操作当前构建,保存页面原结果。' : '确认后以你的系统权限执行。'}</p><div className="approval-actions"><button className="button secondary" onClick={() => decide(false)} disabled={deciding}>拒绝执行</button><button className="button primary" onClick={() => decide(true)} disabled={deciding}><Play size={14} />确认执行</button></div></div>}
|
||||
<div className="approval-path"><Folder size={12} /><span>{approval.cwd}</span></div><p className="approval-shell">{approval.shell || '项目终端'} · UTF-8</p><p className="approval-scope">{approvalPresentation(approval).scope}</p><div className="approval-actions"><button className="button secondary" onClick={() => decide(false)} disabled={deciding}>拒绝执行</button><button className="button primary" onClick={() => decide(true)} disabled={deciding}><Play size={14} />确认执行</button></div></div>}
|
||||
{pending.length > 0 && !isRunning && <button className="review-callout" onClick={() => { setChangeId(pending[0].id); showInspector('changes'); }}><FileCode2 size={17} /><span><strong>{pending.length} 项改动等待审查</strong><small>查看差异后,再应用到项目文件。</small></span><ArrowRight size={17} /></button>}
|
||||
{canContinueReview && <button type="button" aria-label="继续原任务" className="review-callout" disabled={resuming} onClick={continueReviewed}><ClipboardCheck size={17} /><span><strong>继续原任务</strong><small>改动已应用,保留原目标、范围和检查约定继续处理。</small></span><ArrowRight size={17} /></button>}
|
||||
<div ref={chatEnd} />
|
||||
@@ -624,6 +627,7 @@ export default function App() {
|
||||
{selectedProject && <CodeIndexPanel key={selectedProject.id} project={selectedProject} active={tab === 'index'} onOpen={(path, line, expectedSha256) => void loadFile(path, { line, expectedSha256 })} />}
|
||||
<div className="inspector-footer"><ShieldCheck size={13} /><span>{tab === 'changes' ? '应用前会核对文件基线' : tab === 'trace' ? '中断调用保留待核实状态' : tab === 'task' ? '任务目标、检查与结果持久保存' : tab === 'index' ? '结果绑定当前项目及文件 SHA256' : '读取范围限定在当前项目'}</span></div>
|
||||
</aside>
|
||||
{installationOpen && <Modal title="版本与更新" description="核对本机版本、真实更新阶段与原始结果。" onClose={() => setInstallationOpen(false)}><InstallationStatus /></Modal>}
|
||||
{projectOpen && <Modal title="打开项目" description="选择这台电脑上的项目文件夹,或输入完整路径。" onClose={() => { if (!projectBusy) { setProjectOpen(false); setDirectoryPickerOpen(false); setProjectError(''); } }}><form onSubmit={event => { event.preventDefault(); if (!directoryPickerOpen) void openProject(); }}><label className="form-field">项目文件夹<input autoFocus value={projectInput} disabled={projectBusy} onChange={event => { setProjectInput(event.target.value); setProjectError(''); }} placeholder="C:\Projects\my-app" aria-label="项目文件夹路径" /></label>{projectError && <p className="local-files-error" role="alert">{projectError}</p>}{directoryPickerOpen && <ProjectDirectoryPicker initialPath={projectInput.trim()} onChoose={value => { setProjectInput(value); setProjectError(''); setDirectoryPickerOpen(false); }} onCancel={() => setDirectoryPickerOpen(false)} />}<div className="modal-actions"><button type="button" className="button secondary" disabled={pickingProject || projectBusy} onClick={() => desktop ? void pickDesktopProject() : setDirectoryPickerOpen(value => !value)}><FolderOpen size={15} />选择文件夹</button>{exampleId && <button type="button" className="button secondary" disabled={projectBusy} onClick={() => { chooseProject(exampleId); setProjectOpen(false); setDirectoryPickerOpen(false); }}>打开示例项目</button>}<button type="submit" className="button primary" disabled={!projectInput.trim() || projectBusy || directoryPickerOpen}>{projectBusy ? <LoaderCircle className="spin" size={15} /> : <FolderOpen size={15} />}{projectBusy ? '正在打开…' : '打开项目'}</button></div></form></Modal>}
|
||||
{companionOpen && <Modal title="手机连接" description="指定项目和权限,连接到同一个Windows执行宿主。" onClose={() => setCompanionOpen(false)} wide><CompanionPanel projects={projects} selectedProjectId={selectedProject?.id ?? ''} /></Modal>}
|
||||
{desktopOpen && desktop && <Modal title="桌面与后台任务" description="当前窗口连接同一个本机执行宿主。" onClose={() => setDesktopOpen(false)}><DesktopPanel project={selectedProject} session={session} file={openFile} onProject={acceptDesktopProject} onReview={scope => { if (selectedProjectRef.current === scope.projectId && selectedSessionRef.current === scope.sessionId && selectedTaskRef.current === scope.taskId) { setDesktopOpen(false); showInspector('task'); } }} /></Modal>}
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
.installation-status { color: var(--text, #24383e); font-size: 13px; line-height: 1.6; }
|
||||
.installation-status > header { display: flex; align-items: flex-start; justify-content: space-between; gap: 16px; padding-bottom: 18px; border-bottom: 1px solid #dce3e7; }
|
||||
.installation-status h3 { margin: 0 0 4px; font-size: 15px; }
|
||||
.installation-status p { margin: 5px 0; }
|
||||
.installation-status button { flex-shrink: 0; }
|
||||
.installation-facts { display: grid; grid-template-columns: 76px minmax(0, 1fr); gap: 9px 14px; margin: 18px 0; }
|
||||
.installation-facts dt { color: #52636c; }
|
||||
.installation-facts dd { margin: 0; overflow-wrap: anywhere; font: 12px/1.6 var(--font-mono, Consolas, monospace); }
|
||||
.installation-operation { margin-top: 18px; padding: 18px 0 0; border-top: 1px solid #dce3e7; }
|
||||
.installation-stage { display: flex; align-items: center; gap: 9px; }
|
||||
.installation-stage > span:last-child { margin-left: auto; white-space: nowrap; color: #52636c; font-variant-numeric: tabular-nums; }
|
||||
.installation-state-dot { flex: 0 0 7px; height: 7px; border-radius: 50%; background: #337858; }
|
||||
.installation-failed .installation-state-dot, .installation-unknown .installation-state-dot { background: #a04832; }
|
||||
.installation-counts { display: grid; gap: 6px; margin: 16px 0; font-variant-numeric: tabular-nums; }
|
||||
.installation-counts progress { width: 100%; height: 6px; accent-color: #337858; }
|
||||
.installation-counts code { overflow-wrap: anywhere; color: #52636c; font-size: 11px; }
|
||||
.installation-note, .installation-empty { padding: 12px 0; color: #52636c; }
|
||||
.installation-error { margin-top: 12px; padding: 12px; background: #fff2ed; color: #843620; overflow-wrap: anywhere; border-left: 3px solid #b86d4d; }
|
||||
.installation-history { display: grid; gap: 6px; margin-top: 16px; color: #52636c; }
|
||||
.installation-history select { width: 100%; min-width: 0; padding: 8px; border: 1px solid #c5d1d8; border-radius: 4px; color: #24383e; background: #fff; font: inherit; }
|
||||
.connection .version-entry { color: inherit; padding: 0 3px; margin-left: auto; min-width: 0; width: auto; background: transparent; border: 0; font: inherit; font-size: 11px; cursor: pointer; text-decoration: underline; text-underline-offset: 3px; }
|
||||
.connection .version-entry:focus-visible { outline: 2px solid currentColor; outline-offset: 3px; }
|
||||
@media(max-width: 480px) { .installation-status > header { flex-wrap: wrap; } .installation-facts { grid-template-columns: 1fr; gap: 3px; } .installation-facts dd { margin-bottom: 9px; } .installation-stage { flex-wrap: wrap; } }
|
||||
@@ -0,0 +1,49 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { RotateCw } from 'lucide-react';
|
||||
import { api } from './api';
|
||||
import './InstallationStatus.css';
|
||||
|
||||
type Operation = {
|
||||
id: string; sequence: number; state: string; stage: string; label: string; updatedAt: string; elapsedMs: number; scope?: string;
|
||||
counts?: { completedFiles: number; totalFiles: number; completedBytes: number | null; totalBytes: number | null; currentPath?: string } | null;
|
||||
candidate?: { version: string; manifestSha256: string } | null;
|
||||
detail?: { error?: { code: string; message: string }; receiptFile?: string; originalError?: string };
|
||||
progressFile: string; interrupted?: boolean;
|
||||
};
|
||||
type Status = { installed: boolean; runningVersion: string; activeVersion?: string; previousVersion?: string | null; installRoot?: string; operations: Operation[] };
|
||||
const size = (bytes: number) => { const unit = bytes < 1024 ? 0 : bytes < 1024 ** 2 ? 1 : bytes < 1024 ** 3 ? 2 : 3; return new Intl.NumberFormat('zh-CN', { maximumFractionDigits: 1 }).format(bytes / 1024 ** unit) + ' ' + ['B', 'KB', 'MB', 'GB'][unit]; };
|
||||
const scopeLabel = (scope?: string) => scope === 'full-manifest' ? '全部发行文件' : scope === 'directory-inventory' ? '实际目录范围' : scope === 'loaded-inputs' ? '宿主与客户端入口' : '';
|
||||
|
||||
export function InstallationStatus() {
|
||||
const [status, setStatus] = useState<Status | null>(null), [error, setError] = useState(''), [busy, setBusy] = useState(false);
|
||||
const [refresh, setRefresh] = useState(0);
|
||||
const [selected, setSelected] = useState('');
|
||||
useEffect(() => {
|
||||
let alive = true, timer: ReturnType<typeof setTimeout>;
|
||||
const load = async () => {
|
||||
setBusy(true);
|
||||
try {
|
||||
const value = await api<Status>('/installation/status');
|
||||
if (alive) { setStatus(value); setError(''); }
|
||||
} catch (value) { if (alive) setError(value instanceof Error ? value.message : '无法读取原安装进度。'); }
|
||||
finally { if (alive) { setBusy(false); timer = setTimeout(() => void load(), 2500); } }
|
||||
};
|
||||
void load(); return () => { alive = false; clearTimeout(timer); };
|
||||
}, [refresh]);
|
||||
const operation = status?.operations.find(value => value.id === selected) ?? status?.operations[0];
|
||||
return <section className="installation-status" aria-label="版本与更新状态">
|
||||
<header><div><h3>当前版本</h3><p>{status ? <>正在运行 <strong>v{status.runningVersion}</strong>{status.installed && <> · 已登记 v{status.activeVersion}</>}</> : '正在读取本机安装登记…'}</p></div><button className="button secondary" disabled={busy} onClick={() => setRefresh(value => value + 1)}><RotateCw size={14} />刷新状态</button></header>
|
||||
{error && <p role="alert" className="installation-error">{error}{status && ' 以下保留上次读取结果,请刷新后再判断当前状态。'}</p>}
|
||||
{status && !status.installed && <p>当前使用源码或便携目录。安装版会在这里显示所属更新阶段和原始失败记录。</p>}
|
||||
{status?.installed && <dl className="installation-facts"><dt>程序目录</dt><dd>{status.installRoot}</dd><dt>前一版本</dt><dd>{status.previousVersion ? 'v' + status.previousVersion : '首次安装'}</dd></dl>}
|
||||
{status?.installed && !operation && <p className="installation-empty">还没有新版安装进度记录。此前版本的原操作收据保存在程序目录的 .installation 中。</p>}
|
||||
{status && status.operations.length > 1 && <label className="installation-history">安装操作<select aria-label="查看安装操作" value={selected} onChange={event => setSelected(event.target.value)}><option value="">最近一次操作</option>{status.operations.map(value => <option key={value.id} value={value.id}>{new Date(value.updatedAt).toLocaleString('zh-CN')} · {value.interrupted ? '结果待核对' : value.label}</option>)}</select></label>}
|
||||
{operation && <article className={'installation-operation installation-' + operation.state}>
|
||||
<div className="installation-stage" role="status"><span className="installation-state-dot" /><strong>{operation.interrupted ? '原安装进程已结束,结果待核对' : operation.label}</strong><span>{Math.round(operation.elapsedMs / 1000)} 秒</span></div>
|
||||
{operation.counts && <div className="installation-counts"><span>{scopeLabel(operation.scope)}</span><strong>{operation.counts.completedFiles.toLocaleString()} / {operation.counts.totalFiles.toLocaleString()} 文件</strong>{operation.counts.completedBytes !== null && operation.counts.totalBytes !== null && <span>{size(operation.counts.completedBytes)} / {size(operation.counts.totalBytes)}</span>}<progress aria-label="当前核对范围" max={Math.max(1, operation.counts.totalFiles)} value={operation.counts.completedFiles} />{operation.counts.currentPath && <code>{operation.counts.currentPath}</code>}</div>}
|
||||
{operation.detail?.error && <div className="installation-error" role="alert"><strong>{operation.detail.error.code}</strong><p>{operation.detail.error.message}</p></div>}
|
||||
<dl className="installation-facts"><dt>目标版本</dt><dd>{operation.candidate ? 'v' + operation.candidate.version : '准备时尚未读取候选'}</dd><dt>操作编号</dt><dd>{operation.id} · 序号 {operation.sequence}</dd><dt>原始记录</dt><dd>{operation.progressFile}</dd>{operation.detail?.receiptFile && <><dt>结果收据</dt><dd>{operation.detail.receiptFile}</dd></>}</dl>
|
||||
<p className="installation-note">{operation.state === 'ready-to-copy' ? '预检已通过,写入进度由安装器显示;新版本尚未激活。' : operation.interrupted ? '请保留原安装日志与收据,核对已登记版本。不要根据窗口关闭推断安装成功,也不要重复执行原任务。' : operation.state === 'failed' ? '原失败记录已保留。请按具体原因处理,核对已登记版本及回退收据后再开始新的安装。' : operation.state === 'staged' ? '文件已核对并暂存,当前活动版本保留。' : operation.state === 'running' ? '当前阶段核对实际文件。发布版本和回退期间需要保持安装器打开;各阶段单独计数。' : '原会话与工件保留。这里的安装结果不代表模型工程任务已经通过。'}</p>
|
||||
</article>}
|
||||
</section>;
|
||||
}
|
||||
@@ -18,7 +18,7 @@ export interface MobileTask extends MobileBrief {
|
||||
events: { id: string; label: string; phase: string; output: string; taskId?: string; runId?: string; createdAt: string; exitCode?: number;
|
||||
stream?: { status: string; protocol?: string; textCharacters?: number; textPreview?: string; toolFragments?: number } }[];
|
||||
messages: { id: string; role: string; content: string; createdAt: string }[];
|
||||
approvals: { id: string; taskId: string; runId: string; projectId: string; command: string; reason: string; shell: string; fingerprint: string; actionable: boolean }[];
|
||||
approvals: { id: string; taskId: string; runId: string; projectId: string; command: string; reason: string; shell: string; kind?: string; fingerprint: string; actionable: boolean }[];
|
||||
changes: { id: string; path: string; reason: string; status: string; sha256: string; baseSha256: string; additions: number; deletions: number }[];
|
||||
checks: { id: string; status: string; summary: string; requiresVerification?: boolean; results: { name: string; status: string; exitCode?: number; tests?: { total: number; passed: number; failed: number; skipped: number; cancelled: number } }[] }[];
|
||||
reports: { id: string; kind: string; sha256: string; bytes: number }[];
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { MobileBrowserObservation } from './MobileBrowserObservation';
|
||||
import { approvalPresentation } from '../../shared/approval-presentation.mjs';
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { ArrowLeft, ChevronRight, ClipboardCheck, FileDiff, Folder, Link2, RefreshCw, ShieldCheck, Square, Terminal, Wifi, WifiOff, X } from 'lucide-react';
|
||||
import type { CompanionDevice, MobileBrief, MobileTask } from '../companion-types';
|
||||
@@ -131,6 +132,6 @@ export function MobileApp({ initialToken }: { initialToken: string }) {
|
||||
{['running', 'awaiting_approval', 'stopping'].includes(selectedTask.status) && <div className="mobile-stop"><span>{me.device.permissions.stop ? '停止仍由电脑等待所属工具退出' : '此设备没有停止权限'}</span><button disabled={!me.device.permissions.stop || !fresh || !!busy || selectedTask.status === 'stopping'} onClick={() => setDecision({ requestId: crypto.randomUUID(), kind: 'stop', task: selectedTask })}><Square size={14} />停止原任务</button></div>}
|
||||
</>}</main>}
|
||||
{document && <dialog ref={documentDialog} className="mobile-document" aria-label={document.title} onCancel={() => setDocument(null)}><header><button aria-label="关闭文档" onClick={() => setDocument(null)}><ArrowLeft size={20} /></button><strong>{document.title}</strong></header><p><ShieldCheck size={14} />SHA-256 已核对{document.redacted ? ' · 已脱敏' : ''}</p><code>{document.sha256}</code><pre>{document.text}</pre><button onClick={() => setDocument(null)}>返回任务</button></dialog>}
|
||||
{decision && <dialog ref={dialog} className="mobile-confirm" onCancel={() => setDecision(null)}><button className="mobile-confirm-close" aria-label="关闭确认" onClick={() => setDecision(null)} disabled={!!busy}><X size={20} /></button><h2>{decision.kind === 'stop' ? '停止这个原任务' : decision.allow ? '批准原命令请求' : '拒绝原命令请求'}</h2><p>{projectName(decision.task.projectId)} · {decision.task.title}</p>{decision.approval && <pre>{decision.approval.command}</pre>}<code>Task {decision.task.taskId}<br />Run {decision.task.runId}<br />修订 {decision.task.revision}</code>{decision.task.revision !== task?.revision && <p role="alert">任务修订已变化,请关闭并重新核对。</p>}<p>{decision.kind === 'stop' ? '电脑将停止此运行,并保留已经完成的工具结果。' : decision.allow ? '批准后,电脑将在原项目中执行这条已登记命令。' : '拒绝后,这条原命令不会执行。'}</p><div className="mobile-action-pair"><button disabled={!!busy} onClick={() => setDecision(null)}>返回核对</button><button className={decision.kind === 'stop' ? 'mobile-danger' : 'mobile-primary'} disabled={!!busy || !fresh || decision.task.revision !== task?.revision} onClick={() => void submitDecision()}>{busy === 'operation' ? '等待原回执…' : '确认'}</button></div></dialog>}
|
||||
{decision && <dialog ref={dialog} className="mobile-confirm" onCancel={() => setDecision(null)}><button className="mobile-confirm-close" aria-label="关闭确认" onClick={() => setDecision(null)} disabled={!!busy}><X size={20} /></button><h2>{decision.kind === 'stop' ? '停止这个原任务' : (decision.allow ? '批准原' : '拒绝原') + approvalPresentation(decision.approval).subject}</h2><p>{projectName(decision.task.projectId)} · {decision.task.title}</p>{decision.approval && <pre>{decision.approval.command}</pre>}<code>Task {decision.task.taskId}<br />Run {decision.task.runId}<br />修订 {decision.task.revision}</code>{decision.task.revision !== task?.revision && <p role="alert">任务修订已变化,请关闭并重新核对。</p>}<p>{decision.kind === 'stop' ? '电脑将停止此运行,并保留已经完成的工具结果。' : decision.allow ? approvalPresentation(decision.approval).scope : approvalPresentation(decision.approval).denied}</p><div className="mobile-action-pair"><button disabled={!!busy} onClick={() => setDecision(null)}>返回核对</button><button className={decision.kind === 'stop' ? 'mobile-danger' : 'mobile-primary'} disabled={!!busy || !fresh || decision.task.revision !== task?.revision} onClick={() => void submitDecision()}>{busy === 'operation' ? '等待原回执…' : '确认'}</button></div></dialog>}
|
||||
</div>;
|
||||
}
|
||||
|
||||
@@ -26,6 +26,7 @@ export interface ExecutionSnapshot {browsingTabs?:BrowsingTab[];browsingActions?
|
||||
export interface CheckPlan {environment?:NodeEnvironmentBinding|null}
|
||||
export interface CheckJob {environment?:NodeEnvironmentBinding|null}
|
||||
export interface Approval {environmentPlanId?:string}
|
||||
export interface Approval {browsingTabId?:string;mcpRegistrationId?:string}
|
||||
export interface Approval {environmentSummary?:Pick<EnvironmentPlan,'root'|'registry'|'scripts'|'offline'|'timeoutMs'|'lifecycle'|'installScriptPackages'>}
|
||||
export interface NodeEnvironmentBinding {preparation?:{jobId:string;planId:string;sessionId:string;logArtifactId:string;logSha256:string}|null}
|
||||
export interface ModelSelection { type: 'legacy' | 'connection' | 'pool'; id: string; name: string }
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { approvalBinding } from '../../shared/contracts/companion.mjs';
|
||||
import { approvalKind } from '../../shared/approval-presentation.mjs';
|
||||
|
||||
export const pick = (value, names) => Object.fromEntries(names.filter(key => value?.[key] !== undefined).map(key => [key, structuredClone(value[key])]));
|
||||
export const reportKinds = new Set(['delivery-report', 'delivery-report-markdown']);
|
||||
@@ -24,7 +25,7 @@ export function mobileSession(store, runtime, session, redact = String) {
|
||||
messages: session.messages.filter(value => ['assistant', 'system'].includes(value.role)).slice(-8).map(value => ({ ...pick(value, ['id', 'role', 'createdAt']), content: String(value.content).slice(0, 12000) })),
|
||||
approvals: session.approvals.filter(value => value.status === 'pending' && value.taskId === session.taskId && value.runId === session.runId).map(value => ({
|
||||
...pick(value, ['id', 'taskId', 'runId', 'projectId', 'command', 'reason', 'shell', 'createdAt']),
|
||||
fingerprint: approvalBinding(session, value), actionable: runtime.waiters.get(value.id)?.runId === session.runId })),
|
||||
kind: approvalKind(value), fingerprint: approvalBinding(session, value), actionable: runtime.waiters.get(value.id)?.runId === session.runId })),
|
||||
changes: session.changes.filter(value => value.taskId === session.taskId).slice(-100).map(value => pick(value, ['id', 'path', 'reason', 'status', 'sha256', 'baseSha256', 'additions', 'deletions'])),
|
||||
checks: checks.slice(-12).map(value => ({ ...pick(value, ['id', 'status', 'summary', 'requiresVerification', 'createdAt', 'finishedAt']),
|
||||
results: (value.results ?? []).map(item => pick(item, ['name', 'status', 'exitCode', 'tests', 'durationMs'])) })),
|
||||
|
||||
@@ -5,7 +5,7 @@ import { binaryIdentity } from './process-identity.mjs';
|
||||
import { ownedChild, readState, assertLocalTree } from './file-state.mjs';
|
||||
import { canonicalHost, hostError } from '../../shared/contracts/desktop-host.mjs';
|
||||
|
||||
export function inspectHostInstallation(directory, { full = false } = {}) {
|
||||
export function inspectHostInstallation(directory, { full = false, onProgress = null } = {}) {
|
||||
assertLocalTree(directory);
|
||||
const root = fs.realpathSync.native(path.resolve(directory));
|
||||
if (!fs.statSync(root).isDirectory()) throw hostError('宿主安装目录无效。');
|
||||
@@ -26,10 +26,15 @@ export function inspectHostInstallation(directory, { full = false } = {}) {
|
||||
if (full || /^(dist-client|dist-server|dist-desktop)\//.test(row.path)) files.add(row.path);
|
||||
}
|
||||
if (!manifest || manifest.kind === 'source') for (const entry of fs.readdirSync(path.join(root, 'dist-client/assets'))) files.add('dist-client/assets/' + entry);
|
||||
const inputs = [...files].sort().map(relative => {
|
||||
const selected = [...files].sort(), totalBytes = selected.reduce((sum, name) => sum + (names.get(name)?.bytes ?? 0), 0);
|
||||
let completedFiles = 0, completedBytes = 0;
|
||||
const report = currentPath => onProgress?.({ scope: full ? 'full-manifest' : 'loaded-inputs', root, totalFiles: selected.length, totalBytes: manifest ? totalBytes : null, completedFiles, completedBytes, currentPath });
|
||||
report(null);
|
||||
const inputs = selected.map(relative => {
|
||||
const file = ownedChild(root, relative), identity = binaryIdentity(file), declared = names.get(relative);
|
||||
if (manifest?.kind === 'portable' && !declared) throw hostError('实际宿主程序不在原发行清单中。');
|
||||
if (declared && (identity.bytes !== declared.bytes || identity.sha256 !== declared.sha256)) throw hostError('实际宿主程序与原发行清单不一致。');
|
||||
completedFiles++; completedBytes += identity.bytes; report(relative);
|
||||
return { path: relative, bytes: identity.bytes, sha256: identity.sha256 };
|
||||
});
|
||||
const result = { root, version, kind: manifest?.kind ?? 'development-build', manifestSha256: manifest ? digest(fs.readFileSync(manifestFile)) : null,
|
||||
|
||||
@@ -10,25 +10,28 @@ import { observeWindowsProcess, protectUserDirectory, binaryIdentity } from './p
|
||||
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';
|
||||
import { InstallationProgress } from './installation-progress.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 });
|
||||
export function validateInstalledVersion(directory, { onProgress = null } = {}) {
|
||||
const installation = inspectHostInstallation(directory, { full: true, onProgress });
|
||||
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('安装候选含有链接或非常规文件。');
|
||||
if (entry.isDirectory()) walk(next); else if (entry.isFile()) {
|
||||
actual.push(next); onProgress?.({ scope: 'directory-inventory', root: installation.root, completedFiles: actual.length, totalFiles: manifest.files.length + 1, completedBytes: null, totalBytes: null, currentPath: 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);
|
||||
return inspectHostInstallation(directory, { onProgress });
|
||||
}
|
||||
|
||||
export function snapshotPersistentData(dataRoot) {
|
||||
@@ -55,7 +58,7 @@ export function snapshotPersistentData(dataRoot) {
|
||||
}
|
||||
|
||||
export class InstallationManager {
|
||||
constructor({ installRoot, dataRoot, port = 4318, candidateRoot = null, timeoutMs = 60000 }) {
|
||||
constructor({ installRoot, dataRoot, port = 4318, candidateRoot = null, timeoutMs = 60000, operationId = null, expectedManifestSha256 = null, onProgress = null }) {
|
||||
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 });
|
||||
@@ -64,13 +67,34 @@ export class InstallationManager {
|
||||
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);
|
||||
this.progressOptions = { operationId, expectedManifestSha256, onProgress };
|
||||
if (expectedManifestSha256 !== null && !/^[a-f0-9]{64}$/.test(expectedManifestSha256)) throw fail('安装候选清单身份无效。');
|
||||
}
|
||||
async operation(command, action) {
|
||||
return this.lock(async () => {
|
||||
const progress = new InstallationProgress({ stateRoot: this.stateRoot, installRoot: this.installRoot, dataRoot: this.dataRoot, command, ...this.progressOptions });
|
||||
this.progress = progress; this.receiptFile = null;
|
||||
try {
|
||||
const result = await action();
|
||||
// The verified publication receipt is authoritative. A status-file error
|
||||
// after commit must not relabel an activated version as a failed update.
|
||||
try { progress.finish(command === 'preflight' ? 'ready-to-copy' : command === 'cancel' ? 'cancelled' : result.phase === 'staged' ? 'staged' : command === 'uninstall' ? 'uninstall-ready' : 'completed', { activeVersion: result.active?.version ?? result.current?.version ?? result.candidate?.version ?? null, receiptFile: result.receiptFile ?? null }); }
|
||||
catch (error) { if (command === 'preflight') throw error; return { ...result, operationId: progress.value.id, progressFile: progress.file, progressWarning: error.message }; }
|
||||
return { ...result, progressFile: progress.file, operationId: progress.value.id };
|
||||
} catch (error) { try { progress.finish('failed', { error: { code: error.code ?? 'INSTALLATION_FAILED', message: error.message }, receiptFile: this.receiptFile, pointer: fs.existsSync(this.recordFile) ? 'retained-record; inspect original receipt' : 'not-published' }); } catch {} throw error; }
|
||||
finally { this.progress = null; }
|
||||
});
|
||||
}
|
||||
phase(name, detail = {}) { this.progress?.phase(name, detail); }
|
||||
async cancelPreparation() { return this.operation('cancel', async () => ({ phase: 'cancelled', activated: false, dataPolicy: 'preserve-original-data' })); }
|
||||
verification(scope) { return value => this.progress?.count(scope, value); }
|
||||
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);
|
||||
this.phase('verify-current', { version: value.active.version });
|
||||
const root = this.versionRoot(value.active), actual = validateInstalledVersion(root, { onProgress: this.verification('verify-current') });
|
||||
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;
|
||||
@@ -84,7 +108,10 @@ export class InstallationManager {
|
||||
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);
|
||||
this.phase('verify-candidate');
|
||||
const identity = validateInstalledVersion(this.candidateRoot, { onProgress: this.verification('verify-candidate') });
|
||||
if (this.progressOptions.expectedManifestSha256 && identity.manifestSha256 !== this.progressOptions.expectedManifestSha256) throw fail('新候选与本次安装器固定的原清单不同。');
|
||||
this.progress?.candidate(identity);
|
||||
return { directory: path.basename(identity.root), version: identity.version, manifestSha256: identity.manifestSha256, runtimeIdentity: identity.identitySha256 };
|
||||
}
|
||||
async host() {
|
||||
@@ -124,10 +151,12 @@ export class InstallationManager {
|
||||
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 this.operation('preflight', async () => {
|
||||
const current = this.current(); this.phase('inspect-root'); this.inspectRoot(current); this.phase('inspect-host'); 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 })) {
|
||||
@@ -141,10 +170,12 @@ export class InstallationManager {
|
||||
}
|
||||
}
|
||||
async activate({ stageOnly = false, beforePointer = null, afterPointer = null } = {}) {
|
||||
return this.lock(async () => {
|
||||
return this.operation('activate', async () => {
|
||||
const candidate = this.candidate(), old = this.current(); this.inspectRoot(old); const priorHost = stageOnly ? null : await this.host();
|
||||
this.phase('snapshot-data');
|
||||
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() };
|
||||
this.receiptFile = receiptFile;
|
||||
const receipt = { schema: 1, id, operationId: this.progress?.value.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;
|
||||
@@ -161,14 +192,17 @@ export class InstallationManager {
|
||||
};
|
||||
try {
|
||||
if (priorHost && !samePath(priorHost.identity.runtimeRoot, this.candidateRoot)) {
|
||||
this.phase('retain-host', { pid: priorHost.identity.pid });
|
||||
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('新处理器没有保持原宿主实例。');
|
||||
}
|
||||
this.phase('verify-data');
|
||||
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('新候选在预检后发生变化,停止发布候选。');
|
||||
this.phase('publish-pointer', { interruptible: false });
|
||||
const actualBootstrap = fs.existsSync(bootstrapFile) ? fs.readFileSync(bootstrapFile) : null;
|
||||
if (!isDeepStrictEqual(actualBootstrap, originalBootstrap)) throw fail('原启动器在预检后发生变化,停止发布候选。');
|
||||
if (!isDeepStrictEqual(originalBootstrap, candidateBootstrap)) { replaceBootstrap(candidateBootstrap); bootstrapPublished = true; }
|
||||
@@ -176,11 +210,13 @@ export class InstallationManager {
|
||||
dataRoot: this.dataRoot, port: this.port, active: candidate, previous: old?.active ?? null, activatedAt: new Date().toISOString() };
|
||||
writeState(this.recordFile, next);
|
||||
pointerPublished = true;
|
||||
this.phase('verify-publication', { interruptible: false });
|
||||
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) {
|
||||
try { this.phase('rollback', { interruptible: false, originalError: error.message }); } catch {}
|
||||
let rollback = 'pointer-preserved';
|
||||
try {
|
||||
if (pointerPublished && fs.existsSync(this.recordFile)) {
|
||||
@@ -211,10 +247,10 @@ export class InstallationManager {
|
||||
});
|
||||
}
|
||||
async prepareUninstall() {
|
||||
return this.lock(async () => {
|
||||
return this.operation('uninstall', async () => {
|
||||
const current = this.current(); if (!current) throw fail('没有可核对的本产品安装登记。');
|
||||
this.inspectRoot(current);
|
||||
const snapshot = snapshotPersistentData(this.dataRoot), host = await this.host();
|
||||
this.phase('snapshot-data'); const snapshot = snapshotPersistentData(this.dataRoot); this.phase('inspect-host'); const 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');
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { performance } from 'node:perf_hooks';
|
||||
import { ownedChild, readState, writeState, samePath } from './file-state.mjs';
|
||||
import { observeWindowsProcess } from './process-identity.mjs';
|
||||
import { hostError } from '../../shared/contracts/desktop-host.mjs';
|
||||
|
||||
export const INSTALLATION_STAGES = Object.freeze({
|
||||
preparing: '准备安装核对', 'verify-current': '核对原活动版本', 'verify-candidate': '核对新版本',
|
||||
'inspect-root': '核对安装目录', 'inspect-host': '核对后台宿主与活动任务', 'snapshot-data': '记录原会话与工件',
|
||||
'retain-host': '保留原宿主与模型连接', 'verify-data': '核对原会话与工件保持',
|
||||
'publish-pointer': '发布活动版本', 'verify-publication': '核对已发布版本', rollback: '核对原版本回退',
|
||||
'ready-to-copy': '预检通过,等待安装器写入版本文件', staged: '候选已暂存,尚未切换版本',
|
||||
completed: '版本激活完成', failed: '安装未完成,请核对原始原因', 'uninstall-ready': '卸载预检完成,用户数据保留', cancelled: '本次安装准备已取消',
|
||||
});
|
||||
const terminal = new Set(['staged', 'completed', 'failed', 'uninstall-ready', 'cancelled']);
|
||||
const validId = value => typeof value === 'string' && /^(?:[a-f0-9]{64}|[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12})$/.test(value);
|
||||
|
||||
export class InstallationProgress {
|
||||
constructor({ stateRoot, installRoot, dataRoot, command, operationId = null, expectedManifestSha256 = null, onProgress = null }) {
|
||||
const id = operationId ?? randomUUID();
|
||||
if (!validId(id)) throw hostError('安装操作编号无效。');
|
||||
this.file = ownedChild(stateRoot, 'progress-' + id + '.json', { missing: true });
|
||||
const previous = fs.existsSync(this.file) ? readState(this.file, 512 * 1024) : null;
|
||||
if (previous && (previous.schema !== 1 || previous.id !== id || !samePath(previous.installRoot, installRoot) || !samePath(previous.dataRoot, dataRoot)
|
||||
|| previous.expectedManifestSha256 !== expectedManifestSha256 || previous.state !== 'ready-to-copy' || !['activate', 'cancel'].includes(command))) throw hostError('原安装操作不允许重放或改变来源。');
|
||||
if (!previous && command === 'cancel') throw hostError('没有可取消的原安装准备记录。');
|
||||
this.onProgress = onProgress; this.lastSaved = 0;
|
||||
this.value = { schema: 1, id, installRoot, dataRoot, command, expectedManifestSha256,
|
||||
startedAt: previous?.startedAt ?? new Date().toISOString(), sequence: previous?.sequence ?? 0, history: previous?.history ?? [],
|
||||
process: observeWindowsProcess(process.pid), candidate: previous?.candidate ?? null, state: 'running', stage: 'preparing', scope: null, counts: null, interruptible: false };
|
||||
// Process identity only; environment, credentials and private data are never included.
|
||||
const processIdentity = this.value.process;
|
||||
this.value.process = processIdentity ? { pid: processIdentity.pid, createdAt: processIdentity.createdAt } : { pid: process.pid, createdAt: null };
|
||||
this.phase('preparing');
|
||||
}
|
||||
phase(stage, detail = {}) {
|
||||
if (!Object.hasOwn(INSTALLATION_STAGES, stage)) throw hostError('安装阶段无效。');
|
||||
if (this.value.stageStartedAt) this.value.history.push({ stage: this.value.stage, scope: this.value.scope, counts: this.value.counts, startedAt: this.value.stageStartedAt, finishedAt: new Date().toISOString(), elapsedMs: Math.round(performance.now() - this.phaseStarted) });
|
||||
this.value.history = this.value.history.slice(-96);
|
||||
Object.assign(this.value, { stage, label: INSTALLATION_STAGES[stage], scope: null, counts: null, detail, stageStartedAt: new Date().toISOString() });
|
||||
this.phaseStarted = performance.now(); this.save();
|
||||
}
|
||||
count(stage, value) {
|
||||
if (this.value.stage !== stage || this.value.scope !== value.scope) this.phase(stage, { root: value.root });
|
||||
this.value.scope = value.scope;
|
||||
this.value.counts = { completedFiles: value.completedFiles, totalFiles: value.totalFiles, completedBytes: value.completedBytes, totalBytes: value.totalBytes, currentPath: value.currentPath };
|
||||
if (performance.now() - this.lastSaved >= 500 || value.completedFiles === value.totalFiles || value.completedFiles === 0) this.save();
|
||||
}
|
||||
candidate(identity) {
|
||||
this.value.candidate = { root: identity.root, version: identity.version, manifestSha256: identity.manifestSha256, runtimeIdentity: identity.identitySha256 };
|
||||
this.save();
|
||||
}
|
||||
save() {
|
||||
this.value.sequence++; this.value.updatedAt = new Date().toISOString();
|
||||
this.value.elapsedMs = Math.max(0, Date.now() - Date.parse(this.value.startedAt));
|
||||
writeState(this.file, this.value); this.lastSaved = performance.now();
|
||||
// UI/console observers must never decide the installation result.
|
||||
try { this.onProgress?.(structuredClone(this.value)); } catch {}
|
||||
}
|
||||
finish(state, detail = {}) {
|
||||
if (!terminal.has(state) && state !== 'ready-to-copy') throw hostError('安装终态无效。');
|
||||
this.value.state = state; this.phase(state, detail);
|
||||
}
|
||||
}
|
||||
|
||||
export function readInstallationProgress({ appRoot, dataRoot }) {
|
||||
const versions = path.dirname(appRoot);
|
||||
if (path.basename(versions).toLowerCase() !== 'versions') return { installed: false, operations: [] };
|
||||
const installRoot = path.dirname(versions), pointerFile = ownedChild(installRoot, 'current.json', { missing: true });
|
||||
if (!fs.existsSync(pointerFile)) return { installed: false, operations: [] };
|
||||
const pointer = readState(pointerFile, 16384);
|
||||
if (pointer.app !== 'agent-workbench-installation' || !samePath(pointer.dataRoot, dataRoot) || !pointer.active?.version) throw hostError('安装进度与当前数据目录不一致。');
|
||||
const stateRoot = ownedChild(installRoot, '.installation', { missing: true });
|
||||
const operations = fs.existsSync(stateRoot) ? fs.readdirSync(stateRoot).filter(name => /^progress-(?:[a-f0-9-]{36}|[a-f0-9]{64})\.json$/.test(name)).map(name => {
|
||||
const value = readState(ownedChild(stateRoot, name), 512 * 1024);
|
||||
if (value.schema !== 1 || !validId(value.id) || name !== 'progress-' + value.id + '.json' || !samePath(value.installRoot, installRoot) || !samePath(value.dataRoot, dataRoot) || !Number.isSafeInteger(value.sequence) || !Object.hasOwn(INSTALLATION_STAGES, value.stage)) throw hostError('原安装进度无法核对,请保留操作收据。');
|
||||
const actual = value.state === 'running' ? observeWindowsProcess(value.process?.pid) : null;
|
||||
const unknown = value.state === 'running' && (!actual || actual.createdAt !== value.process?.createdAt);
|
||||
return { ...value, state: unknown ? 'unknown' : value.state, interrupted: unknown, progressFile: path.join(stateRoot, name) };
|
||||
}).sort((a, b) => b.updatedAt.localeCompare(a.updatedAt)).slice(0, 5) : [];
|
||||
return { installed: true, activeVersion: pointer.active.version, previousVersion: pointer.previous?.version ?? null, revision: pointer.revision, installRoot, operations };
|
||||
}
|
||||
@@ -1,14 +1,19 @@
|
||||
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.');
|
||||
if (!['preflight', 'activate', 'uninstall', 'cancel'].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.');
|
||||
if (!['--install-root', '--data-root', '--candidate-root', '--port', '--operation-id', '--expected-manifest-sha256'].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();
|
||||
const manager = new InstallationManager({ installRoot: options['--install-root'], dataRoot: options['--data-root'], candidateRoot: options['--candidate-root'], port: Number(options['--port'] || 4318), operationId: options['--operation-id'] ?? null, expectedManifestSha256: options['--expected-manifest-sha256'] ?? null,
|
||||
onProgress: value => {
|
||||
const counts = value.counts;
|
||||
console.log('AWBPROGRESS ' + (value.label + (counts ? ` · ${counts.completedFiles}/${counts.totalFiles} 文件` + (counts.completedBytes !== null ? ` · ${counts.completedBytes}/${counts.totalBytes} 字节` : '') + (counts.currentPath ? ' · ' + counts.currentPath : '') : '')).replace(/[\r\n]/g, ' '));
|
||||
console.log('AWBFILES ' + (counts ? counts.completedFiles + '/' + counts.totalFiles : '-'));
|
||||
} });
|
||||
const result = command === 'preflight' ? await manager.preflight({ stageOnly: !!options.stageOnly }) : command === 'activate' ? await manager.activate({ stageOnly: !!options.stageOnly }) : command === 'cancel' ? await manager.cancelPreparation() : 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; }
|
||||
} catch (error) { console.error('AWBERROR ' + error.message); console.error(JSON.stringify({ success: false, code: error.code || 'INSTALLATION_FAILED', message: error.message })); process.exitCode = 1; }
|
||||
|
||||
@@ -39,6 +39,8 @@ Filename: "{app}\AgentWorkbench.exe"; Description: "打开 Agent Workbench"; Fla
|
||||
|
||||
[Code]
|
||||
var DataRoot: String; Port: String; StageOnly: Boolean; Activated: Boolean; ActivationFailed: Boolean;
|
||||
OperationId: String; LastManagerError: String; PreflightPassed: Boolean; ManagerFinished: Boolean;
|
||||
ManagerPage: TOutputProgressWizardPage;
|
||||
|
||||
function Quoted(Value: String): String;
|
||||
begin
|
||||
@@ -51,16 +53,44 @@ begin
|
||||
DataRoot := ExpandConstant('{param:DATA_ROOT|{localappdata}\AgentWorkbench}');
|
||||
Port := ExpandConstant('{param:PORT|4318}');
|
||||
StageOnly := ExpandConstant('{param:STAGE_ONLY|0}') = '1';
|
||||
OperationId := GetSHA256OfString(ExpandConstant('{tmp}') + GetDateTimeString('yyyy-mm-dd hh:nn:ss', '-', ':'));
|
||||
end;
|
||||
|
||||
procedure ManagerLog(const S: String; const Error, FirstLine: Boolean);
|
||||
var Value: String; Separator: Integer;
|
||||
begin
|
||||
Log(S);
|
||||
if Error and (LastManagerError = '') then LastManagerError := S;
|
||||
if Pos('AWBERROR ', S) = 1 then LastManagerError := Copy(S, 10, Length(S));
|
||||
if Pos('AWBPROGRESS ', S) = 1 then ManagerPage.SetText(Copy(S, 13, Length(S)), '正在核对实际文件和原状态;阶段变化来自安装进程。请保持此窗口打开。');
|
||||
if Pos('AWBFILES ', S) = 1 then begin
|
||||
Value := Copy(S, 10, Length(S)); Separator := Pos('/', Value);
|
||||
ManagerPage.ProgressBar.Visible := Separator > 0;
|
||||
if Separator > 0 then ManagerPage.SetProgress(StrToIntDef(Copy(Value, 1, Separator - 1), 0), StrToIntDef(Copy(Value, Separator + 1, Length(Value)), 1));
|
||||
end;
|
||||
end;
|
||||
|
||||
function RunManager(Command: String; Candidate: Boolean): Boolean;
|
||||
var Parameters: String; ExitCode: Integer;
|
||||
begin
|
||||
LastManagerError := '';
|
||||
Parameters := Quoted(ExpandConstant('{tmp}\awb-install-manager.mjs')) + ' ' + Command +
|
||||
' --install-root ' + Quoted(ExpandConstant('{app}')) + ' --data-root ' + Quoted(DataRoot) + ' --port ' + Quoted(Port);
|
||||
' --install-root ' + Quoted(ExpandConstant('{app}')) + ' --data-root ' + Quoted(DataRoot) + ' --port ' + Quoted(Port) +
|
||||
' --operation-id ' + Quoted(OperationId) + ' --expected-manifest-sha256 {#ManifestSha256}';
|
||||
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);
|
||||
if ManagerPage = nil then ManagerPage := CreateOutputProgressPage('Agent Workbench 版本更新', '核对原版本、当前阶段与实际结果');
|
||||
ManagerPage.SetText('准备核对安装操作', '操作记录:' + ExpandConstant('{app}') + '\.installation\progress-' + OperationId + '.json');
|
||||
ManagerPage.ProgressBar.Visible := False;
|
||||
if Command <> 'cancel' then ManagerPage.Show;
|
||||
WizardForm.CancelButton.Enabled := False;
|
||||
try
|
||||
Result := ExecAndLogOutput(ExpandConstant('{tmp}\awb-install-node.exe'), Parameters, ExpandConstant('{tmp}'), SW_HIDE, ewWaitUntilTerminated, ExitCode, @ManagerLog) and (ExitCode = 0);
|
||||
if not Result and (LastManagerError = '') then LastManagerError := '安装进程未返回成功结果;请保留安装日志及原操作收据。';
|
||||
finally
|
||||
WizardForm.CancelButton.Enabled := True;
|
||||
if Command <> 'cancel' then ManagerPage.Hide;
|
||||
end;
|
||||
end;
|
||||
|
||||
function PrepareToInstall(var NeedsRestart: Boolean): String;
|
||||
@@ -70,19 +100,26 @@ begin
|
||||
if DirExists(ExpandConstant('{app}\versions\{#VersionDirectory}')) then begin
|
||||
Result := '该独立版本目录已经存在。请保留原版本,使用新的安装候选。'; exit;
|
||||
end;
|
||||
if not RunManager('preflight', False) then Result := '安装预检未通过。请等待任务、审批与工具结束并关闭桌面窗口,保留后台执行宿主及原数据;端口和安装身份仍需核对。';
|
||||
PreflightPassed := RunManager('preflight', False);
|
||||
if not PreflightPassed then Result := '安装预检未通过:' + LastManagerError + #13#10 + '原程序和用户数据保留。日志及阶段记录见 .installation 目录。';
|
||||
end;
|
||||
|
||||
procedure CurStepChanged(CurStep: TSetupStep);
|
||||
begin
|
||||
if CurStep = ssPostInstall then begin
|
||||
ActivationFailed := True;
|
||||
if not RunManager('activate', True) then RaiseException('候选激活失败;已尝试恢复原安装指针和执行宿主。请保留 .installation 操作收据核对结果。');
|
||||
if not RunManager('activate', True) then RaiseException('候选激活未完成:' + LastManagerError + #13#10 + '请保留 .installation 原操作收据,核对当前指针和回退结果。');
|
||||
ActivationFailed := False;
|
||||
Activated := not StageOnly;
|
||||
ManagerFinished := True;
|
||||
end;
|
||||
end;
|
||||
|
||||
procedure DeinitializeSetup;
|
||||
begin
|
||||
if PreflightPassed and not ManagerFinished and not ActivationFailed then RunManager('cancel', False);
|
||||
end;
|
||||
|
||||
function GetCustomSetupExitCode: Integer;
|
||||
begin
|
||||
if ActivationFailed then Result := 8 else Result := 0;
|
||||
|
||||
+6
-1
@@ -1,4 +1,5 @@
|
||||
import fs from 'node:fs';
|
||||
import { createHash } from 'node:crypto';
|
||||
import path from 'node:path';
|
||||
import { listFiles, readText, proposeFile, proposePatch, applyChange } from './files.mjs';
|
||||
import { APP_VERSION, executionEnvironment, sessionSnapshot } from './diagnostics.mjs';
|
||||
@@ -19,6 +20,7 @@ import { inspectOperations } from './operations.mjs';
|
||||
import { validateModelWaitSettings } from '../core/models/request-deadline.mjs';
|
||||
import { nativeParameterSettings } from '../shared/contracts/native-parameters.mjs';
|
||||
import { localDirectories } from './local-directories.mjs';
|
||||
import { readInstallationProgress } from '../core/desktop/installation-progress.mjs';
|
||||
|
||||
export function createSessionPublisher(clients) {
|
||||
return session => {
|
||||
@@ -110,6 +112,7 @@ return async (request, response) => {
|
||||
}
|
||||
if (method === 'GET' && route === '/api/host/identity') return json(response, host().attest(url.searchParams.get('challenge')));
|
||||
if (method === 'GET' && route === '/api/host/status') return json(response, host().status());
|
||||
if (method === 'GET' && route === '/api/installation/status') return json(response, { ...readInstallationProgress({ appRoot: appDirectory, dataRoot: store.directory }), runningVersion: APP_VERSION });
|
||||
if (method === 'POST' && route === '/api/host/windows/register') return json(response, host().registerWindow(await body(request)));
|
||||
if (method === 'POST' && route === '/api/host/windows/unregister') {
|
||||
const input = await body(request); const result = host().unregisterWindow(input); runtime.browsing?.disconnect(input.windowId); return json(response, result);
|
||||
@@ -837,7 +840,9 @@ return async (request, response) => {
|
||||
const document = research.find(item => item.id === report[1]);
|
||||
if (!document) throw new Error('研究报告不存在。');
|
||||
const file = path.join(appDirectory, 'docs', document.file);
|
||||
return json(response, { title: document.title, content: fs.existsSync(file) ? fs.readFileSync(file, 'utf8') : '这份报告正在整理,完成后会保存在产品的 docs 目录。' });
|
||||
if (!fs.existsSync(file)) throw Object.assign(new Error('这份原研究报告缺失,请核对完整发行文件。'), { status: 404 });
|
||||
const bytes = fs.readFileSync(file);
|
||||
return json(response, { title: document.title, content: bytes.toString('utf8'), sha256: createHash('sha256').update(bytes).digest('hex') });
|
||||
}
|
||||
if (method === 'POST' && route === '/api/shutdown') {
|
||||
await body(request);
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { randomUUID, createHash } from 'node:crypto';
|
||||
|
||||
export const APP_VERSION = '1.22.1';
|
||||
export const APP_VERSION = '1.23.0';
|
||||
|
||||
export function executionEnvironment() {
|
||||
const windows = process.platform === 'win32';
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { approvalPresentation } from '../shared/approval-presentation.mjs';
|
||||
import { PreviewManager } from '../core/preview/preview-manager.mjs';
|
||||
import { LocalFilePreviews } from '../core/preview/local-file-preview.mjs';
|
||||
import { BrowsingManager } from '../core/browser/browsing-manager.mjs';
|
||||
@@ -712,7 +713,7 @@ export class Runtime {
|
||||
signal.addEventListener('abort', cancel, { once: true });
|
||||
if (signal.aborted) cancel();
|
||||
});
|
||||
if (!decision) { if (!run.controller.signal.aborted) session.status = 'running'; return { status: run.controller.signal.aborted ? 'interrupted' : 'denied', message: '命令未执行。', requires_verification: false }; }
|
||||
if (!decision) { if (!run.controller.signal.aborted) session.status = 'running'; return { status: run.controller.signal.aborted ? 'interrupted' : 'denied', message: approvalPresentation(approval).denied, requires_verification: false }; }
|
||||
run.controller.signal.throwIfAborted();
|
||||
const cwd = safePath(run.project);
|
||||
event.phase = 'running'; event.executedAt = now(); session.status = 'running';
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
export type ApprovalKind = 'browsing' | 'environment' | 'mcp' | 'page-check' | 'check' | 'command';
|
||||
export interface ApprovalSource { kind?: string; browsingTabId?: string; environmentPlanId?: string; mcpRegistrationId?: string; browserPlanId?: string; checkPlanId?: string }
|
||||
export function approvalKind(value?: ApprovalSource): ApprovalKind;
|
||||
export function approvalPresentation(value?: ApprovalSource): { title: string; subject: string; scope: string; denied: string };
|
||||
@@ -0,0 +1,16 @@
|
||||
// Derived from the original approval, never from model prose or page content.
|
||||
export function approvalKind(value = {}) {
|
||||
return value.browsingTabId ? 'browsing' : value.environmentPlanId ? 'environment' : value.mcpRegistrationId ? 'mcp'
|
||||
: value.browserPlanId ? 'page-check' : value.checkPlanId ? 'check' : 'command';
|
||||
}
|
||||
export function approvalPresentation(value = {}) {
|
||||
const kind = value.kind ?? approvalKind(value);
|
||||
return ({
|
||||
browsing: { title: '确认浏览器操作', subject: '浏览器操作', scope: '只在原标签页、原页面观察及已批准范围内执行这次固定动作。', denied: '浏览器操作未执行。' },
|
||||
environment: { title: '确认依赖准备', subject: '依赖准备', scope: '按封存计划准备所属工作区依赖;安装脚本和下载范围如下。', denied: '依赖准备未执行。' },
|
||||
mcp: { title: '确认 MCP 工具调用', subject: 'MCP 工具调用', scope: '向所属 MCP 独立进程发送下方已登记工具与参数。', denied: 'MCP 工具未调用。' },
|
||||
'page-check': { title: '确认实际页面检查', subject: '页面检查', scope: '按封存步骤操作当前构建,保存页面原结果。', denied: '页面检查未执行。' },
|
||||
check: { title: '确认工程检查', subject: '工程检查', scope: '在原项目中执行下方已登记检查。', denied: '工程检查未执行。' },
|
||||
command: { title: '确认这次终端执行', subject: '命令请求', scope: '确认后以你的系统权限执行这条原命令。', denied: '命令未执行。' },
|
||||
})[kind] ?? approvalPresentation({ kind: 'command' });
|
||||
}
|
||||
Reference in New Issue
Block a user