feat(companion): add task PWA and original execution controls

This commit is contained in:
Agent Workbench Dev
2026-10-31 17:53:15 +08:00
parent dfe2e40387
commit bc67e6e0a3
57 changed files with 1212 additions and 15 deletions
+4 -1
View File
@@ -15,6 +15,7 @@ import { SkillCenter } from './SkillCenter';
import { McpPanel } from './McpPanel';
import { WorkerPanel } from './WorkerPanel';
import { DesktopPanel } from './DesktopPanel';
import { CompanionPanel } from './CompanionPanel';
import { desktop } from './desktop';
const activeStates = ['running', 'awaiting_approval', 'stopping'];
@@ -78,6 +79,7 @@ export default function App() {
const [mcpOpen, setMcpOpen] = useState(false);
const [workersOpen, setWorkersOpen] = useState(false);
const [desktopOpen, setDesktopOpen] = useState(false);
const [companionOpen, setCompanionOpen] = useState(false);
const [pickingProject, setPickingProject] = useState(false);
const [researchDocs, setResearchDocs] = useState<ResearchDoc[]>([]);
const [report, setReport] = useState<{ title: string; content: string } | null>(null);
@@ -534,7 +536,7 @@ export default function App() {
</aside>
<main className="task-pane">
<header className="work-header"><div className="work-title">{(!sidebarOpen || mobile) && <IconButton label="展开项目栏" onClick={() => setSidebarOpen(true)}><PanelLeftOpen size={18} /></IconButton>}<span className="header-symbol"><Code2 size={17} /></span><div><span className="header-breadcrumb">{selectedProject?.name || '工作空间'} <ChevronRight size={12} /> 任务</span><h1>{session?.title || '让任务走到完成'}</h1></div></div>
<div className="model-launch">{desktop && <button className="button secondary desktop-launch" onClick={() => setDesktopOpen(true)} aria-label="桌面宿主"><SquareTerminal size={16} /><span>桌面宿主</span></button>}<button className="button secondary" onClick={() => setModelCenterOpen(true)} aria-label="打开模型中心"><ModelServer size={16} /><span>模型中心</span></button><button className={'model-button ' + (config.mode === 'demo' ? 'demo' : '')} onClick={openSettings}><span className="model-light" />{config.mode === 'demo' ? '离线演示' : config.model || '选择模型'}<ChevronDown size={13} /></button></div>
<div className="model-launch"><button className="button secondary" onClick={() => setCompanionOpen(true)} aria-label="手机连接"><Link2 size={16} /><span>手机连接</span></button>{desktop && <button className="button secondary desktop-launch" onClick={() => setDesktopOpen(true)} aria-label="桌面宿主"><SquareTerminal size={16} /><span>桌面宿主</span></button>}<button className="button secondary" onClick={() => setModelCenterOpen(true)} aria-label="打开模型中心"><ModelServer size={16} /><span>模型中心</span></button><button className={'model-button ' + (config.mode === 'demo' ? 'demo' : '')} onClick={openSettings}><span className="model-light" />{config.mode === 'demo' ? '离线演示' : config.model || '选择模型'}<ChevronDown size={13} /></button></div>
</header>
<div className="task-toolbar"><span className="task-local"><GitBranch size={13} />本地项目</span>{session ? <Status value={session.status} /> : <span className="subtle">等待新任务</span>}<div className="toolbar-actions">
<IconButton label="运行诊断" onClick={() => openDiagnostics()}><Activity size={15} /></IconButton>
@@ -577,6 +579,7 @@ export default function App() {
<div className="inspector-footer"><ShieldCheck size={13} /><span>{tab === 'changes' ? '应用前会核对文件基线' : tab === 'trace' ? '中断调用保留待核实状态' : tab === 'task' ? '任务目标、检查与结果持久保存' : tab === 'index' ? '结果绑定当前项目及文件 SHA256' : '读取范围限定在当前项目'}</span></div>
</aside>
{projectOpen && <Modal title="打开项目" description="选择要在本机读取和开发的项目文件夹。" onClose={() => setProjectOpen(false)}><form onSubmit={event => { event.preventDefault(); openProject(); }}><label className="form-field">项目文件夹<input autoFocus value={projectInput} onChange={event => setProjectInput(event.target.value)} placeholder="C:\Projects\my-app" aria-label="项目文件夹路径" /></label><div className="modal-actions">{desktop && <button type="button" className="button secondary" disabled={pickingProject} onClick={() => void pickDesktopProject()}>选择文件夹</button>}{exampleId && <button type="button" className="button secondary" onClick={() => { chooseProject(exampleId); setProjectOpen(false); }}>打开示例项目</button>}<button type="submit" className="button primary" disabled={!projectInput.trim()}><FolderOpen size={15} />打开项目</button></div></form></Modal>}
{companionOpen && <Modal title="手机连接" description="指定项目和权限,连接到同一个Windows执行宿主。" onClose={() => setCompanionOpen(false)} wide><CompanionPanel projects={projects} selectedProjectId={selectedProject?.id ?? ''} /></Modal>}
{desktopOpen && desktop && <Modal title="桌面与后台任务" description="当前窗口连接同一个本机执行宿主。" onClose={() => setDesktopOpen(false)}><DesktopPanel project={selectedProject} session={session} file={openFile} onProject={acceptDesktopProject} onReview={scope => { if (selectedProjectRef.current === scope.projectId && selectedSessionRef.current === scope.sessionId && selectedTaskRef.current === scope.taskId) { setDesktopOpen(false); showInspector('task'); } }} /></Modal>}
{settingsOpen && <Modal title="模型连接" description="同一套项目工具,可以使用离线演示或你自己的模型服务。" onClose={() => setSettingsOpen(false)}><form onSubmit={event => { event.preventDefault(); saveSettings(); }}><div className="mode-picker"><button type="button" className={settings.mode === 'demo' ? 'selected' : ''} onClick={() => setSettings(previous => ({ ...previous, mode: 'demo' }))}><Play size={18} /><strong>离线演示</strong><span>固定脚本,真实本地工具</span></button><button type="button" className={settings.mode === 'compatible' ? 'selected' : ''} onClick={() => setSettings(previous => ({ ...previous, mode: 'compatible' }))}><Link2 size={18} /><strong>兼容模型服务</strong><span>使用自己的本地或远程模型</span></button></div>
{settings.mode === 'compatible' && <><div className="connection-presets"><button type="button" onClick={() => setSettings(previous => ({ ...previous, baseUrl: 'http://127.0.0.1:11434/v1' }))}>Ollama</button><button type="button" onClick={() => setSettings(previous => ({ ...previous, baseUrl: 'http://127.0.0.1:8000/v1' }))}>vLLM</button><span>Chat Completions 兼容接口</span></div><label className="form-field">接口根地址<input type="url" value={settings.baseUrl} onChange={event => setSettings(previous => ({ ...previous, baseUrl: event.target.value }))} placeholder="http://127.0.0.1:11434/v1" /></label><label className="form-field">API Key(按服务要求填写)<input type="password" autoComplete="off" value={keyValue} onChange={event => { setKeyValue(event.target.value); setClearKey(false); }} placeholder={config.hasKey ? '本次运行已设置,留空保留' : '本地服务可以不填'} /></label><div className="key-note"><span>只在本次服务内存中使用,不写入会话与配置。</span>{config.hasKey && <button type="button" onClick={() => { setClearKey(true); setKeyValue(''); }}>{clearKey ? '保存后清除' : '清除 Key'}</button>}</div><div className="model-field"><label className="form-field">模型名称<input list="model-list" value={settings.model} onChange={event => setSettings(previous => ({ ...previous, model: event.target.value }))} placeholder="例如 qwen3:8b" /><datalist id="model-list">{models.map(model => <option key={model} value={model} />)}</datalist></label><button className="button secondary" type="button" onClick={readModels} disabled={settingsBusy || anyRunning}>{settingsBusy ? <LoaderCircle size={14} className="spin" /> : <Search size={14} />}读取模型列表</button></div><div className="model-test-row"><span>填写服务提供的接口根地址。</span><button type="button" className="button secondary" onClick={testModel} disabled={settingsBusy || anyRunning || !settings.model}><Activity size={14} />验证模型响应</button></div>{modelCheck && <div className={'model-check model-check-' + modelCheck.kind} role="status">{modelCheck.message}</div>}</>}
+45
View File
@@ -0,0 +1,45 @@
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 './companion-panel.css';
export function CompanionPanel({ projects, selectedProjectId }: { projects: Project[]; selectedProjectId: string }) {
const [status, setStatus] = useState<CompanionStatus | null>(null), [address, setAddress] = useState(''), [port, setPort] = useState(4319);
const [selected, setSelected] = useState<string[]>(selectedProjectId ? [selectedProjectId] : []);
const [approve, setApprove] = useState(false), [stop, setStop] = useState(false), [hours, setHours] = useState(24);
const [pair, setPair] = useState<{ url: string; qr: string; expiresAt: string } | null>(null), [busy, setBusy] = useState(''), [error, setError] = useState('');
const mounted = useRef(true);
async function refresh() { const result = await api<CompanionStatus>('/companion'); if (mounted.current) { setStatus(result); setAddress(previous => previous || result.addresses[0]?.address || ''); } }
useEffect(() => {
mounted.current = true; void refresh().catch(value => { if (mounted.current) setError(value.message); });
const timer = setInterval(() => void refresh().catch(() => {}), 5000);
return () => { mounted.current = false; clearInterval(timer); };
}, []);
useEffect(() => { if (!pair) return; const timer = setTimeout(() => setPair(null), Math.max(0, Date.parse(pair.expiresAt) - Date.now())); return () => clearTimeout(timer); }, [pair]);
async function act(name: string, action: () => Promise<unknown>) {
if (busy) return; setBusy(name); setError('');
try { await action(); await refresh(); } catch (value) { if (mounted.current) setError(value instanceof Error ? value.message : '手机连接操作失败。'); }
finally { if (mounted.current) setBusy(''); }
}
return <div className="companion-panel">
<div className="companion-heading"><Smartphone size={25} /><div><strong>{status?.enabled ? '手机连接已开启' : '在 iPhone 上接续任务'}</strong><p>同一 Wi-Fi,通过 Safari 查看原任务、确认审批和停止执行。</p></div><span className="companion-state">{status?.enabled ? 'HTTPS' : '默认关闭'}</span></div>
{error && <p className="companion-error" role="alert">{error}</p>}
<section className="companion-network"><h3>Windows 连接地址</h3>
{status?.enabled ? <div className="companion-address"><code>{status.origin}</code><button className="button secondary" disabled={!!busy} onClick={() => void act('close', async () => { await api('/companion/close', {}); setPair(null); })}>关闭手机连接</button></div>
: <form onSubmit={event => { event.preventDefault(); void act('start', () => api('/companion/start', { address, port })); }}><label>局域网地址<select aria-label="手机连接地址" value={address} onChange={event => setAddress(event.target.value)}>{!address && <option value="">请选择网络</option>}{status?.addresses.map(item => <option key={item.address} value={item.address}>{item.name} · {item.address}</option>)}</select></label><label>端口<input aria-label="手机连接端口" type="number" min={1024} max={65535} value={port} onChange={event => setPort(Number(event.target.value))} /></label><button className="button primary" disabled={!!busy || !address || !!status?.busy}><Link2 size={15} />{busy === 'start' ? '正在生成证书…' : '开启 HTTPS'}</button></form>}
{status && !status.addresses.length && !status.enabled && <p>尚未找到局域网地址。请先让电脑连接 Wi-Fi 或有线局域网,再刷新此窗口。</p>}
<p className="companion-note">关闭手机连接后,电脑上的任务继续运行。宿主重启后,需要在这里重新开启。</p>
</section>
{status?.certificate && <details className="companion-certificate" open={!status.devices.length}><summary><ShieldCheck size={16} />首次连接:在 iPhone 信任证书</summary><ol><li>下载本机根证书,用你自己的文件传输方式保存到 iPhone「文件」,点开安装。</li><li>在 iPhone「设置 → 通用 → VPN 与设备管理」安装此证书描述文件。</li><li>在「设置 → 通用 → 关于本机 → 证书信任设置」开启此根证书的完全信任。</li><li>核对下方证书指纹,然后扫描新的配对码。连接地址发生变化时,在电脑重新开启网关。</li></ol><button className="button secondary" disabled={!!busy} onClick={() => void act('certificate', downloadCompanionCertificate)}><Download size={14} />下载手机根证书</button><code className="companion-fingerprint">SHA-256 {status.certificate.sha256}</code><p className="companion-note">证书到期 {new Date(status.certificate.expiresAt).toLocaleDateString()}。若无法连接,请核对同一 Wi-Fi、访客网络隔离和 Windows 防火墙的当前端口;这里不会修改系统信任或防火墙。</p></details>}
<section><h3>连接一台手机</h3><p className="companion-note">仅授予选中项目。配对链接两分钟内有效,用过即失效。</p>
<fieldset disabled={!!busy || !status?.enabled}><legend>允许查看的项目</legend><div className="companion-projects">{projects.map(project => <label key={project.id}><input type="checkbox" checked={selected.includes(project.id)} onChange={event => { setPair(null); setSelected(previous => event.target.checked ? [...previous, project.id] : previous.filter(id => id !== project.id)); }} />{project.name}</label>)}</div></fieldset>
<div className="companion-grant"><span>观察任务 · 必选</span><label><input type="checkbox" checked={approve} onChange={event => { setApprove(event.target.checked); setPair(null); }} />允许审批命令</label><label><input type="checkbox" checked={stop} onChange={event => { setStop(event.target.checked); setPair(null); }} />允许停止任务</label><label>有效期<select aria-label="手机设备有效期" value={hours} onChange={event => { setHours(Number(event.target.value)); setPair(null); }}><option value={24}>24 小时</option><option value={168}>7 天</option><option value={720}>30 天</option></select></label></div>
<button className="button primary" disabled={!!busy || !status?.enabled || !selected.length || selected.length > 16} onClick={() => void act('pair', async () => { const result = await api<{ url: string; qr: string; expiresAt: string }>('/companion/pair', { projectIds: selected, permissions: { observe: true, approve, stop }, expiresInHours: hours }); if (mounted.current) setPair(result); })}>生成一次性配对码</button>
{pair && status?.enabled && <div className="companion-pair"><img src={pair.qr} alt="手机一次性配对二维码" width={224} height={224} /><div><strong>使用 iPhone 相机扫描</strong><p>请先完成证书信任。{new Date(pair.expiresAt).toLocaleTimeString()} 失效。</p><p className="companion-pair-url">{pair.url}</p><p>把链接发给自己时,接收者可以取得所选项目权限。完成配对后此链接立即失效。</p></div></div>}
</section>
<section><h3>已登记设备 <span>{status?.devices.length ?? 0}</span></h3>{!status?.devices.length && <p className="companion-note">配对完成后,设备和授权范围会显示在这里。</p>}{status?.devices.map(device => <div key={device.id} className="companion-device"><Smartphone size={18} /><div><strong>{device.name}</strong><p>{device.projectIds.map(id => projects.find(project => project.id === id)?.name ?? '原项目').join('、')} · {device.permissions.approve ? '可审批' : '观察'}{device.permissions.stop ? ' · 可停止' : ''}</p><small>{({ active: '已授权', revoked: '已撤销', expired: '已到期', reconnect_required: '需重新配对' } as Record<string, string>)[device.status ?? ''] ?? device.status} · {new Date(device.expiresAt).toLocaleString()} 到期</small></div><button className="button secondary" disabled={!!busy || device.status !== 'active'} onClick={() => void act('revoke', async () => { await api('/companion/devices/' + device.id + '/revoke', { revision: device.revision }); setPair(null); })}><X size={13} />撤销</button></div>)}</section>
{!!status?.audit.length && <details className="companion-audit"><summary>最近的设备操作</summary>{status.audit.slice(0, 12).map(item => <p key={item.id}><time>{new Date(item.at).toLocaleTimeString()}</time><span>{status.devices.find(device => device.id === item.deviceId)?.name ?? '原设备'} · {({ pair: '配对', rotate: '轮换会话', revoke: '撤销', approve: '审批', stop: '停止' } as Record<string, string>)[item.action] ?? item.action}</span><code>{item.status}</code></p>)}</details>}
</div>;
}
+5
View File
@@ -16,6 +16,11 @@ export async function exportSession(id: string) {
const blob = await response.blob();
downloadBlob(blob, 'agent-workbench-session-' + id + '.json');
}
export async function downloadCompanionCertificate() {
const response = await fetch('/api/companion/certificate', { headers: { 'X-Workbench-Token': accessToken } });
if (!response.ok) { const value = await response.json().catch(() => ({})); throw new Error(value.error || '手机根证书下载失败。'); }
downloadBlob(await response.blob(), 'Agent-Workbench-Mobile-CA.cer');
}
export async function downloadArtifact(sessionId: string, artifactId: string, name: string) {
const response = await fetch('/api/artifacts/' + artifactId + '?session=' + sessionId + '&download=1', { headers: { 'X-Workbench-Token': accessToken } });
if (!response.ok) {
+1
View File
@@ -0,0 +1 @@
.companion-panel{color:var(--ink);font-size:13px;line-height:1.7}.companion-heading{display:flex;gap:14px;align-items:flex-start;margin-bottom:22px}.companion-heading>div{flex:1}.companion-heading strong{font-size:18px}.companion-heading p{margin:5px 0;color:var(--muted)}.companion-state{padding:3px 8px;border:1px solid var(--line);border-radius:4px;font-size:11px;white-space:nowrap}.companion-panel section{padding:20px 0;border-top:1px solid var(--line)}.companion-panel h3{font-size:14px;margin:0 0 12px}.companion-panel h3 span{font-size:12px;color:var(--muted);margin-left:8px}.companion-network form,.companion-address{display:flex;align-items:flex-end;gap:12px;flex-wrap:wrap}.companion-network label{display:grid;gap:5px}.companion-network select,.companion-network input,.companion-grant select{background:var(--paper);color:var(--ink);padding:9px;border:1px solid #b5c9c3;border-radius:5px}.companion-network input{width:96px}.companion-note{font-size:12px;color:var(--muted)}.companion-address code{flex:1;overflow-wrap:anywhere}.companion-panel fieldset{margin:12px 0;border:1px solid var(--line);padding:12px;border-radius:5px}.companion-panel legend{padding:0 6px;font-size:12px}.companion-projects{display:flex;gap:12px 18px;flex-wrap:wrap;max-height:150px;overflow:auto}.companion-projects label,.companion-grant label{display:flex;gap:7px;align-items:center}.companion-projects input,.companion-grant input{accent-color:var(--teal);width:17px;height:17px}.companion-grant{display:flex;gap:14px;align-items:center;flex-wrap:wrap;margin:14px 0 18px;font-size:12px}.companion-grant>span{color:var(--muted)}.companion-certificate{border-top:1px solid var(--line);padding:18px 0}.companion-certificate summary{display:flex;gap:8px;align-items:center;cursor:pointer;font-weight:600}.companion-certificate ol{padding-left:22px;color:var(--muted);line-height:1.9}.companion-fingerprint{display:block;font-size:11px;overflow-wrap:anywhere;margin-top:12px;color:var(--muted)}.companion-pair{display:flex;gap:22px;margin-top:20px;padding:16px;background:var(--paper);border:1px solid var(--line);align-items:center}.companion-pair img{background:white;flex-shrink:0}.companion-pair>div{min-width:0}.companion-pair p{font-size:12px;color:var(--muted)}.companion-pair-url{overflow-wrap:anywhere;font-family:Consolas,monospace}.companion-device{display:flex;gap:12px;align-items:center;padding:14px 0;border-bottom:1px solid var(--line)}.companion-device>div{flex:1;min-width:0}.companion-device p{margin:2px 0;color:var(--muted);overflow-wrap:anywhere;font-size:12px}.companion-device small{color:var(--muted);font-size:11px}.companion-device button{flex-shrink:0}.companion-audit summary{cursor:pointer;font-size:12px}.companion-audit p{display:flex;gap:14px;color:var(--muted);font-size:11px}.companion-audit p>span{flex:1}.companion-error{padding:12px;color:#943b2c;background:#fff2ed;border:1px solid #e7b9a9;overflow-wrap:anywhere}@media(max-width:620px){.companion-heading strong{font-size:16px}.companion-pair{flex-direction:column;align-items:flex-start}.companion-pair img{align-self:center}.companion-network form{align-items:stretch}.companion-network label:first-child{flex-basis:100%}.companion-network .button{align-self:flex-end}.companion-grant{gap:12px}.companion-address{align-items:flex-start;flex-direction:column}}
+21
View File
@@ -0,0 +1,21 @@
export interface CompanionPermissions { observe: boolean; approve: boolean; stop: boolean }
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 }[];
}
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 }
export interface MobileTask extends MobileBrief {
task: { id: string; goal: string; status: string; usage: MobileUsage; budget: { maxTokens: number }; verification: { status: string } } | null;
run: { id: string; status: string; steps: number; toolCalls: number; stopReason: string | null; usage: MobileUsage } | null;
progress: { total: number; completed: number; unknown: { id: string; tool: string; state: string; runId: string }[] };
events: { id: string; label: string; phase: string; output: string; taskId?: string; runId?: string; createdAt: string; exitCode?: number }[];
messages: { id: string; role: string; content: string; createdAt: string }[];
approvals: { id: string; taskId: string; runId: string; projectId: string; command: string; reason: string; shell: string; fingerprint: string; actionable: boolean }[];
changes: { id: string; path: string; reason: string; status: string; sha256: string; baseSha256: string; additions: number; deletions: number }[];
checks: { id: string; status: string; summary: string; requiresVerification?: boolean; results: { name: string; status: string; exitCode?: number; tests?: { total: number; passed: number; failed: number; skipped: number; cancelled: number } }[] }[];
reports: { id: string; kind: string; sha256: string; bytes: number }[];
}
+131
View File
@@ -0,0 +1,131 @@
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 { mobileApi, MobileError, verifiedText, verifyDigest } from './api';
const stateLabel = (state: string) => ({ idle: '未开始', waiting: '等待审批', validating: '校验中', queued: '排队中', executing: '执行中', error: '错误', running: '执行中', awaiting_approval: '等待审批', stopping: '正在停止', completed: '已完成', needs_review: '待审查', failed: '失败', interrupted: '已中断', cancelled: '已停止', paused: '已暂停', unknown: '需核对', completed_with_changes: '待审查', passed: '通过', pending: '待处理', applied: '已应用', denied: '已拒绝', approved: '已批准', conflict: '有冲突', unverified: '需核对', stale: '已变化' } as Record<string, string>)[state] ?? state;
const time = (value: string) => new Date(value).toLocaleString('zh-CN', { month: 'numeric', day: 'numeric', hour: '2-digit', minute: '2-digit' });
type Me = { device: CompanionDevice; gatewayId: string; operations: { requestId: string; action: string; status: string; taskId: string; runId: string; createdAt: string }[] };
type Decision = { requestId: string; kind: 'approve' | 'stop'; task: MobileTask; approval?: MobileTask['approvals'][number]; allow?: boolean };
export function MobileApp({ initialToken }: { initialToken: string }) {
const [me, setMe] = useState<Me | null>(null), [pairToken, setPairToken] = useState(initialToken), [name, setName] = useState('iPhone');
const [projects, setProjects] = useState<{ id: string; name: string }[]>([]), [sessions, setSessions] = useState<MobileBrief[]>([]), [project, setProject] = useState('');
const [selected, setSelected] = useState(''), [task, setTask] = useState<MobileTask | null>(null), [tab, setTab] = useState('progress');
const [busy, setBusy] = useState(''), [error, setError] = useState(''), [fresh, setFresh] = useState(false), [lastSync, setLastSync] = useState('');
const [connectionRequired, setConnectionRequired] = useState(!!initialToken), [decision, setDecision] = useState<Decision | null>(null);
const [document, setDocument] = useState<{ title: string; text: string; sha256: string; redacted?: boolean } | null>(null), [receipt, setReceipt] = useState('');
const cursor = useRef(0), identity = useRef<Me | null>(null), chosen = useRef(''), running = useRef(false), actionBusy = useRef(false), alive = useRef(true), generation = useRef(0), dialog = useRef<HTMLDialogElement>(null), documentDialog = useRef<HTMLDialogElement>(null);
const revoke = useCallback((message: string) => {
generation.current++; identity.current = null; cursor.current = 0; chosen.current = '';
setMe(null); setProjects([]); setSessions([]); setTask(null); setSelected(''); setDocument(null); setDecision(null); setFresh(false); setConnectionRequired(true); setError(message);
}, []);
const refresh = useCallback(async () => {
if (running.current || !alive.current || globalThis.document.visibilityState === 'hidden') return;
running.current = true; const epoch = generation.current;
try {
const current = await mobileApi<Me>('/me');
if (!alive.current || epoch !== generation.current) return;
const key = 'workbench-mobile-cursor:' + current.gatewayId + ':' + current.device.id;
if (!identity.current || identity.current.device.id !== current.device.id || identity.current.gatewayId !== current.gatewayId) {
let saved = ''; try { saved = sessionStorage.getItem(key) ?? ''; } catch {}
cursor.current = /^\d+$/.test(saved) && Number.isSafeInteger(Number(saved)) ? Number(saved) : 0;
}
// Drain bounded original event pages. They invalidate displayed snapshots;
// reconnecting only reads data and never submits an execution request.
for (let page = 0; page < 10; page++) {
const history = await mobileApi<{ events: { seq: number }[]; nextCursor: number; hasMore: boolean }>('/events?after=' + cursor.current + '&limit=200');
if (!Number.isSafeInteger(history.nextCursor) || history.nextCursor < cursor.current || history.events.some((event, index) => event.seq <= (index ? history.events[index - 1].seq : cursor.current))) throw new MobileError('原进展顺序无法核对,请在电脑查看。');
cursor.current = history.nextCursor; try { sessionStorage.setItem(key, String(cursor.current)); } catch {}
if (!history.hasMore) break;
}
const [nextProjects, nextSessions, nextTask] = await Promise.all([mobileApi<{ id: string; name: string }[]>('/projects'), mobileApi<MobileBrief[]>('/sessions'),
chosen.current ? mobileApi<MobileTask>('/sessions/' + chosen.current) : Promise.resolve(null)]);
if (!alive.current || epoch !== generation.current) return;
identity.current = current; setMe(current); setProjects(nextProjects); setSessions(nextSessions);
if (nextTask && nextTask.id === chosen.current) setTask(previous => previous && previous.id === nextTask.id && previous.revision > nextTask.revision ? previous : nextTask);
setFresh(true); setConnectionRequired(false); setError(''); setLastSync(new Date().toISOString());
} catch (value) {
if (!alive.current || epoch !== generation.current) return;
if (value instanceof MobileError && [401, 403].includes(value.status)) revoke(value.message);
else { setFresh(false); setError(value instanceof Error ? value.message : '手机连接未完成。'); }
} finally { running.current = false; }
}, [revoke]);
useEffect(() => {
alive.current = true; if (!initialToken) void refresh();
const timer = setInterval(() => { if (identity.current) void refresh(); }, 2500);
const resume = () => { if (identity.current || !initialToken) void refresh(); };
const offline = () => setFresh(false);
globalThis.document.addEventListener('visibilitychange', resume); window.addEventListener('online', resume); window.addEventListener('offline', offline);
return () => { alive.current = false; clearInterval(timer); globalThis.document.removeEventListener('visibilitychange', resume); window.removeEventListener('online', resume); window.removeEventListener('offline', offline); };
}, [initialToken, refresh]);
useEffect(() => { if (decision && dialog.current && !dialog.current.open) dialog.current.showModal(); }, [decision]);
useEffect(() => { if (document && documentDialog.current && !documentDialog.current.open) documentDialog.current.showModal(); }, [document]);
async function act(action: string, run: () => Promise<unknown>) {
if (actionBusy.current) return; actionBusy.current = true; setBusy(action); setError('');
try { await run(); } catch (value) {
if (value instanceof MobileError && [401, 403].includes(value.status)) revoke(value.message);
else { if (value instanceof MobileError && (value.status === 0 || value.status >= 500)) setFresh(false); setError(value instanceof Error ? value.message : '手机操作未完成。'); }
} finally { actionBusy.current = false; if (alive.current) setBusy(''); }
}
async function pair(event: React.FormEvent) {
event.preventDefault(); await act('pair', async () => {
let token = pairToken.trim();
if (token.startsWith('https://')) { const url = new URL(token); if (url.origin !== location.origin) throw new MobileError('配对链接不属于当前电脑地址,请重新扫码。'); token = new URLSearchParams(url.hash.slice(1)).get('pair') ?? ''; }
await mobileApi('/pair', { token, name }); setPairToken(''); setConnectionRequired(false); await refresh();
});
}
async function openTask(id: string) {
chosen.current = id; setSelected(id); setTask(null); setTab('progress'); setDocument(null); setReceipt('');
await act('task', async () => { const next = await mobileApi<MobileTask>('/sessions/' + id); if (chosen.current === id) setTask(next); });
}
async function submitDecision() {
if (!decision) return;
const value = decision, original = value.task;
await act('operation', async () => {
const result = await mobileApi<{ status: string; requestId: string }>('/sessions/' + original.id + '/' + value.kind, { requestId: value.requestId, taskId: original.taskId, runId: original.runId, revision: original.revision,
...(value.kind === 'approve' ? { approvalId: value.approval!.id, fingerprint: value.approval!.fingerprint, allow: value.allow } : {}) });
setDecision(null); setReceipt(result.status === 'completed' ? (value.kind === 'stop' ? '原任务停止操作已返回。' : value.allow ? '已批准原请求。' : '已拒绝原请求。') : '原操作结果需在电脑核对;不会自动重放。'); await refresh();
});
}
async function openDiff(change: MobileTask['changes'][number]) {
if (!task) return; const owner = task.id;
await act('document', async () => {
let text = '', after = 0, hash = '', more = true;
while (more) {
const page = await mobileApi<{ id: string; text: string; sha256: string; nextOffset: number; offset: number; hasMore: boolean }>('/sessions/' + owner + '/changes/' + change.id + '?offset=' + after);
if (page.offset !== after || page.nextOffset !== after + page.text.length || hash && page.sha256 !== hash || page.hasMore && !page.text.length) throw new MobileError('文件差异已变化,请刷新任务后重试。');
hash = page.sha256; text += page.text; after = page.nextOffset; more = page.hasMore;
if (text.length > 2 * 1024 * 1024) throw new MobileError('文件差异超过手机显示范围,请在电脑查看。');
}
await verifyDigest(text, hash); if (chosen.current === owner) setDocument({ title: change.path, text, sha256: hash });
});
}
const projectName = (id: string) => projects.find(value => value.id === id)?.name ?? '原项目';
const selectedTask = task?.id === selected ? task : null;
return <div className="mobile-app">
<header className="mobile-header"><span className="mobile-mark"><Terminal size={20} /></span><div><strong>Agent Workbench</strong><span>手机伴随端 · Windows 执行宿主</span></div><button aria-label="刷新任务" disabled={!!busy} onClick={() => void refresh()}><RefreshCw size={19} /></button></header>
{me && <div className={'mobile-connection ' + (fresh ? '' : 'disconnected')}>{fresh ? <Wifi size={14} /> : <WifiOff size={14} />}<span>{fresh ? '已同步 · ' + time(lastSync) : '连接中断 · 当前内容可能已过期'}</span><span>{me.device.permissions.approve ? '可审批' : '观察'}</span></div>}
{error && <div className="mobile-error" role="alert"><strong>{fresh ? '操作未完成' : connectionRequired ? '需要连接' : '连接待恢复'}</strong><p>{error}</p>{me && <button onClick={() => void refresh()} disabled={!!busy}>重新同步</button>}</div>}
{me?.operations?.some(value => value.status === 'unknown') && <div className="mobile-unknown"><strong>手机操作回执需要核对</strong><p>有原审批或停止操作没有完整回执,请在电脑核对;手机不会自动重放。</p>{me.operations.filter(value => value.status === 'unknown').map(value => <code key={value.requestId}>Task {value.taskId} · {value.action === 'stop' ? '停止' : '审批'}</code>)}</div>}
{!me && <main className="mobile-pair-page"><div className="mobile-pair-heading"><Link2 size={32} /><h1>接续电脑上的任务</h1><p>在 Windows 工作台打开「手机连接」,选择项目并生成一次性配对码。</p></div>{connectionRequired || pairToken ? <form onSubmit={event => void pair(event)}><label>设备名称<input value={name} maxLength={60} onChange={event => setName(event.target.value)} autoComplete="off" /></label><label>配对码或配对链接<input type="password" value={pairToken} onChange={event => setPairToken(event.target.value)} autoComplete="off" autoCapitalize="none" spellCheck={false} placeholder="扫描电脑上的二维码后自动填写" /></label><button className="mobile-primary" disabled={!!busy || !pairToken.trim() || !name.trim()}>{busy === 'pair' ? '正在核对授权…' : '连接这台电脑'}</button></form> : <p role="status">正在核对当前手机连接…</p>}<div className="mobile-pair-help"><ShieldCheck size={18} /><p>首次使用需要在 iPhone 安装并信任电脑生成的根证书。请按电脑「手机连接」中的指引操作。</p></div></main>}
{me && !selected && <main className="mobile-task-list"><div className="mobile-page-title"><div><span className="mobile-eyebrow">{me.device.name}</span><h1>项目任务</h1></div><span>{sessions.length} 个会话</span></div><label className="mobile-project-filter"><Folder size={17} /><select aria-label="筛选项目" value={project} onChange={event => setProject(event.target.value)}><option value="">全部授权项目</option>{projects.map(item => <option key={item.id} value={item.id}>{item.name}</option>)}</select></label>
{!sessions.length && <div className="mobile-empty"><ClipboardCheck size={30} /><h2>暂无任务</h2><p>在电脑创建或打开任务,手机会同步该项目的执行进展。</p></div>}
{sessions.filter(item => !project || item.projectId === project).map(item => <button className="mobile-task-row" key={item.id} onClick={() => void openTask(item.id)}><div><span className="mobile-project-name">{projectName(item.projectId)}</span><strong>{item.title}</strong><span className="mobile-row-meta"><span className={'mobile-state state-' + item.status}>{stateLabel(item.status)}</span><time>{time(item.updatedAt)}</time></span></div><ChevronRight size={19} /></button>)}
<details className="mobile-device-settings"><summary>设备连接与授权</summary><p>{projects.map(item => item.name).join('、')}</p><p>观察{me.device.permissions.approve ? ' · 审批' : ''}{me.device.permissions.stop ? ' · 停止' : ''} · {time(me.device.expiresAt)} 到期</p><p>手机显示最近200个未归档会话,完整历史在电脑保留。</p><p>iPhone Safari 中点「共享 → 添加到主屏幕」可安装伴随端。主屏幕应用如要求连接,请在电脑生成新的配对码。</p><div><button disabled={!!busy || !fresh} onClick={() => void act('rotate', async () => { await mobileApi('/rotate', {}); await refresh(); setReceipt('手机会话已轮换。'); })}>轮换手机会话</button><button disabled={!!busy} onClick={() => void act('logout', async () => { await mobileApi('/logout', {}); revoke('已断开并撤销这台手机。'); })}>断开并撤销</button></div></details></main>}
{me && selected && <main className="mobile-task-detail"><button className="mobile-back" onClick={() => { chosen.current = ''; setSelected(''); setTask(null); setDocument(null); }}><ArrowLeft size={18} />项目任务</button>{!selectedTask ? <div className="mobile-empty" role="status">正在读取原任务…</div> : <>
<div className="mobile-task-title"><span className="mobile-eyebrow">{projectName(selectedTask.projectId)}</span><h1>{selectedTask.title}</h1><div><span className={'mobile-state state-' + selectedTask.status}>{stateLabel(selectedTask.status)}</span><span>修订 {selectedTask.revision}</span></div><details className="mobile-goal"><summary>完整任务目标</summary><p>{selectedTask.task?.goal ?? '此会话尚未创建执行任务。'}</p></details><details><summary>原任务与运行</summary><code>Task {selectedTask.taskId ?? '未开始'}<br />Run {selectedTask.runId ?? '未开始'}</code></details></div>
{receipt && <p className="mobile-receipt" role="status">{receipt}</p>}
{!!selectedTask.progress.unknown.length && <div className="mobile-unknown"><strong>{selectedTask.progress.unknown.length} 项工具结果需要核对</strong><p>请在电脑核对原输入和实际结果。刷新、重连和手机审批均不会自动重新执行。</p>{selectedTask.progress.unknown.map(item => <code key={item.id}>{item.tool} · {stateLabel(item.state)}</code>)}</div>}
{!!selectedTask.approvals.length && <section className="mobile-approvals"><h2><ShieldCheck size={18} />等待你的确认</h2>{selectedTask.approvals.map(approval => <article key={approval.id}><span>{approval.shell}</span><pre>{approval.command}</pre><p>{approval.reason}</p>{!me.device.permissions.approve ? <p className="mobile-muted">此设备仅可观察,请在电脑审批。</p> : !approval.actionable ? <p className="mobile-muted">原审批已失效,请在电脑核对。</p> : <div className="mobile-action-pair"><button disabled={!fresh || !!busy} onClick={() => setDecision({ requestId: crypto.randomUUID(), kind: 'approve', task: selectedTask, approval, allow: false })}>拒绝</button><button className="mobile-primary" disabled={!fresh || !!busy} onClick={() => setDecision({ requestId: crypto.randomUUID(), kind: 'approve', task: selectedTask, approval, allow: true })}>核对并批准</button></div>}</article>)}</section>}
<nav className="mobile-tabs" aria-label="任务内容">{[['progress', '执行进展'], ['changes', '文件差异'], ['checks', '检查与报告']].map(([key, label]) => <button key={key} aria-current={tab === key ? 'page' : undefined} onClick={() => { setTab(key); setDocument(null); }}>{label}{key === 'changes' && !!selectedTask.changes.length && <span>{selectedTask.changes.length}</span>}</button>)}</nav>
{tab === 'progress' && <section className="mobile-progress"><div className="mobile-section-heading"><h2>原执行记录</h2><span>{selectedTask.progress.completed} / {selectedTask.progress.total} 工具完成</span></div><ol>{selectedTask.events.map(item => <li key={item.id}><div><strong>{item.label || '执行事件'}</strong><span className={'mobile-state state-' + item.phase}>{stateLabel(item.phase)}</span></div>{item.output && <details><summary>查看原输出片段{item.exitCode !== undefined ? ' · 退出码 ' + item.exitCode : ''}</summary><pre>{item.output}</pre></details>}</li>)}</ol>{!selectedTask.events.length && <p className="mobile-muted">尚无工具执行记录。</p>}{selectedTask.messages.map(message => <article className="mobile-message" key={message.id}><span>{message.role === 'assistant' ? '代理回复' : '系统记录'} · {time(message.createdAt)}</span><p>{message.content}</p></article>)}<p className="mobile-muted">手机显示最近60条执行记录和8条回复;完整记录保留在电脑原会话。</p></section>}
{tab === 'changes' && <section className="mobile-changes"><div className="mobile-section-heading"><h2>当前任务的改动</h2><span>{selectedTask.changes.length} 个文件</span></div>{!selectedTask.changes.length && <p className="mobile-muted">尚未提出文件改动。</p>}{selectedTask.changes.map(change => <button key={change.id} className="mobile-file-row" disabled={!!busy || !fresh} onClick={() => void openDiff(change)}><FileDiff size={19} /><div><strong>{change.path}</strong><span>{stateLabel(change.status)} · <b>+{change.additions}</b> / −{change.deletions}</span></div><ChevronRight size={17} /></button>)}<p className="mobile-muted">手机可查看原差异;应用、恢复和 Git 提交在电脑审查。</p></section>}
{tab === 'checks' && <section className="mobile-checks"><h2>工程检查</h2>{!selectedTask.checks.length && <p className="mobile-muted">尚无工程检查结果。</p>}{selectedTask.checks.map(check => <article key={check.id}><div className="mobile-section-heading"><strong>检查 {check.id.slice(0, 8)}</strong><span className={'mobile-state state-' + check.status}>{stateLabel(check.status)}</span></div><p>{check.summary}</p>{check.results.map((result, index) => <p className="mobile-check-result" key={index}><span>{result.name}</span><span>{stateLabel(result.status)}{result.exitCode !== undefined ? ' · ' + result.exitCode : ''}{result.tests ? ' · ' + result.tests.passed + '/' + result.tests.total + ' 项测试' : ''}</span></p>)}</article>)}<h2>原交付报告</h2>{!selectedTask.reports.length && <p className="mobile-muted">尚未生成交付报告。</p>}{selectedTask.reports.map(report => <button className="mobile-file-row" key={report.id} disabled={!!busy || !fresh} onClick={() => void act('document', async () => { const value = await verifiedText('/sessions/' + selectedTask.id + '/reports/' + report.id); if (chosen.current === selectedTask.id) setDocument({ title: report.kind === 'delivery-report-markdown' ? '交付报告' : '交付报告 JSON', ...value }); })}><ClipboardCheck size={18} /><div><strong>{report.kind === 'delivery-report-markdown' ? '交付报告' : '交付报告 JSON'}</strong><span>{report.bytes.toLocaleString()} bytes · 校验后显示</span></div><ChevronRight size={17} /></button>)}</section>}
{selectedTask.task && <div className="mobile-budget"><span>任务累计用量</span><strong>{selectedTask.task.usage.totalTokens.toLocaleString()} tokens / {selectedTask.task.budget.maxTokens.toLocaleString()}</strong>{!!selectedTask.task.usage.unknownRequests && <p>{selectedTask.task.usage.unknownRequests} 次用量未知,另按 {selectedTask.task.usage.estimatedUnknownTokens.toLocaleString()} tokens 估算;不计为已确认用量。</p>}</div>}
{['running', 'awaiting_approval', 'stopping'].includes(selectedTask.status) && <div className="mobile-stop"><span>{me.device.permissions.stop ? '停止仍由电脑等待所属工具退出' : '此设备没有停止权限'}</span><button disabled={!me.device.permissions.stop || !fresh || !!busy || selectedTask.status === 'stopping'} onClick={() => setDecision({ requestId: crypto.randomUUID(), kind: 'stop', task: selectedTask })}><Square size={14} />停止原任务</button></div>}
</>}</main>}
{document && <dialog ref={documentDialog} className="mobile-document" aria-label={document.title} onCancel={() => setDocument(null)}><header><button aria-label="关闭文档" onClick={() => setDocument(null)}><ArrowLeft size={20} /></button><strong>{document.title}</strong></header><p><ShieldCheck size={14} />SHA-256 已核对{document.redacted ? ' · 已脱敏' : ''}</p><code>{document.sha256}</code><pre>{document.text}</pre><button onClick={() => setDocument(null)}>返回任务</button></dialog>}
{decision && <dialog ref={dialog} className="mobile-confirm" onCancel={() => setDecision(null)}><button className="mobile-confirm-close" aria-label="关闭确认" onClick={() => setDecision(null)} disabled={!!busy}><X size={20} /></button><h2>{decision.kind === 'stop' ? '停止这个原任务' : decision.allow ? '批准原命令请求' : '拒绝原命令请求'}</h2><p>{projectName(decision.task.projectId)} · {decision.task.title}</p>{decision.approval && <pre>{decision.approval.command}</pre>}<code>Task {decision.task.taskId}<br />Run {decision.task.runId}<br />修订 {decision.task.revision}</code>{decision.task.revision !== task?.revision && <p role="alert">任务修订已变化,请关闭并重新核对。</p>}<p>{decision.kind === 'stop' ? '电脑将停止此运行,并保留已经完成的工具结果。' : decision.allow ? '批准后,电脑将在原项目中执行这条已登记命令。' : '拒绝后,这条原命令不会执行。'}</p><div className="mobile-action-pair"><button disabled={!!busy} onClick={() => setDecision(null)}>返回核对</button><button className={decision.kind === 'stop' ? 'mobile-danger' : 'mobile-primary'} disabled={!!busy || !fresh || decision.task.revision !== task?.revision} onClick={() => void submitDecision()}>{busy === 'operation' ? '等待原回执…' : '确认'}</button></div></dialog>}
</div>;
}
+24
View File
@@ -0,0 +1,24 @@
export class MobileError extends Error { constructor(message: string, public status = 0) { super(message); } }
export async function mobileApi<T>(route: string, value?: unknown): Promise<T> {
const controller = new AbortController(), timer = setTimeout(() => controller.abort(), route.endsWith('/stop') ? 75000 : 15000);
try {
const response = await fetch('/mobile-api' + route, { method: value === undefined ? 'GET' : 'POST', credentials: 'same-origin', cache: 'no-store', signal: controller.signal,
headers: value === undefined ? {} : { 'Content-Type': 'application/json' }, ...(value === undefined ? {} : { body: JSON.stringify(value) }) });
const body = await response.json();
if (!response.ok) throw new MobileError(body.error || '当前手机请求未完成。', response.status);
return body as T;
} catch (error) {
if (error instanceof MobileError) throw error;
throw new MobileError(value === undefined ? '连接已断开。请核对 Wi-Fi 与电脑上的手机连接。' : '没有收到完整回执,请先刷新并在电脑核对原操作。');
} finally { clearTimeout(timer); }
}
export async function verifiedText(route: string, maximum = 8 * 1024 * 1024) {
const value = await mobileApi<{ text: string; sha256: string; sourceSha256?: string; redacted?: boolean }>(route);
if (typeof value.text !== 'string' || value.text.length > maximum) throw new MobileError('报告超出手机显示范围,请在电脑查看。');
await verifyDigest(value.text, value.sha256); return value;
}
export async function verifyDigest(text: string, expected: string) {
if (!/^[a-f0-9]{64}$/.test(expected)) throw new MobileError('原结果缺少可核对的SHA-256。');
const hash = Array.from(new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(text)))).map(value => value.toString(16).padStart(2, '0')).join('');
if (hash !== expected) throw new MobileError('结果内容校验失败,请在电脑核对原工件。');
}
+10
View File
@@ -0,0 +1,10 @@
import { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
import { MobileApp } from './MobileApp';
import './mobile.css';
const fragment = new URLSearchParams(location.hash.slice(1));
const token = fragment.get('pair') ?? '';
if (fragment.has('pair')) history.replaceState(null, '', location.pathname);
createRoot(document.getElementById('mobile-root')!).render(<StrictMode><MobileApp initialToken={token} /></StrictMode>);
if ('serviceWorker' in navigator && isSecureContext) navigator.serviceWorker.register('/mobile-sw.js', { scope: '/' }).catch(() => {});
File diff suppressed because one or more lines are too long
+17 -3
View File
@@ -2,10 +2,13 @@ import fs from 'node:fs';
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';
const key = 'mobileCompanion';
const instant = value => new Date(value).toISOString();
const secret = () => randomBytes(32).toString('base64url');
const dictionary = value => value !== null && typeof value === 'object' && !Array.isArray(value);
const date = value => typeof value === 'string' && Number.isFinite(Date.parse(value));
export class DeviceRegistry {
constructor(store, identity, { clock = Date.now } = {}) {
this.store = store; this.identity = identity; this.clock = clock; this.pairings = new Map();
@@ -22,9 +25,20 @@ export class DeviceRegistry {
}
read() {
const state = this.store.storage.meta(key);
if (state && (state.schema !== COMPANION_SCHEMA || state.binding !== this.binding || !Number.isSafeInteger(state.revision)
|| !state.devices || Array.isArray(state.devices) || Object.keys(state.devices).length > 128 || !Array.isArray(state.audit)
|| !state.operations || Array.isArray(state.operations))) throw companionError('原手机登记无法核对;请保留数据并检查原Windows用户和目录。', 409);
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
|| 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)
|| device.revokedAt !== null && !date(device.revokedAt) || device.credentialHash !== null && !/^[a-f0-9]{64}$/.test(device.credentialHash)
|| !Array.isArray(device.projectIds) || !device.projectIds.length || device.projectIds.length > 16 || device.projectIds.some(id => !isId(id)) || new Set(device.projectIds).size !== device.projectIds.length
|| !dictionary(device.permissions) || Object.keys(device.permissions).length !== 3 || device.permissions.observe !== true || typeof device.permissions.approve !== 'boolean' || typeof device.permissions.stop !== 'boolean')
|| Object.entries(state.operations).some(([id, value]) => !dictionary(value) || id !== value.deviceId + ':' + value.requestId
|| !isId(value.deviceId) || !isId(value.requestId) || !isId(value.projectId) || !isId(value.sessionId) || !isId(value.taskId) || !isId(value.runId)
|| !['approve', 'stop'].includes(value.action) || !['pending', 'completed', 'unknown'].includes(value.status) || !/^[a-f0-9]{64}$/.test(value.hash)))) {
throw companionError('原手机登记无法核对;请保留数据并检查原Windows用户和目录。', 409);
}
return state ?? { schema: COMPANION_SCHEMA, binding: this.binding, gatewayId: randomUUID(), revision: 0, devices: {}, audit: [], operations: {} };
}
mutate(action) {
+1 -1
View File
@@ -21,7 +21,7 @@ export function mobileSession(store, runtime, session, redact = String) {
fingerprint: approvalBinding(session, value), actionable: runtime.waiters.get(value.id)?.runId === session.runId })),
changes: session.changes.filter(value => value.taskId === session.taskId).slice(-100).map(value => pick(value, ['id', 'path', 'reason', 'status', 'sha256', 'baseSha256', 'additions', 'deletions'])),
checks: checks.slice(-12).map(value => ({ ...pick(value, ['id', 'status', 'summary', 'requiresVerification', 'createdAt', 'finishedAt']),
results: (value.results ?? []).map(item => pick(item, ['name', 'status', 'exitCode', 'counts', 'durationMs'])) })),
results: (value.results ?? []).map(item => pick(item, ['name', 'status', 'exitCode', 'tests', 'durationMs'])) })),
reports: [...store.core.artifact.values()].filter(value => value.sessionId === session.id && value.taskId === session.taskId && reportKinds.has(value.kind))
.slice(-10).map(value => pick(value, ['id', 'kind', 'sha256', 'bytes', 'createdAt', 'taskId', 'runId'])),
};
+10 -2
View File
@@ -31,7 +31,10 @@ const cookieName = '__Host-Workbench-Device';
const privateV4 = value => /^10\./.test(value) || /^192\.168\./.test(value) || /^172\.(1[6-9]|2\d|3[01])\./.test(value);
export function companionAddresses() {
return Object.entries(os.networkInterfaces()).flatMap(([name, entries]) => (entries ?? []).filter(entry => entry.family === 'IPv4' && !entry.internal && privateV4(entry.address))
.map(entry => ({ name, address: entry.address })));
.map(entry => ({ name, address: entry.address }))).sort((left, right) => {
const virtual = value => /vethernet|hyper-v|wsl|virtual|vmware|vbox|docker|vpn|\btun\b|\btap\b|虚拟/i.test(value.name) ? 1 : 0;
return virtual(left) - virtual(right) || left.name.localeCompare(right.name);
});
}
function reply(response, data, status = 200) {
response.writeHead(status, { 'Content-Type': 'application/json; charset=utf-8' }); response.end(JSON.stringify(data));
@@ -197,7 +200,12 @@ export class CompanionGateway {
const device = this.registry.authenticate(cookie(request)); this.limit('device:' + device.id, 240);
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') return reply(response, { device: { id: device.id, name: device.name, projectIds: device.projectIds, permissions: device.permissions, expiresAt: device.expiresAt, revision: device.revision }, gatewayId: this.registry.read().gatewayId });
if (method === 'GET' && route === '/mobile-api/me') {
const state = this.registry.read();
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 })) });
}
if (method === 'POST' && route === '/mobile-api/rotate') {
fields(await input(request), []); const token = this.registry.rotate(device); setCookie(response, token, device.expiresAt); return reply(response, { rotated: true });
}