From 32780bee8dc4d353b6e58d5e02bee308ea75ae33 Mon Sep 17 00:00:00 2001 From: Agent Workbench Dev Date: Sat, 7 Nov 2026 03:17:05 +0800 Subject: [PATCH] fix: remove open execution record caps and preserve recovery history --- scripts/verify-open-records-ui.mjs | 147 ++++++++++++++++++ src/client/CompanionPanel.tsx | 9 +- src/client/McpJobHistory.tsx | 21 ++- src/client/McpPanel.tsx | 35 ++--- src/client/TaskCheckpointPanel.tsx | 16 +- src/client/TaskPanel.tsx | 4 +- src/client/companion-types.ts | 5 +- src/client/mobile/MobileApp.tsx | 14 +- src/client/mobile/orven-mobile.css | 3 + src/client/types.ts | 3 +- src/client/useRecordPages.ts | 49 ++++++ src/core/companion/device-registry.mjs | 23 ++- src/core/models/credential-vault.mjs | 11 +- src/core/storage/artifact-store.mjs | 15 ++ src/core/tasks/task-checkpoint-manager.mjs | 57 +++++-- src/core/tools/mcp-registry.mjs | 11 +- src/server/app.mjs | 6 +- src/server/companion-gateway.mjs | 14 +- src/server/store.mjs | 4 +- src/shared/contracts/record-page.mjs | 27 ++++ tests/companion.test.mjs | 25 ++- tests/open-records.test.mjs | 170 +++++++++++++++++++++ 22 files changed, 595 insertions(+), 74 deletions(-) create mode 100644 scripts/verify-open-records-ui.mjs create mode 100644 src/client/useRecordPages.ts create mode 100644 src/shared/contracts/record-page.mjs create mode 100644 tests/open-records.test.mjs diff --git a/scripts/verify-open-records-ui.mjs b/scripts/verify-open-records-ui.mjs new file mode 100644 index 00000000..006ade15 --- /dev/null +++ b/scripts/verify-open-records-ui.mjs @@ -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; diff --git a/src/client/CompanionPanel.tsx b/src/client/CompanionPanel.tsx index 05cf6105..49d57ef8 100644 --- a/src/client/CompanionPanel.tsx +++ b/src/client/CompanionPanel.tsx @@ -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('/companion'); if (mounted.current) { setStatus(result); setAddress(previous => previous || result.addresses[0]?.address || ''); } } + const audit = useRecordPages('/companion/audit', value => setError(value instanceof Error ? value.message : String(value))); + async function refresh() { const result = await api('/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 &&
手机一次性配对二维码
使用 iPhone 相机扫描

请先完成证书信任。{new Date(pair.expiresAt).toLocaleTimeString()} 失效。

{pair.url}

把链接发给自己时,接收者可以取得所选项目权限。完成配对后此链接立即失效。

}

已登记设备 {status?.devices.length ?? 0}

{!status?.devices.length &&

配对完成后,设备和授权范围会显示在这里。

}{status?.devices.map(device =>
{device.name}

{device.projectIds.map(id => projects.find(project => project.id === id)?.name ?? '原项目').join('、')} · {device.permissions.approve ? '可审批' : '观察'}{device.permissions.stop ? ' · 可停止' : ''}

{({ active: '已授权', revoked: '已撤销', expired: '已到期', reconnect_required: '需重新配对' } as Record)[device.status ?? ''] ?? device.status} · {new Date(device.expiresAt).toLocaleString()} 到期
)}
- {!!status?.audit.length &&
最近的设备操作{status.audit.slice(0, 12).map(item =>

{status.devices.find(device => device.id === item.deviceId)?.name ?? '原设备'} · {({ pair: '配对', rotate: '轮换会话', revoke: '撤销', approve: '审批', stop: '停止' } as Record)[item.action] ?? item.action}{item.status}

)}
} + {status &&
设备操作记录 · 已加载 {audit.items.length} / {audit.total} 项{audit.items.map(item =>

{status.devices.find(device => device.id === item.deviceId)?.name ?? '原设备'} · {({ pair: '配对', rotate: '轮换会话', revoke: '撤销', approve: '审批', stop: '停止' } as Record)[item.action] ?? item.action}{item.status}

)} + {audit.hasMore && }
} ; } diff --git a/src/client/McpJobHistory.tsx b/src/client/McpJobHistory.tsx index 97087dec..35738f6a 100644 --- a/src/client/McpJobHistory.tsx +++ b/src/client/McpJobHistory.tsx @@ -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 = { 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 | null; input: { artifactId: string; sha256: string; input: Record }; 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('/sessions/' + session.id + '/mcp/jobs', onError); + useEffect(() => { void history.refresh(); }, [session.revision, history.refresh]); + return ; +} + +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; busy: boolean; onSession: (value: Session) => void; onError: (error: unknown) => void; }) { const [selected, setSelected] = useState(null); const [review, setReview] = useState(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 <>
-

MCP 运行记录

{visible.length} 项
+

MCP 运行记录

已加载 {visible.length} / {total} 项
{visible.length ?
{visible.map(job =>
{job.input?.call?.tool || (job.operation === 'probe' ? '协议与工具探测' : '工具调用')}{timestamp(job.startedAt)} · {job.operation === 'probe' ? '探测' : '调用'}
{active.includes(job.status) && }{job.requiresVerification && }{job.status === 'unknown' && job.reviewedAt && !job.requiresVerification ? '已人工核对 · 原结果未知' : labels[job.status] ?? job.status}
@@ -51,7 +61,8 @@ export function McpJobHistory({ session, jobs, busy, onSession, onError }: { {job.error?.message &&

{job.error.message}

}
{job.requiresVerification && }
-
)}
:

当前任务还没有 MCP 操作记录。

} + )} :

{loading ? '正在读取 MCP 记录。' : '当前会话还没有 MCP 操作记录。'}

} + {hasMore && } {selected &&
{selected.report ? '原始 MCP 报告' : '已封存的原始输入'}
SHA256{selected.job.reportSha256 ?? selected.input.sha256}Task / Run{selected.job.taskId} / {selected.job.runId}

报告绑定原 Task/Run 和工具输入。独立所属进程不等于 OS 沙箱,报告也不能证明外部程序没有网络或其他副作用。

diff --git a/src/client/McpPanel.tsx b/src/client/McpPanel.tsx index 7bc1122e..4cb38b74 100644 --- a/src/client/McpPanel.tsx +++ b/src/client/McpPanel.tsx @@ -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 = { verified: '握手已核验', unverified: '尚未探测', changed: '来源或契约异常' }; -type View = { projectId: string; revision: number; protocolVersion: string; boundary: string; limits: Record; registrations: McpRegistration[] }; +type View = { projectId: string; revision: number; protocolVersion: string; boundary: string; executionMode: string; limits: Record; 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(null), [jobs, setJobs] = useState([]); + const [view, setView] = useState(null); + const history = useRecordPages(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>({}); const [draft, setDraft] = useState({ 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(url), session ? api('/sessions/' + session.id + '/mcp/jobs') : Promise.resolve([] as McpJob[]), - ]); + const [nextView] = await Promise.all([api(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('/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(url)); + const current = generation.current; + const timer = window.setInterval(() => { void Promise.all([history.refresh(), api(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

{registration.name}

{stateName[registration.status] ?? registration.status} · 配置修订 {registration.configurationRevision}

{registration.enabled ? '已启用' : '已停用'}
可执行文件{registration.launch.executable.path} SHA256 {registration.launch.executable.sha256.slice(0, 16)} · {registration.launch.executable.bytes.toLocaleString()} B
{registration.launch.entry &&
脚本入口{registration.launch.entry.path}SHA256 {registration.launch.entry.sha256.slice(0, 16)} · {registration.launch.entry.bytes.toLocaleString()} B
} - 请求上限 {registration.timeoutMs.toLocaleString()} ms
+ {view.executionMode === 'unrestricted' ? '开放执行 · 不设请求超时' : '请求上限 ' + registration.timeoutMs.toLocaleString() + ' ms'} {registration.reason &&

{registration.reason}

} {registration.contract &&
实际契约 SHA256 {registration.contract.sha256.slice(0, 16)} · 发现 {registration.tools.length} 项工具
} - {registration.contract &&
允许模型请求的工具已选择 {chosen.length} / 12
+ {registration.contract &&
允许模型请求的工具已选择 {chosen.length}{view.limits.allowedTools === null ? ' · 数量不限' : ' / ' + view.limits.allowedTools}
{registration.tools.map(tool =>
: view &&
尚未登记项目 MCP

只登记你已审查的本地可执行文件。程序和 Node 入口会在探测及启用前重新计算 SHA256。

} {!view && !error &&

正在读取项目注册

}
-

登记本地 MCP

绝对路径 · 默认停用 · 最多 {view?.limits.registrations ?? 16} 项
+

登记本地 MCP

绝对路径 · 默认停用 · {view?.limits.registrations === null ? '登记数量不限' : '最多 ' + (view?.limits.registrations ?? 16) + ' 项'}
- +
仅保留系统路径与临时目录环境,不传入模型 Key;不安装脚本、不使用 shell。
- {session && } + {session && } {!session &&

选择或创建一个任务会话后,可以对已登记程序执行探测。

} {probeTarget && { setProbeTarget(null); setRequestError(''); }}>
{probeTarget.name}{probeTarget.launch.executable.path}{probeTarget.launch.entry && {probeTarget.launch.entry.path}} diff --git a/src/client/TaskCheckpointPanel.tsx b/src/client/TaskCheckpointPanel.tsx index d560e299..bd37bae9 100644 --- a/src/client/TaskCheckpointPanel.tsx +++ b/src/client/TaskCheckpointPanel.tsx @@ -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([]), [view, setView] = useState(null); + const history = useRecordPages(task ? `/sessions/${session.id}/task-checkpoints` : null, onError, api, scope), records = history.items; + const [view, setView] = useState(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(`/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
-

恢复检查点

{records.length} 个
+

恢复检查点

已加载 {records.length} / {history.total} 个

保存完整目标、原工具结果和待处理项;续接前核对源码与任务身份。

{notice &&

{notice}

} @@ -59,6 +58,7 @@ export function TaskCheckpointPanel({ session, busy, onSession, onError, openArt
)} + {history.hasMore && } {view &&
{view.resumable ? '当前可以续接原任务' : '暂不能从此检查点续接'} {view.reasons.length > 0 &&
    {view.reasons.map(reason =>
  • {reason}
  • )}
} {view.resumable && } diff --git a/src/client/TaskPanel.tsx b/src/client/TaskPanel.tsx index 144c4472..fd3c73cf 100644 --- a/src/client/TaskPanel.tsx +++ b/src/client/TaskPanel.tsx @@ -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 && } {task && } {execution?.progress.requiresVerification.length ?
{execution.progress.requiresVerification.length} 项结果需要核对

这些调用已进入执行,但缺少可靠结果。继续任务会保留记录。

{execution.progress.requiresVerification.map(tool => {tool.tool} · {tool.id.slice(0, 8)})}
: null} - {task && !!execution?.mcpJobs?.length && } + {task && !!(execution?.mcpJobCount || execution?.mcpJobs?.length) && } {task &&

运行记录

{execution?.runs.filter(item => item.taskId === task.id).length} 次
diff --git a/src/client/companion-types.ts b/src/client/companion-types.ts index 44c89e52..5b687aa2 100644 --- a/src/client/companion-types.ts +++ b/src/client/companion-types.ts @@ -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; } 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 } diff --git a/src/client/mobile/MobileApp.tsx b/src/client/mobile/MobileApp.tsx index ccdb4d0f..47a2e7ea 100644 --- a/src/client/mobile/MobileApp.tsx +++ b/src/client/mobile/MobileApp.tsx @@ -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)[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; 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(null); const [document, setDocument] = useState<{ title: string; text: string; sha256: string; redacted?: boolean } | null>(null), [receipt, setReceipt] = useState(''); + const operations = useRecordPages(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(null), chosen = useRef(''), running = useRef(false), actionBusy = useRef(false), alive = useRef(true), generation = useRef(0), dialog = useRef(null), documentDialog = useRef(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 && setAppearanceOpen(false)}>} {me &&
{fresh ? : }{fresh ? '已同步 · ' + time(lastSync) : '连接中断 · 当前内容可能已过期'}{me.device.permissions.approve ? '可审批' : '观察'}
} {error &&
{fresh ? '操作未完成' : connectionRequired ? '需要连接' : '连接待恢复'}

{error}

{me && }
} - {me?.operations?.some(value => value.status === 'unknown') &&
手机操作回执需要核对

有原审批或停止操作没有完整回执,请在电脑核对;手机不会自动重放。

{me.operations.filter(value => value.status === 'unknown').map(value => Task {value.taskId} · {value.action === 'stop' ? '停止' : '审批'})}
} + {!!me?.unresolvedOperations?.length &&
手机操作回执需要核对

有原审批或停止操作没有完整回执,请在电脑核对;手机不会自动重放。

{me.unresolvedOperations.map(value => Task {value.taskId} · {value.action === 'stop' ? '停止' : '审批'})}
} + {me &&
手机操作记录 · 已加载 {operations.items.length} / {operations.total} 项{operations.items.map(value =>

{value.action === 'stop' ? '停止' : '审批'} · {value.taskId.slice(0, 8)} · {stateLabel(value.status)} · {time(value.createdAt)}

)} + {operations.hasMore && }
} {!me &&

接续电脑上的任务

在 Windows 工作台打开「手机连接」,选择项目并生成一次性配对码。

{connectionRequired || pairToken ?
void pair(event)}>
:

正在核对当前手机连接…

}

首次使用需要在 iPhone 安装并信任电脑生成的根证书。请按电脑「手机连接」中的指引操作。

} {me && !selected &&
{me.device.name}

项目任务

{sessions.length} 个会话
{!sessions.length &&

暂无任务

在电脑创建或打开任务,手机会同步该项目的执行进展。

} {sessions.filter(item => !project || item.projectId === project).map(item => )} -
设备连接与授权

{projects.map(item => item.name).join('、')}

观察{me.device.permissions.approve ? ' · 审批' : ''}{me.device.permissions.stop ? ' · 停止' : ''} · {time(me.device.expiresAt)} 到期

手机显示最近200个未归档会话,完整历史在电脑保留。

iPhone Safari 中点「共享 → 添加到主屏幕」可安装伴随端。主屏幕应用如要求连接,请在电脑生成新的配对码。

} +
设备连接与授权

{projects.map(item => item.name).join('、')}

观察{me.device.permissions.approve ? ' · 审批' : ''}{me.device.permissions.stop ? ' · 停止' : ''} · {time(me.device.expiresAt)} 到期

显示已授权项目的未归档会话;操作记录可加载更早记录。

iPhone Safari 中点「共享 → 添加到主屏幕」可安装伴随端。主屏幕应用如要求连接,请在电脑生成新的配对码。

} {me && selected &&
{!selectedTask ?
正在读取原任务…
: <>
{projectName(selectedTask.projectId)}

{selectedTask.title}

{stateLabel(selectedTask.status)}修订 {selectedTask.revision}
完整任务目标

{selectedTask.task?.goal ?? '此会话尚未创建执行任务。'}

原任务与运行Task {selectedTask.taskId ?? '未开始'}
Run {selectedTask.runId ?? '未开始'}
{receipt &&

{receipt}

} diff --git a/src/client/mobile/orven-mobile.css b/src/client/mobile/orven-mobile.css index f70cc7ed..fa1a4816 100644 --- a/src/client/mobile/orven-mobile.css +++ b/src/client/mobile/orven-mobile.css @@ -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; } diff --git a/src/client/types.ts b/src/client/types.ts index 23763d4e..a2a97285 100644 --- a/src/client/types.ts +++ b/src/client/types.ts @@ -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 { 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)[]; 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 }[] } diff --git a/src/client/useRecordPages.ts b/src/client/useRecordPages.ts new file mode 100644 index 00000000..f26123b5 --- /dev/null +++ b/src/client/useRecordPages.ts @@ -0,0 +1,49 @@ +import { useCallback, useEffect, useRef, useState } from 'react'; +import { api } from './api'; +import type { RecordPage } from './types'; + +const empty = (): RecordPage => ({ items: [], total: 0, hasMore: false, nextCursor: null }); +type FetchPage = (url: string) => Promise; +export function useRecordPages(url: string | null, onError: (error: unknown) => void, fetchPage: FetchPage = api, scope = url) { + const [page, setPage] = useState>(empty), [loading, setLoading] = useState(false); + const current = useRef(empty()), 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>(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>(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(); setPage(empty()); setLoading(false); + void refresh(); + return () => { epoch.current++; pending.current = false; }; + }, [refresh]); + return { ...page, loading, refresh, loadMore }; +} diff --git a/src/core/companion/device-registry.mjs b/src/core/companion/device-registry.mjs index 696dcfb9..1183f4ba 100644 --- a/src/core/companion/device-registry.mjs +++ b/src/core/companion/device-registry.mjs @@ -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; diff --git a/src/core/models/credential-vault.mjs b/src/core/models/credential-vault.mjs index 78787880..920bbbc5 100644 --- a/src/core/models/credential-vault.mjs +++ b/src/core/models/credential-vault.mjs @@ -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); diff --git a/src/core/storage/artifact-store.mjs b/src/core/storage/artifact-store.mjs index beef52f0..391ac1b5 100644 --- a/src/core/storage/artifact-store.mjs +++ b/src/core/storage/artifact-store.mjs @@ -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); } + } } diff --git a/src/core/tasks/task-checkpoint-manager.mjs b/src/core/tasks/task-checkpoint-manager.mjs index d4daa397..ea82a592 100644 --- a/src/core/tasks/task-checkpoint-manager.mjs +++ b/src/core/tasks/task-checkpoint-manager.mjs @@ -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('恢复包引用的原工具工件身份已变化。'); diff --git a/src/core/tools/mcp-registry.mjs b/src/core/tools/mcp-registry.mjs index 515c0728..3a5c0467 100644 --- a/src/core/tools/mcp-registry.mjs +++ b/src/core/tools/mcp-registry.mjs @@ -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('当前项目有任务正在执行。'); diff --git a/src/server/app.mjs b/src/server/app.mjs index 62d1ad37..fd256ae1 100644 --- a/src/server/app.mjs +++ b/src/server/app.mjs @@ -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 }); diff --git a/src/server/companion-gateway.mjs b/src/server/companion-gateway.mjs index 6250bc0a..a5ec10f4 100644 --- a/src/server/companion-gateway.mjs +++ b/src/server/companion-gateway.mjs @@ -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 }); diff --git a/src/server/store.mjs b/src/server/store.mjs index d615ee7e..c995be78 100644 --- a/src/server/store.mjs +++ b/src/server/store.mjs @@ -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), diff --git a/src/shared/contracts/record-page.mjs b/src/shared/contracts/record-page.mjs new file mode 100644 index 00000000..ecdfb999 --- /dev/null +++ b/src/shared/contracts/record-page.mjs @@ -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 }; +} diff --git a/tests/companion.test.mjs b/tests/companion.test.mjs index 6d7a50d0..5c1e7110 100644 --- a/tests/companion.test.mjs +++ b/tests/companion.test.mjs @@ -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); diff --git a/tests/open-records.test.mjs b/tests/open-records.test.mjs new file mode 100644 index 00000000..7877aa0f --- /dev/null +++ b/tests/open-records.test.mjs @@ -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); +});