154 lines
27 KiB
TypeScript
154 lines
27 KiB
TypeScript
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, 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 { MnemoPlanReceipt } from '../MnemoPlanReceipt';
|
||
import './file-results.css';
|
||
import { BRAND, OrvenMark } from '../brand';
|
||
import { AppearancePanel } from '../AppearancePanel';
|
||
import { Modal } from '../components';
|
||
import { Palette as PaletteIcon } from 'lucide-react';
|
||
|
||
const stateLabel = (state: string) => ({ idle: '未开始', waiting: '等待审批', validating: '校验中', queued: '排队中', executing: '执行中', error: '错误', running: '执行中', awaiting_approval: '等待审批', stopping: '正在停止', completed: '已完成', needs_review: '待审查', failed: '失败', interrupted: '已中断', cancelled: '已停止', paused: '已暂停', unknown: '需核对', completed_with_changes: '待审查', passed: '通过', pending: '待处理', applied: '已应用', denied: '已拒绝', approved: '已批准', conflict: '有冲突', unverified: '需核对', stale: '已变化' } as Record<string, string>)[state] ?? state;
|
||
const time = (value: string) => new Date(value).toLocaleString('zh-CN', { month: 'numeric', day: 'numeric', hour: '2-digit', minute: '2-digit' });
|
||
type Me = { device: CompanionDevice; gatewayId: string; operations: MobileOperation[]; operationsPage: RecordPage<MobileOperation>; unresolvedOperations: MobileOperation[] };
|
||
type Decision = { requestId: string; kind: 'approve' | 'stop'; task: MobileTask; approval?: MobileTask['approvals'][number]; allow?: boolean };
|
||
|
||
export function MobileApp({ initialToken }: { initialToken: string }) {
|
||
const [appearanceOpen, setAppearanceOpen] = useState(false);
|
||
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 operations = useRecordPages<MobileOperation>(me ? '/operations' : null, value => setError(value instanceof Error ? value.message : String(value)), mobileApi, me ? me.gatewayId + '/' + me.device.id + '/' + me.device.revision : null);
|
||
useEffect(() => { if (me) void operations.refresh(); }, [me]);
|
||
const cursor = useRef(0), identity = useRef<Me | null>(null), chosen = useRef(''), running = useRef(false), actionBusy = useRef(false), alive = useRef(true), generation = useRef(0), dialog = useRef<HTMLDialogElement>(null), documentDialog = useRef<HTMLDialogElement>(null);
|
||
const revoke = useCallback((message: string) => {
|
||
generation.current++; identity.current = null; cursor.current = 0; chosen.current = '';
|
||
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"><OrvenMark size={24} /></span><div><strong>{BRAND.name}</strong><span>手机伴随端 · 接续你的工作</span></div><button type="button" aria-label="外观" onClick={() => setAppearanceOpen(true)}><PaletteIcon size={19} /></button><button aria-label="刷新任务" disabled={!!busy} onClick={() => void refresh()}><RefreshCw size={19} /></button></header>
|
||
{appearanceOpen && <Modal title="外观" description="选择适合你的工作台配色,切换后立即生效。" onClose={() => setAppearanceOpen(false)}><AppearancePanel /></Modal>}
|
||
{me && <div className={'mobile-connection ' + (fresh ? '' : 'disconnected')}>{fresh ? <Wifi size={14} /> : <WifiOff size={14} />}<span>{fresh ? '已同步 · ' + time(lastSync) : '连接中断 · 当前内容可能已过期'}</span><span>{me.device.permissions.approve ? '可审批' : '观察'}</span></div>}
|
||
{error && <div className="mobile-error" role="alert"><strong>{fresh ? '操作未完成' : connectionRequired ? '需要连接' : '连接待恢复'}</strong><p>{error}</p>{me && <button onClick={() => void refresh()} disabled={!!busy}>重新同步</button>}</div>}
|
||
{!!me?.unresolvedOperations?.length && <div className="mobile-unknown"><strong>手机操作回执需要核对</strong><p>有原审批或停止操作没有完整回执,请在电脑核对;手机不会自动重放。</p>{me.unresolvedOperations.map(value => <code key={value.requestId}>Task {value.taskId} · {value.action === 'stop' ? '停止' : '审批'}</code>)}</div>}
|
||
{me && <details className="mobile-operation-history"><summary>手机操作记录 · 已加载 {operations.items.length} / {operations.total} 项</summary>{operations.items.map(value => <p key={value.id}>{value.action === 'stop' ? '停止' : '审批'} · {value.taskId.slice(0, 8)} · {stateLabel(value.status)} · {time(value.createdAt)}</p>)}
|
||
{operations.hasMore && <button type="button" disabled={operations.loading} onClick={() => void operations.loadMore()}>加载更早的手机操作</button>}</details>}
|
||
{!me && <main className="mobile-pair-page"><div className="mobile-pair-heading"><Link2 size={32} /><h1>接续电脑上的任务</h1><p>在 Windows 工作台打开「手机连接」,选择项目并生成一次性配对码。</p></div>{connectionRequired || pairToken ? <form onSubmit={event => void pair(event)}><label>设备名称<input value={name} maxLength={60} onChange={event => setName(event.target.value)} autoComplete="off" /></label><label>配对码或配对链接<input type="password" value={pairToken} onChange={event => setPairToken(event.target.value)} autoComplete="off" autoCapitalize="none" spellCheck={false} placeholder="扫描电脑上的二维码后自动填写" /></label><button className="mobile-primary" disabled={!!busy || !pairToken.trim() || !name.trim()}>{busy === 'pair' ? '正在核对授权…' : '连接这台电脑'}</button></form> : <p role="status">正在核对当前手机连接…</p>}<div className="mobile-pair-help"><ShieldCheck size={18} /><p>首次使用需要在 iPhone 安装并信任电脑生成的根证书。请按电脑「手机连接」中的指引操作。</p></div></main>}
|
||
{me && !selected && <main className="mobile-task-list"><div className="mobile-page-title"><div><span className="mobile-eyebrow">{me.device.name}</span><h1>项目任务</h1></div><span>{sessions.length} 个会话</span></div><label className="mobile-project-filter"><Folder size={17} /><select aria-label="筛选项目" value={project} onChange={event => setProject(event.target.value)}><option value="">全部授权项目</option>{projects.map(item => <option key={item.id} value={item.id}>{item.name}</option>)}</select></label>
|
||
{!sessions.length && <div className="mobile-empty"><ClipboardCheck size={30} /><h2>暂无任务</h2><p>在电脑创建或打开任务,手机会同步该项目的执行进展。</p></div>}
|
||
{sessions.filter(item => !project || item.projectId === project).map(item => <button className="mobile-task-row" key={item.id} onClick={() => void openTask(item.id)}><div><span className="mobile-project-name">{projectName(item.projectId)}</span><strong>{item.title}</strong><span className="mobile-row-meta"><span className={'mobile-state state-' + item.status}>{stateLabel(item.status)}</span><time>{time(item.updatedAt)}</time></span></div><ChevronRight size={19} /></button>)}
|
||
<details className="mobile-device-settings"><summary>设备连接与授权</summary><p>{projects.map(item => item.name).join('、')}</p><p>观察{me.device.permissions.approve ? ' · 审批' : ''}{me.device.permissions.stop ? ' · 停止' : ''} · {time(me.device.expiresAt)} 到期</p><p>显示已授权项目的未归档会话;操作记录可加载更早记录。</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.inputAttachments?.map(image=><MobileInputImage key={image.id} sessionId={selectedTask.id} image={image} onError={cause=>{if(cause instanceof MobileError&&[401,403].includes(cause.status))revoke(cause.message);else setError(cause instanceof Error?cause.message:'截图读取失败。');}}/>)}
|
||
{selectedTask.memoryReceipts?.map(plan => <MnemoPlanReceipt key={plan.id} plan={plan} />)}
|
||
{selectedTask.budgetPause&&<aside className="mobile-unknown"><strong>原任务因预算暂停</strong><p>必需输入 {selectedTask.budgetPause.requiredInputTokens?.toLocaleString()??'旧记录未分解'};可用输入 {selectedTask.budgetPause.inputBudget?.toLocaleString()??'未记录'} tokens。请在电脑核对预算并预览续接,原工具结果保留。</p></aside>}
|
||
{!!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.browserObservations?.slice(-1).map(observation=><MobileBrowserObservation key={observation.id} sessionId={selectedTask.id} observation={observation} onError={cause=>{if(cause instanceof MobileError&&[401,403].includes(cause.status))revoke(cause.message);else setError(cause instanceof Error?cause.message:'原网页截图读取失败。');}}/>)}
|
||
{!!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>}
|
||
{!!selectedTask.fileResults?.length && <section className="mobile-file-results" aria-label="当前文件成果"><h2>当前文件成果</h2>{selectedTask.fileResults.map(result => <article key={result.id}><strong>{result.verification === 'current' ? '当前文件已核对' : '文件或要求已变化,请在电脑重新核对'}</strong><p>Task {result.taskId.slice(0, 8)} · Run {result.runId.slice(0, 8)}</p>{result.files.map(file => <p key={file.path}><strong>{file.path}</strong><br /><code>SHA-256 {file.sha256}</code>{file.origin && <><br />来源 Task {file.origin.taskId.slice(0, 8)} · Run {file.origin.runId.slice(0, 8)}<br /><code>原 SHA-256 {file.origin.sha256}</code></>}</p>)}<p>{result.reason}</p><details><summary>原成果凭据 SHA-256</summary><code>{result.contractSha256}</code></details></article>)}<p className="mobile-muted">已有成果与新增修改分开记录;测试、差异和Git结果见各自原记录。</p></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.stream && item.stream.status !== "completed" && <div className="mobile-stream"><strong>{item.stream.status === "receiving" ? "正在接收模型输出" : "模型输出未完成"}</strong><span>{item.stream.textCharacters ?? 0} 字符 · 片段不执行工具</span>{item.stream.textPreview && <pre>{item.stream.textPreview}</pre>}</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 ? '批准原' : '拒绝原') + approvalPresentation(decision.approval).subject}</h2><p>{projectName(decision.task.projectId)} · {decision.task.title}</p>{decision.approval && <pre>{decision.approval.command}</pre>}<code>Task {decision.task.taskId}<br />Run {decision.task.runId}<br />修订 {decision.task.revision}</code>{decision.task.revision !== task?.revision && <p role="alert">任务修订已变化,请关闭并重新核对。</p>}<p>{decision.kind === 'stop' ? '电脑将停止此运行,并保留已经完成的工具结果。' : decision.allow ? approvalPresentation(decision.approval).scope : approvalPresentation(decision.approval).denied}</p><div className="mobile-action-pair"><button disabled={!!busy} onClick={() => setDecision(null)}>返回核对</button><button className={decision.kind === 'stop' ? 'mobile-danger' : 'mobile-primary'} disabled={!!busy || !fresh || decision.task.revision !== task?.revision} onClick={() => void submitDecision()}>{busy === 'operation' ? '等待原回执…' : '确认'}</button></div></dialog>}
|
||
</div>;
|
||
}
|