fix: remove open execution record caps and preserve recovery history
This commit is contained in:
@@ -2,7 +2,8 @@ import { useEffect, useRef, useState } from 'react';
|
||||
import { Download, Link2, ShieldCheck, Smartphone, X } from 'lucide-react';
|
||||
import { api, downloadCompanionCertificate } from './api';
|
||||
import type { Project } from './types';
|
||||
import type { CompanionStatus } from './companion-types';
|
||||
import type { CompanionStatus, CompanionAudit } from './companion-types';
|
||||
import { useRecordPages } from './useRecordPages';
|
||||
import './companion-panel.css';
|
||||
|
||||
export function CompanionPanel({ projects, selectedProjectId }: { projects: Project[]; selectedProjectId: string }) {
|
||||
@@ -11,7 +12,8 @@ export function CompanionPanel({ projects, selectedProjectId }: { projects: Proj
|
||||
const [approve, setApprove] = useState(false), [stop, setStop] = useState(false), [hours, setHours] = useState(24);
|
||||
const [pair, setPair] = useState<{ url: string; qr: string; expiresAt: string } | null>(null), [busy, setBusy] = useState(''), [error, setError] = useState('');
|
||||
const mounted = useRef(true);
|
||||
async function refresh() { const result = await api<CompanionStatus>('/companion'); if (mounted.current) { setStatus(result); setAddress(previous => previous || result.addresses[0]?.address || ''); } }
|
||||
const audit = useRecordPages<CompanionAudit>('/companion/audit', value => setError(value instanceof Error ? value.message : String(value)));
|
||||
async function refresh() { const result = await api<CompanionStatus>('/companion'); if (mounted.current) { setStatus(result); setAddress(previous => previous || result.addresses[0]?.address || ''); await audit.refresh(); } }
|
||||
useEffect(() => {
|
||||
mounted.current = true; void refresh().catch(value => { if (mounted.current) setError(value.message); });
|
||||
const timer = setInterval(() => void refresh().catch(() => {}), 5000);
|
||||
@@ -40,6 +42,7 @@ export function CompanionPanel({ projects, selectedProjectId }: { projects: Proj
|
||||
{pair && status?.enabled && <div className="companion-pair"><img src={pair.qr} alt="手机一次性配对二维码" width={224} height={224} /><div><strong>使用 iPhone 相机扫描</strong><p>请先完成证书信任。{new Date(pair.expiresAt).toLocaleTimeString()} 失效。</p><p className="companion-pair-url">{pair.url}</p><p>把链接发给自己时,接收者可以取得所选项目权限。完成配对后此链接立即失效。</p></div></div>}
|
||||
</section>
|
||||
<section><h3>已登记设备 <span>{status?.devices.length ?? 0}</span></h3>{!status?.devices.length && <p className="companion-note">配对完成后,设备和授权范围会显示在这里。</p>}{status?.devices.map(device => <div key={device.id} className="companion-device"><Smartphone size={18} /><div><strong>{device.name}</strong><p>{device.projectIds.map(id => projects.find(project => project.id === id)?.name ?? '原项目').join('、')} · {device.permissions.approve ? '可审批' : '观察'}{device.permissions.stop ? ' · 可停止' : ''}</p><small>{({ active: '已授权', revoked: '已撤销', expired: '已到期', reconnect_required: '需重新配对' } as Record<string, string>)[device.status ?? ''] ?? device.status} · {new Date(device.expiresAt).toLocaleString()} 到期</small></div><button className="button secondary" disabled={!!busy || device.status !== 'active'} onClick={() => void act('revoke', async () => { await api('/companion/devices/' + device.id + '/revoke', { revision: device.revision }); setPair(null); })}><X size={13} />撤销</button></div>)}</section>
|
||||
{!!status?.audit.length && <details className="companion-audit"><summary>最近的设备操作</summary>{status.audit.slice(0, 12).map(item => <p key={item.id}><time>{new Date(item.at).toLocaleTimeString()}</time><span>{status.devices.find(device => device.id === item.deviceId)?.name ?? '原设备'} · {({ pair: '配对', rotate: '轮换会话', revoke: '撤销', approve: '审批', stop: '停止' } as Record<string, string>)[item.action] ?? item.action}</span><code>{item.status}</code></p>)}</details>}
|
||||
{status && <details className="companion-audit"><summary>设备操作记录 · 已加载 {audit.items.length} / {audit.total} 项</summary>{audit.items.map(item => <p key={item.id}><time>{new Date(item.at).toLocaleString('zh-CN')}</time><span>{status.devices.find(device => device.id === item.deviceId)?.name ?? '原设备'} · {({ pair: '配对', rotate: '轮换会话', revoke: '撤销', approve: '审批', stop: '停止' } as Record<string, string>)[item.action] ?? item.action}</span><code>{item.status}</code></p>)}
|
||||
{audit.hasMore && <button type="button" className="button secondary" disabled={audit.loading} onClick={() => void audit.loadMore()}>加载更早的设备操作</button>}</details>}
|
||||
</div>;
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ import { AlertTriangle, Check, CircleAlert, Clock3, Download, FileText, LoaderCi
|
||||
import type { McpJob, Session } from './types';
|
||||
import { api } from './api';
|
||||
import { Modal } from './components';
|
||||
import { useRecordPages } from './useRecordPages';
|
||||
import './McpPanel.css';
|
||||
|
||||
const active = ['queued', 'connecting', 'discovering', 'calling', 'closing', 'stopping'];
|
||||
@@ -10,15 +11,24 @@ const labels: Record<string, string> = { queued: '排队', connecting: '正在
|
||||
const timestamp = (value: string | null) => value ? new Date(value).toLocaleString('zh-CN', { month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit' }) : '进行中';
|
||||
type Evidence = { job: McpJob; report: Record<string, unknown> | null; input: { artifactId: string; sha256: string; input: Record<string, unknown> }; evidenceSha256: string; note: string };
|
||||
|
||||
export function McpJobHistory({ session, jobs, busy, onSession, onError }: {
|
||||
session: Session; jobs: McpJob[]; busy: boolean; onSession: (value: Session) => void; onError: (error: unknown) => void;
|
||||
export function PaginatedMcpJobHistory({ session, busy, onSession, onError }: {
|
||||
session: Session; busy: boolean; onSession: (value: Session) => void; onError: (error: unknown) => void;
|
||||
}) {
|
||||
const history = useRecordPages<McpJob>('/sessions/' + session.id + '/mcp/jobs', onError);
|
||||
useEffect(() => { void history.refresh(); }, [session.revision, history.refresh]);
|
||||
return <McpJobHistory session={session} jobs={history.items} total={history.total} hasMore={history.hasMore} loading={history.loading}
|
||||
loadMore={history.loadMore} busy={busy} onSession={onSession} onError={onError} />;
|
||||
}
|
||||
|
||||
export function McpJobHistory({ session, jobs, total = jobs.length, hasMore = false, loading = false, loadMore, busy, onSession, onError }: {
|
||||
session: Session; jobs: McpJob[]; total?: number; hasMore?: boolean; loading?: boolean; loadMore?: () => Promise<void>; busy: boolean; onSession: (value: Session) => void; onError: (error: unknown) => void;
|
||||
}) {
|
||||
const [selected, setSelected] = useState<Evidence | null>(null);
|
||||
const [review, setReview] = useState<Evidence | null>(null);
|
||||
const [working, setWorking] = useState(false);
|
||||
const request = useRef(0);
|
||||
const currentTask = session.execution?.task?.id;
|
||||
const visible = jobs.filter(job => job.taskId === currentTask || job.requiresVerification).slice().reverse();
|
||||
const visible = jobs;
|
||||
|
||||
useEffect(() => { request.current++; setSelected(null); setReview(null); setWorking(false); }, [session.id, currentTask]);
|
||||
async function open(job: McpJob, forReview = false) {
|
||||
@@ -42,7 +52,7 @@ export function McpJobHistory({ session, jobs, busy, onSession, onError }: {
|
||||
|
||||
return <>
|
||||
<section className="task-record-section mcp-history" aria-label="MCP运行记录">
|
||||
<div className="record-heading"><ShieldCheck size={15} /><h3>MCP 运行记录</h3><span>{visible.length} 项</span></div>
|
||||
<div className="record-heading"><ShieldCheck size={15} /><h3>MCP 运行记录</h3><span>已加载 {visible.length} / {total} 项</span></div>
|
||||
{visible.length ? <div className="mcp-history-list">{visible.map(job => <article className={'mcp-history-row state-' + job.status} key={job.id}>
|
||||
<div className="mcp-history-title"><div><strong>{job.input?.call?.tool || (job.operation === 'probe' ? '协议与工具探测' : '工具调用')}</strong><small>{timestamp(job.startedAt)} · {job.operation === 'probe' ? '探测' : '调用'}</small></div>
|
||||
<span className={'mcp-job-state state-' + job.status}>{active.includes(job.status) && <LoaderCircle size={12} className="spin" />}{job.requiresVerification && <CircleAlert size={12} />}{job.status === 'unknown' && job.reviewedAt && !job.requiresVerification ? '已人工核对 · 原结果未知' : labels[job.status] ?? job.status}</span></div>
|
||||
@@ -51,7 +61,8 @@ export function McpJobHistory({ session, jobs, busy, onSession, onError }: {
|
||||
{job.error?.message && <p className="mcp-history-error">{job.error.message}</p>}
|
||||
<div className="mcp-history-actions"><button type="button" className="button secondary" disabled={!job.inputArtifactId || working} onClick={() => void open(job)}><FileText size={14} />{job.reportArtifactId ? '查看原报告' : '查看原始输入'}</button>
|
||||
{job.requiresVerification && <button type="button" className="button secondary" disabled={busy || working || !job.inputArtifactId} onClick={() => void open(job, true)}><AlertTriangle size={14} />人工核对结果</button>}</div>
|
||||
</article>)}</div> : <p className="mcp-history-empty"><Clock3 size={15} />当前任务还没有 MCP 操作记录。</p>}
|
||||
</article>)}</div> : <p className="mcp-history-empty"><Clock3 size={15} />{loading ? '正在读取 MCP 记录。' : '当前会话还没有 MCP 操作记录。'}</p>}
|
||||
{hasMore && <button type="button" className="button secondary" disabled={loading} onClick={() => void loadMore?.()}>{loading && <LoaderCircle size={13} className="spin" />}加载更早的 MCP 记录</button>}
|
||||
{selected && <section className="mcp-report" aria-label="MCP原报告"><header><strong>{selected.report ? '原始 MCP 报告' : '已封存的原始输入'}</strong><button type="button" className="text-button" onClick={() => setSelected(null)}>关闭</button></header>
|
||||
<div className="mcp-report-meta"><span>SHA256</span><code>{selected.job.reportSha256 ?? selected.input.sha256}</code><span>Task / Run</span><code>{selected.job.taskId} / {selected.job.runId}</code></div>
|
||||
<p className="mcp-boundary-note">报告绑定原 Task/Run 和工具输入。独立所属进程不等于 OS 沙箱,报告也不能证明外部程序没有网络或其他副作用。</p>
|
||||
|
||||
+16
-19
@@ -5,18 +5,20 @@ import type { McpJob, McpRegistration, Session } from './types';
|
||||
import { api } from './api';
|
||||
import { Modal } from './components';
|
||||
import { McpJobHistory } from './McpJobHistory';
|
||||
import { useRecordPages } from './useRecordPages';
|
||||
import { approvalLabels, mcpPermissionContext } from '../shared/contracts/execution-policy.mjs';
|
||||
import './McpPanel.css';
|
||||
|
||||
const active = ['queued', 'connecting', 'discovering', 'calling', 'closing', 'stopping'];
|
||||
const stateName: Record<string, string> = { verified: '握手已核验', unverified: '尚未探测', changed: '来源或契约异常' };
|
||||
type View = { projectId: string; revision: number; protocolVersion: string; boundary: string; limits: Record<string, number>; registrations: McpRegistration[] };
|
||||
type View = { projectId: string; revision: number; protocolVersion: string; boundary: string; executionMode: string; limits: Record<string, number | null>; registrations: McpRegistration[] };
|
||||
type Draft = { name: string; executable: string; entry: string; timeoutMs: number };
|
||||
|
||||
export function McpPanel({ projectId, session, busy, approvalMode = 'ask', onSession, onError }: {
|
||||
projectId: string; session: Session | null; busy: boolean; approvalMode?: 'ask' | 'auto' | 'full'; onSession: (value: Session) => void; onError: (error: unknown) => void;
|
||||
}) {
|
||||
const [view, setView] = useState<View | null>(null), [jobs, setJobs] = useState<McpJob[]>([]);
|
||||
const [view, setView] = useState<View | null>(null);
|
||||
const history = useRecordPages<McpJob>(session ? '/sessions/' + session.id + '/mcp/jobs' : null, onError), jobs = history.items;
|
||||
const [working, setWorking] = useState(false), [error, setError] = useState(''), [notice, setNotice] = useState('');
|
||||
const [selectedTools, setSelectedTools] = useState<Record<string, string[]>>({});
|
||||
const [draft, setDraft] = useState<Draft>({ name: '', executable: '', entry: '', timeoutMs: 15000 });
|
||||
@@ -30,11 +32,9 @@ export function McpPanel({ projectId, session, busy, approvalMode = 'ask', onSes
|
||||
|
||||
useEffect(() => { mounted.current = true; return () => { mounted.current = false; generation.current++; }; }, []);
|
||||
async function load(current = generation.current) {
|
||||
const [nextView, nextJobs] = await Promise.all([
|
||||
api<View>(url), session ? api<McpJob[]>('/sessions/' + session.id + '/mcp/jobs') : Promise.resolve([] as McpJob[]),
|
||||
]);
|
||||
const [nextView] = await Promise.all([api<View>(url), history.refresh()]);
|
||||
if (!mounted.current || current !== generation.current) return;
|
||||
setView(nextView); setJobs(nextJobs);
|
||||
setView(nextView);
|
||||
setSelectedTools(previous => {
|
||||
const next = { ...previous };
|
||||
for (const registration of nextView.registrations) if (revisions.current.get(registration.id) !== registration.configurationRevision) {
|
||||
@@ -44,17 +44,15 @@ export function McpPanel({ projectId, session, busy, approvalMode = 'ask', onSes
|
||||
});
|
||||
}
|
||||
useEffect(() => {
|
||||
const current = ++generation.current; setView(null); setJobs([]); setError(''); setNotice(''); setProbeTarget(null);
|
||||
const current = ++generation.current; setView(null); setError(''); setNotice(''); setProbeTarget(null);
|
||||
void load(current).catch(cause => { if (mounted.current && generation.current === current) setError(cause instanceof Error ? cause.message : String(cause)); });
|
||||
return () => { if (generation.current === current) generation.current++; };
|
||||
}, [projectId, session?.id]);
|
||||
useEffect(() => {
|
||||
if (!session || !jobs.some(job => active.includes(job.status))) return;
|
||||
const current = generation.current, previous = jobs;
|
||||
const timer = window.setInterval(() => { void api<McpJob[]>('/sessions/' + session.id + '/mcp/jobs').then(async next => {
|
||||
if (!mounted.current || generation.current !== current) return;
|
||||
setJobs(next);
|
||||
if (previous.some(job => active.includes(job.status)) && !next.some(job => active.includes(job.status))) setView(await api<View>(url));
|
||||
const current = generation.current;
|
||||
const timer = window.setInterval(() => { void Promise.all([history.refresh(), api<View>(url)]).then(([, nextView]) => {
|
||||
if (mounted.current && generation.current === current) setView(nextView);
|
||||
}).catch(cause => { if (generation.current === current) setError(cause instanceof Error ? cause.message : String(cause)); }); }, 900);
|
||||
return () => window.clearInterval(timer);
|
||||
}, [jobs, projectId, session?.id]);
|
||||
@@ -79,7 +77,6 @@ export function McpPanel({ projectId, session, busy, approvalMode = 'ask', onSes
|
||||
const result = await api<{ job: McpJob; session: Session }>('/sessions/' + session.id + '/mcp/probe', { id: target.id, configurationRevision: target.configurationRevision, confirm: true });
|
||||
onSession(result.session); setProbeTarget(null); setNotice('探测已启动;完成后根据实际握手和参数契约选择工具。');
|
||||
const current = generation.current; await load(current);
|
||||
setJobs(previous => previous.some(job => job.id === result.job.id) ? previous : [result.job, ...previous].slice(0, 30));
|
||||
} catch (cause) { setRequestError(cause instanceof Error ? cause.message : String(cause)); }
|
||||
finally { setWorking(false); }
|
||||
}
|
||||
@@ -111,12 +108,12 @@ export function McpPanel({ projectId, session, busy, approvalMode = 'ask', onSes
|
||||
<div className="mcp-registration-heading"><Terminal size={18} /><div><h4>{registration.name}</h4><p>{stateName[registration.status] ?? registration.status} · 配置修订 {registration.configurationRevision}</p></div><span className={'mcp-enabled ' + (registration.enabled ? 'on' : '')}>{registration.enabled ? '已启用' : '已停用'}</span></div>
|
||||
<div className="mcp-source"><div><span>可执行文件</span><code>{registration.launch.executable.path}</code><small><Fingerprint size={12} /> SHA256 {registration.launch.executable.sha256.slice(0, 16)} · {registration.launch.executable.bytes.toLocaleString()} B</small></div>
|
||||
{registration.launch.entry && <div><span>脚本入口</span><code>{registration.launch.entry.path}</code><small>SHA256 {registration.launch.entry.sha256.slice(0, 16)} · {registration.launch.entry.bytes.toLocaleString()} B</small></div>}
|
||||
<span>请求上限 {registration.timeoutMs.toLocaleString()} ms</span></div>
|
||||
<span>{view.executionMode === 'unrestricted' ? '开放执行 · 不设请求超时' : '请求上限 ' + registration.timeoutMs.toLocaleString() + ' ms'}</span></div>
|
||||
{registration.reason && <p className="mcp-warning">{registration.reason}</p>}
|
||||
{registration.contract && <div className="mcp-contract-line"><Check size={13} />实际契约 SHA256 {registration.contract.sha256.slice(0, 16)} · 发现 {registration.tools.length} 项工具</div>}
|
||||
{registration.contract && <div className="mcp-tool-list"><div className="mcp-tool-heading"><strong>允许模型请求的工具</strong><span>已选择 {chosen.length} / 12</span></div>
|
||||
{registration.contract && <div className="mcp-tool-list"><div className="mcp-tool-heading"><strong>允许模型请求的工具</strong><span>已选择 {chosen.length}{view.limits.allowedTools === null ? ' · 数量不限' : ' / ' + view.limits.allowedTools}</span></div>
|
||||
{registration.tools.map(tool => <label className={'mcp-tool-option ' + (tool.unsupported ? 'unsupported' : '')} key={tool.name}>
|
||||
<input type="checkbox" checked={chosen.includes(tool.name)} disabled={locked || !!tool.unsupported || registration.status !== 'verified' || chosen.length >= 12 && !chosen.includes(tool.name)} onChange={event => setSelectedTools(previous => ({ ...previous,
|
||||
<input type="checkbox" checked={chosen.includes(tool.name)} disabled={locked || !!tool.unsupported || registration.status !== 'verified' || view.limits.allowedTools !== null && chosen.length >= (view.limits.allowedTools ?? 12) && !chosen.includes(tool.name)} onChange={event => setSelectedTools(previous => ({ ...previous,
|
||||
[registration.id]: event.target.checked ? [...chosen, tool.name] : chosen.filter(name => name !== tool.name) }))} />
|
||||
<span><strong>{tool.name}</strong>{tool.unsupported && <em>参数契约不受支持</em>}<small>{tool.description || '未提供用途说明'}</small>
|
||||
<details><summary>查看参数契约</summary><pre>{JSON.stringify(tool.inputSchema, null, 2)}</pre>{tool.unsupported && <code>{tool.unsupported}</code>}</details></span>
|
||||
@@ -131,14 +128,14 @@ export function McpPanel({ projectId, session, busy, approvalMode = 'ask', onSes
|
||||
})}</div> : view && <div className="mcp-empty"><PlugZap size={24} /><strong>尚未登记项目 MCP</strong><p>只登记你已审查的本地可执行文件。程序和 Node 入口会在探测及启用前重新计算 SHA256。</p></div>}
|
||||
{!view && !error && <p className="mcp-empty"><LoaderCircle size={18} className="spin" />正在读取项目注册</p>}
|
||||
<form className="mcp-register" onSubmit={register}>
|
||||
<div className="mcp-register-heading"><h4><Plus size={16} />登记本地 MCP</h4><span>绝对路径 · 默认停用 · 最多 {view?.limits.registrations ?? 16} 项</span></div>
|
||||
<div className="mcp-register-heading"><h4><Plus size={16} />登记本地 MCP</h4><span>绝对路径 · 默认停用 · {view?.limits.registrations === null ? '登记数量不限' : '最多 ' + (view?.limits.registrations ?? 16) + ' 项'}</span></div>
|
||||
<div className="mcp-form-grid"><label>显示名称<input required value={draft.name} maxLength={100} onChange={event => setDraft({ ...draft, name: event.target.value })} placeholder="例如:项目只读检索" /></label>
|
||||
<label>请求超时(毫秒)<input required type="number" min={500} max={45000} step={500} value={draft.timeoutMs} onChange={event => setDraft({ ...draft, timeoutMs: Number(event.target.value) })} /></label>
|
||||
<label>{view?.executionMode === 'unrestricted' ? '手动限制模式的超时(毫秒)' : '请求超时(毫秒)'}<input required type="number" min={500} max={45000} step={500} value={draft.timeoutMs} onChange={event => setDraft({ ...draft, timeoutMs: Number(event.target.value) })} /></label>
|
||||
<label className="mcp-full">可执行文件绝对路径<input required value={draft.executable} onChange={event => setDraft({ ...draft, executable: event.target.value })} placeholder="C:\Tools\my-mcp.exe 或当前 Node.js 可执行文件" /></label>
|
||||
<label className="mcp-full">Node 脚本入口(可选)<input value={draft.entry} onChange={event => setDraft({ ...draft, entry: event.target.value })} placeholder="仅接受 .js、.mjs、.cjs;留空表示直接启动可执行文件" /></label></div>
|
||||
<footer><span>仅保留系统路径与临时目录环境,不传入模型 Key;不安装脚本、不使用 shell。</span><button type="submit" className="button primary" disabled={locked || !draft.name.trim() || !draft.executable.trim()}>{working ? <LoaderCircle size={14} className="spin" /> : <Plus size={14} />}登记后保持停用</button></footer>
|
||||
</form>
|
||||
{session && <McpJobHistory session={session} jobs={jobs} busy={locked} onSession={onSession} onError={onError} />}
|
||||
{session && <McpJobHistory session={session} jobs={jobs} total={history.total} hasMore={history.hasMore} loading={history.loading} loadMore={history.loadMore} busy={locked} onSession={onSession} onError={onError} />}
|
||||
{!session && <p className="mcp-empty">选择或创建一个任务会话后,可以对已登记程序执行探测。</p>}
|
||||
{probeTarget && <Modal title="启动 MCP 实际探测" description="工作台将启动该登记程序、核对固定协议并读取实际工具 schema,不调用工具或模型。" onClose={() => { setProbeTarget(null); setRequestError(''); }}>
|
||||
<div className="mcp-probe-summary"><strong>{probeTarget.name}</strong><code>{probeTarget.launch.executable.path}</code>{probeTarget.launch.entry && <code>{probeTarget.launch.entry.path}</code>}
|
||||
|
||||
@@ -2,6 +2,7 @@ import { useEffect, useRef, useState } from 'react';
|
||||
import { Archive, FileText, LoaderCircle, Play, RefreshCw, Save } from 'lucide-react';
|
||||
import { api } from './api';
|
||||
import type { Session, TaskCheckpoint, TaskCheckpointView } from './types';
|
||||
import { useRecordPages } from './useRecordPages';
|
||||
|
||||
export function TaskCheckpointPanel({ session, busy, onSession, onError, openArtifact }: {
|
||||
session: Session; busy: boolean; onSession: (value: Session) => void; onError: (error: unknown) => void; openArtifact: (id: string) => void;
|
||||
@@ -10,15 +11,13 @@ export function TaskCheckpointPanel({ session, busy, onSession, onError, openArt
|
||||
const scope = `${session.id}/${task?.id}/${run?.id}`;
|
||||
const selectedScope = useRef(scope); selectedScope.current = scope;
|
||||
const request = useRef(0);
|
||||
const [records, setRecords] = useState<TaskCheckpoint[]>([]), [view, setView] = useState<TaskCheckpointView | null>(null);
|
||||
const history = useRecordPages<TaskCheckpoint>(task ? `/sessions/${session.id}/task-checkpoints` : null, onError, api, scope), records = history.items;
|
||||
const [view, setView] = useState<TaskCheckpointView | null>(null);
|
||||
const [working, setWorking] = useState(false), [notice, setNotice] = useState('');
|
||||
const disabled = busy || working || ['running', 'awaiting_approval', 'stopping'].includes(session.status);
|
||||
useEffect(() => {
|
||||
let alive = true; const id = ++request.current; setRecords([]); setView(null); setWorking(false); setNotice('');
|
||||
if (task) api<TaskCheckpoint[]>(`/sessions/${session.id}/task-checkpoints`).then(values => {
|
||||
if (alive && selectedScope.current === scope && request.current === id) setRecords(values.filter(value => value.taskId === task.id));
|
||||
}).catch(error => { if (alive && selectedScope.current === scope) onError(error); });
|
||||
return () => { alive = false; request.current++; };
|
||||
request.current++; setView(null); setWorking(false); setNotice(''); void history.refresh();
|
||||
return () => { request.current++; };
|
||||
}, [scope]);
|
||||
if (!task || !run) return null;
|
||||
async function save() {
|
||||
@@ -27,7 +26,7 @@ export function TaskCheckpointPanel({ session, busy, onSession, onError, openArt
|
||||
try {
|
||||
const value = await api<{ checkpoint: TaskCheckpoint; session: Session }>(`/sessions/${session.id}/task-checkpoints`, { taskId: task.id, runId: run.id });
|
||||
if (selectedScope.current === scope && request.current === id) {
|
||||
onSession(value.session); setRecords(values => [value.checkpoint, ...values]); setView(null); setNotice('恢复检查点已保存;继续前还会核对当前工程。');
|
||||
onSession(value.session); await history.refresh(); setView(null); setNotice('恢复检查点已保存;继续前还会核对当前工程。');
|
||||
}
|
||||
} catch (error) { if (selectedScope.current === scope && request.current === id) onError(error); }
|
||||
finally { if (selectedScope.current === scope && request.current === id) setWorking(false); }
|
||||
@@ -48,7 +47,7 @@ export function TaskCheckpointPanel({ session, busy, onSession, onError, openArt
|
||||
finally { if (selectedScope.current === scope && request.current === id) setWorking(false); }
|
||||
}
|
||||
return <section className="task-record-section task-checkpoints" aria-label="任务恢复检查点">
|
||||
<div className="record-heading"><Archive size={15} /><h3>恢复检查点</h3><span>{records.length} 个</span></div>
|
||||
<div className="record-heading"><Archive size={15} /><h3>恢复检查点</h3><span>已加载 {records.length} / {history.total} 个</span></div>
|
||||
<p className="record-footnote">保存完整目标、原工具结果和待处理项;续接前核对源码与任务身份。</p>
|
||||
<button type="button" className="button secondary" onClick={() => void save()} disabled={disabled}>{working ? <LoaderCircle size={13} className="spin" /> : <Save size={13} />}保存恢复检查点</button>
|
||||
{notice && <p className="record-footnote" role="status">{notice}</p>}
|
||||
@@ -59,6 +58,7 @@ export function TaskCheckpointPanel({ session, busy, onSession, onError, openArt
|
||||
<div className="context-actions"><button type="button" className="text-button" disabled={disabled} onClick={() => void inspect(checkpoint)}><RefreshCw size={13} />核对恢复条件</button>
|
||||
<button type="button" className="text-button" onClick={() => openArtifact(checkpoint.artifactId)}><FileText size={13} />查看原恢复包</button></div>
|
||||
</article>)}
|
||||
{history.hasMore && <button type="button" className="button secondary" disabled={history.loading} onClick={() => void history.loadMore()}>{history.loading && <LoaderCircle size={13} className="spin" />}加载更早的检查点</button>}
|
||||
{view && <div className="checkpoint-assessment" role="status"><strong>{view.resumable ? '当前可以续接原任务' : '暂不能从此检查点续接'}</strong>
|
||||
{view.reasons.length > 0 && <ul>{view.reasons.map(reason => <li key={reason}>{reason}</li>)}</ul>}
|
||||
{view.resumable && <button type="button" className="button primary" disabled={disabled} onClick={() => void resume()}><Play size={13} />从已核对检查点继续</button>}
|
||||
|
||||
@@ -12,7 +12,7 @@ import { TaskPlanPanel } from './TaskPlanPanel';
|
||||
import { RequirementPanel } from './RequirementPanel';
|
||||
import { TurnProgress } from './TurnProgress';
|
||||
import { TaskCheckpointPanel } from './TaskCheckpointPanel';
|
||||
import { McpJobHistory } from './McpJobHistory';
|
||||
import { PaginatedMcpJobHistory } from './McpJobHistory';
|
||||
import './TaskPanel.css';
|
||||
import { EnvironmentPanel } from './EnvironmentPanel';
|
||||
import { PreviewPanel } from './PreviewPanel';
|
||||
@@ -107,7 +107,7 @@ export function TaskPanel({ project, session, onSession, onError, busy, onWorksp
|
||||
{task && <RequirementPanel session={session} busy={busy} onSession={onSession} onError={onError} openArtifact={openArtifact} />}
|
||||
{task && <TaskCheckpointPanel session={session} busy={busy} onSession={onSession} onError={onError} openArtifact={openArtifact} />}
|
||||
{execution?.progress.requiresVerification.length ? <section className="verification-note" role="status"><ShieldQuestion size={17} /><div><strong>{execution.progress.requiresVerification.length} 项结果需要核对</strong><p>这些调用已进入执行,但缺少可靠结果。继续任务会保留记录。</p>{execution.progress.requiresVerification.map(tool => <code key={tool.id}>{tool.tool} · {tool.id.slice(0, 8)}</code>)}</div></section> : null}
|
||||
{task && !!execution?.mcpJobs?.length && <McpJobHistory session={session} jobs={execution.mcpJobs} busy={busy} onSession={onSession} onError={onError} />}
|
||||
{task && !!(execution?.mcpJobCount || execution?.mcpJobs?.length) && <PaginatedMcpJobHistory session={session} busy={busy} onSession={onSession} onError={onError} />}
|
||||
{task && <section className="task-record-section">
|
||||
<div className="record-heading"><h3>运行记录</h3><span>{execution?.runs.filter(item => item.taskId === task.id).length} 次</span></div>
|
||||
<label className="run-picker">选择一次运行<select aria-label="选择运行记录" value={id} onChange={event => setRunId(event.target.value)}>{execution?.runs.filter(item => item.taskId === task.id).map((item, index) => <option key={item.id} value={item.id}>第 {index + 1} 次 · {time(item.startedAt)}{item.resumeOf ? ' · 接续' : ''}</option>)}</select></label>
|
||||
|
||||
@@ -1,10 +1,13 @@
|
||||
import type { RecordPage } from './types';
|
||||
export interface CompanionPermissions { observe: boolean; approve: boolean; stop: boolean }
|
||||
export interface CompanionAudit { id: string; at: string; deviceId: string; action: string; status: string; taskId?: string }
|
||||
export interface MobileOperation { id: string; requestId: string; action: string; status: string; taskId: string; runId: string; createdAt: string }
|
||||
export interface CompanionDevice { id: string; name: string; projectIds: string[]; permissions: CompanionPermissions; revision: number; expiresAt: string; createdAt?: string; status?: string }
|
||||
export interface CompanionStatus {
|
||||
enabled: boolean; busy: boolean; origin: string | null; addresses: { name: string; address: string }[];
|
||||
gatewayId: string; revision: number; devices: CompanionDevice[];
|
||||
certificate: { sha256: string; expiresAt: string } | null;
|
||||
audit: { id: string; at: string; deviceId: string; action: string; status: string; taskId?: string }[];
|
||||
audit: CompanionAudit[]; auditPage: RecordPage<CompanionAudit>;
|
||||
}
|
||||
export interface MobileBrief { id: string; projectId: string; taskId?: string; runId?: string; title: string; status: string; revision: number; eventSeq: number; updatedAt: string }
|
||||
export interface MobileUsage { totalTokens: number; unknownRequests: number; estimatedUnknownTokens: number }
|
||||
|
||||
@@ -2,7 +2,9 @@ import { MobileBrowserObservation } from './MobileBrowserObservation';
|
||||
import { approvalPresentation } from '../../shared/approval-presentation.mjs';
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { ArrowLeft, ChevronRight, ClipboardCheck, FileDiff, Folder, Link2, RefreshCw, ShieldCheck, Square, Terminal, Wifi, WifiOff, X } from 'lucide-react';
|
||||
import type { CompanionDevice, MobileBrief, MobileTask } from '../companion-types';
|
||||
import type { CompanionDevice, MobileBrief, MobileTask, MobileOperation } from '../companion-types';
|
||||
import { useRecordPages } from '../useRecordPages';
|
||||
import type { RecordPage } from '../types';
|
||||
import { mobileApi, MobileError, verifiedText, verifyDigest } from './api';
|
||||
import { MobileInputImage } from './MobileInputImage';
|
||||
import './file-results.css';
|
||||
@@ -13,7 +15,7 @@ import { Palette as PaletteIcon } from 'lucide-react';
|
||||
|
||||
const stateLabel = (state: string) => ({ idle: '未开始', waiting: '等待审批', validating: '校验中', queued: '排队中', executing: '执行中', error: '错误', running: '执行中', awaiting_approval: '等待审批', stopping: '正在停止', completed: '已完成', needs_review: '待审查', failed: '失败', interrupted: '已中断', cancelled: '已停止', paused: '已暂停', unknown: '需核对', completed_with_changes: '待审查', passed: '通过', pending: '待处理', applied: '已应用', denied: '已拒绝', approved: '已批准', conflict: '有冲突', unverified: '需核对', stale: '已变化' } as Record<string, string>)[state] ?? state;
|
||||
const time = (value: string) => new Date(value).toLocaleString('zh-CN', { month: 'numeric', day: 'numeric', hour: '2-digit', minute: '2-digit' });
|
||||
type Me = { device: CompanionDevice; gatewayId: string; operations: { requestId: string; action: string; status: string; taskId: string; runId: string; createdAt: string }[] };
|
||||
type Me = { device: CompanionDevice; gatewayId: string; operations: MobileOperation[]; operationsPage: RecordPage<MobileOperation>; unresolvedOperations: MobileOperation[] };
|
||||
type Decision = { requestId: string; kind: 'approve' | 'stop'; task: MobileTask; approval?: MobileTask['approvals'][number]; allow?: boolean };
|
||||
|
||||
export function MobileApp({ initialToken }: { initialToken: string }) {
|
||||
@@ -24,6 +26,8 @@ export function MobileApp({ initialToken }: { initialToken: string }) {
|
||||
const [busy, setBusy] = useState(''), [error, setError] = useState(''), [fresh, setFresh] = useState(false), [lastSync, setLastSync] = useState('');
|
||||
const [connectionRequired, setConnectionRequired] = useState(!!initialToken), [decision, setDecision] = useState<Decision | null>(null);
|
||||
const [document, setDocument] = useState<{ title: string; text: string; sha256: string; redacted?: boolean } | null>(null), [receipt, setReceipt] = useState('');
|
||||
const operations = useRecordPages<MobileOperation>(me ? '/operations' : null, value => setError(value instanceof Error ? value.message : String(value)), mobileApi, me ? me.gatewayId + '/' + me.device.id + '/' + me.device.revision : null);
|
||||
useEffect(() => { if (me) void operations.refresh(); }, [me]);
|
||||
const cursor = useRef(0), identity = useRef<Me | null>(null), chosen = useRef(''), running = useRef(false), actionBusy = useRef(false), alive = useRef(true), generation = useRef(0), dialog = useRef<HTMLDialogElement>(null), documentDialog = useRef<HTMLDialogElement>(null);
|
||||
const revoke = useCallback((message: string) => {
|
||||
generation.current++; identity.current = null; cursor.current = 0; chosen.current = '';
|
||||
@@ -117,12 +121,14 @@ export function MobileApp({ initialToken }: { initialToken: string }) {
|
||||
{appearanceOpen && <Modal title="外观" description="选择适合你的工作台配色,切换后立即生效。" onClose={() => setAppearanceOpen(false)}><AppearancePanel /></Modal>}
|
||||
{me && <div className={'mobile-connection ' + (fresh ? '' : 'disconnected')}>{fresh ? <Wifi size={14} /> : <WifiOff size={14} />}<span>{fresh ? '已同步 · ' + time(lastSync) : '连接中断 · 当前内容可能已过期'}</span><span>{me.device.permissions.approve ? '可审批' : '观察'}</span></div>}
|
||||
{error && <div className="mobile-error" role="alert"><strong>{fresh ? '操作未完成' : connectionRequired ? '需要连接' : '连接待恢复'}</strong><p>{error}</p>{me && <button onClick={() => void refresh()} disabled={!!busy}>重新同步</button>}</div>}
|
||||
{me?.operations?.some(value => value.status === 'unknown') && <div className="mobile-unknown"><strong>手机操作回执需要核对</strong><p>有原审批或停止操作没有完整回执,请在电脑核对;手机不会自动重放。</p>{me.operations.filter(value => value.status === 'unknown').map(value => <code key={value.requestId}>Task {value.taskId} · {value.action === 'stop' ? '停止' : '审批'}</code>)}</div>}
|
||||
{!!me?.unresolvedOperations?.length && <div className="mobile-unknown"><strong>手机操作回执需要核对</strong><p>有原审批或停止操作没有完整回执,请在电脑核对;手机不会自动重放。</p>{me.unresolvedOperations.map(value => <code key={value.requestId}>Task {value.taskId} · {value.action === 'stop' ? '停止' : '审批'}</code>)}</div>}
|
||||
{me && <details className="mobile-operation-history"><summary>手机操作记录 · 已加载 {operations.items.length} / {operations.total} 项</summary>{operations.items.map(value => <p key={value.id}>{value.action === 'stop' ? '停止' : '审批'} · {value.taskId.slice(0, 8)} · {stateLabel(value.status)} · {time(value.createdAt)}</p>)}
|
||||
{operations.hasMore && <button type="button" disabled={operations.loading} onClick={() => void operations.loadMore()}>加载更早的手机操作</button>}</details>}
|
||||
{!me && <main className="mobile-pair-page"><div className="mobile-pair-heading"><Link2 size={32} /><h1>接续电脑上的任务</h1><p>在 Windows 工作台打开「手机连接」,选择项目并生成一次性配对码。</p></div>{connectionRequired || pairToken ? <form onSubmit={event => void pair(event)}><label>设备名称<input value={name} maxLength={60} onChange={event => setName(event.target.value)} autoComplete="off" /></label><label>配对码或配对链接<input type="password" value={pairToken} onChange={event => setPairToken(event.target.value)} autoComplete="off" autoCapitalize="none" spellCheck={false} placeholder="扫描电脑上的二维码后自动填写" /></label><button className="mobile-primary" disabled={!!busy || !pairToken.trim() || !name.trim()}>{busy === 'pair' ? '正在核对授权…' : '连接这台电脑'}</button></form> : <p role="status">正在核对当前手机连接…</p>}<div className="mobile-pair-help"><ShieldCheck size={18} /><p>首次使用需要在 iPhone 安装并信任电脑生成的根证书。请按电脑「手机连接」中的指引操作。</p></div></main>}
|
||||
{me && !selected && <main className="mobile-task-list"><div className="mobile-page-title"><div><span className="mobile-eyebrow">{me.device.name}</span><h1>项目任务</h1></div><span>{sessions.length} 个会话</span></div><label className="mobile-project-filter"><Folder size={17} /><select aria-label="筛选项目" value={project} onChange={event => setProject(event.target.value)}><option value="">全部授权项目</option>{projects.map(item => <option key={item.id} value={item.id}>{item.name}</option>)}</select></label>
|
||||
{!sessions.length && <div className="mobile-empty"><ClipboardCheck size={30} /><h2>暂无任务</h2><p>在电脑创建或打开任务,手机会同步该项目的执行进展。</p></div>}
|
||||
{sessions.filter(item => !project || item.projectId === project).map(item => <button className="mobile-task-row" key={item.id} onClick={() => void openTask(item.id)}><div><span className="mobile-project-name">{projectName(item.projectId)}</span><strong>{item.title}</strong><span className="mobile-row-meta"><span className={'mobile-state state-' + item.status}>{stateLabel(item.status)}</span><time>{time(item.updatedAt)}</time></span></div><ChevronRight size={19} /></button>)}
|
||||
<details className="mobile-device-settings"><summary>设备连接与授权</summary><p>{projects.map(item => item.name).join('、')}</p><p>观察{me.device.permissions.approve ? ' · 审批' : ''}{me.device.permissions.stop ? ' · 停止' : ''} · {time(me.device.expiresAt)} 到期</p><p>手机显示最近200个未归档会话,完整历史在电脑保留。</p><p>iPhone Safari 中点「共享 → 添加到主屏幕」可安装伴随端。主屏幕应用如要求连接,请在电脑生成新的配对码。</p><div><button disabled={!!busy || !fresh} onClick={() => void act('rotate', async () => { await mobileApi('/rotate', {}); await refresh(); setReceipt('手机会话已轮换。'); })}>轮换手机会话</button><button disabled={!!busy} onClick={() => void act('logout', async () => { await mobileApi('/logout', {}); revoke('已断开并撤销这台手机。'); })}>断开并撤销</button></div></details></main>}
|
||||
<details className="mobile-device-settings"><summary>设备连接与授权</summary><p>{projects.map(item => item.name).join('、')}</p><p>观察{me.device.permissions.approve ? ' · 审批' : ''}{me.device.permissions.stop ? ' · 停止' : ''} · {time(me.device.expiresAt)} 到期</p><p>显示已授权项目的未归档会话;操作记录可加载更早记录。</p><p>iPhone Safari 中点「共享 → 添加到主屏幕」可安装伴随端。主屏幕应用如要求连接,请在电脑生成新的配对码。</p><div><button disabled={!!busy || !fresh} onClick={() => void act('rotate', async () => { await mobileApi('/rotate', {}); await refresh(); setReceipt('手机会话已轮换。'); })}>轮换手机会话</button><button disabled={!!busy} onClick={() => void act('logout', async () => { await mobileApi('/logout', {}); revoke('已断开并撤销这台手机。'); })}>断开并撤销</button></div></details></main>}
|
||||
{me && selected && <main className="mobile-task-detail"><button className="mobile-back" onClick={() => { chosen.current = ''; setSelected(''); setTask(null); setDocument(null); }}><ArrowLeft size={18} />项目任务</button>{!selectedTask ? <div className="mobile-empty" role="status">正在读取原任务…</div> : <>
|
||||
<div className="mobile-task-title"><span className="mobile-eyebrow">{projectName(selectedTask.projectId)}</span><h1>{selectedTask.title}</h1><div><span className={'mobile-state state-' + selectedTask.status}>{stateLabel(selectedTask.status)}</span><span>修订 {selectedTask.revision}</span></div><details className="mobile-goal"><summary>完整任务目标</summary><p>{selectedTask.task?.goal ?? '此会话尚未创建执行任务。'}</p></details><details><summary>原任务与运行</summary><code>Task {selectedTask.taskId ?? '未开始'}<br />Run {selectedTask.runId ?? '未开始'}</code></details></div>
|
||||
{receipt && <p className="mobile-receipt" role="status">{receipt}</p>}
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
:root { color: var(--orven-ink); background: var(--orven-navigation); --ink: var(--orven-ink); --muted: var(--orven-muted); --line: var(--orven-border-soft); --green: #277859; }
|
||||
.mobile-operation-history { margin: 12px 16px; padding: 12px 0; border-bottom: 1px solid var(--orven-border-soft); font-size: 13px; overflow-wrap: anywhere; }
|
||||
.mobile-operation-history summary { cursor: pointer; font-weight: 600; padding: 8px 0; }
|
||||
.mobile-operation-history p { color: var(--orven-muted); line-height: 1.6; }
|
||||
button, input, select { border-color: var(--orven-border-strong); border-radius: 8px; }
|
||||
button:focus-visible, input:focus-visible, select:focus-visible, summary:focus-visible { outline-color: var(--orven-accent); }
|
||||
.mobile-app { background: #fff; }
|
||||
|
||||
+2
-1
@@ -174,6 +174,7 @@ export interface DeliveryStatus {
|
||||
gaps: { kind: string; id: string; label: string; nextStep: string }[] };
|
||||
diagnostics: { runId: string; status: string; stopReason: string | null; question: string; failure?: RuntimeFailure | null; context: DiagnosticContext }[];
|
||||
}
|
||||
export interface RecordPage<T> { items: T[]; total: number; hasMore: boolean; nextCursor: string | null }
|
||||
export interface TaskCheckpoint {
|
||||
id: string; sessionId: string; projectId: string; taskId: string; runId: string; createdAt: string;
|
||||
status: string; artifactId: string; sha256: string; sourceFingerprint: string; requirementsSha256: string;
|
||||
@@ -295,7 +296,7 @@ export interface RequirementDraft {
|
||||
id: string; taskId: string; runId: string; expectedRevision: number; sourceSetSha256: string; contractArtifactId: string;
|
||||
proposal: { items: (Pick<RequirementItem, 'key' | 'title' | 'criterion' | 'source' | 'role'>)[]; covered_source_ids: string[]; truncated: boolean; note: string };
|
||||
}
|
||||
export interface ExecutionSnapshot { schemaVersion: number; task: Task | null; run: Run | null; runs: RunBrief[]; progress: { totalTools: number; completedTools: number; requiresVerification: { id: string; tool: string; state: string; callId: string }[] }; artifacts: Artifact[]; checks: CheckJob[]; mcpJobs?: McpJob[]; plans?: CheckPlan[]; deliveries?: DeliveryJob[]; deliveryPlans?: DeliveryPlan[]; changeSets?: ChangeSet[]; contextPlans?: ContextPlan[]; workspaces?: WorkspaceRecord[]; researchTargets?: ResearchTarget[]; researchJobs?: ResearchJob[]; engineJobs?: EngineJob[]; engineRuns?: EngineRunView[]; browserPlans?: BrowserPlan[]; browserJobs?: BrowserJob[]; taskPlans?: TaskPlanRecord[]; taskProofs?: { id: string; planId: string; stepKey: string; status: string }[]; collaborations?: CollaborationGroup[]; workers?: WorkerRecord[]; workspaceIdentity?: WorkspaceIdentity; accountedTaskTokens: number }
|
||||
export interface ExecutionSnapshot { schemaVersion: number; task: Task | null; run: Run | null; runs: RunBrief[]; progress: { totalTools: number; completedTools: number; requiresVerification: { id: string; tool: string; state: string; callId: string }[] }; artifacts: Artifact[]; checks: CheckJob[]; mcpJobs?: McpJob[]; mcpJobCount?: number; mcpJobsTruncated?: boolean; plans?: CheckPlan[]; deliveries?: DeliveryJob[]; deliveryPlans?: DeliveryPlan[]; changeSets?: ChangeSet[]; contextPlans?: ContextPlan[]; workspaces?: WorkspaceRecord[]; researchTargets?: ResearchTarget[]; researchJobs?: ResearchJob[]; engineJobs?: EngineJob[]; engineRuns?: EngineRunView[]; browserPlans?: BrowserPlan[]; browserJobs?: BrowserJob[]; taskPlans?: TaskPlanRecord[]; taskProofs?: { id: string; planId: string; stepKey: string; status: string }[]; collaborations?: CollaborationGroup[]; workers?: WorkerRecord[]; workspaceIdentity?: WorkspaceIdentity; accountedTaskTokens: number }
|
||||
export interface WorkerBudget { maxTokens: number; maxSteps: number; maxToolCalls: number }
|
||||
export interface WorkerAssignment { schemaVersion: number; role: string; requirements: string[]; selection: { type: string; id: string } | null; selectionSource: string; model: ModelSnapshot }
|
||||
export interface WorkerQuality { role: string; checks: { status: string; checkJobId: string | null }; requirements: { criterion: string; status: string }[] }
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { api } from './api';
|
||||
import type { RecordPage } from './types';
|
||||
|
||||
const empty = <T,>(): RecordPage<T> => ({ items: [], total: 0, hasMore: false, nextCursor: null });
|
||||
type FetchPage = <T>(url: string) => Promise<T>;
|
||||
export function useRecordPages<T extends { id: string }>(url: string | null, onError: (error: unknown) => void, fetchPage: FetchPage = api, scope = url) {
|
||||
const [page, setPage] = useState<RecordPage<T>>(empty), [loading, setLoading] = useState(false);
|
||||
const current = useRef(empty<T>()), epoch = useRef(0), pending = useRef(false), error = useRef(onError);
|
||||
error.current = onError;
|
||||
const read = useCallback(async (more: boolean) => {
|
||||
if (!url || pending.current || more && !current.current.hasMore) return;
|
||||
const generation = epoch.current, previous = current.current; pending.current = true; setLoading(true);
|
||||
try {
|
||||
const query = (cursor: string | null) => url + '?limit=50' + (cursor ? '&cursor=' + encodeURIComponent(cursor) : '');
|
||||
let next = await fetchPage<RecordPage<T>>(query(more ? previous.nextCursor : null));
|
||||
if (generation !== epoch.current) return;
|
||||
let items = [...next.items];
|
||||
// New records may arrive while older pages are expanded. Walk the gap to
|
||||
// a retained anchor before merging, so polling cannot skip an interval.
|
||||
if (!more && previous.items.length) {
|
||||
const known = new Set(previous.items.map(item => item.id));
|
||||
while (next.hasMore && !items.some(item => known.has(item.id))) {
|
||||
next = await fetchPage<RecordPage<T>>(query(next.nextCursor));
|
||||
if (generation !== epoch.current) return;
|
||||
items.push(...next.items);
|
||||
}
|
||||
if (items.some(item => known.has(item.id))) {
|
||||
const seen = new Set(items.map(item => item.id));
|
||||
items.push(...previous.items.filter(item => !seen.has(item.id)));
|
||||
next = { ...next, hasMore: previous.hasMore, nextCursor: previous.nextCursor };
|
||||
}
|
||||
} else if (more) {
|
||||
const seen = new Set(previous.items.map(item => item.id));
|
||||
items = [...previous.items, ...items.filter(item => !seen.has(item.id))];
|
||||
}
|
||||
const value = { ...next, items };
|
||||
current.current = value; setPage(value);
|
||||
} catch (cause) { if (generation === epoch.current) error.current(cause); }
|
||||
finally { if (generation === epoch.current) { pending.current = false; setLoading(false); } }
|
||||
}, [url, fetchPage, scope]);
|
||||
const refresh = useCallback(() => read(false), [read]), loadMore = useCallback(() => read(true), [read]);
|
||||
useEffect(() => {
|
||||
epoch.current++; pending.current = false; current.current = empty<T>(); setPage(empty<T>()); setLoading(false);
|
||||
void refresh();
|
||||
return () => { epoch.current++; pending.current = false; };
|
||||
}, [refresh]);
|
||||
return { ...page, loading, refresh, loadMore };
|
||||
}
|
||||
Reference in New Issue
Block a user