fix: remove open execution record caps and preserve recovery history

This commit is contained in:
Agent Workbench Dev
2026-11-07 03:17:05 +08:00
parent affd733d03
commit 32780bee8d
22 changed files with 595 additions and 74 deletions
+147
View File
@@ -0,0 +1,147 @@
import fs from 'node:fs';
import path from 'node:path';
import net from 'node:net';
import http from 'node:http';
import https from 'node:https';
import { randomUUID, createHash, X509Certificate } from 'node:crypto';
import assert from 'node:assert/strict';
import { chromium, _electron } from 'playwright';
import { expect } from 'playwright/test';
import { fixture, launchWorkbench, until } from '../tests/helpers.mjs';
import { Provider } from '../src/server/provider.mjs';
import { Runtime } from '../src/server/runtime.mjs';
import { HostController } from '../src/core/desktop/host-controller.mjs';
import { desktopExecutableIdentity } from '../src/core/desktop/app-installation.mjs';
import { projectEnvironment } from '../src/core/process-environment.mjs';
import { openWorkbenchTool } from './ui-navigation.mjs';
const desktop = process.argv.includes('--desktop');
assert.ok(process.env.AGENT_WORKBENCH_QA_APP_ROOT, 'Use a separate candidate build');
const appRoot = fs.realpathSync.native(process.env.AGENT_WORKBENCH_QA_APP_ROOT);
const directory = path.resolve('.qa/m1-open-records-2026-11-07', (desktop ? 'electron-' : 'web-') + randomUUID());
fs.mkdirSync(directory); console.log('EVIDENCE ' + directory);
const disposers = [], t = { after: action => disposers.push(action) }, f = fixture(t, { modernDefaults: true }), errors = [], checks = [], screenshots = [];
const runtime = new Runtime(f.store, new Provider()), run = f.store.beginRun(f.session, '自有完整历史与恢复界面样例', false, f.store.config);
f.store.message(f.session, 'user', '自有完整历史与恢复界面样例'); f.session.providerMessages.push({ role: 'user', content: '自有完整历史与恢复界面样例' });
f.session.status = 'paused'; f.store.finishRun(f.session, run, 'owned_ui_fixture');
const oldInput = { scope: 'Synthetic failed MCP display fixture; no process launched', call: null };
for (let index = 0; index < 61; index++) {
const artifact = f.store.artifactStore.write(f.session, run, { ...oldInput, ordinal: index }, { kind: 'mcp-input' }); f.store.core.artifact.set(artifact.id, artifact);
const job = { id: randomUUID(), sessionId: f.session.id, projectId: f.project.id, taskId: run.taskId, runId: run.id,
operation: 'probe', status: 'failed', startedAt: new Date(Date.now() + index).toISOString(), finishedAt: new Date().toISOString(), requiresVerification: false,
processStarted: false, input: { ...oldInput, ordinal: index }, inputArtifactId: artifact.id, inputSha256: artifact.sha256,
error: { code: 'OWNED_DISPLAY_FIXTURE', message: '自有失败记录 ' + index + ';未启动程序,不补造结果。' } };
f.store.core.mcp_job.set(job.id, job);
}
f.store.save(f.session);
const checkpoints = []; for (let index = 0; index < 61; index++) checkpoints.push(await runtime.checkpointManager().create(f.session));
await runtime.stopAll(); f.store.close();
let host, controller, browser, application, page, window, mobile, relay, cookie = '', result;
const mark = text => { checks.push(text); console.log('PASS ' + text); };
async function resize(width, height = 960) {
if (window) { await window.evaluate((win, size) => win.setContentSize(size.width, size.height), { width, height }); await until(() => page.evaluate(w => innerWidth === w, width)); }
else await page.setViewportSize({ width, height });
}
async function shot(name, target = page) {
assert.ok(await target.evaluate(() => document.documentElement.scrollWidth <= innerWidth + 1), 'No page overflow');
const file = path.join(directory, name + '.png'); await target.screenshot({ path: file, scale: 'css' });
screenshots.push({ file: path.basename(file), sha256: createHash('sha256').update(fs.readFileSync(file)).digest('hex') });
fs.writeFileSync(path.join(directory, name + '.txt'), await target.locator('body').innerText());
}
async function closeDialog() { await page.getByRole('dialog').getByRole('button', { name: '关闭窗口', exact: true }).click(); }
try {
if (desktop) {
const server = net.createServer(); await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)); const port = server.address().port; await new Promise(resolve => server.close(resolve));
assert.notEqual(port, 4318); controller = new HostController({ appRoot, dataRoot: f.data, port, nodePath: process.execPath, timeoutMs: 60000 }); await controller.start();
host = { url: controller.url, api: (route, input) => controller.api(route, input === undefined ? {} : { method: 'POST', input }) };
application = await _electron.launch({ executablePath: desktopExecutableIdentity(appRoot).path, args: [path.join(appRoot, 'dist-desktop/main.cjs'), '--app-root', appRoot,
'--data-root', f.data, '--node', process.execPath, '--port', String(port), '--hidden-window'], cwd: appRoot, env: projectEnvironment(), timeout: 60000 });
page = await application.firstWindow(); window = await application.browserWindow(page); await window.evaluate(win => win.showInactive());
} else { host = await launchWorkbench(t, f.data, {}, { appRoot }); assert.notEqual(new URL(host.url).port, '4318'); }
browser = await chromium.launch({ channel: 'msedge', headless: true }); if (!page) page = await browser.newPage();
page.on('pageerror', error => errors.push(error.message));
await page.addInitScript(({ projectId, sessionId }) => { localStorage.setItem('awb-project', projectId); localStorage.setItem('awb-session', sessionId); }, { projectId: f.project.id, sessionId: f.session.id });
await resize(1280); await page.goto(host.url); await page.getByRole('button', { name: '查看任务记录', exact: true }).click();
const checkpointPanel = page.getByLabel('任务恢复检查点', { exact: true }); await expect(checkpointPanel).toContainText('已加载 50 / 61');
const inlineMcp = page.getByLabel('MCP运行记录', { exact: true }); await expect(inlineMcp).toContainText('已加载 50 / 61');
await inlineMcp.getByRole('button', { name: '加载更早的 MCP 记录', exact: true }).click(); await expect(inlineMcp.locator('.mcp-history-row')).toHaveCount(61);
await checkpointPanel.getByRole('button', { name: '加载更早的检查点', exact: true }).click(); await expect(checkpointPanel.locator('.checkpoint-card')).toHaveCount(61);
await checkpointPanel.getByRole('button', { name: '保存恢复检查点', exact: true }).click(); await expect(checkpointPanel).toContainText('已加载 62 / 62');
await checkpointPanel.getByRole('button', { name: '核对恢复条件', exact: true }).last().click(); await expect(checkpointPanel).toContainText('当前可以续接原任务');
await shot('checkpoints-1280'); mark('Checkpoint pagination retains 61 old records when a new checkpoint is saved and verifies the oldest original');
await checkpointPanel.getByRole('button', { name: '查看原恢复包', exact: true }).last().click();
const original = page.getByRole('dialog', { name: '执行结果工件', exact: true }); await expect(original).toContainText('toolIndex'); await page.keyboard.press('Escape');
const readme = path.join(f.projectRoot, 'README.md'), before = fs.readFileSync(readme); fs.appendFileSync(readme, '\nOwned outside edit.\n');
await checkpointPanel.getByRole('button', { name: '核对恢复条件', exact: true }).last().click(); await expect(checkpointPanel).toContainText('工程源码已变化');
fs.writeFileSync(readme, before); await resize(390, 844); await shot('checkpoint-stale-390'); mark('Original v2 index is visible; changed source reports the true recovery failure at 390px');
await resize(1280); await openWorkbenchTool(page, '项目MCP工具');
const mcp = page.getByRole('dialog', { name: '项目 MCP 工具', exact: true }); await expect(mcp).toContainText('已加载 50 / 61');
await mcp.getByRole('button', { name: '加载更早的 MCP 记录', exact: true }).click(); await expect(mcp.locator('.mcp-history-row')).toHaveCount(61);
await mcp.getByRole('button', { name: '刷新', exact: true }).click(); await expect(mcp.locator('.mcp-history-row')).toHaveCount(61);
await mcp.getByRole('button', { name: '查看原始输入', exact: true }).last().click(); await expect(mcp.getByLabel('MCP原报告')).toContainText('"ordinal": 0');
await shot('mcp-history-1280'); await resize(390, 844); await shot('mcp-history-390');
const history = await host.api('/sessions/' + f.session.id + '/mcp/jobs'); assert.equal(history.length, 61);
assert.equal((await host.api('/sessions/' + f.session.id + '/task-checkpoints')).length, 62);
mark('All 61 MCP failures and earliest sealed input stay accessible after refresh; legacy unpaged APIs retain all rows');
await closeDialog(); await resize(1280); await openWorkbenchTool(page, '手机连接');
const panel = page.getByRole('dialog', { name: '手机连接', exact: true }), initial = await host.api('/companion'); assert.ok(initial.addresses.length);
const socket = net.createServer(); await new Promise(resolve => socket.listen(0, initial.addresses[0].address, resolve)); const port = socket.address().port; await new Promise(resolve => socket.close(resolve));
await panel.getByLabel('手机连接端口', { exact: true }).fill(String(port)); await panel.getByRole('button', { name: '开启 HTTPS', exact: true }).click();
await expect(panel).toContainText('手机连接已开启', { timeout: 25000 });
const certificate = path.join(directory, 'owned-ca.cer');
if (application) {
await application.evaluate(({ BrowserWindow }, filename) => { BrowserWindow.getAllWindows()[0].webContents.session.once('will-download', (_event, item) => item.setSavePath(filename)); }, certificate);
await panel.getByRole('button', { name: '下载手机根证书', exact: true }).click(); await until(() => fs.existsSync(certificate) && fs.statSync(certificate).size > 0, 15000);
} else {
const downloaded = page.waitForEvent('download'); await panel.getByRole('button', { name: '下载手机根证书', exact: true }).click(); await (await downloaded).saveAs(certificate);
}
const ca = new X509Certificate(fs.readFileSync(certificate)).toString();
await panel.getByLabel('允许停止任务', { exact: true }).check(); await panel.getByRole('button', { name: '生成一次性配对码', exact: true }).click();
await expect(panel.locator('.companion-pair-url')).toBeVisible(); const pairUrl = await panel.locator('.companion-pair-url').textContent(), target = new URL((await host.api('/companion')).origin);
relay = http.createServer((request, response) => {
const headers = { Host: target.host, Origin: target.origin, Connection: 'close', ...(cookie ? { Cookie: cookie } : {}), ...(request.headers['content-type'] ? { 'Content-Type': request.headers['content-type'] } : {}) };
const outgoing = https.request(new URL(request.url, target), { method: request.method, headers, ca, servername: '' }, incoming => {
if (incoming.headers['set-cookie']?.length) cookie = incoming.headers['set-cookie'][0].split(';')[0];
const received = { ...incoming.headers }; delete received['set-cookie']; response.writeHead(incoming.statusCode, received); incoming.pipe(response);
}); outgoing.on('error', () => { if (!response.headersSent) response.writeHead(503); response.end(); }); request.pipe(outgoing);
});
await new Promise(resolve => relay.listen(0, '127.0.0.1', resolve)); const relayUrl = 'http://127.0.0.1:' + relay.address().port;
mobile = await browser.newPage({ viewport: { width: 390, height: 844 }, isMobile: true, hasTouch: true }); mobile.on('pageerror', error => errors.push(error.message));
await mobile.goto(relayUrl + '/#pair=' + new URLSearchParams(new URL(pairUrl).hash.slice(1)).get('pair'));
await mobile.getByLabel('设备名称', { exact: true }).fill('自有操作历史窗口'); await mobile.getByRole('button', { name: '连接这台电脑', exact: true }).click();
await expect(mobile.getByRole('heading', { name: '项目任务', exact: true })).toBeVisible();
await mobile.goto('about:blank'); // Seed while polling is stopped, then verify a deterministic first page.
for (let index = 0; index < 61; index++) {
const session = await host.api('/sessions/' + f.session.id);
const response = await fetch(relayUrl + '/mobile-api/sessions/' + f.session.id + '/stop', { method: 'POST', headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ requestId: randomUUID(), taskId: session.taskId, runId: session.runId, revision: session.revision }) });
assert.equal(response.status, 200, await response.text());
}
await mobile.goto(relayUrl); await expect(mobile.getByRole('heading', { name: '项目任务', exact: true })).toBeVisible();
const operations = mobile.locator('.mobile-operation-history'); await expect(operations).toContainText('已加载 50 / 61'); await operations.locator('summary').click();
await operations.getByRole('button', { name: '加载更早的手机操作', exact: true }).click(); await expect(operations).toContainText('已加载 61 / 61');
await mobile.getByRole('button', { name: '刷新任务', exact: true }).click(); await expect(operations).toContainText('已加载 61 / 61'); await shot('mobile-operations-390', mobile);
mark('CA-verified real gateway pairing and 61 durable stop receipts paginate and remain expanded on mobile refresh; no task or model was started');
await closeDialog(); await openWorkbenchTool(page, '手机连接'); // Start a fresh page view after the burst of new audit rows.
const audit = panel.locator('.companion-audit'); await expect(audit).toContainText('已加载 50 / 123', { timeout: 15000 }); await audit.locator('summary').click();
await audit.getByRole('button', { name: '加载更早的设备操作', exact: true }).click(); await expect(audit).toContainText('已加载 100 / 123');
await audit.getByRole('button', { name: '加载更早的设备操作', exact: true }).click(); await expect(audit).toContainText('已加载 123 / 123');
await audit.scrollIntoViewIfNeeded(); await shot('companion-audit-1280'); await resize(390, 844); await audit.scrollIntoViewIfNeeded(); await shot('companion-audit-390');
mark('Desktop audit exposes all 123 original actions with accurate loaded/total counts at 1280 and 390px');
await panel.getByRole('button', { name: '撤销', exact: true }).click(); await mobile.getByRole('button', { name: '刷新任务', exact: true }).click();
await expect(mobile.getByRole('heading', { name: '接续电脑上的任务', exact: true })).toBeVisible(); await expect(mobile.locator('.mobile-operation-history')).toHaveCount(0);
mark('Revocation clears mobile operation history and retained authority is rejected');
assert.deepEqual(errors, []); result = { success: true, appRoot, actualElectron: desktop, checks, screenshots, errors, viewportWidths: [1280, 390],
syntheticMcpDisplayRows: 61, actualCompanionStopReceipts: 61, realModelRequests: 0, productionWrites: 0, nativePhone: 'not-tested; CA-verified local relay only' };
} catch (error) {
if (page) await shot('failure').catch(() => {}); if (mobile) await shot('failure-mobile', mobile).catch(() => {});
result = { success: false, appRoot, actualElectron: desktop, checks, screenshots, errors, error: error.stack, realModelRequests: 0 };
} finally {
if (host) await host.api('/companion/close', {}).catch(() => {});
if (relay) await new Promise(resolve => { relay.closeAllConnections(); relay.close(resolve); });
if (browser) await browser.close(); if (application) await application.close();
if (controller && await controller.health()) await controller.stop(); await host?.close?.();
for (const dispose of disposers.reverse()) await dispose();
fs.writeFileSync(path.join(directory, 'result.json'), JSON.stringify(result, null, 2));
}
console.log(JSON.stringify({ directory, ...result })); if (!result.success) process.exitCode = 1;
+6 -3
View File
@@ -2,7 +2,8 @@ import { useEffect, useRef, useState } from 'react';
import { Download, Link2, ShieldCheck, Smartphone, X } from 'lucide-react';
import { api, downloadCompanionCertificate } from './api';
import type { Project } from './types';
import type { CompanionStatus } from './companion-types';
import type { CompanionStatus, CompanionAudit } from './companion-types';
import { useRecordPages } from './useRecordPages';
import './companion-panel.css';
export function CompanionPanel({ projects, selectedProjectId }: { projects: Project[]; selectedProjectId: string }) {
@@ -11,7 +12,8 @@ export function CompanionPanel({ projects, selectedProjectId }: { projects: Proj
const [approve, setApprove] = useState(false), [stop, setStop] = useState(false), [hours, setHours] = useState(24);
const [pair, setPair] = useState<{ url: string; qr: string; expiresAt: string } | null>(null), [busy, setBusy] = useState(''), [error, setError] = useState('');
const mounted = useRef(true);
async function refresh() { const result = await api<CompanionStatus>('/companion'); if (mounted.current) { setStatus(result); setAddress(previous => previous || result.addresses[0]?.address || ''); } }
const audit = useRecordPages<CompanionAudit>('/companion/audit', value => setError(value instanceof Error ? value.message : String(value)));
async function refresh() { const result = await api<CompanionStatus>('/companion'); if (mounted.current) { setStatus(result); setAddress(previous => previous || result.addresses[0]?.address || ''); await audit.refresh(); } }
useEffect(() => {
mounted.current = true; void refresh().catch(value => { if (mounted.current) setError(value.message); });
const timer = setInterval(() => void refresh().catch(() => {}), 5000);
@@ -40,6 +42,7 @@ export function CompanionPanel({ projects, selectedProjectId }: { projects: Proj
{pair && status?.enabled && <div className="companion-pair"><img src={pair.qr} alt="手机一次性配对二维码" width={224} height={224} /><div><strong>使用 iPhone 相机扫描</strong><p>请先完成证书信任。{new Date(pair.expiresAt).toLocaleTimeString()} 失效。</p><p className="companion-pair-url">{pair.url}</p><p>把链接发给自己时,接收者可以取得所选项目权限。完成配对后此链接立即失效。</p></div></div>}
</section>
<section><h3>已登记设备 <span>{status?.devices.length ?? 0}</span></h3>{!status?.devices.length && <p className="companion-note">配对完成后,设备和授权范围会显示在这里。</p>}{status?.devices.map(device => <div key={device.id} className="companion-device"><Smartphone size={18} /><div><strong>{device.name}</strong><p>{device.projectIds.map(id => projects.find(project => project.id === id)?.name ?? '原项目').join('、')} · {device.permissions.approve ? '可审批' : '观察'}{device.permissions.stop ? ' · 可停止' : ''}</p><small>{({ active: '已授权', revoked: '已撤销', expired: '已到期', reconnect_required: '需重新配对' } as Record<string, string>)[device.status ?? ''] ?? device.status} · {new Date(device.expiresAt).toLocaleString()} 到期</small></div><button className="button secondary" disabled={!!busy || device.status !== 'active'} onClick={() => void act('revoke', async () => { await api('/companion/devices/' + device.id + '/revoke', { revision: device.revision }); setPair(null); })}><X size={13} />撤销</button></div>)}</section>
{!!status?.audit.length && <details className="companion-audit"><summary>最近的设备操作</summary>{status.audit.slice(0, 12).map(item => <p key={item.id}><time>{new Date(item.at).toLocaleTimeString()}</time><span>{status.devices.find(device => device.id === item.deviceId)?.name ?? '原设备'} · {({ pair: '配对', rotate: '轮换会话', revoke: '撤销', approve: '审批', stop: '停止' } as Record<string, string>)[item.action] ?? item.action}</span><code>{item.status}</code></p>)}</details>}
{status && <details className="companion-audit"><summary>设备操作记录 · 已加载 {audit.items.length} / {audit.total} 项</summary>{audit.items.map(item => <p key={item.id}><time>{new Date(item.at).toLocaleString('zh-CN')}</time><span>{status.devices.find(device => device.id === item.deviceId)?.name ?? '原设备'} · {({ pair: '配对', rotate: '轮换会话', revoke: '撤销', approve: '审批', stop: '停止' } as Record<string, string>)[item.action] ?? item.action}</span><code>{item.status}</code></p>)}
{audit.hasMore && <button type="button" className="button secondary" disabled={audit.loading} onClick={() => void audit.loadMore()}>加载更早的设备操作</button>}</details>}
</div>;
}
+16 -5
View File
@@ -3,6 +3,7 @@ import { AlertTriangle, Check, CircleAlert, Clock3, Download, FileText, LoaderCi
import type { McpJob, Session } from './types';
import { api } from './api';
import { Modal } from './components';
import { useRecordPages } from './useRecordPages';
import './McpPanel.css';
const active = ['queued', 'connecting', 'discovering', 'calling', 'closing', 'stopping'];
@@ -10,15 +11,24 @@ const labels: Record<string, string> = { queued: '排队', connecting: '正在
const timestamp = (value: string | null) => value ? new Date(value).toLocaleString('zh-CN', { month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit' }) : '进行中';
type Evidence = { job: McpJob; report: Record<string, unknown> | null; input: { artifactId: string; sha256: string; input: Record<string, unknown> }; evidenceSha256: string; note: string };
export function McpJobHistory({ session, jobs, busy, onSession, onError }: {
session: Session; jobs: McpJob[]; busy: boolean; onSession: (value: Session) => void; onError: (error: unknown) => void;
export function PaginatedMcpJobHistory({ session, busy, onSession, onError }: {
session: Session; busy: boolean; onSession: (value: Session) => void; onError: (error: unknown) => void;
}) {
const history = useRecordPages<McpJob>('/sessions/' + session.id + '/mcp/jobs', onError);
useEffect(() => { void history.refresh(); }, [session.revision, history.refresh]);
return <McpJobHistory session={session} jobs={history.items} total={history.total} hasMore={history.hasMore} loading={history.loading}
loadMore={history.loadMore} busy={busy} onSession={onSession} onError={onError} />;
}
export function McpJobHistory({ session, jobs, total = jobs.length, hasMore = false, loading = false, loadMore, busy, onSession, onError }: {
session: Session; jobs: McpJob[]; total?: number; hasMore?: boolean; loading?: boolean; loadMore?: () => Promise<void>; busy: boolean; onSession: (value: Session) => void; onError: (error: unknown) => void;
}) {
const [selected, setSelected] = useState<Evidence | null>(null);
const [review, setReview] = useState<Evidence | null>(null);
const [working, setWorking] = useState(false);
const request = useRef(0);
const currentTask = session.execution?.task?.id;
const visible = jobs.filter(job => job.taskId === currentTask || job.requiresVerification).slice().reverse();
const visible = jobs;
useEffect(() => { request.current++; setSelected(null); setReview(null); setWorking(false); }, [session.id, currentTask]);
async function open(job: McpJob, forReview = false) {
@@ -42,7 +52,7 @@ export function McpJobHistory({ session, jobs, busy, onSession, onError }: {
return <>
<section className="task-record-section mcp-history" aria-label="MCP运行记录">
<div className="record-heading"><ShieldCheck size={15} /><h3>MCP 运行记录</h3><span>{visible.length} 项</span></div>
<div className="record-heading"><ShieldCheck size={15} /><h3>MCP 运行记录</h3><span>已加载 {visible.length} / {total} 项</span></div>
{visible.length ? <div className="mcp-history-list">{visible.map(job => <article className={'mcp-history-row state-' + job.status} key={job.id}>
<div className="mcp-history-title"><div><strong>{job.input?.call?.tool || (job.operation === 'probe' ? '协议与工具探测' : '工具调用')}</strong><small>{timestamp(job.startedAt)} · {job.operation === 'probe' ? '探测' : '调用'}</small></div>
<span className={'mcp-job-state state-' + job.status}>{active.includes(job.status) && <LoaderCircle size={12} className="spin" />}{job.requiresVerification && <CircleAlert size={12} />}{job.status === 'unknown' && job.reviewedAt && !job.requiresVerification ? '已人工核对 · 原结果未知' : labels[job.status] ?? job.status}</span></div>
@@ -51,7 +61,8 @@ export function McpJobHistory({ session, jobs, busy, onSession, onError }: {
{job.error?.message && <p className="mcp-history-error">{job.error.message}</p>}
<div className="mcp-history-actions"><button type="button" className="button secondary" disabled={!job.inputArtifactId || working} onClick={() => void open(job)}><FileText size={14} />{job.reportArtifactId ? '查看原报告' : '查看原始输入'}</button>
{job.requiresVerification && <button type="button" className="button secondary" disabled={busy || working || !job.inputArtifactId} onClick={() => void open(job, true)}><AlertTriangle size={14} />人工核对结果</button>}</div>
</article>)}</div> : <p className="mcp-history-empty"><Clock3 size={15} />当前任务还没有 MCP 操作记录。</p>}
</article>)}</div> : <p className="mcp-history-empty"><Clock3 size={15} />{loading ? '正在读取 MCP 记录。' : '当前会话还没有 MCP 操作记录。'}</p>}
{hasMore && <button type="button" className="button secondary" disabled={loading} onClick={() => void loadMore?.()}>{loading && <LoaderCircle size={13} className="spin" />}加载更早的 MCP 记录</button>}
{selected && <section className="mcp-report" aria-label="MCP原报告"><header><strong>{selected.report ? '原始 MCP 报告' : '已封存的原始输入'}</strong><button type="button" className="text-button" onClick={() => setSelected(null)}>关闭</button></header>
<div className="mcp-report-meta"><span>SHA256</span><code>{selected.job.reportSha256 ?? selected.input.sha256}</code><span>Task / Run</span><code>{selected.job.taskId} / {selected.job.runId}</code></div>
<p className="mcp-boundary-note">报告绑定原 Task/Run 和工具输入。独立所属进程不等于 OS 沙箱,报告也不能证明外部程序没有网络或其他副作用。</p>
+16 -19
View File
@@ -5,18 +5,20 @@ import type { McpJob, McpRegistration, Session } from './types';
import { api } from './api';
import { Modal } from './components';
import { McpJobHistory } from './McpJobHistory';
import { useRecordPages } from './useRecordPages';
import { approvalLabels, mcpPermissionContext } from '../shared/contracts/execution-policy.mjs';
import './McpPanel.css';
const active = ['queued', 'connecting', 'discovering', 'calling', 'closing', 'stopping'];
const stateName: Record<string, string> = { verified: '握手已核验', unverified: '尚未探测', changed: '来源或契约异常' };
type View = { projectId: string; revision: number; protocolVersion: string; boundary: string; limits: Record<string, number>; registrations: McpRegistration[] };
type View = { projectId: string; revision: number; protocolVersion: string; boundary: string; executionMode: string; limits: Record<string, number | null>; registrations: McpRegistration[] };
type Draft = { name: string; executable: string; entry: string; timeoutMs: number };
export function McpPanel({ projectId, session, busy, approvalMode = 'ask', onSession, onError }: {
projectId: string; session: Session | null; busy: boolean; approvalMode?: 'ask' | 'auto' | 'full'; onSession: (value: Session) => void; onError: (error: unknown) => void;
}) {
const [view, setView] = useState<View | null>(null), [jobs, setJobs] = useState<McpJob[]>([]);
const [view, setView] = useState<View | null>(null);
const history = useRecordPages<McpJob>(session ? '/sessions/' + session.id + '/mcp/jobs' : null, onError), jobs = history.items;
const [working, setWorking] = useState(false), [error, setError] = useState(''), [notice, setNotice] = useState('');
const [selectedTools, setSelectedTools] = useState<Record<string, string[]>>({});
const [draft, setDraft] = useState<Draft>({ name: '', executable: '', entry: '', timeoutMs: 15000 });
@@ -30,11 +32,9 @@ export function McpPanel({ projectId, session, busy, approvalMode = 'ask', onSes
useEffect(() => { mounted.current = true; return () => { mounted.current = false; generation.current++; }; }, []);
async function load(current = generation.current) {
const [nextView, nextJobs] = await Promise.all([
api<View>(url), session ? api<McpJob[]>('/sessions/' + session.id + '/mcp/jobs') : Promise.resolve([] as McpJob[]),
]);
const [nextView] = await Promise.all([api<View>(url), history.refresh()]);
if (!mounted.current || current !== generation.current) return;
setView(nextView); setJobs(nextJobs);
setView(nextView);
setSelectedTools(previous => {
const next = { ...previous };
for (const registration of nextView.registrations) if (revisions.current.get(registration.id) !== registration.configurationRevision) {
@@ -44,17 +44,15 @@ export function McpPanel({ projectId, session, busy, approvalMode = 'ask', onSes
});
}
useEffect(() => {
const current = ++generation.current; setView(null); setJobs([]); setError(''); setNotice(''); setProbeTarget(null);
const current = ++generation.current; setView(null); setError(''); setNotice(''); setProbeTarget(null);
void load(current).catch(cause => { if (mounted.current && generation.current === current) setError(cause instanceof Error ? cause.message : String(cause)); });
return () => { if (generation.current === current) generation.current++; };
}, [projectId, session?.id]);
useEffect(() => {
if (!session || !jobs.some(job => active.includes(job.status))) return;
const current = generation.current, previous = jobs;
const timer = window.setInterval(() => { void api<McpJob[]>('/sessions/' + session.id + '/mcp/jobs').then(async next => {
if (!mounted.current || generation.current !== current) return;
setJobs(next);
if (previous.some(job => active.includes(job.status)) && !next.some(job => active.includes(job.status))) setView(await api<View>(url));
const current = generation.current;
const timer = window.setInterval(() => { void Promise.all([history.refresh(), api<View>(url)]).then(([, nextView]) => {
if (mounted.current && generation.current === current) setView(nextView);
}).catch(cause => { if (generation.current === current) setError(cause instanceof Error ? cause.message : String(cause)); }); }, 900);
return () => window.clearInterval(timer);
}, [jobs, projectId, session?.id]);
@@ -79,7 +77,6 @@ export function McpPanel({ projectId, session, busy, approvalMode = 'ask', onSes
const result = await api<{ job: McpJob; session: Session }>('/sessions/' + session.id + '/mcp/probe', { id: target.id, configurationRevision: target.configurationRevision, confirm: true });
onSession(result.session); setProbeTarget(null); setNotice('探测已启动;完成后根据实际握手和参数契约选择工具。');
const current = generation.current; await load(current);
setJobs(previous => previous.some(job => job.id === result.job.id) ? previous : [result.job, ...previous].slice(0, 30));
} catch (cause) { setRequestError(cause instanceof Error ? cause.message : String(cause)); }
finally { setWorking(false); }
}
@@ -111,12 +108,12 @@ export function McpPanel({ projectId, session, busy, approvalMode = 'ask', onSes
<div className="mcp-registration-heading"><Terminal size={18} /><div><h4>{registration.name}</h4><p>{stateName[registration.status] ?? registration.status} · 配置修订 {registration.configurationRevision}</p></div><span className={'mcp-enabled ' + (registration.enabled ? 'on' : '')}>{registration.enabled ? '已启用' : '已停用'}</span></div>
<div className="mcp-source"><div><span>可执行文件</span><code>{registration.launch.executable.path}</code><small><Fingerprint size={12} /> SHA256 {registration.launch.executable.sha256.slice(0, 16)} · {registration.launch.executable.bytes.toLocaleString()} B</small></div>
{registration.launch.entry && <div><span>脚本入口</span><code>{registration.launch.entry.path}</code><small>SHA256 {registration.launch.entry.sha256.slice(0, 16)} · {registration.launch.entry.bytes.toLocaleString()} B</small></div>}
<span>请求上限 {registration.timeoutMs.toLocaleString()} ms</span></div>
<span>{view.executionMode === 'unrestricted' ? '开放执行 · 不设请求超时' : '请求上限 ' + registration.timeoutMs.toLocaleString() + ' ms'}</span></div>
{registration.reason && <p className="mcp-warning">{registration.reason}</p>}
{registration.contract && <div className="mcp-contract-line"><Check size={13} />实际契约 SHA256 {registration.contract.sha256.slice(0, 16)} · 发现 {registration.tools.length} 项工具</div>}
{registration.contract && <div className="mcp-tool-list"><div className="mcp-tool-heading"><strong>允许模型请求的工具</strong><span>已选择 {chosen.length} / 12</span></div>
{registration.contract && <div className="mcp-tool-list"><div className="mcp-tool-heading"><strong>允许模型请求的工具</strong><span>已选择 {chosen.length}{view.limits.allowedTools === null ? ' · 数量不限' : ' / ' + view.limits.allowedTools}</span></div>
{registration.tools.map(tool => <label className={'mcp-tool-option ' + (tool.unsupported ? 'unsupported' : '')} key={tool.name}>
<input type="checkbox" checked={chosen.includes(tool.name)} disabled={locked || !!tool.unsupported || registration.status !== 'verified' || chosen.length >= 12 && !chosen.includes(tool.name)} onChange={event => setSelectedTools(previous => ({ ...previous,
<input type="checkbox" checked={chosen.includes(tool.name)} disabled={locked || !!tool.unsupported || registration.status !== 'verified' || view.limits.allowedTools !== null && chosen.length >= (view.limits.allowedTools ?? 12) && !chosen.includes(tool.name)} onChange={event => setSelectedTools(previous => ({ ...previous,
[registration.id]: event.target.checked ? [...chosen, tool.name] : chosen.filter(name => name !== tool.name) }))} />
<span><strong>{tool.name}</strong>{tool.unsupported && <em>参数契约不受支持</em>}<small>{tool.description || '未提供用途说明'}</small>
<details><summary>查看参数契约</summary><pre>{JSON.stringify(tool.inputSchema, null, 2)}</pre>{tool.unsupported && <code>{tool.unsupported}</code>}</details></span>
@@ -131,14 +128,14 @@ export function McpPanel({ projectId, session, busy, approvalMode = 'ask', onSes
})}</div> : view && <div className="mcp-empty"><PlugZap size={24} /><strong>尚未登记项目 MCP</strong><p>只登记你已审查的本地可执行文件。程序和 Node 入口会在探测及启用前重新计算 SHA256。</p></div>}
{!view && !error && <p className="mcp-empty"><LoaderCircle size={18} className="spin" />正在读取项目注册</p>}
<form className="mcp-register" onSubmit={register}>
<div className="mcp-register-heading"><h4><Plus size={16} />登记本地 MCP</h4><span>绝对路径 · 默认停用 · 最多 {view?.limits.registrations ?? 16} 项</span></div>
<div className="mcp-register-heading"><h4><Plus size={16} />登记本地 MCP</h4><span>绝对路径 · 默认停用 · {view?.limits.registrations === null ? '登记数量不限' : '最多 ' + (view?.limits.registrations ?? 16) + ' 项'}</span></div>
<div className="mcp-form-grid"><label>显示名称<input required value={draft.name} maxLength={100} onChange={event => setDraft({ ...draft, name: event.target.value })} placeholder="例如:项目只读检索" /></label>
<label>请求超时(毫秒)<input required type="number" min={500} max={45000} step={500} value={draft.timeoutMs} onChange={event => setDraft({ ...draft, timeoutMs: Number(event.target.value) })} /></label>
<label>{view?.executionMode === 'unrestricted' ? '手动限制模式的超时(毫秒)' : '请求超时(毫秒)'}<input required type="number" min={500} max={45000} step={500} value={draft.timeoutMs} onChange={event => setDraft({ ...draft, timeoutMs: Number(event.target.value) })} /></label>
<label className="mcp-full">可执行文件绝对路径<input required value={draft.executable} onChange={event => setDraft({ ...draft, executable: event.target.value })} placeholder="C:\Tools\my-mcp.exe 或当前 Node.js 可执行文件" /></label>
<label className="mcp-full">Node 脚本入口(可选)<input value={draft.entry} onChange={event => setDraft({ ...draft, entry: event.target.value })} placeholder="仅接受 .js、.mjs、.cjs;留空表示直接启动可执行文件" /></label></div>
<footer><span>仅保留系统路径与临时目录环境,不传入模型 Key;不安装脚本、不使用 shell。</span><button type="submit" className="button primary" disabled={locked || !draft.name.trim() || !draft.executable.trim()}>{working ? <LoaderCircle size={14} className="spin" /> : <Plus size={14} />}登记后保持停用</button></footer>
</form>
{session && <McpJobHistory session={session} jobs={jobs} busy={locked} onSession={onSession} onError={onError} />}
{session && <McpJobHistory session={session} jobs={jobs} total={history.total} hasMore={history.hasMore} loading={history.loading} loadMore={history.loadMore} busy={locked} onSession={onSession} onError={onError} />}
{!session && <p className="mcp-empty">选择或创建一个任务会话后,可以对已登记程序执行探测。</p>}
{probeTarget && <Modal title="启动 MCP 实际探测" description="工作台将启动该登记程序、核对固定协议并读取实际工具 schema,不调用工具或模型。" onClose={() => { setProbeTarget(null); setRequestError(''); }}>
<div className="mcp-probe-summary"><strong>{probeTarget.name}</strong><code>{probeTarget.launch.executable.path}</code>{probeTarget.launch.entry && <code>{probeTarget.launch.entry.path}</code>}
+8 -8
View File
@@ -2,6 +2,7 @@ import { useEffect, useRef, useState } from 'react';
import { Archive, FileText, LoaderCircle, Play, RefreshCw, Save } from 'lucide-react';
import { api } from './api';
import type { Session, TaskCheckpoint, TaskCheckpointView } from './types';
import { useRecordPages } from './useRecordPages';
export function TaskCheckpointPanel({ session, busy, onSession, onError, openArtifact }: {
session: Session; busy: boolean; onSession: (value: Session) => void; onError: (error: unknown) => void; openArtifact: (id: string) => void;
@@ -10,15 +11,13 @@ export function TaskCheckpointPanel({ session, busy, onSession, onError, openArt
const scope = `${session.id}/${task?.id}/${run?.id}`;
const selectedScope = useRef(scope); selectedScope.current = scope;
const request = useRef(0);
const [records, setRecords] = useState<TaskCheckpoint[]>([]), [view, setView] = useState<TaskCheckpointView | null>(null);
const history = useRecordPages<TaskCheckpoint>(task ? `/sessions/${session.id}/task-checkpoints` : null, onError, api, scope), records = history.items;
const [view, setView] = useState<TaskCheckpointView | null>(null);
const [working, setWorking] = useState(false), [notice, setNotice] = useState('');
const disabled = busy || working || ['running', 'awaiting_approval', 'stopping'].includes(session.status);
useEffect(() => {
let alive = true; const id = ++request.current; setRecords([]); setView(null); setWorking(false); setNotice('');
if (task) api<TaskCheckpoint[]>(`/sessions/${session.id}/task-checkpoints`).then(values => {
if (alive && selectedScope.current === scope && request.current === id) setRecords(values.filter(value => value.taskId === task.id));
}).catch(error => { if (alive && selectedScope.current === scope) onError(error); });
return () => { alive = false; request.current++; };
request.current++; setView(null); setWorking(false); setNotice(''); void history.refresh();
return () => { request.current++; };
}, [scope]);
if (!task || !run) return null;
async function save() {
@@ -27,7 +26,7 @@ export function TaskCheckpointPanel({ session, busy, onSession, onError, openArt
try {
const value = await api<{ checkpoint: TaskCheckpoint; session: Session }>(`/sessions/${session.id}/task-checkpoints`, { taskId: task.id, runId: run.id });
if (selectedScope.current === scope && request.current === id) {
onSession(value.session); setRecords(values => [value.checkpoint, ...values]); setView(null); setNotice('恢复检查点已保存;继续前还会核对当前工程。');
onSession(value.session); await history.refresh(); setView(null); setNotice('恢复检查点已保存;继续前还会核对当前工程。');
}
} catch (error) { if (selectedScope.current === scope && request.current === id) onError(error); }
finally { if (selectedScope.current === scope && request.current === id) setWorking(false); }
@@ -48,7 +47,7 @@ export function TaskCheckpointPanel({ session, busy, onSession, onError, openArt
finally { if (selectedScope.current === scope && request.current === id) setWorking(false); }
}
return <section className="task-record-section task-checkpoints" aria-label="任务恢复检查点">
<div className="record-heading"><Archive size={15} /><h3>恢复检查点</h3><span>{records.length} 个</span></div>
<div className="record-heading"><Archive size={15} /><h3>恢复检查点</h3><span>已加载 {records.length} / {history.total} 个</span></div>
<p className="record-footnote">保存完整目标、原工具结果和待处理项;续接前核对源码与任务身份。</p>
<button type="button" className="button secondary" onClick={() => void save()} disabled={disabled}>{working ? <LoaderCircle size={13} className="spin" /> : <Save size={13} />}保存恢复检查点</button>
{notice && <p className="record-footnote" role="status">{notice}</p>}
@@ -59,6 +58,7 @@ export function TaskCheckpointPanel({ session, busy, onSession, onError, openArt
<div className="context-actions"><button type="button" className="text-button" disabled={disabled} onClick={() => void inspect(checkpoint)}><RefreshCw size={13} />核对恢复条件</button>
<button type="button" className="text-button" onClick={() => openArtifact(checkpoint.artifactId)}><FileText size={13} />查看原恢复包</button></div>
</article>)}
{history.hasMore && <button type="button" className="button secondary" disabled={history.loading} onClick={() => void history.loadMore()}>{history.loading && <LoaderCircle size={13} className="spin" />}加载更早的检查点</button>}
{view && <div className="checkpoint-assessment" role="status"><strong>{view.resumable ? '当前可以续接原任务' : '暂不能从此检查点续接'}</strong>
{view.reasons.length > 0 && <ul>{view.reasons.map(reason => <li key={reason}>{reason}</li>)}</ul>}
{view.resumable && <button type="button" className="button primary" disabled={disabled} onClick={() => void resume()}><Play size={13} />从已核对检查点继续</button>}
+2 -2
View File
@@ -12,7 +12,7 @@ import { TaskPlanPanel } from './TaskPlanPanel';
import { RequirementPanel } from './RequirementPanel';
import { TurnProgress } from './TurnProgress';
import { TaskCheckpointPanel } from './TaskCheckpointPanel';
import { McpJobHistory } from './McpJobHistory';
import { PaginatedMcpJobHistory } from './McpJobHistory';
import './TaskPanel.css';
import { EnvironmentPanel } from './EnvironmentPanel';
import { PreviewPanel } from './PreviewPanel';
@@ -107,7 +107,7 @@ export function TaskPanel({ project, session, onSession, onError, busy, onWorksp
{task && <RequirementPanel session={session} busy={busy} onSession={onSession} onError={onError} openArtifact={openArtifact} />}
{task && <TaskCheckpointPanel session={session} busy={busy} onSession={onSession} onError={onError} openArtifact={openArtifact} />}
{execution?.progress.requiresVerification.length ? <section className="verification-note" role="status"><ShieldQuestion size={17} /><div><strong>{execution.progress.requiresVerification.length} 项结果需要核对</strong><p>这些调用已进入执行,但缺少可靠结果。继续任务会保留记录。</p>{execution.progress.requiresVerification.map(tool => <code key={tool.id}>{tool.tool} · {tool.id.slice(0, 8)}</code>)}</div></section> : null}
{task && !!execution?.mcpJobs?.length && <McpJobHistory session={session} jobs={execution.mcpJobs} busy={busy} onSession={onSession} onError={onError} />}
{task && !!(execution?.mcpJobCount || execution?.mcpJobs?.length) && <PaginatedMcpJobHistory session={session} busy={busy} onSession={onSession} onError={onError} />}
{task && <section className="task-record-section">
<div className="record-heading"><h3>运行记录</h3><span>{execution?.runs.filter(item => item.taskId === task.id).length} 次</span></div>
<label className="run-picker">选择一次运行<select aria-label="选择运行记录" value={id} onChange={event => setRunId(event.target.value)}>{execution?.runs.filter(item => item.taskId === task.id).map((item, index) => <option key={item.id} value={item.id}>第 {index + 1} 次 · {time(item.startedAt)}{item.resumeOf ? ' · 接续' : ''}</option>)}</select></label>
+4 -1
View File
@@ -1,10 +1,13 @@
import type { RecordPage } from './types';
export interface CompanionPermissions { observe: boolean; approve: boolean; stop: boolean }
export interface CompanionAudit { id: string; at: string; deviceId: string; action: string; status: string; taskId?: string }
export interface MobileOperation { id: string; requestId: string; action: string; status: string; taskId: string; runId: string; createdAt: string }
export interface CompanionDevice { id: string; name: string; projectIds: string[]; permissions: CompanionPermissions; revision: number; expiresAt: string; createdAt?: string; status?: string }
export interface CompanionStatus {
enabled: boolean; busy: boolean; origin: string | null; addresses: { name: string; address: string }[];
gatewayId: string; revision: number; devices: CompanionDevice[];
certificate: { sha256: string; expiresAt: string } | null;
audit: { id: string; at: string; deviceId: string; action: string; status: string; taskId?: string }[];
audit: CompanionAudit[]; auditPage: RecordPage<CompanionAudit>;
}
export interface MobileBrief { id: string; projectId: string; taskId?: string; runId?: string; title: string; status: string; revision: number; eventSeq: number; updatedAt: string }
export interface MobileUsage { totalTokens: number; unknownRequests: number; estimatedUnknownTokens: number }
+10 -4
View File
@@ -2,7 +2,9 @@ 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';
import type { CompanionDevice, MobileBrief, MobileTask, MobileOperation } from '../companion-types';
import { useRecordPages } from '../useRecordPages';
import type { RecordPage } from '../types';
import { mobileApi, MobileError, verifiedText, verifyDigest } from './api';
import { MobileInputImage } from './MobileInputImage';
import './file-results.css';
@@ -13,7 +15,7 @@ import { Palette as PaletteIcon } from 'lucide-react';
const stateLabel = (state: string) => ({ idle: '未开始', waiting: '等待审批', validating: '校验中', queued: '排队中', executing: '执行中', error: '错误', running: '执行中', awaiting_approval: '等待审批', stopping: '正在停止', completed: '已完成', needs_review: '待审查', failed: '失败', interrupted: '已中断', cancelled: '已停止', paused: '已暂停', unknown: '需核对', completed_with_changes: '待审查', passed: '通过', pending: '待处理', applied: '已应用', denied: '已拒绝', approved: '已批准', conflict: '有冲突', unverified: '需核对', stale: '已变化' } as Record<string, string>)[state] ?? state;
const time = (value: string) => new Date(value).toLocaleString('zh-CN', { month: 'numeric', day: 'numeric', hour: '2-digit', minute: '2-digit' });
type Me = { device: CompanionDevice; gatewayId: string; operations: { requestId: string; action: string; status: string; taskId: string; runId: string; createdAt: string }[] };
type Me = { device: CompanionDevice; gatewayId: string; operations: MobileOperation[]; operationsPage: RecordPage<MobileOperation>; unresolvedOperations: MobileOperation[] };
type Decision = { requestId: string; kind: 'approve' | 'stop'; task: MobileTask; approval?: MobileTask['approvals'][number]; allow?: boolean };
export function MobileApp({ initialToken }: { initialToken: string }) {
@@ -24,6 +26,8 @@ export function MobileApp({ initialToken }: { initialToken: string }) {
const [busy, setBusy] = useState(''), [error, setError] = useState(''), [fresh, setFresh] = useState(false), [lastSync, setLastSync] = useState('');
const [connectionRequired, setConnectionRequired] = useState(!!initialToken), [decision, setDecision] = useState<Decision | null>(null);
const [document, setDocument] = useState<{ title: string; text: string; sha256: string; redacted?: boolean } | null>(null), [receipt, setReceipt] = useState('');
const operations = useRecordPages<MobileOperation>(me ? '/operations' : null, value => setError(value instanceof Error ? value.message : String(value)), mobileApi, me ? me.gatewayId + '/' + me.device.id + '/' + me.device.revision : null);
useEffect(() => { if (me) void operations.refresh(); }, [me]);
const cursor = useRef(0), identity = useRef<Me | null>(null), chosen = useRef(''), running = useRef(false), actionBusy = useRef(false), alive = useRef(true), generation = useRef(0), dialog = useRef<HTMLDialogElement>(null), documentDialog = useRef<HTMLDialogElement>(null);
const revoke = useCallback((message: string) => {
generation.current++; identity.current = null; cursor.current = 0; chosen.current = '';
@@ -117,12 +121,14 @@ export function MobileApp({ initialToken }: { initialToken: string }) {
{appearanceOpen && <Modal title="外观" description="选择适合你的工作台配色,切换后立即生效。" onClose={() => setAppearanceOpen(false)}><AppearancePanel /></Modal>}
{me && <div className={'mobile-connection ' + (fresh ? '' : 'disconnected')}>{fresh ? <Wifi size={14} /> : <WifiOff size={14} />}<span>{fresh ? '已同步 · ' + time(lastSync) : '连接中断 · 当前内容可能已过期'}</span><span>{me.device.permissions.approve ? '可审批' : '观察'}</span></div>}
{error && <div className="mobile-error" role="alert"><strong>{fresh ? '操作未完成' : connectionRequired ? '需要连接' : '连接待恢复'}</strong><p>{error}</p>{me && <button onClick={() => void refresh()} disabled={!!busy}>重新同步</button>}</div>}
{me?.operations?.some(value => value.status === 'unknown') && <div className="mobile-unknown"><strong>手机操作回执需要核对</strong><p>有原审批或停止操作没有完整回执,请在电脑核对;手机不会自动重放。</p>{me.operations.filter(value => value.status === 'unknown').map(value => <code key={value.requestId}>Task {value.taskId} · {value.action === 'stop' ? '停止' : '审批'}</code>)}</div>}
{!!me?.unresolvedOperations?.length && <div className="mobile-unknown"><strong>手机操作回执需要核对</strong><p>有原审批或停止操作没有完整回执,请在电脑核对;手机不会自动重放。</p>{me.unresolvedOperations.map(value => <code key={value.requestId}>Task {value.taskId} · {value.action === 'stop' ? '停止' : '审批'}</code>)}</div>}
{me && <details className="mobile-operation-history"><summary>手机操作记录 · 已加载 {operations.items.length} / {operations.total} 项</summary>{operations.items.map(value => <p key={value.id}>{value.action === 'stop' ? '停止' : '审批'} · {value.taskId.slice(0, 8)} · {stateLabel(value.status)} · {time(value.createdAt)}</p>)}
{operations.hasMore && <button type="button" disabled={operations.loading} onClick={() => void operations.loadMore()}>加载更早的手机操作</button>}</details>}
{!me && <main className="mobile-pair-page"><div className="mobile-pair-heading"><Link2 size={32} /><h1>接续电脑上的任务</h1><p>在 Windows 工作台打开「手机连接」,选择项目并生成一次性配对码。</p></div>{connectionRequired || pairToken ? <form onSubmit={event => void pair(event)}><label>设备名称<input value={name} maxLength={60} onChange={event => setName(event.target.value)} autoComplete="off" /></label><label>配对码或配对链接<input type="password" value={pairToken} onChange={event => setPairToken(event.target.value)} autoComplete="off" autoCapitalize="none" spellCheck={false} placeholder="扫描电脑上的二维码后自动填写" /></label><button className="mobile-primary" disabled={!!busy || !pairToken.trim() || !name.trim()}>{busy === 'pair' ? '正在核对授权…' : '连接这台电脑'}</button></form> : <p role="status">正在核对当前手机连接…</p>}<div className="mobile-pair-help"><ShieldCheck size={18} /><p>首次使用需要在 iPhone 安装并信任电脑生成的根证书。请按电脑「手机连接」中的指引操作。</p></div></main>}
{me && !selected && <main className="mobile-task-list"><div className="mobile-page-title"><div><span className="mobile-eyebrow">{me.device.name}</span><h1>项目任务</h1></div><span>{sessions.length} 个会话</span></div><label className="mobile-project-filter"><Folder size={17} /><select aria-label="筛选项目" value={project} onChange={event => setProject(event.target.value)}><option value="">全部授权项目</option>{projects.map(item => <option key={item.id} value={item.id}>{item.name}</option>)}</select></label>
{!sessions.length && <div className="mobile-empty"><ClipboardCheck size={30} /><h2>暂无任务</h2><p>在电脑创建或打开任务,手机会同步该项目的执行进展。</p></div>}
{sessions.filter(item => !project || item.projectId === project).map(item => <button className="mobile-task-row" key={item.id} onClick={() => void openTask(item.id)}><div><span className="mobile-project-name">{projectName(item.projectId)}</span><strong>{item.title}</strong><span className="mobile-row-meta"><span className={'mobile-state state-' + item.status}>{stateLabel(item.status)}</span><time>{time(item.updatedAt)}</time></span></div><ChevronRight size={19} /></button>)}
<details className="mobile-device-settings"><summary>设备连接与授权</summary><p>{projects.map(item => item.name).join('、')}</p><p>观察{me.device.permissions.approve ? ' · 审批' : ''}{me.device.permissions.stop ? ' · 停止' : ''} · {time(me.device.expiresAt)} 到期</p><p>手机显示最近200个未归档会话,完整历史在电脑保留。</p><p>iPhone Safari 中点「共享 → 添加到主屏幕」可安装伴随端。主屏幕应用如要求连接,请在电脑生成新的配对码。</p><div><button disabled={!!busy || !fresh} onClick={() => void act('rotate', async () => { await mobileApi('/rotate', {}); await refresh(); setReceipt('手机会话已轮换。'); })}>轮换手机会话</button><button disabled={!!busy} onClick={() => void act('logout', async () => { await mobileApi('/logout', {}); revoke('已断开并撤销这台手机。'); })}>断开并撤销</button></div></details></main>}
<details className="mobile-device-settings"><summary>设备连接与授权</summary><p>{projects.map(item => item.name).join('、')}</p><p>观察{me.device.permissions.approve ? ' · 审批' : ''}{me.device.permissions.stop ? ' · 停止' : ''} · {time(me.device.expiresAt)} 到期</p><p>显示已授权项目的未归档会话;操作记录可加载更早记录。</p><p>iPhone Safari 中点「共享 → 添加到主屏幕」可安装伴随端。主屏幕应用如要求连接,请在电脑生成新的配对码。</p><div><button disabled={!!busy || !fresh} onClick={() => void act('rotate', async () => { await mobileApi('/rotate', {}); await refresh(); setReceipt('手机会话已轮换。'); })}>轮换手机会话</button><button disabled={!!busy} onClick={() => void act('logout', async () => { await mobileApi('/logout', {}); revoke('已断开并撤销这台手机。'); })}>断开并撤销</button></div></details></main>}
{me && selected && <main className="mobile-task-detail"><button className="mobile-back" onClick={() => { chosen.current = ''; setSelected(''); setTask(null); setDocument(null); }}><ArrowLeft size={18} />项目任务</button>{!selectedTask ? <div className="mobile-empty" role="status">正在读取原任务…</div> : <>
<div className="mobile-task-title"><span className="mobile-eyebrow">{projectName(selectedTask.projectId)}</span><h1>{selectedTask.title}</h1><div><span className={'mobile-state state-' + selectedTask.status}>{stateLabel(selectedTask.status)}</span><span>修订 {selectedTask.revision}</span></div><details className="mobile-goal"><summary>完整任务目标</summary><p>{selectedTask.task?.goal ?? '此会话尚未创建执行任务。'}</p></details><details><summary>原任务与运行</summary><code>Task {selectedTask.taskId ?? '未开始'}<br />Run {selectedTask.runId ?? '未开始'}</code></details></div>
{receipt && <p className="mobile-receipt" role="status">{receipt}</p>}
+3
View File
@@ -1,4 +1,7 @@
:root { color: var(--orven-ink); background: var(--orven-navigation); --ink: var(--orven-ink); --muted: var(--orven-muted); --line: var(--orven-border-soft); --green: #277859; }
.mobile-operation-history { margin: 12px 16px; padding: 12px 0; border-bottom: 1px solid var(--orven-border-soft); font-size: 13px; overflow-wrap: anywhere; }
.mobile-operation-history summary { cursor: pointer; font-weight: 600; padding: 8px 0; }
.mobile-operation-history p { color: var(--orven-muted); line-height: 1.6; }
button, input, select { border-color: var(--orven-border-strong); border-radius: 8px; }
button:focus-visible, input:focus-visible, select:focus-visible, summary:focus-visible { outline-color: var(--orven-accent); }
.mobile-app { background: #fff; }
+2 -1
View File
@@ -174,6 +174,7 @@ export interface DeliveryStatus {
gaps: { kind: string; id: string; label: string; nextStep: string }[] };
diagnostics: { runId: string; status: string; stopReason: string | null; question: string; failure?: RuntimeFailure | null; context: DiagnosticContext }[];
}
export interface RecordPage<T> { items: T[]; total: number; hasMore: boolean; nextCursor: string | null }
export interface TaskCheckpoint {
id: string; sessionId: string; projectId: string; taskId: string; runId: string; createdAt: string;
status: string; artifactId: string; sha256: string; sourceFingerprint: string; requirementsSha256: string;
@@ -295,7 +296,7 @@ export interface RequirementDraft {
id: string; taskId: string; runId: string; expectedRevision: number; sourceSetSha256: string; contractArtifactId: string;
proposal: { items: (Pick<RequirementItem, 'key' | 'title' | 'criterion' | 'source' | 'role'>)[]; covered_source_ids: string[]; truncated: boolean; note: string };
}
export interface ExecutionSnapshot { schemaVersion: number; task: Task | null; run: Run | null; runs: RunBrief[]; progress: { totalTools: number; completedTools: number; requiresVerification: { id: string; tool: string; state: string; callId: string }[] }; artifacts: Artifact[]; checks: CheckJob[]; mcpJobs?: McpJob[]; plans?: CheckPlan[]; deliveries?: DeliveryJob[]; deliveryPlans?: DeliveryPlan[]; changeSets?: ChangeSet[]; contextPlans?: ContextPlan[]; workspaces?: WorkspaceRecord[]; researchTargets?: ResearchTarget[]; researchJobs?: ResearchJob[]; engineJobs?: EngineJob[]; engineRuns?: EngineRunView[]; browserPlans?: BrowserPlan[]; browserJobs?: BrowserJob[]; taskPlans?: TaskPlanRecord[]; taskProofs?: { id: string; planId: string; stepKey: string; status: string }[]; collaborations?: CollaborationGroup[]; workers?: WorkerRecord[]; workspaceIdentity?: WorkspaceIdentity; accountedTaskTokens: number }
export interface ExecutionSnapshot { schemaVersion: number; task: Task | null; run: Run | null; runs: RunBrief[]; progress: { totalTools: number; completedTools: number; requiresVerification: { id: string; tool: string; state: string; callId: string }[] }; artifacts: Artifact[]; checks: CheckJob[]; mcpJobs?: McpJob[]; mcpJobCount?: number; mcpJobsTruncated?: boolean; plans?: CheckPlan[]; deliveries?: DeliveryJob[]; deliveryPlans?: DeliveryPlan[]; changeSets?: ChangeSet[]; contextPlans?: ContextPlan[]; workspaces?: WorkspaceRecord[]; researchTargets?: ResearchTarget[]; researchJobs?: ResearchJob[]; engineJobs?: EngineJob[]; engineRuns?: EngineRunView[]; browserPlans?: BrowserPlan[]; browserJobs?: BrowserJob[]; taskPlans?: TaskPlanRecord[]; taskProofs?: { id: string; planId: string; stepKey: string; status: string }[]; collaborations?: CollaborationGroup[]; workers?: WorkerRecord[]; workspaceIdentity?: WorkspaceIdentity; accountedTaskTokens: number }
export interface WorkerBudget { maxTokens: number; maxSteps: number; maxToolCalls: number }
export interface WorkerAssignment { schemaVersion: number; role: string; requirements: string[]; selection: { type: string; id: string } | null; selectionSource: string; model: ModelSnapshot }
export interface WorkerQuality { role: string; checks: { status: string; checkJobId: string | null }; requirements: { criterion: string; status: string }[] }
+49
View File
@@ -0,0 +1,49 @@
import { useCallback, useEffect, useRef, useState } from 'react';
import { api } from './api';
import type { RecordPage } from './types';
const empty = <T,>(): RecordPage<T> => ({ items: [], total: 0, hasMore: false, nextCursor: null });
type FetchPage = <T>(url: string) => Promise<T>;
export function useRecordPages<T extends { id: string }>(url: string | null, onError: (error: unknown) => void, fetchPage: FetchPage = api, scope = url) {
const [page, setPage] = useState<RecordPage<T>>(empty), [loading, setLoading] = useState(false);
const current = useRef(empty<T>()), epoch = useRef(0), pending = useRef(false), error = useRef(onError);
error.current = onError;
const read = useCallback(async (more: boolean) => {
if (!url || pending.current || more && !current.current.hasMore) return;
const generation = epoch.current, previous = current.current; pending.current = true; setLoading(true);
try {
const query = (cursor: string | null) => url + '?limit=50' + (cursor ? '&cursor=' + encodeURIComponent(cursor) : '');
let next = await fetchPage<RecordPage<T>>(query(more ? previous.nextCursor : null));
if (generation !== epoch.current) return;
let items = [...next.items];
// New records may arrive while older pages are expanded. Walk the gap to
// a retained anchor before merging, so polling cannot skip an interval.
if (!more && previous.items.length) {
const known = new Set(previous.items.map(item => item.id));
while (next.hasMore && !items.some(item => known.has(item.id))) {
next = await fetchPage<RecordPage<T>>(query(next.nextCursor));
if (generation !== epoch.current) return;
items.push(...next.items);
}
if (items.some(item => known.has(item.id))) {
const seen = new Set(items.map(item => item.id));
items.push(...previous.items.filter(item => !seen.has(item.id)));
next = { ...next, hasMore: previous.hasMore, nextCursor: previous.nextCursor };
}
} else if (more) {
const seen = new Set(previous.items.map(item => item.id));
items = [...previous.items, ...items.filter(item => !seen.has(item.id))];
}
const value = { ...next, items };
current.current = value; setPage(value);
} catch (cause) { if (generation === epoch.current) error.current(cause); }
finally { if (generation === epoch.current) { pending.current = false; setLoading(false); } }
}, [url, fetchPage, scope]);
const refresh = useCallback(() => read(false), [read]), loadMore = useCallback(() => read(true), [read]);
useEffect(() => {
epoch.current++; pending.current = false; current.current = empty<T>(); setPage(empty<T>()); setLoading(false);
void refresh();
return () => { epoch.current++; pending.current = false; };
}, [refresh]);
return { ...page, loading, refresh, loadMore };
}
+16 -7
View File
@@ -3,6 +3,8 @@ import { randomBytes, randomUUID } from 'node:crypto';
import { companionError, companionHash, companionName, deviceGrant, COMPANION_SCHEMA } from '../../shared/contracts/companion.mjs';
import { assertLocalTree } from '../desktop/file-state.mjs';
import { isId } from '../../shared/contracts/execution.mjs';
import { ceiling } from '../../shared/contracts/execution-policy.mjs';
import { recordPage } from '../../shared/contracts/record-page.mjs';
const key = 'mobileCompanion';
const instant = value => new Date(value).toISOString();
@@ -26,8 +28,7 @@ export class DeviceRegistry {
read() {
const state = this.store.storage.meta(key);
if (state && (state.schema !== COMPANION_SCHEMA || state.binding !== this.binding || !isId(state.gatewayId) || !Number.isSafeInteger(state.revision) || state.revision < 0
|| !dictionary(state.devices) || Object.keys(state.devices).length > 128 || !Array.isArray(state.audit) || state.audit.length > 500
|| !dictionary(state.operations) || Object.keys(state.operations).length > 2000
|| !dictionary(state.devices) || !Array.isArray(state.audit) || !dictionary(state.operations)
|| Object.entries(state.devices).some(([id, device]) => !dictionary(device) || id !== device.id || !isId(id)
|| typeof device.name !== 'string' || !device.name.trim() || device.name.length > 60 || /[\x00-\x1f\x7f]/.test(device.name)
|| !Number.isSafeInteger(device.revision) || device.revision < 1 || !date(device.createdAt) || !date(device.expiresAt)
@@ -50,13 +51,21 @@ export class DeviceRegistry {
}
audit(state, action, deviceId, status, extra = {}) {
state.audit.push({ id: randomUUID(), at: instant(this.clock()), deviceId, action, status, ...extra });
state.audit = state.audit.slice(-500);
}
initialize() { return this.mutate(state => ({ gatewayId: state.gatewayId })); }
view() {
const state = this.read();
const state = this.read(), page = this.auditPage({}, state);
return { gatewayId: state.gatewayId, revision: state.revision, devices: Object.values(state.devices).map(({ credentialHash, ...device }) => ({ ...device,
status: device.revokedAt ? 'revoked' : Date.parse(device.expiresAt) <= this.clock() ? 'expired' : credentialHash ? 'active' : 'reconnect_required' })), audit: state.audit.slice(-50).reverse() };
status: device.revokedAt ? 'revoked' : Date.parse(device.expiresAt) <= this.clock() ? 'expired' : credentialHash ? 'active' : 'reconnect_required' })), audit: page.items, auditPage: page };
}
auditPage(options = {}, state = this.read()) {
return recordPage([...state.audit].reverse(), options, 'companion-audit:' + state.gatewayId);
}
operationsPage(device, options = {}, state = this.read()) {
const records = Object.values(state.operations).filter(value => value.deviceId === device.id && device.projectIds.includes(value.projectId)).reverse()
.map(value => ({ id: value.requestId, requestId: value.requestId, action: value.action, status: value.status === 'pending' ? 'unknown' : value.status,
taskId: value.taskId, runId: value.runId, createdAt: value.createdAt }));
return recordPage(records, options, 'companion-operations:' + state.gatewayId + ':' + device.id + ':' + device.revision);
}
pair(grant, generation) {
this.assertHost(); deviceGrant(this.store, grant);
@@ -72,7 +81,7 @@ export class DeviceRegistry {
deviceGrant(this.store, pairing.grant);
const tokenValue = secret();
const device = this.mutate(state => {
if (Object.keys(state.devices).length >= 128) throw companionError('设备登记达到128条上限,请保留原审计并检查设备登记。', 409);
if (Object.keys(state.devices).length >= ceiling(this.store, 128)) throw companionError('设备登记达到128条上限,请保留原审计并检查设备登记。', 409);
const at = this.clock(), device = { id: randomUUID(), name, projectIds: pairing.grant.projectIds, permissions: pairing.grant.permissions,
revision: 1, createdAt: instant(at), expiresAt: instant(at + pairing.grant.expiresInHours * 3600000), revokedAt: null,
credentialHash: companionHash(tokenValue) };
@@ -121,7 +130,7 @@ export class DeviceRegistry {
if (existing.hash !== hash) throw companionError('同一请求ID不能更换操作或输入。', 409);
return { ...existing, duplicate: true };
}
if (Object.keys(state.operations).length >= 2000) throw companionError('手机操作账本达到上限,请在电脑处理。', 409);
if (Object.keys(state.operations).length >= ceiling(this.store, 2000)) throw companionError('手机操作账本达到上限,请在电脑处理。', 409);
const operation = { hash, deviceId: device.id, requestId: input.requestId, action, sessionId: session.id,
taskId: session.taskId, runId: session.runId, projectId: session.projectId, status: 'pending', createdAt: instant(this.clock()) };
state.operations[id] = operation;
+9 -2
View File
@@ -17,7 +17,7 @@ export class CredentialVault {
}
reload() {
const state = this.store.storage.meta(metadata, empty());
this.blocked = !state || state.schema !== 1 || !Number.isSafeInteger(state.revision) || !state.entries || typeof state.entries !== 'object' || Array.isArray(state.entries) || Object.keys(state.entries).length > 101;
this.blocked = !state || state.schema !== 1 || !Number.isSafeInteger(state.revision) || state.revision < 0 || !state.entries || typeof state.entries !== 'object' || Array.isArray(state.entries);
this.state = this.blocked ? empty() : state;
}
binding(connection) {
@@ -30,8 +30,15 @@ export class CredentialVault {
if (connection.credentialSource) return { status: 'reference', storage: 'source-reference', sourceId: connection.credentialSource.connectionId,
message: '共用上游源连接的凭据与加载状态,请在源连接管理;没有复制或额外保存 Key。' };
if (this.blocked) return { status: 'unavailable', storage: 'windows-user-dpapi', message: '本机保存登记格式损坏或来自新版本,未覆盖原记录。' };
if (!Object.hasOwn(this.state.entries, connection.id)) return { status: 'not_saved', storage: 'memory', message: '当前凭据只在宿主内存中。' };
const value = this.state.entries[connection.id];
if (!value) return { status: 'not_saved', storage: 'memory', message: '当前凭据只在宿主内存中。' };
if (!value || typeof value !== 'object' || Array.isArray(value) || value.schema !== 1 || value.connectionId !== connection.id
|| !Number.isSafeInteger(value.connectionRevision) || value.connectionRevision < 1 || !Number.isSafeInteger(value.credentialRevision) || value.credentialRevision < 1
|| typeof value.enabled !== 'boolean' || typeof value.savedAt !== 'string' || !Number.isFinite(Date.parse(value.savedAt))
|| value.userSid !== null && typeof value.userSid !== 'string' || !/^[a-f0-9]{64}$/.test(value.dataIdentity) || !/^[a-f0-9]{64}$/.test(value.bindingSha256)
|| typeof value.ciphertext !== 'string' || !value.ciphertext.length || value.ciphertext.length > 200000 || !/^[A-Za-z0-9+/]+={0,2}$/.test(value.ciphertext)) {
return { status: 'invalid_record', storage: 'windows-user-dpapi', message: '此连接的原保存登记无法核对,原记录已保留;其他有效连接继续加载。' };
}
const issue = value.userSid !== this.userSid ? 'user_mismatch' : value.dataIdentity !== this.dataIdentity ? 'directory_mismatch'
: value.connectionRevision !== connection.revision || value.bindingSha256 !== this.binding(connection) ? 'source_changed'
: this.issues.get(connection.id);
+15
View File
@@ -41,4 +41,19 @@ export class ArtifactStore {
if (bytes.length !== artifact.bytes || createHash('sha256').update(bytes).digest('hex') !== artifact.sha256) throw new Error('执行工件校验失败,实际结果需要核对。');
return bytes;
}
verify(artifact) {
if (!/^[a-f0-9]{2}\/[a-f0-9]{64}\.blob$/.test(artifact.relative)) throw new Error('执行工件路径无效。');
const file = path.join(this.root, artifact.relative);
if (fs.lstatSync(path.dirname(file)).isSymbolicLink() || fs.lstatSync(file).isSymbolicLink()) throw new Error('执行工件不能是链接。');
const handle = fs.openSync(file, 'r');
try {
const stat = fs.fstatSync(handle);
if (!stat.isFile() || stat.size !== artifact.bytes) throw new Error('执行工件校验失败,实际结果需要核对。');
const hash = createHash('sha256'), buffer = Buffer.allocUnsafe(Math.min(1024 * 1024, Math.max(1, stat.size)));
let length = 0, bytes;
while ((bytes = fs.readSync(handle, buffer, 0, buffer.length, null)) > 0) { length += bytes; hash.update(buffer.subarray(0, bytes)); }
if (length !== artifact.bytes || hash.digest('hex') !== artifact.sha256) throw new Error('执行工件校验失败,实际结果需要核对。');
return { bytes: length, sha256: artifact.sha256 };
} finally { fs.closeSync(handle); }
}
}
+46 -11
View File
@@ -8,6 +8,8 @@ import { pendingDeliveryReview } from '../../shared/contracts/delivery-review.mj
import { assertChangeSetsResolved } from '../../shared/contracts/change-sets.mjs';
import { assertWorkspacesResolved } from '../../shared/contracts/workspaces.mjs';
import { assertMcpResolved } from '../tools/mcp-contract.mjs';
import { ceiling } from '../../shared/contracts/execution-policy.mjs';
import { recordPage } from '../../shared/contracts/record-page.mjs';
const at = () => new Date().toISOString();
const failure = (message, status = 409) => Object.assign(new Error(message), { status });
@@ -19,25 +21,25 @@ const counts = state => ({ tools: state.tools.length, completed: state.tools.fil
export class TaskCheckpointManager {
constructor(store, { taskPlans, redact = String }) { this.store = store; this.taskPlans = taskPlans; this.redact = redact; }
list(session) {
return [...this.store.core.task_checkpoint.values()].filter(value => value.sessionId === session.id && value.taskId === session.taskId)
.slice(-TASK_CHECKPOINT_LIMITS.checkpoints).reverse().map(value => structuredClone(value));
list(session, page = null) {
const records = [...this.store.core.task_checkpoint.values()].filter(value => value.sessionId === session.id && value.taskId === session.taskId).reverse();
return structuredClone(page ? recordPage(records, page, 'checkpoints:' + session.id + ':' + session.taskId) : records);
}
artifact(session, id, taskId) {
const artifact = this.store.owned('artifact', id, session.id);
if (artifact.taskId !== taskId || this.store.owned('run', artifact.runId, session.id).taskId !== taskId) throw failure('恢复依据的原工件不属于当前任务。');
this.store.artifactStore.readBytes(artifact);
this.store.artifactStore.verify(artifact);
return artifact;
}
ledger(session, task) {
const tools = [...this.store.core.tool.values()].filter(value => value.sessionId === session.id && value.taskId === task.id);
if (tools.length > TASK_CHECKPOINT_LIMITS.tools) throw failure('当前任务超过恢复包2000项工具引用的上限,请缩小任务范围。');
if (tools.length > ceiling(this.store, TASK_CHECKPOINT_LIMITS.tools)) throw failure('当前任务超过恢复包2000项工具引用的上限,请缩小任务范围。');
let resultBytes = 0;
for (const tool of tools) if (tool.resultArtifactId) {
resultBytes += this.store.owned('artifact', tool.resultArtifactId, session.id).bytes;
if (resultBytes > TASK_CHECKPOINT_LIMITS.resultBytes) throw failure('恢复检查点的原结果核验超过64MB上限,请缩小任务范围。');
if (resultBytes > ceiling(this.store, TASK_CHECKPOINT_LIMITS.resultBytes)) throw failure('恢复检查点的原结果核验超过64MB上限,请缩小任务范围。');
}
const calls = new Map(session.providerMessages.flatMap(value => value.tool_calls ?? []).map(value => [value.id, value]));
return tools.map(tool => {
@@ -71,10 +73,41 @@ export class TaskCheckpointManager {
})));
}
sealTools(session, run, tools) {
const segments = [];
// Segment size affects the index layout, not the number of retained tools.
for (let start = 0; start < tools.length; start += 256) {
const entries = tools.slice(start, start + 256);
const artifact = this.store.artifactStore.write(session, run, { schemaVersion: 1, kind: 'task-checkpoint-tools',
sessionId: session.id, projectId: session.projectId, taskId: run.taskId, runId: run.id, start, tools: entries }, { kind: 'task-checkpoint-tools' });
this.store.core.artifact.set(artifact.id, artifact);
segments.push({ start, count: entries.length, artifact: identity(artifact) });
}
return { count: tools.length, segments };
}
expandTools(session, record, state) {
const index = state.toolIndex;
if (!index || !Number.isSafeInteger(index.count) || index.count < 0 || !Array.isArray(index.segments) || 'tools' in state) throw failure('恢复检查点工具索引无效。');
const tools = [];
for (const segment of index.segments) {
const artifact = this.artifact(session, segment.artifact.id, record.taskId);
if (artifact.runId !== record.runId || artifact.kind !== 'task-checkpoint-tools' || planHash(identity(artifact)) !== planHash(segment.artifact)) throw failure('恢复检查点工具分段身份已变化。');
const original = JSON.parse(this.store.artifactStore.read(artifact));
if (original.schemaVersion !== 1 || original.kind !== 'task-checkpoint-tools' || original.sessionId !== session.id || original.projectId !== session.projectId
|| original.taskId !== record.taskId || original.runId !== record.runId || segment.start !== tools.length || original.start !== tools.length
|| !Array.isArray(original.tools) || !original.tools.length || original.tools.length !== segment.count) throw failure('恢复检查点工具分段顺序或内容不一致。');
for (const tool of original.tools) tools.push(tool);
}
if (tools.length !== index.count) throw failure('恢复检查点工具分段不完整。');
const { toolIndex, ...rest } = state;
return { tools, ...rest };
}
create(session) { return this.taskPlans.mutate(session, 'user', async () => {
const { task, run } = this.taskPlans.task(session), taskId = task.id, runId = run.id;
if (['running', 'awaiting_approval', 'stopping'].includes(session.status)) throw failure('先停止当前任务,再封存稳定的恢复检查点。');
if (this.list(session).length >= TASK_CHECKPOINT_LIMITS.checkpoints) throw failure('当前任务已达到30个恢复检查点上限。');
if (this.list(session).length >= ceiling(this.store, TASK_CHECKPOINT_LIMITS.checkpoints)) throw failure('当前任务已达到30个恢复检查点上限。');
const requirements = taskRequirements(task), requirementsSha256 = planHash(requirements);
await verifyWorkspaceProject(this.store, this.store.project(session.projectId));
const inspection = await inspectProject(this.store.project(session.projectId));
@@ -84,15 +117,16 @@ export class TaskCheckpointManager {
if (lastContext) verifyPlanEvidence(this.store, session, lastContext);
if (session.taskId !== taskId || session.runId !== runId || planHash(taskRequirements(task)) !== requirementsSha256) throw failure('保存期间任务或要求已变化,请重新核对。');
const safeRequirements = JSON.parse(this.redact(JSON.stringify(requirements)));
const bundle = { schemaVersion: 1, kind: 'task-recovery-checkpoint', sessionId: session.id,
const { tools, ...rest } = state;
const bundle = { schemaVersion: 2, kind: 'task-recovery-checkpoint', sessionId: session.id,
projectId: session.projectId, taskId, runId, savedAt: at(), requirements: safeRequirements, requirementsSha256,
workspace: projectWorkspaceIdentity(this.store.project(session.projectId)), sourceFingerprint: inspection.sourceFingerprint,
sourceScope: inspection.scope, git: { head: inspection.git.head, branch: inspection.git.branch }, state,
sourceScope: inspection.scope, git: { head: inspection.git.head, branch: inspection.git.branch }, state: { ...rest, toolIndex: this.sealTools(session, run, tools) },
lastRequest: lastContext ? { planId: lastContext.id, artifactId: lastContext.requestArtifactId, sha256: lastContext.requestSha256 } : null,
note: '恢复包是原任务数据与结果引用,不授予权限,不重放工具,不将未知调用改为成功。' };
const artifact = this.store.artifactStore.write(session, run, bundle, { kind: 'task-recovery-checkpoint' });
this.store.core.artifact.set(artifact.id, artifact);
const record = { schemaVersion: 1, id: randomUUID(), sessionId: session.id, projectId: session.projectId, taskId, runId,
const record = { schemaVersion: 2, id: randomUUID(), sessionId: session.id, projectId: session.projectId, taskId, runId,
status: 'stored', createdAt: bundle.savedAt, artifactId: artifact.id, sha256: artifact.sha256,
sourceFingerprint: inspection.sourceFingerprint, requirementsSha256, stateSha256: planHash(state),
counts: counts(state) };
@@ -102,12 +136,13 @@ export class TaskCheckpointManager {
original(session, id) {
const record = this.store.owned('task_checkpoint', id, session.id), artifact = this.artifact(session, record.artifactId, record.taskId);
const bundle = JSON.parse(this.store.artifactStore.read(artifact));
if (![1, 2].includes(bundle.schemaVersion) || bundle.schemaVersion !== record.schemaVersion) throw failure('恢复检查点版本无法核对。');
if (bundle.schemaVersion === 2) bundle.state = this.expandTools(session, record, bundle.state);
if (artifact.kind !== 'task-recovery-checkpoint' || artifact.sha256 !== record.sha256 || artifact.runId !== record.runId
|| bundle.kind !== 'task-recovery-checkpoint' || bundle.sessionId !== session.id || bundle.projectId !== session.projectId
|| bundle.taskId !== record.taskId || bundle.runId !== record.runId || bundle.requirementsSha256 !== record.requirementsSha256
|| bundle.sourceFingerprint !== record.sourceFingerprint || planHash(bundle.state) !== record.stateSha256
|| planHash(counts(bundle.state)) !== planHash(record.counts)) throw failure('恢复检查点与原封存身份或内容不一致。');
if (bundle.state.tools.length > TASK_CHECKPOINT_LIMITS.tools || bundle.state.tools.reduce((sum, tool) => sum + (tool.resultArtifact?.bytes ?? 0), 0) > TASK_CHECKPOINT_LIMITS.resultBytes) throw failure('恢复包的原工具结果范围超过核验上限。');
for (const tool of bundle.state.tools) if (tool.resultArtifact) {
const source = this.artifact(session, tool.resultArtifact.id, record.taskId);
if (planHash(identity(source)) !== planHash(tool.resultArtifact)) throw failure('恢复包引用的原工具工件身份已变化。');
+8 -3
View File
@@ -4,6 +4,7 @@ import path from 'node:path';
import os from 'node:os';
import { createHash, randomUUID } from 'node:crypto';
import { McpStdio } from './mcp-stdio.mjs';
import { recordPage } from '../../shared/contracts/record-page.mjs';
import { MCP_PROTOCOL, MCP_LIMITS, MCP_ACTIVE, mcpError, mcpHash, checkMcpSchema, validateMcpArguments, mcpCallInput } from './mcp-contract.mjs';
const at = () => new Date().toISOString();
@@ -55,7 +56,8 @@ export class McpRegistry {
return { ...value, status, reason, tools };
});
return JSON.parse(this.redact(JSON.stringify({ projectId, revision: state.revision, registrations, protocolVersion: MCP_PROTOCOL,
limits: MCP_LIMITS, boundary: '所属独立进程,不是OS沙箱;只锁定程序/入口与实际握手契约,依赖文件未全量封存。' })));
limits: Object.fromEntries(Object.entries(MCP_LIMITS).map(([key, value]) => [key, ceiling(this.store, value)])),
executionMode: this.store.config.executionMode, boundary: '所属独立进程,不是OS沙箱;只锁定程序/入口与实际握手契约,依赖文件未全量封存。' })));
}
register(projectId, input) {
this.idle(projectId); fields(input, ['name', 'executable', 'entry', 'timeoutMs']);
@@ -112,13 +114,16 @@ export class McpRegistry {
&& entry.configurationRevision === value.configurationRevision && entry.contractSha256 === input.contract_sha256 && entry.tool === input.tool && mcpHash(entry.inputSchema) === mcpHash(tool.inputSchema))) throw mcpError('工具不在本次发送的MCP目录范围内。');
return value;
}
jobs(session) { return [...this.store.core.mcp_job.values()].filter(value => value.sessionId === session.id).slice(-30).reverse(); }
jobs(session, page = null) {
const records = [...this.store.core.mcp_job.values()].filter(value => value.sessionId === session.id).reverse();
return page ? recordPage(records, page, 'mcp:' + session.id) : records;
}
start(session, input, { source = 'user', signal = null, call = null, invocationId = null } = {}) {
fields(input, ['id', 'configurationRevision', 'confirm']);
if (session.archived || !Number.isSafeInteger(input.configurationRevision) || input.confirm !== true) throw mcpError('启动MCP程序需要确认当前登记身份。', 400);
const value = this.find(session.projectId, input.id, input.configurationRevision); this.verifyLaunch(value);
if (this.taskPlans.projectActive(session.projectId) || this.projectBusy(session.projectId, source === 'agent' ? session.id : null)) throw mcpError('项目正在执行其他操作,请等待结束后核验MCP。');
if (this.jobs(session).filter(job => job.taskId === session.taskId).length >= 30) throw mcpError('当前任务已达到30次MCP操作上限。');
if (this.jobs(session).filter(job => job.taskId === session.taskId).length >= ceiling(this.store, 30)) throw mcpError('当前任务已达到30次MCP操作上限。');
if ([...this.store.core.mcp_job.values()].some(job => job.projectId === session.projectId && job.requiresVerification)) throw mcpError('项目有外部MCP结果待核对,请先审查所属原记录。');
if (!this.store.core.task.get(session.taskId)) {
if (source !== 'user' || this.projectBusy(session.projectId)) throw mcpError('当前项目有任务正在执行。');
+4 -2
View File
@@ -25,6 +25,7 @@ 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';
import { recordPageQuery } from '../shared/contracts/record-page.mjs';
export function createSessionPublisher(clients) {
return session => {
@@ -103,6 +104,7 @@ return async (request, response) => {
if (route.startsWith('/api/companion')) {
const gateway = companionGateway({ appDirectory, server, store, provider, runtime });
if (method === 'GET' && route === '/api/companion') return json(response, gateway.status());
if (method === 'GET' && route === '/api/companion/audit') return json(response, gateway.registry.auditPage(recordPageQuery(url) ?? {}));
if (method === 'POST' && route === '/api/companion/start') return json(response, await gateway.start(await body(request)));
if (method === 'POST' && route === '/api/companion/close') { const value = await body(request); if (Object.keys(value).length) throw Object.assign(new Error('关闭手机连接不接受额外字段。'), { status: 400 }); return json(response, await gateway.close()); }
if (method === 'POST' && route === '/api/companion/pair') return json(response, await gateway.pairing(await body(request)));
@@ -488,7 +490,7 @@ return async (request, response) => {
'X-Content-Type-Options': 'nosniff', ...(engineRun[2] === 'download' ? { 'Content-Disposition': 'attachment; filename="agent-workbench-engine-run-' + job.id + '.json"' } : {}) });
response.end(text); return;
}
if (method === 'GET' && action === 'mcp/jobs') return json(response, runtime.mcpRegistry().jobs(session));
if (method === 'GET' && action === 'mcp/jobs') return json(response, runtime.mcpRegistry().jobs(session, recordPageQuery(url)));
if (method === 'POST' && action === 'mcp/probe') {
const started = runtime.mcpRegistry().start(session, await body(request));
return json(response, { job: started.job, session: store.publicSession(session) }, 202);
@@ -535,7 +537,7 @@ return async (request, response) => {
if (method === 'GET' && action === 'research') {
const manager = runtime.researchManager(); return json(response, { availability: manager.availability(), targets: manager.targets(session), jobs: manager.jobs(session) });
}
if (method === 'GET' && action === 'task-checkpoints') return json(response, runtime.checkpointManager().list(session));
if (method === 'GET' && action === 'task-checkpoints') return json(response, runtime.checkpointManager().list(session, recordPageQuery(url)));
if (method === 'POST' && action === 'task-checkpoints') {
const input = await body(request);
if (Object.keys(input).some(key => !['taskId', 'runId'].includes(key)) || input.taskId !== session.taskId || input.runId !== session.runId) throw Object.assign(new Error('检查点的原任务或运行已变化,请刷新当前任务。'), { status: 409 });
+10 -4
View File
@@ -12,6 +12,7 @@ import { isId } from '../shared/contracts/execution.mjs';
import { mobileSession, sessionBrief, reportKinds } from '../core/companion/projection.mjs';
import { InputAttachments } from '../core/context/input-attachments.mjs';
import { hostAuthority } from '../core/desktop/host-authority.mjs';
import { recordPageQuery } from '../shared/contracts/record-page.mjs';
export function companionGateway(context) {
if (!context.server.workbenchCompanion) {
@@ -190,7 +191,7 @@ export class CompanionGateway {
const mobileUrl = new URL(request.url, this.origin), route = mobileUrl.pathname, method = request.method;
if (mobileUrl.origin !== this.origin || request.headers.origin && request.headers.origin !== this.origin) throw companionError('请求来源不属于当前手机网关。', 403);
if (method === 'POST' && request.headers.origin !== this.origin) throw companionError('手机操作需要来自当前HTTPS页面。', 403);
if (mobileUrl.search && route !== '/mobile-api/events' && !/^\/mobile-api\/sessions\/[a-f0-9-]+\/changes\/[a-f0-9-]+$/.test(route)) throw companionError('手机接口不接受额外查询字段。');
if (mobileUrl.search && !['/mobile-api/events', '/mobile-api/operations'].includes(route) && !/^\/mobile-api\/sessions\/[a-f0-9-]+\/changes\/[a-f0-9-]+$/.test(route)) throw companionError('手机接口不接受额外查询字段。');
if (method === 'POST' && route === '/mobile-api/pair') {
this.limit('pair:' + request.socket.remoteAddress, 8);
const value = await input(request, this.store.config); fields(value, ['token', 'name']);
@@ -204,10 +205,15 @@ export class CompanionGateway {
if (!this.sockets.has(request.socket)) request.socket.once('close', () => this.sockets.delete(request.socket));
this.sockets.set(request.socket, device.id);
if (method === 'GET' && route === '/mobile-api/me') {
const state = this.registry.read();
const state = this.registry.read(), page = this.registry.operationsPage(device, {}, state);
return reply(response, { device: { id: device.id, name: device.name, projectIds: device.projectIds, permissions: device.permissions, expiresAt: device.expiresAt, revision: device.revision },
gatewayId: state.gatewayId, operations: Object.values(state.operations).filter(value => value.deviceId === device.id && device.projectIds.includes(value.projectId)).slice(-20)
.map(value => ({ requestId: value.requestId, action: value.action, status: value.status === 'pending' ? 'unknown' : value.status, taskId: value.taskId, runId: value.runId, createdAt: value.createdAt })) });
gatewayId: state.gatewayId, operations: page.items, operationsPage: page,
unresolvedOperations: Object.values(state.operations).filter(value => value.deviceId === device.id && device.projectIds.includes(value.projectId) && ['pending', 'unknown'].includes(value.status))
.map(value => ({ requestId: value.requestId, action: value.action, status: 'unknown', taskId: value.taskId, runId: value.runId, createdAt: value.createdAt })) });
}
if (method === 'GET' && route === '/mobile-api/operations') {
try { return reply(response, this.registry.operationsPage(device, recordPageQuery(mobileUrl) ?? {})); }
catch (error) { throw companionError(error.message, error.status ?? 400); }
}
if (method === 'POST' && route === '/mobile-api/rotate') {
fields(await input(request, this.store.config), []); const token = this.registry.rotate(device); setCookie(response, token, device.expiresAt); return reply(response, { rotated: true });
+3 -1
View File
@@ -684,6 +684,8 @@ export class Store extends EventEmitter {
executionSnapshot(session) {
const task = this.core.task.get(session.taskId), run = this.core.run.get(session.runId);
const tools = [...this.core.tool.values()].filter(value => value.sessionId === session.id && value.taskId === task?.id);
const mcpAll = [...this.core.mcp_job.values()].filter(value => value.sessionId === session.id);
const mcpPreview = mcpAll.filter(value => value.taskId === task?.id || value.requiresVerification).slice(-30);
const artifacts = [...this.core.artifact.values()].filter(value => value.sessionId === session.id && value.taskId === task?.id).slice(-30);
const jobs = [...this.core.check_job.values()].filter(value => value.sessionId === session.id && value.taskId === task?.id).slice(-10);
const projectWorkspaces = [...this.core.workspace.values()].filter(value => value.projectId === session.projectId);
@@ -715,7 +717,7 @@ export class Store extends EventEmitter {
environmentPlans: [...this.core.environment_plan.values()].filter(value=>value.sessionId===session.id && value.taskId===task?.id).slice(-5),
environmentJobs: [...this.core.environment_job.values()].filter(value=>value.sessionId===session.id && (value.taskId===task?.id || value.requiresVerification)).filter((value,index,all)=>index>=all.length-12 || value.requiresVerification || ['queued','running','stopping'].includes(value.status)),
} : {}),
mcpJobs: [...this.core.mcp_job.values()].filter(value => value.sessionId === session.id && (value.taskId === task?.id || value.requiresVerification)).slice(-30),
mcpJobs: mcpPreview, mcpJobCount: mcpAll.length, mcpJobsTruncated: mcpAll.length > mcpPreview.length,
taskPlans: [...this.core.task_plan.values()].filter(value => value.sessionId === session.id && value.taskId === task?.id).slice(-6),
taskProofs: [...this.core.task_proof.values()].filter(value => value.sessionId === session.id && value.taskId === task?.id).slice(-24),
researchTargets: [...this.core.research_target.values()].filter(value => value.sessionId === session.id && value.taskId === task?.id).slice(-32),
+27
View File
@@ -0,0 +1,27 @@
// A page is a view over retained records, never a storage or execution ceiling.
const invalid = (message, status = 400) => Object.assign(new Error(message), { status });
export function recordPageQuery(url) {
const params = url.searchParams;
if ([...params.keys()].some(key => !['cursor', 'limit'].includes(key))
|| ['cursor', 'limit'].some(key => params.getAll(key).length > 1)) throw invalid('记录分页参数无效。');
if (!params.size) return null;
return { cursor: params.get('cursor'), limit: params.get('limit') ?? 50 };
}
export function recordPage(records, { cursor = null, limit = 50 } = {}, scope) {
if (!/^\d+$/.test(String(limit)) || !Number.isSafeInteger(Number(limit)) || Number(limit) < 1) throw invalid('记录每页数量需要正整数。');
let start = 0;
if (cursor !== null) {
let value;
try {
if (typeof cursor !== 'string' || !/^[A-Za-z0-9_-]+$/.test(cursor)) throw new Error();
value = JSON.parse(Buffer.from(cursor, 'base64url').toString('utf8'));
} catch { throw invalid('记录游标无效,请刷新记录。'); }
if (value?.scope !== scope || typeof value.id !== 'string') throw invalid('记录游标不属于当前范围。');
const index = records.findIndex(record => record.id === value.id);
if (index < 0) throw invalid('原记录游标已变化,请刷新记录。', 409);
start = index + 1;
}
const items = records.slice(start, start + Number(limit)), hasMore = start + items.length < records.length;
const nextCursor = hasMore ? Buffer.from(JSON.stringify({ scope, id: items.at(-1).id })).toString('base64url') : null;
return { items, total: records.length, hasMore, nextCursor };
}
+24 -1
View File
@@ -111,7 +111,7 @@ test('devices have project and action boundaries; rotation, expiration, revocati
f.host.instanceId = randomUUID(); assert.throws(() => f.registry.authenticate(fresh.token), /宿主/);
});
test('persistent registry stores hashes and a bounded audit, never raw credentials', t => {
test('persistent registry stores hashes and retained audit, never raw credentials', t => {
const f = setup(t), ticket = f.registry.pair(f.grant, 'g'), accepted = f.registry.consume(ticket.token, 'iPhone', 'g');
const text = JSON.stringify(f.store.storage.meta('mobileCompanion'));
assert.ok(!text.includes(ticket.token) && !text.includes(accepted.token));
@@ -121,6 +121,29 @@ test('persistent registry stores hashes and a bounded audit, never raw credentia
assert.ok(!JSON.stringify(registry.view()).includes('credentialHash'));
});
test('mobile operation pages expose all owned receipts and an older pending warning without replay or foreign cursor access', async t => {
const f = await running(t), paired = await f.pair({ ...f.grant, permissions: { observe: true, approve: false, stop: true } });
const run = f.store.beginRun(f.session, 'Owned operation-page fixture', false, f.store.config); f.session.status = 'paused'; f.store.finishRun(f.session, run, 'owned_pause');
f.gateway.registry.mutate(state => {
for (let index = 0; index < 61; index++) {
const requestId = randomUUID(); state.operations[paired.device.id + ':' + requestId] = { deviceId: paired.device.id, requestId, action: 'stop',
sessionId: f.session.id, projectId: f.project.id, taskId: run.taskId, runId: run.id, status: index ? 'completed' : 'pending', hash: companionHash('owned-' + index), createdAt: new Date().toISOString() };
}
});
let effects = 0; f.runtime.stop = async () => { effects++; };
const before = f.gateway.registry.read(), me = await f.request('/mobile-api/me', undefined, { cookie: paired.cookie });
assert.equal(me.status, 200); assert.equal(me.body.operationsPage.total, 61); assert.equal(me.body.operations.length, 50);
assert.equal(me.body.operations.some(value => value.status === 'unknown'), false); assert.equal(me.body.unresolvedOperations.length, 1);
assert.equal(me.body.unresolvedOperations[0].status, 'unknown');
const page = await f.request('/mobile-api/operations?limit=50', undefined, { cookie: paired.cookie }); assert.equal(page.status, 200);
const tail = await f.request('/mobile-api/operations?cursor=' + page.body.nextCursor, undefined, { cookie: paired.cookie });
assert.equal(tail.status, 200); assert.equal(tail.body.items.length, 11); assert.equal(tail.body.items.at(-1).status, 'unknown'); assert.equal(tail.body.hasMore, false);
const other = await f.pair(); assert.equal((await f.request('/mobile-api/operations?cursor=' + page.body.nextCursor, undefined, { cookie: other.cookie })).status, 400);
assert.equal((await f.request('/mobile-api/operations?limit=1&limit=2', undefined, { cookie: paired.cookie })).status, 400);
assert.equal(JSON.stringify(tail.body).includes('hash'), false); assert.equal(effects, 0);
assert.deepEqual(f.gateway.registry.read().operations, before.operations);
});
test('real TLS verifies IP SAN, CA chain, encrypted restart and public fingerprint', async t => {
const f = await running(t), first = f.gateway.tls.publicCertificate();
assert.equal(new X509Certificate(first.bytes).ca, true);
+170
View File
@@ -0,0 +1,170 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import path from 'node:path';
import { randomUUID, randomBytes, createCipheriv, createDecipheriv } from 'node:crypto';
import { fixture, compatibleFixture, completion, call } from './helpers.mjs';
import { Runtime } from '../src/server/runtime.mjs';
import { Store } from '../src/server/store.mjs';
import { Provider } from '../src/server/provider.mjs';
import { DeviceRegistry } from '../src/core/companion/device-registry.mjs';
import { CredentialVault } from '../src/core/models/credential-vault.mjs';
import { planHash } from '../src/shared/contracts/task-plans.mjs';
import { recordPage, recordPageQuery } from '../src/shared/contracts/record-page.mjs';
function paused(t) {
const f = fixture(t, { modernDefaults: true }), runtime = new Runtime(f.store, new Provider());
const run = f.store.beginRun(f.session, 'Owned complete-record recovery fixture', false, f.store.config);
f.session.providerMessages.push({ role: 'user', content: 'Owned complete-record recovery fixture' });
f.session.status = 'paused'; f.store.finishRun(f.session, run, 'owned_pause');
f.onCleanup(() => runtime.stopAll());
return { ...f, run, runtime, manager: runtime.checkpointManager() };
}
function references(f, count, large = false) {
const tools = [], calls = [];
const small = f.store.artifactStore.write(f.session, f.run, { status: 'completed', message: 'owned-small-result' }); f.store.core.artifact.set(small.id, small);
const big = large ? f.store.artifactStore.write(f.session, f.run, Buffer.alloc(64 * 1024 * 1024 + 1, 97)) : small;
f.store.core.artifact.set(big.id, big);
for (let index = 0; index < count; index++) {
const input = call('owned-call-' + index, 'read_file', { path: 'README.md', index }); calls.push(input);
const value = { id: randomUUID(), sessionId: f.session.id, projectId: f.project.id, taskId: f.session.taskId, runId: f.run.id,
callId: input.id, tool: input.function.name, argsSha256: planHash(input.function.arguments), state: 'completed', requiresVerification: false,
resultArtifactId: index === count - 1 ? big.id : small.id };
f.store.core.tool.set(value.id, value); tools.push(value);
}
f.session.providerMessages.push({ role: 'assistant', content: '', tool_calls: calls }, ...calls.map(value => ({ role: 'tool', tool_call_id: value.id, content: 'Owned stored result reference' })));
f.store.save(f.session); return { tools, small, big };
}
function sealedTestCredentials() {
const key = randomBytes(32);
return { protect(bytes, entropy) {
const iv = randomBytes(12), cipher = createCipheriv('aes-256-gcm', key, iv); cipher.setAAD(entropy);
const encrypted = Buffer.concat([cipher.update(bytes), cipher.final()]);
return Buffer.concat([iv, cipher.getAuthTag(), encrypted]);
}, unprotect(bytes, entropy) {
const cipher = createDecipheriv('aes-256-gcm', key, bytes.subarray(0, 12)); cipher.setAAD(entropy); cipher.setAuthTag(bytes.subarray(12, 28));
return Buffer.concat([cipher.update(bytes.subarray(28)), cipher.final()]);
} };
}
test('record cursors retain every row during new inserts and reject foreign, missing and malformed anchors', () => {
const rows = Array.from({ length: 102 }, (_, index) => ({ id: 'row-' + index })).reverse();
const first = recordPage(rows, { limit: 50 }, 'scope'), next = recordPage([{ id: 'new' }, ...rows], { cursor: first.nextCursor, limit: 50 }, 'scope');
const last = recordPage(rows, { cursor: next.nextCursor, limit: 50 }, 'scope');
assert.equal(first.total, 102); assert.equal(new Set([...first.items, ...next.items, ...last.items].map(value => value.id)).size, 102);
assert.equal(last.hasMore, false); assert.equal(last.nextCursor, null);
assert.throws(() => recordPage(rows, { cursor: first.nextCursor }, 'foreign'), /范围/);
assert.throws(() => recordPage([], { cursor: first.nextCursor }, 'scope'), /已变化/);
for (const cursor of ['', '%', 'null', Buffer.from('null').toString('base64url')]) assert.throws(() => recordPage(rows, { cursor }, 'scope'), /游标/);
for (const query of ['limit=0', 'limit=1&limit=2', 'cursor=x&cursor=y', 'unknown=x']) assert.throws(() => recordPage(rows, recordPageQuery(new URL('http://localhost/?' + query)), 'scope'));
});
test('unrestricted MCP executes 31 real stdio calls in one task and preserves every report across pages and restart', async t => {
const f = fixture(t, { modernDefaults: true }), provider = new Provider(); provider.setKey('owned-local-fixture-only');
f.store.saveConfig({ approvalMode: 'full' });
const runtime = new Runtime(f.store, provider); f.onCleanup(() => runtime.stopAll());
const registry = runtime.mcpRegistry(), entry = path.join(f.root, 'owned-mcp.mjs'); fs.copyFileSync('tests/fixtures/registered-mcp-server.mjs', entry);
let registration = registry.register(f.project.id, { name: 'Owned boundary MCP', executable: process.execPath, entry, timeoutMs: 2000 });
assert.equal((await registry.start(f.session, { id: registration.id, configurationRevision: 1, confirm: true }).promise).status, 'completed');
registration = registry.find(f.project.id, registration.id);
registration = registry.configure(f.project.id, { id: registration.id, configurationRevision: registration.configurationRevision, enabled: true, allowedTools: ['echo'] });
const input = { registration_id: registration.id, configuration_revision: registration.configurationRevision, contract_sha256: registration.contract.sha256, tool: 'echo', arguments: { text: 'owned-boundary' } };
const server = await compatibleFixture(t, (_url, _body, requests) => requests.length <= 31 ? completion([call('owned-mcp-' + requests.length, 'call_registered_mcp', input)]) : completion([], 'Owned boundary done'));
f.store.saveConfig({ mode: 'compatible', baseUrl: server.baseUrl, model: 'owned-fixture-model' });
runtime.start(f.session.id, 'Run the owned boundary sequence'); await runtime.active.get(f.session.id).promise;
assert.equal(f.session.status, 'completed', JSON.stringify(f.session.error)); assert.equal(server.requests.length, 32);
const jobs = registry.jobs(f.session); assert.equal(jobs.filter(value => value.taskId === f.session.taskId && value.operation === 'call').length, 31);
const snapshot = f.store.executionSnapshot(f.session); assert.equal(snapshot.mcpJobCount, jobs.length); assert.equal(snapshot.mcpJobsTruncated, true);
for (const job of jobs) { assert.equal(job.status, 'completed'); assert.equal(job.cleanup.rootExited, true); assert.ok(registry.report(f.session, job.id)); }
const first = registry.jobs(f.session, { limit: 11 }), second = registry.jobs(f.session, { cursor: first.nextCursor, limit: 50 });
assert.equal(new Set([...first.items, ...second.items].map(value => value.id)).size, jobs.length);
const hashes = jobs.map(value => value.reportSha256); await runtime.stopAll(); f.store.close();
const store = new Store(f.data); f.onCleanup(() => store.close()); const next = new Runtime(store, new Provider()); f.onCleanup(() => next.stopAll());
assert.deepEqual(next.mcpRegistry().jobs(store.session(f.session.id)).map(value => value.reportSha256), hashes);
});
test('31 checkpoints remain readable and resumable with legacy v1 original SHA intact after restart', async t => {
const f = paused(t); references(f, 1);
const records = []; for (let index = 0; index < 31; index++) records.push(await f.manager.create(f.session));
assert.equal(f.manager.list(f.session).length, 31);
const first = f.manager.list(f.session, { limit: 17 }), second = f.manager.list(f.session, { cursor: first.nextCursor, limit: 17 });
assert.equal(new Set([...first.items, ...second.items].map(value => value.id)).size, 31);
const { bundle } = f.manager.original(f.session, records[0].id); bundle.schemaVersion = 1;
const artifact = f.store.artifactStore.write(f.session, f.run, bundle, { kind: 'task-recovery-checkpoint' }); f.store.core.artifact.set(artifact.id, artifact);
const legacy = { ...records[0], schemaVersion: 1, id: randomUUID(), artifactId: artifact.id, sha256: artifact.sha256 };
f.store.putRecord('task_checkpoint', f.session, legacy, 'owned.legacy_checkpoint'); const before = f.store.artifactStore.readBytes(artifact);
f.store.close(); const store = new Store(f.data); f.onCleanup(() => store.close());
const runtime = new Runtime(store, new Provider()); f.onCleanup(() => runtime.stopAll()); const session = store.session(f.session.id), manager = runtime.checkpointManager();
const restarted = await manager.inspect(session, records.at(-1).id);
assert.equal(restarted.resumable, true, JSON.stringify({ reasons: restarted.reasons, status: session.status }));
assert.equal((await manager.inspect(session, legacy.id)).resumable, true); assert.deepEqual(store.artifactStore.readBytes(artifact), before);
let resumes = 0; await manager.resume(session, records.at(-1).id, records.at(-1).sha256, { resume(id) { assert.equal(id, session.id); resumes++; } });
assert.equal(resumes, 1); assert.equal(store.core.tool.size, 1);
});
test('2001 tool references and over 64MiB results use segmented indexes and streaming SHA verification without losing corruption detection', async t => {
const f = paused(t), { big } = references(f, 2001, true);
const readBytes = f.store.artifactStore.readBytes.bind(f.store.artifactStore);
f.store.artifactStore.readBytes = artifact => { assert.notEqual(artifact.id, big.id, 'large source must be verified without whole-file buffering'); return readBytes(artifact); };
const checkpoint = await f.manager.create(f.session), manifest = JSON.parse(f.store.artifactStore.read(f.store.core.artifact.get(checkpoint.artifactId)));
assert.equal(manifest.schemaVersion, 2); assert.equal(manifest.state.toolIndex.count, 2001); assert.equal(manifest.state.toolIndex.segments.length, 8);
assert.equal(f.manager.original(f.session, checkpoint.id).bundle.state.tools.length, 2001); assert.equal((await f.manager.inspect(f.session, checkpoint.id)).resumable, true);
const filename = path.join(f.store.artifactStore.root, big.relative), handle = fs.openSync(filename, 'r+');
fs.writeSync(handle, Buffer.from('b'), 0, 1, big.bytes - 1); fs.closeSync(handle);
await assert.rejects(f.manager.inspect(f.session, checkpoint.id), /工件校验失败/);
assert.equal(fs.statSync(filename).size, big.bytes);
});
test('checkpoint segment corruption is rejected and explicit restricted mode still controls creation without hiding history', async t => {
const f = paused(t); references(f, 1); const checkpoint = await f.manager.create(f.session);
const manifest = JSON.parse(f.store.artifactStore.read(f.store.core.artifact.get(checkpoint.artifactId))), segment = f.store.core.artifact.get(manifest.state.toolIndex.segments[0].artifact.id);
fs.writeFileSync(path.join(f.store.artifactStore.root, segment.relative), '{}');
await assert.rejects(f.manager.inspect(f.session, checkpoint.id), /工件校验失败/);
f.store.saveConfig({ executionMode: 'restricted' });
for (let index = 0; index < 30; index++) f.store.core.task_checkpoint.set('owned-' + index, { ...checkpoint, id: 'owned-' + index });
assert.equal(f.manager.list(f.session).length, 31); await assert.rejects(f.manager.create(f.session), /30个/);
});
test('102 independently sealed credentials restore by entry; corrupt, disabled and foreign entries preserve raw metadata and valid neighbors', t => {
const f = fixture(t, { modernDefaults: true }), encryption = sealedTestCredentials(), provider = new Provider(); provider.credentials = new Map();
const vault = new CredentialVault(f.store, provider, encryption);
const connections = Array.from({ length: 102 }, (_, index) => ({ id: randomUUID(), revision: 1, protocol: 'openai-chat', model: 'owned-' + index, baseUrl: 'http://127.0.0.1:1/v1', requiresKey: true }));
f.store.storage.transaction(() => { for (const connection of connections) vault.stage(connection.id, vault.prepare(connection, 'owned-credential-' + connection.model, 1)); });
const metadata = f.store.storage.meta('modelCredentials'); assert.equal(Object.keys(metadata.entries).length, 102);
f.store.close(); const store = new Store(f.data); f.onCleanup(() => store.close()); const nextProvider = new Provider(); nextProvider.credentials = new Map();
const next = new CredentialVault(store, nextProvider, encryption);
const hub = { connections: () => connections }; next.restore(hub);
assert.equal(nextProvider.credentials.size, 102); for (const connection of connections) assert.equal(nextProvider.credentials.get(connection.id).key, 'owned-credential-' + connection.model);
const state = store.storage.meta('modelCredentials');
state.entries[connections[0].id] = null; state.entries[connections[1].id] = { unknown: 'owned-original-broken-entry' };
state.entries[connections[2].id].enabled = false; state.entries[connections[3].id].userSid = 'owned-other-user';
store.storage.transaction(() => store.storage.setMeta('modelCredentials', state));
const cleanProvider = new Provider(); cleanProvider.credentials = new Map(); const isolated = new CredentialVault(store, cleanProvider, encryption); isolated.restore(hub);
assert.equal(cleanProvider.credentials.size, 98); assert.equal(isolated.status(connections[0]).status, 'invalid_record'); assert.equal(isolated.status(connections[1]).status, 'invalid_record');
assert.equal(isolated.status(connections[2]).status, 'disabled'); assert.equal(isolated.status(connections[3]).status, 'user_mismatch');
assert.deepEqual(store.storage.meta('modelCredentials'), state); assert.equal(JSON.stringify(isolated.view(hub)).includes('ciphertext'), false);
state.schema = 99; store.storage.transaction(() => store.storage.setMeta('modelCredentials', state));
const future = new CredentialVault(store, new Provider(), encryption); assert.equal(future.blocked, true); assert.deepEqual(store.storage.meta('modelCredentials'), state);
});
test('2001 companion operations and over 500 audit entries survive restart, preserve idempotency and expose older unknown without replay', t => {
const f = paused(t), host = { instanceId: randomUUID(), ownerId: randomUUID(), userSid: 'owned-user', pid: process.pid, createdAt: new Date().toISOString() };
const registry = new DeviceRegistry(f.store, () => host); registry.initialize();
const grant = { projectIds: [f.project.id], permissions: { observe: true, approve: false, stop: true }, expiresInHours: 24 };
const paired = registry.consume(registry.pair(grant, 'g').token, 'Owned phone', 'g'), device = registry.authenticate(paired.token), requests = [];
// Exercise each real product transaction, including its durable receipt.
for (let index = 0; index < 2001; index++) {
const input = { requestId: randomUUID(), taskId: f.session.taskId, runId: f.session.runId, revision: f.session.revision }; requests.push(input);
registry.reserve(device, 'stop', f.session, input); if (index !== 0) registry.finish(device, input, 'completed');
}
const before = registry.read(); assert.equal(Object.keys(before.operations).length, 2001); assert.equal(before.audit.length, 4002);
assert.equal(registry.reserve(device, 'stop', f.session, requests[0]).duplicate, true);
assert.throws(() => registry.reserve(device, 'stop', f.session, { ...requests[0], revision: -1 }), /请求ID/);
f.store.close(); const store = new Store(f.data); f.onCleanup(() => store.close()); const nextHost = { ...host, instanceId: randomUUID() }, next = new DeviceRegistry(store, () => nextHost), current = next.authenticate(paired.token);
const ids = [], audits = []; let page = {};
do { const result = next.operationsPage(current, page); ids.push(...result.items); page = { cursor: result.nextCursor }; if (!result.hasMore) break; } while (true);
page = {}; do { const result = next.auditPage(page); audits.push(...result.items); page = { cursor: result.nextCursor }; if (!result.hasMore) break; } while (true);
assert.equal(new Set(ids.map(value => value.id)).size, 2001); assert.equal(ids.at(-1).status, 'unknown'); assert.equal(audits.length, 4002);
assert.equal(next.reserve(current, 'stop', store.session(f.session.id), requests[0]).status, 'pending'); assert.deepEqual(next.read().operations, before.operations);
assert.equal(JSON.stringify(next.view()).includes('credentialHash'), false);
});