docs(release): seal and deliver task agreement 1.25 with retained production state

This commit is contained in:
Agent Workbench Dev
2026-11-04 15:34:29 +08:00
parent 78976ac775
commit ddefe5f108
1444 changed files with 2161122 additions and 17 deletions
@@ -0,0 +1,663 @@
import { EmbeddedBrowserPanel } from './EmbeddedBrowserPanel';
import { ProjectDirectoryPicker } from './ProjectDirectoryPicker';
import { HtmlFilePreview } from './HtmlFilePreview';
import { InstallationStatus } from './InstallationStatus';
import { approvalPresentation } from '../shared/approval-presentation.mjs';
import { useEffect, useMemo, useRef, useState } from 'react';
import { Activity, Brain, ClipboardCheck, RotateCw, ArrowDownToLine, ArrowRight, ArrowUp, BookOpenText, Check, ChevronDown, ChevronRight, Code2, Copy, File, FileCode2, Folder, FolderOpen, GitBranch, Link2, LoaderCircle, Maximize2, MessageSquare, Minimize2, PanelLeftClose, PanelLeftOpen, Pencil, Play, Plus, Puzzle, Search, Server as ModelServer, Settings2, ShieldCheck, Square, SquareTerminal, Trash2, X } from 'lucide-react';
import type { Bootstrap, Change, Config, ModelSelection, FileEntry, OpenFile, Project, ResearchDoc, Session, SessionBrief, ToolEvent, RuntimeDiagnostics, RuntimeFailure } from './types';
import { api, downloadBlob, exportSession, setToken } from './api';
import { DiffView, EmptyInspector, IconButton, Modal, ResearchContent, Status, ToolRow, FailureCard, ModelStreamPreview } from './components';
import { DiagnosticsPanel } from './DiagnosticsPanel';
import { TaskPanel } from './TaskPanel';
import { CodeIndexPanel } from './CodeIndexPanel';
import { ChangesInspector } from './ChangesInspector';
import { ResearchPanel } from './ResearchPanel';
import { EnginePanel } from './EnginePanel';
import { ModelCenter } from './ModelCenter';
import { ProjectMemoryPanel } from './ProjectMemoryPanel';
import { SkillCenter } from './SkillCenter';
import { McpPanel } from './McpPanel';
import { WorkerPanel } from './WorkerPanel';
import { EvaluationPanel } from './EvaluationPanel';
import { DesktopPanel } from './DesktopPanel';
import { CompanionPanel } from './CompanionPanel';
import { desktop } from './desktop';
import { AttachmentComposer,InputImage } from './InputAttachments';
import { BudgetPausePanel } from './BudgetPausePanel';
const activeStates = ['running', 'awaiting_approval', 'stopping'];
const activeMcpStates = ['queued', 'connecting', 'discovering', 'calling', 'closing', 'stopping'];
const defaultConfig: Config = { mode: 'demo', baseUrl: 'http://127.0.0.1:11434/v1', model: '', contextLimit: 16000, maxSteps: 12, maxOutputTokens: 2048, hasKey: false, maxRunDurationMs: 600000, maxRunTokens: 200000, maxTaskTokens: 1000000, modelResponseTimeoutMs: 300000, modelStreamIdleTimeoutMs: 120000 };
export default function App() {
const [token, setAccess] = useState('');
const [version, setVersion] = useState('1.10.0');
const [diagnosticsOpen, setDiagnosticsOpen] = useState(false);
const [diagnostics, setDiagnostics] = useState<RuntimeDiagnostics | null>(null);
const [diagnosticsBusy, setDiagnosticsBusy] = useState(false);
const [resuming, setResuming] = useState(false);
const [modelCheck, setModelCheck] = useState<{ kind: 'success' | 'error'; message: string } | null>(null);
const [projects, setProjects] = useState<Project[]>([]);
const [briefs, setBriefs] = useState<SessionBrief[]>([]);
const [projectId, setProjectId] = useState('');
const [sessionId, setSessionId] = useState('');
const [session, setSession] = useState<Session | null>(null);
const [config, setConfig] = useState<Config>(defaultConfig);
const [modelSelection, setModelSelection] = useState<ModelSelection>({ type: "legacy", id: "legacy-default", name: "原模型连接" });
const [exampleId, setExampleId] = useState<string | null>(null);
const [files, setFiles] = useState<FileEntry[]>([]);
const [filter, setFilter] = useState('');
const [collapsed, setCollapsed] = useState<Set<string>>(new Set());
const [openFile, setOpenFile] = useState<OpenFile | null>(null);
const [fileMode, setFileMode] = useState<'source' | 'preview'>('source');
const [fileLoading, setFileLoading] = useState(false);
const [fileLine, setFileLine] = useState<number | null>(null);
const [fileNotice, setFileNotice] = useState('');
const [draftSaving, setDraftSaving] = useState(false);
const [changeBusy, setChangeBusy] = useState('');
const [deciding, setDeciding] = useState(false);
const [editing, setEditing] = useState(false);
const editingRef = useRef(editing); editingRef.current = editing;
const [draft, setDraft] = useState('');
const [composer, setComposer] = useState('');
const [sending, setSending] = useState(false);
const [imageSelection,setImageSelection]=useState<{sessionId:string;ids:string[]}>({sessionId:'',ids:[]});
const [creatingSession, setCreatingSession] = useState(false);
const [tab, setTab] = useState<'file' | 'changes' | 'trace' | 'task' | 'index' | 'browse'>('file');
const [changeId, setChangeId] = useState('');
const [eventId, setEventId] = useState('');
const [wide, setWide] = useState(false);
const [inspectorWidth,setInspectorWidth]=useState<number|null>(null),[inspectorResizing,setInspectorResizing]=useState(false);
const inspectorDrag=useRef<{x:number;width:number}|null>(null);
const [sidebarOpen, setSidebarOpen] = useState(() => window.innerWidth > 620);
const [narrow, setNarrow] = useState(() => window.innerWidth <= 940);
const [viewportWidth,setViewportWidth]=useState(()=>window.innerWidth);
const [mobile, setMobile] = useState(() => window.innerWidth <= 620);
const [connected, setConnected] = useState(false);
const [settingsOpen, setSettingsOpen] = useState(false);
const [settings, setSettings] = useState<Config>(defaultConfig);
const [keyValue, setKeyValue] = useState('');
const [clearKey, setClearKey] = useState(false);
const [models, setModels] = useState<string[]>([]);
const [settingsBusy, setSettingsBusy] = useState(false);
const [projectOpen, setProjectOpen] = useState(false);
const [projectInput, setProjectInput] = useState('');
const [directoryPickerOpen, setDirectoryPickerOpen] = useState(false);
const [projectBusy, setProjectBusy] = useState(false);
const [projectError, setProjectError] = useState('');
const [toast, setToast] = useState('');
const [researchOpen, setResearchOpen] = useState(false);
const [reaOpen, setReaOpen] = useState(false);
const [engineOpen, setEngineOpen] = useState(false);
const [modelCenterOpen, setModelCenterOpen] = useState(false);
const [memoryOpen, setMemoryOpen] = useState(false);
const [skillsOpen, setSkillsOpen] = useState(false);
const [mcpOpen, setMcpOpen] = useState(false);
const [workersOpen, setWorkersOpen] = useState(false);
const [evaluationsOpen, setEvaluationsOpen] = useState(false);
const [desktopOpen, setDesktopOpen] = useState(false);
const [installationOpen, setInstallationOpen] = 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);
const chatEnd = useRef<HTMLDivElement>(null);
const conversationRef = useRef<HTMLElement>(null);
const codeViewRef = useRef<HTMLDivElement>(null);
const composerRef = useRef<HTMLTextAreaElement>(null);
const filterRef = useRef<HTMLInputElement>(null);
const selectedSessionRef = useRef('');
const selectedProjectRef = useRef('');
const selectedTaskRef = useRef('');
const revisions = useRef(new Map<string, number>());
const archivedSessions = useRef(new Set<string>());
const eventCursor = useRef(0);
const filesRequest = useRef(0);
const fileRequest = useRef(0);
const reportRequest = useRef(0);
const workspaceRequest = useRef(0);
const sessionCreation = useRef<Promise<Session | null> | null>(null);
const selectedProject = projects.find(project => project.id === projectId);
const isRunning = !!session && (activeStates.includes(session.status) || session.execution?.checks.some(job => ['queued', 'running'].includes(job.status)) === true
|| session.execution?.previewJobs?.some(job => ['queued','starting','stopping'].includes(job.status)) === true
|| session.execution?.browsingActions?.some(job => ['queued','dispatched'].includes(job.status)) === true
|| session.execution?.environmentJobs?.some(job => ['queued','running','stopping'].includes(job.status)) === true
|| session.execution?.deliveries?.some(job => ['queued', 'preparing', 'prepared', 'publishing', 'committed', 'reporting'].includes(job.status)) === true
|| session.execution?.changeSets?.some(set => ['applying', 'rolling_back'].includes(set.status)) === true
|| session.execution?.workspaces?.some(value => ['creating', 'verifying', 'registering'].includes(value.status)) === true
|| session.execution?.researchJobs?.some(value => ['queued', 'connecting', 'analyzing', 'stopping'].includes(value.status)) === true
|| session.execution?.engineJobs?.some(value => ['queued', 'starting', 'initializing', 'checking', 'stopping'].includes(value.status)) === true
|| session.execution?.mcpJobs?.some(value => activeMcpStates.includes(value.status)) === true
|| session.execution?.collaborations?.some(value => ['preparing', 'starting', 'running', 'stopping', 'collecting', 'merge_preparing', 'reconciling'].includes(value.status)) === true
|| session.execution?.browserJobs?.some(value => ['queued', 'snapshotting', 'launching', 'running', 'closing'].includes(value.status)) === true);
const anyRunning = isRunning || briefs.some(item => activeStates.includes(item.status));
const restrictedWorker = !!session?.execution?.workers?.length;
const pending = session?.changes.filter(change => ['pending', 'conflict'].includes(change.status)) || [];
const reviewedRun = session?.execution?.run;
const canContinueReview = !!session && pending.length === 0 && !isRunning
&& !(session.execution?.task?.contract?.checks === 'skip' && session.execution.task.delivery?.status === 'files_applied')
&& (reviewedRun?.status === 'needs_review' || reviewedRun?.status === 'paused' && reviewedRun.stopReason === 'step_limit')
&& reviewedRun?.taskId === session.execution?.task?.id
&& reviewedRun?.stopReason !== 'git_review'
&& !session.execution?.progress.requiresVerification.length
&& session.changes.some(change => change.status === 'applied' && (!change.taskId || change.taskId === session.execution?.task?.id));
const selectedChange = session?.changes.find(change => change.id === changeId) || pending[0] || session?.changes.at(-1);
const selectedEvent = session?.events.find(event => event.id === eventId) || session?.events.at(-1);
const approval = session?.approvals.find(item => item.status === 'pending');
const projectSessions = briefs.filter(item => item.projectId === projectId);
const visibleFiles = useMemo(() => {
const children = new Map<string, FileEntry[]>();
for (const file of files) {
const parent = file.path.split('/').slice(0, -1).join('/');
children.set(parent, [...(children.get(parent) ?? []), file]);
}
const ordered: FileEntry[] = [];
function visit(parent: string) {
const siblings = (children.get(parent) ?? []).sort((a, b) => Number(b.kind === 'directory') - Number(a.kind === 'directory') || a.name.localeCompare(b.name));
for (const file of siblings) { ordered.push(file); if (file.kind === 'directory') visit(file.path); }
}
visit('');
return ordered.filter(file => {
if (filter) return file.path.toLocaleLowerCase().includes(filter.toLocaleLowerCase());
const parts = file.path.split('/');
for (let index = 1; index < parts.length; index++) if (collapsed.has(parts.slice(0, index).join('/'))) return false;
return true;
});
}, [files, filter, collapsed]);
function notify(message: string) { setToast(message); }
function failure(error: unknown) { notify(error instanceof Error ? error.message : String(error)); }
function failureFor(origin: Session) {
const { id, projectId } = origin, taskId = origin.execution?.task?.id ?? '';
return (error: unknown) => {
if (selectedSessionRef.current === id && selectedProjectRef.current === projectId && selectedTaskRef.current === taskId) failure(error);
};
}
function selectSession(id: string) {
if (selectedSessionRef.current === id) return;
workspaceRequest.current++; selectedSessionRef.current = id; selectedTaskRef.current = ''; setSessionId(id); setSession(null); setToast(''); setReaOpen(false); setEngineOpen(false);
localStorage.setItem('awb-session', id); setChangeId(''); setEventId('');
}
function acceptSession(updated: Session) {
const revision = updated.revision ?? 0;
if (revision < (revisions.current.get(updated.id) ?? 0)) return;
revisions.current.set(updated.id, revision);
if (updated.archived) archivedSessions.current.add(updated.id); else archivedSessions.current.delete(updated.id);
if (selectedSessionRef.current === updated.id && selectedProjectRef.current === updated.projectId) {
selectedTaskRef.current = updated.execution?.task?.id ?? '';
setSession(previous => previous?.id === updated.id && previous.revision > revision ? previous : updated);
}
setBriefs(previous => {
const remaining = previous.filter(item => item.id !== updated.id);
if (updated.archived) return remaining;
return [{ id: updated.id, projectId: updated.projectId, title: updated.title, status: updated.status, revision,
updatedAt: updated.updatedAt, changeCount: updated.changes.filter(change => ['pending', 'conflict'].includes(change.status)).length }, ...remaining]
.sort((a, b) => b.updatedAt.localeCompare(a.updatedAt));
});
}
function showInspector(next: 'file' | 'changes' | 'trace' | 'task' | 'index' | 'browse') {
setTab(next);
if (window.innerWidth <= 940) setWide(true);
if (window.innerWidth <= 620) setSidebarOpen(false);
}
async function refreshFiles(id = selectedProjectRef.current) {
if (!id) return;
const request = ++filesRequest.current;
const result = await api<{ files: FileEntry[]; truncated: boolean }>('/projects/' + id + '/files');
if (request === filesRequest.current && selectedProjectRef.current === id) setFiles(result.files);
}
async function chooseProject(id: string, preferredSession?: string) {
if (selectedProjectRef.current !== id) setToast('');
workspaceRequest.current++; selectedProjectRef.current = id; setProjectId(id); localStorage.setItem('awb-project', id);
filesRequest.current++; fileRequest.current++;
setOpenFile(null); setFiles([]); setFileLoading(false); setFileLine(null); setFileNotice(''); setEditing(false); setCollapsed(new Set()); setFilter('');
const candidate = preferredSession || briefs.find(item => item.projectId === id)?.id || '';
selectSession(candidate);
if (window.innerWidth <= 620) setSidebarOpen(false);
}
async function chooseSession(id: string) {
if (selectedSessionRef.current === id) {
try { acceptSession(await api<Session>('/sessions/' + id)); } catch (error) { failure(error); }
} else selectSession(id);
if (window.innerWidth <= 620) setSidebarOpen(false);
}
function acceptWorkspaceBootstrap(value: Bootstrap) {
setProjects(value.projects);
setBriefs(previous => {
const merged = new Map(value.sessions.map(item => [item.id, item]));
for (const item of previous) if (!archivedSessions.current.has(item.id) && item.revision >= (merged.get(item.id)?.revision ?? -1)) merged.set(item.id, item);
return [...merged.values()].filter(item => !archivedSessions.current.has(item.id)).sort((a, b) => b.updatedAt.localeCompare(a.updatedAt));
});
}
async function refreshWorkspaceState(originProjectId: string, originSessionId: string, isCurrent: () => boolean = () => true) {
const request = ++workspaceRequest.current;
const [bootstrap, updated] = await Promise.all([api<Bootstrap>('/bootstrap'), api<Session>('/sessions/' + originSessionId)]);
if (!isCurrent() || request !== workspaceRequest.current || selectedProjectRef.current !== originProjectId || selectedSessionRef.current !== originSessionId) return;
acceptWorkspaceBootstrap(bootstrap); acceptSession(updated);
}
async function navigateWorkspace(nextProjectId: string, nextSessionId: string, isCurrent: () => boolean = () => true, view: 'task' | 'changes' | 'approval' = 'task') {
const originProjectId = selectedProjectRef.current, originSessionId = selectedSessionRef.current, request = ++workspaceRequest.current;
const [bootstrap, next] = await Promise.all([api<Bootstrap>('/bootstrap'), api<Session>('/sessions/' + nextSessionId)]);
if (!isCurrent() || request !== workspaceRequest.current || selectedProjectRef.current !== originProjectId || selectedSessionRef.current !== originSessionId) return;
if (next.projectId !== nextProjectId || next.archived || !bootstrap.projects.some(value => value.id === nextProjectId)) throw new Error('目标会话已归档或项目身份发生变化,请从项目栏选择当前会话。');
acceptWorkspaceBootstrap(bootstrap);
await chooseProject(nextProjectId, nextSessionId); acceptSession(next);
if (view === 'approval') setWide(false); else showInspector(view);
}
async function newSession() {
if (sessionCreation.current) return sessionCreation.current;
if (!projectId) { setProjectOpen(true); return null; }
const targetProject = projectId, targetSelection = selectedSessionRef.current;
setCreatingSession(true);
const request = (async () => {
try {
const created = await api<Session>('/sessions', { projectId: targetProject });
if (selectedProjectRef.current !== targetProject || selectedSessionRef.current !== targetSelection) { acceptSession(created); return null; }
selectSession(created.id); acceptSession(created); setTab('file');
if (window.innerWidth <= 620) setSidebarOpen(false);
return created;
} finally { sessionCreation.current = null; setCreatingSession(false); }
})();
sessionCreation.current = request;
return request;
}
async function submit() {
if (!composer.trim() || sending || isRunning || (sessionId && !session)) return;
if (restrictedWorker || session?.execution?.collaborations?.some(value => !['completed', 'discarded', 'resolved_external'].includes(value.status))) { setWorkersOpen(true); return; }
if (config.mode === 'compatible' && modelSelection.type === 'legacy' && !config.model) { setModelCenterOpen(true); notify('请先填写模型名称。'); return; }
setSending(true);
const content = composer.trim();
try {
const target = session || await newSession();
if (!target) return;
acceptSession(await api<Session>('/sessions/' + target.id + '/messages', { content,attachmentIds:imageSelection.sessionId===target.id?imageSelection.ids:[] }));
if (selectedSessionRef.current === target.id) {
setComposer(previous => previous.trim() === content ? '' : previous); setImageSelection({sessionId:target.id,ids:[]}); composerRef.current?.focus();
}
} catch (error) { failure(error); }
finally { setSending(false); }
}
async function openProject() {
if (!projectInput.trim() || projectBusy) return;
setProjectBusy(true); setProjectError('');
try {
const project = await api<Project>('/projects', { root: projectInput.trim() });
setProjects(previous => [project, ...previous.filter(item => item.id !== project.id)]);
await chooseProject(project.id); setProjectOpen(false); setProjectInput('');
notify('已打开项目 ' + project.name);
} catch (error) { setProjectError(error instanceof Error ? error.message : '打开项目失败。'); }
finally { setProjectBusy(false); }
}
async function acceptDesktopProject(project: Project) {
setProjects(previous => [project, ...previous.filter(item => item.id !== project.id)]);
await chooseProject(project.id); setProjectOpen(false); setDesktopOpen(false); notify('已打开项目 ' + project.name);
}
async function pickDesktopProject() {
if (!desktop || pickingProject) return;
setPickingProject(true);
try { const project = await desktop.pickProject(); if (project) await acceptDesktopProject(project); } catch (error) { failure(error); }
finally { setPickingProject(false); }
}
async function loadFile(relative: string, location?: { line: number; expectedSha256: string }) {
if (!projectId) return;
const targetProject = projectId, request = ++fileRequest.current;
showInspector('file'); setFileLoading(true); setEditing(false); setFileLine(null); setFileNotice('');
try {
const file = await api<OpenFile>('/projects/' + targetProject + '/file?path=' + encodeURIComponent(relative));
if (fileRequest.current === request && selectedProjectRef.current === targetProject) {
setOpenFile(file); setDraft(file.content); setFileMode(!location && /\.html?$/i.test(file.path) ? 'preview' : 'source');
if (location && file.sha256 !== location.expectedSha256) setFileNotice('文件在索引后已变化,已打开当前内容。请回到索引刷新后重新定位。');
else if (location && location.line >= 1 && location.line <= file.content.split('\n').length) setFileLine(location.line);
}
} catch (error) { if (fileRequest.current === request) failure(error); }
finally { if (fileRequest.current === request) setFileLoading(false); }
}
async function saveDraft() {
if (!openFile || draftSaving) return;
const file = openFile, content = draft;
setDraftSaving(true);
try {
const target = session || await newSession(); if (!target) return;
const updated = await api<Session>('/sessions/' + target.id + '/proposals', { path: file.path, content, reason: '手动编辑文件', base_sha256: file.sha256 });
acceptSession(updated);
if (selectedSessionRef.current === target.id) { setChangeId(updated.changes.at(-1)?.id || ''); setEditing(false); showInspector('changes'); notify('编辑内容已保存为待审查提案。'); }
} catch (error) { failure(error); } finally { setDraftSaving(false); }
}
async function changeAction(change: Change, action: 'apply' | 'reject') {
if (!session || changeBusy || isRunning) return;
const targetSession = session.id, targetProject = projectId, currentFileRequest = fileRequest.current;
setChangeBusy(change.id);
try {
const updated = await api<Session>('/sessions/' + targetSession + '/changes/' + change.id + '/' + action, {});
acceptSession(updated); await refreshFiles(targetProject);
if (action === 'apply' && openFile?.path === change.path && selectedProjectRef.current === targetProject && currentFileRequest === fileRequest.current) {
const file = await api<OpenFile>('/projects/' + targetProject + '/file?path=' + encodeURIComponent(change.path));
if (selectedProjectRef.current === targetProject && currentFileRequest === fileRequest.current) { setOpenFile(file); setDraft(file.content); setEditing(false); setFileLine(null); setFileNotice(''); }
}
notify(action === 'apply' ? '已应用 ' + change.path : '已撤回提案。');
} catch (error) { failure(error); } finally { setChangeBusy(''); }
}
async function refreshBatchFiles() {
const targetProject = selectedProjectRef.current, marker = fileRequest.current, relative = openFile?.path;
await refreshFiles(targetProject);
if (!relative || selectedProjectRef.current !== targetProject || fileRequest.current !== marker) return;
if (editingRef.current) { setFileNotice('文件批次已更新项目;本地编辑草稿保留,请先核对当前文件。'); return; }
try {
const file = await api<OpenFile>('/projects/' + targetProject + '/file?path=' + encodeURIComponent(relative));
if (selectedProjectRef.current === targetProject && fileRequest.current === marker && !editingRef.current) {
setOpenFile(file); setDraft(file.content); setFileLine(null); setFileNotice('');
}
} catch (error) { if (selectedProjectRef.current === targetProject && fileRequest.current === marker) setFileNotice('批次更新后该文件已移除或不可读取,请从文件列表重新选择。'); }
}
async function decide(allow: boolean) {
if (!session || !approval || deciding) return;
setDeciding(true);
try { acceptSession(await api<Session>('/sessions/' + session.id + '/approvals/' + approval.id, { allow })); }
catch (error) { failure(error); } finally { setDeciding(false); }
}
function openSettings() { setSettings(config); setKeyValue(''); setClearKey(false); setModels([]); setModelCheck(null); setSettingsOpen(true); }
async function saveSettings() {
setSettingsBusy(true);
try {
const payload = { ...settings, ...(keyValue || clearKey ? { apiKey: clearKey ? '' : keyValue } : {}) };
const saved = await api<Config>('/config', payload); setConfig(saved); setModelSelection({ type: "legacy", id: "legacy-default", name: "原模型连接" }); setSettingsOpen(false);
notify(saved.mode === 'demo' ? '已切换到离线演示。' : '模型连接已保存。API Key 仅在本次服务内存中使用。');
} catch (error) { failure(error); } finally { setSettingsBusy(false); }
}
async function readModels() {
setSettingsBusy(true);
try {
const result = await api<{ models: string[] }>('/config/models', { baseUrl: settings.baseUrl, ...(keyValue || clearKey ? { apiKey: clearKey ? '' : keyValue } : {}) });
setModels(result.models);
if (!settings.model && result.models[0]) setSettings(previous => ({ ...previous, model: result.models[0] }));
notify('读到 ' + result.models.length + ' 个模型。');
} catch (error) { failure(error); } finally { setSettingsBusy(false); }
}
async function openDiagnostics() {
const targetId = sessionId;
setDiagnosticsOpen(true); setDiagnosticsBusy(true);
if (diagnostics?.session?.session.id !== targetId) setDiagnostics(null);
try { const value = await api<RuntimeDiagnostics>('/diagnostics' + (targetId ? '?session=' + encodeURIComponent(targetId) : '')); if (selectedSessionRef.current === targetId) setDiagnostics(value); }
catch (error) { failure(error); } finally { setDiagnosticsBusy(false); }
}
async function resumeSession() {
if (session?.execution?.workers?.length || session?.execution?.collaborations?.some(value => !['completed', 'discarded', 'resolved_external'].includes(value.status))) { setWorkersOpen(true); return; }
if (!session || resuming || isRunning) return;
setResuming(true);
try { acceptSession(await api<Session>('/sessions/' + session.id + '/resume', {})); }
catch (error) { failure(error); } finally { setResuming(false); }
}
async function continueReviewed() {
if (session?.execution?.workers?.length || session?.execution?.collaborations?.some(value => !['completed', 'discarded', 'resolved_external'].includes(value.status))) { setWorkersOpen(true); return; }
if (!session || resuming || isRunning) return; setResuming(true);
try { acceptSession(await api<Session>('/sessions/' + session.id + '/continue-reviewed', {})); }
catch (error) { failure(error); } finally { setResuming(false); }
}
async function testModel() {
setSettingsBusy(true); setModelCheck(null);
try {
const result = await api<{ ok: boolean; durationMs: number }>('/config/test', { baseUrl: settings.baseUrl, model: settings.model,
...(keyValue || clearKey ? { apiKey: clearKey ? '' : keyValue } : {}) });
setModelCheck({ kind: 'success', message: '模型响应验证通过,用时 ' + (result.durationMs / 1000).toFixed(1) + ' 秒。' });
} catch (error) { setModelCheck({ kind: 'error', message: error instanceof Error ? error.message : String(error) }); }
finally { setSettingsBusy(false); }
}
function failureForMessage(message: { id: string; content: string; createdAt: string }): RuntimeFailure | null {
if (session?.failure?.messageId === message.id) return session.failure;
const recorded = session?.events.filter(event => event.kind === 'error' && event.output === message.content && event.diagnostic).at(-1);
if (recorded?.diagnostic) return recorded.diagnostic;
if (message.content.trim() === 'fetch failed') return { source: 'model_connection', stage: 'model_request', kind: 'network',
title: '模型服务连接失败', message: '工作台在请求模型响应时发生连接失败。已应用改动和执行记录保留。',
detail: '这是旧版的 fetch failed 记录,旧版未保存更具体的连接原因。', suggestion: '可以查看当前运行诊断和模型连接。', occurredAt: message.createdAt, historical: true };
return null;
}
async function openResearch() {
try { setResearchDocs(await api<ResearchDoc[]>('/research')); setReport(await api('/research/overview')); setResearchOpen(true); }
catch (error) { failure(error); }
}
async function openRea() {
const originProject = selectedProjectRef.current, originSession = selectedSessionRef.current;
try {
const target = session || await newSession();
if (target && selectedProjectRef.current === originProject && selectedSessionRef.current === target.id) setReaOpen(true);
} catch (error) { if (selectedProjectRef.current === originProject && selectedSessionRef.current === originSession) failure(error); }
}
async function loadReport(id: string) {
const request = ++reportRequest.current;
try { const document = await api<{ title: string; content: string }>('/research/' + id); if (request === reportRequest.current) setReport(document); }
catch (error) { if (request === reportRequest.current) failure(error); }
}
useEffect(() => {
let alive = true;
api<Bootstrap>('/bootstrap').then(result => {
if (!alive) return;
setToken(result.token); setAccess(result.token); setVersion(result.version); setProjects(result.projects); setBriefs(result.sessions); setConfig(result.config); if (result.modelSelection) setModelSelection(result.modelSelection); setSettings(result.config); setExampleId(result.exampleProjectId);
const savedCursor = Number(sessionStorage.getItem('awb-event-cursor:' + location.origin));
eventCursor.current = Number.isSafeInteger(savedCursor) && savedCursor >= 0 && savedCursor <= (result.eventCursor ?? 0) ? savedCursor : result.eventCursor ?? 0;
for (const brief of result.sessions) revisions.current.set(brief.id, brief.revision);
const savedProject = localStorage.getItem('awb-project');
const id = result.projects.some(project => project.id === savedProject) ? savedProject! : result.exampleProjectId || result.projects[0]?.id || '';
selectedProjectRef.current = id; setProjectId(id);
const savedSession = localStorage.getItem('awb-session');
const session = result.sessions.find(item => item.id === savedSession && item.projectId === id) || result.sessions.find(item => item.projectId === id);
if (session) selectSession(session.id);
}).catch(error => { if (alive) failure(error); });
return () => { alive = false; };
}, []);
useEffect(() => { if (token && projectId) refreshFiles(projectId).catch(failure); }, [token, projectId]);
useEffect(() => {
if (!token) return;
let alive = true, generation = 0;
const refreshSelection = () => {
if (document.visibilityState === 'hidden') return;
const marker = ++generation;
void api<{ config: Config; modelSelection: ModelSelection }>('/model-center/selection').then(value => {
if (alive && marker === generation) { setConfig(value.config); setModelSelection(value.modelSelection); }
}).catch(() => { /* Existing connection status handles host disconnection. */ });
};
window.addEventListener('focus', refreshSelection); document.addEventListener('visibilitychange', refreshSelection);
return () => { alive = false; generation++; window.removeEventListener('focus', refreshSelection); document.removeEventListener('visibilitychange', refreshSelection); };
}, [token]);
useEffect(() => {
if (!token || !sessionId) return;
let alive = true;
api<Session>('/sessions/' + sessionId).then(result => { if (alive) acceptSession(result); }).catch(error => { if (alive) failure(error); });
return () => { alive = false; };
}, [token, sessionId]);
const readyWorkspaceIds = (session?.execution?.workspaces ?? []).filter(value => value.status === 'ready').map(value => value.childProjectId).join(',');
useEffect(() => {
if (!session || !readyWorkspaceIds || readyWorkspaceIds.split(',').every(id => projects.some(value => value.id === id))) return;
let alive = true; const originProject = session.projectId, originSession = session.id;
refreshWorkspaceState(originProject, originSession, () => alive).catch(error => {
if (alive && selectedProjectRef.current === originProject && selectedSessionRef.current === originSession) failure(error);
});
return () => { alive = false; };
}, [session?.id, readyWorkspaceIds]);
useEffect(() => {
if (!token) return;
let alive = true, refreshTimer: ReturnType<typeof setTimeout> | null = null;
async function resync() {
const seen = new Map(revisions.current), current = selectedSessionRef.current;
try {
const [list, selected] = await Promise.all([api<SessionBrief[]>('/sessions'), current ? api<Session>('/sessions/' + current) : Promise.resolve(null)]);
if (!alive) return;
setBriefs(previous => {
const merged = new Map(list.filter(item => !archivedSessions.current.has(item.id)).map(item => [item.id, item]));
for (const item of previous) {
const incoming = merged.get(item.id);
if (!archivedSessions.current.has(item.id) && (incoming && item.revision > incoming.revision || !incoming && item.revision > (seen.get(item.id) ?? -1))) merged.set(item.id, item);
}
return [...merged.values()].sort((a, b) => b.updatedAt.localeCompare(a.updatedAt));
});
if (selected) acceptSession(selected);
} catch (error) { if (alive) failure(error); }
}
function scheduleSync() {
if (refreshTimer !== null) return;
refreshTimer = setTimeout(() => { refreshTimer = null; void resync(); }, 80);
}
const source = new EventSource('/api/events?token=' + encodeURIComponent(token) + '&after=' + eventCursor.current);
source.onopen = () => {
setConnected(true);
scheduleSync();
};
source.onerror = () => setConnected(false);
source.onmessage = event => {
const update = JSON.parse(event.data);
if (update.kind === 'session') acceptSession(update.session as Session);
else if (update.kind === 'session_changed') scheduleSync();
else if (update.kind === 'ready' && update.replayIncomplete) scheduleSync();
const cursor = Number(event.lastEventId || update.seq || update.eventCursor);
if (Number.isSafeInteger(cursor) && cursor >= eventCursor.current) {
eventCursor.current = cursor; sessionStorage.setItem('awb-event-cursor:' + location.origin, String(cursor));
}
};
return () => { alive = false; source.close(); if (refreshTimer !== null) clearTimeout(refreshTimer); };
}, [token]);
useEffect(() => { if (toast) { const timeout = setTimeout(() => setToast(''), 6000); return () => clearTimeout(timeout); } }, [toast]);
useEffect(() => {
const viewport = conversationRef.current;
if (viewport) viewport.scrollTop = viewport.scrollHeight;
}, [session?.messages.length, session?.events.length, approval?.id]);
useEffect(() => {
if (!fileLine || tab !== 'file' || editing) return;
const frame = requestAnimationFrame(() => {
const viewport = codeViewRef.current, line = viewport?.querySelector<HTMLElement>('[data-line="' + fileLine + '"]');
if (viewport && line) viewport.scrollTop += line.getBoundingClientRect().top - viewport.getBoundingClientRect().top - viewport.clientHeight * .35;
});
return () => cancelAnimationFrame(frame);
}, [openFile?.sha256, fileLine, tab, wide, editing]);
useEffect(() => {
let previousMobile = window.innerWidth <= 620;
const update = () => {
const nextMobile = window.innerWidth <= 620;
setNarrow(window.innerWidth <= 940); setMobile(nextMobile); setViewportWidth(window.innerWidth);
if (nextMobile && !previousMobile) { setSidebarOpen(false); setWide(false); }
previousMobile = nextMobile;
};
window.addEventListener('resize', update); return () => window.removeEventListener('resize', update);
}, []);
useEffect(() => {
const handler = (event: KeyboardEvent) => {
if ((event.ctrlKey || event.metaKey) && event.key.toLowerCase() === 'k') { event.preventDefault(); setSidebarOpen(true); setWide(false); requestAnimationFrame(() => filterRef.current?.focus()); }
if (event.key === 'Escape' && !event.defaultPrevented && !document.querySelector('[role="dialog"][aria-modal="true"]')) { if (window.innerWidth <= 940) setWide(false); if (window.innerWidth <= 620) setSidebarOpen(false); }
};
window.addEventListener('keydown', handler); return () => window.removeEventListener('keydown', handler);
}, []);
useEffect(()=>{
if(!inspectorResizing)return;
const move=(event:PointerEvent)=>{const drag=inspectorDrag.current;if(!drag)return;const sidebar=sidebarOpen?(window.innerWidth>=1700?260:window.innerWidth<=1120?210:242):0;
setInspectorWidth(Math.max(310,Math.min(Math.max(310,Math.min(1000,window.innerWidth-sidebar-320)),drag.width+drag.x-event.clientX)));};
const finish=()=>{inspectorDrag.current=null;setInspectorResizing(false);};
// Removing a native child view can release Chromium's pointer capture.
// Keep the drag on the main window until release/cancel rather than losing
// its original start point when that native focus transition occurs.
window.addEventListener('pointermove',move);window.addEventListener('pointerup',finish);window.addEventListener('pointercancel',finish);window.addEventListener('blur',finish);
return()=>{window.removeEventListener('pointermove',move);window.removeEventListener('pointerup',finish);window.removeEventListener('pointercancel',finish);window.removeEventListener('blur',finish);};
},[inspectorResizing,sidebarOpen]);
const entries = [...(session?.messages || []).map(message => ({ id: message.id, date: message.createdAt, message })),
...(session?.events || []).filter(event => event.kind !== 'error').map(event => ({ id: event.id, date: event.createdAt, event }))].sort((a, b) => a.date.localeCompare(b.date));
const toolEvents = session?.events.filter(event => event.kind === 'tool') || [];
const lineCount = openFile?.content.split('\n').length || 0;
const ready = !!token && connected;
const sidebarWidth=sidebarOpen?(viewportWidth>=1700?260:viewportWidth<=1120?210:242):0;
const maximumInspector=Math.max(310,Math.min(1000,viewportWidth-sidebarWidth-320));
const resizeInspector=(width:number)=>setInspectorWidth(Math.max(310,Math.min(maximumInspector,width)));
return (
<div className={'workbench ' + (sidebarOpen ? '' : 'sidebar-hidden ') + (wide ? 'inspector-wide ' : '')+(inspectorResizing?'inspector-resizing':'')}
style={!narrow&&inspectorWidth!==null?{gridTemplateColumns:sidebarWidth+'px minmax(310px,1fr) '+Math.min(maximumInspector,inspectorWidth)+'px'}:undefined}>
<aside className="project-sidebar">
<div className="brand"><span className="brand-mark">AW</span><div><strong>Agent Workbench</strong><span>本地编程工作台 · 正式版</span></div><IconButton label="收起项目栏" onClick={() => setSidebarOpen(false)}><PanelLeftClose size={16} /></IconButton></div>
<div className="project-selector"><span className="field-eyebrow">当前项目</span><div className="project-select-row"><FolderOpen size={17} /><select aria-label="当前项目" value={projectId} onChange={event => chooseProject(event.target.value)}>{projects.map(project => <option key={project.id} value={project.id}>{project.name}{project.id === exampleId ? '(示例)' : ''}</option>)}{!projects.length && <option value="">选择一个项目</option>}</select><IconButton label="打开项目" onClick={() => setProjectOpen(true)}><Plus size={15} /></IconButton></div>{selectedProject && <span className="project-root" title={selectedProject.root}>{selectedProject.root}</span>}{projectId === exampleId && <span className="example-tag">当前为自带示例,可打开自己的项目开始开发</span>}</div>
<div className="sidebar-section sessions-section"><div className="section-label"><span>任务会话</span><IconButton label="新建任务" disabled={creatingSession || restrictedWorker} onClick={() => newSession().catch(failure)}><Plus size={15} /></IconButton></div>
<button type="button" className="new-task-button" disabled={creatingSession || restrictedWorker} onClick={() => newSession().catch(failure)}><Plus size={15} />新建任务<span>↵</span></button>
<div className="session-list">{projectSessions.slice(0, 15).map(item => <div key={item.id} className={'session-item ' + (item.id === sessionId ? 'selected' : '')}>
<button type="button" className="session-select" onClick={() => chooseSession(item.id)}><MessageSquare size={14} /><span>{item.title}</span>{item.changeCount > 0 && <b>{item.changeCount}</b>}</button>
{!activeStates.includes(item.status) && <IconButton label={'归档会话 ' + item.title} onClick={() => api('/sessions/' + item.id + '/archive', {}).then(() => { if (item.id === selectedSessionRef.current) selectSession(''); }).catch(failure)}><Trash2 size={12} /></IconButton>}
</div>)}{!projectSessions.length && <p className="sidebar-hint">开始一个任务,过程会自动保存。</p>}</div>
</div>
<div className="sidebar-section file-section"><div className="section-label"><span>项目文件 <b>{files.filter(file => file.kind === 'file').length}</b></span><IconButton label="刷新文件" onClick={() => refreshFiles().catch(failure)}><Folder size={14} /></IconButton></div>
<div className="file-filter"><Search size={14} /><input ref={filterRef} value={filter} onChange={event => setFilter(event.target.value)} placeholder="筛选文件" aria-label="筛选文件" /><kbd>⌃ K</kbd></div>
<div className="file-tree">{visibleFiles.map(file => <button key={file.path} type="button" title={file.path} className={'tree-row ' + (openFile?.path === file.path ? 'selected' : '')} style={{ paddingLeft: 10 + Math.min(file.path.split('/').length - 1, 6) * 13 }} onClick={() => {
if (file.kind === 'directory') setCollapsed(previous => { const next = new Set(previous); if (next.has(file.path)) next.delete(file.path); else next.add(file.path); return next; }); else loadFile(file.path);
}}>{file.kind === 'directory' ? <><span className="tree-chevron">{collapsed.has(file.path) ? <ChevronRight size={11} /> : <ChevronDown size={11} />}</span><Folder size={14} /></> : <><span className="tree-chevron" /><File size={13} /></>}<span>{filter ? file.path : file.name}</span></button>)}{filter && !visibleFiles.length && <p className="sidebar-hint">没有匹配的文件。</p>}</div>
</div>
<div className="sidebar-footer"><button onClick={openResearch}><BookOpenText size={16} />机制研究与设计<ChevronRight size={13} /></button><button onClick={() => setMemoryOpen(true)} disabled={!selectedProject || restrictedWorker}><Brain size={16} />项目记忆<ChevronRight size={13} /></button><button onClick={() => openDiagnostics()}><Activity size={16} />运行诊断<ChevronRight size={13} /></button><button className="model-sidebar-entry" onClick={() => setModelCenterOpen(true)} aria-label="选择与管理模型"><ModelServer size={16} /><span>模型与连接<small>{config.mode === 'demo' ? '离线演示' : modelSelection.type === 'legacy' ? config.model || '尚未配置' : modelSelection.name}</small></span><ChevronRight size={13} /></button><div className={'connection ' + (ready ? 'connected' : '')}><span />{ready ? '本地服务已连接' : '正在连接本地服务'}<button className="version-entry" aria-label="版本与更新" onClick={() => setInstallationOpen(true)}>v{version}</button></div></div>
</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"><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' : '')} aria-label="切换当前模型" title="选择模型、模型池或添加连接" onClick={() => setModelCenterOpen(true)}><span className="model-light" />{config.mode === 'demo' ? '离线演示' : modelSelection.type !== 'legacy' ? modelSelection.name : 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>
<IconButton label="项目技能" onClick={() => setSkillsOpen(true)} disabled={!selectedProject || restrictedWorker}><BookOpenText size={15} /></IconButton>
<IconButton label="项目MCP工具" onClick={() => setMcpOpen(true)} disabled={!selectedProject || restrictedWorker}><Puzzle size={15} /></IconButton>
<IconButton label="查看任务记录" onClick={() => showInspector('task')}><ClipboardCheck size={15} /></IconButton>
<IconButton label="隔离协作" onClick={() => setWorkersOpen(true)} disabled={!session}><GitBranch size={15} /></IconButton>
<IconButton label="工程评测" onClick={() => setEvaluationsOpen(true)} disabled={!session || restrictedWorker}><ClipboardCheck size={15} /></IconButton>
<IconButton label="本地代理引擎" onClick={() => setEngineOpen(true)} disabled={!session || restrictedWorker && !session.execution?.workers?.some(value => value.engine)}><Link2 size={15} /></IconButton>
<IconButton label="REA 工件研究" onClick={() => void openRea()} disabled={!selectedProject || creatingSession || restrictedWorker}><BookOpenText size={15} /></IconButton>
{narrow && <><IconButton label="查看文件" onClick={() => showInspector('file')}><FileCode2 size={16} /></IconButton><IconButton label="查看改动" onClick={() => showInspector('changes')}><GitBranch size={16} /></IconButton><IconButton label="查看执行轨迹" onClick={() => showInspector('trace')}><SquareTerminal size={16} /></IconButton></>}
{pending.length > 0 && <button className="text-button review-toolbar" onClick={() => { setChangeId(pending[0].id); showInspector('changes'); }}><FileCode2 size={13} />审核 {pending.length} 项</button>}
{session && <><IconButton label="导出会话" onClick={() => exportSession(session.id).catch(failure)}><ArrowDownToLine size={15} /></IconButton>
{!isRunning && pending.length === 0 && ['failed', 'paused'].includes(session.status) && <button className="text-button" disabled={resuming} onClick={() => resumeSession()}><RotateCw size={13} />{session.status === 'failed' && session.failure?.source === 'model_connection' ? '重试模型请求' : '继续任务'}</button>}</>}
</div></div>
<section ref={conversationRef} className="conversation" aria-label="任务对话">
{!session?.messages.length && !session?.events.length ? <div className="welcome"><span className="welcome-label"><span />从项目到结果</span><h2>读懂项目。<br />把每一步做好。</h2><p>给出一个任务,读取依据、工具执行和文件改动会在这里连成完整过程。</p><div className="starter-prompts">{['了解这个项目,并提出一项改进', '查找关键实现,解释调用关系', '检查项目,并准备可审查的修改'].map((prompt, index) => <button key={prompt} onClick={() => { setComposer(prompt); composerRef.current?.focus(); }}><span>{index === 0 ? <FolderOpen size={17} /> : index === 1 ? <Link2 size={17} /> : <FileCode2 size={17} />}</span>{prompt}<ArrowRight size={14} /></button>)}</div><div className="welcome-note"><ShieldCheck size={16} /><span>文件修改先审查,终端命令逐次确认。</span></div>{config.mode === 'demo' && <div className="demo-note"><span>演示</span>固定脚本会调用真实本地工具,不进行模型推理。</div>}</div> : <div className="conversation-entries">
{session?.recoveryNotice && <div className="recovery-note"><ShieldCheck size={16} /><div><strong>已恢复会话记录</strong><p>{session.recoveryNotice}</p></div></div>}
{entries.map(entry => 'message' in entry && entry.message ? <div key={entry.id} className={'message message-' + entry.message.role}><span className="message-avatar">{entry.message.role === 'user' ? '你' : entry.message.role === 'assistant' ? 'AW' : '·'}</span><div className="message-body"><div className="message-label">{entry.message.role === 'user' ? '你的任务' : entry.message.role === 'assistant' ? session?.executionMode === 'demo' ? '演示执行器' : '编程助手' : '工作台'}<time>{new Date(entry.date).toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })}</time></div><div className="message-text">{entry.message.role === 'system' && failureForMessage(entry.message)
? <FailureCard failure={failureForMessage(entry.message)!} onDiagnose={() => openDiagnostics()} onRetry={session?.status === 'failed' && session?.failure?.messageId === entry.message.id ? () => resumeSession() : undefined} busy={resuming || isRunning} />
: entry.message.role === 'assistant' ? <ResearchContent content={entry.message.content} /> : entry.message.content}</div>{entry.message.attachmentIds?.map(id=>{const image=session?.inputAttachments?.find(value=>value.id===id);return image&&session?<InputImage key={id} sessionId={session.id} image={image} onError={failure}/>:null;})}</div></div> : 'event' in entry && entry.event ? <div key={entry.id} className="inline-event">{['tool', 'model'].includes(entry.event.kind) ? <><ToolRow event={entry.event} onSelect={() => { setEventId(entry.event!.id); showInspector('trace'); }} /><ModelStreamPreview event={entry.event} /></> : <div className={'system-event event-' + entry.event.phase}><span />{entry.event.label}{entry.event.output && <p>{entry.event.output}</p>}</div>}</div> : null)}
{isRunning && !approval && <div className="working-note"><LoaderCircle size={14} className="spin" /><span>{session?.executionMode === 'demo' ? '正在执行演示流程' : '正在处理任务'}</span></div>}
</div>}
{session&&<BudgetPausePanel key={session.id+session.execution?.run?.id} session={session} config={config} onSession={acceptSession} onRecovery={()=>setWorkersOpen(true)}/>}
{approval && <div className="approval-card"><div className="approval-heading"><span><ShieldCheck size={17} /></span><div><strong>{approvalPresentation(approval).title}</strong><p>{approval.reason}</p></div></div><pre>{approval.command}</pre>
{approval.environmentSummary&&<div className="approval-shell"><p>所属工作区:{approval.environmentSummary.root}</p><p>注册源:{approval.environmentSummary.registry} · {approval.environmentSummary.offline?'只使用缓存':'允许下载'} · {Math.round(approval.environmentSummary.timeoutMs/1000)} 秒</p><strong>{approval.environmentSummary.scripts==='skip'?'跳过全部安装脚本':'允许根工程及依赖安装脚本'}</strong><details><summary>安装脚本范围</summary>{approval.environmentSummary.lifecycle.map(row=><div key={row.name}><strong>{row.name}</strong><pre>{row.script}</pre></div>)}<p>锁文件标记 {approval.environmentSummary.installScriptPackages.length} 个包带安装脚本;下载前无法读取其正文。</p></details><p>准备完成后仍需实际工程检查。停止后保留部分依赖,原计划不会自动重放。</p></div>}
{approval.checkScripts?.filter(check => check.python).map(check => <p className="approval-shell" key={check.name}>Python {check.python!.runtime.version || '执行时核对版本'} · {check.python!.runtime.logicalExecutable || check.python!.runtime.executable || '解释器缺失'}</p>)}
<div className="approval-path"><Folder size={12} /><span>{approval.cwd}</span></div><p className="approval-shell">{approval.shell || '项目终端'} · UTF-8</p><p className="approval-scope">{approvalPresentation(approval).scope}</p><div className="approval-actions"><button className="button secondary" onClick={() => decide(false)} disabled={deciding}>拒绝执行</button><button className="button primary" onClick={() => decide(true)} disabled={deciding}><Play size={14} />确认执行</button></div></div>}
{pending.length > 0 && !isRunning && <button className="review-callout" onClick={() => { setChangeId(pending[0].id); showInspector('changes'); }}><FileCode2 size={17} /><span><strong>{pending.length} 项改动等待审查</strong><small>查看差异后,再应用到项目文件。</small></span><ArrowRight size={17} /></button>}
{canContinueReview && <button type="button" aria-label="继续原任务" className="review-callout" disabled={resuming} onClick={continueReviewed}><ClipboardCheck size={17} /><span><strong>继续原任务</strong><small>改动已应用,保留原目标、范围和检查约定继续处理。</small></span><ArrowRight size={17} /></button>}
<div ref={chatEnd} />
</section>
<footer className="composer-wrap"><form className="composer" onSubmit={event => { event.preventDefault(); submit(); }}><AttachmentComposer session={session} selectedIds={imageSelection.sessionId===session?.id?imageSelection.ids:[]} onSelection={(id,ids)=>setImageSelection({sessionId:id,ids})} onEnsureSession={newSession} onSession={acceptSession} onError={failure} disabled={isRunning||sending||creatingSession||!ready||restrictedWorker} routeName={modelSelection.type==='legacy'?'原模型连接':modelSelection.name} onModels={()=>setModelCenterOpen(true)}/><textarea ref={composerRef} aria-label="任务内容" placeholder={config.mode === 'demo' ? '先体验完整流程,或连接自己的模型开始开发…' : '描述项目任务,或询问工作台的执行状态与报错…'} value={composer} onChange={event => setComposer(event.target.value)} onKeyDown={event => { if ((event.ctrlKey || event.metaKey) && event.key === 'Enter') { event.preventDefault(); submit(); } }} maxLength={20000} rows={3} /><div className="composer-bottom"><span><Folder size={13} />{selectedProject?.name || '选择项目'}<span className="composer-divider" />{config.mode === 'demo' ? '固定演示脚本' : modelSelection.type !== 'legacy' ? modelSelection.name : '兼容模型服务'}</span>{isRunning ? <button type="button" className="stop-button" onClick={() => session && api('/sessions/' + session.id + '/stop', {}).catch(failure)}><Square size={13} />停止</button> : <button type="submit" className="send-button" aria-label="发送任务" disabled={!composer.trim() || sending || creatingSession || !ready || !!(sessionId && !session)}>{sending ? <LoaderCircle size={17} className="spin" /> : <ArrowUp size={18} />}</button>}</div></form><div className="composer-footnote"><span>Ctrl + Enter 发送 · 会话自动保存</span><span>{session?.estimatedTokens ? '上下文估算 ' + session.estimatedTokens.toLocaleString() + ' tokens' : '改动与执行结果可追溯'}</span></div></footer>
</main>
{((mobile && sidebarOpen) || (narrow && wide)) && <button type="button" className="panel-scrim" aria-label="关闭侧边面板" onClick={() => { setSidebarOpen(false); setWide(false); }} />}
<aside className="inspector">
{!narrow&&<div className="inspector-resize-handle" role="separator" aria-label="调整检视区宽度" aria-orientation="vertical" tabIndex={0} aria-valuemin={310} aria-valuemax={maximumInspector} aria-valuenow={inspectorWidth??undefined}
onPointerDown={event=>{if(event.button!==0)return;event.preventDefault();inspectorDrag.current={x:event.clientX,width:event.currentTarget.parentElement!.getBoundingClientRect().width};event.currentTarget.setPointerCapture(event.pointerId);setInspectorResizing(true);}}
onDoubleClick={()=>setInspectorWidth(null)}
onKeyDown={event=>{const width=event.currentTarget.parentElement!.getBoundingClientRect().width;if(event.key==='ArrowLeft'||event.key==='ArrowRight'){event.preventDefault();resizeInspector(width+(event.key==='ArrowLeft'?32:-32));}else if(event.key==='Home'){event.preventDefault();resizeInspector(310);}else if(event.key==='End'){event.preventDefault();resizeInspector(maximumInspector);}}}/>}
<div className="inspector-tabs"><button className={tab === 'file' ? 'selected' : ''} onClick={() => setTab('file')}><FileCode2 size={14} />文件</button><button className={tab === 'changes' ? 'selected' : ''} onClick={() => setTab('changes')}><GitBranch size={14} />改动{pending.length > 0 && <b>{pending.length}</b>}</button><button className={tab === 'trace' ? 'selected' : ''} onClick={() => setTab('trace')}><SquareTerminal size={14} />轨迹</button><button className={tab === 'task' ? 'selected' : ''} onClick={() => setTab('task')}><ClipboardCheck size={14} />任务</button><button className={tab === 'index' ? 'selected' : ''} onClick={() => setTab('index')}><Search size={14} />索引</button><button className={tab === 'browse' ? 'selected' : ''} onClick={() => setTab('browse')}><Link2 size={14} />浏览</button><IconButton label={narrow ? '关闭检视区' : wide ? '缩小检视区' : '放大检视区'} onClick={() => setWide(previous => !previous)}>{narrow ? <X size={16} /> : wide ? <Minimize2 size={14} /> : <Maximize2 size={14} />}</IconButton></div>
{tab === 'file' && (fileLoading ? <div className="loading-inspector"><LoaderCircle className="spin" size={24} />正在读取文件</div> : openFile ? <div className="file-inspector"><div className="file-heading"><FileCode2 size={15} /><span title={openFile.path}>{openFile.path}</span>{/\.html?$/i.test(openFile.path) && <div className="file-mode-switch" role="group" aria-label="文件显示方式"><button type="button" aria-pressed={fileMode === 'preview'} disabled={editing} onClick={() => setFileMode('preview')}>预览</button><button type="button" aria-pressed={fileMode === 'source'} onClick={() => { setFileMode('source'); setEditing(false); }}>源码</button></div>}<IconButton label="复制文件内容" onClick={() => navigator.clipboard.writeText(openFile.content).then(() => notify('已复制文件内容。')).catch(failure)}><Copy size={14} /></IconButton><IconButton label={editing ? '取消编辑' : '编辑文件'} onClick={() => { setFileMode('source'); setEditing(previous => !previous); setDraft(openFile.content); }}><Pencil size={14} /></IconButton></div><div className="file-details"><span>{lineCount} 行 · {openFile.bytes.toLocaleString()} B{fileLine ? ' · 定位第 ' + fileLine + ' 行' : ''}</span><span className="code-utility">{openFile.sha256.slice(0, 10)}</span></div>{fileNotice && <div className="file-index-notice" role="status">{fileNotice}</div>}{editing ? <><textarea className="code-editor" aria-label="编辑文件内容" spellCheck={false} value={draft} onChange={event => setDraft(event.target.value)} /><div className="editor-actions"><button className="button primary" onClick={saveDraft} disabled={draft === openFile.content || draftSaving}><GitBranch size={14} />保存为提案</button></div></> : fileMode === 'preview' && /\.html?$/i.test(openFile.path) ? <HtmlFilePreview key={projectId + ':' + openFile.path} projectId={projectId} path={openFile.path} /> : <div className="code-view" ref={codeViewRef}>{openFile.content.split('\n').map((line, index) => <div key={index} data-line={index + 1} className={fileLine === index + 1 ? 'code-line-target' : ''}><span>{index + 1}</span><code>{line.replace(/\r$/, '') || ' '}</code></div>)}</div>}</div> : <EmptyInspector kind="file" />)}
{tab === 'changes' && (session ? <ChangesInspector session={session} selectedChange={selectedChange} busy={!!changeBusy} isRunning={isRunning} onSelect={setChangeId} onAction={changeAction} onSession={acceptSession} onError={failureFor(session)} onFilesChanged={refreshBatchFiles} /> : <EmptyInspector kind="changes" />)}
{tab === 'trace' && (session?.events.length ? <div className="trace-inspector"><div className="trace-caption"><span>完整执行记录</span><span>{toolEvents.length} 次工具调用</span></div><div className="trace-list">{session.events.map(event => <ToolRow key={event.id} event={event} selected={selectedEvent?.id === event.id} onSelect={() => setEventId(event.id)} />)}</div>{selectedEvent && <div className="event-details"><div className="event-detail-heading"><strong>{selectedEvent.label}</strong><Status value={selectedEvent.phase} /></div>{selectedEvent.input && <><h4>输入</h4><pre>{JSON.stringify(selectedEvent.input, null, 2)}</pre></>}<h4>结果</h4><pre>{selectedEvent.output || (selectedEvent.phase === 'waiting' ? '等待确认后执行。' : '正在等待工具结果。')}</pre>{selectedEvent.durationMs !== undefined && <p className="subtle">耗时 {(selectedEvent.durationMs / 1000).toFixed(2)} 秒,包含确认等待。</p>}</div>}</div> : <EmptyInspector kind="trace" />)}
{tab === 'task' && (session && selectedProject ? <TaskPanel key={session.id} project={selectedProject} session={session} onSession={acceptSession} onError={failureFor(session)} busy={isRunning} onWorkspaceRefresh={refreshWorkspaceState} onWorkspaceNavigate={navigateWorkspace} onOpenPreview={()=>showInspector('browse')} /> : <EmptyInspector kind="trace" />)}
{tab === 'browse' && session && selectedProject && <EmbeddedBrowserPanel key={session.id} project={selectedProject} session={session} onSession={acceptSession} onError={failureFor(session)} onReturn={()=>setTab('task')}/> }
{selectedProject && <CodeIndexPanel key={selectedProject.id} project={selectedProject} active={tab === 'index'} onOpen={(path, line, expectedSha256) => void loadFile(path, { line, expectedSha256 })} />}
<div className="inspector-footer"><ShieldCheck size={13} /><span>{tab === 'changes' ? '应用前会核对文件基线' : tab === 'trace' ? '中断调用保留待核实状态' : tab === 'task' ? '任务目标、检查与结果持久保存' : tab === 'index' ? '结果绑定当前项目及文件 SHA256' : '读取范围限定在当前项目'}</span></div>
</aside>
{installationOpen && <Modal title="版本与更新" description="核对本机版本、真实更新阶段与原始结果。" onClose={() => setInstallationOpen(false)}><InstallationStatus /></Modal>}
{projectOpen && <Modal title="打开项目" description="选择这台电脑上的项目文件夹,或输入完整路径。" onClose={() => { if (!projectBusy) { setProjectOpen(false); setDirectoryPickerOpen(false); setProjectError(''); } }}><form onSubmit={event => { event.preventDefault(); if (!directoryPickerOpen) void openProject(); }}><label className="form-field">项目文件夹<input autoFocus value={projectInput} disabled={projectBusy} onChange={event => { setProjectInput(event.target.value); setProjectError(''); }} placeholder="C:\Projects\my-app" aria-label="项目文件夹路径" /></label>{projectError && <p className="local-files-error" role="alert">{projectError}</p>}{directoryPickerOpen && <ProjectDirectoryPicker initialPath={projectInput.trim()} onChoose={value => { setProjectInput(value); setProjectError(''); setDirectoryPickerOpen(false); }} onCancel={() => setDirectoryPickerOpen(false)} />}<div className="modal-actions"><button type="button" className="button secondary" disabled={pickingProject || projectBusy} onClick={() => desktop ? void pickDesktopProject() : setDirectoryPickerOpen(value => !value)}><FolderOpen size={15} />选择文件夹</button>{exampleId && <button type="button" className="button secondary" disabled={projectBusy} onClick={() => { chooseProject(exampleId); setProjectOpen(false); setDirectoryPickerOpen(false); }}>打开示例项目</button>}<button type="submit" className="button primary" disabled={!projectInput.trim() || projectBusy || directoryPickerOpen}>{projectBusy ? <LoaderCircle className="spin" size={15} /> : <FolderOpen size={15} />}{projectBusy ? '正在打开…' : '打开项目'}</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>}</>}
<details className="budget-settings"><summary>上下文与任务预算<ChevronDown size={13} /></summary><div className="budget-fields"><label>上下文预算<input type="number" min={1000} max={200000} value={settings.contextLimit} onChange={event => setSettings(previous => ({ ...previous, contextLimit: Number(event.target.value) }))} /></label><label>最大工具轮次<input type="number" min={1} max={30} value={settings.maxSteps} onChange={event => setSettings(previous => ({ ...previous, maxSteps: Number(event.target.value) }))} /></label><label>输出上限<input type="number" min={256} max={16000} value={settings.maxOutputTokens} onChange={event => setSettings(previous => ({ ...previous, maxOutputTokens: Number(event.target.value) }))} /></label><label>运行时间(分钟)<input aria-label="运行时间预算" type="number" min={1} max={60} value={settings.maxRunDurationMs / 60000} onChange={event => setSettings(previous => ({ ...previous, maxRunDurationMs: Number(event.target.value) * 60000 }))} /></label><label>单次运行 tokens<input aria-label="单次运行token预算" type="number" min={1000} max={2000000} value={settings.maxRunTokens} onChange={event => setSettings(previous => ({ ...previous, maxRunTokens: Number(event.target.value) }))} /></label><label>任务累计 tokens<input aria-label="任务累计token预算" type="number" min={1000} max={10000000} value={settings.maxTaskTokens} onChange={event => setSettings(previous => ({ ...previous, maxTaskTokens: Number(event.target.value) }))} /></label></div><p>上下文使用本地估算;实际用量与未知用量分开保存。达到预算会暂停,已完成的工具结果保留。</p></details>{anyRunning && <p className="form-warning">有任务在执行,请先停止任务再改变连接。</p>}<div className="modal-actions"><button type="button" className="button secondary" onClick={() => setSettingsOpen(false)}>取消</button><button type="submit" className="button primary" disabled={settingsBusy || anyRunning}><Check size={15} />保存并切换原连接</button></div></form></Modal>}
{diagnosticsOpen && <Modal title="运行诊断" description="查看工作台的模型连接、终端环境、最近错误和文件实际状态。" wide onClose={() => setDiagnosticsOpen(false)}><DiagnosticsPanel value={diagnostics} busy={diagnosticsBusy} onRefresh={() => openDiagnostics()} /></Modal>}
{reaOpen && session && selectedProject && <Modal title="REA 工件研究" description="原分析与同一项目、任务和运行绑定。" wide onClose={() => setReaOpen(false)}><ResearchPanel key={session.id} project={selectedProject} session={session} onSession={acceptSession} onError={failureFor(session)} busy={isRunning} /></Modal>}
{engineOpen && session && selectedProject && <Modal title="本地代理引擎" description="本地安装、受控工程运行与原记录。" wide onClose={() => setEngineOpen(false)}><EnginePanel key={session.id} project={selectedProject} session={session} onSession={acceptSession} onError={failureFor(session)} busy={isRunning} onNavigate={async (projectId, sessionId) => { setEngineOpen(false); await navigateWorkspace(projectId, sessionId); }} /></Modal>}
{researchOpen && <Modal title="机制研究与独立设计" description="从分发客户端的静态证据提炼产品机制。运行时与远端服务的未知部分在报告中说明。" wide onClose={() => setResearchOpen(false)}><div className="research-layout"><nav>{researchDocs.map(document => <button className={report?.title === document.title ? 'selected' : ''} key={document.id} onClick={() => loadReport(document.id)}><BookOpenText size={15} /><span><strong>{document.title}</strong><small>{document.description}</small></span></button>)}</nav><article className="research-document">{report && <ResearchContent content={report.content} />}</article></div></Modal>}
{modelCenterOpen && <Modal title="模型中心" description="连接、模型池与执行健康统一管理。" wide onClose={() => setModelCenterOpen(false)}><ModelCenter busy={anyRunning} runModel={session?.execution?.run?.model} onConfig={(value, selection) => { setConfig(value); if (selection) setModelSelection(selection); }} onLegacy={() => { setModelCenterOpen(false); openSettings(); }} /></Modal>}
{memoryOpen && selectedProject && <Modal title="项目记忆" description="项目事实与决策绑定源码指纹,变化后自动要求重新核对。" wide onClose={() => setMemoryOpen(false)}><ProjectMemoryPanel key={selectedProject.id + ':' + (session?.id ?? '')} project={selectedProject} session={session?.projectId === selectedProject.id ? session : null} /></Modal>}
{skillsOpen && selectedProject && <Modal title="项目技能" description="管理当前项目的技能来源、版本与启用状态。" wide onClose={() => setSkillsOpen(false)}><SkillCenter key={selectedProject.id} projectId={selectedProject.id} busy={isRunning} /></Modal>}
{mcpOpen && selectedProject && <Modal title="项目 MCP 工具" description="实际探测本地 stdio 服务,选择可以请求的工具,并核对每次运行原记录。" wide onClose={() => setMcpOpen(false)}><McpPanel key={selectedProject.id + ':' + (session?.id ?? '')} projectId={selectedProject.id} session={session?.projectId === selectedProject.id ? session : null} busy={isRunning} onSession={acceptSession} onError={session ? failureFor(session) : failure} /></Modal>}
{workersOpen && session && <Modal title="隔离协作" description="固定父子目标、独立工作区、预算与原成果审查。" wide onClose={() => setWorkersOpen(false)}><WorkerPanel key={session.id} session={session} config={config} busy={isRunning} onSession={acceptSession} onNavigate={async (projectId, sessionId, view) => { setWorkersOpen(false); await navigateWorkspace(projectId, sessionId, () => true, view); }} onReview={() => { setWorkersOpen(false); showInspector('changes'); }} /></Modal>}
{evaluationsOpen && session && <Modal title="工程质量评测" description="固定需求与测试,比较原版和候选,审查后交付。" wide onClose={() => setEvaluationsOpen(false)}><EvaluationPanel key={session.id} session={session} config={config} busy={isRunning} onSession={acceptSession} onNavigate={async (projectId, sessionId, view) => { setEvaluationsOpen(false); await navigateWorkspace(projectId, sessionId, () => true, view); }} onReview={() => { setEvaluationsOpen(false); showInspector('changes'); }} onRecovery={() => { setEvaluationsOpen(false); setWorkersOpen(true); }} /></Modal>}
{toast && <div className="toast" role="status"><span>{toast}</span><IconButton label="关闭提示" onClick={() => setToast('')}><X size={14} /></IconButton></div>}
</div>
);
}
@@ -0,0 +1,59 @@
.browser-panel { min-width: 0; }
.browser-intro { color: var(--muted); line-height: 1.8; font-size: 12px; margin: 4px 0 14px; }
.browser-missing { font-size: 12px; color: #8b5734; background: #fbf6ee; padding: 12px; border: 1px solid #e6d6c4; line-height: 1.8; }
.browser-plan-editor { border: 1px solid var(--line); border-radius: 6px; background: var(--paper); }
.browser-plan-editor > summary { cursor: pointer; padding: 13px 14px; font-size: 12px; font-weight: 600; }
.browser-plan-editor form { padding: 0 14px 14px; }
.browser-fields { display: grid; grid-template-columns: 1fr .8fr 1.3fr; gap: 10px; }
.browser-fields label { font-size: 11px; display: flex; gap: 6px; flex-direction: column; color: var(--muted); min-width: 0; }
.browser-panel input, .browser-panel select { min-width: 0; width: 100%; border: 1px solid var(--line); border-radius: 4px; padding: 8px; background: #fff; color: var(--ink); font-size: 11px; }
.browser-panel input:focus-visible, .browser-panel select:focus-visible { outline: 2px solid #8ebbb0; outline-offset: 1px; }
.browser-step-heading { display: flex; align-items: center; justify-content: space-between; margin: 18px 0 10px; }
.browser-step-heading strong { font-size: 11px; font-weight: 600; }
.browser-step-heading strong span { color: var(--muted); margin-left: 5px; font-weight: 400; }
.browser-step-empty { font-size: 11px; color: var(--muted); line-height: 1.8; padding: 10px 0 14px; }
.browser-step { display: grid; grid-template-columns: 16px 88px minmax(0, 1fr) minmax(70px, .8fr) 26px; gap: 6px; align-items: center; margin-bottom: 9px; }
.browser-step-number { color: var(--teal); font-size: 11px; }
.browser-step-value { color: var(--muted); font-size: 10px; }
.browser-plan-editor form > .button { margin-top: 8px; }
.browser-panel .button { font-size: 11px; padding: 8px 11px; }
.browser-panel .text-button { font-size: 11px; }
.browser-sealed-plan { margin-top: 12px; background: #f0f6f3; border: 1px solid #cdded6; border-left: 3px solid var(--teal); padding: 13px 14px; border-radius: 5px; }
.browser-sealed-plan > div { display: flex; align-items: center; gap: 12px; justify-content: space-between; font-size: 12px; }
.browser-sealed-plan code { color: var(--teal); font-size: 10px; overflow-wrap: anywhere; }
.browser-sealed-plan p, .browser-sealed-plan details { font-size: 11px; color: var(--muted); line-height: 1.8; margin: 8px 0; overflow-wrap: anywhere; }
.browser-sealed-plan summary, .browser-actual-steps summary { cursor: pointer; }
.browser-sealed-plan ol, .browser-confirm ol { padding-left: 20px; line-height: 1.9; overflow-wrap: anywhere; }
.browser-plan-used { font-size: 10px; color: var(--muted); display: block; margin-top: 9px; }
.browser-results { margin-top: 21px; }
.browser-results h4 { font-size: 12px; font-weight: 600; margin: 0 0 10px; }
.browser-result { border-top: 1px solid var(--line); padding: 14px 0; min-width: 0; }
.browser-result-heading { display: flex; justify-content: space-between; align-items: center; gap: 9px; }
.browser-result-heading > strong { font-size: 12px; }
.browser-result > p { font-size: 11px; color: var(--muted); line-height: 1.8; overflow-wrap: anywhere; margin: 8px 0; }
.browser-result-source { display: flex; flex-wrap: wrap; gap: 8px 13px; font-size: 10px; color: #42685e; margin: 9px 0; }
.browser-assertions { color: #42685e !important; }
.browser-actual-steps { font-size: 11px; color: var(--muted); margin: 8px 0 12px; }
.browser-actual-steps ol { list-style: none; padding: 0; margin-top: 10px; }
.browser-actual-steps li { display: flex; align-items: flex-start; flex-wrap: wrap; gap: 7px; padding: 7px 0; border-top: 1px solid #edf2ef; line-height: 1.7; }
.browser-actual-steps li > span { overflow-wrap: anywhere; min-width: 0; }
.browser-actual-steps small { display: block; width: 100%; color: #a34d35; overflow-wrap: anywhere; }
.browser-result-actions { display: flex; flex-wrap: wrap; gap: 9px 14px; align-items: center; }
.browser-confirm { font-size: 12px; line-height: 1.8; }
.browser-confirm > code { display: block; color: var(--teal); overflow-wrap: anywhere; font-size: 10px; }
.browser-image-preview { overflow: auto; max-height: 64vh; background: #edf3f1; padding: 9px; border: 1px solid var(--line); text-align: center; }
.browser-image-preview img { max-width: 100%; height: auto; vertical-align: top; background: white; }
@media (max-width: 940px) {
.browser-step { grid-template-columns: 16px 100px minmax(0, 1fr) 26px; }
.browser-step > :nth-child(4) { grid-column: 2 / 4; grid-row: 2; }
.browser-step > :last-child { grid-column: 4; grid-row: 1; }
}
@media (max-width: 620px) {
.browser-fields { grid-template-columns: 1fr 1fr; }
.browser-fields > :last-child { grid-column: 1 / 3; }
.browser-result-heading { align-items: flex-start; }
.browser-result-source { gap: 7px 10px; }
.browser-panel input, .browser-panel select { min-height: 36px; font-size: 12px; }
.browser-step { grid-template-columns: 14px 84px minmax(0, 1fr) 25px; }
.browser-image-preview { padding: 4px; }
}
@@ -0,0 +1,120 @@
import { useEffect, useRef, useState } from 'react';
import { ArrowDownToLine, Check, FileText, Image, LoaderCircle, Monitor, Play, Plus, Square, Trash2 } from 'lucide-react';
import { api, browserImageBlob, downloadArtifact, downloadBlob } from './api';
import { Modal, Status } from './components';
import type { ArtifactPreview, BrowserJob, BrowserPlan, BrowserStep, Session } from './types';
import './BrowserPanel.css';
const actions: Record<BrowserStep['action'], string> = { assert_visible: '验证可见', assert_text: '验证文字', assert_count: '验证数量', click: '点击', fill: '填写', select: '选择选项' };
const active = ['queued', 'snapshotting', 'launching', 'running', 'closing'];
const viewports = { desktop: { width: 1280, height: 900 }, mobile: { width: 390, height: 844 } };
const clock = (value: string) => new Date(value).toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit', second: '2-digit' });
const describe = (step: BrowserStep) => actions[step.action] + ' · ' + step.selector + (step.text !== undefined ? ' → ' + step.text : step.count !== undefined ? ' → ' + step.count : step.value !== undefined ? ' → ' + step.value : step.visible === false ? ' → 不可见' : '');
export function BrowserPanel({ session, busy, onSession, onError }: { session: Session; busy: boolean; onSession: (session: Session) => void; onError: (error: unknown) => void }) {
const task = session.execution?.task, plans = session.execution?.browserPlans ?? [], jobs = session.execution?.browserJobs ?? [], latest = plans.at(-1);
const [available, setAvailable] = useState<{ status: string; message?: string; playwrightVersion: string } | null>(null);
const [builds, setBuilds] = useState<string[]>([]), [buildDirectory, setBuildDirectory] = useState('dist'), [pathname, setPathname] = useState('/');
const [viewport, setViewport] = useState<keyof typeof viewports>('desktop'), [steps, setSteps] = useState<BrowserStep[]>([]);
const [planning, setPlanning] = useState(false), [starting, setStarting] = useState(false), [confirm, setConfirm] = useState<BrowserPlan | null>(null);
const [preview, setPreview] = useState<ArtifactPreview | null>(null), [loadingRecord, setLoadingRecord] = useState(false), [recordJob, setRecordJob] = useState<BrowserJob | null>(null);
const [image, setImage] = useState<{ url: string; blob: Blob; job: BrowserJob; image: BrowserJob['screenshots'][number] } | null>(null), [loadingImage, setLoadingImage] = useState('');
const identity = session.id + ':' + (task?.id ?? ''), owner = useRef(identity), scope = useRef(0), request = useRef(0), imageRequest = useRef(0), imageUrl = useRef(''), mutation = useRef(false);
owner.current = identity;
const stillHere = (stamp: number) => owner.current === identity && scope.current === stamp;
const route = '/sessions/' + session.id;
const running = jobs.some(job => active.includes(job.status)), currentPending = latest && !jobs.some(job => job.planId === latest.id);
useEffect(() => {
const stamp = ++scope.current; request.current++; imageRequest.current++; setAvailable(null); setBuilds([]); setConfirm(null); setPreview(null); setImage(null);
setSteps([]); setBuildDirectory('dist'); setPathname('/'); setViewport('desktop'); setPlanning(false); setStarting(false); setLoadingRecord(false); setLoadingImage(''); mutation.current = false;
if (imageUrl.current) { URL.revokeObjectURL(imageUrl.current); imageUrl.current = ''; }
if (task) api<{ availability: { status: string; message?: string; playwrightVersion: string }; builds: string[] }>(route + '/browser').then(value => {
if (stillHere(stamp)) { setAvailable(value.availability); setBuilds(value.builds); if (value.builds[0]) setBuildDirectory(value.builds[0]); }
}).catch(error => { if (stillHere(stamp)) onError(error); });
return () => { scope.current++; request.current++; imageRequest.current++; if (imageUrl.current) URL.revokeObjectURL(imageUrl.current); imageUrl.current = ''; };
}, [identity]);
async function mutate(action: string, input: unknown) {
if (mutation.current) return; mutation.current = true; const stamp = scope.current;
try { const value = await api<Session>(route + action, input); if (stillHere(stamp)) { onSession(value); setConfirm(null); } }
catch (error) { if (stillHere(stamp)) onError(error); }
finally { if (stillHere(stamp)) { mutation.current = false; setPlanning(false); setStarting(false); } }
}
function plan(event: React.FormEvent) { event.preventDefault(); if (mutation.current) return; setPlanning(true); void mutate('/browser-plans', { build_directory: buildDirectory, path: pathname, viewport: viewports[viewport], steps }); }
function changeStep(index: number, patch: Partial<BrowserStep>) { setSteps(values => values.map((step, i) => i === index ? { ...step, ...patch } : step)); }
function changeAction(index: number, action: BrowserStep['action']) { setSteps(values => values.map((step, i) => i !== index ? step : { action, selector: step.selector,
...(['fill', 'select'].includes(action) ? { value: '' } : action === 'assert_text' ? { text: '' } : action === 'assert_count' ? { count: 1 } : action === 'assert_visible' ? { visible: true } : {}) })); }
async function openRecord(job: BrowserJob, offset = 0) {
const id = ++request.current, stamp = scope.current; setLoadingRecord(true);
try { const value = await api<ArtifactPreview>(route + '/browser-jobs/' + job.id + '/record?offset=' + offset + '&limit=8000'); if (request.current === id && stillHere(stamp)) { setPreview(value); setRecordJob(job); } }
catch (error) { if (request.current === id && stillHere(stamp)) onError(error); }
finally { if (request.current === id && stillHere(stamp)) setLoadingRecord(false); }
}
async function openImage(job: BrowserJob, entry: BrowserJob['screenshots'][number]) {
const id = ++imageRequest.current, stamp = scope.current; setLoadingImage(entry.artifactId);
try { const blob = await browserImageBlob(session.id, job.id, entry.artifactId); if (imageRequest.current === id && stillHere(stamp)) {
if (imageUrl.current) URL.revokeObjectURL(imageUrl.current); const url = URL.createObjectURL(blob); imageUrl.current = url; setImage({ url, blob, job, image: entry });
} } catch (error) { if (imageRequest.current === id && stillHere(stamp)) onError(error); }
finally { if (imageRequest.current === id && stillHere(stamp)) setLoadingImage(''); }
}
if (!task) return null;
return <section className="task-record-section browser-panel" aria-label="工程页面验收">
<div className="record-heading"><Monitor size={16} /><h3>页面验收</h3><span>{available?.status === 'available' ? 'Edge · 实际浏览器' : '检测浏览器环境'}</span></div>
<p className="browser-intro">操作当前构建的实际页面,核对交互与结果。每次检查保留页面记录和原始截图。</p>
{available?.status === 'missing' && <p className="browser-missing" role="status">{available.message}</p>}
{!builds.length && !plans.length && <p className="record-empty">当前工程没有dist、build或out页面构建。先构建Web工程,或填写已有构建目录。</p>}
<details className="browser-plan-editor" open={!!builds.length || !!plans.length}>
<summary>准备页面检查</summary>
<form onSubmit={plan}>
<div className="browser-fields"><label>构建目录<input aria-label="页面构建目录" value={buildDirectory} maxLength={160} required onChange={event => setBuildDirectory(event.target.value)} placeholder="dist" /></label>
<label>页面路径<input aria-label="预览页面路径" value={pathname} maxLength={300} required onChange={event => setPathname(event.target.value)} /></label>
<label>视口<select aria-label="浏览器视口" value={viewport} onChange={event => setViewport(event.target.value as keyof typeof viewports)}><option value="desktop">桌面 · 1280×900</option><option value="mobile">手机布局 · 390×844</option></select></label></div>
<div className="browser-step-heading"><strong>检查步骤 <span>{steps.length}/20</span></strong><button type="button" className="text-button" disabled={steps.length >= 20} onClick={() => setSteps(values => [...values, { action: 'assert_visible', selector: '', visible: true }])}><Plus size={13} />添加步骤</button></div>
{!steps.length && <p className="browser-step-empty">先读取页面与截图,再根据实际元素添加交互和断言。</p>}
{steps.map((step, index) => <div className="browser-step" key={index}>
<span className="browser-step-number">{index + 1}</span><select aria-label={'步骤 ' + (index + 1) + ' 操作'} value={step.action} onChange={event => changeAction(index, event.target.value as BrowserStep['action'])}>{Object.entries(actions).map(([value, label]) => <option value={value} key={value}>{label}</option>)}</select>
<input aria-label={'步骤 ' + (index + 1) + ' 元素'} placeholder="CSS元素,例如 #search" value={step.selector} maxLength={300} required onChange={event => changeStep(index, { selector: event.target.value })} />
{['fill', 'select'].includes(step.action) && <input aria-label={'步骤 ' + (index + 1) + ' 输入值'} value={step.value ?? ''} maxLength={2000} placeholder="实际输入或选项值" onChange={event => changeStep(index, { value: event.target.value })} />}
{step.action === 'assert_text' && <input aria-label={'步骤 ' + (index + 1) + ' 预期文字'} value={step.text ?? ''} maxLength={4000} placeholder="预期页面文字" onChange={event => changeStep(index, { text: event.target.value })} />}
{step.action === 'assert_count' && <input aria-label={'步骤 ' + (index + 1) + ' 预期数量'} type="number" min={0} max={1000} required value={step.count ?? 1} onChange={event => changeStep(index, { count: Number(event.target.value) })} />}
{step.action === 'assert_visible' && <select aria-label={'步骤 ' + (index + 1) + ' 可见性'} value={step.visible === false ? 'hidden' : 'visible'} onChange={event => changeStep(index, { visible: event.target.value === 'visible' })}><option value="visible">可见</option><option value="hidden">不可见</option></select>}
{step.action === 'click' && <span className="browser-step-value">点击唯一元素</span>}
<button type="button" className="icon-button" aria-label={'删除步骤 ' + (index + 1)} onClick={() => setSteps(values => values.filter((_, i) => i !== index))}><Trash2 size={13} /></button>
</div>)}
<button type="submit" className="button secondary" disabled={busy || running || planning || available?.status !== 'available'}>{planning ? <LoaderCircle size={13} className="spin" /> : <Check size={13} />}封存页面计划</button>
</form>
</details>
{latest && <div className="browser-sealed-plan"><div><strong>已封存计划</strong><code title={latest.fingerprint}>{latest.fingerprint.slice(0, 12)}</code></div>
<p>{latest.build.directory}{latest.path} · {latest.viewport.width}×{latest.viewport.height} · {latest.build.files} 个构建文件 · {latest.steps.length} 个步骤</p>
<details><summary>查看封存步骤</summary>{latest.steps.length ? <ol>{latest.steps.map((step, index) => <li key={index}>{describe(step)}</li>)}</ol> : <p>读取实际DOM并保存截图;尚未设置验收断言。</p>}</details>
<button type="button" className="button primary" disabled={busy || running || starting || !currentPending} onClick={() => setConfirm(latest)}><Play size={13} />运行这份计划</button>
{!currentPending && <span className="browser-plan-used">原结果已保存;调整后封存新计划。</span>}
</div>}
{!!jobs.length && <div className="browser-results"><h4>原页面结果 · {jobs.length} 次</h4>{jobs.slice().reverse().map(job => <article className={'browser-result browser-result-' + job.status} key={job.id}>
<div className="browser-result-heading"><strong>页面检查 · {clock(job.startedAt)}</strong><Status value={job.status} /></div>
<p>{job.summary}</p><div className="browser-result-source"><code title={job.taskId}>Task {job.taskId.slice(0, 8)}</code><code title={job.runId}>Run {job.runId.slice(0, 8)}</code><code title={job.buildSha256}>构建 {job.buildSha256.slice(0, 10)}</code></div>
<p className="browser-assertions">实际断言 {job.assertions?.passed ?? 0}/{job.assertions?.total ?? 0}{job.cleanup?.exited ? ' · 浏览器已退出' : ''}{job.requiresVerification ? ' · 结束状态待核对' : ''}</p>
{!!job.steps.length && <details className="browser-actual-steps"><summary>实际步骤结果</summary><ol>{job.steps.map((step, index) => <li key={index}><Status value={step.status} /><span>{describe(step)}</span>{step.error && <small>{step.error}</small>}</li>)}</ol></details>}
<div className="browser-result-actions">{active.includes(job.status) && <button type="button" className="text-button" onClick={() => void mutate('/browser-jobs/' + job.id + '/stop', {})}><Square size={12} />停止浏览器检查</button>}
{job.resultArtifactId && <><button type="button" className="text-button" disabled={loadingRecord} onClick={() => void openRecord(job)}><FileText size={13} />查看原执行记录</button>
<button type="button" className="text-button" onClick={() => { const stamp = scope.current; void downloadArtifact(session.id, job.resultArtifactId!, 'workbench-browser-' + job.id + '.json').catch(error => { if (stillHere(stamp)) onError(error); }); }}><ArrowDownToLine size={13} />下载原结果</button></>}
{job.screenshots.map(entry => <button type="button" className="text-button" key={entry.artifactId} disabled={!!loadingImage} onClick={() => void openImage(job, entry)}>{loadingImage === entry.artifactId ? <LoaderCircle size={13} className="spin" /> : <Image size={13} />}{entry.label === 'initial' ? '初始截图' : entry.label === 'final' ? '最终截图' : '失败截图'}</button>)}
{job.requiresVerification && <button type="button" className="button secondary" disabled={busy || running} onClick={() => void mutate('/browser-jobs/' + job.id + '/acknowledge', { fingerprint: job.planFingerprint })}>确认已核对中断</button>}
</div>
</article>)}</div>}
{confirm && <Modal title="执行页面检查" description="核对以下构建、视口和实际操作。执行结果会保存在当前任务。" onClose={() => setConfirm(null)}>
<div className="browser-confirm"><strong>{confirm.build.directory}{confirm.path}</strong><p>{confirm.viewport.width}×{confirm.viewport.height} · {confirm.build.files} 个文件</p><code>构建 SHA256 {confirm.build.sha256}</code>
{confirm.steps.length ? <ol>{confirm.steps.map((step, index) => <li key={index}>{describe(step)}</li>)}</ol> : <p>读取页面与截图,尚未设置验收断言。</p>}</div>
<div className="modal-actions"><button type="button" className="button secondary" disabled={starting} onClick={() => setConfirm(null)}>取消</button><button type="button" className="button primary" disabled={starting} onClick={() => { if (mutation.current) return; setStarting(true); void mutate('/browser-jobs', { planId: confirm.id }); }}><Play size={13} />确认运行页面检查</button></div>
</Modal>}
{preview && recordJob && <Modal title="浏览器原执行记录" description={'SHA256 ' + preview.sha256} wide onClose={() => { request.current++; setPreview(null); setLoadingRecord(false); }}>
<pre className="artifact-preview">{preview.content}</pre><div className="artifact-pagination"><span>字符 {preview.offset}–{preview.offset + preview.content.length} / {preview.totalCharacters}</span>
<button type="button" className="button secondary" disabled={loadingRecord || preview.offset === 0} onClick={() => void openRecord(recordJob, Math.max(0, preview.offset - 8000))}>上一段</button>
<button type="button" className="button secondary" disabled={loadingRecord || !preview.truncated} onClick={() => void openRecord(recordJob, preview.offset + preview.content.length)}>下一段</button></div>
</Modal>}
{image && <Modal title="原始页面截图" description={image.image.width + '×' + image.image.height + ' · SHA256 ' + image.image.sha256} wide onClose={() => { imageRequest.current++; setImage(null); if (imageUrl.current) URL.revokeObjectURL(imageUrl.current); imageUrl.current = ''; }}>
<div className="browser-image-preview"><img src={image.url} alt="当前任务原始页面截图" /></div><div className="modal-actions"><button type="button" className="button secondary" onClick={() => downloadBlob(image.blob, 'workbench-browser-' + image.job.id + '-' + image.image.label + '.png')}><ArrowDownToLine size={13} />下载原始PNG</button></div>
</Modal>}
</section>;
}
@@ -0,0 +1,37 @@
import { useState } from 'react';
import { RotateCw } from 'lucide-react';
import { api } from './api';
import { Modal } from './components';
import type { Config,Session } from './types';
import './input-attachments.css';
import { budgetPausePresentation } from '../shared/budget-presentation.mjs';
type Fields={contextLimit:number;maxOutputTokens:number;maxRunTokens:number;maxTaskTokens:number;maxSteps:number;maxRunDurationMs:number};
type Preview={id:string;sha256:string;taskId:string;runId:string;config:Fields&{model:string};eligibleConnections:{id:string;name:string;model:string}[];budget:{inputBudget:number;contextLimit:number};completedToolIds:string[];unknownToolIds:string[];attachmentIds:string[];note:string};
const labels:Record<string,string>={transportAndImageFramingTokens:'请求格式与图片说明',goalAndContextTextTokens:'目标、全部要求及工程上下文',toolDefinitionTokens:'工具定义',historyAndEvidenceTokens:'必需历史及实际依据',imageReservationTokens:'图像本地预留',requestOverheadTokens:'请求格式',fixedInstructionTokens:'完整目标与原生提示',retainedHistoryAndViewTokens:'保留历史与工具结果'};
export function BudgetPausePanel({session,config,onSession,onRecovery}:{session:Session;config:Config;onSession:(value:Session)=>void;onRecovery?:()=>void}){
const [open,setOpen]=useState(false),[busy,setBusy]=useState(false),[error,setError]=useState(''),[plan,setPlan]=useState<Preview|null>(null);
const [fields,setFields]=useState<Fields>({contextLimit:session.execution?.run?.model.contextLimit??config.contextLimit,maxOutputTokens:session.execution?.run?.model.maxOutputTokens??config.maxOutputTokens,
maxRunTokens:config.maxRunTokens,maxTaskTokens:session.execution?.task?.budget.maxTokens??config.maxTaskTokens,maxSteps:config.maxSteps,maxRunDurationMs:config.maxRunDurationMs});
const [selection,setSelection]=useState(''),[options,setOptions]=useState<{value:string;name:string}[]>([]);
const run=session.execution?.run,pause=run?.budgetPause,reason=pause?.reason??run?.stopReason??'';
const diagnosis=budgetPausePresentation(pause,reason);
const controlled=session.execution?.task?.origin==='isolated-worker'||run?.engine==='deepseek-workbench';
const calibrationSources=new Set(pause?.tokenReservation?.routes.flatMap(route=>route.sources.map(source=>source.attemptId))??[]).size;
if(!['paused','failed'].includes(session.status)||!diagnosis)return null;
async function start(){setOpen(true);setError('');setPlan(null);try{const center=await api<{selected:{type:string;id:string};connections:{id:string;name:string;contextLimit:number}[];pools:{id:string;name:string}[]}>('/model-center');setSelection(center.selected.type+':'+center.selected.id);setOptions([...center.connections.map(row=>({value:(row.id==='legacy-default'?'legacy':'connection')+':'+row.id,name:row.name+' · '+row.contextLimit.toLocaleString()+' 上下文'})),...center.pools.map(row=>({value:'pool:'+row.id,name:row.name+' · 按成员最小容量'}))]);}catch(cause){setError((cause as Error).message);}}
async function preview(){setBusy(true);setError('');setPlan(null);try{const [type,id]=selection.split(':');const value=await api<Preview>('/sessions/'+session.id+'/resume-preview',{...fields,...(selection?{selection:{type,id}}:{})});setPlan(value);onSession(await api<Session>('/sessions/'+session.id));}catch(cause){setError((cause as Error).message);}finally{setBusy(false);}}
async function confirm(){if(!plan)return;setBusy(true);setError('');try{onSession(await api<Session>('/sessions/'+session.id+'/resume-budget',{planId:plan.id,sha256:plan.sha256}));setOpen(false);}catch(cause){setError((cause as Error).message);}finally{setBusy(false);}}
return <aside className="budget-pause" aria-label="任务预算诊断"><h3>{diagnosis.title}</h3>{pause?.requiredInputTokens!==undefined?<><p>完整要求与必需输入估算 <strong>{pause.requiredInputTokens.toLocaleString()}</strong> tokens;{diagnosis.inputLabel} <strong>{pause.inputBudget?.toLocaleString()}</strong>。请求已暂停,原任务和工具结果保留。</p><dl className="budget-facts">{Object.entries(pause.breakdown??{}).map(([key,value])=><div key={key} style={{display:'contents'}}><dt>{labels[key]??key}</dt><dd>{value.toLocaleString()}</dd></div>)}<dt>所选上下文窗口</dt><dd>{pause.contextLimit?.toLocaleString()}</dd><dt>响应预留 / 安全余量</dt><dd>{pause.outputReservation?.toLocaleString()} / {pause.safetyTokens?.toLocaleString()}</dd><dt>运行 / 任务剩余</dt><dd>{pause.runRemainingTokens?.toLocaleString()??'不限'} / {pause.taskRemainingTokens?.toLocaleString()??'不限'}</dd></dl></>:<p>原 Task 已保存。可核对剩余预算和模型容量,再准备同一任务的新 Run;旧记录没有的预算分解不补造。</p>}
{diagnosis.guidance&&<p>{diagnosis.guidance}</p>}
{pause?.originalInputTokens!==undefined&&<p>原生完整历史估算 {pause.originalInputTokens.toLocaleString()} tokens。原始输入、历史索引与拒绝正文已保存为任务工件,本次拒绝没有发送模型请求。</p>}
{!!pause?.transportReservationTokens&&<p>准备原生任务时另留 {pause.transportReservationTokens.toLocaleString()} tokens 给引擎提示和消息封装;实际原生请求仍单独核对容量。</p>}
{!!pause?.imageReservationTokens&&<p>图像使用单独的本地预留,属于容量估算;实际计费与服务报告用量分列。</p>}
{pause?.modelFailure&&<p>本次模型原错误:{pause.modelFailure.message}{pause.modelFailure.upstreamRequestId?<> · 上游请求 ID:{pause.modelFailure.upstreamRequestId}</>:null}。原响应和请求诊断仍可核对。</p>}
{pause?.tokenReservation&&<p>{calibrationSources?<>依据同一模型线路的 {calibrationSources} 次已知响应校准,</>:'按本地估算,'}下一次请求需预留 <strong>{pause.tokenReservation.reservedTokens.toLocaleString()}</strong> tokens{pause.remainingTokens!==undefined?<>,剩余 <strong>{pause.remainingTokens.toLocaleString()}</strong></>:null}。已在发送前暂停;这项预留用于后续预算,原始用量记录保持。</p>}
{pause?.tokenAccounting&&<><dl className="budget-facts"><dt>本次运行上游报告用量</dt><dd>{pause.tokenAccounting.run.reportedTokens.toLocaleString()}</dd><dt>用量未知请求 / 本地预留</dt><dd>{pause.tokenAccounting.run.unknownRequests.toLocaleString()} / {pause.tokenAccounting.run.estimatedUnknownTokens.toLocaleString()}</dd><dt>本次运行预算 / 记账超出</dt><dd>{pause.tokenAccounting.run.maximumTokens>0?pause.tokenAccounting.run.maximumTokens.toLocaleString():'不限'} / {pause.tokenAccounting.run.exceededTokens.toLocaleString()}</dd><dt>任务累计预算 / 记账超出</dt><dd>{pause.tokenAccounting.task.maximumTokens>0?pause.tokenAccounting.task.maximumTokens.toLocaleString():'不限'} / {pause.tokenAccounting.task.exceededTokens.toLocaleString()}</dd></dl><p>单个在途响应可能超过预估。超额后停止后续请求;用量未知的请求仍按本地预留控制预算,不补造实际计费。</p></>}
{controlled?<><p>受限子任务在隔离协作中处理。当前协作沿用已封存容量与累计预算;若配置不足,先保留现场,再为新目标选择合适配置。已完成工具和原失败不会自动重放。</p>{onRecovery&&<button type="button" className="button secondary" onClick={onRecovery}>打开隔离协作</button>}</>:<button type="button" className="button secondary" onClick={()=>void start()}><RotateCw size={14}/>核对预算并续接原任务</button>}
{open&&<Modal title="续接原任务" description="先核对新Run的容量与预算,再确认执行。" onClose={()=>{if(!busy)setOpen(false);}} wide><p className="input-sha">Task {session.execution?.task?.id}<br/>原 Run {run?.id}</p><div className="budget-resume-fields"><label>本次模型连接或池<select aria-label="续接模型连接" value={selection} disabled={busy} onChange={event=>{setSelection(event.target.value);setPlan(null);}}>{options.map(row=><option key={row.value} value={row.value}>{row.name}</option>)}</select></label>{([['contextLimit','上下文窗口',1000,200000],['maxOutputTokens','响应预留',256,16000],['maxRunTokens','新Run累计tokens',1000,2000000],['maxTaskTokens','原任务累计tokens',1000,10000000],['maxSteps','新Run工具轮次',1,30],['maxRunDurationMs','新Run时间(分钟)',1,60]] as const).map(([key,label,min,max])=><label key={key}>{label}<input aria-label={label} type="number" min={min} max={max} value={key==='maxRunDurationMs'?fields[key]/60000:fields[key]} disabled={busy} onChange={event=>{setFields({...fields,[key]:Number(event.target.value)*(key==='maxRunDurationMs'?60000:1)});setPlan(null);}}/></label>)}</div><p>容量须符合服务实际限制;池按成员最小容量核对。新增预算只用于这次明确续接,不修改全局设置。</p>{error&&<p className="budget-error" role="alert">{error}</p>}<div className="modal-actions"><button type="button" className="button secondary" disabled={busy||!selection} onClick={()=>void preview()}>准备续接预览</button></div>{plan&&<div className="budget-preview" role="status"><strong>将创建原Task的新Run</strong><p>可用模型 {plan.eligibleConnections.length?plan.eligibleConnections.map(row=>row.name+' / '+row.model).join('、'):plan.config.model} · 上下文 {plan.budget.contextLimit.toLocaleString()} · 可用输入 {plan.budget.inputBudget.toLocaleString()} tokens</p><p>保留 {plan.completedToolIds.length} 项完成工具、{plan.attachmentIds.length} 张附件;{plan.unknownToolIds.length} 项未知结果仍须核对。</p><p>{plan.note}</p><p className="input-sha">预览 SHA-256 {plan.sha256}</p><div className="modal-actions"><button type="button" className="button primary" disabled={busy} onClick={()=>void confirm()}>确认预算并续接</button></div></div>}</Modal>}
</aside>;
}
@@ -0,0 +1,8 @@
.change-set-bar{display:flex;align-items:center;flex-wrap:wrap;gap:9px;padding:12px;border-bottom:1px solid #dce7d8;background:#f2f7ee;flex-shrink:0;color:#456243}
.change-set-bar>div{flex:1;min-width:150px}.change-set-bar strong{display:block;font-size:12px;font-weight:600}.change-set-bar small{display:block;font-size:10px;line-height:1.6;margin-top:3px;color:#71836b;overflow-wrap:anywhere}.change-set-bar .button{padding:7px 10px;font-size:11px;min-height:30px}
.batch-attention{background:#fff7ea;border-color:#e6d1ac;color:#7c613b}.batch-attention small{color:#8a7658}.batch-sealed-note{font-size:10px!important;color:#6b7d55!important}
.batch-select-list{flex:1;min-height:0;overflow:auto;border-top:1px solid #dce7d8}.batch-select-list>label{display:flex;align-items:center;gap:12px;padding:14px 8px;border-bottom:1px solid #e6ece1;cursor:pointer}.batch-select-list input{width:16px;height:16px;accent-color:#507247;flex-shrink:0}.batch-select-list>label>span:first-of-type{flex:1;min-width:0}.batch-select-list strong{display:block;font:12px Consolas,monospace;overflow-wrap:anywhere}.batch-select-list small{display:block;font-size:11px;color:#7c8b72;margin-top:5px;line-height:1.6;overflow-wrap:anywhere}
.batch-heading{display:flex;align-items:center;gap:10px;flex-wrap:wrap;font-size:11px;line-height:1.7;padding:10px 0 14px;flex-shrink:0}.batch-heading>span:nth-child(2){flex:1;min-width:180px;overflow-wrap:anywhere}.batch-heading select{max-width:100%;font-size:11px;border:1px solid #d9e5d4;padding:6px;border-radius:5px;color:#4a6646;background:#f7faf3}
.batch-review-grid{display:grid;grid-template-columns:minmax(180px,26%) minmax(0,1fr);flex:1;min-height:160px;border:1px solid #dfe8d7;border-radius:7px;overflow:hidden}.batch-file-list{overflow:auto;min-height:0;border-right:1px solid #dfe8d7;background:#f8faf5}.batch-file-list button{display:block;width:100%;text-align:left;padding:12px;border-bottom:1px solid #e7edde;color:#506647;outline-offset:-3px}.batch-file-list button.selected{background:#eaf2df;box-shadow:inset 3px 0 #6e8f54}.batch-file-list strong{display:block;font:11px Consolas,monospace;overflow-wrap:anywhere}.batch-file-list small{display:block;font-size:10px;margin-top:5px;color:#7c8b71}.batch-file-list code{display:block;font-size:10px;color:#8b967e;margin-top:5px}.batch-file-list .batch-problem{color:#966636;line-height:1.6;overflow-wrap:anywhere}.batch-diff{display:flex;flex-direction:column;min-width:0;min-height:0}.batch-diff-heading{display:flex;align-items:center;justify-content:space-between;gap:10px;padding:10px 12px;border-bottom:1px solid #dfe8d7;flex-shrink:0;font-size:11px}.batch-diff-heading strong{font:11px Consolas,monospace;overflow-wrap:anywhere}.batch-diff-heading span{color:#89957e;white-space:nowrap}
.batch-fingerprint{display:grid;grid-template-columns:60px minmax(0,1fr);gap:5px 12px;padding:11px 0;font-size:10px;flex-shrink:0;color:#8a967e}.batch-fingerprint code{font-size:10px;color:#6b7f58;overflow-wrap:anywhere}.batch-actions{display:flex;align-items:center;justify-content:flex-end;flex-wrap:wrap;gap:8px;padding-top:12px;border-top:1px solid #dfe8d7;flex-shrink:0}.batch-actions>span{font-size:10px;line-height:1.7;flex:1;min-width:130px;color:#7c8c70;overflow-wrap:anywhere}.batch-actions .button{font-size:11px;min-height:34px}.batch-confirmation{padding:12px;background:#fff7e9;border:1px solid #e3cdac;border-radius:7px;flex-shrink:0;font-size:12px;line-height:1.7;color:#82673f}.batch-confirmation p{font-size:11px;margin:6px 0 10px}.batch-confirmation .button{font-size:11px;margin-right:8px}.status-partial,.status-rolling_back{background:#fff0d8;color:#846129}.status-applying{background:#e9f2df;color:#617e42}.status-rolled_back,.status-resolved_external,.status-external_preserved{background:#edf2eb;color:#66805c}
@media(max-width:650px){.batch-review-grid{grid-template-columns:minmax(0,1fr);grid-template-rows:110px minmax(100px,1fr);min-height:180px}.batch-file-list{border-right:0;border-bottom:1px solid #dfe8d7}.batch-file-list button{padding:8px 10px}.batch-file-list small,.batch-file-list code{display:inline-block;margin:3px 10px 0 0}.batch-heading{padding:6px 0 9px}.batch-actions .button{flex:1;white-space:normal}.batch-actions>span{flex-basis:100%}.batch-fingerprint{gap:3px 8px;padding:8px 0}.batch-confirmation{padding:9px}.batch-confirmation .button{min-height:32px;padding:6px 8px}.change-set-bar>div{min-width:130px}.change-set-bar .button{font-size:10px}}
@@ -0,0 +1,107 @@
import { useEffect, useRef, useState } from 'react';
import { Check, Files, LoaderCircle, RotateCcw, ScanLine, ShieldCheck } from 'lucide-react';
import type { ChangeSet, Session } from './types';
import { api } from './api';
import { DiffView, Modal, Status } from './components';
import './ChangeSetPanel.css';
const openStates = ['prepared', 'applying', 'rolling_back', 'unknown', 'partial'];
const labels: Record<string, string> = { before: '原文件', after: '建议内容', external: '外部改动', unavailable: '无法读取', writing: '正在写入', restoring: '正在回退' };
export function ChangeSetPanel({ session, busy, onSession, onError, onFilesChanged }: {
session: Session; busy: boolean; onSession: (session: Session) => void; onError: (error: unknown) => void; onFilesChanged: () => Promise<void>;
}) {
const sets = session.execution?.changeSets ?? [], taskId = session.execution?.task?.id;
const pending = session.changes.filter(change => change.taskId === taskId && change.status === 'pending'
&& !sets.some(set => set.id === change.changeSetId && openStates.includes(set.status)));
const current = sets.slice().reverse().find(set => openStates.includes(set.status)) ?? sets.at(-1);
const [stage, setStage] = useState<'select' | 'review' | null>(null);
const [setId, setSetId] = useState(''), [fileId, setFileId] = useState('');
const [choices, setChoices] = useState<string[]>([]), [working, setWorking] = useState(false);
const [confirmation, setConfirmation] = useState<'rollback' | 'acknowledge' | null>(null);
const scope = session.id + ':' + (taskId ?? ''), scopeRef = useRef(scope); scopeRef.current = scope;
const filesSignature = sets.filter(set => ['completed', 'rolled_back', 'partial', 'unknown', 'resolved_external'].includes(set.status))
.map(set => set.id + ':' + set.status + ':' + set.finishedAt).join('|');
const lastFiles = useRef({ scope, signature: filesSignature });
useEffect(() => {
scopeRef.current = scope;
setStage(null); setSetId(''); setFileId(''); setChoices([]); setConfirmation(null); setWorking(false);
return () => { if (scopeRef.current === scope) scopeRef.current = ''; };
}, [scope]);
useEffect(() => {
const previous = lastFiles.current; lastFiles.current = { scope, signature: filesSignature };
if (previous.scope === scope && previous.signature !== filesSignature) void onFilesChanged().catch(error => { if (scopeRef.current === scope) onError(error); });
}, [scope, filesSignature, onFilesChanged, onError]);
const selected = sets.find(set => set.id === setId) ?? current;
const file = selected?.files.find(value => value.changeId === fileId) ?? selected?.files[0];
const proposal = session.changes.find(change => change.id === file?.changeId);
const active = !!selected && ['applying', 'rolling_back'].includes(selected.status);
const disabled = busy || working || active;
const close = () => { setStage(null); setConfirmation(null); };
async function prepare() {
if (!choices.length || choices.length > 32 || disabled) return;
const target = scope; setWorking(true);
try {
const result = await api<Session>('/sessions/' + session.id + '/change-sets', { changeIds: choices });
if (scopeRef.current !== target) return;
onSession(result);
const next = result.execution?.changeSets?.slice().reverse().find(set => set.status === 'prepared');
if (next) { setSetId(next.id); setFileId(next.files[0]?.changeId ?? ''); setStage('review'); }
} catch (error) { if (scopeRef.current === target) onError(error); }
finally { if (scopeRef.current === target) setWorking(false); }
}
async function act(set: ChangeSet, action: 'apply' | 'reconcile' | 'rollback' | 'discard' | 'acknowledge') {
if (disabled) return;
const target = scope; setWorking(true);
try {
const result = await api<Session>('/sessions/' + session.id + '/change-sets/' + set.id + '/' + action,
{ fingerprint: set.fingerprint, ...(action === 'acknowledge' ? { observationFingerprint: set.observationFingerprint } : {}) });
if (scopeRef.current === target) { onSession(result); setConfirmation(null); }
} catch (error) { if (scopeRef.current === target) onError(error); }
finally { if (scopeRef.current === target) setWorking(false); }
}
const canAcknowledge = selected?.status === 'partial' && !!selected.observationFingerprint
&& !!selected.observations?.length && selected.observations.every(value => ['before', 'external'].includes(value.state));
return <>
<div className={'change-set-bar' + (current?.requiresVerification ? ' batch-attention' : '')}>
<Files size={17} /><div><strong>{current ? `多文件变更集 · ${current.files.length} 个文件` : '组合审查文件改动'}</strong>
<small>{current ? current.requiresVerification ? '实际文件需要核对,恢复入口保留在这个任务。' : current.summary : pending.length ? `${pending.length} 份提案可组合为一个审查批次。` : '本任务有提案后,可一起审查与应用。'}</small></div>
{current && <button type="button" className="button secondary" disabled={working} onClick={() => { setSetId(current.id); setFileId(current.files[0]?.changeId ?? ''); setStage('review'); }}>审查变更集</button>}
{!current || !openStates.includes(current.status) ? <button type="button" className="button secondary" disabled={!taskId || !pending.length || busy || working}
onClick={() => { setChoices(pending.slice(0, 32).map(change => change.id)); setStage('select'); }}>组合审查</button> : null}
</div>
{stage === 'select' && <Modal title="选择要一起审查的提案" description="选择1到32份同任务提案,封存后查看整批差异。" wide onClose={close}>
<div className="batch-select-list">{pending.map(change => <label key={change.id}><input type="checkbox" aria-label={'选择提案 ' + change.path} checked={choices.includes(change.id)}
onChange={event => setChoices(previous => event.target.checked ? [...previous, change.id] : previous.filter(id => id !== change.id))} />
<span><strong>{change.path}</strong><small>{change.reason}</small></span><span className="change-stats"><b>+{change.additions}</b><i>−{change.deletions}</i></span></label>)}</div>
<div className="batch-actions"><span>已选择 {choices.length} / 32 项</span><button type="button" className="button primary" disabled={disabled || !choices.length || choices.length > 32} onClick={prepare}>
{working ? <LoaderCircle size={14} className="spin" /> : <ShieldCheck size={14} />}封存审查范围</button></div>
</Modal>}
{stage === 'review' && selected && <Modal title="多文件变更集审查" description={`本任务 ${selected.taskId.slice(0, 8)} · ${selected.files.length} 个文件`} wide onClose={close}>
<div className="batch-heading"><Status value={selected.status} /><span>{selected.summary}</span>
{sets.length > 1 && <select aria-label="选择变更批次" value={selected.id} onChange={event => { setSetId(event.target.value); setFileId(''); setConfirmation(null); }}>
{sets.slice().reverse().map(set => <option key={set.id} value={set.id}>{set.id.slice(0, 8)} · {set.files.length} 个文件 · {set.status}</option>)}</select>}
</div>
<div className="batch-review-grid"><div className="batch-file-list" aria-label="批次文件范围">{selected.files.map(item => {
const observation = selected.observations?.find(value => value.path === item.path);
return <button type="button" key={item.changeId} aria-label={'查看批次差异 ' + item.path} className={file?.changeId === item.changeId ? 'selected' : ''}
onClick={() => setFileId(item.changeId)}><strong>{item.path}</strong><small>{labels[observation?.state ?? item.state] ?? item.state}</small>
<code title={observation?.actualSha256 ?? item.baseSha256 ?? '新文件'}>{(observation?.actualSha256 ?? item.baseSha256)?.slice(0, 12) ?? '新文件'}</code>
{observation?.problem && <small className="batch-problem">{observation.problem}</small>}{item.restoreError && <small className="batch-problem">{item.restoreError}</small>}</button>;
})}</div><div className="batch-diff"><div className="batch-diff-heading"><strong>{file?.path}</strong><span>提案差异</span></div>{proposal && <DiffView change={proposal} />}</div></div>
<div className="batch-fingerprint"><span>审查指纹</span><code>{selected.fingerprint}</code><span>Git基线</span><code>{selected.baseline.available ? `${selected.baseline.branch ?? '未命名'} · ${selected.baseline.head?.slice(0, 12) ?? '尚无提交'}` : '项目尚未启用Git'}</code></div>
{confirmation && <div className="batch-confirmation" role="alert"><strong>{confirmation === 'rollback' ? '回退本批次已写入的文件' : '保留外部改动并结束恢复'}</strong>
<p>{confirmation === 'rollback' ? '只有当前字节仍等于本批次建议时才恢复原文,外部修改会保留。已新建的文件会按同样规则移除。' : '将保留目前已核对的外部内容,并结束这个未成功应用的批次。当前文件再次变化时会拒绝确认。'}</p>
<button type="button" className="button secondary" disabled={disabled} onClick={() => setConfirmation(null)}>返回审查</button>
<button type="button" className="button primary" disabled={disabled} onClick={() => act(selected, confirmation)}>{confirmation === 'rollback' ? '确认回退本批次' : '确认保留外部改动'}</button></div>}
<div className="batch-actions"><span>{active ? '文件批次正在执行,结果会持续更新。' : selected.requiresVerification ? '先核对实际文件,恢复不会自动续写。' : '应用前会核对所有文件及原审查指纹。'}</span>
{working && <LoaderCircle size={14} className="spin" />}
{['prepared', 'stale'].includes(selected.status) && <button type="button" className="button secondary" disabled={disabled} onClick={() => act(selected, 'discard')}>撤销未执行批次</button>}
{selected.status === 'prepared' && <button type="button" className="button primary" disabled={disabled} onClick={() => act(selected, 'apply')}><Check size={14} />确认应用全部 {selected.files.length} 项</button>}
{selected.requiresVerification && <button type="button" className="button secondary" disabled={disabled} onClick={() => act(selected, 'reconcile')}><ScanLine size={14} />核对实际文件</button>}
{['completed', 'partial', 'unknown'].includes(selected.status) && <button type="button" className="button secondary" disabled={disabled || !!confirmation} onClick={() => setConfirmation('rollback')}><RotateCcw size={14} />回退本批已写入文件</button>}
{canAcknowledge && <button type="button" className="button secondary" disabled={disabled || !!confirmation} onClick={() => setConfirmation('acknowledge')}>保留外部改动,结束恢复</button>}
</div>
</Modal>}
</>;
}
@@ -0,0 +1,30 @@
import { ArrowDownToLine, Check, FileCode2 } from 'lucide-react';
import type { Change, Session } from './types';
import { downloadBlob } from './api';
import { DiffView, EmptyInspector, IconButton, Status } from './components';
import { ChangeSetPanel } from './ChangeSetPanel';
export function ChangesInspector({ session, selectedChange, busy, isRunning, onSelect, onAction, onSession, onError, onFilesChanged }: {
session: Session; selectedChange?: Change; busy: boolean; isRunning: boolean; onSelect: (id: string) => void;
onAction: (change: Change, action: 'apply' | 'reject') => Promise<void>; onSession: (session: Session) => void;
onError: (error: unknown) => void; onFilesChanged: () => Promise<void>;
}) {
const sealed = !!selectedChange?.changeSetId && !!session.execution?.changeSets?.some(set => set.id === selectedChange.changeSetId
&& ['prepared', 'applying', 'rolling_back', 'unknown', 'partial'].includes(set.status));
return <div className="changes-inspector"><ChangeSetPanel session={session} busy={busy || isRunning} onSession={onSession} onError={onError} onFilesChanged={onFilesChanged} />
{selectedChange ? <>
<div className="change-list">{session.changes.map(change => <button key={change.id} className={selectedChange.id === change.id ? 'selected' : ''} onClick={() => onSelect(change.id)}>
<FileCode2 size={14} /><span>{change.path}</span><span className="change-stats"><b>+{change.additions}</b><i>−{change.deletions}</i></span></button>)}</div>
<div className="change-summary"><div><strong>{selectedChange.path}</strong><Status value={selectedChange.status} /></div><p>{selectedChange.reason}</p>
{selectedChange.patch && <p className="patch-detail">精确补丁 · {selectedChange.patch.edits} 处替换 · {selectedChange.patch.lineEnding === 'mixed' ? '按原文核对混合换行' : '保留 ' + selectedChange.patch.lineEnding.toUpperCase() + ' 换行'}{selectedChange.patch.preservedBom ? ' · 保留 BOM' : ''}</p>}
{sealed && <p className="batch-sealed-note">已封存到变更集,请在上方审查整个批次。</p>}</div>
<DiffView change={selectedChange} />
<div className="change-actions">{['pending', 'conflict'].includes(selectedChange.status) ? <>
<button type="button" className="button secondary" onClick={() => onAction(selectedChange, 'reject')} disabled={busy || isRunning || sealed}>撤回提案</button>
<button type="button" className="button primary" disabled={selectedChange.status !== 'pending' || busy || isRunning || sealed} onClick={() => onAction(selectedChange, 'apply')}><Check size={14} />应用这项改动</button>
</> : <span className="subtle">{selectedChange.status === 'applied' ? '这项改动已写入项目。' : selectedChange.status === 'external_preserved' ? '已保留外部内容,批次未记为成功应用。' : selectedChange.status === 'rolled_back' ? '这项改动已恢复为原文件。' : '这项提案已结束。'}</span>}
<IconButton label="下载建议内容" onClick={() => downloadBlob(new Blob([selectedChange.content], { type: 'text/plain;charset=utf-8' }), selectedChange.path.split('/').at(-1) || 'proposal.txt')}><ArrowDownToLine size={15} /></IconButton>
</div>
</> : <EmptyInspector kind="changes" />}
</div>;
}
@@ -0,0 +1,38 @@
.code-index-panel{display:flex;flex:1;flex-direction:column;min-height:0;overflow:hidden;background:#FCFDFC}
.code-index-panel[hidden]{display:none}
.index-heading{display:flex;align-items:center;justify-content:space-between;gap:12px;padding:17px 16px 13px;border-bottom:1px solid #dde8e3}
.index-heading>div{min-width:0}.index-heading .field-eyebrow{display:block;max-width:100%;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
.index-heading h3{margin:7px 0 0;font-family:Bahnschrift,'Segoe UI','Microsoft YaHei',sans-serif;font-size:20px;font-weight:600;color:#154B4A}
.index-search{padding:13px 16px;border-bottom:1px solid #dde8e3;background:#FCFDFC}
.index-query{display:flex;align-items:center;gap:8px;padding:0 10px;border:1px solid #b8ccc4;border-radius:7px;color:#154B4A;background:white}
.index-query:focus-within{border-color:#4664D9;box-shadow:0 0 0 2px #4664D918}
.index-query input{flex:1;min-width:0;width:100%;border:0!important;box-shadow:none!important;padding:10px 0;background:transparent;outline:none;font-size:12px;color:#1C2E32}
.index-query input:focus-visible{outline:none!important}
.index-search-controls{display:flex;justify-content:space-between;gap:9px;margin-top:9px}.index-search-controls select{min-width:0;flex:1;border:1px solid #ccdcd4;background:#EDF3F1;border-radius:6px;padding:7px 9px;color:#1C2E32;font-size:12px}
.index-search-controls .button{padding:7px 13px;font-size:12px;min-width:78px;justify-content:center}
.index-scroll{flex:1;min-height:0;overflow:auto;padding:13px 16px 20px}
.index-coverage{border-left:3px solid #154B4A;background:#EDF3F1;padding:11px 12px;font-size:11px;line-height:1.6;color:#526b63}
.index-coverage>div{display:flex;justify-content:space-between;gap:8px}.index-coverage strong{color:#154B4A;font-size:12px}.index-coverage p{margin:5px 0;color:#1C2E32;font-variant-numeric:tabular-nums}.index-coverage.partial{border-color:#A16C21;background:#A16C210B}.index-coverage.partial strong{color:#A16C21}
.index-scope{margin:10px 0 16px;font-size:11px;color:#526b63;line-height:1.8}.index-scope summary{cursor:pointer;color:#154B4A}.index-scope p{margin:7px 0}.index-scope>code{display:block;font-size:10px;overflow-wrap:anywhere;line-height:1.7;margin-top:5px}
.index-result-caption{display:flex;justify-content:space-between;gap:8px;font-size:11px;color:#60736d;padding:0 0 9px}.index-result-caption>span:first-child{min-width:0;overflow-wrap:anywhere}.index-result-caption>span:last-child{flex-shrink:0}
.index-results{display:flex;flex-direction:column;gap:8px}
.index-result{width:100%;text-align:left;padding:12px 10px;border:1px solid #d8e4de;border-radius:7px;background:#FCFDFC;transition:border-color .15s,background .15s;color:#1C2E32;cursor:pointer}
.index-result:hover:not(:disabled){border-color:#154B4A;background:#EDF3F150}.index-result:disabled{opacity:.55;cursor:default}.index-result:focus-visible{outline:2px solid #4664D9;outline-offset:2px}
.index-result-title{display:flex;align-items:center;gap:6px;color:#154B4A}.index-result-title>strong{font-family:'Cascadia Code',Consolas,monospace;font-size:12px;overflow-wrap:anywhere;min-width:0;flex:1}.index-result-title>span{flex-shrink:0;font-size:10px;color:#526b63;padding:1px 5px;background:#EDF3F1;border-radius:3px}.index-result-title>svg{flex-shrink:0}
.index-result-location{display:flex;align-items:baseline;gap:1px;margin:7px 0;color:#526b63;font-family:'Cascadia Code',Consolas,monospace;font-size:11px}.index-result-location>span{min-width:0;overflow-wrap:anywhere}.index-result-location>b{color:#4664D9;font-weight:500;flex-shrink:0}
.index-signature{display:block;width:100%;font-size:10px;color:#61736c;white-space:nowrap;text-overflow:ellipsis;overflow:hidden}.index-target{font-size:10px;overflow-wrap:anywhere;color:#526b63;line-height:1.7;margin:6px 0 0}
.index-result-evidence{display:flex;justify-content:space-between;gap:6px;margin-top:8px;font-size:10px;color:#73827b}.index-result-evidence>code{font-size:10px;flex-shrink:0}
.index-empty{text-align:center;padding:35px 13px;color:#60736d;font-size:12px;line-height:1.8}.index-empty>svg{color:#154B4A}.index-empty h4{font-size:14px;color:#154B4A;margin:12px 0 4px}.index-empty p{margin:0}
.index-limit{font-size:11px;line-height:1.8;margin:14px 0 0;color:#60736d}.index-error,.index-warnings{font-size:11px;line-height:1.8;background:#A16C210B;border:1px solid #A16C2135;border-radius:6px;padding:10px;margin:0 0 12px;color:#76541f}.index-error p,.index-warnings p{margin:5px 0;overflow-wrap:anywhere}.index-warnings p>span{display:block;font-family:'Cascadia Code',Consolas,monospace;color:#1C2E32;font-size:10px}
.file-index-notice{padding:10px 13px;border-bottom:1px solid #A16C2135;background:#A16C210B;color:#76541f;font-size:11px;line-height:1.7;flex-shrink:0}
.code-view>div.code-line-target{background:#4664D915;box-shadow:inset 3px 0 #4664D9}.code-view>div.code-line-target>span{color:#4664D9;font-weight:600}
.patch-detail{color:#154B4A!important;font-size:11px!important}
.inspector-tabs{gap:3px;padding-left:8px;padding-right:8px}.inspector-tabs>button:not(.icon-button){white-space:nowrap;flex-shrink:0;padding-left:6px;padding-right:6px;gap:4px}.inspector-tabs>.icon-button{flex-shrink:0}
.diff-caption{position:sticky;top:0;z-index:1;background:#FCFDFC}.diff-jump{font-size:10px;color:#4664D9;white-space:nowrap;padding:3px 5px;border-radius:3px}.diff-jump:hover{background:#4664D910}
@media(max-width:1250px){.inspector-tabs{gap:1px;padding-left:7px;padding-right:7px}.inspector-tabs>button:not(.icon-button){padding-left:7px;padding-right:7px}}
@media(max-width:620px){.index-heading,.index-search{padding-left:13px;padding-right:13px}.index-scroll{padding-left:13px;padding-right:13px}}
@media(prefers-reduced-motion:reduce){.index-result{transition:none}}
.index-cache{margin:12px 0;border-top:1px solid #d8e4de;border-bottom:1px solid #d8e4de;font-size:12px;color:#405c54;line-height:1.7;padding:3px 0}
.index-cache>summary{cursor:pointer;color:#154B4A;padding:10px 0;font-weight:600;min-height:44px}.index-cache p{margin:8px 0;overflow-wrap:anywhere}
.index-cache-controls{display:flex;flex-wrap:wrap;gap:8px;align-items:center;justify-content:space-between}.index-cache-controls label{display:flex;align-items:center;gap:8px;min-height:44px;cursor:pointer}.index-cache-controls input{width:17px;height:17px;accent-color:#154B4A}.index-cache-controls button{font-size:12px;min-height:44px;padding:6px 10px}
.index-cache-metrics{display:grid;grid-template-columns:94px minmax(0,1fr);gap:7px 10px;margin:13px 0}.index-cache-metrics dt{color:#526b63}.index-cache-metrics dd{margin:0;color:#1C2E32;overflow-wrap:anywhere;font-variant-numeric:tabular-nums}.index-cache .index-cache-feedback{border-left:3px solid #154B4A;background:#EDF3F1;padding:8px 10px;color:#154B4A}.index-cache .index-cache-warning{color:#76541f}
@@ -0,0 +1,123 @@
import { useEffect, useRef, useState } from 'react';
import { ArrowUpRight, FileCode2, LoaderCircle, RefreshCw, Search } from 'lucide-react';
import { api } from './api';
import type { CodeQuery, CodeQueryKind, CodeResult, Project, ProjectCacheStatus } from './types';
import './CodeIndexPanel.css';
const kindNames: Record<string, string> = { function: '函数', method: '方法', class: '类', interface: '接口', type: '类型', enum: '枚举', binding: '变量' };
const resultName = (result: CodeResult) => result.resultKind === 'symbol' ? result.qualifiedName || result.name : result.name;
const reasons: Record<string, string> = { cold: '首次建立', memory: '本次进程复用', disk: '从本机派生缓存载入', disabled: '缓存已关闭',
'process-only': '仅本次进程', 'incomplete-scan': '读取范围不完整,重新分析可读文件', 'identity-changed': '分支、解析配置或项目身份变化',
'source-or-access-changed': '源码或读取权限变化', 'files-added-or-removed': '文件新增、删除或重命名', corrupt: '派生材料损坏,已重建',
unavailable: '派生缓存不可用,已重建', capacity: '超出缓存容量,保留当前检索结果', stored: '已保存派生材料', 'cleared-during-refresh': '核对期间已清除,未重新填入缓存' };
const reason = (value: string) => reasons[value] ?? value;
const size = (bytes: number) => bytes < 1024 * 1024 ? (bytes / 1024).toFixed(1) + ' KiB' : (bytes / (1024 * 1024)).toFixed(1) + ' MiB';
export function CodeIndexPanel({ project, active, onOpen }: {
project: Project; active: boolean; onOpen: (path: string, line: number, sha256: string) => void;
}) {
const [query, setQuery] = useState('');
const [kind, setKind] = useState<CodeQueryKind>('all');
const [result, setResult] = useState<CodeQuery | null>(null);
const [busy, setBusy] = useState(false);
const [error, setError] = useState('');
const [cacheInfo, setCacheInfo] = useState<ProjectCacheStatus | null>(null);
const [cacheMessage, setCacheMessage] = useState('');
const [cacheError, setCacheError] = useState('');
const request = useRef(0);
const initialLoad = useRef(false);
async function search(nextKind = kind) {
const current = ++request.current;
setBusy(true); setError(''); setCacheMessage('');
try {
const response = await api<CodeQuery>('/projects/' + project.id + '/code-query?query=' + encodeURIComponent(query.trim()) + '&kind=' + nextKind + '&limit=40');
if (current !== request.current || response.index.projectId !== project.id) return;
setResult(response);
if (response.index.cache) setCacheInfo({ ...response.index.cache, latest: response.index.cache });
} catch (cause) {
if (current === request.current) setError(cause instanceof Error ? cause.message : String(cause));
} finally { if (current === request.current) setBusy(false); }
}
async function changeCache(action: 'toggle' | 'clear', enabled?: boolean) {
const current = ++request.current; setBusy(true); setCacheError(''); setCacheMessage('');
try {
const response = await (action === 'toggle' ? api<ProjectCacheStatus>('/project-cache', { enabled })
: api<ProjectCacheStatus>('/projects/' + project.id + '/index-cache', {}, 'DELETE'));
if (current !== request.current) return;
setCacheInfo(response);
setCacheMessage(action === 'clear' ? '本项目派生缓存已清除;下次查询重新分析。工程、会话与原工件保留。'
: enabled ? '本机解析缓存已启用;下次查询按当前源码核对。' : '本机解析缓存已关闭;后续查询从当前源码重新分析。');
} catch (cause) { if (current === request.current) setCacheError(cause instanceof Error ? cause.message : String(cause)); }
finally { if (current === request.current) setBusy(false); }
}
useEffect(() => { request.current++; initialLoad.current = false; setResult(null); setCacheInfo(null); setCacheMessage(''); setCacheError('');
return () => { request.current++; initialLoad.current = false; }; }, [project.id, project.root]);
useEffect(() => {
if (active && !initialLoad.current) { initialLoad.current = true; void search(); }
}, [active, project.id, project.root]);
const index = result?.index, coverage = index?.coverage, metrics = cacheInfo?.latest ?? index?.cache;
return <section className="code-index-panel" aria-label="工程索引" hidden={!active}>
<header className="index-heading"><div><span className="field-eyebrow">当前项目 · {project.name}</span><h3>定位代码</h3></div>
<button className="icon-button" aria-label="刷新工程索引" title="重新核对文件变化并刷新结果" disabled={busy} onClick={() => void search()}>
{busy ? <LoaderCircle size={16} className="spin" /> : <RefreshCw size={16} />}
</button>
</header>
<form className="index-search" onSubmit={event => { event.preventDefault(); void search(); }}>
<label className="index-query"><Search size={15} /><input aria-label="索引查询" maxLength={200} placeholder="函数、类、文件名或导入" value={query} onChange={event => setQuery(event.target.value)} /></label>
<div className="index-search-controls"><select aria-label="索引结果类型" value={kind} onChange={event => { const next = event.target.value as CodeQueryKind; setKind(next); void search(next); }}>
<option value="all">全部结果</option><option value="symbols">符号声明</option><option value="imports">导入关系</option><option value="files">项目文件</option>
</select><button className="button primary" type="submit" disabled={busy}>{busy ? <LoaderCircle size={14} className="spin" /> : <Search size={14} />}查找</button></div>
</form>
<div className="index-scroll" aria-busy={busy}>
{error && <div className="index-error" role="alert"><strong>索引未刷新</strong><p>{error}</p><button className="button secondary" disabled={busy} onClick={() => void search()}>重试索引</button></div>}
{index && coverage && <>
<div className={'index-coverage ' + (coverage.truncated ? 'partial' : '')}>
<div><strong>{coverage.truncated ? '部分结果' : '当前范围已索引'}</strong><span>{new Date(index.generatedAt).toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit', second: '2-digit' })}</span></div>
<p>{coverage.fileCount} 个文件 · {coverage.symbolCount} 个符号 · {coverage.importCount} 处导入</p>
<span>本次 {index.refresh.updatedFiles} 更新 · {index.refresh.reusedFiles} 复用 · {index.refresh.removedFiles} 移除</span>
</div>
{cacheInfo && <details className="index-cache"><summary>解析缓存 · {cacheInfo.enabled ? '已启用' : '已关闭'}</summary>
<div className="index-cache-controls"><label><input type="checkbox" role="switch" aria-label="启用本机解析缓存" checked={cacheInfo.enabled} disabled={busy}
onChange={event => void changeCache('toggle', event.target.checked)} />启用本机解析缓存</label>
<button className="button secondary" disabled={busy} onClick={() => void changeCache('clear')}>清除本项目缓存</button></div>
<p>开关作用于本机所有项目;清除仅移除当前项目的派生解析材料。</p>
<p>{cacheInfo.diskProjects} / {cacheInfo.maximumProjects} 个项目 · 磁盘 {size(cacheInfo.diskBytes)} / {size(cacheInfo.maximumBytes)} · 单项目上限 {size(cacheInfo.maximumEntryBytes)}</p>
{metrics && <dl className="index-cache-metrics"><dt>上次检索核对</dt><dd>{new Date(metrics.checkedAt).toLocaleString('zh-CN')} · {metrics.sourceVerified ? `${metrics.verificationPasses} 轮 SHA 核对` : '范围不完整'}</dd>
<dt>解析材料</dt><dd>{reason(metrics.origin)} · {metrics.reusedFiles} 复用 / {metrics.parsedFiles} 重新解析</dd>
<dt>失效原因</dt><dd>{metrics.invalidation ? reason(metrics.invalidation) : '未发现已缓存来源变化'}</dd>
<dt>本次检索用时</dt><dd>{Math.round(metrics.durationMs)} ms · 其中解析 {metrics.parseMs.toFixed(1)} ms</dd>
<dt>派生存储</dt><dd>{reason(metrics.storageReason)}</dd></dl>}
<p>每次查询都核对当前来源。本地复用量与模型服务的 token 计费分别记录。</p>
{cacheInfo.error && <p className="index-cache-warning">{cacheInfo.error}</p>}
{cacheError && <p className="index-cache-warning" role="alert">缓存操作未完成:{cacheError} 可重试本次操作。</p>}
{cacheMessage && <p className="index-cache-feedback" aria-live="polite">{cacheMessage}</p>}
</details>}
<details className="index-scope"><summary>查看索引范围与依据</summary>
<p>{coverage.astFiles} 个 JS/TS/React 文件采用静态声明分析;{coverage.pythonCandidateFiles} 个 Python 文件提供声明候选。</p>
<p>已检查 {index.sourceScope.scannedFiles} 个文件,快照上限 {index.sourceScope.maximumFiles} 个文件;单文件符号分析上限 {Math.round(coverage.maximumFileBytes / 1000)} KB。</p>
<p>{index.sourceScope.note}</p>{index.notes.map(note => <p key={note}>{note}</p>)}
<code title={index.indexFingerprint}>索引 {index.indexFingerprint}</code>
<code title={index.sourceFingerprint}>源码 {index.sourceFingerprint}</code>
</details>
{index.warnings.length > 0 && <div className="index-warnings"><strong>{coverage.unindexedFiles} 个文件需要补充核对</strong>
{index.warnings.slice(0, 4).map(warning => <p key={warning.path}><span>{warning.path}</span>{warning.message}</p>)}
{index.warnings.length > 4 && <p>其余文件可按名称查询后读取当前内容。</p>}
</div>}
<div className="index-result-caption" role="status"><span>{result!.query ? `“${result!.query}”` : '当前结果'} · {result!.totalMatches} 项匹配</span><span>显示 {result!.results.length} 项</span></div>
<div className="index-results">{result!.results.map((item, position) => <button type="button" className="index-result" key={item.resultKind + item.path + item.line + position}
disabled={busy || !!error} aria-label={'打开 ' + item.path + ' 第 ' + item.line + ' 行 ' + resultName(item)} onClick={() => onOpen(item.path, item.line, item.sha256)}>
<div className="index-result-title"><FileCode2 size={14} /><strong>{resultName(item)}</strong><span>{item.resultKind === 'symbol' ? kindNames[item.kind] || '声明' : item.resultKind === 'import' ? '导入' : '文件'}</span><ArrowUpRight size={13} /></div>
<div className="index-result-location"><span>{item.path}</span><b>:{item.line}</b></div>
{item.signature && <code className="index-signature" title={item.signature}>{item.signature}</code>}
{item.resultKind === 'import' && <p className="index-target">{item.target ? '文件候选 → ' + item.target : item.status === 'external-or-alias' ? '外部模块或路径别名,目标未解析' : '当前范围没有对应本地文件'}</p>}
<div className="index-result-evidence"><span>{item.evidenceMethod === 'python-declaration-candidate' ? 'Python 候选 · 需读源码核对' : item.evidenceMethod === 'javascript-typescript-ast' ? '静态声明' : '文件指纹'}{item.exported ? ' · 已导出' : ''}</span><code>{item.sha256.slice(0, 10)}</code></div>
</button>)}</div>
{result!.results.length === 0 && <div className="index-empty"><Search size={22} /><h4>当前范围没有匹配</h4><p>调整名称、路径或结果类型;文件刚有变化时可刷新索引。</p></div>}
{result!.truncated && <p className="index-limit">这里只展示当前范围的有限结果。可以增加查询词缩小范围;无匹配不代表整个项目都没有该代码。</p>}
</>}
{!result && !error && <div className="index-empty"><LoaderCircle className="spin" size={22} /><h4>正在核对项目文件</h4><p>读取实际声明、导入及文件指纹。</p></div>}
</div>
</section>;
}
@@ -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>;
}
@@ -0,0 +1,58 @@
.git-delivery .record-footnote { display: block; }
.delivery-route { display: flex; align-items: center; gap: 5px; flex-wrap: wrap; font-size: 10px; margin: 13px 0 16px; color: var(--muted); }
.delivery-route span { border: 1px solid var(--line); border-radius: 4px; padding: 5px 7px; }
.delivery-route .done { background: #edf7ef; border-color: #b8d6c4; color: #277958; }
.delivery-route i { font-style: normal; }
.delivery-message { margin: 10px 0; font-size: 11px; }
.delivery-message textarea { resize: vertical; min-height: 58px; max-height: 150px; width: 100%; font-size: 11px; line-height: 1.7; padding: 9px; border: 1px solid var(--line); border-radius: 5px; background: white; }
.delivery-author { font-size: 11px; margin: 10px 0 15px; }
.delivery-author summary { cursor: pointer; color: var(--teal); }
.delivery-author p { color: var(--muted); font-size: 10px; line-height: 1.8; margin: 8px 0; }
.delivery-author .form-field { font-size: 11px; margin: 8px 0; }
.delivery-author input { padding: 7px 9px; font-size: 11px; }
.delivery-job { font-size: 11px; line-height: 1.8; padding: 14px 0; border-top: 1px solid var(--line); margin-top: 15px; }
.delivery-job .record-heading { flex-wrap: wrap; margin-bottom: 5px; }
.delivery-job time { color: var(--muted); font-size: 10px; }
.delivery-job > p { margin: 7px 0; overflow-wrap: anywhere; }
.delivery-current { display: flex; align-items: center; gap: 6px; color: var(--teal); }
.delivery-commit { display: flex; align-items: flex-start; gap: 6px; background: #edf3f1; padding: 8px; border-radius: 4px; margin-top: 8px; color: var(--teal); }
.delivery-commit svg { flex: none; margin-top: 3px; }
.delivery-commit code { overflow-wrap: anywhere; font-size: 10px; }
.delivery-paths { padding-left: 14px; margin: 10px 0; color: var(--muted); }
.delivery-paths li { overflow-wrap: anywhere; }
.delivery-preserved { display: flex; align-items: flex-start; gap: 6px; color: #277958; }
.delivery-preserved svg, .delivery-warning svg { flex: none; margin-top: 3px; }
.delivery-report-actions { display: flex; gap: 4px 10px; flex-wrap: wrap; margin-top: 8px; }
.delivery-report-actions .text-button { padding: 3px 0; }
.delivery-attention { padding: 12px; border: 1px solid #e7d8b8; background: #fffaf0; border-radius: 5px; }
.delivery-review-boundary { margin: 14px 0; font-size: 11px; line-height: 1.8; }
.delivery-review-boundary > p { margin: 7px 0; color: #805d22; overflow-wrap: anywhere; }
.delivery-warning { display: flex; align-items: flex-start; gap: 6px; color: #805d22; font-size: 11px; line-height: 1.8; }
.delivery-report-summary { border-top: 1px solid var(--line); padding-top: 16px; margin-top: 15px; }
.delivery-report-summary > .text-button { display: flex; margin-top: 8px; padding-left: 0; }
.delivery-confirm { flex: 1; min-height: 0; overflow: auto; font-size: 12px; }
.delivery-confirm-overview { display: flex; flex-direction: column; gap: 5px; border-left: 2px solid #7da89c; padding-left: 11px; margin-bottom: 16px; line-height: 1.7; }
.delivery-confirm-overview span { color: var(--muted); font-size: 11px; }
.delivery-confirm-message { white-space: pre-wrap; }
.delivery-checks { list-style: none; padding: 0; margin: 17px 0; font-size: 11px; }
.delivery-checks li { display: flex; align-items: flex-start; gap: 7px; margin-top: 9px; color: #277958; flex-wrap: wrap; }
.delivery-checks strong { font-family: "Cascadia Code", Consolas, monospace; font-size: 11px; }
.delivery-checks span { color: var(--muted); }
.delivery-policy { background: #faf7ef; color: #805d22; border-left: 2px solid #bd9654; padding: 10px 12px; font-size: 11px; line-height: 1.8; margin: 14px 0; }
.delivery-diffs details { border: 1px solid var(--line); border-radius: 5px; margin: 9px 0; overflow: hidden; }
.delivery-diffs summary { padding: 11px; background: #edf3f1; cursor: pointer; font-size: 11px; line-height: 1.6; }
.delivery-diffs summary span { overflow-wrap: anywhere; }
.delivery-diffs summary small { float: right; color: var(--muted); margin-left: 9px; font-size: 10px; }
.delivery-diffs p { font-size: 11px; line-height: 1.8; margin: 10px 12px; overflow-wrap: anywhere; }
.delivery-diffs pre { font-size: 11px; line-height: 1.7; overflow: auto; max-height: 340px; padding: 12px; background: #fcfdfc; }
.delivery-file-hash { display: block; padding: 9px 12px; font-size: 10px; color: var(--muted); overflow-wrap: anywhere; border-top: 1px solid var(--line); }
.status-preparing, .status-prepared, .status-publishing, .status-committed, .status-reporting { background: #edf3f1; color: var(--teal); }
@media (max-width: 620px) {
.delivery-confirm .record-fields { grid-template-columns: 76px minmax(0, 1fr); }
.delivery-confirm-overview strong { font-size: 12px; }
.delivery-checks li { column-gap: 5px; }
.delivery-checks span { width: 100%; padding-left: 18px; }
.delivery-diffs summary small { float: none; display: block; margin: 4px 0 0 13px; }
.delivery-report-actions { column-gap: 12px; }
}
@media (prefers-reduced-motion: reduce) { .delivery-current .spin { animation: none; } }
@@ -0,0 +1,137 @@
import { useEffect, useRef, useState } from 'react';
import { ArrowDownToLine, Check, FileCheck2, FileText, GitCommitHorizontal, LoaderCircle, RefreshCw, ShieldQuestion } from 'lucide-react';
import { api, downloadArtifact } from './api';
import { Modal, Status } from './components';
import type { DeliveryPlan, Session } from './types';
import './DeliveryPanel.css';
const active = ['queued', 'preparing', 'prepared', 'publishing', 'committed', 'reporting'];
const stageLabel: Record<string, string> = { queued: '正在核对提交基线', preparing: '正在准备已审核文件', prepared: '文件快照已准备', publishing: '正在生成本地提交', committed: '正在核对实际提交', reporting: '正在生成交付报告' };
const date = (value: string | null) => value ? new Date(value).toLocaleString('zh-CN', { month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit' }) : '执行中';
export function DeliveryPanel({ session, busy, onSession, onError, openArtifact }: {
session: Session; busy: boolean; onSession: (value: Session) => void; onError: (error: unknown) => void; openArtifact: (id: string) => void;
}) {
const task = session.execution?.task;
const jobs = session.execution?.deliveries ?? [];
const [message, setMessage] = useState('');
const [authorName, setAuthorName] = useState('');
const [authorEmail, setAuthorEmail] = useState('');
const [planning, setPlanning] = useState(false);
const [confirm, setConfirm] = useState<DeliveryPlan | null>(null);
const [submitting, setSubmitting] = useState(false);
const [reporting, setReporting] = useState(false);
const [reconciling, setReconciling] = useState('');
const [downloading, setDownloading] = useState(false);
const identity = useRef(0);
const inFlight = useRef(false);
const running = jobs.some(job => active.includes(job.status));
const unresolved = jobs.some(job => job.requiresVerification);
const pending = session.changes.some(change => ['pending', 'conflict'].includes(change.status));
const hasApplied = session.changes.some(change => change.taskId === task?.id && change.status === 'applied');
const existingOnly = !hasApplied && !!session.execution?.fileResults?.length;
const reports = session.execution?.artifacts.filter(artifact => artifact.kind === 'delivery-report-markdown') ?? [];
const latestReport = reports.at(-1);
const waitingPlan = (session.execution?.deliveryPlans ?? []).filter(plan => plan.taskId === task?.id
&& plan.runId === session.execution?.run?.id && ['planned', 'accepted'].includes(plan.status)
&& (session.execution?.run?.review?.status === 'pending' && session.execution.run.review.planId === plan.id || plan.preparedBy === 'agent' && plan.status === 'planned')).at(-1);
useEffect(() => {
identity.current++; setConfirm(null); setPlanning(false); setSubmitting(false); setReporting(false); setReconciling('');
setMessage(task ? '完成:' + task.goal.replace(/\s+/g, ' ').slice(0, 90) : ''); setAuthorName(''); setAuthorEmail('');
inFlight.current = false;
return () => { identity.current++; };
}, [session.id, task?.id]);
async function prepare() {
if (inFlight.current) return;
inFlight.current = true; setPlanning(true); const request = identity.current;
try {
const result = await api<Session>('/sessions/' + session.id + '/delivery-plans', { message, ...(authorName.trim() ? { authorName: authorName.trim() } : {}), ...(authorEmail.trim() ? { authorEmail: authorEmail.trim() } : {}) });
if (request !== identity.current) return;
onSession(result); setConfirm(result.execution?.deliveryPlans?.at(-1) ?? null);
} catch (error) { if (request === identity.current) onError(error); }
finally { if (request === identity.current) { inFlight.current = false; setPlanning(false); } }
}
async function commit() {
if (!confirm || inFlight.current) return;
inFlight.current = true; setSubmitting(true); const request = identity.current;
try {
const result = await api<Session>('/sessions/' + session.id + '/delivery-jobs', { planId: confirm.id });
if (request === identity.current) { onSession(result); setConfirm(null); }
} catch (error) { if (request === identity.current) onError(error); }
finally { if (request === identity.current) { inFlight.current = false; setSubmitting(false); } }
}
async function discard() {
if (!waitingPlan || inFlight.current) return;
inFlight.current = true; setSubmitting(true); const request = identity.current;
try {
const result = await api<Session>('/sessions/' + session.id + '/delivery-plans/' + waitingPlan.id + '/discard', {});
if (request === identity.current) { onSession(result); setConfirm(null); }
} catch (error) { if (request === identity.current) onError(error); }
finally { if (request === identity.current) { inFlight.current = false; setSubmitting(false); } }
}
async function report() {
if (inFlight.current) return;
inFlight.current = true; setReporting(true); const request = identity.current;
try {
const result = await api<Session>('/sessions/' + session.id + '/delivery-reports', {});
if (request !== identity.current) return;
onSession(result);
const artifact = result.execution?.artifacts.filter(value => value.kind === 'delivery-report-markdown').at(-1);
if (artifact) openArtifact(artifact.id);
} catch (error) { if (request === identity.current) onError(error); }
finally { if (request === identity.current) { inFlight.current = false; setReporting(false); } }
}
async function reconcile(jobId: string) {
if (inFlight.current) return;
inFlight.current = true; setReconciling(jobId); const request = identity.current;
try {
const result = await api<Session>('/sessions/' + session.id + '/delivery-jobs/' + jobId + '/reconcile', {});
if (request === identity.current) onSession(result);
} catch (error) { if (request === identity.current) onError(error); }
finally { if (request === identity.current) { inFlight.current = false; setReconciling(''); } }
}
async function download(id: string, extension: string) {
setDownloading(true);
try { await downloadArtifact(session.id, id, 'Agent-Workbench-delivery-' + (task?.id.slice(0, 8) ?? session.id.slice(0, 8)) + extension); }
catch (error) { onError(error); } finally { setDownloading(false); }
}
return <section className="task-record-section git-delivery" aria-label="Git交付">
<div className="record-heading"><GitCommitHorizontal size={16} /><h3>审核提交与交付</h3></div>
<p className="record-footnote">核对当前任务已应用的文件和实际测试,预览后生成本地提交。其他项目改动保留。</p>
<div className="delivery-route" aria-label="交付步骤"><span className={hasApplied && !pending ? 'done' : ''}>文件已审查</span><i>→</i><span className={task?.verification.status === 'passed' ? 'done' : ''}>实际检查</span><i>→</i><span className={jobs.some(job => job.status === 'completed') ? 'done' : ''}>本地提交</span></div>
{waitingPlan && <div className="delivery-attention delivery-review-boundary" aria-label="等待Git确认"><strong>Git预览已保存,等待确认</strong><p>{waitingPlan.paths.length} 个文件 · {waitingPlan.baseline.branch} · HEAD {waitingPlan.baseline.head.slice(0, 12)}</p><p>任务已暂停请求模型。审查现有预览后确认提交,或撤回预览再继续。</p><div className="delivery-report-actions"><button type="button" className="button primary" disabled={busy || running || submitting || waitingPlan.status !== 'planned'} onClick={() => setConfirm(waitingPlan)}>查看待确认预览</button><button type="button" className="button secondary" disabled={busy || running || unresolved || submitting} onClick={discard}>撤回预览</button></div>{waitingPlan.status === 'accepted' && <p>这份预览已尝试执行;请核对原结果,确认未提交后重新预览。</p>}</div>}
<label className="form-field delivery-message">提交说明<textarea aria-label="提交说明" rows={2} value={message} maxLength={1600} disabled={busy || running} onChange={event => setMessage(event.target.value)} /></label>
<details className="delivery-author"><summary>Git署名</summary><p>默认采用项目Git署名;尚未配置时使用 Agent Workbench 本地身份。预览会展示实际署名。</p><label className="form-field">提交者姓名<input value={authorName} disabled={busy || running} onChange={event => setAuthorName(event.target.value)} placeholder="采用默认署名" autoComplete="off" /></label><label className="form-field">提交者邮箱<input type="email" value={authorEmail} disabled={busy || running} onChange={event => setAuthorEmail(event.target.value)} placeholder="采用默认邮箱" autoComplete="off" /></label></details>
<button type="button" className="button primary" aria-label="预览Git提交" disabled={!task || !hasApplied || pending || busy || running || unresolved || planning || !message.trim()} onClick={prepare}>{planning ? <LoaderCircle size={14} className="spin" /> : <GitCommitHorizontal size={14} />}预览Git提交</button>
{existingOnly ? <p className="record-footnote">本任务沿用已有成果,无新增修改,不创建空提交。可生成报告核对成果与原检查。</p> : (!hasApplied || pending) && <p className="record-footnote">应用本任务的文件提案后,可以准备Git提交。</p>}
{jobs.slice().reverse().map(job => <div key={job.id} className={'delivery-job ' + (job.requiresVerification ? 'delivery-attention' : '')}>
<div className="record-heading"><Status value={job.status} /><code>{job.id.slice(0, 8)}</code>{active.includes(job.status) && <button type="button" className="text-button" onClick={() => api<Session>('/sessions/' + session.id + '/delivery-jobs/' + job.id + '/stop', {}).then(onSession).catch(onError)}>停止提交</button>}</div>
<time>{date(job.startedAt)} · {job.branch}</time>
{active.includes(job.status) && <p className="delivery-current"><LoaderCircle size={13} className="spin" />{stageLabel[job.status]}</p>}
{job.commit && <div className="delivery-commit"><GitCommitHorizontal size={14} /><code title={job.commit}>{job.commit}</code></div>}
<ul className="delivery-paths">{job.paths.map(relative => <li key={relative}>{relative}</li>)}</ul>
{job.summary && <p>{job.summary}</p>}
{job.requiresVerification && <><p className="delivery-warning"><ShieldQuestion size={14} />先核对实际提交;本次不会再次提交文件。匹配本次遗留索引锁时会完成索引恢复。</p><button type="button" className="button secondary" disabled={busy || !!reconciling} onClick={() => reconcile(job.id)}>{reconciling === job.id ? <LoaderCircle size={14} className="spin" /> : <RefreshCw size={14} />}核对提交结果</button></>}
{job.status === 'completed' && <p className="delivery-preserved"><FileCheck2 size={13} />实际提交已核对 · 无关修改已保留</p>}
{job.reportError && <p className="delivery-warning">提交已保存;报告生成失败,可以再次生成报告。</p>}
{job.reportMarkdownArtifactId && <div className="delivery-report-actions"><button type="button" className="text-button" onClick={() => openArtifact(job.reportMarkdownArtifactId!)}><FileText size={13} />查看交付报告</button><button type="button" className="text-button" disabled={downloading} onClick={() => download(job.reportMarkdownArtifactId!, '.md')}><ArrowDownToLine size={13} />下载Markdown</button>{job.reportArtifactId && <button type="button" className="text-button" disabled={downloading} onClick={() => download(job.reportArtifactId!, '.json')}>下载JSON</button>}</div>}
</div>)}
<div className="delivery-report-summary"><button type="button" className="button secondary" disabled={!task || busy || running || reporting || planning} onClick={report}>{reporting ? <LoaderCircle size={14} className="spin" /> : <FileText size={14} />}生成交付报告</button>
{latestReport && <button type="button" className="text-button" onClick={() => openArtifact(latestReport.id)}>查看最新报告</button>}
<p className="record-footnote">报告记录实际源码、检查、提交和模型用量,注明尚待确认的结果。</p>
</div>
{confirm && <Modal title="确认本地Git提交" description="核对以下文件、实际检查和提交署名后确认。" wide onClose={() => { if (!submitting) setConfirm(null); }}>
<div className="delivery-confirm">
<div className="delivery-confirm-overview"><strong>{confirm.paths.length} 个文件 · {confirm.baseline.branch}</strong><span>Task {confirm.taskId.slice(0, 8)} · HEAD {confirm.baseline.head.slice(0, 12)}</span></div>
<dl className="record-fields"><dt>提交说明</dt><dd className="delivery-confirm-message">{confirm.message}</dd><dt>实际署名</dt><dd>{confirm.author.name} &lt;{confirm.author.email}&gt;{confirm.author.source === 'workbench-local' && <small> · 工作台本地默认身份</small>}</dd><dt>源文件指纹</dt><dd><code>{confirm.sourceFingerprint}</code></dd><dt>检查记录</dt><dd><code>{confirm.checkJobId}</code></dd></dl>
<ul className="delivery-checks">{confirm.checkSummary.map(check => <li key={check.name}><Check size={13} /><strong>{check.command}</strong><span>退出码 {check.exitCode}{check.tests ? ' · ' + check.tests.passed + '/' + check.tests.total + ' 测试通过' : ''}</span></li>)}</ul>
<p className="delivery-policy">{confirm.policy.note}</p>
<div className="delivery-diffs">{confirm.files.map(file => <details key={file.path} open={confirm.files.length === 1}><summary><span>{file.path}</span><small>+{file.additions} / −{file.deletions}</small></summary><p>{file.reason}</p><pre aria-label={'提交差异 ' + file.path}>{file.diff}</pre><code className="delivery-file-hash">SHA256 {file.sha256}</code></details>)}</div>
</div>
<div className="modal-actions"><button type="button" className="button secondary" disabled={submitting} onClick={() => setConfirm(null)}>返回修改</button><button type="button" className="button primary" aria-label="确认创建本地提交" disabled={submitting} onClick={commit}>{submitting ? <LoaderCircle size={14} className="spin" /> : <Check size={14} />}确认创建本地提交</button></div>
</Modal>}
</section>;
}
@@ -0,0 +1,28 @@
import { useEffect, useRef, useState } from 'react';
import { ClipboardCheck, FolderOpen, Monitor, RotateCw, Square } from 'lucide-react';
import type { OpenFile, Project, Session } from './types';
import { desktop, type DesktopHostStatus, type DesktopTaskScope } from './desktop';
export function DesktopPanel({ project, session, file, onProject, onReview }: {
project?: Project; session: Session | null; file: OpenFile | null; onProject(project: Project): Promise<void>; onReview(scope: DesktopTaskScope): void;
}) {
const [status, setStatus] = useState<DesktopHostStatus | null>(null), [busy, setBusy] = useState(''), [error, setError] = useState('');
const alive = useRef(true);
useEffect(() => { alive.current = true; void refresh(); return () => { alive.current = false; }; }, []);
async function act(name: string, action: () => Promise<unknown>) {
if (busy || !desktop) return;
setBusy(name); setError('');
try { await action(); } catch (value) { if (alive.current) setError(value instanceof Error ? value.message : '本机操作失败,请核对当前宿主。'); }
finally { if (alive.current) setBusy(''); }
}
async function refresh() { await act('refresh', async () => { const value = await desktop!.status(); if (alive.current) setStatus(value); }); }
const task = session?.execution?.task, scope = project && session && task ? { projectId: project.id, sessionId: session.id, taskId: task.id } : null;
return <div className="desktop-panel">
<div className="desktop-host-heading"><Monitor size={21} /><div><strong>{status?.state === 'ready' ? '执行宿主正在运行' : status?.state === 'stopping' ? '所属任务正在停止' : '正在核对执行宿主'}</strong><p>关闭窗口后,后台任务继续。重新打开可查看原任务进度。</p></div><button className="button secondary" disabled={!!busy} onClick={() => void refresh()}><RotateCw size={14} />刷新</button></div>
{status?.identity && <dl className="desktop-host-facts"><dt>当前程序</dt><dd>v{status.identity.version} · PID {status.identity.pid}</dd><dt>后台任务</dt><dd>{status.activity?.active ? '有所属操作正在执行' : '当前没有活动操作'} · {status.activity?.unresolvedTools || 0} 项结果待核对</dd><dt>桌面窗口</dt><dd>{status.desktopWindows?.count || 0} 个已登记窗口</dd><dt>会话与连接</dt><dd className="code-utility">{status.identity.dataRoot}</dd><dt>运行目录</dt><dd className="code-utility">{status.identity.runtimeRoot}</dd></dl>}
<div className="desktop-project-actions"><button className="button primary" disabled={!!busy} onClick={() => void act('pick', async () => { const picked = await desktop!.pickProject(); if (picked && alive.current) await onProject(picked); })}><FolderOpen size={15} />选择项目文件夹</button><button className="button secondary" disabled={!!busy || !project} onClick={() => void act('folder', () => desktop!.projectFolder(project!.id))}>打开项目目录</button><button className="button secondary" disabled={!!busy || !scope} onClick={() => void act('review', async () => { const original = scope!; await desktop!.reviewTask(original); if (alive.current) onReview(original); })}><ClipboardCheck size={15} />审查当前任务</button><button className="button secondary" disabled={!!busy || !scope || !file} onClick={() => void act('reveal', () => desktop!.revealFile({ ...scope!, path: file!.path, sha256: file!.sha256 }))}>定位当前文件</button></div>
{!scope && <p className="desktop-scope-note">选择已有任务后,可核对任务归属并审查成果。读取文件后可在文件管理器中定位。</p>}
{error && <p className="desktop-error" role="alert">{error}</p>}
<div className="desktop-stop-row"><div><strong>退出执行宿主</strong><p>停止所属任务、模型请求和工具进程,再退出桌面。系统会要求确认。</p></div><button className="button secondary" disabled={!!busy} onClick={() => void act('stop', async () => { const result = await desktop!.stopHost(); if (result.cancelled && alive.current) { const updated = await desktop!.status(); if (alive.current) setStatus(updated); } })}><Square size={13} />停止并退出</button></div>
</div>;
}
@@ -0,0 +1,24 @@
import { Activity, LoaderCircle, RotateCw } from 'lucide-react';
import type { RuntimeDiagnostics } from './types';
import { Status } from './components';
import { ModelErrorDetails } from './ModelErrorDetails';
export function DiagnosticsPanel({ value, busy, onRefresh }: { value: RuntimeDiagnostics | null; busy: boolean; onRefresh: () => void }) {
if (!value) return <div className="diagnostic-loading"><LoaderCircle size={20} className="spin" />{busy ? '正在读取本机执行记录…' : '诊断记录暂时不可用,请刷新重试。'}<button type="button" className="button secondary" disabled={busy} onClick={onRefresh}>刷新</button></div>;
const failure = value.session?.lastFailure;
return <div className="diagnostic-panel">
<div className="diagnostic-intro"><Activity size={18} /><div><strong>Agent Workbench {value.version}</strong><p>依据本机保存的执行记录检查当前状态。</p></div><button type="button" className="button secondary" onClick={onRefresh} disabled={busy}><RotateCw size={13} className={busy ? 'spin' : ''} />刷新</button></div>
<div className="diagnostic-grid"><section><h3>运行环境</h3><dl><dt>终端</dt><dd>{value.environment.shell}</dd><dt>Node.js</dt><dd>{value.environment.node}</dd><dt>输入与输出</dt><dd>{value.environment.encoding}</dd></dl><p className="diagnostic-note">{value.environment.shellSyntax}</p></section>
<section><h3>模型连接</h3><dl><dt>模式</dt><dd>{value.connection.mode === 'demo' ? '离线演示' : '兼容模型服务'}</dd><dt>模型</dt><dd>{value.connection.model || '未配置'}</dd><dt>服务地址</dt><dd>{value.connection.endpoint}</dd><dt>凭据状态</dt><dd>{value.connection.hasKey ? '本次运行已配置' : '未配置'}</dd></dl>{value.connection.lastRequest && <p className="diagnostic-note">最近请求:{value.connection.lastRequest.status === 'completed' ? '成功' : value.connection.lastRequest.status === 'retrying' ? '重试中' : value.connection.lastRequest.status === 'interrupted' ? '已停止' : '失败'} · {value.connection.lastRequest.attempts ?? 1} 次</p>}</section></div>
{value.session && <section className="diagnostic-session"><div className="diagnostic-section-heading"><h3>当前项目与会话</h3><Status value={value.session.session.status} /></div><strong>{value.session.project.name}</strong><p className="diagnostic-path">{value.session.project.root}</p><p className="diagnostic-note">{value.session.changes.filter(change => change.status === 'applied').length} 项已应用 · {value.session.changes.filter(change => ['pending', 'conflict'].includes(change.status)).length} 项待处理</p></section>}
{value.projectCache && <section aria-label="解析缓存诊断"><h3>项目解析缓存</h3><dl><dt>本机开关</dt><dd>{value.projectCache.enabled ? '已启用' : '已关闭'}</dd>
<dt>派生存储</dt><dd>{value.projectCache.diskProjects} / {value.projectCache.maximumProjects} 个项目 · {(value.projectCache.diskBytes / 1024 / 1024).toFixed(2)} / {(value.projectCache.maximumBytes / 1024 / 1024).toFixed(0)} MiB</dd>
<dt>当前进程</dt><dd>{value.projectCache.memoryProjects ?? 0} 个项目 · {value.projectCache.pending ?? 0} 个核对中</dd>
<dt>当前项目上次核对</dt><dd>{value.projectCache.latest ? new Date(value.projectCache.latest.checkedAt).toLocaleString('zh-CN') : '本次进程尚未检索'}</dd></dl>
{value.projectCache.latest && <p className="diagnostic-note">{value.projectCache.latest.reusedFiles} 份解析材料复用,{value.projectCache.latest.parsedFiles} 份重新解析;来源{value.projectCache.latest.sourceVerified ? '已核对' : '范围不完整'}。</p>}
<p className="diagnostic-note">在工程「索引 → 解析缓存」管理开关与清除。此处仅显示派生缓存状态,不触发工程检索或模型请求。</p>{value.projectCache.error && <p className="diagnostic-note">{value.projectCache.error}</p>}</section>}
{failure && <section className="diagnostic-failure"><div className="diagnostic-section-heading"><h3>最近的错误记录</h3><span>{failure.source === 'model_connection' ? '模型服务请求' : '工作台任务'}</span></div><strong>{failure.title}</strong><p>{failure.message}</p><ModelErrorDetails failure={failure} />{failure.occurredAt && <small>{new Date(failure.occurredAt).toLocaleString('zh-CN')}</small>}{failure.suggestion && <p className="diagnostic-note">{failure.suggestion}</p>}</section>}
{!!value.session?.changes.length && <section><h3>文件改动的实际状态</h3><div className="diagnostic-changes">{value.session.changes.map(change => <div key={change.id}><code>{change.path}</code><Status value={change.status} /></div>)}</div></section>}
{!!value.session?.recentTools.length && <section><h3>近期工具结果</h3><div className="diagnostic-tools">{value.session.recentTools.slice(-8).map((tool, index) => <details key={index}><summary><code>{tool.tool}</code><Status value={tool.phase} />{tool.exitCode !== null && <span>退出码 {tool.exitCode}</span>}</summary><pre>{tool.outputExcerpt || '没有文本输出。'}</pre></details>)}</div></section>}
</div>;
}
@@ -0,0 +1,4 @@
.embedded-browser{display:flex;flex-direction:column;min-height:0;overflow:auto;flex:1;background:#f7f9fc;color:#203248}.browser-panel-heading{display:flex;align-items:center;justify-content:space-between;gap:8px;padding:12px 14px;border-bottom:1px solid #d7e0eb}.browser-panel-heading strong{font-size:13px}.browser-tabstrip{display:flex;overflow:auto;flex-shrink:0;background:#edf2f8;padding:6px 8px 0;gap:3px}.browser-tabstrip button{border:0;background:transparent;display:flex;gap:6px;align-items:center;max-width:190px;padding:9px 12px;font-size:11px;color:#425871;border-radius:5px 5px 0 0}.browser-tabstrip button[aria-selected=true]{background:#fff;color:#203248}.browser-tabstrip span{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.browser-addressbar{display:flex;align-items:center;gap:4px;padding:9px 10px;background:#fff;border-bottom:1px solid #dde4ee;flex-shrink:0}.browser-addressbar button{display:grid;place-items:center;min-width:28px;min-height:30px;border:0;background:transparent;color:#334e6d}.browser-addressbar code{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-size:11px;color:#263f60}.browser-source{display:flex;flex-wrap:wrap;justify-content:space-between;gap:4px;padding:6px 14px;background:#f0f4f9;font-size:10px;color:#455b76}.native-browser-slot{height:360px;min-height:260px;flex-shrink:0;display:flex;align-items:center;justify-content:center;flex-direction:column;background:#fff;color:#62748c;border-bottom:1px solid #d8e1ec}.native-browser-slot p{font-size:12px}.browser-empty{padding:40px 24px;min-height:240px;display:flex;align-items:center;justify-content:center;flex-direction:column;text-align:center;color:#526780}.browser-empty h3{font-size:15px;color:#233d5d;margin-top:16px}.browser-empty p{font-size:12px;line-height:1.8;max-width:320px}.browser-saved-image{margin:0;background:#fff}.browser-saved-image img{display:block;max-width:100%;height:auto}.browser-saved-image figcaption{font-size:11px;padding:8px 14px;color:#536980}.browser-evidence{padding:14px;font-size:12px}.browser-evidence-heading{display:flex;align-items:center;justify-content:space-between;gap:8px}.browser-evidence-stamp{display:flex;align-items:center;gap:5px;font-size:10px;color:#3e596f;flex-wrap:wrap}.browser-sha{display:block;overflow-wrap:anywhere;color:#4d6279;font-size:10px;margin-bottom:12px}.browser-evidence details{margin:10px 0;border-top:1px solid #d7e0eb;padding-top:10px}.browser-evidence summary{cursor:pointer;color:#2b4665}.browser-evidence pre{white-space:pre-wrap;overflow-wrap:anywhere;max-height:260px;overflow:auto;padding:10px;background:#edf2f8;font-size:11px}.browser-controls>div{display:grid;grid-template-columns:30px 1fr auto;gap:6px;align-items:center;border-bottom:1px solid #e0e6ee;padding:9px 0}.browser-controls span{overflow-wrap:anywhere}.browser-controls button{border:1px solid #becbdc;background:white;padding:5px 8px;border-radius:4px;color:#2a486b}.browser-receipts>div{display:flex;flex-wrap:wrap;gap:5px 10px;border-top:1px solid #d7e0eb;padding:10px 0;font-size:11px}.browser-receipts strong{font-weight:600}.browser-receipts p{flex-basis:100%;margin:0;color:#8b2d36;overflow-wrap:anywhere}.browser-choice{display:flex;align-items:start;gap:8px;font-size:12px;line-height:1.7;margin:12px 0}.browser-choice input{margin-top:4px}.browser-inline-error{margin:12px 14px;color:#982b37;font-size:12px;overflow-wrap:anywhere}.browser-inline-note{margin:10px 14px;font-size:12px;line-height:1.7;color:#4b617c}.browser-addressbar button:disabled{opacity:.4}.browser-tabstrip button:focus-visible,.browser-addressbar button:focus-visible{outline:2px solid #3a699f;outline-offset:-2px}@media(max-width:620px){.native-browser-slot{height:320px}.browser-tabstrip button{max-width:155px}.browser-panel-heading{padding:11px 12px}}
.inspector-tabs>button:not(.icon-button){min-width:0;padding-left:7px;padding-right:7px;gap:4px;flex:1;white-space:nowrap}.inspector-tabs>.icon-button{flex:0 0 28px;width:28px}.project-sidebar .session-item.selected .session-select,.project-sidebar .session-item.selected .session-select span{color:#213f59}.project-sidebar .session-item.selected .session-select svg{color:#46627a}
.inspector{position:relative}.inspector-resize-handle{position:absolute;left:0;top:0;bottom:0;width:7px;z-index:2;cursor:col-resize;touch-action:none}.inspector-resize-handle:hover,.inspector-resize-handle:focus-visible,.inspector-resizing .inspector-resize-handle{background:#497b9d55;outline:0}.inspector-resizing{user-select:none;cursor:col-resize}
.inspector-resizing:after{content:"";position:fixed;inset:0;z-index:25;cursor:col-resize}
@@ -0,0 +1,60 @@
import { useEffect, useRef, useState } from 'react';
import { ArrowLeft, ArrowRight, Camera, ExternalLink, Globe2, Plus, RefreshCw, ShieldCheck, X } from 'lucide-react';
import { api, browsingScreenshot, downloadArtifact } from './api';
import { desktop } from './desktop';
import { Modal } from './components';
import type { BrowsingSnapshot, BrowsingObservation, Project, Session } from './types';
import './EmbeddedBrowserPanel.css';
const labels:Record<string,string>={open:'已打开',closed:'已关闭',revoked:'授权已撤销',unavailable:'桌面连接已结束',queued:'等待桌面执行',dispatched:'已派发,等待原回执',completed:'原回执已保存',failed:'执行失败',unknown:'结果未知,先核对原页面',interrupted:'已中断'};
export function EmbeddedBrowserPanel({project,session,onSession,onError,onReturn}:{project:Project;session:Session;onSession:(session:Session)=>void;onError:(error:unknown)=>void;onReturn:()=>void}) {
const [snapshot,setSnapshot]=useState<BrowsingSnapshot|null>(null),[selected,setSelected]=useState(''),[working,setWorking]=useState(''),[failure,setFailure]=useState('');
const [open,setOpen]=useState(false),[url,setUrl]=useState(''),[extraOrigins,setExtraOrigins]=useState(''),[interact,setInteract]=useState(true),[persistent,setPersistent]=useState(false),[profileId,setProfileId]=useState('');
const [inputValue,setInputValue]=useState(''),[downloadUrl,setDownloadUrl]=useState(''),[confirm,setConfirm]=useState<{action:string;ref?:string;label?:string;value?:string;url?:string}|null>(null),[clear,setClear]=useState(false);
const [image,setImage]=useState(''),[imageError,setImageError]=useState(''),scope=useRef(0),loadSequence=useRef(0),view=useRef<HTMLDivElement>(null);
const tabs=snapshot?.tabs??[],tab=tabs.find(value=>value.id===selected)??tabs.filter(value=>value.status==='open').at(-1)??tabs.at(-1);
const observation=snapshot?.observations.find(value=>value.id===tab?.observationId), preview=session.execution?.previewJobs?.filter(job=>job.status==='ready').at(-1);
async function refresh() {const original=scope.current,request=++loadSequence.current;try{const value=await api<BrowsingSnapshot>('/sessions/'+session.id+'/browsing');if(original===scope.current&&request===loadSequence.current)setSnapshot(value);}catch(error){if(original===scope.current)setFailure(error instanceof Error?error.message:String(error));}}
useEffect(()=>{scope.current++;setSnapshot(null);setSelected('');setWorking('');setFailure('');setConfirm(null);setOpen(false);setClear(false);setProfileId('');void refresh();const timer=setInterval(()=>void refresh(),2000);return()=>{scope.current++;clearInterval(timer);};},[session.id,session.execution?.task?.id]);
useEffect(()=>{let disposed=false,objectUrl='';setImage('');setImageError('');if(observation)browsingScreenshot(session.id,observation.id).then(value=>{objectUrl=value;if(disposed)URL.revokeObjectURL(value);else setImage(value);}).catch(error=>{if(!disposed)setImageError(error.message);});return()=>{disposed=true;if(objectUrl)URL.revokeObjectURL(objectUrl);};},[observation?.id,session.id]);
useEffect(()=>{
if(!desktop?.browsingLayout)return;
let last='',disposed=false;
const update=()=>{if(disposed)return;const box=view.current?.getBoundingClientRect();const visible=!!box&&tab?.status==='open'&&box.width>=80&&box.height>=80&&box.x>=0&&box.y>=0&&!document.hidden&&!document.querySelector('[role="dialog"][aria-modal="true"],.inspector-resizing');
const input=visible?{projectId:project.id,sessionId:session.id,taskId:tab!.taskId,tabId:tab!.id,visible:true,bounds:{x:Math.round(box!.x),y:Math.round(box!.y),width:Math.floor(Math.min(box!.width,window.innerWidth-box!.x)),height:Math.floor(Math.min(box!.height,window.innerHeight-box!.y))}}:{visible:false};
const key=JSON.stringify(input);if(key===last)return;last=key;void desktop!.browsingLayout!(input).catch(()=>{last='';});};
const resize=new ResizeObserver(update);if(view.current)resize.observe(view.current);const mutations=new MutationObserver(update);mutations.observe(document.body,{subtree:true,childList:true,attributes:true,attributeFilter:['class','style','aria-hidden']});
window.addEventListener('resize',update);window.addEventListener('scroll',update,true);document.addEventListener('visibilitychange',update);const timer=setInterval(()=>{last='';update();},800);update();
return()=>{disposed=true;resize.disconnect();mutations.disconnect();clearInterval(timer);window.removeEventListener('resize',update);window.removeEventListener('scroll',update,true);document.removeEventListener('visibilitychange',update);void desktop!.browsingLayout!({visible:false}).catch(()=>{});};
},[tab?.id,tab?.status,session.id,project.id]);
async function perform(action:string,input:unknown={}) {const original=scope.current;setWorking(action);setFailure('');try{const result=await api<Session>('/sessions/'+session.id+'/'+action,input);if(original===scope.current){onSession(result);setConfirm(null);setOpen(false);setClear(false);await refresh();}}catch(error){if(original===scope.current){setFailure(error instanceof Error?error.message:String(error));onError(error);}}finally{if(original===scope.current)setWorking('');}}
function act(action:{action:string;ref?:string;value?:string;url?:string;amount?:number;milliseconds?:number}) {if(!tab||!observation)return;void perform('browsing/tabs/'+tab.id+'/act',{...action,observationId:observation.id,revision:observation.revision,approved:true});}
const canAct=!!observation&&tab?.status==='open'&&tab.interact&&!working;
return <section className="embedded-browser" aria-label="内置浏览器">
<div className="browser-panel-heading"><button type="button" className="text-button" onClick={onReturn}><ArrowLeft size={14}/>返回任务</button><strong>浏览区</strong><button type="button" className="text-button" disabled={!!working} onClick={()=>{setUrl(preview?.url??'');setOpen(true);}}><Plus size={14}/>打开目标</button></div>
<div className="browser-tabstrip" role="tablist" aria-label="所属浏览标签页">{tabs.filter(value=>value.status==='open').map(value=><button type="button" role="tab" aria-selected={value.id===tab?.id} key={value.id} onClick={()=>setSelected(value.id)} title={value.url}><Globe2 size={13}/><span>{value.title||new URL(value.url).host}</span></button>)}</div>
{tab&&<><div className="browser-addressbar"><button type="button" title="后退" aria-label="浏览后退" disabled={!canAct} onClick={()=>act({action:'back'})}><ArrowLeft size={15}/></button><button type="button" title="前进" aria-label="浏览前进" disabled={!canAct} onClick={()=>act({action:'forward'})}><ArrowRight size={15}/></button><button type="button" aria-label="刷新浏览页面" disabled={!canAct} onClick={()=>act({action:'reload'})}><RefreshCw size={14}/></button><code title={tab.url}>{tab.url}</code><button type="button" aria-label="关闭浏览标签页" disabled={!!working||tab.status!=='open'} onClick={()=>perform('browsing/tabs/'+tab.id+'/close',{approved:true})}><X size={14}/></button></div>
<div className="browser-source"><span>{project.name} · Task {tab.taskId.slice(0,8)}</span><span>{labels[tab.status]??tab.status}</span></div></>}
{failure&&<p role="alert" className="browser-inline-error">{failure}</p>}
{!snapshot?.available&&<p className="browser-inline-note">桌面浏览器未连接。请打开本工作台桌面端;网页端仍可核对已有观察和原动作。</p>}
{tab?.status==='open'&&desktop?.browsingLayout?<div className="native-browser-slot" ref={view}><Globe2 size={28}/><p>所属网页在此区域显示</p></div>:image?<figure className="browser-saved-image"><img src={image} alt="所属标签页原观察截图"/><figcaption>原页面观察 · {observation?new Date(observation.createdAt).toLocaleString('zh-CN'):''}</figcaption></figure>:<div className="browser-empty"><Globe2 size={30}/><h3>在任务旁核对真实页面</h3><p>普通 HTML 可从左侧文件列表直接打开预览。需要运行的应用先启动项目预览,网站请从「打开目标」授权。页面观察与动作保存在本任务中。</p></div>}
{imageError&&<p role="alert" className="browser-inline-error">{imageError}</p>}
{tab&&<div className="browser-evidence"><div className="browser-evidence-heading"><strong>页面观察与原动作</strong><button type="button" className="text-button" disabled={!!working||tab.status!=='open'||!snapshot?.available} onClick={()=>perform('browsing/tabs/'+tab.id+'/observe')}><Camera size={14}/>重新观察</button></div>
{observation&&<><p className="browser-evidence-stamp"><ShieldCheck size={13}/>{image?'原截图 SHA-256 已核对':imageError?'原截图核对未通过':'正在核对原截图'} · {new Date(observation.createdAt).toLocaleTimeString('zh-CN')}{!observation.scope.complete?' · 有界采样,未覆盖全部内容':''}</p><code className="browser-sha">{observation.screenshotSha256}</code>
<details><summary>可见页面文字(网站提供的任务数据)</summary><pre>{observation.text}</pre></details>
<details><summary>可见控件 · {observation.controls.length} 项</summary><div className="browser-controls">{observation.controls.map(control=><div key={control.ref}><code>{control.ref}</code><span>{control.label}</span><button type="button" disabled={!canAct||control.disabled||control.restricted} onClick={()=>{setInputValue('');setConfirm({action:control.tag==='input'||control.tag==='textarea'?'fill':'click',ref:control.ref,label:control.label});}}>{control.tag==='input'||control.tag==='textarea'?'输入':'点击'}</button></div>)}</div></details></>}
<details><summary>网站授权与登录资料</summary><p>{tab.origins.join('、')}</p><p>{tab.interact?'允许原审批后的固定交互':'仅代理观察'} · {tab.persistent?'独立持久登录资料':'独立临时登录资料'}</p><button className="button secondary" type="button" disabled={!!working} onClick={()=>setClear(true)}>撤销并清除登录资料</button></details>
<details><summary>按明确地址下载文件</summary><label className="form-field">本次下载地址<input aria-label="浏览下载地址" type="url" value={downloadUrl} onChange={event=>setDownloadUrl(event.target.value)}/></label><button className="button secondary" type="button" disabled={!canAct||!downloadUrl} onClick={()=>setConfirm({action:'download',url:downloadUrl,label:'下载地址:'+downloadUrl+'。原字节保存在任务工件中,单次最多6MiB,不自动打开文件。'})}>核对本次下载</button></details>
<div className="browser-receipts">{snapshot?.actions.filter(action=>action.tabId===tab.id).slice(-6).reverse().map(action=><div key={action.id}><strong>{action.input.action??({open:'打开页面',observe:'观察页面',close:'关闭页面',clear:'清除资料'}[action.kind]??action.kind)}</strong><span>{labels[action.status]??action.status}</span>{action.error&&<p>{action.error}</p>}{action.downloadArtifactId&&<button type="button" className="text-button" onClick={()=>void downloadArtifact(session.id,action.downloadArtifactId!,'browser-download-'+action.id+'.bin').catch(onError)}>保存原下载文件</button>}{action.status==='unknown'&&!action.reconciliation&&<button type="button" className="text-button" disabled={!!working} onClick={()=>setConfirm({action:'acknowledge',ref:action.id,label:'我已核对原页面与动作记录,保留未知结果,不重放原提交。'})}>核对并保留原未知结果</button>}</div>)}</div>
</div>}
{open&&<Modal title="打开浏览目标" description="授权范围只用于当前任务,网页文字不能扩展权限。" onClose={()=>{if(!working)setOpen(false);}}><form onSubmit={event=>{event.preventDefault();void perform('browsing/tabs',{url,origins:extraOrigins.split(/[\n,,]/).map(value=>value.trim()).filter(Boolean),interact,persistent,approved:true,...(profileId?{profileId}:{}),...(preview&&url.startsWith(new URL(preview.url).origin+'/')?{previewJobId:preview.id}:{})});}}>
<label className="form-field">目标地址<input aria-label="浏览目标地址" type="url" required value={url} onChange={event=>setUrl(event.target.value)}/></label>
<label className="form-field">另外允许的资源来源(可选,每行一个HTTPS来源)<textarea value={extraOrigins} onChange={event=>setExtraOrigins(event.target.value)} rows={2}/></label>
<label className="browser-choice"><input type="checkbox" checked={interact} onChange={event=>setInteract(event.target.checked)}/>允许经本次审批的点击、输入、导航和下载</label><label className="browser-choice"><input type="checkbox" checked={persistent} onChange={event=>setPersistent(event.target.checked)}/>保存独立登录资料,关闭标签页后保留</label>
{!!snapshot?.profiles.length&&<label className="form-field">使用本会话已有登录资料<select value={profileId} onChange={event=>setProfileId(event.target.value)}><option value="">创建独立资料</option>{snapshot.profiles.filter(profile=>profile.status==='active').map(profile=><option key={profile.id} value={profile.id}>{profile.origins.join('、')} · {profile.id.slice(0,8)}</option>)}</select></label>}
<p className="record-footnote">新窗口、设备权限、外部协议和自动下载默认拒绝。代理不填写密码或选择本地文件;下载需要明确地址与单次审批。</p>{failure&&<p role="alert" className="browser-inline-error">{failure}</p>}<div className="modal-actions"><button className="button secondary" type="button" disabled={!!working} onClick={()=>setOpen(false)}>取消</button><button className="button primary" type="submit" disabled={!!working||!snapshot?.available}><ExternalLink size={14}/>确认授权并打开</button></div>
</form></Modal>}
{confirm&&<Modal title="核对本次页面动作" onClose={()=>{if(!working)setConfirm(null);}}><p>{confirm.label}</p>{confirm.action==='fill'&&<label className="form-field">本次输入<input aria-label="页面字段输入" maxLength={4000} value={inputValue} onChange={event=>setInputValue(event.target.value)}/></label>}<p className="record-footnote">只执行一次。页面已变化则需要重新观察;结果未知时先核对原页面,不自动重试。</p>{failure&&<p role="alert" className="browser-inline-error">{failure}</p>}<div className="modal-actions"><button className="button secondary" type="button" onClick={()=>setConfirm(null)} disabled={!!working}>取消</button><button className="button primary" type="button" disabled={!!working} onClick={()=>{if(confirm.action==='acknowledge')void perform('browsing/actions/'+confirm.ref+'/acknowledge',{approved:true});else {const {label,...action}=confirm;act({...action,...(confirm.action==='fill'?{value:inputValue}:{})});}}}>确认执行一次</button></div></Modal>}
{clear&&tab&&<Modal title="撤销网站授权并清除登录资料" onClose={()=>setClear(false)}><p>将关闭这份登录资料的页面,清除该资料的 Cookie、站点存储和缓存。原页面观察、截图及动作记录保留。开发服务需要另外停止。</p><div className="modal-actions"><button className="button secondary" type="button" onClick={()=>setClear(false)} disabled={!!working}>取消</button><button className="button primary" type="button" disabled={!!working} onClick={()=>perform('browsing/tabs/'+tab.id+'/clear',{approved:true})}>确认撤销并清除</button></div></Modal>}
</section>;
}
@@ -0,0 +1,73 @@
.engine-panel { color: var(--ink); min-width: 0; }
.engine-heading { display: flex; align-items: flex-start; justify-content: space-between; gap: 24px; margin-bottom: 23px; }
.engine-eyebrow { color: var(--teal); font-size: 11px; letter-spacing: .04em; }
.engine-heading h3 { font-size: 23px; font-weight: 650; letter-spacing: -.035em; line-height: 1.4; margin: 5px 0 8px; }
.engine-heading p { color: var(--muted); font-size: 12px; line-height: 1.8; max-width: 570px; }
.engine-install-state { color: #8b5734; font-size: 11px; border: 1px solid #e8dccc; border-radius: 5px; padding: 6px 9px; flex-shrink: 0; margin-top: 7px; }
.engine-install-state.found { color: var(--teal); background: #eff7f3; border-color: #c6ded4; }
.engine-layout { display: grid; grid-template-columns: minmax(240px, .82fr) minmax(0, 1.45fr); gap: 24px; }
.engine-connection, .engine-results { min-width: 0; }
.engine-panel h4 { display: flex; align-items: center; gap: 8px; font-size: 13px; font-weight: 650; margin-bottom: 14px; }
.engine-connection form { border: 1px solid var(--line); border-radius: 7px; background: var(--paper); padding: 18px; }
.engine-connection .form-field { margin-bottom: 13px; }
.engine-detection-note { font-size: 12px; line-height: 1.8; color: #8b5734; margin: 13px 0; overflow-wrap: anywhere; }
.engine-detection-note.available { color: var(--teal); }
.engine-install-details { display: grid; grid-template-columns: 70px minmax(0, 1fr); gap: 10px; font-size: 11px; margin: 16px 0; }
.engine-install-details dt { color: var(--muted); }
.engine-install-details dd { margin: 0; line-height: 1.7; overflow-wrap: anywhere; }
.engine-start { margin-top: 14px; }
.engine-scope { padding: 23px 2px 0; }
.engine-scope > p { display: flex; align-items: center; gap: 7px; color: var(--teal); font-size: 12px; margin-bottom: 12px; }
.engine-scope-next { border-top: 1px solid var(--line); margin-top: 19px; padding-top: 15px; }
.engine-scope-next > span { font-size: 11px; color: #59706b; }
.engine-scope-next p, .engine-scope details p { font-size: 12px; color: var(--muted); line-height: 1.85; margin-top: 8px; }
.engine-scope details { margin-top: 17px; font-size: 11px; color: var(--muted); }
.engine-scope summary { cursor: pointer; }
.engine-results-heading { display: flex; align-items: flex-start; justify-content: space-between; gap: 12px; }
.engine-results-heading h4 span { color: var(--muted); font-size: 11px; font-weight: 400; }
.engine-empty { border: 1px dashed #cbdcd3; border-radius: 7px; padding: 41px 24px; display: flex; flex-direction: column; gap: 12px; align-items: flex-start; color: var(--muted); }
.engine-empty strong { font-size: 15px; font-weight: 550; color: var(--ink); }
.engine-empty p { font-size: 12px; line-height: 1.85; max-width: 380px; }
.engine-job { border: 1px solid var(--line); background: var(--paper); padding: 17px; margin-bottom: 13px; border-radius: 7px; min-width: 0; }
.engine-job.verified { border-left: 3px solid #5b9886; padding-left: 15px; }
.engine-job-heading { display: flex; align-items: flex-start; justify-content: space-between; gap: 12px; }
.engine-job-heading strong { font-size: 13px; display: block; }
.engine-job-heading small { display: block; color: var(--muted); font-size: 11px; margin-top: 5px; }
.engine-job-state { display: inline-flex; align-items: center; gap: 5px; font-size: 10px; color: #766449; padding-top: 2px; flex-shrink: 0; }
.engine-job-state.completed { color: var(--teal); }
.engine-job-state.failed, .engine-job-state.unknown { color: #a34d35; }
.engine-job-summary { color: var(--muted); font-size: 12px; line-height: 1.85; margin: 13px 0; overflow-wrap: anywhere; }
.engine-proof { display: flex; align-items: center; justify-content: space-between; gap: 7px; padding: 13px 0; margin-bottom: 13px; border-block: 1px solid #e3ece7; color: #859892; }
.engine-proof > div { display: flex; align-items: center; gap: 7px; min-width: 0; }
.engine-proof > div.observed { color: var(--teal); }
.engine-proof span { font-size: 9px; }
.engine-proof code { display: block; font-size: 10px; margin-top: 5px; overflow-wrap: anywhere; }
.engine-job-actions { display: flex; flex-wrap: wrap; align-items: center; gap: 9px 12px; }
.engine-job-actions .button { padding: 7px 9px; font-size: 11px; }
.engine-job-actions .text-button { font-size: 11px; }
.engine-origin { border-top: 1px solid var(--line); padding-top: 10px; margin-top: 15px; font-size: 10px; color: var(--muted); }
.engine-origin summary { cursor: pointer; }
.engine-origin dl { display: grid; grid-template-columns: 87px minmax(0, 1fr); gap: 9px; margin-top: 14px; }
.engine-origin dt, .engine-origin dd { margin: 0; line-height: 1.7; min-width: 0; overflow-wrap: anywhere; }
.engine-retry-note { overflow-wrap: anywhere; margin-bottom: 14px; color: var(--teal); font-size: 12px; }
.engine-record-meta { font-size: 11px; color: var(--muted); border-bottom: 1px solid var(--line); padding-bottom: 13px; margin-bottom: 16px; }
.engine-record-meta code { display: block; overflow-wrap: anywhere; margin-top: 7px; font-size: 10px; }
.engine-original { margin: 0; padding: 17px; background: #f1f5f2; border: 1px solid var(--line); border-radius: 5px; font-size: 11px; line-height: 1.8; max-height: 44vh; overflow: auto; white-space: pre-wrap; overflow-wrap: anywhere; }
.engine-page-controls { display: flex; align-items: center; gap: 9px; flex-wrap: wrap; margin-top: 14px; font-size: 11px; color: var(--muted); }
.engine-page-controls > span { margin-right: auto; }
@media (max-width: 800px) { .engine-layout { grid-template-columns: minmax(0, 1fr); gap: 26px; } }
@media (max-width: 620px) {
.engine-heading { display: block; margin-bottom: 20px; }
.engine-heading h3 { font-size: 21px; }
.engine-install-state { display: inline-block; margin-top: 14px; }
.engine-connection form { padding: 15px; }
.engine-job { padding: 13px; }
.engine-job.verified { padding-left: 11px; }
.engine-job-heading { flex-wrap: wrap; gap: 8px; }
.engine-proof { gap: 4px; }
.engine-proof > div { gap: 4px; }
.engine-proof > div > svg { display: none; }
.engine-proof code { font-size: 9px; }
.engine-original { padding: 12px; max-height: 42vh; }
}
@media (prefers-reduced-motion: reduce) { .engine-panel .spin { animation: none; } }
@@ -0,0 +1,128 @@
import { useEffect, useRef, useState } from 'react';
import { ArrowRight, Check, Download, Fingerprint, Link2, LoaderCircle, Play, RefreshCw, Square, Unplug } from 'lucide-react';
import { api, downloadEngineReport } from './api';
import { Modal } from './components';
import { EngineRunPanel } from './EngineRunPanel';
import type { ArtifactPreview, EngineAvailability, EngineJob, Project, Session } from './types';
import './EnginePanel.css';
const active = ['queued', 'starting', 'initializing', 'checking', 'stopping'];
const states: Record<string, string> = { queued: '等待启动', starting: '原程序启动中', initializing: '正在连接', checking: '正在核验',
stopping: '正在停止', completed: '连接通过', failed: '连接未通过', cancelled: '已停止', unknown: '结果待核对' };
const date = (value: string) => new Date(value).toLocaleString('zh-CN', { month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit' });
type Preview = { job: EngineJob; page: ArtifactPreview };
export function EnginePanel({ project, session, busy, onSession, onError, onNavigate }: {
project: Project; session: Session; busy: boolean; onSession: (value: Session) => void; onError: (error: unknown) => void;
onNavigate?: (projectId: string, sessionId: string) => Promise<void>;
}) {
const [root, setRoot] = useState(''), [installation, setInstallation] = useState<EngineAvailability | null>(null);
const [checking, setChecking] = useState(false), [pending, setPending] = useState(false);
const [retry, setRetry] = useState<EngineJob | null>(null), [preview, setPreview] = useState<Preview | null>(null);
const [viewBusy, setViewBusy] = useState(false), [notice, setNotice] = useState('');
const mounted = useRef(true), detection = useRef(0), scope = useRef(0), viewRequest = useRef(0);
const taskId = session.execution?.task?.id ?? null;
const jobs = (session.execution?.engineJobs ?? []).slice().reverse();
const restricted = !!session.execution?.workers?.length;
const running = jobs.some(job => active.includes(job.status)), disabled = busy || running || pending;
useEffect(() => { mounted.current = true; return () => { mounted.current = false; detection.current++; scope.current++; viewRequest.current++; }; }, []);
useEffect(() => { scope.current++; viewRequest.current++; setPreview(null); setRetry(null); setViewBusy(false); setPending(false); setNotice(''); }, [taskId]);
useEffect(() => { void detect(); }, []);
async function detect(candidate = root) {
const current = ++detection.current; setChecking(true); setNotice('');
try {
const value = await api<EngineAvailability>('/engines/deepseek/availability' + (candidate.trim() ? '?root=' + encodeURIComponent(candidate.trim()) : ''));
if (mounted.current && current === detection.current) { setInstallation(value); if (!candidate.trim() && value.root) setRoot(value.root); }
} catch (error) { if (mounted.current && current === detection.current) onError(error); }
finally { if (mounted.current && current === detection.current) setChecking(false); }
}
function editRoot(value: string) { detection.current++; setRoot(value); setInstallation(null); setChecking(false); setNotice('目录已改变,请先检测这个安装。'); }
async function start(previous?: EngineJob) {
const current = scope.current; setPending(true); setNotice('');
try {
const value = await api<{ job: EngineJob; session: Session }>('/sessions/' + session.id + '/engines/jobs', {
root: previous?.installation.root ?? installation?.root ?? root.trim(),
...(previous ? { retry: true } : { identitySha256: installation?.identitySha256 }),
});
if (mounted.current && current === scope.current) { onSession(value.session); setRetry(null); }
} catch (error) { if (mounted.current && current === scope.current) onError(error); }
finally { if (mounted.current && current === scope.current) setPending(false); }
}
async function stop() {
const current = scope.current; setPending(true);
try { const value = await api<Session>('/sessions/' + session.id + '/engines/stop', {}); if (mounted.current && current === scope.current) onSession(value); }
catch (error) { if (mounted.current && current === scope.current) onError(error); }
finally { if (mounted.current && current === scope.current) setPending(false); }
}
async function openRecord(job: EngineJob, offset = 0) {
const current = ++viewRequest.current, currentScope = scope.current; setViewBusy(true);
try {
const page = await api<ArtifactPreview>('/sessions/' + session.id + '/engines/jobs/' + job.id + '/report?offset=' + offset + '&limit=4000');
if (mounted.current && currentScope === scope.current && current === viewRequest.current) setPreview({ job, page });
} catch (error) { if (mounted.current && currentScope === scope.current && current === viewRequest.current) onError(error); }
finally { if (mounted.current && currentScope === scope.current && current === viewRequest.current) setViewBusy(false); }
}
async function download(job: EngineJob) {
const current = scope.current;
try { await downloadEngineReport(session.id, job.id); }
catch (error) { if (mounted.current && current === scope.current) onError(error); }
}
return <div className="engine-panel">
<EngineRunPanel session={session} onSession={onSession} onError={onError} onNavigate={onNavigate} />
{!restricted && <>
<header className="engine-heading"><div><span className="engine-eyebrow">{project.name} · 当前任务</span><h3>连接本地代理引擎</h3>
<p>本页连接检查不发送模型任务。核对本机的 DeepSeek Harness,并将实际记录保存到这个任务。</p></div>
<span className={'engine-install-state ' + (installation?.status === 'available' ? 'found' : '')} aria-live="polite">
{checking ? '正在检测安装' : installation?.status === 'available' ? '已找到 ' + installation.version : '等待检测'}</span></header>
<div className="engine-layout"><section className="engine-connection">
<form onSubmit={event => { event.preventDefault(); void detect(); }}>
<h4><Link2 size={16} />DeepSeek Harness</h4>
<label className="form-field">本地安装目录<input aria-label="DeepSeek安装目录" value={root} onChange={event => editRoot(event.target.value)}
placeholder="D:\Ai-project\DeepSeek-Harness-Desktop\deepseek-harness" disabled={disabled} /></label>
<button type="submit" className="button secondary" disabled={checking || disabled}><RefreshCw size={14} className={checking ? 'spin' : ''} />检测安装</button>
{installation && <p className={'engine-detection-note ' + installation.status} role="status">{installation.message}</p>}
{notice && <p className="engine-detection-note" role="status">{notice}</p>}
{installation?.status === 'available' && <dl className="engine-install-details"><dt>发行版本</dt><dd>{installation.version}</dd><dt>连接范围</dt><dd>启动、协议、会话目录与停止</dd>
<dt>运行环境</dt><dd>Node.js {installation.node?.version}</dd></dl>}
<button type="button" className="button primary engine-start" onClick={() => void start()} disabled={disabled || checking || installation?.status !== 'available'}>
{pending ? <LoaderCircle size={14} className="spin" /> : <Play size={14} />}核验连接</button>
</form>
<div className="engine-scope"><h4>当前可用能力</h4><p><Check size={14} />原程序连接与独立进程停止</p><p><Check size={14} />同任务保存原记录与来源</p>
<div className="engine-scope-next"><span>受控工程执行</span><p>在「隔离协作」选择 DeepSeek Harness,封存实际安装、范围和预算后开始;提案、检查和父成果沿用工作台审查。</p></div>
<details><summary>连接与执行范围</summary><p>本页连接检查不发送模型任务。工程执行使用单独的所属进程和任务记录;实际模型尝试由工作台连接发送,文件应用与工程检查由工作台审查。</p></details></div>
</section><section className="engine-results"><div className="engine-results-heading"><h4>本任务连接记录 <span>{jobs.length}</span></h4>
{running && <button type="button" className="button secondary" onClick={() => void stop()} disabled={pending}><Square size={13} />停止检查</button>}</div>
{!jobs.length && <div className="engine-empty"><Unplug size={25} /><strong>先验证这个安装能否连接</strong><p>检查完成后,可以查看实际启动、协议返回和进程结束记录;检查不会调用已配置的模型。</p></div>}
{jobs.map(job => { const verified = job.status === 'completed' && job.verification?.verified === true;
return <article key={job.id} data-engine-job={job.id} className={'engine-job ' + (verified ? 'verified' : '')}>
<div className="engine-job-heading"><div><strong>DeepSeek Harness {job.installation.version}</strong><small>{date(job.startedAt)}</small></div>
<span className={'engine-job-state ' + job.status}>{active.includes(job.status) && <LoaderCircle size={12} className="spin" />}{states[job.status] ?? job.status}</span></div>
<p className="engine-job-summary">{job.summary}</p>
<div className="engine-proof" aria-label="引擎实际检查依据">
<div className={job.installation.identitySha256 ? 'observed' : ''}><Fingerprint size={15} /><span>安装身份<code>{job.installation.identitySha256?.slice(0, 12) ?? '等待核对'}</code></span></div>
<ArrowRight size={12} /><div className={job.readiness ? 'observed' : ''}><span>启动完成<code>{job.readiness ? 'PID ' + job.readiness.pid : '尚无信号'}</code></span></div>
<ArrowRight size={12} /><div className={job.serverInfo ? 'observed' : ''}><span>协议返回<code>{job.serverInfo?.version ?? '尚无返回'}</code></span></div>
<ArrowRight size={12} /><div className={job.reportSummary?.rootExited ? 'observed' : ''}><span>进程结束<code>{job.reportSummary?.rootExited ? '已核对' : job.finishedAt ? '待核对' : '检查中'}</code></span></div>
</div>
<div className="engine-job-actions"><button className="button secondary" onClick={() => void openRecord(job)} disabled={!job.reportArtifactId || viewBusy}><Fingerprint size={13} />查看原记录</button>
<button className="text-button" onClick={() => void download(job)} disabled={!job.reportArtifactId}><Download size={13} />下载完整记录</button>
{!active.includes(job.status) && <button className="text-button" onClick={() => setRetry(job)} disabled={disabled}><RefreshCw size={13} />重新核验</button>}</div>
<details className="engine-origin"><summary>任务与安装来源</summary><dl><dt>项目</dt><dd>{project.name}</dd><dt>Task</dt><dd>{job.taskId}</dd><dt>Run</dt><dd>{job.runId}</dd>
<dt>SDK 会话</dt><dd>{job.sdkSessionId}</dd><dt>安装目录</dt><dd>{job.installation.root}</dd><dt>安装 SHA256</dt><dd>{job.installation.identitySha256}</dd>
<dt>原记录 SHA256</dt><dd>{job.reportSha256 ?? '尚未封存'}</dd><dt>模型请求</dt><dd>{job.reportSummary?.modelRequests ?? '尚未核对'}</dd></dl></details>
</article>;
})}
</section></div></>}
{retry && <Modal title="重新核验引擎连接" description="启动一个新的独立检查;原检查记录继续保留。" onClose={() => setRetry(null)}>
<p className="engine-retry-note">{retry.installation.root}</p><p>将重新核对当前安装、启动完成、SDK 返回和进程关闭。本次不会发送模型任务。</p>
<div className="modal-actions"><button className="button secondary" onClick={() => setRetry(null)}>返回记录</button><button className="button primary" disabled={disabled} onClick={() => void start(retry)}><RefreshCw size={14} />开始新的核验</button></div></Modal>}
{preview && <Modal title="引擎原检查记录" description="核对封存的安装、任务身份和原记录 SHA256 后读取。" wide onClose={() => { viewRequest.current++; setPreview(null); setViewBusy(false); }}>
<div className="engine-record-meta"><span>原记录 SHA256</span><code>{preview.page.sha256}</code></div>
<pre className="engine-original" aria-label="引擎原记录内容">{preview.page.content}</pre>
<div className="engine-page-controls"><span>{preview.page.offset.toLocaleString()}–{(preview.page.offset + preview.page.content.length).toLocaleString()} / {preview.page.totalCharacters.toLocaleString()} 字符</span>
<button className="button secondary" onClick={() => void openRecord(preview.job, 0)} disabled={viewBusy || preview.page.offset === 0}>回到首页</button>
<button className="button secondary" onClick={() => void openRecord(preview.job, preview.page.offset + preview.page.content.length)} disabled={viewBusy || !preview.page.truncated}><ArrowRight size={13} />下一页</button></div>
<div className="modal-actions"><button className="button secondary" onClick={() => void download(preview.job)}><Download size={14} />下载完整记录</button></div>
</Modal>}
</div>;
}
@@ -0,0 +1,33 @@
.engine-run-panel { --engine-ink:#153047; --engine-muted:#587087; --engine-line:#c7d3de; --engine-blue:#2560a3; display:grid; gap:16px; color:var(--engine-ink); margin-bottom:24px; }
.engine-run-panel > header { display:flex; justify-content:space-between; gap:14px; align-items:center; }
.engine-run-panel > header > div { min-width:0; }
.engine-run-panel header span { font-size:11px; color:var(--engine-muted); }
.engine-run-panel h3 { margin:5px 0 0; font-size:18px; font-weight:650; }
.engine-run-scope { display:flex; gap:12px; border-left:3px solid var(--engine-blue); background:#edf3fa; padding:15px; }
.engine-run-scope svg { flex-shrink:0; }
.engine-run-scope p { margin:6px 0; font-size:12px; line-height:1.7; overflow-wrap:anywhere; }
.engine-run-panel article { border:1px solid var(--engine-line); border-left:3px solid var(--engine-blue); border-radius:6px; background:white; padding:18px; display:grid; gap:15px; }
.engine-run-panel article.attention { border-left-color:#925619; }
.engine-run-title { display:flex; justify-content:space-between; align-items:flex-start; gap:12px; }
.engine-run-title > div { min-width:0; display:grid; gap:5px; }
.engine-run-title strong { font-size:14px; }
.engine-run-title small { color:var(--engine-muted); font-size:11px; }
.engine-run-state { display:inline-flex; align-items:center; gap:5px; background:#edf3fa; color:var(--engine-blue); font-size:11px; padding:5px 8px; border-radius:3px; white-space:nowrap; }
.engine-run-proof { display:grid; grid-template-columns:repeat(5,minmax(0,1fr)); border-top:1px solid var(--engine-line); border-bottom:1px solid var(--engine-line); }
.engine-run-proof > div { display:flex; align-items:flex-start; gap:6px; padding:12px 9px; min-width:0; border-right:1px solid var(--engine-line); }
.engine-run-proof > div:last-child { border-right:0; }
.engine-run-proof span { display:grid; gap:7px; color:var(--engine-muted); font-size:11px; }
.engine-run-proof strong,.engine-run-proof code { font-size:12px; color:var(--engine-ink); overflow-wrap:anywhere; }
.engine-run-error { margin:0; padding:10px; color:#794d21; background:#fff8ee; border:1px solid #dec6a8; font-size:12px; line-height:1.7; overflow-wrap:anywhere; }
.engine-run-note,.engine-run-empty { font-size:12px; color:var(--engine-muted); line-height:1.7; margin:0; }
.engine-run-actions,.engine-run-record > div { display:flex; flex-wrap:wrap; align-items:center; gap:10px; }
.engine-run-panel .button { min-height:38px; white-space:nowrap; font-size:12px; }
.engine-run-panel details { font-size:12px; color:var(--engine-muted); }
.engine-run-panel summary { cursor:pointer; }
.engine-run-panel dl { display:grid; grid-template-columns:100px minmax(0,1fr); gap:8px; margin:12px 0 0; }
.engine-run-panel dd { margin:0; overflow-wrap:anywhere; }
.engine-run-record { display:grid; gap:14px; min-width:0; }
.engine-run-record > code { overflow-wrap:anywhere; font-size:11px; }
.engine-run-record pre { font:12px/1.7 'Cascadia Code',Consolas,monospace; white-space:pre-wrap; overflow-wrap:anywhere; padding:14px; margin:0; max-height:55vh; overflow:auto; background:#edf3fa; border:1px solid #c7d3de; }
.engine-run-record > div > span { font-size:11px; color:#587087; margin-right:auto; }
@media(max-width:620px) { .engine-run-panel > header { align-items:flex-start; flex-wrap:wrap; } .engine-run-panel article { padding:14px; } .engine-run-proof { grid-template-columns:repeat(2,minmax(0,1fr)); } .engine-run-proof > div { border-bottom:1px solid var(--engine-line); } .engine-run-panel .button { min-height:42px; } .engine-run-panel dl { grid-template-columns:70px minmax(0,1fr); } .engine-run-record > div > span { flex-basis:100%; } .worker-engine-install { grid-template-columns:minmax(0,1fr); } }
@@ -0,0 +1,63 @@
import { useEffect, useRef, useState } from 'react';
import { ArrowRight, ArrowUpRight, Download, FileText, Fingerprint, LoaderCircle, ShieldCheck, Square } from 'lucide-react';
import { api, downloadEngineRunReport } from './api';
import { Modal } from './components';
import type { Session, EngineRunView, ArtifactPreview } from './types';
import './EngineRunPanel.css';
const active = ['queued', 'starting', 'initializing', 'running', 'waiting_tool', 'closing', 'stopping'];
const labels: Record<string, string> = { queued: '待启动', starting: '启动中', initializing: '核对启动', running: '执行中', waiting_tool: '等待宿主工具', closing: '核对停止', stopping: '停止中', completed: '运行已核验', failed: '执行未通过', cancelled: '已停止', unknown: '结果待核对', resolved_external: '已保留原未知结果' };
type Preview = { job: EngineRunView; kind: 'input' | 'report'; page: ArtifactPreview };
export function EngineRunPanel({ session, onSession, onError, onNavigate }: {
session: Session; onSession: (session: Session) => void; onError: (error: unknown) => void;
onNavigate?: (projectId: string, sessionId: string) => Promise<void>;
}) {
const jobs = (session.execution?.engineRuns ?? []).slice().reverse(), worker = session.execution?.workers?.[0];
const [preview, setPreview] = useState<Preview | null>(null), [pending, setPending] = useState(false);
const scope = useRef(0), request = useRef(0);
useEffect(() => { scope.current++; request.current++; setPreview(null); setPending(false); return () => { scope.current++; request.current++; }; }, [session.id]);
async function read(job: EngineRunView, kind: 'input' | 'report', offset = 0) {
const generation = scope.current, current = ++request.current; setPending(true);
try {
const page = await api<ArtifactPreview>('/sessions/' + session.id + '/engine-runs/' + job.id + '/' + kind + '?offset=' + offset + '&limit=4000');
if (generation === scope.current && current === request.current) setPreview({ job, kind, page });
} catch (error) { if (generation === scope.current && current === request.current) onError(error); }
finally { if (generation === scope.current && current === request.current) setPending(false); }
}
async function stop() {
const generation = scope.current; setPending(true);
try { const value = await api<Session>('/sessions/' + session.id + '/stop', {}); if (generation === scope.current) onSession(value); }
catch (error) { if (generation === scope.current) onError(error); }
finally { if (generation === scope.current) setPending(false); }
}
async function download(job: EngineRunView) {
const generation = scope.current;
try { await downloadEngineRunReport(session.id, job.id); } catch (error) { if (generation === scope.current) onError(error); }
}
if (!jobs.length && !worker?.engine) return null;
return <section className="engine-run-panel" aria-label="受控引擎工程运行">
<header><div><span>所属独立工程 / 原执行依据</span><h3>受控引擎运行</h3></div>{jobs.some(job => active.includes(job.status)) && <button className="button secondary" disabled={pending} onClick={() => void stop()}><Square size={14} />停止引擎任务</button>}</header>
{worker && <div className="engine-run-scope"><ShieldCheck size={18} /><div><strong>{worker.label}</strong><p>允许修改:{worker.paths.join('、')}。提案、检查和父工程交付沿用原审查。</p>{onNavigate && <button className="text-button" onClick={() => void onNavigate(worker.parentProjectId, worker.parentSessionId)}>返回父目标<ArrowUpRight size={13} /></button>}</div></div>}
{!jobs.length && <p className="engine-run-empty">安装与范围已经封存。请从父目标开始引擎任务。</p>}
{jobs.map(job => <article key={job.id} data-engine-run={job.id} className={job.requiresVerification ? 'attention' : ''}>
<div className="engine-run-title"><div><strong>DeepSeek Harness {job.installation.version}</strong><small>{new Date(job.startedAt).toLocaleString('zh-CN')}</small></div><span className="engine-run-state">{active.includes(job.status) && <LoaderCircle className="spin" size={13} />}{labels[job.status] ?? job.status}</span></div>
<div className="engine-run-proof" aria-label="原引擎执行依据">
<div><Fingerprint size={15} /><span>固定安装<code>{job.installation.controlledSha256?.slice(0, 12)}</code></span></div>
<div><span>所属进程<code>{job.nativeSummary.pid ? 'PID ' + job.nativeSummary.pid : '尚未封存'}</code></span></div>
<div><span>实际模型请求<strong>{job.modelRequests}</strong></span></div>
<div><span>实际工具请求<strong>{job.toolRequests}</strong></span></div>
<div><span>进程树关闭<strong>{job.nativeSummary.treeConfirmed ? '已核对' : job.finishedAt ? '待核对' : '运行中'}</strong></span></div>
</div>
{job.error && <p className="engine-run-error">{job.error}</p>}
{job.status === 'completed' && <p className="engine-run-note">原引擎运行与调用账本已核验。工程完成仍以提案应用、当前检查和父工程交付为准。</p>}
{job.requiresVerification && <p className="engine-run-note">请返回父目标核对原输入与现场。原未知结果保留,继续会创建新的运行。</p>}
{job.installation.strategy && <div className="engine-prompt-note"><strong>Purge {job.installation.strategy.kind==='purge-original-restricted-v1'?'原版受限模式':'提示实验'} · {job.installation.strategy.source.version}</strong><p>{job.installation.strategy.kind==='purge-original-restricted-v1'?'本 Run 加载固定原版入口,自动重试和继续关闭;工作台审批与预算继续生效。':'本 Run 使用已封存工程提示,原审批与预算继续生效。'}</p><details><summary>查看本次实验策略</summary><dl><dt>策略 SHA256</dt><dd>{job.installation.strategy.sha256}</dd><dt>来源 SHA256</dt><dd>{job.installation.strategy.source.sourceSha256}</dd><dt>文本 SHA256</dt><dd>{job.installation.strategy.promptSha256}</dd><dt>来源目录</dt><dd>{job.installation.strategy.source.root}</dd>{job.installation.strategy.kind==='purge-original-restricted-v1'&&<><dt>固定运行依赖 SHA256</dt><dd>{job.installation.strategy.runtime.sha256}</dd><dt>加载范围</dt><dd>{job.installation.strategy.runtime.inputs.length} 份固定输入 / {job.installation.strategy.runtime.nativeAddons.length} 个固定原生模块</dd></>}</dl><pre>{job.installation.strategy.prompt}</pre></details></div>}
{job.review && <p className="engine-run-note">人工核对记录:<code>{job.review.evidenceSha256.slice(0, 16)}</code>。原未知输出未改写为完成。</p>}
<div className="engine-run-actions"><button className="button secondary" disabled={pending} onClick={() => void read(job, 'input')}><FileText size={14} />查看原输入</button><button className="button secondary" disabled={pending || !job.reportArtifactId} onClick={() => void read(job, 'report')}><Fingerprint size={14} />查看原报告</button><button className="text-button" disabled={!job.reportArtifactId} onClick={() => void download(job)}><Download size={14} />下载完整报告</button></div>
<details><summary>任务身份与来源</summary><dl><dt>Task</dt><dd>{job.taskId}</dd><dt>Run</dt><dd>{job.runId}</dd><dt>SDK 会话</dt><dd>{job.sdkSessionId}</dd><dt>安装目录</dt><dd>{job.installation.root}</dd><dt>输入 SHA256</dt><dd>{job.inputSha256}</dd><dt>报告 SHA256</dt><dd>{job.reportSha256 ?? '尚未封存'}</dd><dt>原事件</dt><dd>{job.nativeSummary.notifications} 项</dd></dl></details>
</article>)}
{preview && <Modal title={preview.kind === 'input' ? '引擎原执行输入' : '引擎原运行报告'} description="原字节按 SHA256 核对后分页读取。" wide onClose={() => { request.current++; setPreview(null); setPending(false); }}>
<div className="engine-run-record"><code>{preview.page.sha256}</code><pre aria-label="引擎运行原记录">{preview.page.content}</pre><div><span>{preview.page.offset.toLocaleString()}–{(preview.page.offset + preview.page.content.length).toLocaleString()} / {preview.page.totalCharacters.toLocaleString()} 字符</span><button className="button secondary" disabled={pending || preview.page.offset === 0} onClick={() => void read(preview.job, preview.kind, 0)}>回到首页</button><button className="button secondary" disabled={pending || !preview.page.truncated} onClick={() => void read(preview.job, preview.kind, preview.page.offset + preview.page.content.length)}>下一页<ArrowRight size={14} /></button></div></div>
</Modal>}
</section>;
}
@@ -0,0 +1,26 @@
.environment-panel { min-width:0; }
.environment-error { padding:10px;border-left:3px solid #b63d3d;background:#fff0ef;color:#8b2828;overflow-wrap:anywhere;font-size:12px;line-height:1.7; }
.environment-panel h4 { margin:0 0 10px;font-size:13px;color:var(--text-primary,#20344c); }
.environment-diagnostic,.environment-plan,.environment-job,.environment-prepare { margin-top:14px;padding-top:14px;border-top:1px solid var(--border,#dce4ec);min-width:0; }
.environment-result-heading { display:flex;align-items:center;flex-wrap:wrap;gap:8px;font-size:12px; }
.environment-result-heading>code { margin-left:auto;color:var(--text-muted,#687c91);font-size:11px; }
.environment-state { display:inline-flex;padding:3px 7px;background:#edf2f7;color:#40576d;border-radius:4px;font-size:11px; }
.environment-state.ready { color:#176143;background:#e8f5ee; }
.environment-state.needs_preparation { color:#855716;background:#fff4df; }
.environment-fields { display:grid;grid-template-columns:96px minmax(0,1fr);gap:8px 12px;margin:12px 0;font-size:12px;line-height:1.6; }
.environment-fields dt { color:var(--text-muted,#687c91); }
.environment-fields dd { margin:0;min-width:0;overflow-wrap:anywhere; }
.environment-fields dd code { display:block;font-size:11px;overflow-wrap:anywhere; }
.environment-path { display:block;overflow-wrap:anywhere;font-size:11px;line-height:1.7; }
.environment-panel p { font-size:12px;line-height:1.65;overflow-wrap:anywhere; }
.environment-panel pre,.environment-confirm pre { max-height:260px;overflow:auto;padding:10px;background:var(--surface-subtle,#f3f6fa);border:1px solid var(--border,#dce4ec);border-radius:5px;font:11px/1.7 Consolas,monospace;white-space:pre-wrap;overflow-wrap:anywhere; }
.environment-panel details,.environment-confirm details { margin:10px 0;font-size:12px; }
.environment-panel summary { cursor:pointer;line-height:1.8;color:var(--text-secondary,#40576d); }
.environment-prepare label { display:block;font-size:12px;line-height:1.65;margin:10px 0; }
.environment-prepare label>input:not([type=checkbox]) { display:block;width:100%;margin-top:5px;padding:8px;border:1px solid var(--border,#dce4ec);border-radius:5px;background:var(--surface,#fff);font:12px/1.5 inherit;color:inherit; }
.environment-prepare .environment-choice { display:flex;gap:8px;align-items:flex-start; }
.environment-choice input { flex-shrink:0;margin-top:4px; }
.environment-issues { padding-left:18px;color:#8a561b;font-size:12px;line-height:1.8;overflow-wrap:anywhere; }
.environment-actions { display:flex;gap:12px;flex-wrap:wrap; }
.environment-confirm { min-width:0;max-height:65vh;overflow:auto; }
@media(max-width:600px) { .environment-fields { grid-template-columns:minmax(0,1fr);gap:3px; }.environment-fields dd { margin-bottom:8px; }.environment-panel .button { max-width:100%;white-space:normal;min-height:40px; }.environment-actions .text-button { min-height:40px; } }
@@ -0,0 +1,83 @@
import { useEffect, useRef, useState } from 'react';
import { Check, FileText, LoaderCircle, PackageCheck, RefreshCw, Square } from 'lucide-react';
import { api, downloadArtifact } from './api';
import { Modal } from './components';
import type { EnvironmentPlan, Project, Session } from './types';
import './EnvironmentPanel.css';
const labels: Record<string,string> = {ready:'依赖已就绪',needs_preparation:'需要准备依赖',unsupported:'暂不支持自动准备',planned:'计划待确认',consumed:'计划已使用',queued:'排队中',running:'正在准备',stopping:'正在停止',prepared:'依赖准备完成',failed:'准备失败',cancelled:'已停止',unknown:'结果待核对',stale:'输入已变化',unverified:'未能完整核验',missing:'未找到',available:'已识别',deferred:'等待检查审批'};
const activeStates=['queued','running','stopping'];
export function EnvironmentPanel({project,session,busy,onSession,onError,openArtifact}:{project:Project;session:Session;busy:boolean;onSession:(value:Session)=>void;onError:(error:unknown)=>void;openArtifact:(id:string)=>void}) {
const [working,setWorking]=useState(''),[registry,setRegistry]=useState('https://registry.npmjs.org/'),[allowScripts,setAllowScripts]=useState(false),[offline,setOffline]=useState(false);
const [failure,setFailure]=useState('');
const [confirm,setConfirm]=useState<EnvironmentPlan|null>(null),[reconcile,setReconcile]=useState<string|null>(null),scope=useRef(0);
const execution=session.execution,diagnostic=execution?.environmentDiagnostics?.at(-1),node=diagnostic?.node,python=diagnostic?.python;
const plans=execution?.environmentPlans??[],plan=plans.at(-1),jobs=execution?.environmentJobs??[],active=jobs.some(job=>activeStates.includes(job.status));
const unresolved=jobs.some(job=>job.requiresVerification&&!job.reconciliation);
useEffect(()=>{scope.current++;setWorking('');setFailure('');setConfirm(null);setReconcile(null);setRegistry('https://registry.npmjs.org/');setAllowScripts(false);setOffline(false);return()=>{scope.current++;};},[session.id,execution?.task?.id]);
async function perform(action:string,input:unknown={},after?:()=>void) {
const current=scope.current;setWorking(action);setFailure('');
try{const value=await api<Session>('/sessions/'+session.id+'/'+action,input);if(current===scope.current){onSession(value);after?.();}}
catch(error){if(current===scope.current){setFailure(error instanceof Error?error.message:String(error));onError(error);}}
finally{if(current===scope.current)setWorking('');}
}
const disabled=busy||active||!!working;
return <section className="task-record-section environment-panel" aria-label="工程环境与依赖">
<div className="record-heading"><PackageCheck size={15}/><h3>工程环境与依赖</h3></div>
<p className="record-footnote">先核对环境,再准备依赖、执行工程检查。诊断只读取声明与实际文件。</p>
{failure&&!confirm&&!reconcile&&<p className="environment-error" role="alert">{failure}</p>}
<button type="button" className="button secondary" disabled={disabled||!execution?.task} onClick={()=>perform('environment-diagnostics')}>
{working==='environment-diagnostics'?<LoaderCircle size={14} className="spin"/>:<RefreshCw size={14}/>}{diagnostic?'重新诊断工程环境':'诊断工程环境'}</button>
{diagnostic&&<div className="environment-diagnostic" role="status">
{node&&<><div className="environment-result-heading"><strong>Node / npm</strong><span className={'environment-state '+node.status}>{labels[node.status]??node.status}</span></div>
<dl className="environment-fields"><dt>实际运行时</dt><dd>Node {node.runtime.node.version} · npm {node.runtime.npm?.version??'未找到'}<code title={node.runtime.node.path}>{node.runtime.node.path}</code></dd>
<dt>声明与锁文件</dt><dd>{node.declarations.map(file=><code key={file.path} title={file.sha256}>{file.path.split(/[\\/]/).at(-1)} · {file.sha256.slice(0,12)}</code>)}{node.lockVersion&&<span>package-lock v{node.lockVersion} · {node.packageCount} 个锁定包</span>}</dd>
<dt>实际依赖文件</dt><dd>{node.installed.status==='verified'?`${node.installed.files} 项 · ${(node.installed.bytes/1024/1024).toFixed(1)} MB` : node.installed.status==='missing'?'没有 node_modules':node.installed.message}
{node.installed.sha256&&<code title={node.installed.sha256}>SHA-256 {node.installed.sha256.slice(0,16)}</code>}</dd>
{!!node.missing.length&&<><dt>缺少依赖</dt><dd>{node.missing.join('、')}</dd></>}{!!node.mismatched.length&&<><dt>版本需核对</dt><dd>{node.mismatched.join('、')}</dd></>}
{!!node.sources.length&&<><dt>锁定下载来源</dt><dd>{node.sources.map(source=><code key={source}>{source}</code>)}</dd></>}
</dl>{!!node.issues.length&&<ul className="environment-issues">{node.issues.map(issue=><li key={issue}>{issue}</li>)}</ul>}
</>}
{python&&<><div className="environment-result-heading"><strong>Python / {python.framework??'检查器'}</strong><span className="environment-state">{labels[python.status]??python.status}</span></div>
<p>{python.runtime.version??'版本等待审批后核对'} · pytest {python.pytest.version??'未找到元数据'}</p><code className="environment-path">{python.runtime.logicalExecutable??'没有可用解释器'}</code><p className="record-footnote">{python.message}</p></>}
{!node&&!python&&<p>尚未识别可支持的 Node 或 Python 工程声明。</p>}
<button type="button" className="text-button" onClick={()=>openArtifact(diagnostic.artifactId)}><FileText size={13}/>查看原诊断</button>
</div>}
{node&&<div className="environment-prepare">
<h4>准备所属工作区</h4>
{!project.workspace&&<p className="record-footnote">先在上方创建并打开独立开发工作区;依赖准备在该工作区执行。</p>}
<details><summary>下载与脚本选项</summary><label>注册源<input aria-label="依赖注册源" value={registry} disabled={disabled} onChange={event=>setRegistry(event.target.value)}/></label>
<label className="environment-choice"><input type="checkbox" checked={offline} disabled={disabled} onChange={event=>setOffline(event.target.checked)}/>只使用本工作区的下载缓存(离线)</label>
<label className="environment-choice"><input type="checkbox" checked={allowScripts} disabled={disabled} onChange={event=>setAllowScripts(event.target.checked)}/>允许依赖生命周期脚本</label>
<p className="record-footnote">默认跳过脚本。部分原生依赖需要脚本才能使用;允许后,根工程和下载包的安装脚本会以本机账户执行。具体执行范围会在确认页显示。</p>
</details>
<button type="button" className="button secondary" disabled={disabled||unresolved||!project.workspace||!node.preparable} onClick={()=>perform('environment-plans',{registry,scripts:allowScripts?'allow':'skip',offline})}>{working==='environment-plans'?<LoaderCircle size={14} className="spin"/>:<PackageCheck size={14}/>}创建依赖准备计划</button>
</div>}
{plan&&<div className="environment-plan"><div className="environment-result-heading"><strong>npm ci</strong><span className="environment-state">{labels[plan.status]??plan.status}</span></div>
<p>{plan.packageCount} 个锁定包 · {plan.offline?'离线缓存':'下载自 '+plan.registry} · {plan.scripts==='skip'?'跳过安装脚本':'允许安装脚本'}</p><code className="environment-path">{plan.root}</code>
<details><summary>查看固定命令与计划身份</summary><pre>{plan.invocation.executable+'\n'+plan.invocation.args.map(arg=>JSON.stringify(arg)).join('\n')}</pre><code className="environment-path">SHA-256 {plan.fingerprint}</code></details>
{plan.status==='planned'&&<button type="button" className="button primary" disabled={disabled||unresolved} onClick={()=>setConfirm(plan)}>核对并批准依赖准备</button>}
</div>}
{jobs.slice().reverse().map(job=><div className="environment-job" key={job.id}>
<div className="environment-result-heading"><strong>{labels[job.status]??job.status}</strong><code title={job.id}>{job.id.slice(0,8)}</code>
{activeStates.includes(job.status)&&<button type="button" className="text-button" disabled={!!working} onClick={()=>perform('environment-jobs/'+job.id+'/stop')}><Square size={12}/>停止依赖准备</button>}</div>
<p>{job.summary??'按封存计划准备依赖,原进程与日志正在记录。'}</p>{job.result&&<p className="record-footnote">退出码 {job.result.exitCode??'未返回'} · {(job.result.durationMs/1000).toFixed(1)} 秒{job.result.truncated?' · 日志超出上限,保留首尾':''}</p>}
{job.logExcerpt&&<details open={activeStates.includes(job.status)}><summary>原执行日志预览</summary><pre>{job.logExcerpt}</pre></details>}
{job.logArtifactId&&<div className="environment-actions"><button type="button" className="text-button" onClick={()=>openArtifact(job.logArtifactId!)}><FileText size={13}/>查看依赖日志</button><button type="button" className="text-button" onClick={()=>{void downloadArtifact(session.id,job.logArtifactId!,'dependency-'+job.id+'.log').catch(onError);}}>下载原日志</button></div>}
{job.after&&<details><summary>准备后的环境身份</summary><code className="environment-path">SHA-256 {job.after.identity}</code><p className="record-footnote">依赖准备完成后,还需要实际测试与构建。</p></details>}
{job.requiresVerification&&!job.reconciliation&&<button type="button" className="button secondary" disabled={disabled} onClick={()=>setReconcile(job.id)}>核对中断现场</button>}
{job.reconciliation&&<p className="record-footnote">已核对原进程结束并保留现场,原未知结果保持。再次执行需要新计划。</p>}
</div>)}
{confirm&&<Modal title="确认依赖准备" description="核对目标、实际命令、下载来源和脚本范围后执行。" onClose={()=>{if(!working)setConfirm(null);}}>
<div className="environment-confirm"><dl className="environment-fields"><dt>独立工作区</dt><dd><code>{confirm.root}</code></dd><dt>注册源</dt><dd>{confirm.registry}{confirm.offline?'(只使用缓存)':''}</dd>
<dt>执行时限</dt><dd>{Math.round(confirm.timeoutMs/1000)} 秒,可随时停止</dd><dt>生命周期脚本</dt><dd><strong>{confirm.scripts==='skip'?'全部跳过(--ignore-scripts=true)':'允许执行根工程和依赖包安装脚本'}</strong></dd></dl>
<pre>{confirm.invocation.executable+'\n'+confirm.invocation.args.map(arg=>JSON.stringify(arg)).join('\n')}</pre>
{!!confirm.lifecycle.length&&<details open><summary>根工程的安装脚本</summary>{confirm.lifecycle.map(script=><div key={script.name}><strong>{script.name}</strong><pre>{script.script}</pre></div>)}</details>}
{!!confirm.installScriptPackages.length&&<p>锁文件标记了 {confirm.installScriptPackages.length} 个带安装脚本的包:{confirm.installScriptPackages.join('、')}。脚本正文需下载后才能读取。</p>}
<p className="record-footnote">会更新该工作区的 node_modules。失败或停止后保留现场与日志;原计划只执行一次。安装完成后继续核对工程检查结果。</p>
{failure&&<p className="environment-error" role="alert">{failure}</p>}
</div><div className="modal-actions"><button type="button" className="button secondary" disabled={!!working} onClick={()=>setConfirm(null)}>取消</button><button type="button" className="button primary" disabled={disabled} onClick={()=>perform('environment-jobs',{planId:confirm.id,fingerprint:confirm.fingerprint,approved:true},()=>setConfirm(null))}><Check size={14}/>确认执行依赖准备</button></div>
</Modal>}
{reconcile&&<Modal title="核对中断的依赖准备" onClose={()=>setReconcile(null)}><p>将只读核对原所属进程和当前工程环境。原进程仍存在时保留阻塞状态;确认结束后保留原未知结果,并允许重新创建计划。</p><div className="modal-actions"><button type="button" className="button secondary" onClick={()=>setReconcile(null)}>取消</button><button type="button" className="button primary" disabled={!!working} onClick={()=>perform('environment-jobs/'+reconcile+'/reconcile',{fingerprint:jobs.find(job=>job.id===reconcile)?.planFingerprint},()=>setReconcile(null))}>确认只读核对</button></div></Modal>}
</section>;
}
@@ -0,0 +1,69 @@
.evaluation-console { --ev-ink:#25344a; --ev-muted:#596a7d; --ev-line:#ccd5df; --ev-wash:#f4f7fa; color:var(--ev-ink);display:grid;gap:22px;min-width:0;overflow-wrap:anywhere; }
.evaluation-console h2,.evaluation-console h3,.evaluation-console h4,.evaluation-report h3,.evaluation-report h4 { margin:0; }
.evaluation-heading,.evaluation-report-heading { display:flex;align-items:flex-start;justify-content:space-between;gap:18px; }
.evaluation-heading h2 {font-size:21px;letter-spacing:-.025em;line-height:1.4;}
.evaluation-heading p:not(.evaluation-kicker) {font-size:13px;color:var(--ev-muted);line-height:1.7;margin:7px 0 0;}
.evaluation-kicker {font-size:12px;font-weight:650;color:#385e89;margin:0 0 6px;}
.evaluation-heading >button {flex-shrink:0;}
.evaluation-history {display:grid;grid-template-columns:auto minmax(0,1fr);align-items:center;gap:14px;font-size:13px;}
.evaluation-console input,.evaluation-console textarea,.evaluation-console select {width:100%;min-width:0;border:1px solid #bbc7d5;border-radius:5px;background:#fff;padding:9px 11px;font:inherit;font-size:13px;color:var(--ev-ink);}
.evaluation-console textarea {resize:vertical;line-height:1.65;}
.evaluation-console :focus-visible {outline:2px solid #346daa;outline-offset:3px;}
.evaluation-console button,.evaluation-report button {min-height:36px;}
.evaluation-form {display:grid;gap:18px;}
.evaluation-form label {display:grid;gap:7px;font-size:13px;font-weight:600;}
.evaluation-form fieldset {min-width:0;display:grid;gap:14px;border:1px solid var(--ev-line);border-left:3px solid #456d99;padding:18px 20px;border-radius:5px;}
.evaluation-form legend {font-size:12px;font-weight:650;padding:0 7px;}
.evaluation-budget {display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:14px;}
.evaluation-note {font-size:12px;color:var(--ev-muted,#596a7d);line-height:1.75;margin:0;}
.evaluation-error {background:#fff5e9;border:1px solid #d9b992;border-left:3px solid #986024;color:#76501f;padding:12px 15px;font-size:13px;line-height:1.7;}
.evaluation-actions {display:flex;flex-wrap:wrap;align-items:center;gap:10px;}
.evaluation-source {border-bottom:1px solid var(--ev-line);padding:0 0 20px;}
.evaluation-source>div {display:flex;justify-content:space-between;gap:12px;align-items:center;}
.evaluation-source>p {font-size:13px;line-height:1.7;}
.evaluation-status {font-size:12px;background:#e9eff6;color:#345579;padding:5px 9px;border-radius:4px;flex-shrink:0;}
.evaluation-console dl,.evaluation-report dl {display:grid;gap:9px;margin:14px 0;font-size:12px;}
.evaluation-console dl>div,.evaluation-report dl>div {display:grid;grid-template-columns:100px minmax(0,1fr);gap:8px;}
.evaluation-console dt,.evaluation-report dt {color:#596a7d;}
.evaluation-console dd,.evaluation-report dd {margin:0;display:flex;align-items:center;gap:6px;flex-wrap:wrap;}
.evaluation-workspace {display:grid;grid-template-columns:190px minmax(0,1fr);gap:24px;align-items:start;}
.evaluation-workspace>nav {display:grid;border:1px solid var(--ev-line);border-radius:5px;overflow:hidden;}
.evaluation-workspace>nav>button {text-align:left;display:grid;gap:7px;background:#fff;border:0;border-bottom:1px solid var(--ev-line);padding:15px 13px;font:inherit;color:var(--ev-ink);cursor:pointer;}
.evaluation-workspace>nav>button:last-child {border-bottom:0;}
.evaluation-workspace>nav>button[aria-pressed=true] {background:#eaf0f7;box-shadow:inset 3px 0 #396b9e;}
.evaluation-workspace>nav small {font-size:11px;color:var(--ev-muted);}
.evaluation-workspace>nav strong {font-size:13px;line-height:1.5;}
.evaluation-workspace>nav span {font-size:11px;color:var(--ev-muted);line-height:1.6;}
.evaluation-sample {min-width:0;display:grid;gap:17px;}
.evaluation-sample>h3 {font-size:18px;line-height:1.5;}
.evaluation-goal {font-size:14px;line-height:1.8;white-space:pre-wrap;margin:0;}
.evaluation-criteria {border-left:2px solid #7f94ae;padding-left:12px;font-size:13px;line-height:1.7;}
.evaluation-criteria p {margin:5px 0 0;white-space:pre-wrap;}
.evaluation-paths {display:flex;gap:7px;flex-wrap:wrap;font-size:12px;}
.evaluation-paths code {background:var(--ev-wash);padding:4px 6px;}
.evaluation-commands {border-top:1px solid var(--ev-line);border-bottom:1px solid var(--ev-line);padding:13px 0;font-size:12px;}
.evaluation-commands summary {cursor:pointer;font-weight:650;line-height:1.7;}
.evaluation-commands>div {margin-top:13px;}
.evaluation-console pre,.evaluation-report pre {white-space:pre-wrap;overflow-wrap:anywhere;font-size:12px;line-height:1.7;background:#f1f4f8;color:#304056;padding:12px;border-radius:4px;max-height:360px;overflow:auto;}
.evaluation-lanes {display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:0;border:1px solid #ccd5df;border-radius:5px;overflow:hidden;}
.evaluation-lanes>section {min-width:0;padding:16px;background:#fff;}
.evaluation-lanes>section+section {border-left:1px solid #ccd5df;background:#f5f8fc;}
.evaluation-lanes>section>p {font-size:12px;line-height:1.75;color:#596a7d;}
.evaluation-lane-title {display:flex;flex-wrap:wrap;gap:8px;align-items:center;justify-content:space-between;}
.evaluation-lane-title h4 {font-size:14px;}
.evaluation-lane-title>span {font-size:11px;color:#596a7d;}
.evaluation-delivery {padding:18px;border:1px solid var(--ev-line);border-left:3px solid #3d6e96;background:#f5f8fc;font-size:13px;line-height:1.8;}
.evaluation-delivery h3 {font-size:14px;}
.evaluation-confirm {display:grid;gap:18px;font-size:14px;line-height:1.8;padding:22px;}
.evaluation-report {display:grid;gap:22px;min-width:0;padding:24px;color:#25344a;overflow-wrap:anywhere;}
.evaluation-report-heading h3 {font-size:18px;}
.evaluation-report-heading p {font-size:13px;line-height:1.7;}
.evaluation-outcome {font-size:12px;color:#73551c;}
.evaluation-outcome.passed {color:#216245;}
.evaluation-outcome.failed {color:#a33e39;}
.evaluation-attempt {border-top:1px solid #ccd5df;padding:13px 0 0;margin-top:13px;font-size:12px;line-height:1.7;}
.evaluation-attempt>div {display:grid;gap:4px;margin-top:10px;}
.evaluation-attempt code {font-size:11px;color:#596a7d;}
.evaluation-report summary {font-size:12px;cursor:pointer;}
@media(max-width:760px) { .evaluation-workspace {grid-template-columns:minmax(0,1fr);gap:18px;}.evaluation-workspace>nav {grid-template-columns:repeat(3,minmax(0,1fr));}.evaluation-workspace>nav>button {padding:12px 10px;border-bottom:0;border-right:1px solid var(--ev-line);}.evaluation-budget{grid-template-columns:repeat(2,minmax(0,1fr));} }
@media(max-width:520px) { .evaluation-heading h2{font-size:18px;}.evaluation-heading{gap:10px;}.evaluation-history{grid-template-columns:minmax(0,1fr);gap:8px;}.evaluation-workspace>nav{grid-template-columns:minmax(0,1fr);}.evaluation-workspace>nav>button{border-right:0;border-bottom:1px solid var(--ev-line);}.evaluation-source>div{align-items:flex-start;flex-direction:column;}.evaluation-lanes{grid-template-columns:minmax(0,1fr);}.evaluation-lanes>section+section{border-left:0;border-top:1px solid #ccd5df;}.evaluation-report{padding:16px;}.evaluation-report-heading{flex-direction:column;}.evaluation-console button,.evaluation-report button{min-height:42px;}.evaluation-form fieldset{padding:15px;}.evaluation-console dl>div,.evaluation-report dl>div{grid-template-columns:88px minmax(0,1fr);} }
@@ -0,0 +1,98 @@
import { useCallback, useEffect, useRef, useState } from 'react';
import { ArrowUpRight, ClipboardCheck, Download, GitBranch, LoaderCircle, Plus, RefreshCw, Square } from 'lucide-react';
import { api, downloadBlob } from './api';
import { Modal } from './components';
import type { Config, Session, EvaluationBatch, EvaluationSample, EvaluationReport, EvaluationRole } from './types';
import './EvaluationPanel.css';
const live = ['preparing','baseline_running','candidate_running','collecting','adopting'];
const labels: Record<string,string> = {pending:'未执行',planned:'计划已封存',ready:'同源工作区就绪',preparing:'准备同源工程',baseline_running:'原版检查中',baseline_complete:'原版结果已保存',candidate_running:'候选执行中',awaiting_review:'等待改动审查',awaiting_approval:'等待检查审批',candidate_complete:'候选完成',paused:'候选已暂停',failed:'失败',stopped:'已停止',unknown:'结果待核对',sealed:'报告已封存',between_samples:'等待下一样本',completed:'本批已封存',retained:'已保留现场结束',collecting:'核对原证据',adopting:'准备采纳',awaiting_delivery:'等待父工程交付',passed:'通过'};
const label = (status:string) => labels[status] ?? status;
const split = (value:string) => value.split(/[\n,,]/).map(value=>value.trim()).filter(Boolean);
const draft = () => ({label:'',goal:'',criteria:'',paths:'',checks:'test, build'});
const number = (value:number) => value.toLocaleString('zh-CN');
const elapsed = (role:EvaluationRole) => role.startedAt && role.finishedAt ? Math.max(0,Math.round((Date.parse(role.finishedAt)-Date.parse(role.startedAt))/1000))+' 秒' : '未记录完整起止';
export function EvaluationPanel({session,config,busy,onSession,onNavigate,onReview,onRecovery}: {
session:Session;config:Config;busy:boolean;onSession:(session:Session)=>void;
onNavigate:(projectId:string,sessionId:string,view?:'task'|'changes'|'approval')=>Promise<void>;onReview:()=>void;onRecovery:()=>void;
}) {
const [batches,setBatches]=useState<EvaluationBatch[]>([]),[selected,setSelected]=useState(''),[sampleId,setSampleId]=useState('');
const [loading,setLoading]=useState(true),[action,setAction]=useState(''),[error,setError]=useState(''),[creating,setCreating]=useState(false);
const [title,setTitle]=useState(''),[samples,setSamples]=useState([draft()]);
const [evidenceMode,setEvidenceMode]=useState('configured-model');
const [tokens,setTokens]=useState(config.maxRunTokens),[steps,setSteps]=useState(Math.min(200,config.maxSteps*2)),[tools,setTools]=useState(96),[minutes,setMinutes]=useState(Math.floor(config.maxRunDurationMs/60000));
const [confirmation,setConfirmation]=useState<{batchId:string;sampleId:string;operation:string}|null>(null),[report,setReport]=useState<EvaluationReport|null>(null);
const scope=useRef(0),fetching=useRef(false),currentBatch=useRef(''),currentSample=useRef('');
const load=useCallback(async()=>{
if(fetching.current)return;fetching.current=true;const generation=scope.current;
try{const view=await api<{batches:EvaluationBatch[]}>('/sessions/'+session.id+'/evaluations');if(generation===scope.current)setBatches(view.batches);}
catch(error){if(generation===scope.current)setError(error instanceof Error?error.message:String(error));}
finally{if(generation===scope.current){fetching.current=false;setLoading(false);}}
},[session.id]);
useEffect(()=>{scope.current++;fetching.current=false;setBatches([]);setSelected('');setSampleId('');setReport(null);void load();return()=>{scope.current++;};},[load]);
useEffect(()=>{void load();},[session.revision,load]);
const batch=batches.find(batch=>batch.id===selected)??batches.at(-1),sample=batch?.samples.find(sample=>sample.id===sampleId)??batch?.samples.find(sample=>!sample.report)??batch?.samples.at(-1);
currentBatch.current=batch?.id??'';
currentSample.current=sample?.id??'';
const running=!!batch&&live.includes(batch.status);
useEffect(()=>{if(!running)return;const timer=setInterval(()=>void load(),1200);return()=>clearInterval(timer);},[running,load]);
useEffect(()=>{setConfirmation(null);setReport(null);setError('');},[session.id,batch?.id,sample?.id]);
async function execute(operation:string,target=batch,item=sample){
if(!target||currentBatch.current!==target.id)return;const generation=scope.current;setAction(operation);setError('');setConfirmation(null);
try{const reply=await api<{session:Session}>('/sessions/'+session.id+'/evaluations/'+target.id+'/'+operation,{fingerprint:target.fingerprint,...(item?{sampleId:item.id}:{})});if(generation===scope.current){onSession(reply.session);await load();}}
catch(error){if(generation===scope.current)setError(error instanceof Error?error.message:String(error));}
finally{if(generation===scope.current)setAction('');}
}
async function create(){const generation=scope.current;setAction('create');setError('');
try{const reply=await api<{batch:EvaluationBatch;session:Session}>('/sessions/'+session.id+'/evaluations',{title,samples:samples.map(sample=>({...sample,paths:split(sample.paths),checks:split(sample.checks)})),budget:{maxTokens:tokens,maxSteps:steps,maxToolCalls:tools,maxDurationMs:minutes*60000},evidenceMode});if(generation===scope.current){onSession(reply.session);setSelected(reply.batch.id);setCreating(false);await load();}}
catch(error){if(generation===scope.current)setError(error instanceof Error?error.message:String(error));}
finally{if(generation===scope.current)setAction('');}
}
async function showReport(){if(!batch||!sample)return;const generation=scope.current,target=batch.id,id=sample.id;setAction('report');setError('');
try{const result=await api<EvaluationReport>('/sessions/'+session.id+'/evaluations/'+batch.id+'/report?sampleId='+sample.id);if(generation===scope.current&&currentBatch.current===target&&currentSample.current===id)setReport(result);}
catch(error){if(generation===scope.current)setError(error instanceof Error?error.message:String(error));}finally{if(generation===scope.current)setAction('');}
}
const confirm=(operation:string)=>{if(batch&&sample)setConfirmation({batchId:batch.id,sampleId:sample.id,operation});};
const canCreate=!busy&&!action&&(!batch||['completed','retained'].includes(batch.status));
return <div className="evaluation-console" aria-label="工程评测控制台">
<header className="evaluation-heading"><div><p className="evaluation-kicker">工程质量 · 固定样本</p><h2>同一份需求,核对改进前后</h2><p>封存来源与原测试,在隔离工程里生成候选,再把真实结果带回审查。</p></div><button className="button secondary" disabled={loading||!!action} onClick={()=>void load()}><RefreshCw size={14}/>刷新</button></header>
{error&&<div className="evaluation-error" role="alert">{error}</div>}
{loading?<p role="status"><LoaderCircle size={15} className="spin"/>正在读取评测…</p>:<>
{!!batches.length&&<label className="evaluation-history">评测记录<select aria-label="选择评测记录" value={batch?.id??''} onChange={event=>{setSelected(event.target.value);setSampleId('');setCreating(false);}}>{batches.map(batch=><option key={batch.id} value={batch.id}>{batch.title} · {label(batch.status)}</option>)}</select></label>}
{(!batch||creating)?<section className="evaluation-form" aria-label="新建工程评测">
<label>评测名称<input value={title} maxLength={120} onChange={event=>setTitle(event.target.value)} placeholder="例如 修复导入边界并保持原测试"/></label>
<label>评测来源<select aria-label="评测来源" value={evidenceMode} onChange={event=>setEvidenceMode(event.target.value)}><option value="configured-model">实际配置模型 · 保留真实结果</option><option value="local-fixture">本地固定响应 · 只验证执行链</option></select></label>
<p className="evaluation-note">每批 1–3 个样本,按队列显式推进。每个样本都从当前已提交 HEAD 检出;原暂存和未提交内容留在来源工程。</p>
{samples.map((sample,index)=><fieldset key={index}><legend>固定样本 {index+1}</legend>{(['label','goal','criteria','paths','checks'] as const).map(key=><label key={key}>{({label:'样本名称',goal:'具体需求',criteria:'验收条件',paths:'允许修改的源码文件',checks:'完整检查名称'})[key]}{key==='label'?<input value={sample[key]} maxLength={64} onChange={event=>setSamples(values=>values.map((value,i)=>i===index?{...value,[key]:event.target.value}:value))}/>:<textarea aria-label={({label:'样本名称',goal:'具体需求',criteria:'验收条件',paths:'允许修改的源码文件',checks:'完整检查名称'})[key]} rows={key==='goal'||key==='criteria'?3:2} maxLength={key==='goal'?6000:4000} value={sample[key]} placeholder={key==='paths'?'例如 src/parser.mjs,每行一个已有文件':key==='checks'?'test, typecheck, build;Python 使用 python:test, python:compile':undefined} onChange={event=>setSamples(values=>values.map((value,i)=>i===index?{...value,[key]:event.target.value}:value))}/>}</label>)}{samples.length>1&&<button className="text-button" onClick={()=>setSamples(values=>values.filter((_,i)=>i!==index))}>移除此未保存样本</button>}</fieldset>)}
{samples.length<3&&<button className="button secondary" onClick={()=>setSamples(values=>[...values,draft()])}><Plus size={14}/>添加固定样本</button>}
<div className="evaluation-budget"><label>总 token 预算<input type="number" min={samples.length*2000} max={Math.min(config.maxTaskTokens,config.maxRunTokens*samples.length)} value={tokens} onChange={event=>setTokens(Number(event.target.value))}/></label><label>总请求轮次<input type="number" min={samples.length*2} max={200} value={steps} onChange={event=>setSteps(Number(event.target.value))}/></label><label>总工具次数<input type="number" min={samples.length*2} max={512} value={tools} onChange={event=>setTools(Number(event.target.value))}/></label><label>总时限(分钟)<input type="number" min={1} max={Math.floor(config.maxRunDurationMs/60000)} value={minutes} onChange={event=>setMinutes(Number(event.target.value))}/></label></div>
<p className="evaluation-note">预算按样本均分,续接保留累计用量。总时限从首次原版检查开始,包含审查等待。候选不修改测试、脚本或运行配置。</p>
<div className="evaluation-actions"><button className="button" disabled={!canCreate||!title.trim()||samples.some(sample=>!sample.label.trim()||!sample.goal.trim()||!sample.criteria.trim()||!split(sample.paths).length||!split(sample.checks).length)} onClick={()=>void create()}><ClipboardCheck size={15}/>封存评测计划</button>{creating&&<button className="button secondary" onClick={()=>setCreating(false)}>返回原评测</button>}</div>
</section>:sample&&<>
<section className="evaluation-source"><div><strong>{batch.title}</strong><span className="evaluation-status">{label(batch.status)}</span></div><p>{batch.message}</p><dl><div><dt>固定来源</dt><dd><GitBranch size={13}/>{batch.source.branch} · <code>{batch.source.head.slice(0,12)}</code></dd></div><div><dt>候选模型</dt><dd>{batch.model.mode==='demo'?'离线演示,不能验证模型能力':batch.model.model}</dd></div><div><dt>完整样本分母</dt><dd>{batch.summary.finished} / {batch.summary.samples} 已封存 · 通过 {batch.summary.candidate.passed} · 失败 {batch.summary.candidate.failed} · 未知 {batch.summary.candidate.unknown} · 未执行 {batch.summary.candidate.pending}</dd></div></dl><p className="evaluation-note">{batch.evidenceMode==='local-fixture'?'本批使用本地固定响应,仅验证执行链和真实检查。':batch.summary.scope}</p></section>
<div className="evaluation-workspace"><nav aria-label="固定样本队列">{batch.samples.map((item,index)=><button key={item.id} aria-pressed={sample.id===item.id} onClick={()=>{setSampleId(item.id);setReport(null);}}><small>样本 {index+1}</small><strong>{item.label}</strong><span>{label(item.status)}</span>{item.report&&<span>原版 {label(item.report.summary.original)} → 候选 {label(item.report.summary.candidate)}</span>}</button>)}</nav>
<article className="evaluation-sample"><h3>{sample.label}</h3><p className="evaluation-goal">{sample.goal}</p><div className="evaluation-criteria"><strong>验收条件</strong><p>{sample.criteria}</p></div><div className="evaluation-paths">{sample.paths.map(path=><code key={path}>{path}</code>)}</div>
{sample.error&&<p className="evaluation-error">{sample.error}</p>}
<details className="evaluation-commands" open={sample.status==='ready'}><summary>固定检查 · {sample.checks.join(' / ')}</summary>{sample.commands?.map(command=><div key={command.name}><strong>{command.command}</strong><pre>{command.script}</pre>{command.lifecycle?.map(step=><p key={step.name}>{step.name}:<code>{step.script}</code></p>)}</div>)??<p>工作区准备完成后显示实际命令,执行前需要核对。</p>}</details>
{!!sample.workers?.length&&<div className="evaluation-lanes">{sample.workers.map(worker=><section key={worker.id} aria-label={worker.evaluation?.role==='original'?'原版工程':'候选工程'}><div className="evaluation-lane-title"><h4>{worker.evaluation?.role==='original'?'原版':'候选'}</h4><span>{worker.evaluation?.role==='original'?'只跑固定检查':label(worker.sessionStatus==='awaiting_approval'?'awaiting_approval':worker.status)}</span></div><p>{worker.summary}</p>{worker.status!=='unprepared'&&<button className="button secondary" onClick={()=>void onNavigate(worker.projectId,worker.sessionId,worker.sessionStatus==='awaiting_approval'?'approval':worker.sessionStatus==='needs_review'?'changes':'task')}>{worker.sessionStatus==='awaiting_approval'?'核对并审批检查':worker.sessionStatus==='needs_review'?'审查候选改动':'打开原任务'}<ArrowUpRight size={13}/></button>}</section>)}</div>}
{!!sample.workers?.length&&<p className="evaluation-note">新检出的工程如缺依赖,可先打开两侧原任务,在「工程环境与依赖」分别核对并准备;两侧使用同一锁文件及运行时,再执行原版检查。</p>}{sample.contractSha256&&<p className="evaluation-note">同源输入已封存 · SHA-256 <code>{sample.contractSha256.slice(0,16)}</code></p>}
<div className="evaluation-actions">
{sample.status==='pending'&&<button className="button" disabled={!!action||running||busy||batch.samples.slice(0,batch.samples.indexOf(sample)).some(sample=>!sample.report)} onClick={()=>confirm('prepare')}>准备同源工作区</button>}
{sample.status==='ready'&&<button className="button" disabled={!!action||running} onClick={()=>confirm('baseline')}>核对并运行原版</button>}
{['baseline_complete','paused','awaiting_review','failed','stopped'].includes(sample.status)&&!!sample.baselineJobId&&!sample.report&&<button className="button" disabled={!!action||running||config.mode==='demo'||sample.workers?.some(worker=>worker.evaluation?.role==='candidate'&&worker.sessionStatus==='needs_review')} onClick={()=>confirm('start')}>{sample.status==='baseline_complete'?'开始候选改进':'继续候选任务'}</button>}
{running&&<button className="button secondary" disabled={action==='stop'} onClick={()=>void execute('stop')}><Square size={14}/>停止本批执行</button>}
{!running&&!sample.report&&sample.status!=='pending'&&<button className="button secondary" disabled={!!action} onClick={()=>confirm('seal')}>封存当前结果</button>}
{sample.report&&<button className="button secondary" disabled={!!action} onClick={()=>void showReport()}>查看原版 / 候选对照</button>}
{sample.report?.summary.candidate==='passed'&&!batch.adoption&&batch.samples.every(sample=>sample.report)&&<button className="button" disabled={!!action||running||batch.status==='retained'} onClick={()=>confirm('adopt')}>采纳此候选,准备父工程审查</button>}
{batch.status==='unknown'&&<button className="button secondary" onClick={onRecovery}>打开原协作核对现场</button>}
</div>
</article></div>
{batch.adoption&&<section className="evaluation-delivery"><h3>父工程交付</h3><p>{batch.adoption.delivery?'已完成本地提交 '+batch.adoption.delivery.commit:batch.message}</p>{batch.status==='awaiting_delivery'&&<div className="evaluation-actions"><button className="button secondary" onClick={onReview}>审查父工程变更集</button><button className="button secondary" disabled={!!action||busy} onClick={()=>void execute('finalize')}>核对父工程检查与 Git</button></div>}</section>}
<footer className="evaluation-actions">{!running&&!['completed','retained'].includes(batch.status)&&<button className="text-button" disabled={!!action} onClick={()=>confirm('retain')}>保留现场,结束本批</button>}{canCreate&&<button className="button secondary" onClick={()=>setCreating(true)}><Plus size={14}/>新建下一批评测</button>}</footer>
</>}
</>}
{confirmation&&batch&&sample&&<Modal title="确认评测操作" onClose={()=>setConfirmation(null)}><div className="evaluation-confirm"><h3>{sample.label}</h3><p>{({prepare:'从封存 HEAD 创建两个独立 Git 工作区,保留来源原修改。',baseline:'请核对上方完整检查命令。将以本机账户执行原工程程序,不请求模型。',start:'将请求封存模型并使用剩余预算。候选提案仍需审查,工程检查仍需审批。',seal:'保存当前全部尝试、失败、停止与未知。封存后该样本不能再执行或修改。',adopt:'核对原通过报告及当前来源后,生成父工程待审查变更集。应用、父检查和 Git 交付仍需确认。',retain:'保留原任务、工作区和全部结果,结束本批;未执行样本仍计入原分母。'} as Record<string,string>)[confirmation.operation]}</p><button className="button" disabled={!!action} onClick={()=>{if(confirmation.batchId===batch.id&&confirmation.sampleId===sample.id)void execute(confirmation.operation);}}>确认{({prepare:'准备',baseline:'运行原版',start:'开始候选',seal:'封存结果',adopt:'准备采纳',retain:'保留现场结束'} as Record<string,string>)[confirmation.operation]}</button></div></Modal>}
{report&&sample&&<Modal title="原版与候选对照" wide onClose={()=>setReport(null)}><div className="evaluation-report"><div className="evaluation-report-heading"><div><h3>{report.label}</h3>{report.evidenceMode==='local-fixture'&&<p className="evaluation-note">本地固定响应 · 执行链验收</p>}<p>{report.inputVerified?'原测试与非候选输入已核对':report.inputError??'原输入无法核对'}</p></div><button className="button secondary" onClick={()=>downloadBlob(new Blob([JSON.stringify(report,null,2)],{type:'application/json'}),'agent-workbench-evaluation-'+report.sampleId+'.json')}><Download size={14}/>导出原报告</button></div><div className="evaluation-lanes">{(['original','candidate'] as const).map(role=>{const result=report[role];return <section key={role}><div className="evaluation-lane-title"><h4>{role==='original'?'原版':'候选'}</h4><strong className={'evaluation-outcome '+result.outcome}>{label(result.outcome)}</strong></div><p>{result.reason??result.evidenceError}</p><dl><div><dt>用时</dt><dd>{elapsed(result)}</dd></div><div><dt>模型请求</dt><dd>{result.usage?.requests??'未知'}</dd></div><div><dt>上游用量</dt><dd>{result.usage?.reported?number(result.usage.totalTokens)+' tokens':'未知;保留预算估算'}</dd></div><div><dt>费用</dt><dd>未报告</dd></div><div><dt>实际人工操作</dt><dd>审批 {result.approvals?.filter(approval=>approval.status==='approved').length??0} 次 · 应用提案 {result.changes?.filter(change=>change.status==='applied').length??0} 项</dd></div></dl>{result.attempts.length?result.attempts.map((attempt,index)=><div className="evaluation-attempt" key={attempt.id}><strong>检查尝试 {index+1} · {label(attempt.status)}</strong>{attempt.results.map(check=><div key={check.logArtifactId}><span>{check.name} · {check.status?label(check.status):'证据缺失'}</span>{check.tests&&<span>测试 {check.tests.passed}/{check.tests.total} · 失败 {check.tests.failed}</span>}<code>{check.logSha256?.slice(0,16)??'原日志无法核对'}</code></div>)}</div>):<p>没有完整检查结果;保持未知。</p>}</section>;})}</div><p className="evaluation-note">{report.environmentComparison&&<span>依赖环境:{report.environmentComparison.matched?'原版与候选实际输入一致':'缺少相同环境的有效证据'}。 </span>}{report.note}</p><details><summary>报告原字段与工件引用</summary><pre>{JSON.stringify(report,null,2)}</pre></details></div></Modal>}
</div>;
}
@@ -0,0 +1,15 @@
.file-results .record-heading { flex-wrap: wrap; }
.file-result-row { border-top: 1px solid var(--line); padding: 13px 0; font-size: 12px; line-height: 1.7; overflow-wrap: anywhere; }
.file-result-row > div:first-child { display: flex; flex-direction: column; gap: 2px; margin-bottom: 8px; }
.file-result-row small { color: var(--muted); font-size: 11px; }
.file-result-row > p { margin: 8px 0; }
.file-result-sha { display: block; font: 11px/1.65 "Cascadia Code", Consolas, monospace; overflow-wrap: anywhere; color: var(--muted); }
.file-result-error, .file-result-notice { padding: 9px 11px; background: #faf4e8; color: #684b19; border-left: 2px solid #b18c48; font-size: 12px; line-height: 1.7; overflow-wrap: anywhere; }
.file-result-form { border-top: 1px solid var(--line); padding-top: 12px; margin-top: 8px; }
.file-result-form summary { cursor: pointer; font-weight: 600; font-size: 12px; padding: 5px 0; }
.file-result-form label { display: flex; flex-direction: column; gap: 6px; margin: 12px 0; font-size: 12px; }
.file-result-form select, .file-result-form textarea { width: 100%; min-width: 0; border: 1px solid var(--line); border-radius: 5px; padding: 9px; background: var(--panel, #fff); font: inherit; color: inherit; }
.file-result-form pre { max-height: 230px; overflow: auto; white-space: pre-wrap; overflow-wrap: anywhere; background: #f3f6f4; border: 1px solid var(--line); padding: 10px; font: 11px/1.7 Consolas, monospace; }
.file-result-finish { border-top: 1px solid var(--line); margin-top: 12px; padding-top: 9px; }
.file-result-outcome { padding: 10px; background: #edf7ef; color: #256148; font-size: 12px; line-height: 1.7; }
@media (max-width: 600px) { .file-results button, .file-result-form select { min-height: 42px; } .file-result-form textarea { font-size: 16px; } }
@@ -0,0 +1,83 @@
import { useEffect, useRef, useState } from 'react';
import { FileCheck2, FileText, LoaderCircle, RefreshCw } from 'lucide-react';
import { api } from './api';
import type { Session, FileResultView } from './types';
import './FileResultsPanel.css';
type View = { taskId: string; results: FileResultView[]; sources: { id: string; taskId: string; runId: string; reason: string; files: { path: string; sha256: string }[] }[] };
type File = { path: string; content: string; sha256: string; bytes: number };
export function FileResultsPanel({ session, busy, onSession, openArtifact }: {
session: Session; busy: boolean; onSession: (value: Session) => void; openArtifact: (id: string) => void;
}) {
const task = session.execution?.task;
const [view, setView] = useState<View | null>(null), [files, setFiles] = useState<string[]>([]);
const [path, setPath] = useState(''), [file, setFile] = useState<File | null>(null), [source, setSource] = useState('');
const [reason, setReason] = useState(''), [notice, setNotice] = useState('');
const [loading, setLoading] = useState(false), [acting, setActing] = useState(false);
const scope = useRef(0), readRequest = useRef(0), viewRequest = useRef(0), flight = useRef(false);
const known = view?.sources.filter(row => row.files.some(file => file.path === path)) ?? [];
const current = view?.results.some(row => row.verification === 'current');
async function load() {
const id = scope.current, request = ++viewRequest.current; setLoading(true);
try {
const [result, inventory] = await Promise.all([api<View>('/sessions/' + session.id + '/file-results' + (path ? '?path=' + encodeURIComponent(path) : '')), api<{ files: { path: string; kind: string; bytes: number }[] }>('/projects/' + session.projectId + '/files')]);
if (scope.current !== id || viewRequest.current !== request) return;
setView(result); setFiles(inventory.files.filter(item => item.kind === 'file' && item.bytes <= 1024 * 1024).map(item => item.path));
} catch (error) { if (scope.current === id && viewRequest.current === request) setNotice(error instanceof Error ? error.message : String(error)); }
finally { if (scope.current === id && viewRequest.current === request) setLoading(false); }
}
useEffect(() => {
scope.current++; readRequest.current++; flight.current = false; setActing(false); setView(null); setPath(''); setFile(null); setSource(''); setReason(''); setNotice(''); void load();
return () => { scope.current++; readRequest.current++; };
}, [session.id, task?.id]);
useEffect(() => { void load(); }, [session.execution?.fileResults?.at(-1)?.id, session.execution?.run?.id, session.status]);
async function choose(value: string) {
setPath(value); setFile(null); setSource(''); setNotice('');
const id = scope.current, request = ++readRequest.current, viewId = ++viewRequest.current;
setLoading(false);
if (!value) return;
try { const [result, currentView] = await Promise.all([api<File>('/projects/' + session.projectId + '/file?path=' + encodeURIComponent(value)), api<View>('/sessions/' + session.id + '/file-results?path=' + encodeURIComponent(value))]);
if (scope.current === id && readRequest.current === request) { setFile(result); if (viewRequest.current === viewId) setView(currentView); }
} catch (error) { if (scope.current === id && readRequest.current === request) setNotice(error instanceof Error ? error.message : String(error)); }
}
async function save(complete = false) {
if (!task || !session.execution?.run || flight.current) return;
if (!complete && (!file || file.path !== path || !reason.trim())) return;
const id = scope.current; viewRequest.current++; setLoading(false); flight.current = true; setActing(true); setNotice('');
try {
const result = await api<View & { session: Session }>('/sessions/' + session.id + '/file-results' + (complete ? '/complete' : ''), {
taskId: task.id, runId: session.execution.run.id,
...(!complete && file ? { files: [{ path: file.path, sha256: file.sha256, ...(source ? { source_result_id: source } : {}) }], reason } : {}),
});
if (scope.current !== id) return;
setView(result); onSession(result.session); setNotice(complete ? '任务已按当前成果结束,原运行和检查记录保留。' : '当前文件已核对并登记;未新增文件改动、测试或Git提交。');
} catch (error) { if (scope.current === id) setNotice(error instanceof Error ? error.message : String(error)); }
finally { if (scope.current === id) { flight.current = false; setActing(false); } }
}
return <section className="task-record-section file-results" aria-label="当前文件成果" aria-busy={loading || acting}>
<div className="record-heading"><FileCheck2 size={15} /><h3>当前文件成果</h3><span>{view?.results.length ?? 0} 份凭据</span></div>
<p className="record-footnote">已有文件可以核对后沿用。成果、实际修改、检查与提交分别保留。</p>
<button type="button" className="text-button" disabled={loading || acting} onClick={() => void load()}>{loading ? <LoaderCircle size={13} className="spin" /> : <RefreshCw size={13} />}刷新成果状态</button>
{view?.results.map(row => <article className="file-result-row" key={row.id}>
<div><strong>{row.verification === 'current' ? '当前文件已核对' : row.verification === 'stale' ? '需要重新核对' : '原凭据需核查'}</strong><small>Task {row.taskId.slice(0, 8)} · Run {row.runId.slice(0, 8)}</small></div>
{row.files.map(item => <div key={item.path}><code>{item.path}</code><small className="file-result-sha">SHA-256 {item.sha256}</small>{item.origin && <p className="record-footnote">采用自 Task {item.origin.taskId.slice(0, 8)} · Run {item.origin.runId.slice(0, 8)}<br />原文件 SHA-256 {item.origin.sha256}</p>}
{row.verification !== 'current' && <button type="button" className="text-button" disabled={busy || acting} onClick={() => { void choose(item.path); setReason(row.reason); }}>重新打开此文件核对</button>}
</div>)}
<p>{row.reason}</p>{row.error && <p className="file-result-error">{row.error}</p>}
<button type="button" className="text-button" onClick={() => openArtifact(row.contractArtifactId)}><FileText size={13} />查看原成果凭据</button>
</article>)}
<details className="file-result-form">
<summary>核对已有文件</summary>
<label>选择项目内文件<select aria-label="成果文件" value={path} disabled={busy || acting || loading} onChange={event => void choose(event.target.value)}><option value="">选择一个文件</option>{files.map(value => <option key={value} value={value}>{value}</option>)}</select></label>
{path && <button type="button" className="text-button" disabled={busy || acting} onClick={() => void choose(path)}><RefreshCw size={13} />重新读取当前文件</button>}
{file && <><p className="record-footnote">{file.bytes.toLocaleString('zh-CN')} 字节 · 当前读取 SHA-256</p><code className="file-result-sha">{file.sha256}</code><pre aria-label="成果文件内容">{file.content.length > 12000 ? file.content.slice(0, 12000) + '\n…界面仅展开前12000字符;核对保存完整文件快照。' : file.content}</pre></>}
{!!known.length && <label>采用来源<select aria-label="成果来源" value={source} disabled={busy || acting} onChange={event => setSource(event.target.value)}><option value="">选择原任务成果</option>{known.map(row => <option key={row.id} value={row.id}>Task {row.taskId.slice(0, 8)} · {row.reason.slice(0, 60)}</option>)}</select></label>}
<label>采用原因<textarea aria-label="成果采用原因" rows={3} maxLength={600} placeholder="说明这个文件满足了当前任务的哪些要求" value={reason} disabled={busy || acting} onChange={event => setReason(event.target.value)} /></label>
<button type="button" className="button secondary" disabled={busy || acting || !file || !reason.trim() || !!known.length && !source} onClick={() => void save()}>{acting ? <LoaderCircle size={14} className="spin" /> : <FileCheck2 size={14} />}核对并采用此文件</button>
</details>
{current && task?.status !== 'completed' && <div className="file-result-finish"><p className="record-footnote">当前要求已满足时可结束。修改要求、原检查和执行计划仍需通过核对。</p><button type="button" className="button secondary" disabled={busy || acting} onClick={() => void save(true)}>按当前成果结束任务</button></div>}
{task?.delivery?.status === 'existing_verified' && <p className="file-result-outcome">结束时采用已有成果 · 无新增修改。当前有效性见逐项核对,检查与Git另列。</p>}
{notice && <p className="file-result-notice" role="status">{notice}</p>}
</section>;
}
@@ -0,0 +1,24 @@
import { useEffect, useState } from 'react';
import { ExternalLink, LoaderCircle, RotateCw } from 'lucide-react';
import { api } from './api';
import { desktop } from './desktop';
import './LocalFiles.css';
type Preview = { id: string; url: string; projectId: string; path: string };
export function HtmlFilePreview({ projectId, path }: { projectId: string; path: string }) {
const [preview, setPreview] = useState<Preview | null>(null), [error, setError] = useState(''), [attempt, setAttempt] = useState(0), [loaded, setLoaded] = useState(false);
useEffect(() => {
let current = true, owned: Preview | null = null;
const close = (value: Preview) => api('/projects/' + projectId + '/file-previews/' + value.id, {}, 'DELETE').catch(() => {});
setPreview(null); setError(''); setLoaded(false);
void api<Preview>('/projects/' + projectId + '/file-previews', { path }).then(value => {
if (current) { owned = value; setPreview(value); } else void close(value);
}).catch(cause => { if (current) setError(cause instanceof Error ? cause.message : '无法打开 HTML 预览。'); });
return () => { current = false; if (owned) void close(owned); };
}, [projectId, path, attempt]);
return <div className="html-file-preview">
<div className="html-preview-toolbar"><span>HTML 文件预览</span><button type="button" className="button secondary" onClick={() => setAttempt(value => value + 1)}><RotateCw size={14} />刷新预览</button>{preview && (desktop?.openFilePreview ? <button type="button" className="button secondary" onClick={() => void desktop!.openFilePreview!({ projectId, url: preview.url }).catch(cause => setError(cause.message))}><ExternalLink size={14} />在浏览器打开</button> : <a className="button secondary" href={preview.url} target="_blank" rel="noopener noreferrer"><ExternalLink size={14} />独立页面</a>)}</div>
{error ? <div className="html-preview-message" role="alert"><p>{error}</p><button className="button secondary" onClick={() => setAttempt(value => value + 1)}>重试预览</button></div> : <>{!loaded && <div className="html-preview-message" role="status"><LoaderCircle size={17} className="spin" />正在打开 HTML 页面…</div>}{preview && <iframe key={preview.id} title={'HTML 预览:' + path} src={preview.url} sandbox="allow-scripts" referrerPolicy="no-referrer" onLoad={() => setLoaded(true)} onError={() => setError('页面加载失败,请刷新预览后重试。')} />}</>}
<p className="html-preview-note">直接读取已保存文件,支持页面脚本与相对资源。需要后端或构建的应用请启动项目预览。</p>
</div>;
}
@@ -0,0 +1,35 @@
import { useEffect,useRef,useState } from 'react';
import { ImagePlus,Download,X,LoaderCircle } from 'lucide-react';
import { api,downloadBlob,inputImageBlob } from './api';
import { Modal } from './components';
import type { InputAttachment,Session } from './types';
import './input-attachments.css';
export function InputImage({sessionId,image,onError}:{sessionId:string;image:InputAttachment;onError:(error:unknown)=>void}){
const [url,setUrl]=useState(''),[open,setOpen]=useState(false),[error,setError]=useState('');
useEffect(()=>{let alive=true,objectUrl='';setUrl('');setError('');void inputImageBlob(sessionId,image).then(blob=>{if(alive){objectUrl=URL.createObjectURL(blob);setUrl(objectUrl);}}).catch(cause=>{if(alive)setError(cause.message);});return()=>{alive=false;if(objectUrl)URL.revokeObjectURL(objectUrl);};},[sessionId,image.id,image.sentSha256]);
return <div className="input-receipt"><button type="button" className="input-thumbnail" aria-label={'查看截图 '+image.name} disabled={!url} onClick={()=>setOpen(true)}>{url?<img src={url} alt={image.name} width={72} height={48}/>:<span>{error?'读取失败':'核对中'}</span>}</button><div><strong>{image.name}</strong><span>发送副本 {image.sentWidth} × {image.sentHeight} · {Math.ceil(image.sentBytes/1024)} KB</span><small>{error|| (url?'SHA-256 已核对':'核对原字节…')}</small></div>
{open&&<Modal title="任务截图" description={image.name+' · 原图 '+image.width+' × '+image.height} onClose={()=>setOpen(false)} wide><img className="input-preview" src={url} alt={image.name}/><p className="input-sha">原图 SHA-256 {image.sha256}<br/>发送副本 SHA-256 {image.sentSha256}</p><p>发送副本已去除元数据并归正方向,最长边不超过1024像素、768KB。细小文字请先裁剪;原图完整保留。</p><div className="modal-actions"><button className="button secondary" type="button" onClick={()=>void inputImageBlob(sessionId,image,true).then(blob=>downloadBlob(blob,image.name)).catch(onError)}><Download size={14}/>下载原图</button><button className="button secondary" type="button" onClick={()=>void inputImageBlob(sessionId,image).then(blob=>downloadBlob(blob,'sent-'+image.id+'.png')).catch(onError)}>下载发送副本</button></div></Modal>}
</div>;
}
export function AttachmentComposer({session,selectedIds,onSelection,onEnsureSession,onSession,onError,disabled,routeName,onModels}:{session:Session|null;selectedIds:string[];onSelection:(id:string,ids:string[])=>void;onEnsureSession:()=>Promise<Session|null>;onSession:(value:Session)=>void;onError:(error:unknown)=>void;disabled:boolean;routeName:string;onModels:()=>void}){
const input=useRef<HTMLInputElement>(null),[busy,setBusy]=useState(false);
const drafts=session?.inputAttachments?.filter(value=>value.status==='draft')??[];
async function upload(file:File){
setBusy(true);
try{
if(file.size>2*1024*1024)throw new Error('单张截图最多2MB,请裁剪后添加。');
if(!['image/png','image/jpeg'].includes(file.type))throw new Error('请选择静态PNG或JPEG截图。');
const target=session??await onEnsureSession();if(!target)return;
const bytes=new Uint8Array(await file.arrayBuffer());let binary='';for(let p=0;p<bytes.length;p+=8192)binary+=String.fromCharCode(...bytes.subarray(p,p+8192));
const row=await api<InputAttachment>('/sessions/'+target.id+'/input-attachments',{name:file.name,mediaType:file.type,base64:btoa(binary)});
onSession(await api<Session>('/sessions/'+target.id));onSelection(target.id,[row.id]);
}catch(error){onError(error);}finally{setBusy(false);if(input.current)input.current.value='';}
}
async function remove(id:string){if(!session)return;setBusy(true);try{await api('/sessions/'+session.id+'/input-attachments/'+id,{},'DELETE');onSession(await api<Session>('/sessions/'+session.id));if(selectedIds.includes(id))onSelection(session.id,[]);}catch(error){onError(error);}finally{setBusy(false);}}
return <div className="input-composer"><div className="input-composer-tools"><button type="button" className="input-add" disabled={disabled||busy} onClick={()=>input.current?.click()}>{busy?<LoaderCircle size={15} className="spin"/>:<ImagePlus size={15}/>}添加截图</button><span>每任务1张 · PNG/JPEG · 原图≤2MB</span><input ref={input} type="file" accept="image/png,image/jpeg" aria-label="选择工程截图" hidden onChange={event=>{const file=event.target.files?.[0];if(file)void upload(file);}}/></div>
{!!drafts.length&&<div className="input-drafts">{drafts.map(image=><div className={'input-draft '+(selectedIds.includes(image.id)?'selected':'')} key={image.id}><label><input type="checkbox" checked={selectedIds.includes(image.id)} disabled={disabled||busy} onChange={event=>onSelection(session!.id,event.target.checked?[image.id]:[])}/><span>随任务发送</span></label><InputImage sessionId={session!.id} image={image} onError={onError}/><button type="button" className="input-remove" aria-label={'移除截图 '+image.name} disabled={disabled||busy} onClick={()=>void remove(image.id)}><X size={15}/></button></div>)}</div>}
{!!selectedIds.length&&<p className="input-route">将随文字发送至 <strong>{routeName}</strong>,池仅使用声明或检测支持视觉的成员。<button type="button" onClick={onModels}>核对模型能力</button><span>发送副本≤1024像素/768KB;图片预留单独估算,实际用量以服务返回为准。</span></p>}
</div>;
}
@@ -0,0 +1,23 @@
.installation-status { color: var(--text, #24383e); font-size: 13px; line-height: 1.6; }
.installation-status > header { display: flex; align-items: flex-start; justify-content: space-between; gap: 16px; padding-bottom: 18px; border-bottom: 1px solid #dce3e7; }
.installation-status h3 { margin: 0 0 4px; font-size: 15px; }
.installation-status p { margin: 5px 0; }
.installation-status button { flex-shrink: 0; }
.installation-facts { display: grid; grid-template-columns: 76px minmax(0, 1fr); gap: 9px 14px; margin: 18px 0; }
.installation-facts dt { color: #52636c; }
.installation-facts dd { margin: 0; overflow-wrap: anywhere; font: 12px/1.6 var(--font-mono, Consolas, monospace); }
.installation-operation { margin-top: 18px; padding: 18px 0 0; border-top: 1px solid #dce3e7; }
.installation-stage { display: flex; align-items: center; gap: 9px; }
.installation-stage > span:last-child { margin-left: auto; white-space: nowrap; color: #52636c; font-variant-numeric: tabular-nums; }
.installation-state-dot { flex: 0 0 7px; height: 7px; border-radius: 50%; background: #337858; }
.installation-failed .installation-state-dot, .installation-unknown .installation-state-dot { background: #a04832; }
.installation-counts { display: grid; gap: 6px; margin: 16px 0; font-variant-numeric: tabular-nums; }
.installation-counts progress { width: 100%; height: 6px; accent-color: #337858; }
.installation-counts code { overflow-wrap: anywhere; color: #52636c; font-size: 11px; }
.installation-note, .installation-empty { padding: 12px 0; color: #52636c; }
.installation-error { margin-top: 12px; padding: 12px; background: #fff2ed; color: #843620; overflow-wrap: anywhere; border-left: 3px solid #b86d4d; }
.installation-history { display: grid; gap: 6px; margin-top: 16px; color: #52636c; }
.installation-history select { width: 100%; min-width: 0; padding: 8px; border: 1px solid #c5d1d8; border-radius: 4px; color: #24383e; background: #fff; font: inherit; }
.connection .version-entry { color: inherit; padding: 0 3px; margin-left: auto; min-width: 0; width: auto; background: transparent; border: 0; font: inherit; font-size: 11px; cursor: pointer; text-decoration: underline; text-underline-offset: 3px; }
.connection .version-entry:focus-visible { outline: 2px solid currentColor; outline-offset: 3px; }
@media(max-width: 480px) { .installation-status > header { flex-wrap: wrap; } .installation-facts { grid-template-columns: 1fr; gap: 3px; } .installation-facts dd { margin-bottom: 9px; } .installation-stage { flex-wrap: wrap; } }
@@ -0,0 +1,49 @@
import { useEffect, useState } from 'react';
import { RotateCw } from 'lucide-react';
import { api } from './api';
import './InstallationStatus.css';
type Operation = {
id: string; sequence: number; state: string; stage: string; label: string; updatedAt: string; elapsedMs: number; scope?: string;
counts?: { completedFiles: number; totalFiles: number; completedBytes: number | null; totalBytes: number | null; currentPath?: string } | null;
candidate?: { version: string; manifestSha256: string } | null;
detail?: { error?: { code: string; message: string }; receiptFile?: string; originalError?: string };
progressFile: string; interrupted?: boolean;
};
type Status = { installed: boolean; runningVersion: string; activeVersion?: string; previousVersion?: string | null; installRoot?: string; operations: Operation[] };
const size = (bytes: number) => { const unit = bytes < 1024 ? 0 : bytes < 1024 ** 2 ? 1 : bytes < 1024 ** 3 ? 2 : 3; return new Intl.NumberFormat('zh-CN', { maximumFractionDigits: 1 }).format(bytes / 1024 ** unit) + ' ' + ['B', 'KB', 'MB', 'GB'][unit]; };
const scopeLabel = (scope?: string) => scope === 'full-manifest' ? '全部发行文件' : scope === 'directory-inventory' ? '实际目录范围' : scope === 'loaded-inputs' ? '宿主与客户端入口' : '';
export function InstallationStatus() {
const [status, setStatus] = useState<Status | null>(null), [error, setError] = useState(''), [busy, setBusy] = useState(false);
const [refresh, setRefresh] = useState(0);
const [selected, setSelected] = useState('');
useEffect(() => {
let alive = true, timer: ReturnType<typeof setTimeout>;
const load = async () => {
setBusy(true);
try {
const value = await api<Status>('/installation/status');
if (alive) { setStatus(value); setError(''); }
} catch (value) { if (alive) setError(value instanceof Error ? value.message : '无法读取原安装进度。'); }
finally { if (alive) { setBusy(false); timer = setTimeout(() => void load(), 2500); } }
};
void load(); return () => { alive = false; clearTimeout(timer); };
}, [refresh]);
const operation = status?.operations.find(value => value.id === selected) ?? status?.operations[0];
return <section className="installation-status" aria-label="版本与更新状态">
<header><div><h3>当前版本</h3><p>{status ? <>正在运行 <strong>v{status.runningVersion}</strong>{status.installed && <> · 已登记 v{status.activeVersion}</>}</> : '正在读取本机安装登记…'}</p></div><button className="button secondary" disabled={busy} onClick={() => setRefresh(value => value + 1)}><RotateCw size={14} />刷新状态</button></header>
{error && <p role="alert" className="installation-error">{error}{status && ' 以下保留上次读取结果,请刷新后再判断当前状态。'}</p>}
{status && !status.installed && <p>当前使用源码或便携目录。安装版会在这里显示所属更新阶段和原始失败记录。</p>}
{status?.installed && <dl className="installation-facts"><dt>程序目录</dt><dd>{status.installRoot}</dd><dt>前一版本</dt><dd>{status.previousVersion ? 'v' + status.previousVersion : '首次安装'}</dd></dl>}
{status?.installed && !operation && <p className="installation-empty">还没有新版安装进度记录。此前版本的原操作收据保存在程序目录的 .installation 中。</p>}
{status && status.operations.length > 1 && <label className="installation-history">安装操作<select aria-label="查看安装操作" value={selected} onChange={event => setSelected(event.target.value)}><option value="">最近一次操作</option>{status.operations.map(value => <option key={value.id} value={value.id}>{new Date(value.updatedAt).toLocaleString('zh-CN')} · {value.interrupted ? '结果待核对' : value.label}</option>)}</select></label>}
{operation && <article className={'installation-operation installation-' + operation.state}>
<div className="installation-stage" role="status"><span className="installation-state-dot" /><strong>{operation.interrupted ? '原安装进程已结束,结果待核对' : operation.label}</strong><span>{Math.round(operation.elapsedMs / 1000)} 秒</span></div>
{operation.counts && <div className="installation-counts"><span>{scopeLabel(operation.scope)}</span><strong>{operation.counts.completedFiles.toLocaleString()} / {operation.counts.totalFiles.toLocaleString()} 文件</strong>{operation.counts.completedBytes !== null && operation.counts.totalBytes !== null && <span>{size(operation.counts.completedBytes)} / {size(operation.counts.totalBytes)}</span>}<progress aria-label="当前核对范围" max={Math.max(1, operation.counts.totalFiles)} value={operation.counts.completedFiles} />{operation.counts.currentPath && <code>{operation.counts.currentPath}</code>}</div>}
{operation.detail?.error && <div className="installation-error" role="alert"><strong>{operation.detail.error.code}</strong><p>{operation.detail.error.message}</p></div>}
<dl className="installation-facts"><dt>目标版本</dt><dd>{operation.candidate ? 'v' + operation.candidate.version : '准备时尚未读取候选'}</dd><dt>操作编号</dt><dd>{operation.id} · 序号 {operation.sequence}</dd><dt>原始记录</dt><dd>{operation.progressFile}</dd>{operation.detail?.receiptFile && <><dt>结果收据</dt><dd>{operation.detail.receiptFile}</dd></>}</dl>
<p className="installation-note">{operation.state === 'ready-to-copy' ? '预检已通过,写入进度由安装器显示;新版本尚未激活。' : operation.interrupted ? '请保留原安装日志与收据,核对已登记版本。不要根据窗口关闭推断安装成功,也不要重复执行原任务。' : operation.state === 'failed' ? '原失败记录已保留。请按具体原因处理,核对已登记版本及回退收据后再开始新的安装。' : operation.state === 'staged' ? '文件已核对并暂存,当前活动版本保留。' : operation.state === 'running' ? '当前阶段核对实际文件。发布版本和回退期间需要保持安装器打开;各阶段单独计数。' : '原会话与工件保留。这里的安装结果不代表模型工程任务已经通过。'}</p>
</article>}
</section>;
}
@@ -0,0 +1 @@
.directory-picker{border:1px solid #d3dfd9;border-radius:8px;background:#fff;margin:14px 0;overflow:hidden}.directory-location{display:flex;align-items:center;gap:6px;padding:10px;border-bottom:1px solid #dfe7e2}.directory-location input{min-width:0;flex:1;border:1px solid #c4d2ca;border-radius:5px;padding:9px;font-size:12px;background:#fff;color:#294a3c}.directory-location .button{padding:0 10px}.directory-bookmarks{display:flex;flex-wrap:wrap;gap:5px;padding:9px 12px;background:#f4f7f5}.directory-bookmarks button{padding:6px 9px;border:1px solid #d4dfd8;border-radius:4px;color:#345b48;font-size:12px;background:#fff}.directory-filter{display:block;width:calc(100% - 24px);margin:10px 12px;padding:9px;border:1px solid #c4d2ca;border-radius:5px;background:#fff;color:#294a3c;font-size:12px}.directory-list{height:235px;overflow:auto;padding:0 8px 8px}.directory-list>button{display:flex;align-items:center;gap:9px;width:100%;padding:10px 8px;text-align:left;border-radius:4px;font-size:13px;color:#2f5140}.directory-list>button:hover,.directory-list>button:focus-visible{background:#e9f0ec}.directory-list>button>span{overflow-wrap:anywhere}.directory-list>p{display:flex;align-items:center;justify-content:center;gap:8px;padding:30px 10px;font-size:12px;color:#526b5d}.directory-selection{border-top:1px solid #dfe7e2;padding:12px;display:grid;gap:12px}.directory-selection>span{font-size:12px;overflow-wrap:anywhere;line-height:1.6}.directory-selection>div{display:flex;justify-content:flex-end;flex-wrap:wrap;gap:8px}.local-files-error{font-size:12px;color:#9a352d;background:#fff2ee;padding:10px 12px;line-height:1.6}.file-mode-switch{display:flex;gap:4px;margin-left:auto}.file-mode-switch button{padding:6px 9px;border-radius:4px;color:#456151;font-size:12px}.file-mode-switch button[aria-pressed=true]{background:#e3ece6;color:#214c37;font-weight:600}.file-mode-switch button:disabled{opacity:.5}.html-file-preview{display:flex;flex:1;min-height:0;flex-direction:column;position:relative;background:#fff}.html-preview-toolbar{display:flex;flex-wrap:wrap;align-items:center;gap:7px;padding:10px;border-bottom:1px solid #dfe7e2;flex-shrink:0}.html-preview-toolbar>span{font-size:11px;color:#536b5c;margin-right:auto}.html-preview-toolbar .button{height:30px;padding:0 9px;font-size:11px;text-decoration:none}.html-file-preview iframe{border:0;width:100%;min-height:200px;flex:1;background:#fff}.html-preview-message{display:flex;align-items:center;justify-content:center;gap:9px;padding:24px;font-size:12px;color:#3e5b4c;line-height:1.7}.html-preview-note{margin:0;padding:9px 12px;font-size:11px;line-height:1.6;color:#536b5c;border-top:1px solid #dfe7e2;background:#f4f7f5;flex-shrink:0}.file-heading:has(.file-mode-switch){flex-wrap:wrap}.file-heading:has(.file-mode-switch)>span{min-width:90px}@media(max-width:620px){.directory-list{height:190px}.directory-picker button,.file-mode-switch button{min-height:40px}.directory-location{padding:7px;gap:3px}.directory-location .button{padding:0 7px}.html-preview-toolbar .button{min-height:38px}.html-preview-toolbar>span{width:100%}}
@@ -0,0 +1,70 @@
import { useEffect, useRef, useState } from 'react';
import { AlertTriangle, Check, CircleAlert, Clock3, Download, FileText, LoaderCircle, ShieldCheck } from 'lucide-react';
import type { McpJob, Session } from './types';
import { api } from './api';
import { Modal } from './components';
import './McpPanel.css';
const active = ['queued', 'connecting', 'discovering', 'calling', 'closing', 'stopping'];
const labels: Record<string, string> = { queued: '排队', connecting: '正在连接', discovering: '发现工具', calling: '正在调用', closing: '正在关闭', stopping: '正在停止', completed: '完成', failed: '失败', cancelled: '已停止', unknown: '结果待核对' };
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;
}) {
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();
useEffect(() => { request.current++; setSelected(null); setReview(null); setWorking(false); }, [session.id, currentTask]);
async function open(job: McpJob, forReview = false) {
const id = ++request.current; setWorking(true);
try {
const value = await api<Evidence>('/sessions/' + session.id + '/mcp/jobs/' + job.id + '/evidence');
if (request.current === id) { setSelected(value); if (forReview) setReview(value); }
}
catch (error) { if (request.current === id) onError(error); }
finally { if (request.current === id) setWorking(false); }
}
async function acknowledge() {
if (!review) return; const id = ++request.current; setWorking(true);
try {
await api('/sessions/' + session.id + '/mcp/jobs/' + review.job.id + '/acknowledge', { confirm: true, evidence_sha256: review.evidenceSha256 });
const updated = await api<Session>('/sessions/' + session.id);
if (request.current === id) { onSession(updated); setReview(null); }
} catch (error) { if (request.current === id) onError(error); }
finally { if (request.current === id) setWorking(false); }
}
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>
{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>
<div className="mcp-history-meta"><span>Task {job.taskId.slice(0, 8)}</span><span>Run {job.runId.slice(0, 8)}</span><span>PID {job.pid ?? '未启动'}</span>
<span>{job.cleanup?.rootExited ? '所属进程已退出' : job.finishedAt ? '进程退出待核对' : '进程运行中'}</span></div>
{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>}
{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>
<details className="mcp-original-input"><summary>查看原始操作输入 · SHA256 {selected.input.sha256.slice(0, 16)}</summary><pre>{JSON.stringify(selected.input.input, null, 2)}</pre></details>
{selected.report ? <pre tabIndex={0}>{JSON.stringify(selected.report, null, 2)}</pre> : <p className="mcp-history-error">{selected.note}</p>}
<button type="button" className="text-button" onClick={() => { const blob = new Blob([JSON.stringify(selected.report ?? selected, null, 2)], { type: 'application/json' }); const link = document.createElement('a'); link.href = URL.createObjectURL(blob); link.download = (selected.report ? 'mcp-report-' : 'mcp-recovery-') + selected.job.id + '.json'; link.click(); setTimeout(() => URL.revokeObjectURL(link.href), 1000); }}><Download size={13} />{selected.report ? '下载显示的原报告' : '下载已保存的记录'}</button>
</section>}
</section>
{review && <Modal title="核对未知的外部结果" description="这只记录人工核对,不会把未知结果改成成功。" onClose={() => setReview(null)}>
<div className="mcp-review-warning"><AlertTriangle size={17} /><p>外部副作用可能已经发生。请核对原输入、当前文件和程序状态;历史PID仅供核对,不会被用来停止进程。</p></div>
<p className="mcp-boundary-note">{review.note}</p>
<details className="mcp-original-input"><summary>查看已校验原始输入</summary><pre>{JSON.stringify(review.input.input, null, 2)}</pre></details>
<div className="modal-actions"><button type="button" className="button secondary" disabled={working} onClick={() => setReview(null)}>返回</button><button type="button" className="button primary" disabled={working || !review.evidenceSha256} onClick={() => void acknowledge()}>{working ? <LoaderCircle size={14} className="spin" /> : <Check size={14} />}{review.report ? '我已查看原报告' : '我已核对原输入和进程'}</button></div>
</Modal>}
</>;
}
@@ -0,0 +1,99 @@
.mcp-panel { color: #253b4b; --mcp-line: #cad5dc; --mcp-ink: #183849; --mcp-muted: #607584; --mcp-surface: #f2f6f6; }
.mcp-heading { display: flex; align-items: start; justify-content: space-between; gap: 20px; margin-bottom: 18px; }
.mcp-kicker { display: flex; align-items: center; gap: 7px; color: #496f73; font-size: 11px; font-weight: 700; }
.mcp-heading h3 { margin: 8px 0; color: var(--mcp-ink); font: 700 23px/1.35 'Microsoft YaHei UI', 'Segoe UI', sans-serif; }
.mcp-heading p { max-width: 640px; margin: 0; color: var(--mcp-muted); font-size: 13px; line-height: 1.7; }
.mcp-heading > button { flex: 0 0 auto; }
.mcp-status-bar { display: flex; flex-wrap: wrap; gap: 10px 20px; align-items: center; padding: 12px 2px; border-block: 1px solid var(--mcp-line); color: #496171; font-size: 12px; }
.mcp-status-bar > span { display: inline-flex; align-items: center; gap: 7px; }
.mcp-light { width: 7px; height: 7px; border-radius: 50%; background: #2f816b; }
.mcp-alert, .mcp-notice, .mcp-warning, .mcp-boundary { display: flex; align-items: start; gap: 9px; padding: 11px 12px; margin: 12px 0; border: 1px solid #d8c4b8; background: #fff7f1; color: #92563c; font-size: 12px; line-height: 1.65; overflow-wrap: anywhere; }
.mcp-alert svg, .mcp-notice svg, .mcp-boundary svg { flex: 0 0 auto; margin-top: 2px; }
.mcp-notice { border-color: #bdd8cb; background: #eff7f3; color: #356b5e; }
.mcp-warning { border: 0; padding: 0; background: transparent; color: #8f642d; }
.mcp-boundary { border-color: #c5d8d8; background: #f0f7f6; color: #456d6a; }
.mcp-registration-list { display: grid; gap: 12px; margin-top: 14px; }
.mcp-registration { min-width: 0; padding: 16px; border: 1px solid var(--mcp-line); border-left: 4px solid #6c8990; border-radius: 5px; background: #fff; }
.mcp-registration.status-changed { border-left-color: #aa6548; }
.mcp-registration-heading { display: flex; align-items: start; gap: 10px; }
.mcp-registration-heading > svg { flex: 0 0 auto; margin-top: 2px; color: #4d7479; }
.mcp-registration-heading > div { flex: 1; min-width: 0; }
.mcp-registration-heading h4 { margin: 0 0 4px; color: #203f4b; font-size: 15px; overflow-wrap: anywhere; }
.mcp-registration-heading p { margin: 0; color: var(--mcp-muted); font-size: 11px; }
.mcp-enabled { flex: 0 0 auto; padding: 4px 7px; border: 1px solid #d0d9dc; color: #60717a; font-size: 10px; border-radius: 3px; }
.mcp-enabled.on { color: #276855; border-color: #b6d2c7; background: #edf6f1; }
.mcp-source { display: grid; gap: 9px; margin: 14px 0; padding: 11px; background: var(--mcp-surface); font-size: 11px; }
.mcp-source > div { display: grid; gap: 3px; min-width: 0; }
.mcp-source > div > span, .mcp-source > span { color: #637781; }
.mcp-source code, .mcp-source small { overflow-wrap: anywhere; word-break: break-word; }
.mcp-source code { color: #243e4c; font: 11px/1.55 Consolas, monospace; }
.mcp-source small { display: flex; align-items: center; gap: 5px; color: #648077; font-size: 10px; }
.mcp-contract-line { display: flex; align-items: center; gap: 6px; margin: 12px 0; color: #357566; font-size: 11px; overflow-wrap: anywhere; }
.mcp-tool-list { border-top: 1px solid #e1e8e8; padding-top: 11px; }
.mcp-tool-heading { display: flex; align-items: center; justify-content: space-between; gap: 10px; margin-bottom: 7px; font-size: 12px; }
.mcp-tool-heading span { color: var(--mcp-muted); font-size: 10px; }
.mcp-tool-option { display: grid; grid-template-columns: 18px minmax(0, 1fr); gap: 9px; padding: 10px 7px; border-top: 1px solid #ebefef; }
.mcp-tool-option > input { width: 16px; height: 16px; margin: 2px 0 0; accent-color: #347b70; }
.mcp-tool-option > span { min-width: 0; display: grid; gap: 4px; }
.mcp-tool-option strong { color: #294a54; font-size: 12px; overflow-wrap: anywhere; }
.mcp-tool-option em { color: #9a5b42; font-size: 10px; font-style: normal; }
.mcp-tool-option small { color: #687c84; font-size: 11px; line-height: 1.5; overflow-wrap: anywhere; }
.mcp-tool-option details { color: #526d72; font-size: 10px; }
.mcp-tool-option summary { width: fit-content; min-height: 26px; padding: 4px 0; cursor: pointer; }
.mcp-tool-option pre, .mcp-report pre { max-height: 260px; overflow: auto; padding: 10px; background: #f1f5f5; color: #314e59; white-space: pre-wrap; overflow-wrap: anywhere; font: 10px/1.6 Consolas, monospace; }
.mcp-tool-option.unsupported { opacity: .7; }
.mcp-controls { display: flex; flex-wrap: wrap; gap: 8px; margin-top: 12px; }
.mcp-register { margin-top: 18px; padding: 16px; border: 1px solid var(--mcp-line); border-radius: 5px; background: var(--mcp-surface); }
.mcp-register-heading { display: flex; justify-content: space-between; align-items: center; gap: 10px; flex-wrap: wrap; margin-bottom: 13px; }
.mcp-register-heading h4 { display: flex; align-items: center; gap: 6px; margin: 0; color: #294753; font-size: 13px; }
.mcp-register-heading span { color: var(--mcp-muted); font-size: 10px; }
.mcp-form-grid { display: grid; grid-template-columns: minmax(0, 1fr) 190px; gap: 11px; }
.mcp-form-grid label { display: grid; gap: 5px; min-width: 0; color: #4d6571; font-size: 11px; font-weight: 600; }
.mcp-full { grid-column: 1 / -1; }
.mcp-panel input:not([type="checkbox"]) { width: 100%; min-width: 0; padding: 9px 10px; border: 1px solid #c7d3d6; border-radius: 3px; background: #fff; color: #233d49; font: 12px/1.45 'Segoe UI', 'Microsoft YaHei UI', sans-serif; }
.mcp-panel input:focus-visible, .mcp-panel summary:focus-visible, .mcp-report pre:focus-visible { outline: 2px solid #4b8580; outline-offset: 2px; }
.mcp-register footer { display: flex; align-items: center; justify-content: space-between; gap: 12px; margin-top: 12px; color: var(--mcp-muted); font-size: 10px; line-height: 1.5; }
.mcp-empty, .mcp-history-empty { display: flex; flex-direction: column; align-items: center; gap: 9px; padding: 24px 12px; margin: 12px 0; border: 1px dashed #c9d6d9; color: #657b82; text-align: center; font-size: 12px; }
.mcp-empty strong { color: #36565d; font-size: 13px; }
.mcp-empty p { max-width: 530px; margin: 0; line-height: 1.65; }
.mcp-history { margin-top: 18px; }
.mcp-history-list { display: grid; gap: 8px; }
.mcp-history-row { padding: 11px; border: 1px solid #d4dfe0; border-left: 3px solid #66888a; border-radius: 4px; background: #fff; }
.mcp-history-row.state-unknown { border-left-color: #b45d44; background: #fffaf7; }
.mcp-history-title { display: flex; justify-content: space-between; align-items: start; gap: 10px; }
.mcp-history-title > div { min-width: 0; display: grid; gap: 3px; }
.mcp-history-title strong { color: #2b4650; font-size: 12px; overflow-wrap: anywhere; }
.mcp-history-title small { color: #6e8086; font-size: 10px; }
.mcp-job-state { display: inline-flex; align-items: center; flex: 0 0 auto; gap: 5px; color: #46786b; font-size: 10px; }
.mcp-job-state.state-failed, .mcp-job-state.state-unknown { color: #a34e3d; }
.mcp-history-meta { display: flex; flex-wrap: wrap; gap: 5px 12px; margin-top: 8px; color: #6a7e83; font-size: 10px; overflow-wrap: anywhere; }
.mcp-history-error { color: #9a5240; font-size: 11px; line-height: 1.5; overflow-wrap: anywhere; }
.mcp-history-actions { display: flex; flex-wrap: wrap; gap: 7px; margin-top: 9px; }
.mcp-report { margin-top: 12px; border: 1px solid #c8d7d7; border-radius: 4px; overflow: hidden; }
.mcp-report header { display: flex; justify-content: space-between; align-items: center; gap: 8px; padding: 9px 11px; background: #eaf2f1; color: #355b5a; font-size: 12px; }
.mcp-report-meta { display: grid; grid-template-columns: 75px minmax(0, 1fr); gap: 5px 9px; padding: 10px 11px 0; color: #6a7f80; font-size: 10px; }
.mcp-report-meta code { min-width: 0; color: #48656a; overflow-wrap: anywhere; }
.mcp-report pre { max-height: 360px; margin: 0; }
.mcp-original-input { padding: 8px 11px; border-top: 1px solid #dce6e5; color: #536e70; font-size: 10px; }
.mcp-original-input summary { min-height: 26px; padding: 4px 0; cursor: pointer; overflow-wrap: anywhere; }
.mcp-original-input pre { max-height: 220px; margin: 5px 0 0; overflow: auto; padding: 10px; background: #f1f5f5; color: #314e59; white-space: pre-wrap; overflow-wrap: anywhere; font: 11px/1.6 Consolas, monospace; }
.mcp-report > .text-button { margin: 8px; }
.mcp-boundary-note { padding: 0 11px; color: #7c6954; font-size: 10px; line-height: 1.55; }
.mcp-review-warning { display: grid; grid-template-columns: 20px minmax(0, 1fr); gap: 8px; align-items: start; padding: 12px; border: 1px solid #e0c7b8; background: #fff7f1; color: #89533e; font-size: 12px; line-height: 1.65; }
.mcp-review-warning p { margin: 0; }
.mcp-probe-summary { display: grid; gap: 8px; padding: 12px; border: 1px solid #cad9d9; background: #f3f7f6; font-size: 12px; }
.mcp-probe-summary code { overflow-wrap: anywhere; color: #39575e; font: 11px/1.5 Consolas, monospace; }
.mcp-probe-summary span { color: #7d5e48; line-height: 1.55; }
@media (max-width: 620px) {
.mcp-heading { flex-direction: column; gap: 12px; }
.mcp-heading h3 { font-size: 20px; }
.mcp-registration, .mcp-register { padding: 12px; }
.mcp-form-grid { grid-template-columns: minmax(0, 1fr); }
.mcp-full { grid-column: auto; }
.mcp-register footer { flex-direction: column; align-items: stretch; }
.mcp-register footer .button { justify-content: center; }
.mcp-controls > .button { flex: 1 1 auto; justify-content: center; }
.mcp-history-title { flex-direction: column; }
.mcp-history-actions > .button { flex: 1; justify-content: center; }
.mcp-panel .button { min-height: 44px; }
}
@@ -0,0 +1,148 @@
import { useEffect, useRef, useState } from 'react';
import type { FormEvent } from 'react';
import { AlertTriangle, Check, CircleAlert, Fingerprint, LoaderCircle, PlugZap, Plus, Power, RefreshCw, ShieldCheck, Terminal } from 'lucide-react';
import type { McpJob, McpRegistration, Session } from './types';
import { api } from './api';
import { Modal } from './components';
import { McpJobHistory } from './McpJobHistory';
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 Draft = { name: string; executable: string; entry: string; timeoutMs: number };
export function McpPanel({ projectId, session, busy, onSession, onError }: {
projectId: string; session: Session | null; busy: boolean; onSession: (value: Session) => void; onError: (error: unknown) => void;
}) {
const [view, setView] = useState<View | null>(null), [jobs, setJobs] = useState<McpJob[]>([]);
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 });
const [probeTarget, setProbeTarget] = useState<McpRegistration | null>(null);
const [requestError, setRequestError] = useState('');
const generation = useRef(0), revisions = useRef(new Map<string, number>()), mounted = useRef(true);
const url = '/projects/' + projectId + '/mcp';
const busyJobs = jobs.some(job => active.includes(job.status));
const locked = busy || busyJobs || working;
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[]),
]);
if (!mounted.current || current !== generation.current) return;
setView(nextView); setJobs(nextJobs);
setSelectedTools(previous => {
const next = { ...previous };
for (const registration of nextView.registrations) if (revisions.current.get(registration.id) !== registration.configurationRevision) {
next[registration.id] = [...registration.allowedTools]; revisions.current.set(registration.id, registration.configurationRevision);
}
return next;
});
}
useEffect(() => {
const current = ++generation.current; setView(null); setJobs([]); 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));
}).catch(cause => { if (generation.current === current) setError(cause instanceof Error ? cause.message : String(cause)); }); }, 900);
return () => window.clearInterval(timer);
}, [jobs, projectId, session?.id]);
async function perform(action: () => Promise<unknown>, message: string) {
const current = generation.current; setWorking(true); setError(''); setNotice('');
try { await action(); if (current === generation.current) { setNotice(message); await load(current); } }
catch (cause) { if (current === generation.current) setError(cause instanceof Error ? cause.message : String(cause)); }
finally { if (current === generation.current) setWorking(false); }
}
function register(event: FormEvent) {
event.preventDefault();
void perform(async () => {
await api(url, { name: draft.name.trim(), executable: draft.executable.trim(), ...(draft.entry.trim() ? { entry: draft.entry.trim() } : {}), timeoutMs: draft.timeoutMs });
setDraft({ name: '', executable: '', entry: '', timeoutMs: 15000 });
}, '程序已登记并保持停用。请先实际探测,再选择允许的工具。');
}
async function probe() {
if (!probeTarget || !session) return;
const target = probeTarget; setWorking(true); setError(''); setNotice(''); setRequestError('');
try {
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); }
}
async function stop() {
if (!session) return;
await perform(async () => { const updated = await api<Session>('/sessions/' + session.id + '/mcp/stop', {}); onSession(updated); }, 'MCP 操作已停止,已发出的调用若没有结果会保留为待核对。');
}
const saveTools = (registration: McpRegistration) => perform(async () => {
const value = await api<McpRegistration>(url + '/configure', { id: registration.id, configurationRevision: registration.configurationRevision,
enabled: !!selectedTools[registration.id]?.length, allowedTools: selectedTools[registration.id] ?? [] });
revisions.current.set(value.id, -1);
}, selectedTools[registration.id]?.length ? '已保存所选工具并启用。每次调用仍需单独确认。' : '已停用该 MCP。');
const disable = (registration: McpRegistration) => perform(async () => {
await api(url + '/configure', { id: registration.id, configurationRevision: registration.configurationRevision, enabled: false, allowedTools: [] });
revisions.current.set(registration.id, -1);
}, '该 MCP 已停用,后续请求不会再发送它的工具目录。');
return <section className="mcp-panel" aria-label="项目MCP工具管理" aria-busy={working}>
<header className="mcp-heading"><div><span className="mcp-kicker"><PlugZap size={15} />项目能力 / MCP</span><h3>受控连接外部工具</h3><p>登记本地 stdio 程序,读取实际握手与参数契约。每次探测和工具调用都需要确认,启用不代表自动执行。</p></div>
<button type="button" className="button secondary" disabled={working} onClick={() => void perform(() => load(), '项目 MCP 状态已重新核对。')}><RefreshCw size={14} className={working ? 'spin' : ''} />刷新</button></header>
<div className="mcp-status-bar"><span><i className="mcp-light" />{view?.registrations.filter(item => item.enabled && item.status === 'verified').length ?? 0} 项已启用</span><span>{view?.registrations.length ?? 0} 项已登记</span><span>协议 {view?.protocolVersion ?? '2025-03-26'}</span><span><ShieldCheck size={14} />调用逐次审批</span></div>
{error && <p className="mcp-alert" role="alert"><CircleAlert size={16} />{error}</p>}
{notice && <p className="mcp-notice" role="status"><Check size={16} />{notice}</p>}
{busy && <p className="mcp-warning">当前项目正在执行;完成或停止后才能修改 MCP 配置。</p>}
<div className="mcp-boundary"><ShieldCheck size={16} /><span>{view?.boundary ?? '每次操作使用独立所属进程。进程隔离不等于 OS 沙箱,外部服务和程序可能拥有自己的网络或副作用。'}</span></div>
{view?.registrations.length ? <div className="mcp-registration-list">{view.registrations.map(registration => {
const chosen = selectedTools[registration.id] ?? registration.allowedTools;
return <article className={'mcp-registration status-' + registration.status} key={registration.id}>
<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>
{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.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,
[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>
</label>)}
{!registration.tools.length && <p className="mcp-empty">实际服务没有声明可发现工具。</p>}
</div>}
<div className="mcp-controls"><button type="button" className="button secondary" disabled={locked || !session || registration.status === 'changed'} onClick={() => { setRequestError(''); setProbeTarget(registration); }}><PlugZap size={14} />实际探测</button>
{registration.contract && <button type="button" className={registration.enabled ? 'button secondary' : 'button primary'} disabled={locked || registration.status !== 'verified' || !!selectedTools[registration.id]?.length && !registration.contract} onClick={() => void saveTools(registration)}><Power size={14} />{chosen.length ? '保存并启用所选工具' : '停用 MCP'}</button>}
{registration.enabled && <button type="button" className="button secondary" disabled={locked} onClick={() => void disable(registration)}><Power size={14} />立即停用</button>}
{busyJobs && session && <button type="button" className="button danger" disabled={working} onClick={() => void stop()}><AlertTriangle size={14} />停止当前 MCP 操作</button>}</div>
</article>;
})}</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-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 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 && <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>}
<span>程序会以当前 Windows 用户权限运行;独立进程不等于 OS 沙箱。探测期间不会继承工作台模型凭据。</span></div>
{requestError && <p className="mcp-alert" role="alert"><CircleAlert size={15} />{requestError}</p>}
<div className="modal-actions"><button type="button" className="button secondary" disabled={working} onClick={() => setProbeTarget(null)}>取消</button><button type="button" className="button primary" disabled={working || busy} onClick={() => void probe()}>{working ? <LoaderCircle size={14} className="spin" /> : <PlugZap size={14} />}确认启动并探测</button></div>
</Modal>}
</section>;
}
@@ -0,0 +1,18 @@
import { useState } from 'react';
import type { Config } from './types';
export function ModelBudgetSettings({ value, disabled, onSave }: { value: Config; disabled: boolean; onSave: (input: Partial<Config>) => void }) {
const [draft, setDraft] = useState(() => ({ contextLimit: value.contextLimit, maxOutputTokens: value.maxOutputTokens,
maxSteps: value.maxSteps, maxRunDurationMs: value.maxRunDurationMs, maxRunTokens: value.maxRunTokens, maxTaskTokens: value.maxTaskTokens }));
const fields = [
['contextLimit', '上下文预算', 1000, 200000], ['maxOutputTokens', '输出上限', 256, 16000],
['maxSteps', '最大工具轮次', 1, 30], ['maxRunDurationMs', '运行时间(秒)', 1, 3600],
['maxRunTokens', '单次运行 tokens', 1000, 2000000], ['maxTaskTokens', '任务累计 tokens', 1000, 10000000],
] as const;
return <form className="mc-editor" aria-label="运行预算设置" onSubmit={event => { event.preventDefault(); onSave(draft); }}>
<h3>运行预算</h3><p>保存仅调整后续运行的预算,保留已选连接或模型池。实际上下文与输出上限还受所选连接限制;旧运行的预算与用量保持原记录。</p>
<div className="mc-form-grid">{fields.map(([key, label, min, max]) => <label key={key}>{label}<input aria-label={label} type="number" required step={1} min={min} max={max} disabled={disabled}
value={key === 'maxRunDurationMs' ? draft[key] / 1000 : draft[key]} onChange={event => setDraft(previous => ({ ...previous, [key]: Number(event.target.value) * (key === 'maxRunDurationMs' ? 1000 : 1) }))} /></label>)}</div>
<div className="mc-actions"><button className="button primary" type="submit" disabled={disabled}>保存运行预算</button></div>
</form>;
}
@@ -0,0 +1,27 @@
.modal:has(.model-center){width:min(1260px,calc(100vw - 48px));max-width:none;height:min(900px,calc(100dvh - 48px));display:flex;flex-direction:column;padding:0;overflow:hidden}.modal:has(.model-center)>.modal-heading{padding:20px 28px 16px;margin:0;border-bottom:1px solid #cbd5df;flex-shrink:0;background:#fff}.modal:has(.model-center)>.modal-heading h2{color:#16324c;font-size:20px;font-weight:700}.modal:has(.model-center)>.modal-heading p{color:#53647c;font-size:12px;margin-top:6px}.modal:has(.model-center)>.modal-heading>.icon-button{margin:0;min-width:36px;min-height:36px;color:#53647c}
.model-center{display:flex;flex-direction:column;width:100%;min-width:0;min-height:0;color:#15283f;background:#f1f4f7;font-size:13px}.mc-overview{padding:25px 28px;display:flex;align-items:center;gap:25px;background:#e7edf2;border-bottom:1px solid #cbd5df;flex-shrink:0}.mc-eyebrow{font-family:Bahnschrift,sans-serif;letter-spacing:.13em;font-size:10px;font-weight:650;color:#526782}.mc-overview h2{font-size:25px;font-weight:650;letter-spacing:-.04em;margin:8px 0;line-height:1.3}.mc-overview p,.mc-section-title p{color:#52647a;font-size:12px;line-height:1.7}.mc-current{margin-left:auto;display:flex;gap:12px;align-items:center;padding:14px 18px;background:#fff;border:1px solid #c2d0dd;border-radius:8px;min-width:220px}.mc-current>span{font-size:11px;color:#62728a}.mc-current strong{display:block;font-size:14px;color:#15283f;margin-top:3px;overflow-wrap:anywhere}.mc-current .mc-count{margin-left:auto;white-space:nowrap}
.mc-tabs{display:flex;gap:4px;padding:0 24px;flex-shrink:0;border-bottom:1px solid #cbd5df;background:white;overflow-x:auto}.mc-tabs button{display:flex;align-items:center;gap:8px;white-space:nowrap;min-height:49px;padding:12px 15px;border-bottom:3px solid transparent;color:#53647c;font-weight:600}.mc-tabs button[aria-current]{color:#215b96;border-bottom-color:#2560a3}.mc-tabs button:hover{background:#edf2f7}.mc-tabs .mc-refresh{margin-left:auto;padding:12px}.mc-content{padding:24px 28px 32px;overflow:auto;min-height:0;flex:1;scrollbar-gutter:stable}.mc-section-title{display:flex;gap:20px;align-items:center;justify-content:space-between;margin-bottom:20px}.mc-section-title h3{font-size:17px;margin-bottom:5px}.mc-section-title>.button{flex-shrink:0}.mc-notice{padding:12px 28px;line-height:1.7;border-bottom:1px solid #e0b777;color:#734c1c;background:#fff5df;overflow-wrap:anywhere;flex-shrink:0}
.mc-connections{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:16px}.mc-connection{background:white;border:1px solid #c7d3de;border-radius:9px;padding:19px;min-width:0;box-shadow:0 2px 5px #15283f06}.mc-card-heading{display:flex;gap:12px;align-items:center;margin-bottom:18px}.mc-card-heading>div{min-width:0;flex:1}.mc-card-heading h4{font-size:15px;overflow-wrap:anywhere}.mc-card-heading>div>span{font-size:11px;color:#62728a;display:block;margin-top:4px}.mc-service-icon{display:grid;place-items:center;flex-shrink:0;border:1px solid #b9c9d8;border-radius:7px;width:41px;height:41px;color:#2560a3;background:#edf3fa}.mc-state{display:inline-flex;padding:4px 7px;border-radius:4px;font-size:11px;font-weight:600;background:#e9eef3;color:#4a5d74;white-space:nowrap;border:1px solid #d1dbe4}.mc-state-completed,.mc-state-passed{color:#216d5f;background:#e6f3ee;border-color:#b9d9cb}.mc-state-configured{color:#255d91;background:#edf4fd;border-color:#bcd0e7}.mc-state-failed,.mc-state-needs_attention{color:#a7353e;background:#fff0f0;border-color:#e8bac0}.mc-state-needs_key,.mc-state-cooling,.mc-state-unknown,.mc-state-attention{color:#8b5c12;background:#fff4d9;border-color:#e6d09d}.mc-connection dl{display:grid;grid-template-columns:86px minmax(0,1fr);gap:10px 7px;margin:0}.mc-connection dt{color:#67788d;font-size:11px}.mc-connection dd{margin:0;overflow-wrap:anywhere;font-size:12px;line-height:1.5;font-family:"Cascadia Code",Consolas,"Microsoft YaHei",monospace}.mc-capabilities{display:flex;flex-wrap:wrap;gap:6px;margin-top:17px}.mc-capabilities span{padding:4px 6px;color:#61738b;border:1px solid #d7e0e9;border-radius:4px;font-size:10px}.mc-connection footer{border-top:1px solid #e0e6ec;padding-top:14px;margin-top:15px;display:flex;align-items:center;gap:8px;flex-wrap:wrap}.mc-icon-action{display:flex;gap:5px;align-items:center;font-size:11px;padding:8px}.mc-probe{width:100%;text-align:left;color:#476180;font-size:11px;padding:7px 0 0}.mc-disabled{background:#f7f9fb}.mc-card-warning{font-size:12px;line-height:1.7;overflow-wrap:anywhere;color:#8b4a39;margin-top:12px}
.mc-editor{padding:22px;border:1px solid #b2c6da;border-top:3px solid #2560a3;border-radius:7px;background:white;margin:22px 0 4px}.mc-editor h3{font-size:16px;margin-bottom:18px}.mc-form-grid{display:grid;grid-template-columns:1fr 1fr;gap:17px}.mc-form-grid label{display:flex;flex-direction:column;gap:8px;font-size:12px;color:#4b5f77}.mc-form-grid input,.mc-form-grid select{width:100%;min-width:0;min-height:40px;background:white;border:1px solid #b9c8d6;border-radius:5px;padding:9px 11px}.mc-form-grid .mc-full{grid-column:1/-1}.mc-actions{display:flex;gap:9px;justify-content:flex-end;margin-top:18px;flex-wrap:wrap}.mc-checkbox{display:flex!important;flex-direction:row!important;align-items:center;gap:9px;font-size:12px;line-height:1.7;margin:14px 0;color:#51647c}.mc-checkbox input{width:16px!important;min-height:16px!important;height:16px;flex-shrink:0;accent-color:#2560a3}.mc-help{display:flex;gap:7px;align-items:flex-start;color:#67788d;font-size:11px;line-height:1.8;margin:15px 0;overflow-wrap:anywhere}.mc-empty{padding:38px 20px;background:#fff;border:1px dashed #b5c6d7;border-radius:7px;color:#61738a;font-size:13px;line-height:1.8;margin:18px 0}
.mc-pool{display:flex;gap:18px;align-items:flex-start;background:white;border:1px solid #c7d3de;border-radius:8px;padding:21px;margin-bottom:14px}.mc-pool>svg{color:#2560a3;margin-top:2px}.mc-pool>div:first-of-type{flex:1;min-width:0}.mc-pool h4{font-size:15px}.mc-pool p{font-size:12px;color:#64748b;line-height:1.8;margin-top:6px}.mc-pool .mc-actions{margin:0}.mc-members{display:flex;gap:6px;flex-wrap:wrap;margin-top:13px}.mc-members span{font-size:11px;color:#4b607d;padding:4px 8px;background:#eff3f8;border-radius:4px}.mc-editor fieldset{border:1px solid #d0dae5;border-radius:5px;margin:16px 0 0;padding:5px 14px}.mc-editor legend{font-size:12px;color:#566a83;padding:0 6px}.mc-member-choice{display:flex;align-items:center;gap:12px;padding:12px 0;border-bottom:1px solid #e2e8ef}.mc-member-choice:last-child{border:0}.mc-member-choice>span{flex:1;font-size:13px}.mc-member-choice small{display:block;margin-top:3px;font-size:11px;color:#6c7e94}.mc-member-choice>input[type=number]{width:60px;padding:7px;border:1px solid #c6d2df;border-radius:4px}
.mc-attempts article{padding:17px 18px;background:white;border:1px solid #cbd6e2;border-left:3px solid #748eac;margin-bottom:10px;border-radius:4px}.mc-attempts article>div{display:flex;align-items:center;gap:12px;flex-wrap:wrap}.mc-attempts strong{font-size:13px}.mc-attempts time{font-size:11px;color:#637891;margin-left:auto}.mc-attempts p{font-size:12px;color:#556b87;line-height:1.7;margin-top:9px}.mc-attempts code{font-size:10px;color:#7a8ca0;display:block;margin-top:7px;overflow-wrap:anywhere}.mc-checks{display:grid;gap:11px}.mc-checks article{display:flex;align-items:flex-start;gap:14px;border:1px solid #cbd6e2;border-radius:6px;padding:18px;background:white}.mc-checks h4{font-size:14px}.mc-checks p{font-size:12px;color:#5d7088;line-height:1.8;margin-top:5px}.mc-import-source{padding:17px;background:white;border:1px solid #cbd6e2;margin-bottom:10px;display:flex;align-items:center;gap:15px;flex-wrap:wrap;border-radius:6px}.mc-import-source code{flex:1;overflow-wrap:anywhere;font-size:11px;min-width:140px}.mc-import-source>span,.mc-import-source p{font-size:12px;color:#64778e}
@media(max-width:940px){.mc-connections{grid-template-columns:1fr}.mc-overview h2{font-size:22px}.mc-pool{flex-wrap:wrap}.mc-pool .mc-actions{width:100%}}
@media(max-width:620px){.modal:has(.model-center){width:100vw;height:100dvh;max-height:100dvh;border-radius:0}.modal:has(.model-center)>.modal-heading{padding:17px 16px}.mc-overview{padding:17px 16px;display:block}.mc-overview h2{font-size:21px}.mc-current{padding:10px 12px;margin:13px 0 0;min-width:0}.mc-current strong{font-size:13px}.mc-tabs{padding:0 8px}.mc-tabs button{padding:12px 10px;min-height:48px;font-size:12px}.mc-content{padding:18px 15px 28px}.mc-section-title{gap:12px;align-items:flex-start;flex-direction:column}.mc-form-grid{grid-template-columns:1fr}.mc-form-grid .mc-full{grid-column:auto}.mc-editor{padding:18px 14px}.mc-connection{padding:16px 13px}.mc-card-heading{gap:9px}.mc-service-icon{width:34px;height:34px}.mc-card-heading h4{font-size:14px}.mc-connection dl{grid-template-columns:72px minmax(0,1fr)}.mc-notice{padding:12px 16px}.model-center button{min-height:44px}.mc-state{font-size:10px}.mc-attempts time{margin-left:0}.mc-import-source{gap:9px}.mc-member-choice input[type=number]{min-height:44px}.mc-form-grid input,.mc-form-grid select{min-height:44px}}
@media(max-width:620px){.modal:has(.model-center)>.modal-heading>.icon-button{min-width:44px;min-height:44px}}
.mc-checks article>div{min-width:0;flex:1}.mc-checks p,.mc-operations-pages p{overflow-wrap:anywhere}.mc-operations-pages .mc-row-actions{display:flex;gap:8px;flex-wrap:wrap;margin:12px 0}.mc-operations-pages{border-top:1px solid #cbd6e2;margin-top:18px;padding-top:12px}.mc-operations-pages .error{color:#a23731}
.mc-probe-scope { display: flex; align-items: center; gap: 6px; font-size: 12px; color: var(--text-muted, #53616b); }
.mc-probe-scope select { min-height: 36px; max-width: 136px; padding: 4px 8px; color: inherit; border: 1px solid #c7d2d9; border-radius: 6px; background: white; }
.mc-capabilities [data-capability="unsupported"] { color: #903c35; background: #fbefed; }
.mc-capabilities [data-capability="verified"] { color: #285c47; background: #eaf5ed; }
.mc-route-rejections { margin: 8px 0 0; color: #7c4c22; font-size: 12px; overflow-wrap: anywhere; }
.mc-stream-receipt { border-top: 1px solid var(--border); margin-top: 10px; padding-top: 8px; }
.mc-stream-receipt code { display: block; overflow-wrap: anywhere; font-size: 11px; line-height: 1.7; }
.mc-stream-receipt .button { margin-top: 8px; }
.mc-editor > p { color: #475b73; font-size: 13px; line-height: 1.8; margin: 12px 0; }
.mc-form-grid label > small { color: #475b73; font-size: 12px; line-height: 1.7; font-weight: 400; }
.mc-native>label{display:flex;flex-direction:column;gap:8px;font-size:12px;color:#40576e;margin:14px 0}.mc-native select,.mc-native textarea{width:100%;min-width:0;padding:10px;border:1px solid #a9bdcf;border-radius:5px;background:white;font-size:12px;line-height:1.75}.mc-native textarea{resize:vertical;font-family:Consolas,"Microsoft YaHei",monospace}.mc-native select:focus-visible,.mc-native textarea:focus-visible{outline:2px solid #2560a3;outline-offset:2px}
.mc-route-control{margin-bottom:24px;padding:18px 20px;background:#fff;border:1px solid #b8cadb;border-left:3px solid #2560a3;border-radius:6px;min-width:0}.mc-route-heading{display:flex;align-items:center;justify-content:space-between;gap:16px;margin-bottom:14px}.mc-route-heading h3{font-size:15px;margin-bottom:5px}.mc-route-heading p,.mc-route-detail{font-size:12px;color:#4b6078;line-height:1.7;overflow-wrap:anywhere}.mc-route-heading>.button{flex-shrink:0}.mc-route-select{display:flex;gap:12px;align-items:center;font-size:12px;color:#425974}.mc-route-select select{min-width:0;flex:1;width:100%;min-height:42px;border:1px solid #a7bbcf;border-radius:5px;background:#fff;padding:10px;color:#15283f;font-size:13px}.mc-route-detail{margin-top:9px}.mc-run-model{display:flex;flex-wrap:wrap;gap:6px 12px;border-top:1px solid #dce4eb;margin-top:13px;padding-top:12px;font-size:12px;line-height:1.7;overflow-wrap:anywhere}.mc-run-model strong{color:#344c67}.mc-run-model span{color:#405670}.mc-run-model small{width:100%;color:#566b81;font-size:11px}.mc-route-select select:focus-visible{outline:2px solid #2560a3;outline-offset:2px}
@media(max-width:620px){.mc-route-control{padding:14px}.mc-route-heading{align-items:flex-start;gap:10px}.mc-route-heading p{font-size:11px}.mc-route-heading>.button{padding:8px;font-size:11px}.mc-route-select{align-items:stretch;flex-direction:column;gap:7px}.mc-route-select select{font-size:12px}.mc-run-model{display:block}.mc-run-model strong,.mc-run-model span,.mc-run-model small{display:block}.mc-run-model span{margin-top:4px}}
.mc-request-url { overflow-wrap: anywhere; font-family: var(--font-mono, monospace); font-size: 12px; line-height: 1.6; }
@@ -0,0 +1,199 @@
import { useEffect, useRef, useState } from 'react';
import { Activity, Check, CircleHelp, KeyRound, Layers3, Plus, Power, RefreshCw, Route, Server, Settings2 } from 'lucide-react';
import { api, downloadArtifact } from './api';
import type { Config, ModelSelection, ModelSnapshot, RuntimeFailure } from './types';
import './ModelCenter.css';
import { ModelIdentityDetails } from './ModelIdentityDetails';
import type { ModelIdentity } from '../shared/contracts/model-identity.mjs';
import { ModelWaitSettings, type WaitSettings } from './ModelWaitSettings';
import { NativeParameters } from './NativeParameters';
import { ModelErrorDetails } from './ModelErrorDetails';
import { ModelBudgetSettings } from './ModelBudgetSettings';
import { modelRequestUrl, protocolLabel } from '../shared/contracts/model-endpoint.mjs';
import { ModelNetworkDiagnostics } from './ModelNetworkDiagnostics';
const previewUrl = (value: { protocol: string; baseUrl: string }) => { try { return modelRequestUrl(value); } catch { return '请填写有效的接口根地址'; } };
type Connection = { id: string; name: string; brand: string; protocol: string; messagesAuth?: string; baseUrl: string; model: string; enabled: boolean; revision: number; hasKey: boolean;
requiresKey: boolean; modelIdentityPolicy?: string; modelIdentityAliases?: string[]; modelIdentityAliasSource?: string; nativeParameters?: Record<string, unknown>; outputTokenField?: string; streaming?: boolean; capabilityDeclarations?: Record<string, string>; capabilities?: Record<string, string>; capabilityEvidence?: { checkedAt: string }; contextLimit: number; maxOutputTokens: number; concurrency: number; status: string; activeRequests: number; savedCredential?: { status: string }; health: { state: string; reason?: string; cooldownUntil?: number } };
type Pool = { id?: string; name: string; members: { connectionId: string; weight: number }[]; strategy: string; sticky: boolean; maxAttempts: number; revision?: number; queueTimeoutMs: number };
type Attempt = { modelIdentity?: ModelIdentity; diagnostic?: RuntimeFailure; requestUrl?: string; upstreamResponse?: { requestId?: string | null; requestUrl?: string; responseUrl?: string | null; redirectMode?: string }; id: string; connectionId: string; poolId: string | null; model: string; protocol?: string; streaming?: boolean; rejections?: { connectionName: string; capability: string; reason: string }[]; status: string; startedAt: string; ordinal: number; usageStatus: string; reason?: string; taskId?: string; sessionId?: string; runId: string; requestArtifactId?: string; responseArtifactId?: string; responseSha256?: string; responseRedacted?: boolean; stream?: { bytes: number; capturedBytes?: number; frames: number; sha256: string; terminal: boolean }; usage?: { prompt_tokens?: number; completion_tokens?: number } };
type ImportRecord = { id: string; source: string; path: string; enabled: boolean; lastCheckedAt?: string; lastSyncedAt?: string; lastError?: string; lastResult?: { imported?: number; conflicts?: string[] } };
type Center = { revision: number; selected: { type: string; id: string }; waitSettings: WaitSettings; connections: Connection[]; pools: Pool[]; imports: ImportRecord[]; attempts: Attempt[]; waiting: number };
type Operations = { checkedAt: string; version: string; scope: string; activeTasks: number; queue: number; checks: { id: string; title: string; status: string; detail: string }[];
artifacts?: { offset: number; checked: number; total: number; remaining: number; olderOffset: number | null; newerOffset: number | null; results: { id: string; passed: boolean; error?: string }[] } };
type SavedCredential = { id: string; name: string; revision: number; status: string; enabled?: boolean; savedAt?: string; message: string };
type CredentialView = { supported: boolean; unavailable: boolean; connections: SavedCredential[]; scope: string };
const savedStates: Record<string, string> = { not_saved: '仅本次内存', saved: '本机加密保存', disabled: '关闭自动加载', source_changed: '配置已变化', decrypt_failed: '无法解密', user_mismatch: '用户不匹配', directory_mismatch: '目录不匹配', unavailable: '保存登记不可用' };
const states: Record<string, string> = { configured: '已配置', needs_key: '待填凭据', disabled: '已停用', needs_attention: '需要处理', cooling: '冷却中', completed: '收到响应', failed: '失败', running: '请求中', unknown: '结果待核对', interrupted: '已中断', rejected: '能力不匹配', passed: '通过', attention: '待配置' };
const initial = { modelIdentityAliasesText: '', modelIdentityPolicy: 'record', modelIdentityAliases: [] as string[], modelIdentityAliasSource: '', name: '', brand: '自定义', protocol: 'chat-completions', streaming: false, capabilityDeclarations: { text: 'supported', tools: 'supported', streaming: 'unknown', vision: 'unknown', audio: 'unknown' } as Record<string, string>, model: '', baseUrl: 'https://api.openai.com/v1', requiresKey: true, enabled: true, contextLimit: 16000, maxOutputTokens: 2048, concurrency: 1 };
const capabilityLabels: Record<string, string> = { text: '文本', tools: '工具', streaming: '流式', vision: '视觉', audio: '语音' };
const capabilityStates: Record<string, string> = { protocol_declared: '声明支持', verified: '已验证', unknown: '待验证', unsupported: '不支持' };
const emptyPool: Pool = { name: '', members: [], strategy: 'round-robin', sticky: true, maxAttempts: 3, queueTimeoutMs: 15000 };
export function ModelCenter({ onConfig, onLegacy, busy, runModel }: { onConfig: (value: Config, selection?: ModelSelection) => void; onLegacy: () => void; busy: boolean; runModel?: ModelSnapshot }) {
const [view, setView] = useState<Center | null>(null);
const [runtimeConfig, setRuntimeConfig] = useState<Config | null>(null);
const [tab, setTab] = useState('connections');
const [draft, setDraft] = useState<typeof initial & { id?: string; revision?: number; messagesAuth?: string; nativeParameters?: Record<string, unknown>; outputTokenField?: string }>(initial);
const [editing, setEditing] = useState(false), [key, setKey] = useState('');
const [nativeTarget, setNativeTarget] = useState<Connection | null>(null);
const [persistKey, setPersistKey] = useState(false), [persistImports, setPersistImports] = useState(false);
const [credentialView, setCredentialView] = useState<CredentialView | null>(null), [credentialKey, setCredentialKey] = useState(''), [credentialTarget, setCredentialTarget] = useState('');
const [pool, setPool] = useState<Pool>(emptyPool), [poolEditing, setPoolEditing] = useState(false);
const [working, setWorking] = useState(false), [notice, setNotice] = useState('');
const [noticeFailure, setNoticeFailure] = useState<RuntimeFailure | null>(null);
const [probeScopes, setProbeScopes] = useState<Record<string, string>>({});
const [networkTarget, setNetworkTarget] = useState('');
const [operations, setOperations] = useState<Operations | null>(null), [autoInspect, setAutoInspect] = useState(false);
const [importPath, setImportPath] = useState(''), [importSource, setImportSource] = useState('ccswitch');
const [preview, setPreview] = useState<{ id: string; entries: { id: string; name: string; model: string; baseUrl: string; hasKey: boolean }[]; notices: string[] } | null>(null);
const [discovery, setDiscovery] = useState<{ source: string; path: string; available: boolean; supported: boolean; detail?: string }[]>([]);
const alive = useRef(true), generation = useRef(0);
const tabsRef = useRef<HTMLElement>(null);
async function refresh() {
const marker = ++generation.current;
const [result, selection] = await Promise.all([api<Center>('/model-center'), api<{ config: Config; modelSelection: ModelSelection }>('/model-center/selection')]);
if (alive.current && marker === generation.current) { setView(result); setRuntimeConfig(selection.config); onConfig(selection.config, selection.modelSelection); }
}
function addConnection() { setTab('connections'); setDraft(initial); setKey(''); setPersistKey(false); setEditing(true); }
async function selectRoute(value: string) {
await act(async () => {
if (value === 'demo') await api('/model-center/mode', { mode: 'demo' });
else { const [type, id] = value.split(':'); await api('/model-center/select', { type, id }); }
if (alive.current) setNotice(value === 'demo' ? '已切换到离线演示;已保存连接仍保留。' : '默认模型已更新;后续运行使用此选择,旧运行保留原记录。');
});
}
async function act(action: () => Promise<void>) {
setWorking(true); setNotice(''); setNoticeFailure(null);
try { await action(); if (alive.current) { await refresh(); if (credentialView) await refreshCredentials(); } }
catch (cause) { if (alive.current) { setNotice(cause instanceof Error ? cause.message : '操作未完成,请刷新核对。');
if (cause && typeof cause === 'object' && 'diagnostic' in cause && cause.diagnostic) setNoticeFailure(cause.diagnostic as RuntimeFailure); } }
finally { if (alive.current) setWorking(false); }
}
async function inspect(offset?: number) { const value = await api<Operations>('/operations' + (offset === undefined ? '' : '?artifactOffset=' + offset)); if (alive.current) setOperations(value); }
async function refreshCredentials() { const value = await api<CredentialView>('/model-center/credentials'); if (alive.current) setCredentialView(value); }
useEffect(() => { alive.current = true; void refresh().catch(error => { if (alive.current) setNotice(error.message); }); return () => { alive.current = false; generation.current++; }; }, []);
useEffect(() => { if (!autoInspect || tab !== 'operations') return; const timer = window.setInterval(() => { void inspect().catch(error => { if (alive.current) setNotice(error.message); }); }, 30000); return () => window.clearInterval(timer); }, [autoInspect, tab]);
useEffect(() => { setCredentialKey(''); if (tab === 'credentials') void refreshCredentials().catch(error => { if (alive.current) setNotice(error.message); }); }, [tab]);
useEffect(() => { if (!editing) return; const frame = requestAnimationFrame(() => document.querySelector('.mc-editor[aria-label="编辑模型连接"]')?.scrollIntoView({ block: 'start' })); return () => cancelAnimationFrame(frame); }, [editing]);
useEffect(() => {
const ensureVisible = () => { const nav = tabsRef.current, button = nav?.querySelector<HTMLButtonElement>('button[aria-current]'); if (!nav || !button) return;
const area = nav.getBoundingClientRect(), target = button.getBoundingClientRect(), start = target.left - area.left;
if (start < 0) nav.scrollLeft += start - 12; else if (start + target.width > nav.clientWidth) nav.scrollLeft += start + target.width - nav.clientWidth + 12;
};
const frame = requestAnimationFrame(ensureVisible); window.addEventListener('resize', ensureVisible);
return () => { cancelAnimationFrame(frame); window.removeEventListener('resize', ensureVisible); };
}, [tab]);
const selected = view?.selected;
const selectionName = selected?.type === 'pool' ? view?.pools.find(value => value.id === selected.id)?.name : view?.connections.find(value => value.id === selected?.id)?.name;
const locked = working || busy;
return <section className="model-center" aria-label="模型控制台" aria-busy={working}>
<div className="mc-overview"><div><span className="mc-eyebrow">MODEL CONTROL</span><h2>选择模型,继续开发。</h2><p>连接、模型池和实际请求使用同一个入口。</p></div><div className="mc-current"><Route size={18} /><span>新任务默认<strong>{runtimeConfig?.mode === 'demo' ? '离线演示' : selectionName || '正在读取'}</strong></span><span className="mc-count">{view?.waiting ?? 0} 等待</span></div></div>
<nav ref={tabsRef} className="mc-tabs" aria-label="模型中心分类">{[['connections', '模型连接', Server], ['network', '连接诊断', Activity], ['pools', '模型池', Layers3], ['budgets', '运行预算', Settings2], ['waits', '等待时限', Settings2], ['attempts', '请求账本', Route], ['imports', '配置导入', Settings2], ['credentials', '凭据保存', KeyRound], ['operations', '运行巡检', Activity]].map(([id, title, Icon]) => {
const Symbol = Icon as typeof Server; return <button key={id as string} type="button" aria-current={tab === id ? 'page' : undefined} onClick={() => { setTab(id as string); setNotice(''); }}><Symbol size={16} />{title as string}</button>;
})}<button className="mc-refresh" type="button" disabled={working} onClick={() => void act(refresh)} aria-label="刷新模型中心"><RefreshCw size={16} /></button></nav>
{notice && <div className="mc-notice" role="status">{notice}{noticeFailure && <ModelErrorDetails failure={noticeFailure} />}</div>}
{busy && <p className="mc-notice">有任务正在执行;连接可停用,其他配置请在任务结束后修改。</p>}
{!view ? <p className="mc-empty">正在读取实际连接状态…</p> : <div className="mc-content">
<section className="mc-route-control" aria-label="默认模型选择">
<div className="mc-route-heading"><div><h3>新任务默认模型</h3><p>选择已保存的连接,或使用模型池调度。切换本身不请求模型。</p></div><button className="button secondary" disabled={locked} onClick={addConnection}><Plus size={15} />添加模型</button></div>
<label className="mc-route-select">当前选择<select aria-label="新任务默认模型" disabled={locked || !runtimeConfig} value={runtimeConfig?.mode === 'demo' ? 'demo' : selected?.type + ':' + selected?.id} onChange={event => void selectRoute(event.target.value)}>
<option value="demo">离线演示 · 固定脚本</option>
<optgroup label="模型连接">{view.connections.map(connection => <option key={connection.id} value={(connection.id === 'legacy-default' ? 'legacy' : 'connection') + ':' + connection.id} disabled={!connection.enabled || connection.requiresKey && !connection.hasKey}>{connection.name} · {connection.model || '尚未填写型号'}{connection.status !== 'configured' ? ' · ' + states[connection.status] : ''}</option>)}</optgroup>
{!!view.pools.length && <optgroup label="模型池">{view.pools.map(pool => <option key={pool.id} value={'pool:' + pool.id}>{pool.name} · {pool.members.length} 个连接</option>)}</optgroup>}
</select></label>
<div className="mc-route-detail">{runtimeConfig?.mode === 'demo' ? '离线演示使用固定脚本,不调用大模型。' : selected?.type === 'pool' ? '模型池按成员配置调度;每次实际连接和返回型号保存在请求账本。' : (() => { const connection = view.connections.find(c => c.id === selected?.id); return connection ? `${protocolLabel(connection.protocol)} · ${previewUrl(connection)} · 请求 ${connection.model || '未配置'}` : '请选择可用连接。'; })()}</div>
{runModel && <div className="mc-run-model"><strong>当前会话最近运行</strong><span>{runModel.mode === 'demo' ? '离线演示' : runModel.routing?.members?.length ? runModel.routing.members.map(member => member.name + ' · ' + member.model).join(';') : runModel.model}</span><small>这是该次运行封存的请求配置;实际返回型号请看请求账本。更改默认选择不会改写旧记录。</small></div>}
</section>
{tab === 'budgets' && runtimeConfig && <ModelBudgetSettings key={JSON.stringify(runtimeConfig)} value={runtimeConfig} disabled={locked} onSave={input => void act(async () => { await api('/model-center/runtime-budgets', input); if (alive.current) setNotice('运行预算已保存,当前模型选择保持。'); })} />}
{tab === 'waits' && <ModelWaitSettings key={JSON.stringify(view.waitSettings)} value={view.waitSettings} disabled={locked} onSave={value => void act(async () => {
const result = await api<{ config: Config }>('/model-center/wait-settings', value);
if (alive.current) { onConfig(result.config); setNotice('等待时限已保存,从下一次运行生效。当前模型路由保持。'); }
})} />}
{tab === 'connections' && <>
<div className="mc-section-title"><div><h3>模型连接</h3><p>保存多条连接后可在上方切换;添加连接不会替换当前模型。凭据可选择本机加密保存。</p></div><button className="button primary" disabled={locked} onClick={addConnection}><Plus size={16} />添加连接</button></div>
<div className="mc-connections">{view.connections.map(value => <article className={'mc-connection ' + (!value.enabled ? 'mc-disabled' : '')} key={value.id}>
<div className="mc-card-heading"><span className="mc-service-icon"><Server size={20} /></span><div><h4>{value.name}</h4><span>{value.brand} · {protocolLabel(value.protocol)}{value.streaming ? ' · 流式开启' : ''}</span></div><span className={'mc-state mc-state-' + value.status}>{states[value.status]}</span></div>
<dl><dt>模型</dt><dd>{value.model || '尚未填写'}</dd><dt>请求地址</dt><dd>{previewUrl(value)}</dd>{value.protocol === 'anthropic-messages' && <><dt>鉴权</dt><dd>{value.messagesAuth === 'bearer' ? 'Bearer' : 'x-api-key'} · anthropic-version 2023-06-01</dd></>}<dt>凭据</dt><dd>{value.hasKey ? value.savedCredential?.status === 'saved' ? '已设置,可从本机加密保存加载' : '已设置,重启需重新填写' : value.requiresKey ? '尚未填写' : '此服务可不填'}</dd><dt>请求 / 容量</dt><dd>{value.activeRequests} 在途 · 并发 {value.concurrency} · 上下文 {value.contextLimit.toLocaleString()}</dd></dl>
<div className="mc-capabilities">{Object.entries(capabilityLabels).map(([key, title]) => <span key={key} data-capability={value.capabilities?.[key] ?? 'unknown'}>{title}:{capabilityStates[value.capabilities?.[key] ?? 'unknown']}</span>)}</div>
{value.health.reason && <p className="mc-card-warning">{value.health.reason}{!!value.health.cooldownUntil && value.health.cooldownUntil > Date.now() && ' · 冷却至 ' + new Date(value.health.cooldownUntil).toLocaleTimeString()}</p>}
<footer><button className="button secondary" disabled={locked || !value.enabled} onClick={() => void act(async () => { const result = await api<{ config: Config }>('/model-center/select', { type: value.id === 'legacy-default' ? 'legacy' : 'connection', id: value.id }); onConfig(result.config, { type: value.id === 'legacy-default' ? 'legacy' : 'connection', id: value.id, name: value.name }); })}>{selected?.id === value.id ? <Check size={14} /> : <Route size={14} />}{selected?.id === value.id ? '当前使用' : '用于新任务'}</button>
<button className="button secondary" disabled={locked} onClick={() => { if (value.id === 'legacy-default') { onLegacy(); return; } setDraft({ ...initial, ...value, modelIdentityAliasesText: (value.modelIdentityAliases ?? []).join(', '), streaming: value.streaming === true, capabilityDeclarations: { ...initial.capabilityDeclarations, ...value.capabilityDeclarations } }); setKey(''); setPersistKey(false); setEditing(true); }}>编辑</button>
<button className="button secondary" onClick={() => { setNetworkTarget(value.id); setTab('network'); }}>连接诊断</button>
{value.id !== 'legacy-default' && <button className="mc-icon-action" aria-label={(value.enabled ? '停用' : '启用') + value.name} disabled={working} onClick={() => void act(async () => { await api('/model-center/toggle', { id: value.id, enabled: !value.enabled }); })}><Power size={15} />{value.enabled ? '停用' : '启用'}</button>}
<label className="mc-probe-scope">检测范围<select aria-label={value.name + '检测范围'} value={probeScopes[value.id] ?? 'text'} disabled={locked} onChange={event => setProbeScopes({ ...probeScopes, [value.id]: event.target.value })}><option value="text">文本响应</option><option value="tools">工具调用</option><option value="streaming">流式文本</option><option value="vision">合成图像识别</option></select></label>
<button className="button secondary" disabled={locked} onClick={() => { setNativeTarget(value); setEditing(false); }}>原生参数</button><button className="mc-probe" disabled={locked || !value.enabled} onClick={() => void act(async () => { const result = await api<{ scope: string }>('/model-center/probe', { id: value.id, scope: probeScopes[value.id] ?? 'text' }); if (alive.current) setNotice(capabilityLabels[result.scope] + '检测通过;只验证所选能力,原请求与用量已记入账本。'); })}>验证响应(调用模型)</button></footer>
</article>)}</div>
{nativeTarget && <NativeParameters key={nativeTarget.id + ":" + nativeTarget.revision} connection={nativeTarget} busy={locked} onCancel={() => setNativeTarget(null)} onSave={async input => { await act(async () => { const result = await api<{ config: Config }>("/model-center/native-parameters", input); if (alive.current) { onConfig(result.config); setNativeTarget(null); setNotice("原生参数已保存;新任务按所选协议发送,旧请求保持原记录。"); } }); }} />}{editing && <form className="mc-editor" aria-label="编辑模型连接" onSubmit={event => { event.preventDefault(); void act(async () => { await api('/model-center/connections', { ...draft, modelIdentityAliases: draft.modelIdentityAliasesText.split(',').map(v=>v.trim()).filter(Boolean), ...(key ? { apiKey: key } : {}), ...(persistKey ? { persistKey: true } : {}) }); if (alive.current) { setKey(''); setEditing(false); setNotice(persistKey ? '连接与本机加密凭据已一起保存。' : '连接已保存。'); } }); }}>
<h3>{draft.id ? '编辑模型连接' : '添加模型连接'}</h3><div className="mc-form-grid">
<label>连接名称<input required value={draft.name} onChange={event => setDraft({ ...draft, name: event.target.value })} /></label>
<label>服务品牌<select value={draft.brand} onChange={event => setDraft({ ...draft, brand: event.target.value })}>{['自定义', 'OpenAI', 'Claude 兼容代理', 'DeepSeek', 'Ollama', 'vLLM', '兼容服务'].map(brand => <option key={brand}>{brand}</option>)}</select></label>
<label>接口协议<select aria-label="接口协议" value={draft.protocol} onChange={event => setDraft({ ...draft, protocol: event.target.value, nativeParameters: {}, outputTokenField: undefined })}><option value="chat-completions">Chat Completions</option><option value="responses">OpenAI Responses</option><option value="anthropic-messages">Anthropic Messages</option></select></label>
<label>工具调用能力<select aria-label="工具调用能力" value={draft.capabilityDeclarations.tools} onChange={event => setDraft({ ...draft, capabilityDeclarations: { ...draft.capabilityDeclarations, tools: event.target.value } })}><option value="supported">服务声明支持</option><option value="unknown">尚未确定</option><option value="unsupported">明确不支持</option></select></label>
<label>流式能力<select aria-label="流式能力" value={draft.capabilityDeclarations.streaming} onChange={event => setDraft({ ...draft, streaming: event.target.value === 'supported' && draft.streaming, capabilityDeclarations: { ...draft.capabilityDeclarations, streaming: event.target.value } })}><option value="unknown">尚未确定</option><option value="supported">服务声明支持</option><option value="unsupported">明确不支持</option></select></label>
<label>视觉能力<select aria-label="视觉能力" value={draft.capabilityDeclarations.vision} onChange={event=>setDraft({...draft,capabilityDeclarations:{...draft.capabilityDeclarations,vision:event.target.value}})}><option value="unknown">尚未确定</option><option value="supported">服务声明支持</option><option value="unsupported">明确不支持</option></select></label>
<label className="mc-checkbox"><input type="checkbox" checked={draft.streaming} disabled={draft.capabilityDeclarations.streaming !== 'supported'} onChange={event => setDraft({ ...draft, streaming: event.target.checked })} />使用流式输出</label>
<label className="mc-full">接口根地址<input type="url" required value={draft.baseUrl} onChange={event => setDraft({ ...draft, baseUrl: event.target.value })} /></label>
<p className="mc-help mc-full" aria-label="请求地址预览">POST {previewUrl(draft)}<br />{draft.protocol === 'anthropic-messages' ? '填写服务根地址或 /v1 根地址,工作台补齐 /v1/messages。鉴权按供应商文档选择。' : '工作台按此根地址追加协议路径;服务要求 /v1 时,请在根地址中填写。'}切换协议会重置本表单的原生参数,保存后从新任务生效。</p>
{draft.protocol === 'anthropic-messages' && <label>Messages 鉴权<select aria-label="Messages 鉴权" value={draft.messagesAuth ?? 'api-key'} onChange={event => setDraft({ ...draft, messagesAuth: event.target.value })}><option value="api-key">x-api-key(Anthropic 标准)</option><option value="bearer">Bearer(兼容服务)</option></select></label>}
<label>请求模型名称<input required value={draft.model} onChange={event => setDraft({ ...draft, model: event.target.value })} /></label>
<label>型号核对<select aria-label="型号核对" value={draft.modelIdentityPolicy} onChange={event => setDraft({ ...draft, modelIdentityPolicy: event.target.value })}><option value="record">记录请求与返回型号</option><option value="require-match">无法核对或不一致时暂停</option></select></label>
<label className="mc-full">允许的返回型号(可选,逗号分隔)<input value={draft.modelIdentityAliasesText} onChange={event => setDraft({ ...draft, modelIdentityAliasesText: event.target.value })} /></label>
<label className="mc-full">型号映射依据<input required={draft.modelIdentityAliasesText.trim().length > 0} value={draft.modelIdentityAliasSource} placeholder="填写供应商映射说明或可核对的出处" onChange={event => setDraft({ ...draft, modelIdentityAliasSource: event.target.value })} /></label>
<label>临时 API Key<input type="password" autoComplete="off" value={key} placeholder={draft.id ? '留空保留本次凭据' : '按服务要求填写'} onChange={event => setKey(event.target.value)} /></label>
<label>上下文上限<input type="number" min="1000" max="200000" value={draft.contextLimit} onChange={event => setDraft({ ...draft, contextLimit: Number(event.target.value) })} /></label>
<label>输出上限<input type="number" min="256" max="16000" value={draft.maxOutputTokens} onChange={event => setDraft({ ...draft, maxOutputTokens: Number(event.target.value) })} /></label>
<label>并发请求上限<input type="number" min="1" max="8" value={draft.concurrency} onChange={event => setDraft({ ...draft, concurrency: Number(event.target.value) })} /></label>
<label className="mc-checkbox"><input type="checkbox" checked={draft.requiresKey} onChange={event => setDraft({ ...draft, requiresKey: event.target.checked })} />服务需要 API Key</label></div>
<label className="mc-checkbox"><input type="checkbox" checked={persistKey} onChange={event => setPersistKey(event.target.checked)} />本机加密保存本次填写的 API Key</label>
<p className="mc-help"><CircleHelp size={14} />品牌仅用于分类,请选择服务实际提供的协议。能力检测会发起一次模型请求,可能产生费用;使用合成输入,不发送项目文件。文本检测不能证明工具或视觉能力。配置变化后需重新检测并核对凭据保存状态。</p>
<div className="mc-actions"><button className="button secondary" type="button" onClick={() => { setEditing(false); setKey(''); }}>取消</button><button className="button primary" disabled={locked || persistKey && !key.trim()} type="submit">保存模型连接</button></div>
</form>}
</>}
{tab === 'network' && <ModelNetworkDiagnostics connections={view.connections} initialId={networkTarget || (selected?.type !== 'pool' ? selected?.id : undefined)} disabled={locked} />}
{tab === 'credentials' && <section aria-label="本机加密凭据">
<div className="mc-section-title"><div><h3>本机加密凭据</h3><p>使用当前Windows用户加密。保存后的 Key 不会回显或包含在导出中。</p></div></div>
{!credentialView ? <p className="mc-empty">正在核对本机保存状态…</p> : <>
<p className="mc-help">只保存这次填写或确认导入的凭据。临时连接在宿主退出后需要重新填写。</p>
{credentialView.unavailable && <p className="mc-card-warning">原保存登记格式不可用;原数据保留,请核对后修复。</p>}
<form className="mc-editor" aria-label="保存加密凭据" onSubmit={event => { event.preventDefault(); void act(async () => {
const target = view.connections.find(value => value.id === (credentialTarget || view.connections[0]?.id));
if (!target) return;
const result = await api<{ config: Config }>('/model-center/credentials', { id: target.id, revision: target.revision, action: 'save', apiKey: credentialKey });
if (alive.current) { setCredentialKey(''); setNotice('本机加密凭据已保存;宿主重启后按原连接身份加载。'); onConfig(result.config); }
}); }}>
<div className="mc-form-grid"><label>选择保存连接<select aria-label="选择保存连接" value={credentialTarget || view.connections[0]?.id || ''} onChange={event => { setCredentialTarget(event.target.value); setCredentialKey(''); }}>{view.connections.map(value => <option key={value.id} value={value.id}>{value.name} · {value.model || '未填写模型'}</option>)}</select></label>
<label>重新填写 API Key<input type="password" autoComplete="off" value={credentialKey} onChange={event => setCredentialKey(event.target.value)} /></label></div>
<p className="mc-help">只保存这次新填的凭据。不同用户、目录或连接配置无法加载原保存块。</p>
<div className="mc-actions"><button type="submit" className="button primary" disabled={locked || !credentialView.supported || credentialView.unavailable || !credentialKey.trim()}>加密保存凭据</button></div>
</form>
<div className="mc-connections">{credentialView.connections.map(value => <article className="mc-connection" key={value.id}>
<div className="mc-card-heading"><KeyRound size={20} /><div><h4>{value.name}</h4><span>{savedStates[value.status] || value.status}</span></div></div>
<p className="mc-help">{value.message}</p>{value.savedAt && <p className="mc-help">保存于 {new Date(value.savedAt).toLocaleString()}</p>}
<div className="mc-actions">{value.status !== 'not_saved' && <>
<button className="button secondary" disabled={locked} onClick={() => void act(async () => { await api('/model-center/credentials', { id: value.id, revision: value.revision, action: value.enabled ? 'disable' : 'enable' }); })}>{value.enabled ? '关闭自动加载' : '启用自动加载'}</button>
<button className="button secondary" disabled={locked} onClick={() => void act(async () => { await api('/model-center/credentials', { id: value.id, revision: value.revision, action: 'delete' }); })}>删除本机保存</button>
</>}
<button className="button secondary" disabled={locked} onClick={() => void act(async () => { const result = await api<{ config: Config }>('/model-center/credentials', { id: value.id, revision: value.revision, action: 'forget' }); if (alive.current) onConfig(result.config); })}>清除该连接凭据</button>
</div>
</article>)}</div><p className="mc-help">删除本机保存保留本次内存连接;清除该连接凭据会同时移除本机保存与内存凭据。</p>
</>}
</section>}
{tab === 'pools' && <><div className="mc-section-title"><div><h3>模型池</h3><p>按能力、凭据、健康和并发选择成员,切换保留已完成操作。</p></div><button className="button primary" disabled={locked} onClick={() => { setPool(emptyPool); setPoolEditing(true); }}><Plus size={16} />新建模型池</button></div>
{!view.pools.length && <p className="mc-empty">添加多个连接后建立模型池,设置轮询与故障切换规则。</p>}
{view.pools.map(value => <article className="mc-pool" key={value.id}><Layers3 size={23} /><div><h4>{value.name}</h4><p>{value.strategy === 'weighted' ? '权重轮询' : '顺序轮询'} · {value.members.length} 个成员 · {value.maxAttempts} 次尝试上限 · {value.sticky ? '运行内保持连接' : '每次请求重新选择'}</p><div className="mc-members">{value.members.map(member => <span key={member.connectionId}>{view.connections.find(connection => connection.id === member.connectionId)?.name} ×{member.weight}</span>)}</div></div><div className="mc-actions"><button className="button secondary" disabled={locked} onClick={() => { setPool(value); setPoolEditing(true); }}>编辑</button><button className="button primary" disabled={locked} onClick={() => void act(async () => { const result = await api<{ config: Config }>('/model-center/select', { type: 'pool', id: value.id }); onConfig(result.config, { type: 'pool', id: value.id!, name: value.name }); })}>{selected?.id === value.id ? '当前模型池' : '使用此模型池'}</button></div></article>)}
{poolEditing && <form className="mc-editor" aria-label="编辑模型池" onSubmit={event => { event.preventDefault(); void act(async () => { await api('/model-center/pools', pool); if (alive.current) setPoolEditing(false); }); }}><h3>模型池规则</h3><div className="mc-form-grid"><label>模型池名称<input required value={pool.name} onChange={event => setPool({ ...pool, name: event.target.value })} /></label><label>调度策略<select value={pool.strategy} onChange={event => setPool({ ...pool, strategy: event.target.value })}><option value="round-robin">顺序轮询</option><option value="weighted">权重轮询</option></select></label><label>单请求尝试上限<input type="number" min="1" max="8" value={pool.maxAttempts} onChange={event => setPool({ ...pool, maxAttempts: Number(event.target.value) })} /></label><label>排队上限(秒)<input type="number" min="1" max="60" value={pool.queueTimeoutMs / 1000} onChange={event => setPool({ ...pool, queueTimeoutMs: Number(event.target.value) * 1000 })} /></label></div><label className="mc-checkbox"><input type="checkbox" checked={pool.sticky} onChange={event => setPool({ ...pool, sticky: event.target.checked })} />同一运行优先保持连接;明确失败后才切换</label>
<fieldset><legend>模型池成员与权重</legend>{view.connections.map(connection => { const member = pool.members.find(value => value.connectionId === connection.id); return <label key={connection.id} className="mc-member-choice"><input type="checkbox" checked={!!member} onChange={event => setPool({ ...pool, members: event.target.checked ? [...pool.members, { connectionId: connection.id, weight: 1 }] : pool.members.filter(value => value.connectionId !== connection.id) })} /><span>{connection.name}<small>{connection.model || '尚未选择模型'} · {states[connection.status]}</small></span><input type="number" aria-label={connection.name + '权重'} disabled={!member} min="1" max="10" value={member?.weight ?? 1} onChange={event => setPool({ ...pool, members: pool.members.map(value => value.connectionId === connection.id ? { ...value, weight: Number(event.target.value) } : value) })} /></label>; })}</fieldset>
<div className="mc-actions"><button className="button secondary" type="button" onClick={() => setPoolEditing(false)}>取消</button><button className="button primary" disabled={locked || !pool.members.length}>保存模型池</button></div></form>}
</>}
{tab === 'attempts' && <><div className="mc-section-title"><div><h3>请求账本</h3><p>最近100次物理请求;最多保存1000次。未知用量保持未知。</p></div><span>{view.attempts.length} 条记录</span></div>{!view.attempts.length && <p className="mc-empty">当前没有模型中心请求。选择连接或模型池执行任务后,实际尝试会保存在这里。</p>}<div className="mc-attempts">{view.attempts.map(value => <article key={value.id}><div><span className={'mc-state mc-state-' + value.status}>{states[value.status]}</span><strong>{value.model}</strong><time>{new Date(value.startedAt).toLocaleString()}</time></div><p>{view.connections.find(connection => connection.id === value.connectionId)?.name || '未派发'} · {value.protocol ? protocolLabel(value.protocol) : '能力筛选'}{value.streaming ? ' · 流式' : ''} · {value.ordinal ? '尝试 ' + value.ordinal : '未发送'} · {value.usageStatus === 'reported' ? `${value.usage?.prompt_tokens ?? '?'} 输入 / ${value.usage?.completion_tokens ?? '?'} 输出 tokens` : value.usageStatus === 'not_dispatched' ? '未产生请求用量' : '用量未知'}</p><code>Run {value.runId}</code>{value.stream && <div className="mc-stream-receipt"><p>{value.stream.terminal ? "响应完整终结" : "响应未完整,片段保留待核对"} · 已接收 {value.stream.bytes.toLocaleString()} bytes · {value.stream.frames} 个事件{value.stream.capturedBytes !== undefined && value.stream.capturedBytes < value.stream.bytes ? " · 仅保存上限内片段" : ""}</p><code>原流 SHA256 {value.stream.sha256}</code>{value.responseSha256 && <code>工件 SHA256 {value.responseSha256}{value.responseRedacted ? "(已脱敏)" : ""}</code>}{value.sessionId && value.responseArtifactId && <button className="button secondary" disabled={working} onClick={() => void act(async () => { await downloadArtifact(value.sessionId!, value.responseArtifactId!, "model-stream-" + value.id + ".sse"); })}>下载已保存的响应</button>}</div>}{value.requestUrl && <p className="mc-request-url">请求地址:{value.requestUrl}{value.upstreamResponse?.responseUrl && <><br />响应地址:{value.upstreamResponse.responseUrl}</>}</p>}{value.reason && <p className="mc-card-warning">{value.reason}</p>}{<ModelIdentityDetails identity={value.modelIdentity} requestedModel={value.model} />}{value.diagnostic && <ModelErrorDetails failure={value.diagnostic} />}{!value.diagnostic && value.upstreamResponse?.requestId && <p className="mc-help">上游请求 ID:{value.upstreamResponse.requestId}</p>}{value.requestArtifactId && value.sessionId && <button className="button secondary" disabled={working} onClick={() => void act(async () => { await downloadArtifact(value.sessionId!, value.requestArtifactId!, "model-request-" + value.id + ".json"); })}>下载实际请求</button>}{!!value.rejections?.length && <p className="mc-route-rejections">{value.rejections.map(item => item.connectionName + ':' + (capabilityLabels[item.capability] ?? item.capability) + ' · ' + item.reason).join(';')}</p>}</article>)}</div></>}
{tab === 'imports' && <><div className="mc-section-title"><div><h3>已有配置导入</h3><p>先预览来源和模型,再导入。原客户端配置保持原样。</p></div><button className="button secondary" disabled={working} onClick={() => void act(async () => { const value = await api<{ sources: typeof discovery }>('/model-center/imports'); if (alive.current) setDiscovery(value.sources); })}>识别本机来源</button></div>
{view.imports.length > 0 && <><h4>已登记来源</h4>{view.imports.map(value => <article className="mc-import-source" key={value.id}><strong>{value.source}</strong><code>{value.path}</code><span>{value.enabled ? '每分钟检查' : '自动同步已关闭'}</span>{value.lastCheckedAt && <p>最近检查 {new Date(value.lastCheckedAt).toLocaleString()}</p>}{value.lastError && <p className="mc-card-warning">{value.lastError}</p>}{!!value.lastResult?.conflicts?.length && <p className="mc-card-warning">有 {value.lastResult.conflicts.length} 项与手动修改冲突,已保留工作台中的修改。</p>}<button className="button secondary" disabled={locked} onClick={() => void act(async () => { await api('/model-center/import-toggle', { id: value.id, enabled: !value.enabled }); })}>{value.enabled ? '关闭自动同步' : '启用自动同步'}</button></article>)}<button className="button secondary" disabled={locked || !view.imports.some(value => value.enabled)} onClick={() => void act(async () => { const result = await api<{ results: { imported?: string[]; conflicts?: string[]; error?: string }[] }>('/model-center/import-sync', {}); const imported = result.results.reduce((sum, value) => sum + (value.imported?.length ?? 0), 0); const conflicts = result.results.reduce((sum, value) => sum + (value.conflicts?.length ?? 0), 0); if (alive.current) setNotice(`已检查启用来源:更新 ${imported} 项,冲突 ${conflicts} 项。`); })}>立即同步已启用来源</button></>}
{discovery.map(value => <article className="mc-import-source" key={value.source}><strong>{value.source}</strong><code>{value.path || '当前版本尚无可发现的配置路径'}</code><span>{value.available ? value.supported ? '可预览' : '当前不支持' : '未发现'}</span>{value.detail && <p>{value.detail}</p>}<button className="button secondary" disabled={!value.available || !value.supported || locked} onClick={() => { setImportSource(value.source); setImportPath(value.path); }}>选择来源</button></article>)}
<div className="mc-editor"><div className="mc-form-grid"><label>配置格式<select value={importSource} onChange={event => setImportSource(event.target.value)}><option value="ccswitch">CCSwitch SQLite</option><option value="workbench-json">工作台连接 JSON</option></select></label><label>本地文件路径<input value={importPath} onChange={event => { setImportPath(event.target.value); setPreview(null); }} /></label></div><button className="button secondary" disabled={locked || !importPath} onClick={() => void act(async () => { const value = await api<typeof preview>('/model-center/import-preview', { source: importSource, path: importPath }); if (alive.current) setPreview(value); })}>预览可导入连接</button></div>
{preview && <div className="mc-editor"><h3>本次预览</h3>{preview.entries.map(value => <p key={value.id}>{value.name} · {value.model} · {value.baseUrl} · {value.hasKey ? '含临时凭据' : '无凭据'}</p>)}{preview.notices.map((value, index) => <p className="mc-help" key={index}>{value}</p>)}<label className="mc-checkbox"><input type="checkbox" checked={persistImports} onChange={event => setPersistImports(event.target.checked)} />本机加密保存本次确认导入的凭据</label><button className="button primary" disabled={locked || !preview.entries.length} onClick={() => void act(async () => { await api('/model-center/import-apply', { previewId: preview.id, persistCredentials: persistImports }); if (alive.current) { setPreview(null); setNotice(persistImports ? '连接与本次确认导入的加密凭据已共同保存。' : '已导入可支持的连接。临时凭据只在本次宿主内存中。'); } })}>导入这些连接</button></div>}
</>}
{tab === 'operations' && <><div className="mc-section-title"><div><h3>运行巡检</h3><p>核对宿主、任务、来源与数据,按页检查历史工件。</p></div><button className="button primary" disabled={working} onClick={() => void act(() => inspect())}><Activity size={15} />开始本地巡检</button></div><label className="mc-checkbox"><input type="checkbox" checked={autoInspect} onChange={event => setAutoInspect(event.target.checked)} />在此页面每30秒检查,离开即停止</label>{operations ? <><p className="mc-help">{new Date(operations.checkedAt).toLocaleString()} · v{operations.version} · {operations.activeTasks} 活动任务 · {operations.queue} 排队</p><div className="mc-checks">{operations.checks.map(value => <article key={value.id}><span className={'mc-state mc-state-' + value.status}>{states[value.status] || value.status}</span><div><h4>{value.title}</h4><p>{value.detail}</p></div></article>)}</div>{operations.artifacts && <div className="mc-operations-pages" aria-label="历史工件巡检分页"><p className="mc-help">本页核对 {operations.artifacts.checked} 项 · 全部 {operations.artifacts.total} 项 · 本页未覆盖 {operations.artifacts.remaining} 项</p><div className="mc-row-actions"><button className="button" disabled={working || operations.artifacts.olderOffset === null} onClick={() => void act(() => inspect(operations.artifacts!.olderOffset!))}>检查更早工件</button><button className="button" disabled={working || operations.artifacts.newerOffset === null} onClick={() => void act(() => inspect(operations.artifacts!.newerOffset!))}>检查较新工件</button></div>{operations.artifacts.results.filter(value => !value.passed).map(value => <p className="mc-help error" key={value.id}>工件 {value.id}:{value.error}</p>)}</div>}<p className="mc-help">{operations.scope}</p></> : <p className="mc-empty">执行一次本地检查,查看实际结果与检查范围。</p>}</>}
</div>}
</section>;
}
@@ -0,0 +1,9 @@
.model-error-details{font-size:12px;line-height:1.7;margin-top:10px;min-width:0;color:#344e40}
.model-error-details summary{cursor:pointer;font-weight:600;color:#365d48;padding:6px 0}
.model-error-details summary:focus-visible,.model-error-details pre:focus-visible{outline:2px solid #4c795e;outline-offset:3px}
.model-error-details dl{display:grid;grid-template-columns:minmax(84px,128px) minmax(0,1fr);gap:6px 14px;margin:12px 0}
.model-error-details dt{color:#56695b}.model-error-details dd{margin:0;min-width:0;overflow-wrap:anywhere}
.model-error-details pre{max-height:280px;max-width:100%;overflow:auto;white-space:pre-wrap;overflow-wrap:anywhere;padding:12px;background:#f2f4f1;border:1px solid #d5ded5;border-radius:5px;font-size:12px;line-height:1.7;color:#2c4134}
.model-error-caption,.model-error-hash{font-size:11px;overflow-wrap:anywhere;color:#526556}.model-error-hash code{font-size:10px}
.model-error-details .button{margin:6px 0;max-width:100%;min-height:38px}
@media(max-width:560px){.model-error-details dl{grid-template-columns:1fr;gap:2px}.model-error-details dd{margin-bottom:7px}.model-error-details pre{padding:9px}}
@@ -0,0 +1,49 @@
import { ModelIdentityDetails } from './ModelIdentityDetails';
import { useState } from 'react';
import type { RuntimeFailure } from './types';
import { downloadArtifact } from './api';
import './ModelErrorDetails.css';
const decisions: Record<string, string> = { retry_after_wait: '按等待时间重试', stream_not_replayed: '流式响应已开始,保留原片段并停止自动重发',
not_retryable: '该错误不在同一线路自动重试', attempt_limit: '达到本次尝试上限', wait_budget: '剩余等待预算不足,保持上游建议时间并结束本次请求' };
export function ModelErrorDetails({ failure }: { failure: RuntimeFailure }) {
const upstream = failure.upstream;
const requestId = upstream?.requestId ?? failure.upstreamRequestId;
const [notice, setNotice] = useState(''), [busy, setBusy] = useState(false);
const origin = failure.origin === 'upstream' ? '上游模型服务' : failure.origin === 'local' || failure.source === 'workbench' ? '工作台本地' : '旧记录未保存具体层级';
return <>{failure.modelIdentity && <ModelIdentityDetails identity={failure.modelIdentity} requestedModel={failure.model ?? '未记录'} />}<details className="model-error-details"><summary>{upstream ? '查看上游原文与请求信息' : '查看错误详情'}</summary>
<dl><dt>错误来源</dt><dd>{origin}</dd>
{failure.model && <><dt>请求型号</dt><dd>{failure.model}</dd></>}
{(failure.requestUrl || failure.endpoint) && <><dt>请求地址</dt><dd>{failure.requestUrl || (failure.endpoint ?? '') + (failure.route ?? '')}</dd></>}
{failure.responseUrl && <><dt>响应地址</dt><dd>{failure.responseUrl}</dd></>}
{failure.redirectMode === 'manual' && <><dt>重定向</dt><dd>未自动跟随;不会向跳转地址转发凭据</dd></>}
{requestId && <><dt>上游请求 ID</dt><dd><code>{requestId}</code></dd></>}
{upstream?.responseId && <><dt>上游响应 ID</dt><dd><code>{upstream.responseId}</code></dd></>}
{failure.wireAttemptId && <><dt>本地物理尝试 ID</dt><dd><code>{failure.wireAttemptId}</code></dd></>}
{upstream?.code && <><dt>上游 code</dt><dd><code>{upstream.code}</code></dd></>}
{upstream?.type && <><dt>上游 type</dt><dd><code>{upstream.type}</code></dd></>}
{upstream?.param && <><dt>上游参数位置</dt><dd>{upstream.param}</dd></>}
{upstream?.eventType && <><dt>上游事件</dt><dd>{upstream.eventType}</dd></>}
{upstream?.reason && <><dt>上游结束原因</dt><dd>{upstream.reason}</dd></>}
{upstream?.retryAfter !== null && upstream?.retryAfter !== undefined && <><dt>原 Retry-After</dt><dd><code>{upstream.retryAfter}</code>{upstream.retryAfterMs !== null && upstream.retryAfterMs !== undefined ? ' · ' + upstream.retryAfterMs / 1000 + ' 秒' : ' · 未能解析,已停止自动重试'}</dd></>}
{failure.limitReason === 'unspecified' && <><dt>限额类型</dt><dd>上游未提供明确原因</dd></>}
{failure.retryDecision && <><dt>重试处理</dt><dd>{decisions[failure.retryDecision] ?? failure.retryDecision}</dd></>}
</dl>
{!upstream && failure.detail && <p>{failure.detail}</p>}
{upstream?.rawPreview !== undefined && <><p className="model-error-caption">上游原文{upstream.scope === 'sse-event' ? ' · 失败事件' : ' · 响应正文'}{upstream.capture?.redacted ? ' · 已脱敏' : ''}{upstream.previewTruncated ? ' · 此处显示前 8000 字符' : ''}</p>
<pre tabIndex={0} aria-label="上游错误原文">{upstream.rawPreview || '(空响应)'}</pre>
{upstream.capture && <p className="model-error-caption">已接收 {upstream.capture.receivedBytes.toLocaleString()} 字节,保留前 {upstream.capture.capturedBytes.toLocaleString()} 字节。{upstream.capture.complete ? '该范围完整接收。' : upstream.capture.truncated ? '已达到保存上限,仅保留前缀;完整长度未知。' : '接收中断,原文可能不完整。'}{upstream.artifactScope === 'sse-stream' ? '下载文件包含已保存的整段事件流。' : ''}</p>}
</>}
{!!upstream?.shortenedFields?.length && <p className="model-error-caption">部分诊断字段已缩短,详见保存的原文。</p>}
{upstream?.capture?.retention === 'preview-only' && <p className="model-error-caption">此请求未绑定工程任务,仅保留以上诊断预览;完整原文未归档为任务工件。</p>}
{upstream?.artifactSha256 && <p className="model-error-hash">工件 SHA-256 <code>{upstream.artifactSha256}</code></p>}
{upstream?.artifactId && upstream.sessionId && <button className="button secondary" type="button" disabled={busy} onClick={async () => {
setBusy(true); setNotice('');
try { await downloadArtifact(upstream.sessionId!, upstream.artifactId!, 'model-error-' + (failure.wireAttemptId ?? upstream.artifactId) + (upstream.artifactScope === 'sse-stream' ? '.sse' : '.txt')); setNotice('已下载保存的脱敏响应。'); }
catch (cause) { setNotice(cause instanceof Error ? cause.message : '下载失败,请重试。'); }
finally { setBusy(false); }
}}>下载已保存的原文</button>}
{notice && <p role="status">{notice}</p>}
</details></>;
}
@@ -0,0 +1,8 @@
.model-identity-details{font-size:12px;line-height:1.7;margin-top:8px;min-width:0;color:#344e40}
.model-identity-details summary{cursor:pointer;font-weight:600;padding:4px 0;overflow-wrap:anywhere}
.model-identity-details[data-status="mismatch"] summary,.model-identity-details[data-status="mixed"] summary,.model-identity-details[data-status="invalid"] summary{color:#89421b}
.model-identity-details summary:focus-visible{outline:2px solid #4c795e;outline-offset:3px}
.model-identity-details dl{display:grid;grid-template-columns:minmax(84px,128px) minmax(0,1fr);gap:4px 12px;margin:8px 0}
.model-identity-details dd{margin:0;min-width:0;overflow-wrap:anywhere}.model-identity-details dt{color:#526556}
.model-identity-details .model-identity-hash{overflow-wrap:anywhere;font-size:11px}.model-identity-details .button{max-width:100%;min-height:36px;margin:4px 0}
@media(max-width:560px){.model-identity-details dl{grid-template-columns:1fr;gap:2px}.model-identity-details dd{margin-bottom:6px}}
@@ -0,0 +1,24 @@
import { useState } from 'react';
import { modelIdentityLabel, type ModelIdentity } from '../shared/contracts/model-identity.mjs';
import { downloadArtifact } from './api';
import './ModelIdentityDetails.css';
export function ModelIdentityDetails({ identity, requestedModel }: { identity?: ModelIdentity; requestedModel: string }) {
const [busy, setBusy] = useState(false), [notice, setNotice] = useState('');
const source = identity?.responseSource;
return <details className="model-identity-details" data-status={identity?.status ?? 'historical'}>
<summary>{modelIdentityLabel(identity)}</summary>
<dl><dt>请求型号</dt><dd>{identity?.requestedModel ?? requestedModel}</dd>
<dt>上游报告型号</dt><dd>{identity?.reportedModels.length ? identity.reportedModels.join('、') : identity ? '未报告' : '历史记录未核对'}</dd>
<dt>处理方式</dt><dd>{identity?.policy === 'require-match' ? '不一致或无法核对时暂停' : '记录原结果和型号差异'}</dd>
{identity?.mapping && <><dt>映射依据</dt><dd>{identity.mapping.source}<br /><small>用户登记 · {identity.mapping.models.join('、')}</small></dd></>}
</dl><p>这里只核对接口报告的型号,不能据此认证底层模型。</p>
{source && <><p className="model-identity-hash">原响应 SHA-256 <code>{source.sha256}</code></p>
<button className="button secondary" type="button" disabled={busy} onClick={async () => {
setBusy(true); setNotice('');
try { await downloadArtifact(source.sessionId, source.artifactId, 'model-response-' + source.artifactId + (source.scope === 'sse-stream' ? '.sse' : '.json')); setNotice('已下载保存的响应。'); }
catch (error) { setNotice(error instanceof Error ? error.message : '下载失败,请核对原任务。'); } finally { setBusy(false); }
}}>{busy ? '正在读取原响应…' : '下载原响应'}</button></>}
{notice && <p role="status">{notice}</p>}
</details>;
}
@@ -0,0 +1,3 @@
.mc-network{min-width:0}.mn-controls{display:flex;align-items:flex-end;gap:10px;flex-wrap:wrap}.mn-controls label{display:grid;gap:7px;min-width:220px;flex:1;max-width:470px;font-weight:600;color:#304b65}.mn-controls select{width:100%;min-height:40px;border:1px solid #adbdcd;border-radius:5px;background:#fff;padding:7px 10px;color:#17314a;font:inherit}.mn-controls .button{min-height:40px}.mn-endpoint{overflow-wrap:anywhere;margin:12px 0 8px;font-family:Consolas,monospace;font-size:12px;color:#304b65;line-height:1.7}.mn-endpoint span{color:#53647c}.mn-scope{display:flex;gap:9px;align-items:flex-start;color:#435b73;line-height:1.8;margin:10px 0 18px;font-size:13px}.mn-scope svg{flex-shrink:0;margin-top:4px}.mn-link{padding:0;border:0;text-decoration:underline;color:#174c78;background:none;font:inherit;cursor:pointer}.mn-error,.mn-warning{padding:12px 14px;border-left:3px solid #ac6a20;background:#fff5e7;color:#75420f;line-height:1.8;overflow-wrap:anywhere}.mn-error{color:#942e29;border-color:#b43c34;background:#fff0ed}.mn-workspace{display:grid;grid-template-columns:minmax(0,1fr) 230px;border:1px solid #c3d0dc;border-radius:6px;background:white;overflow:hidden}.mn-result{min-width:0;padding:20px}.mn-result-heading{display:flex;justify-content:space-between;gap:12px;align-items:flex-start;border-bottom:1px solid #d2dce5;padding-bottom:15px}.mn-result-heading p{font-size:12px;color:#53647c;margin:9px 0 0;line-height:1.8}.mn-revision{font-size:12px;color:#53647c;white-space:nowrap}.mn-status{display:inline-block;font-size:12px;line-height:1.7;font-weight:600;color:#435b73}.mn-result-heading .mn-status{font-size:16px}.mn-status-passed{color:#246348}.mn-status-failed{color:#9d352d}.mn-status-partial{color:#80500e}.mn-status-running{color:#195d94}.mn-dns{padding:18px 0}.mn-dns h4{font-size:13px;margin:0;color:#1c354e}.mn-dns h4 span{font-size:12px;color:#53647c;font-weight:400;margin-left:8px}.mn-dns p{color:#94382e;overflow-wrap:anywhere;line-height:1.8}.mn-dns ul{list-style:none;margin:10px 0 0;padding:0;display:grid;gap:6px}.mn-dns li{display:flex;gap:12px;font-size:12px;align-items:flex-start;line-height:1.7}.mn-dns li>span{color:#53647c;white-space:nowrap}.mn-dns code{color:#25445d;overflow-wrap:anywhere}.mn-paths{border-collapse:collapse;width:100%;table-layout:fixed;color:#28425a;font-size:12px}.mn-paths caption{text-align:left;color:#1c354e;font-weight:600;margin:0 0 10px;font-size:13px}.mn-paths th,.mn-paths td{text-align:left;vertical-align:top;padding:12px 7px;border-bottom:1px solid #d6e0e9;overflow-wrap:anywhere;line-height:1.8}.mn-paths thead th{background:#edf2f6;font-weight:500;color:#4b6277}.mn-paths th:first-child{width:27%}.mn-paths th:nth-child(2){width:16%}.mn-paths th:nth-child(3){width:25%}.mn-paths code,.mn-paths small{display:block;font-size:12px;font-weight:400;line-height:1.8;color:#53647c;margin-top:5px;overflow-wrap:anywhere}.mn-paths small svg{vertical-align:middle;color:#246348;margin-right:3px}.mn-outcome{color:#80500e;line-height:1.8}.mn-transport{margin-top:18px;font-size:12px;color:#435b73}.mn-transport summary{cursor:pointer;padding:8px 0;color:#244e72;font-size:13px}.mn-transport dl{display:grid;grid-template-columns:105px minmax(0,1fr);gap:9px;line-height:1.7}.mn-transport dt{color:#53647c}.mn-transport dd{margin:0;overflow-wrap:anywhere}.mn-history{background:#f5f8fa;border-left:1px solid #d2dce5;padding:18px 14px;min-width:0}.mn-history h4{display:flex;align-items:center;gap:7px;font-size:13px;color:#304b65;margin:0 0 10px}.mn-history p{color:#53647c;font-size:12px;line-height:1.8}.mn-history button{display:grid;gap:4px;padding:12px 10px;width:100%;margin-top:8px;text-align:left;background:transparent;border:1px solid transparent;border-radius:4px;cursor:pointer;color:#304b65;font:inherit}.mn-history button[aria-pressed=true]{border-color:#9eb6ca;background:#fff}.mn-history button:hover{background:#e8eff5}.mn-history button span,.mn-history button small{font-size:12px;line-height:1.7;color:#53647c}.mn-history button strong{font-size:13px;line-height:1.7;font-weight:600}.mn-empty{padding:28px 4px;min-height:210px;color:#486580}.mn-empty h4{color:#25445d;font-size:15px;margin:14px 0 8px}.mn-empty p{max-width:520px;line-height:1.9;margin:0;color:#53647c}.mc-network button:focus-visible,.mc-network select:focus-visible,.mc-network summary:focus-visible{outline:2px solid #256c9e;outline-offset:3px}
@media(max-width:900px){.mn-workspace{grid-template-columns:minmax(0,1fr)}.mn-history{border-left:0;border-top:1px solid #d2dce5}.mn-history button{max-width:100%}.mn-result{padding:16px}.mn-history{max-height:300px;overflow:auto}}
@media(max-width:620px){.mn-controls label{min-width:100%;max-width:none}.mn-controls .button{min-height:44px;flex:1;justify-content:center}.mn-result{padding:13px 10px}.mn-result-heading{flex-wrap:wrap}.mn-paths th,.mn-paths td{padding:10px 4px}.mn-paths th:first-child{width:24%}.mn-paths th:nth-child(2){width:18%}.mn-paths th:nth-child(3){width:25%}.mn-transport dl{grid-template-columns:85px minmax(0,1fr)}.mn-history button{min-height:44px}.mn-dns h4 span{display:block;margin:7px 0 0}}
@@ -0,0 +1,98 @@
import { useEffect, useRef, useState } from 'react';
import { Check, CircleHelp, History, Play, RefreshCw, Square, Wifi } from 'lucide-react';
import { api } from './api';
import './ModelNetworkDiagnostics.css';
type Connection = { id: string; name: string; baseUrl: string; revision: number };
type Trial = { mode: string; status: string; stage: string; address?: string; family?: string; code?: string; tcpMs?: number; tlsMs?: number;
tls?: string; tlsProtocol?: string; certificateAuthorized?: boolean; attempts: { address: string; code?: string }[] };
type Job = { id: string; connectionId: string; connectionRevision: number; connectionName: string; status: string; startedAt: string; finishedAt: string | null;
stale: boolean; code?: string; elapsedMs: number; budgetMs: number; target: { endpoint: string; host: string; port: number; scheme: string };
transport: { autoSelectFamily: boolean; familyAttemptTimeoutMs: number; connectTimeoutMs: number };
route: { proxyConfigured: boolean; noProxyConfigured: boolean; customTransport: boolean };
stages: { dns?: { status: string; elapsedMs?: number; code?: string; addresses?: { address: string; family: number }[] } }; trials: Trial[] };
type View = { jobs: Job[]; active: number; retained: number };
const labels: Record<string, string> = { passed: '通过', partial: '部分路径可连接', failed: '未通过', running: '检查中', pending: '等待',
cancelled: '已停止', interrupted: '已中断', skipped: '未检查' };
const reasons: Record<string, string> = { ENOTFOUND: '域名没有解析结果', EAI_AGAIN: 'DNS 暂时不可用', DNS_NO_ADDRESSES: '没有可用的 IP 地址',
ECONNREFUSED: '目标拒绝连接', ENETUNREACH: '目标网络不可达', EHOSTUNREACH: '目标主机不可达', TCP_CONNECT_TIMEOUT: '建立 TCP 连接超时',
TLS_HANDSHAKE_TIMEOUT: '等待 TLS 握手超时', SELF_SIGNED_CERT_IN_CHAIN: '证书链未受信任', DEPTH_ZERO_SELF_SIGNED_CERT: '证书未受信任',
UNABLE_TO_VERIFY_LEAF_SIGNATURE: '无法核验证书链', ERR_TLS_CERT_ALTNAME_INVALID: '证书与域名不匹配', CERT_HAS_EXPIRED: '证书已过期',
ADDRESS_FAMILY_UNAVAILABLE: 'DNS 未返回此地址族', DNS_NOT_COMPLETED: 'DNS 尚未通过', DIAGNOSTIC_DEADLINE: '已到达诊断时间上限',
DIAGNOSTIC_CANCELLED: '用户停止了本次诊断', HOST_STOPPED: '执行宿主停止了诊断', HOST_RESTARTED: '宿主重启,原诊断未重放',
DIAGNOSTIC_INTERNAL_ERROR: '诊断未能完整保存,请核对宿主状态' };
const detail = (code?: string) => code ? (reasons[code] ?? '连接检查未完成') + ' · ' + code : '';
const duration = (value?: number) => value === undefined ? '—' : value.toLocaleString() + ' ms';
export function ModelNetworkDiagnostics({ connections, initialId, disabled }: { connections: Connection[]; initialId?: string; disabled: boolean }) {
const fallback = connections.find(value => value.id === initialId) ?? connections.find(value => value.id !== 'legacy-default') ?? connections[0];
const [connectionId, setConnectionId] = useState(fallback?.id ?? '');
const [view, setView] = useState<View | null>(null), [focused, setFocused] = useState('');
const [working, setWorking] = useState(false), [error, setError] = useState('');
const mounted = useRef(true), generation = useRef(0);
const selected = connections.find(value => value.id === connectionId);
const jobs = view?.jobs.filter(value => value.connectionId === connectionId) ?? [];
const job = jobs.find(value => value.id === focused) ?? jobs[0];
const activeJob = view?.jobs.find(value => value.status === 'running');
async function load() {
const marker = ++generation.current, result = await api<View>('/model-center/network-diagnostics');
if (mounted.current && generation.current === marker) setView(result);
}
useEffect(() => { mounted.current = true; void load().catch(cause => { if (mounted.current) setError(cause.message); });
return () => { mounted.current = false; generation.current++; }; }, []);
useEffect(() => {
if (!view?.active) return;
const timer = window.setInterval(() => { void load().catch(cause => { if (mounted.current) setError(cause.message); }); }, 600);
return () => window.clearInterval(timer);
}, [view?.active]);
useEffect(() => { if (!selected && fallback) { setConnectionId(fallback.id); setFocused(''); } }, [selected, fallback?.id]);
async function act(operation: () => Promise<void>) {
setWorking(true); setError('');
try { await operation(); if (mounted.current) await load(); }
catch (cause) { if (mounted.current) { setError(cause instanceof Error ? cause.message : '操作未完成,请刷新核对原记录。'); void load().catch(() => {}); } }
finally { if (mounted.current) setWorking(false); }
}
return <section className="mc-network" aria-label="模型连接诊断">
<div className="mc-section-title"><div><h3>连接诊断</h3><p>检查端点的 DNS、TCP 和 TLS。无需 Key,不发送模型请求。</p></div>
<button className="button secondary" aria-label="刷新连接诊断" disabled={working} onClick={() => void act(load)}><RefreshCw size={15} />刷新</button></div>
<div className="mn-controls"><label>诊断连接<select aria-label="诊断连接" value={connectionId} disabled={working} onChange={event => { setConnectionId(event.target.value); setFocused(''); setError(''); }}>
{connections.map(value => <option key={value.id} value={value.id}>{value.name}</option>)}</select></label>
<button className="button primary" disabled={disabled || working || !selected || !view || !!view.active} onClick={() => void act(async () => {
const result = await api<{ job: Job }>('/model-center/network-diagnostics', { id: selected!.id, revision: selected!.revision });
if (mounted.current) setFocused(result.job.id);
})}><Play size={15} />开始直连检查</button>
{activeJob && <button className="button secondary" disabled={working} onClick={() => void act(async () => {
await api('/model-center/network-diagnostics/' + activeJob.id + '/stop', {});
})}><Square size={14} />停止诊断</button>}
</div>
{selected && <p className="mn-endpoint">{selected.baseUrl} <span>· 配置修订 {selected.revision}</span></p>}
<p className="mn-scope"><CircleHelp size={16} /><span>本次只检查端点直连路径,保留证书校验;握手通过不能证明 Key、型号或模型能力可用。检查最多约 12 秒,离开后结果保留。</span></p>
{error && <p className="mn-error" role="alert">{error}</p>}
{activeJob && activeJob.connectionId !== connectionId && <p className="mn-scope">{activeJob.connectionName} 正在检查。<button type="button" className="mn-link" onClick={() => { setConnectionId(activeJob.connectionId); setFocused(activeJob.id); }}>查看正在运行的诊断</button></p>}
{!view ? <p className="mc-empty">正在读取诊断记录…</p> : <div className="mn-workspace">
<div className="mn-result" aria-label="本次连接诊断结果">
{!job ? <div className="mn-empty"><Wifi size={24} /><h4>先检查连接,再判断问题阶段</h4><p>选择已保存的连接并开始检查。这里会保留解析地址、连接耗时和证书核对结果,原任务不会被重新执行。</p></div> : <>
<header className="mn-result-heading"><div><span className={'mn-status mn-status-' + job.status} role="status">{job.status === 'passed' ? '直连握手通过' : labels[job.status] ?? job.status}</span>
<p>{job.connectionName} · {new Date(job.startedAt).toLocaleString()} · {duration(job.elapsedMs)}</p></div><span className="mn-revision">修订 {job.connectionRevision}</span></header>
{job.stale && <p className="mn-warning">连接配置已变化。下方是原修订 {job.connectionRevision} 的记录,请重新检查当前连接。</p>}
{(job.route.proxyConfigured || job.route.customTransport) && <p className="mn-warning">{job.route.customTransport ? '此宿主使用自定义模型运输。' : '宿主已配置环境代理' + (job.route.noProxyConfigured ? '及 NO_PROXY 规则。' : '。')}本次未发送代理 CONNECT 或模型 HTTP 请求,实际 API 路线尚未核验。</p>}
<div className="mn-dns"><h4>DNS 地址解析 <span>{labels[job.stages.dns?.status ?? 'pending']} · {duration(job.stages.dns?.elapsedMs)}</span></h4>
{job.stages.dns?.code && <p>{detail(job.stages.dns.code)}</p>}
{!!job.stages.dns?.addresses?.length && <ul>{job.stages.dns.addresses.map((value, index) => <li key={value.address + index}><span>IPv{value.family}</span><code>{value.address}</code></li>)}</ul>}
</div>
<table className="mn-paths"><caption>直连路径与握手阶段</caption><thead><tr><th>路径</th><th>TCP</th><th>TLS</th><th>结果</th></tr></thead>
<tbody>{job.trials.map(trial => <tr key={trial.mode}><th scope="row">{({ auto: '自动选择', ipv4: '固定 IPv4', ipv6: '固定 IPv6' } as Record<string, string>)[trial.mode] ?? trial.mode}
{trial.address && <code>{trial.address}</code>}</th><td>{duration(trial.tcpMs)}</td><td>{trial.tls === 'not_applicable' ? 'HTTP 端点无需 TLS' : trial.tlsProtocol ?? duration(trial.tlsMs)}
{trial.certificateAuthorized && <small><Check size={12} />证书已核对 · {duration(trial.tlsMs)}</small>}</td><td><span className={'mn-status mn-status-' + trial.status}>{trial.status === 'running' ? (trial.stage === 'tls' ? 'TLS 握手中' : 'TCP 连接中') : labels[trial.status] ?? trial.status}</span>
{trial.code && <small>{detail(trial.code)}</small>}{trial.attempts.some(value => value.code) && <small>候选地址失败:{trial.attempts.filter(value => value.code).map(value => value.address + ' · ' + value.code).join(';')}</small>}</td></tr>)}</tbody></table>
{job.code && <p className="mn-outcome">{detail(job.code)}</p>}
<details className="mn-transport"><summary>查看原诊断范围与运输参数</summary><dl><dt>原端点</dt><dd>{job.target.endpoint}</dd><dt>检查目标</dt><dd>{job.target.host}:{job.target.port}</dd>
<dt>自动地址族</dt><dd>{job.transport.autoSelectFamily ? '开启' : '关闭'} · 候选间隔 {job.transport.familyAttemptTimeoutMs} ms</dd><dt>连接 / 总时限</dt><dd>{job.transport.connectTimeoutMs} / {job.budgetMs} ms</dd>
<dt>模型 API</dt><dd>未请求;能力与连接健康结论保持原记录</dd><dt>记录</dt><dd>{job.id}</dd></dl></details>
</>}
</div>
<aside className="mn-history" aria-label="连接诊断历史"><h4><History size={16} />近期检查</h4><p>保存最近 {view.retained} 条;点击查看原记录。</p>
{!jobs.length && <p>这条连接还没有检查记录。</p>}{jobs.map(value => <button key={value.id} type="button" aria-pressed={job?.id === value.id} onClick={() => setFocused(value.id)}><span>{new Date(value.startedAt).toLocaleString()}</span><strong>{labels[value.status] ?? value.status}{value.stale ? ' · 旧配置' : ''}</strong><small>修订 {value.connectionRevision} · {duration(value.elapsedMs)}</small></button>)}
</aside>
</div>}
</section>;
}
@@ -0,0 +1,18 @@
import { useState } from 'react';
export type WaitSettings = { modelResponseTimeoutMs: number; modelStreamIdleTimeoutMs: number };
export function ModelWaitSettings({ value, disabled, onSave }: { value: WaitSettings; disabled: boolean; onSave: (value: WaitSettings) => void }) {
const [responseSeconds, setResponseSeconds] = useState(value.modelResponseTimeoutMs / 1000);
const [idleSeconds, setIdleSeconds] = useState(value.modelStreamIdleTimeoutMs / 1000);
return <form className="mc-editor" aria-label="模型等待时限" onSubmit={event => { event.preventDefault(); onSave({ modelResponseTimeoutMs: responseSeconds * 1000, modelStreamIdleTimeoutMs: idleSeconds * 1000 }); }}>
<h3>给模型足够时间,保留等待边界。</h3>
<p>适用于原模型连接及模型池内的每次请求;从下一次运行生效。保存只调整等待时限,保留当前模型池和连接。</p>
<div className="mc-form-grid">
<label>单次模型响应上限(秒)<input aria-label="单次模型响应上限(秒)" type="number" min={15} max={900} step={1} required value={responseSeconds} disabled={disabled} onChange={event => setResponseSeconds(Number(event.target.value))} /><small>包含服务排队与生成。默认 300 秒,最多 900 秒。</small></label>
<label>流式无数据上限(秒)<input aria-label="流式无数据上限(秒)" type="number" min={5} max={300} step={1} required value={idleSeconds} disabled={disabled} onChange={event => setIdleSeconds(Number(event.target.value))} /><small>开始流式响应后连续没有新数据的等待时间。默认 120 秒。</small></label>
</div>
<p>持续收到数据仍受单次响应上限约束。停止任务立即生效;任务总预算先到时会暂停。不完整的文件或命令参数不会执行。</p>
<div className="mc-actions"><button type="submit" className="button primary" disabled={disabled}>保存等待时限</button></div>
</form>;
}
@@ -0,0 +1,26 @@
import { useEffect, useRef, useState } from 'react';
import { nativeParameterSettings } from '../shared/contracts/native-parameters.mjs';
export type NativeConnection = { id: string; revision: number; name: string; protocol: string; nativeParameters?: Record<string, unknown>; outputTokenField?: string };
export function NativeParameters({ connection, busy, onCancel, onSave }: { connection: NativeConnection; busy: boolean; onCancel: () => void;
onSave: (input: { id: string; revision: number; nativeParameters: Record<string, unknown>; outputTokenField: string }) => Promise<void> }) {
const [text, setText] = useState(JSON.stringify(connection.nativeParameters ?? {}, null, 2));
const [field, setField] = useState(connection.outputTokenField ?? (connection.protocol === 'responses' ? 'max_output_tokens' : 'max_tokens'));
const [error, setError] = useState('');
const form = useRef<HTMLFormElement>(null);
useEffect(() => { form.current?.scrollIntoView({ block: 'nearest' }); }, []);
return <form ref={form} className="mc-editor mc-native" aria-label="原生请求参数" onSubmit={async event => {
event.preventDefault(); setError('');
try { const settings = nativeParameterSettings(connection.protocol, JSON.parse(text), field); await onSave({ id: connection.id, revision: connection.revision, ...settings }); }
catch (cause) { setError(cause instanceof Error ? cause.message : '参数格式无效。'); }
}}>
<h3>{connection.name} · 原生请求参数</h3>
<p className="mc-help">参数按所选协议原字段发送,并封存在实际请求中。具体模型是否接受这些选项,以服务响应为准;未填写的选项采用上游默认值。</p>
<label>输出上限字段<select aria-label="输出上限字段" value={field} disabled={busy} onChange={event => setField(event.target.value)}>{(connection.protocol === 'responses' ? ['max_output_tokens'] : connection.protocol === 'anthropic-messages' ? ['max_tokens'] : ['max_tokens', 'max_completion_tokens']).map(value => <option key={value}>{value}</option>)}</select></label>
<p className="mc-help">数值沿用当前任务和连接的输出预算,不允许原生参数覆盖预算、消息、工具或接口。</p>
<label>原生参数 JSON<textarea aria-label="原生参数 JSON" rows={7} maxLength={8192} spellCheck={false} value={text} disabled={busy} onChange={event => setText(event.target.value)} /></label>
<p className="mc-help">{connection.protocol === 'anthropic-messages' ? '已接入 temperature(0–1)、top_p、top_k、stop_sequences、thinking。启用 thinking 时 budget_tokens 至少1024且小于本次输出预算;具体型号支持情况以上游响应为准。' : connection.protocol === 'responses' ? '已接入 temperature、top_p、parallel_tool_calls、reasoning.effort、text.verbosity。' : '已接入 temperature、top_p、seed、parallel_tool_calls、reasoning_effort、verbosity。'}其他字段保存时会给出具体提示。语音、视频和服务端内置工具尚未接入。</p>
{error && <p className="mc-card-warning" role="alert">{error}</p>}
<div className="mc-actions"><button className="button secondary" type="button" disabled={busy} onClick={onCancel}>取消</button><button className="button primary" disabled={busy} type="submit">保存原生参数</button></div>
</form>;
}
@@ -0,0 +1,2 @@
.preview-service{border-top:1px solid var(--border,#dce3eb);padding:18px 0;color:var(--text,#223047)}
.preview-heading{display:flex;align-items:center;gap:10px;justify-content:space-between;font-size:13px}.preview-heading span{font-size:11px;color:#52647b}.preview-service p{font-size:12px;line-height:1.65;margin:9px 0}.preview-start{display:flex;gap:10px;align-items:end;flex-wrap:wrap}.preview-start label{display:grid;gap:5px;font-size:11px}.preview-start input{width:96px;padding:8px;border:1px solid #bcc9d8;border-radius:5px;background:#fff}.preview-plan,.preview-actions{display:flex;gap:8px;flex-wrap:wrap;align-items:center;margin-top:12px}.preview-job{padding:14px 0;border-top:1px solid #dce3eb;margin-top:14px}.preview-url{display:block;margin-top:8px;font-size:12px;overflow-wrap:anywhere}.preview-service pre,.preview-confirm pre{white-space:pre-wrap;overflow-wrap:anywhere;max-height:240px;overflow:auto;background:#edf1f5;padding:12px;font-size:11px;color:#24354a}.preview-confirm code,.preview-confirm p{overflow-wrap:anywhere}.preview-error{color:#9d292d!important}.preview-service details{font-size:12px;margin-top:10px}.preview-service summary{cursor:pointer}.preview-confirm .record-footnote{font-size:11px}
@@ -0,0 +1,43 @@
import { useEffect, useRef, useState } from 'react';
import { Check, FileText, Play, Square } from 'lucide-react';
import { api } from './api';
import { Modal } from './components';
import type { Project, Session, PreviewPlan } from './types';
import './PreviewPanel.css';
const live = ['queued', 'starting', 'ready', 'stopping'];
const labels:Record<string,string> = { planned:'等待核对', consumed:'计划已使用', queued:'正在准备', starting:'核对启动来源', ready:'预览已就绪', stopping:'正在停止', stopped:'已停止', exited:'服务已退出', failed:'启动或运行失败', unknown:'原进程待核对' };
export function PreviewPanel({ project, session, busy, onSession, onError, openArtifact, onOpen }: { project:Project; session:Session; busy:boolean; onSession:(session:Session)=>void; onError:(error:unknown)=>void; openArtifact:(id:string)=>void; onOpen?:()=>void }) {
const [port,setPort] = useState('5173'), [working,setWorking] = useState(''), [failure,setFailure] = useState(''), [confirm,setConfirm] = useState<PreviewPlan|null>(null);
const scope = useRef(0), plan = session.execution?.previewPlans?.at(-1), jobs = session.execution?.previewJobs ?? [], running = jobs.some(job=>live.includes(job.status));
useEffect(()=>{ scope.current++; setConfirm(null); setWorking(''); setFailure(''); return ()=>{scope.current++;}; },[session.id,session.execution?.task?.id]);
async function perform(action:string,input:unknown={}) {
const original=scope.current; setWorking(action); setFailure('');
try { const result=await api<Session>('/sessions/'+session.id+'/'+action,input); if(scope.current===original){onSession(result);setConfirm(null);} }
catch(error){if(scope.current===original){setFailure(error instanceof Error?error.message:String(error));onError(error);}}
finally{if(scope.current===original)setWorking('');}
}
return <section className="preview-service" aria-label="项目开发预览">
<div className="preview-heading"><strong>项目开发预览</strong><span>Vite · 所属工作区</span></div>
<p>启动开发服务,边修改代码边核对真实页面。页面验收和检查结果另行记录。</p>
{!project.workspace&&<p className="record-footnote">先创建并打开独立工作区,再准备项目依赖。</p>}
<div className="preview-start"><label>本机端口<input aria-label="预览端口" inputMode="numeric" type="number" min={1024} max={65535} value={port} disabled={!!working||running} onChange={event=>setPort(event.target.value)}/></label>
<button type="button" className="button secondary" disabled={busy||!!working||running||!project.workspace} onClick={()=>perform('preview-plans',{port:Number(port)})}><Play size={13}/>创建启动计划</button></div>
{failure&&<p role="alert" className="preview-error">{failure}</p>}
{plan?.status==='planned'&&<div className="preview-plan"><code>{plan.url}</code><button type="button" className="button primary" disabled={busy||!!working||running} onClick={()=>setConfirm(plan)}>核对并批准预览</button></div>}
{jobs.slice().reverse().map(job=><article className="preview-job" key={job.id}><div className="preview-heading"><strong>{labels[job.status]??job.status}</strong><code>{job.id.slice(0,8)}</code></div>
<code className="preview-url">{job.url}</code><p>{job.summary??'正在记录原进程、核对监听来源及首页响应。'}</p>
{job.process&&<p className="record-footnote">所属 PID {job.process.pid}{job.readiness?' · 监听与首页已核对':''}</p>}
<div className="preview-actions">{job.status==='ready'&&onOpen&&<button className="button primary" type="button" onClick={onOpen}>打开浏览区</button>}
{live.includes(job.status)&&<button className="button secondary" type="button" disabled={!!working} onClick={()=>perform('preview-jobs/'+job.id+'/stop')}><Square size={13}/>停止开发服务</button>}
{job.requiresVerification&&!job.reconciliation&&<button className="button secondary" type="button" disabled={!!working} onClick={()=>perform('preview-jobs/'+job.id+'/reconcile',{fingerprint:job.planFingerprint})}>只读核对原进程</button>}
{job.logArtifactId&&<button className="text-button" type="button" onClick={()=>openArtifact(job.logArtifactId!)}><FileText size={13}/>原执行日志</button>}</div>
{job.logExcerpt&&<details><summary>日志预览</summary><pre>{job.logExcerpt}</pre></details>}{job.reconciliation&&<p className="record-footnote">原进程已确认结束,未知结果保留。重新启动需新计划。</p>}
</article>)}
{confirm&&<Modal title="确认项目预览" description="核对所属工作区和实际命令后启动。" onClose={()=>{if(!working)setConfirm(null);}}><div className="preview-confirm">
<p>工作区 <code>{confirm.root}</code></p><p>监听地址 <code>{confirm.url}</code> · 最长运行8小时</p>
<pre>{confirm.invocation.executable+'\n'+confirm.invocation.args.map(value=>JSON.stringify(value)).join('\n')}</pre>
<p>会执行该项目的 Vite 配置和插件代码。源码修改可以触发热更新;关闭浏览页后服务仍运行,需要使用「停止开发服务」。</p><p className="record-footnote">实际依赖 SHA-256 {confirm.nodeIdentity}</p>
{failure&&<p role="alert" className="preview-error">{failure}</p>}</div><div className="modal-actions"><button type="button" className="button secondary" disabled={!!working} onClick={()=>setConfirm(null)}>取消</button><button type="button" className="button primary" disabled={!!working} onClick={()=>perform('preview-jobs',{planId:confirm.id,fingerprint:confirm.fingerprint,approved:true})}><Check size={14}/>确认启动预览</button></div></Modal>}
</section>;
}
@@ -0,0 +1,30 @@
import { useEffect, useRef, useState } from 'react';
import { ArrowUp, Folder, LoaderCircle, RotateCw } from 'lucide-react';
import { api } from './api';
import './LocalFiles.css';
type Directory = { name: string; path: string };
type Listing = { current: string; parent: string | null; directories: Directory[]; bookmarks: Directory[]; truncated: boolean };
export function ProjectDirectoryPicker({ initialPath, onChoose, onCancel }: { initialPath: string; onChoose(path: string): void; onCancel(): void }) {
const [listing, setListing] = useState<Listing | null>(null), [busy, setBusy] = useState(true), [error, setError] = useState('');
const [location, setLocation] = useState(initialPath), [filter, setFilter] = useState('');
const request = useRef(0);
async function browse(path: string) {
const sequence = ++request.current; setBusy(true); setError('');
try {
const value = await api<Listing>('/local-directories?path=' + encodeURIComponent(path));
if (sequence === request.current) { setListing(value); setLocation(value.current); setFilter(''); }
} catch (cause) { if (sequence === request.current) setError(cause instanceof Error ? cause.message : '读取文件夹失败。'); }
finally { if (sequence === request.current) setBusy(false); }
}
useEffect(() => { void browse(initialPath); return () => { request.current++; }; }, []);
return <section className="directory-picker" aria-label="本机文件夹选择">
<div className="directory-location"><button type="button" className="icon-button" aria-label="上一级文件夹" disabled={busy || !listing?.parent} onClick={() => void browse(listing!.parent!)}><ArrowUp size={16} /></button><input aria-label="浏览文件夹路径" disabled={busy} value={location} onChange={event => setLocation(event.target.value)} onKeyDown={event => { if (event.key === 'Enter') { event.preventDefault(); void browse(location); } }} /><button type="button" className="button secondary" disabled={busy} onClick={() => void browse(location)}>前往</button><button type="button" className="icon-button" aria-label="刷新文件夹" disabled={busy} onClick={() => void browse(listing?.current || location)}><RotateCw size={15} /></button></div>
{listing && <nav className="directory-bookmarks" aria-label="常用位置">{listing.bookmarks.map(item => <button type="button" key={item.path} disabled={busy} onClick={() => void browse(item.path)}>{item.name}</button>)}</nav>}
{error && <p className="local-files-error" role="alert">{error}</p>}
<input className="directory-filter" aria-label="筛选子文件夹" placeholder="筛选当前目录下的文件夹" value={filter} onChange={event => setFilter(event.target.value)} />
<div className="directory-list" aria-busy={busy}>{busy ? <p role="status"><LoaderCircle className="spin" size={16} />正在读取文件夹…</p> : listing?.directories.filter(item => item.name.toLocaleLowerCase().includes(filter.toLocaleLowerCase())).map(item => <button type="button" key={item.path} onClick={() => void browse(item.path)}><Folder size={17} /><span>{item.name}</span></button>)}{!busy && listing && !listing.directories.filter(item => item.name.toLocaleLowerCase().includes(filter.toLocaleLowerCase())).length && <p>{filter ? '没有匹配的子文件夹。' : '此文件夹没有子文件夹,可以直接选择。'}</p>}</div>
{listing?.truncated && <p className="subtle">此处文件较多,已显示部分文件夹;可在上方输入完整路径。</p>}
<div className="directory-selection"><span title={listing?.current}>已定位:{listing?.current || '尚未选择'}</span><div><button type="button" className="button secondary" onClick={onCancel}>取消选择</button><button type="button" className="button primary" disabled={busy || !!error || !listing} onClick={() => onChoose(listing!.current)}>使用此文件夹</button></div></div>
</section>;
}
@@ -0,0 +1,3 @@
.project-memory{display:flex;flex-direction:column;min-height:0;background:#f8fafc;color:#15283f;padding:24px 28px;overflow:auto}.memory-overview{display:flex;align-items:flex-start;justify-content:space-between;gap:18px;padding-bottom:18px;border-bottom:1px solid #cbd5df}.memory-eyebrow{display:flex;align-items:center;gap:7px;color:#2560a3;letter-spacing:.13em;font-size:10px;font-weight:700}.memory-overview h3{font-size:22px;margin:8px 0 5px}.memory-overview p{color:#5b6d83;font-size:12px;line-height:1.8}.memory-summary{display:flex;gap:16px;flex-wrap:wrap;padding:13px 0;color:#5d7088;font-size:12px}.memory-summary strong{color:#15283f;font-size:16px;margin-right:4px}.memory-summary code{color:#33577f}.memory-list{display:grid;gap:11px}.memory-card{padding:17px 18px;background:#fff;border:1px solid #cbd6e2;border-left:3px solid #2f806e;border-radius:6px}.memory-card.memory-expired{border-left-color:#b4772b;background:#fffaf0}.memory-card.memory-archived{border-left-color:#8b9aaa;background:#f4f7fa;opacity:.82}.memory-card-heading{display:flex;align-items:center;gap:10px;flex-wrap:wrap}.memory-card-heading h4{font-size:14px;flex:1;min-width:130px}.memory-card-heading time{font-size:11px;color:#74859a}.memory-state{padding:3px 7px;border:1px solid #b9d9cb;border-radius:4px;color:#216d5f;background:#e6f3ee;font-size:10px;font-weight:650}.memory-expired .memory-state{color:#8b5c12;background:#fff4d9;border-color:#e6d09d}.memory-archived .memory-state{color:#67788d;background:#e9eef3;border-color:#d1dbe4}.memory-content{font-size:13px;line-height:1.8;white-space:pre-wrap;overflow-wrap:anywhere;margin-top:11px;color:#233b55}.memory-meta{display:flex;gap:8px;align-items:center;flex-wrap:wrap;margin-top:12px;color:#6a7d92;font-size:11px}.memory-meta code{font-size:10px;color:#7b8ca1}.memory-tag{padding:3px 6px;background:#edf3f8;color:#4e6884;border-radius:3px}.memory-warning{display:flex;align-items:flex-start;gap:6px;color:#8b5c12;font-size:11px;line-height:1.7;margin-top:11px}.memory-card>.text-button{padding:8px 0;margin-top:8px}.memory-notice,.memory-error{display:flex;gap:7px;align-items:flex-start;padding:11px 13px;margin:15px 0 0;border-radius:5px;font-size:12px;line-height:1.7}.memory-notice{color:#216d5f;background:#e6f3ee;border:1px solid #b9d9cb}.memory-error{color:#a7353e;background:#fff0f0;border:1px solid #e8bac0}.memory-empty{display:grid;place-items:center;padding:38px 20px;margin:7px 0 17px;background:#fff;border:1px dashed #b5c6d7;border-radius:7px;color:#61738a;text-align:center}.memory-empty svg{color:#6c87a5;margin-bottom:10px}.memory-empty strong{color:#314b68;font-size:14px}.memory-empty p{font-size:12px;line-height:1.8;margin-top:7px;max-width:480px}.memory-editor{padding:19px 20px;margin-top:18px;border:1px solid #b2c6da;border-top:3px solid #2560a3;border-radius:7px;background:#fff}.memory-editor-heading{display:flex;align-items:flex-start;justify-content:space-between;color:#2560a3}.memory-editor-heading h4{font-size:15px;color:#15283f}.memory-editor-heading p{font-size:11px;color:#687a90;margin-top:5px;line-height:1.7}.memory-form-grid{display:grid;grid-template-columns:1fr 1fr;gap:14px;margin-top:16px}.memory-form-grid label{display:flex;flex-direction:column;gap:7px;color:#4e637d;font-size:11px}.memory-form-grid input,.memory-form-grid textarea{border:1px solid #b9c8d6;border-radius:5px;padding:9px 10px;min-height:38px;font:inherit;color:#15283f;resize:vertical}.memory-form-grid input:focus,.memory-form-grid textarea:focus{outline:2px solid #2560a333;border-color:#2560a3}.memory-full{grid-column:1/-1}.memory-editor-footer{display:flex;align-items:center;justify-content:space-between;gap:15px;flex-wrap:wrap;margin-top:14px}.memory-editor-footer>span{display:flex;align-items:center;gap:6px;color:#67798e;font-size:11px}.memory-editor-footer svg{color:#2f806e}.project-memory button{min-height:36px}
@media(max-width:620px){.project-memory{padding:18px 15px}.memory-overview{flex-direction:column}.memory-form-grid{grid-template-columns:1fr}.memory-full{grid-column:auto}.memory-editor{padding:17px 14px}.memory-card{padding:15px 13px}.memory-card-heading time{width:100%}}
.memory-unverified .memory-state{color:#8a5b16;background:#fff7df;border-color:#ead39a}.memory-scope-warning{margin:14px 0;padding:12px 14px;line-height:1.7}
@@ -0,0 +1,52 @@
import { useEffect, useRef, useState } from 'react';
import type { FormEvent } from 'react';
import { Archive, Brain, CircleHelp, LoaderCircle, Plus, RefreshCw, ShieldCheck } from 'lucide-react';
import type { Project, ProjectMemory, ProjectMemoryView, Session } from './types';
import { api } from './api';
import './ProjectMemory.css';
const statusLabel: Record<string, string> = { current: '当前', unverified: '扫描不完整', expired: '已过期', archived: '已归档' };
export function ProjectMemoryPanel({ project, session }: { project: Project; session: Session | null }) {
const [view, setView] = useState<ProjectMemoryView | null>(null);
const [loading, setLoading] = useState(false);
const [working, setWorking] = useState(false);
const [notice, setNotice] = useState('');
const [error, setError] = useState('');
const [draft, setDraft] = useState({ title: '', content: '', sourcePath: '', tags: '', expiresAt: '' });
const alive = useRef(true);
const load = async () => {
setLoading(true); setError('');
try { const result = await api<ProjectMemoryView>('/projects/' + project.id + '/memories'); if (alive.current) setView(result); }
catch (cause) { if (alive.current) setError(cause instanceof Error ? cause.message : '项目记忆读取失败。'); }
finally { if (alive.current) setLoading(false); }
};
useEffect(() => { alive.current = true; void load(); return () => { alive.current = false; }; }, [project.id]);
const create = async (event: FormEvent) => {
event.preventDefault(); if (!session || !draft.content.trim()) return;
setWorking(true); setError(''); setNotice('');
try {
await api('/sessions/' + session.id + '/memories', { title: draft.title || '未命名记忆', content: draft.content, tags: draft.tags.split(',').map(value => value.trim()).filter(Boolean), ...(draft.sourcePath.trim() ? { source: { kind: 'file', path: draft.sourcePath.trim() } } : {}), ...(draft.expiresAt ? { expiresAt: new Date(draft.expiresAt).toISOString() } : {}) });
if (alive.current) { setDraft({ title: '', content: '', sourcePath: '', tags: '', expiresAt: '' }); setNotice('记忆已保存,并绑定当前源码指纹。'); await load(); }
} catch (cause) { if (alive.current) setError(cause instanceof Error ? cause.message : '项目记忆保存失败。'); }
finally { if (alive.current) setWorking(false); }
};
const archive = async (memory: ProjectMemory) => {
if (!session) return;
setWorking(true); setError('');
try { await api('/sessions/' + session.id + '/memories/' + memory.id + '/archive', {}); if (alive.current) { setNotice('已归档这条记忆。'); await load(); } }
catch (cause) { if (alive.current) setError(cause instanceof Error ? cause.message : '项目记忆归档失败。'); }
finally { if (alive.current) setWorking(false); }
};
const memories = view?.memories ?? [];
return <section className="project-memory" aria-label="项目记忆">
<header className="memory-overview"><div><span className="memory-eyebrow"><Brain size={14} />PROJECT MEMORY</span><h3>项目记忆</h3><p>当前记忆按预算提供给本项目后续任务;来源匹配后仍需结合实际代码核对内容。</p></div><button type="button" className="button secondary" onClick={() => void load()} disabled={loading || working}><RefreshCw size={14} className={loading ? 'spin' : ''} />重新核对</button></header>
{notice && <p className="memory-notice" role="status"><ShieldCheck size={14} />{notice}</p>}
{error && <p className="memory-error" role="alert">{error}</p>}
{view && <div className="memory-summary"><span><strong>{view.summary.current}</strong> 条当前记忆</span>{(view.summary.unverified ?? 0) > 0 && <span><strong>{view.summary.unverified}</strong> 条未能验证</span>}<span><strong>{view.summary.expired}</strong> 条需重新核对</span><span>源码 <code>{view.sourceFingerprint.slice(0, 12)}</code></span></div>}
{view && !view.scope.complete && <p className="memory-warning memory-scope-warning" role="status"><CircleHelp size={14} />本次源码扫描未覆盖完整工程(已扫描 {view.scope.scannedFiles} 个文件,{view.scope.bytes.toLocaleString()} 字节);现有记忆暂标为“扫描不完整”,不会作为当前事实。请缩小项目范围或排除超预算文件后重新核对。</p>}
{!memories.length && !loading && <div className="memory-empty"><Brain size={25} /><strong>这个项目还没有记忆</strong><p>保存架构决策、约束和经过核对的工程事实,后续任务可以直接查看来源。</p></div>}
<div className="memory-list">{memories.map(memory => <article key={memory.id} className={'memory-card memory-' + memory.status}><div className="memory-card-heading"><span className="memory-state">{statusLabel[memory.status] || memory.status}</span><h4>{memory.title}</h4><time>{new Date(memory.updatedAt).toLocaleString('zh-CN')}</time></div><p className="memory-content">{memory.content}</p><div className="memory-meta"><span>来源:{memory.source.kind === 'file' ? memory.source.path : memory.source.label || memory.source.kind}</span>{memory.source.sha256 && <code>来源 SHA {memory.source.sha256.slice(0, 12)}</code>}<code>工程 {memory.sourceFingerprint.slice(0, 12)}</code>{memory.tags.map(tag => <span className="memory-tag" key={tag}>{tag}</span>)}</div>{memory.expiredReason && <p className="memory-warning"><CircleHelp size={14} />{memory.expiredReason}</p>}{memory.status !== 'archived' && <button type="button" className="text-button" disabled={working || memory.sessionId !== session?.id} onClick={() => void archive(memory)}><Archive size={13} />归档</button>}</article>)}</div>
<form className="memory-editor" onSubmit={create}><div className="memory-editor-heading"><div><h4>保存一条项目记忆</h4><p>来源默认绑定当前会话;填写文件路径后会额外保存文件 SHA256。</p></div><Plus size={18} /></div><div className="memory-form-grid"><label>标题<input value={draft.title} onChange={event => setDraft({ ...draft, title: event.target.value })} maxLength={240} placeholder="例如:接口层必须保持本地鉴权" /></label><label>来源文件(可选)<input value={draft.sourcePath} onChange={event => setDraft({ ...draft, sourcePath: event.target.value })} placeholder="src/server/app.mjs" /></label><label>标签(逗号分隔)<input value={draft.tags} onChange={event => setDraft({ ...draft, tags: event.target.value })} placeholder="架构,约束" /></label><label>到期时间(可选)<input type="datetime-local" value={draft.expiresAt} onChange={event => setDraft({ ...draft, expiresAt: event.target.value })} /></label><label className="memory-full">内容<textarea required value={draft.content} onChange={event => setDraft({ ...draft, content: event.target.value })} maxLength={16000} rows={4} placeholder="记录可验证的事实、决策或限制……" /></label></div><div className="memory-editor-footer"><span><ShieldCheck size={14} />不会调用模型,也不会执行项目命令。</span><button type="submit" className="button primary" disabled={!session || working || !draft.content.trim() || Boolean(view && !view.scope.complete)}>{working ? <LoaderCircle size={14} className="spin" /> : <Plus size={14} />}保存记忆</button></div></form>
</section>;
}
@@ -0,0 +1,25 @@
.purge-strategy-control { border:1px solid #c7d3de; border-left:3px solid #626594; border-radius:6px; padding:15px; background:#f5f6fa; min-width:0; }
.purge-strategy-control > header { display:flex; align-items:center; flex-wrap:wrap; gap:9px; }
.purge-strategy-control > header > svg { color:#626594; flex-shrink:0; }
.worker-plan-form .purge-strategy-control > header label { display:flex; flex-direction:row; gap:8px; align-items:center; color:#243d54; font-size:13px; font-weight:600; }
.worker-plan-form .purge-strategy-control input[type=checkbox] { width:18px; height:18px; min-height:18px; accent-color:#626594; }
.purge-strategy-control > header > span { color:#626594; font-size:11px; margin-left:auto; }
.purge-strategy-control p { font-size:12px; line-height:1.7; margin:8px 0; color:#587087; }
.purge-strategy-fields { display:grid; gap:11px; margin-top:13px; min-width:0; }
.worker-console .purge-strategy-fields > button { justify-self:start; white-space:nowrap; min-height:42px; }
.purge-strategy-fields > small { color:#587087; font-size:11px; }
.purge-source-state { padding:12px; border:1px solid #c7d3de; background:white; border-radius:4px; min-width:0; }
.purge-source-state strong { font-size:12px; color:#243d54; }
.purge-source-state code,.purge-strategy-fields dd { overflow-wrap:anywhere; font:11px/1.7 'Cascadia Code',Consolas,monospace; color:#626594; }
.purge-strategy-fields details { font-size:12px; color:#587087; min-width:0; }
.purge-strategy-fields summary { cursor:pointer; }
.purge-strategy-fields dl > div { margin-top:8px; }
.purge-strategy-fields .purge-source-inputs { max-height:260px; overflow:auto; padding-right:8px; }
.purge-strategy-fields select { width:100%; min-height:42px; min-width:0; border:1px solid #b8c7d5; border-radius:4px; background:white; color:#243d54; padding:8px; }
.purge-strategy-fields dd { margin:4px 0 0; }
.purge-strategy-control .purge-source-error { color:#794d21; background:#fff8ee; padding:10px; border-left:3px solid #925619; overflow-wrap:anywhere; }
.engine-run-panel .engine-prompt-note { padding:12px; background:#f5f6fa; border-left:3px solid #626594; font-size:12px; line-height:1.7; }
.engine-prompt-note strong { color:#626594; }
.engine-prompt-note p { margin:5px 0 0; color:#587087; }
.engine-prompt-note pre { white-space:pre-wrap; overflow-wrap:anywhere; font-size:12px; line-height:1.7; }
@media(max-width:620px) { .purge-strategy-control { padding:12px; } .purge-strategy-control > header > span { margin-left:0; flex-basis:100%; } .worker-plan-form .purge-strategy-control > header label { min-height:42px; } }
@@ -0,0 +1,52 @@
import { useEffect, useRef, useState } from 'react';
import { FlaskConical, LoaderCircle, ShieldCheck } from 'lucide-react';
import { api } from './api';
import type { PurgeSourceAvailability } from './types';
import './PurgeStrategyControl.css';
export type PurgeDraft = { enabled: boolean; kind: 'purge-prompt-experiment' | 'purge-original-restricted-v1'; root: string; prompt: string; source: PurgeSourceAvailability | null };
export const emptyPurgeDraft = (): PurgeDraft => ({ enabled: false, kind: 'purge-prompt-experiment', root: '', prompt: '', source: null });
export const purgeStrategyInput = (value: PurgeDraft) => ({kind:value.kind,root:value.source?.root,sourceSha256:value.source?.sourceSha256,prompt:value.prompt,
...(value.kind==='purge-original-restricted-v1'?{runtimeSha256:value.source?.runtimeSha256}:{})});
export function purgeDraftReady(value: PurgeDraft) {
return !value.enabled || value.source?.status === 'available' && !!value.source.sourceSha256
&& (value.source.kind??'purge-prompt-experiment')===value.kind && (value.kind!=='purge-original-restricted-v1'||!!value.source.runtimeSha256)
&& !!value.prompt.trim() && new TextEncoder().encode(value.prompt).length <= 24000;
}
export function PurgeStrategyControl({ value, onChange, busy, harnessRoot }: { value: PurgeDraft; onChange: (value: PurgeDraft) => void; busy: boolean; harnessRoot?: string | null }) {
const [detecting, setDetecting] = useState(false), [error, setError] = useState('');
const request = useRef(0), current = useRef(value); current.current = value;
const previousHarness = useRef(harnessRoot);
useEffect(() => { if(previousHarness.current===harnessRoot)return;previousHarness.current=harnessRoot;request.current++;setDetecting(false);setError('');
if(current.current.kind==='purge-original-restricted-v1')onChange({...current.current,source:null}); }, [harnessRoot, onChange]);
useEffect(() => () => { request.current++; }, []);
function enabled(next: boolean) { request.current++; setDetecting(false); setError(''); onChange({ ...value, enabled: next }); }
function editRoot(root: string) { request.current++; setDetecting(false); setError(''); onChange({ ...value, root, source: null }); }
async function detect() {
const generation = ++request.current; setDetecting(true); setError(''); onChange({ ...current.current, source: null });
try {
const query=new URLSearchParams({kind:value.kind});if(value.root.trim())query.set('root',value.root.trim());if(value.kind==='purge-original-restricted-v1'&&harnessRoot)query.set('harnessRoot',harnessRoot);
const source = await api<PurgeSourceAvailability>('/engines/purge/source?'+query);
if (generation !== request.current) return;
onChange({ ...current.current, root: source.root ?? current.current.root, source, prompt: current.current.prompt || source.defaultPrompt });
} catch (failure) { if (generation === request.current) setError(failure instanceof Error ? failure.message : String(failure)); }
finally { if (generation === request.current) setDetecting(false); }
}
const original=value.kind==='purge-original-restricted-v1';
return <section className="purge-strategy-control" aria-label={original?'Purge 原版受限模式':'Purge 提示实验'}>
<header><FlaskConical size={17} /><label><input type="checkbox" checked={value.enabled} disabled={busy} onChange={event => enabled(event.target.checked)} />启用 Purge {original?'原版受限模式':'提示实验'}</label><span>{value.enabled ? '仅对本计划生效' : '默认关闭'}</span></header>
<p>{original?'运行原版 1.1.78 的固定受限配置,继续使用工作台的工具审批和累计预算。原版效果需另行实测。':'追加已封存的工程提示,继续使用原任务范围、检查审批和累计预算。实际收益需同题对照验证。'}</p>
{value.enabled && <div className="purge-strategy-fields">
<label>执行模式<select aria-label="Purge 执行模式" value={value.kind} disabled={busy} onChange={event=>{request.current++;setDetecting(false);setError('');onChange({...value,kind:event.target.value as PurgeDraft['kind'],source:null});}}>
<option value="purge-prompt-experiment">独立工程提示 · 不加载原版插件</option><option value="purge-original-restricted-v1">原版 1.1.78 · 固定受限配置</option>
</select></label>
<label>Purge 源码目录<input aria-label="Purge 源码目录" value={value.root} placeholder="留空检测已知来源,或填写绝对目录" disabled={busy} onChange={event => editRoot(event.target.value)} /></label>
<button type="button" className="button secondary" disabled={busy || detecting} onClick={() => void detect()}>{detecting ? <LoaderCircle className="spin" size={14} /> : <ShieldCheck size={14} />}检测 Purge 来源</button>
{value.source && <div className="purge-source-state" role="status"><strong>{value.source.status === 'available' ? '已核对 Purge ' + value.source.version : '来源尚不可用'}</strong><p>{value.source.message}</p>{value.source.sourceSha256 && <code>{value.source.sourceSha256}</code>}{original&&value.source.runtimeSha256&&<p>固定运行依赖 {value.source.runtimeInputs} 份 · <code>{value.source.runtimeSha256}</code></p>}</div>}
{error && <p className="purge-source-error" role="alert">{error}</p>}
<label>增强工程提示<textarea aria-label="增强工程提示" rows={5} maxLength={8000} value={value.prompt} disabled={busy} onChange={event => onChange({ ...value, prompt: event.target.value })} /></label>
<small>{new TextEncoder().encode(value.prompt).length.toLocaleString()} / 24,000 字节 · 完整文本随计划保存,运行期间不能替换。</small>
<details><summary>实验来源与执行范围</summary><p>{original?'YuJunZhiXue / dsh-purge(Apache-2.0)原版入口,完整来源和运行副本逐份核对。自动更新、宿主修改、原版工具、自动重试和继续关闭;内部提示及钩子仍由原版装配。这是固定可信源码的 Windows x64 配置,Node 权限不等同于操作系统沙箱。':'独立提示装配参考 YuJunZhiXue / dsh-purge(Apache-2.0)。不加载上游完整插件;实验不开启宿主修改、权限绕过或自动重试。'}</p>{value.source?.inputs && <dl className="purge-source-inputs">{value.source.inputs.map(input => <div key={input.relative}><dt>{input.relative}</dt><dd>{input.sha256}</dd></div>)}</dl>}</details>
</div>}
</section>;
}
@@ -0,0 +1,91 @@
import { useEffect, useState } from 'react';
import { Archive, BrainCircuit, FileText, LoaderCircle } from 'lucide-react';
import { api } from './api';
import { Modal } from './components';
import type { ContextHistory, ContextHistoryGroup, ContextPlan, Session } from './types';
const number = (value: number | undefined) => (value ?? 0).toLocaleString('zh-CN');
const states: Record<string, string> = { prepared: '已准备', requesting: '正在请求', completed: '已收到响应', failed: '请求失败', interrupted: '请求已中断' };
const toolNames: Record<string, string> = { read_file: '读取文件', read_artifact: '读取保存工件', inspect_project: '识别工程', inspect_session: '核对运行记录',
index_project: '建立符号索引', query_code: '定位代码', propose_patch: '精确补丁提案', propose_file: '文件提案', run_command: '终端命令', run_checks: '工程检查',
plan_checks: '检查计划', prepare_change_set: '封存变更集', plan_delivery: 'Git交付预览', delivery_report: '交付报告', list_files: '查看文件', search_files: '搜索文件' };
export function RequestContextPanel({ session, runId, openArtifact, onError }: {
session: Session; runId: string; openArtifact: (id: string) => void; onError: (error: unknown) => void;
}) {
const [historical, setHistorical] = useState<ContextPlan[]>([]);
const [selected, setSelected] = useState('');
const [historyId, setHistoryId] = useState('');
useEffect(() => {
let alive = true; setHistorical([]); setSelected(''); setHistoryId('');
if (runId && runId !== session.execution?.run?.id) {
api<ContextPlan[]>('/sessions/' + session.id + '/context-plans?run=' + runId).then(value => { if (alive) setHistorical(value); })
.catch(error => { if (alive) onError(error); });
}
return () => { alive = false; };
}, [session.id, runId, session.execution?.run?.id]);
const plans = runId === session.execution?.run?.id ? session.execution?.contextPlans?.filter(plan => plan.runId === runId) ?? []
: historical.filter(plan => plan.runId === runId && plan.sessionId === session.id);
const plan = plans.find(plan => plan.id === selected) ?? plans.at(-1);
if (!plan) return null;
const total = plan.estimatedInputTokens + plan.budget.outputReservation + plan.budget.safetyTokens;
return <section className="task-record-section request-context" aria-label="请求上下文">
<div className="record-heading"><BrainCircuit size={15} /><h3>请求上下文</h3><span>{states[plan.status] ?? plan.status}</span></div>
{plans.length > 1 && <label className="run-picker">查看一次模型请求<select aria-label="选择模型请求" value={plan.id} onChange={event => setSelected(event.target.value)}>
{plans.map((value, index) => <option key={value.id} value={value.id}>第 {value.requestIndex ?? index + 1} 次 · {states[value.status] ?? value.status}</option>)}
</select></label>}
<div className="context-meter" aria-label="估算上下文占用"><i style={{ width: Math.min(100, total / plan.budget.contextLimit * 100) + '%' }} /></div>
<dl className="record-fields"><dt>请求输入估算</dt><dd>{number(plan.estimatedInputTokens)} tokens</dd><dt>输出 / 安全余量</dt><dd>{number(plan.budget.outputReservation)} / {number(plan.budget.safetyTokens)} tokens</dd>
<dt>模型上下文窗口</dt><dd>{number(plan.budget.contextLimit)} tokens</dd><dt>已报告输入</dt><dd>{plan.actualUsage?.prompt_tokens === undefined ? '服务未返回' : number(plan.actualUsage.prompt_tokens) + ' tokens'}</dd>
<dt>历史记录</dt><dd>保留 {plan.retainedMessages} 条 · 保存 {plan.archivedGroups} 组原记录</dd>
{!!plan.workingSetEntries && <><dt>当前任务依据</dt><dd>{plan.workingSetEntries} 项代码与执行结果</dd></>}
{!!plan.projectMemoryEntries && <><dt>项目记忆</dt><dd>{plan.projectMemoryEntries} 条来源已核对的记录</dd></>}
{!!plan.skillCatalogEntries && <><dt>技能目录</dt><dd>{plan.skillCatalogEntries} 项本次目录记录</dd></>}
<dt>发送内容</dt><dd>{number(plan.requestBytes)} B<code className="context-sha" title={plan.requestSha256}>{plan.requestSha256.slice(0, 16)}</code></dd>
</dl>
<p className="record-footnote">估算包含系统提示、工具定义和历史。任务要求完整保留;省略的原记录可从本机工件检索。实际用量以模型服务为准。</p>
{plan.error && <p className="run-stop">{plan.error}</p>}
<div className="context-actions"><button type="button" className="text-button" onClick={() => openArtifact(plan.requestArtifactId)}><FileText size={13} />查看发送内容</button>
<button type="button" className="text-button" onClick={() => openArtifact(plan.artifactId)}><FileText size={13} />查看请求计划</button>
{plan.workingSetArtifactId && <button type="button" className="text-button" onClick={() => openArtifact(plan.workingSetArtifactId!)}><BrainCircuit size={13} />查看工作依据</button>}
{plan.latestToolsArtifactId && <button type="button" className="text-button" onClick={() => openArtifact(plan.latestToolsArtifactId!)}><FileText size={13} />查看最近工具反馈</button>}
{plan.projectMemoryArtifactId && <button type="button" className="text-button" onClick={() => openArtifact(plan.projectMemoryArtifactId!)}><BrainCircuit size={13} />查看本次项目记忆</button>}
{plan.skillCatalogArtifactId && <button type="button" className="text-button" onClick={() => openArtifact(plan.skillCatalogArtifactId!)}><FileText size={13} />查看本次技能目录</button>}
{!!plan.archivedGroups && <button type="button" className="text-button" onClick={() => setHistoryId(plan.id)}><Archive size={13} />检索完整历史</button>}</div>
{historyId && <HistoryModal key={session.id + ':' + historyId} sessionId={session.id} planId={historyId} onError={onError}
onClose={() => setHistoryId('')} openArtifact={id => { setHistoryId(''); openArtifact(id); }} />}
</section>;
}
function groupTitle(group: ContextHistoryGroup) {
if (group.tools?.length) return group.tools.map(tool => toolNames[tool.name] ?? tool.name).join(' · ');
return group.roles[0] === 'user' ? '用户要求' : '助手记录';
}
function HistoryModal({ sessionId, planId, onClose, openArtifact, onError }: {
sessionId: string; planId: string; onClose: () => void; openArtifact: (id: string) => void; onError: (error: unknown) => void;
}) {
const [history, setHistory] = useState<ContextHistory | null>(null), [offset, setOffset] = useState(0), [loading, setLoading] = useState(false);
useEffect(() => {
let alive = true; setLoading(true);
api<ContextHistory>('/sessions/' + sessionId + '/context-plans/' + planId + '/history?offset=' + offset + '&limit=12')
.then(value => { if (alive) setHistory(value); }).catch(error => { if (alive) onError(error); }).finally(() => { if (alive) setLoading(false); });
return () => { alive = false; };
}, [sessionId, planId, offset]);
return <Modal title="完整历史记录" description="这些记录已从本次请求中省略,原始参数和实际结果仍保存在本机。读取记录不会执行工具。" wide onClose={onClose}>
<div className="context-history-list" aria-busy={loading}>{loading ? <p className="record-empty"><LoaderCircle size={15} className="spin" />正在核对历史工件</p>
: history?.groups.map(group => <article className="context-history-group" key={group.index}>
<div><strong>{groupTitle(group)}</strong><small>原消息 {group.startMessage + 1}–{group.endMessage + 1}</small></div>
<code className="context-sha" title={group.sha256}>SHA256 {group.sha256.slice(0, 20)}</code>
{!!group.archive.chunks && <p>原记录较大,已保存 {group.archive.chunks} 份可核验分片。</p>}
{group.tools?.map(tool => <div className="context-history-tool" key={tool.call_id}><span>{toolNames[tool.name] ?? tool.name}</span><code>{tool.call_id}</code>
{(tool.requires_verification || tool.result.requires_verification || tool.result.status === 'unknown') && <span className="context-unknown">结果需核对</span>}
{tool.result.path && <small>{tool.result.path}</small>}{tool.result_artifact_id && <button type="button" className="text-button" onClick={() => openArtifact(tool.result_artifact_id!)}>读取工具结果</button>}
</div>)}
<button type="button" className="text-button" onClick={() => openArtifact(group.archive.artifact_id)}><FileText size={13} />读取原记录</button>
</article>)}</div>
<div className="artifact-pagination"><span>记录 {history ? Math.min(history.totalGroups, history.offset + 1) + '–' + Math.min(history.totalGroups, history.offset + history.groups.length) + ' / ' + history.totalGroups : '正在读取'}</span>
<button type="button" className="button secondary" disabled={loading || offset === 0} onClick={() => setOffset(Math.max(0, offset - 12))}>上一页</button>
<button type="button" className="button secondary" disabled={loading || !history?.truncated} onClick={() => setOffset(offset + 12)}>下一页</button></div>
</Modal>;
}
@@ -0,0 +1,69 @@
import { useState } from 'react';
import { Modal } from './components';
import type { RequirementDraft, RequirementItem, RequirementView, TaskPlanStep } from './types';
export const requirementRoles = { requirement: '业务要求', reference: '参考资料', prohibition: '禁止事项', unknown: '待澄清' };
const kinds: Record<TaskPlanStep['kind'], string> = { analysis: '研究与读取', changes: '已应用改动', results: '当前文件', checks: '工程检查', browser: '页面断言' };
export const requirementInput = (row: RequirementItem) => ({ key: row.key, title: row.title, criterion: row.criterion,
...(row.role ? { role: row.role } : {}), kind: row.kind, method: row.method,
source: { kind: row.source.kind, id: row.source.id, start: row.source.start, end: row.source.end },
...(row.method === 'scope' ? {} : row.kind === 'analysis' ? { tools: row.tools } : ['changes', 'results'].includes(row.kind) ? { paths: row.paths }
: row.kind === 'checks' ? { checks: row.checks } : { viewport_width: row.viewport_width, actions: row.actions }) });
const evidenceScope = (kind: TaskPlanStep['kind']) => kind === 'analysis' ? { tools: ['read_file'] } : ['changes', 'results'].includes(kind)
? { paths: [] } : kind === 'checks' ? { checks: ['test', 'build'] } : { viewport_width: 1280, actions: ['assert_visible'] };
export function changeRequirementRole(row: RequirementItem, role: NonNullable<RequirementItem['role']>): RequirementItem {
const { tools, paths, checks, actions, viewport_width, ...base } = row;
return role === 'requirement' ? { ...base, role, method: 'evidence', kind: 'analysis', tools: ['read_file'] }
: { ...base, role, kind: 'analysis', method: 'scope' };
}
export function RequirementScopeFields({ row, change, prefix = '' }: { row: RequirementItem; change: (row: RequirementItem) => void; prefix?: string }) {
const updateKind = (kind: TaskPlanStep['kind']) => {
const { tools, paths, checks, actions, viewport_width, ...base } = row;
change({ ...base, kind, ...evidenceScope(kind) });
};
return <>
<label>内容用途<select aria-label={prefix + '内容用途'} value={row.role ?? 'requirement'} onChange={event => change(changeRequirementRole(row, event.target.value as NonNullable<RequirementItem['role']>))}>
{Object.entries(requirementRoles).map(([key, value]) => <option key={key} value={key}>{value}</option>)}</select></label>
{row.method === 'scope' ? <p className="record-footnote">{row.role === 'unknown' ? '尚未确定用途,保存后仍阻止要求复核完成。' : row.role === 'reference' ? '只记录参考用途,不要求修改此文件,也不计为交付成果。' : '保留用户边界供执行和复核使用;记录边界不等于已证明遵守。既有操作审批仍保留。'}</p> : <>
<label>复核方式<select aria-label={prefix + '要求复核方式'} value={row.method} onChange={event => {
const method = event.target.value as RequirementItem['method'];
const { tools, paths, checks, actions, viewport_width, ...base } = row;
change(method === 'not_requested' ? { ...base, method, kind: 'checks', checks: ['test', 'build'] }
: method === 'user' ? { ...base, method, kind: 'analysis', tools: ['read_file'] } : { ...row, method });
}}><option value="evidence">核对实际证据</option><option value="user">用户体验确认</option><option value="not_requested">按用户约定不执行检查</option></select></label>
{row.method === 'evidence' && <><label>证据类别<select aria-label={prefix + '要求证据类别'} value={row.kind} onChange={event => updateKind(event.target.value as TaskPlanStep['kind'])}>{Object.entries(kinds).map(([key, value]) => <option key={key} value={key}>{value}</option>)}</select></label>
{['results', 'changes'].includes(row.kind) && <label>文件范围(每行一项)<textarea aria-label={prefix + '要求文件范围'} required value={row.paths?.join('\n') ?? ''} onChange={event => change({ ...row, paths: event.target.value.split('\n').filter(Boolean) })} /></label>}
{row.kind === 'analysis' && <label>读取工具(逗号分隔)<input aria-label={prefix + '要求读取工具'} required value={row.tools?.join(',') ?? ''} onChange={event => change({ ...row, tools: event.target.value.split(',').map(value => value.trim()) })} /></label>}
{row.kind === 'checks' && <label>检查名称(逗号分隔)<input aria-label={prefix + '要求检查名称'} required value={row.checks?.join(',') ?? ''} onChange={event => change({ ...row, checks: event.target.value.split(',').map(value => value.trim()) })} /></label>}
{row.kind === 'browser' && <label>验收视口<select aria-label={prefix + '要求验收视口'} value={row.viewport_width} onChange={event => change({ ...row, viewport_width: Number(event.target.value) })}><option value={1280}>桌面 · 1280px</option><option value={390}>手机 · 390px</option></select></label>}</>}
</>}
</>;
}
export function RequirementDraftEditor({ value, view, saving, submit, close }: { value: RequirementDraft; view: RequirementView; saving: boolean;
submit: (input: object) => void; close: () => void }) {
const [rows, setRows] = useState<RequirementItem[]>(value.proposal.items.map(row => ({ ...row, role: 'unknown', kind: 'analysis', method: 'scope', depends_on: [] })));
const [reviewed, setReviewed] = useState(false);
const count = view.items.length + rows.filter(row => !view.items.some(old => old.key === row.key)).length;
return <Modal title="审阅原文草案" description="草案只整理原文。逐项确定用途、验收方式和范围后保存;待澄清内容继续保留。" wide onClose={() => { if (!saving) close(); }}>
<form className="plan-editor requirement-editor requirement-draft-editor" onSubmit={event => {
event.preventDefault(); const keys = new Set(rows.map(row => row.key));
submit({ draft_id: value.id, source_set_sha256: value.sourceSetSha256,
reviewed_source_ids: [...new Set([...view.sources.filter(row => !view.unreviewed_sources?.includes(row.id)).map(row => row.id), ...value.proposal.covered_source_ids])],
requirements: [...view.items.filter(row => !keys.has(row.key)).map(requirementInput), ...rows.map(requirementInput)] });
}}>
<p className="record-footnote">{value.proposal.note}</p>
{value.proposal.truncated && <p role="alert" className="plan-problem">草案达到保留上限,部分原文未收录。未完整收录的来源仍保持未审阅,请分小任务或手动核对。</p>}
{count > 24 && <p role="alert" className="plan-problem">合计 {count} 项,超过24项上限。请取消并逐项手动审阅,原草案与旧要求均保留。</p>}
<fieldset disabled={saving} className="requirement-draft-items">{rows.map((row, i) => <section className="plan-editor-step" key={row.key} aria-label={`草案条目 ${i + 1}`}>
<p className="requirement-draft-origin">{row.source.kind === 'goal' ? '原目标' : '追加要求'} · [{row.source.start}, {row.source.end})</p>
<blockquote className="requirement-quote">{row.source.quote}</blockquote>
<label>名称<input aria-label={`草案名称 ${i + 1}`} required maxLength={100} value={row.title} onChange={event => setRows(values => values.map((item, index) => index === i ? { ...item, title: event.target.value } : item))} /></label>
<label>验收条件或范围说明<textarea aria-label={`草案条件 ${i + 1}`} required maxLength={300} rows={2} value={row.criterion} onChange={event => setRows(values => values.map((item, index) => index === i ? { ...item, criterion: event.target.value } : item))} /></label>
<RequirementScopeFields row={row} prefix={`草案${i + 1} `} change={next => setRows(values => values.map((item, index) => index === i ? next : item))} />
</section>)}</fieldset>
<label className="requirement-review-check"><input type="checkbox" required checked={reviewed} disabled={saving} onChange={event => setReviewed(event.target.checked)} />已核对所收录的原文和分类;未确定内容保留为待澄清。</label>
<div className="modal-actions"><button type="button" className="button secondary" disabled={saving} onClick={close}>取消</button><button className="button primary" disabled={saving || !reviewed || count > 24}>审阅并保存</button></div>
</form>
</Modal>;
}
@@ -0,0 +1,26 @@
.requirement-list { list-style: none; padding: 0; margin: 0; }
.requirement-list > li { padding: 14px 0; border-top: 1px solid #dce7e2; font-size: 12px; line-height: 1.65; overflow-wrap: anywhere; }
.requirement-heading { display: flex; justify-content: space-between; align-items: baseline; gap: 10px; }
.requirement-heading strong { font-size: 13px; }
.requirement-role, .requirement-draft-origin { color: #526a70; font-size: 11px; margin: 4px 0; }
.requirement-draft-items { border: 0; margin: 0; padding: 0; min-width: 0; }
.requirement-draft-editor .plan-editor-step { border-top: 1px solid #dce7e2; padding-top: 14px; margin-top: 14px; }
.requirement-review-check { display: flex !important; align-items: flex-start; gap: 9px; font-size: 12px; padding: 12px 0; line-height: 1.7; }
.requirement-review-check input { width: auto !important; margin-top: 4px; flex-shrink: 0; }
.requirement-reference_recorded, .requirement-boundary_recorded { color: #526a70; background: #eef1f4; }
.requirement-panel .plan-toolbar { flex-wrap: wrap; }
.requirement-state { color: #674917; background: #fbf2df; padding: 2px 6px; border-radius: 3px; flex-shrink: 0; font-size: 11px; }
.requirement-evidence_verified, .requirement-user_confirmed { color: #154b4a; background: #edf3f1; }
.requirement-list summary, .requirement-history summary { cursor: pointer; color: #526a70; }
.requirement-list blockquote, .requirement-quote { margin: 9px 0; border-left: 2px solid #bbcfc7; padding: 6px 12px; white-space: pre-wrap; font-size: 12px; max-height: 150px; overflow: auto; }
.requirement-list code { font-size: 10px; overflow-wrap: anywhere; }
.requirement-actions { display: flex; flex-wrap: wrap; gap: 12px; margin: 7px 0; }
.requirement-confirm label { display: grid; gap: 6px; }
.requirement-confirm textarea { width: 100%; box-sizing: border-box; font: inherit; padding: 8px; border: 1px solid #cbded3; border-radius: 5px; margin-bottom: 8px; }
.requirement-history { font-size: 11px; margin-top: 12px; }
.requirement-history p { display: grid; gap: 4px; }
.requirement-editor { max-height: 72vh; overflow: auto; }
.requirement-offsets { display: flex; gap: 12px; margin: 12px 0; }
.requirement-offsets label { min-width: 0; font-size: 12px; }
.requirement-panel button:focus-visible, .requirement-panel textarea:focus-visible, .requirement-editor :is(input, select, textarea):focus-visible { outline: 2px solid #4664d9; outline-offset: 2px; }
@media (max-width: 600px) { .requirement-heading { flex-direction: column; gap: 4px; } .requirement-panel .button, .requirement-editor button, .requirement-editor select { min-height: 44px; } }
@@ -0,0 +1,100 @@
import { useEffect, useRef, useState } from 'react';
import { Check, FileText, Plus, RefreshCw, ListChecks } from 'lucide-react';
import { api } from './api';
import { Modal } from './components';
import type { RequirementDraft, RequirementItem, RequirementView, Session, TaskPlanStep } from './types';
import { RequirementDraftEditor, RequirementScopeFields, requirementInput as clean, requirementRoles } from './RequirementDraftEditor';
import './RequirementPanel.css';
import { requirementStates as states } from '../shared/contracts/task-follow-up.mjs';
const kinds: Record<TaskPlanStep['kind'], string> = { analysis: '研究与读取', changes: '已应用改动', results: '当前文件', checks: '工程检查', browser: '页面断言' };
const scope = (kind: TaskPlanStep['kind']) => kind === 'analysis' ? { tools: ['read_file'] } : ['changes', 'results'].includes(kind)
? { paths: [] } : kind === 'checks' ? { checks: ['test', 'build'] } : { viewport_width: 1280, actions: ['assert_visible'] };
export function RequirementPanel({ session, busy, onSession, onError, openArtifact }: {
session: Session; busy: boolean; onSession: (value: Session) => void; onError: (error: unknown) => void; openArtifact: (id: string) => void;
}) {
const task = session.execution?.task, run = session.execution?.run;
const identity = `${session.projectId}/${session.id}/${task?.id}/${run?.id}`;
const selected = useRef(identity); selected.current = identity;
const generation = useRef(0), mutation = useRef(false);
const [view, setView] = useState<RequirementView | null>(null), [loading, setLoading] = useState(false), [saving, setSaving] = useState(false);
const [draft, setDraft] = useState<RequirementItem | null>(null), [picked, setPicked] = useState<Record<string, string>>({}), [notes, setNotes] = useState<Record<string, string>>({});
const [proposal, setProposal] = useState<RequirementDraft | null>(null);
const [notice, setNotice] = useState('');
const disabled = busy || saving || ['running', 'awaiting_approval', 'stopping'].includes(session.status);
useEffect(() => { generation.current++; setView(null); setDraft(null); setProposal(null); setPicked({}); setNotes({}); setNotice(''); setSaving(false); mutation.current = false;
return () => { generation.current++; }; }, [identity]);
useEffect(() => { const timer = setTimeout(() => { void load(); }, 120); return () => clearTimeout(timer); }, [identity, session.revision, session.status]);
async function load() {
if (!task || mutation.current) return;
const scopeId = identity, request = ++generation.current; setLoading(true);
try { const result = await api<RequirementView>(`/sessions/${session.id}/requirements?taskId=${task.id}`);
if (selected.current === scopeId && generation.current === request) setView(result);
} catch (error) { if (selected.current === scopeId && generation.current === request) onError(error); }
finally { if (selected.current === scopeId && generation.current === request) setLoading(false); }
}
async function mutate(action: string, input: object) {
if (!task || !run || !view || mutation.current) return;
mutation.current = true; generation.current++; setSaving(true); setNotice(''); const scopeId = identity;
try {
const reply = await api<{ session: Session; requirements: RequirementView; draft?: RequirementDraft; verification?: { status: string; message?: string } }>(`/sessions/${session.id}/${action}`,
{ taskId: task.id, runId: run.id, expected_revision: view.revision, ...input });
if (selected.current !== scopeId) return;
setView(reply.requirements); onSession(reply.session);
setNotice(reply.verification?.status === 'error' ? reply.verification.message ?? '复核未通过,原失败已保留。' : action === 'requirements' ? '要求与原文来源已保存。' : action === 'requirement-drafts' ? '草案已整理,尚未成为要求或完成依据。' : '本次复核已记录。');
if (reply.draft) setProposal(reply.draft);
if (action === 'requirements') { setDraft(null); setProposal(null); }
} catch (error) { if (selected.current === scopeId) onError(error); }
finally { if (selected.current === scopeId) { mutation.current = false; setSaving(false); setLoading(false); } }
}
function edit(row?: RequirementItem) {
const source = view?.sources[0]; if (!source) return;
setDraft(row ? { ...clean(row), depends_on: [] } : { key: 'req_' + crypto.randomUUID().slice(0, 8), title: '', criterion: '', kind: 'analysis', method: 'evidence',
source: { kind: source.kind, id: source.id, start: 0, end: source.text.length }, depends_on: [], ...scope('analysis') });
}
const source = view?.sources.find(row => row.id === draft?.source.id && row.kind === draft?.source.kind);
return <section className="task-record-section requirement-panel" aria-label="要求与证据">
<div className="record-heading"><h3>要求与证据</h3><span>{view?.items.length ?? 0} 项</span></div>
<p className="record-footnote">逐项保留用户原文与实际依据,工程证据和用户体验分别记录。</p>
<div className="plan-toolbar"><button className="text-button" disabled={loading || disabled} onClick={() => void load()}><RefreshCw size={13} />刷新复核</button>
<button className="button secondary" disabled={disabled || !view || view.status === 'unverified'} onClick={() => void mutate('requirement-drafts', { source_set_sha256: view!.source_set_sha256 })}><ListChecks size={13} />从原文整理草案</button>
<button className="button secondary" disabled={disabled || !view || view.status === 'unverified' || (view.items.length >= 24)} onClick={() => edit()}><Plus size={13} />记录要求</button></div>
{notice && <p className="plan-notice" role="status">{notice}</p>}
{view?.error && <p className="plan-problem" role="alert">{view.error}</p>}
{!!view?.unreviewed_sources?.length && <p className="plan-problem">有 {view.unreviewed_sources.length} 份用户来源尚未审阅。核对原目标和追加要求后保存要求;旧复核记录保留。</p>}
{view && !view.items.length && <p className="record-empty">尚未逐项记录要求。模型的完成答复保留在原会话中。</p>}
<ol className="requirement-list">{view?.items.map(row => <li key={row.key}>
<div className="requirement-heading"><strong>{row.title}</strong><span className={'requirement-state requirement-' + row.status}>{states[row.status ?? 'pending'] ?? row.status}</span></div>
<p className="requirement-role">{requirementRoles[row.role ?? 'requirement']}{row.method !== 'scope' ? ' · ' + kinds[row.kind] + (row.paths?.length ? ' · ' + row.paths.join('、') : '') : ''}</p>
<p>{row.criterion}</p>
<details><summary>用户原文 · {row.source.kind === 'goal' ? '原目标' : '追加要求'} · 要求修订 {row.revision}</summary>
<blockquote>{row.source.quote}</blockquote><code>{row.source.id} [{row.source.start}, {row.source.end})</code></details>
{row.error && <p className="plan-problem">{row.error}</p>}{row.last_rejection && <p className="plan-problem">原复核失败:{row.last_rejection.message}</p>}
{row.user_note && <p>用户确认:{row.user_note}</p>}
<div className="requirement-actions"><button className="text-button" disabled={disabled} onClick={() => edit(row)}>修订此要求</button>
{row.proof_artifact_id && <button className="text-button" onClick={() => openArtifact(row.proof_artifact_id!)}><FileText size={13} />原复核记录</button>}</div>
{row.method === 'evidence' && <div className="plan-evidence"><label>选择实际依据 · {kinds[row.kind]}<select aria-label={`要求依据 ${row.title}`} disabled={disabled} value={picked[row.key] ?? ''} onChange={event => setPicked(values => ({ ...values, [row.key]: event.target.value }))}>
<option value="">选择此任务的原结果</option>{row.candidates?.map(candidate => <option key={candidate.id} value={candidate.id}>{candidate.label} · {candidate.status} · {candidate.id.slice(0, 8)}</option>)}</select></label>
<button className="button secondary" disabled={disabled || !picked[row.key]} onClick={() => void mutate('requirement-proofs', { key: row.key, evidence_id: picked[row.key] })}><Check size={13} />复核所选证据</button></div>}
{row.method === 'user' && <div className="requirement-confirm"><label>实际体验与结论<textarea aria-label={`用户确认 ${row.title}`} rows={2} maxLength={1000} disabled={disabled} value={notes[row.key] ?? ''} onChange={event => setNotes(values => ({ ...values, [row.key]: event.target.value }))} /></label>
<button className="button secondary" disabled={disabled || !notes[row.key]?.trim()} onClick={() => void mutate('requirement-proofs', { key: row.key, note: notes[row.key] })}>记录用户确认</button></div>}
{row.method === 'not_requested' && <p className="record-footnote">检查未执行,不计为测试通过。</p>}
{row.method === 'scope' && <p className="record-footnote">{row.role === 'unknown' ? '请先澄清原文的用途或验收范围。' : row.role === 'reference' ? '参考资料不计为需要修改或交付的文件。' : '仅记录禁止事项;是否遵守仍需实际证据,不代表验收通过。'}</p>}
</li>)}</ol>
{!!view?.history?.length && <details className="requirement-history"><summary>原复核历史 · {view.history.length} 条</summary>{view.history.map(row => <p key={row.id}><button className="text-button" onClick={() => openArtifact(row.artifact_id)}>{row.key} · 修订 {row.revision} · {row.status === 'rejected' ? '未通过' : '已记录'}</button>{row.error && <span>{row.error}</span>}</p>)}</details>}
{draft && view && <Modal title="记录用户要求" description="选定用户原文、验收范围和复核方式;修订保留旧要求与原失败。" wide onClose={() => { if (!saving) setDraft(null); }}>
<form className="plan-editor requirement-editor" onSubmit={event => { event.preventDefault(); const rows = view.items.some(row => row.key === draft.key) ? view.items.map(row => row.key === draft.key ? clean(draft) : clean(row)) : [...view.items.map(clean), clean(draft)]; void mutate('requirements', { requirements: rows, source_set_sha256: view.source_set_sha256,
reviewed_source_ids: [...new Set([...view.sources.filter(row => !view.unreviewed_sources?.includes(row.id)).map(row => row.id), ...(source && draft.source.start === 0 && draft.source.end === source.text.length ? [source.id] : [])])] }); }}>
<fieldset disabled={saving} className="plan-editor-step">
<label>要求名称<input aria-label="要求名称" maxLength={100} required value={draft.title} onChange={event => setDraft({ ...draft, title: event.target.value })} /></label>
<label>验收条件<textarea aria-label="要求验收条件" rows={2} required maxLength={300} value={draft.criterion} onChange={event => setDraft({ ...draft, criterion: event.target.value })} /></label>
<label>用户原文来源<select aria-label="要求原文来源" value={draft.source.id} onChange={event => { const row = view.sources.find(value => value.id === event.target.value)!; setDraft({ ...draft, source: { kind: row.kind, id: row.id, start: 0, end: row.text.length } }); }}>{view.sources.map((row, i) => <option key={row.id} value={row.id}>{row.kind === 'goal' ? '原目标' : `追加要求 ${i}`} · {row.text.slice(0, 65)}</option>)}</select></label>
<blockquote className="requirement-quote">{source?.text.slice(draft.source.start, draft.source.end)}</blockquote>
<div className="requirement-offsets"><label>原文起点<input aria-label="原文起点" type="number" min={0} max={Math.max(0, (source?.text.length ?? 1) - 1)} value={draft.source.start} onChange={event => setDraft({ ...draft, source: { ...draft.source, start: Number(event.target.value) } })} /></label><label>原文终点<input aria-label="原文终点" type="number" min={draft.source.start + 1} max={source?.text.length} value={draft.source.end} onChange={event => setDraft({ ...draft, source: { ...draft.source, end: Number(event.target.value) } })} /></label></div>
<RequirementScopeFields row={draft} change={setDraft} />
</fieldset><div className="modal-actions"><button type="button" className="button secondary" disabled={saving} onClick={() => setDraft(null)}>取消</button><button className="button primary" disabled={saving}>保存要求</button></div>
</form></Modal>}
{proposal && view && <RequirementDraftEditor value={proposal} view={view} saving={saving} close={() => setProposal(null)} submit={input => void mutate('requirements', input)} />}
</section>;
}
@@ -0,0 +1,82 @@
.rea-panel { color: var(--ink); min-width: 0; }
.rea-heading { display: flex; justify-content: space-between; align-items: flex-start; gap: 24px; margin-bottom: 22px; }
.rea-heading > div:first-child { max-width: 570px; }
.rea-eyebrow { color: var(--teal); font-size: 11px; letter-spacing: .04em; }
.rea-heading h3 { font-size: 23px; letter-spacing: -.04em; line-height: 1.4; margin: 5px 0 8px; font-weight: 650; }
.rea-heading p, .rea-hint, .rea-empty { color: var(--muted); font-size: 12px; line-height: 1.8; }
.rea-availability { display: flex; align-items: flex-end; flex-direction: column; gap: 9px; flex-shrink: 0; padding-top: 5px; }
.rea-availability > span { color: #8b5734; font-size: 11px; padding: 5px 9px; border: 1px solid #e8dccc; border-radius: 5px; }
.rea-availability > span.found { color: var(--teal); border-color: #c6ded4; background: #eff7f3; }
.rea-install-note { padding: 12px 15px; border: 1px solid #e6d6c4; background: #fbf6ee; line-height: 1.8; margin-bottom: 18px; }
.rea-grid { display: grid; grid-template-columns: minmax(240px, .82fr) minmax(0, 1.45fr); gap: 24px; }
.rea-registration, .rea-results { min-width: 0; }
.rea-registration form { padding: 18px; background: var(--paper); border: 1px solid var(--line); border-radius: 7px; }
.rea-panel h4 { font-size: 13px; font-weight: 650; display: flex; gap: 8px; align-items: center; margin-bottom: 14px; }
.rea-registration form .form-field { margin-bottom: 14px; }
.rea-registration textarea { resize: vertical; min-height: 77px; width: 100%; border: 1px solid var(--line); border-radius: 6px; background: #fff; padding: 10px 11px; color: var(--ink); font-size: 12px; line-height: 1.7; }
.rea-hint { margin: -2px 0 15px; }
.rea-targets { padding-top: 21px; }
.rea-targets h4 span { color: var(--muted); font-size: 11px; font-weight: 400; }
.rea-target { border-top: 1px solid var(--line); padding: 14px 0 16px; min-width: 0; }
.rea-target strong { display: block; font-size: 12px; }
.rea-target small { display: block; overflow-wrap: anywhere; color: var(--muted); line-height: 1.65; margin: 7px 0; }
.rea-target > code { display: block; color: #526a66; font-size: 10px; overflow-wrap: anywhere; line-height: 1.65; }
.rea-target-actions { display: flex; gap: 8px; margin-top: 12px; align-items: center; }
.rea-target-actions select { min-width: 0; flex: 1; padding: 7px 8px; border: 1px solid var(--line); border-radius: 5px; background: var(--paper); font-size: 11px; }
.rea-results-heading { display: flex; align-items: flex-start; justify-content: space-between; gap: 12px; }
.rea-empty-result { border: 1px dashed #cbdcd3; padding: 42px 24px; display: flex; flex-direction: column; align-items: flex-start; color: var(--muted); gap: 12px; border-radius: 7px; }
.rea-empty-result strong { color: var(--ink); font-size: 15px; font-weight: 550; }
.rea-empty-result p { line-height: 1.8; font-size: 12px; max-width: 380px; }
.rea-job { border: 1px solid var(--line); background: var(--paper); padding: 17px; border-radius: 7px; margin-bottom: 13px; min-width: 0; }
.rea-job.verified { border-left: 3px solid #5b9886; padding-left: 15px; }
.rea-job-heading { display: flex; justify-content: space-between; align-items: flex-start; gap: 12px; }
.rea-job-heading > div { min-width: 0; }
.rea-job-heading strong { font-size: 13px; display: block; overflow-wrap: anywhere; }
.rea-job-heading > div > span { font-size: 11px; color: var(--muted); display: block; margin-top: 5px; }
.rea-job-state { display: inline-flex; align-items: center; gap: 5px; font-size: 10px; color: #766449; flex-shrink: 0; padding-top: 2px; }
.rea-job-state.completed { color: var(--teal); }
.rea-job-state.failed, .rea-job-state.stale, .rea-job-state.unknown { color: #a34d35; }
.rea-job-summary { color: var(--muted); line-height: 1.85; margin: 13px 0; font-size: 12px; overflow-wrap: anywhere; }
.rea-source-chain { display: flex; align-items: center; justify-content: space-between; gap: 7px; border-top: 1px solid #e3ece7; border-bottom: 1px solid #e3ece7; padding: 13px 0; margin-bottom: 12px; color: #42685e; }
.rea-source-chain > div { display: flex; align-items: center; gap: 7px; min-width: 0; }
.rea-source-chain span { font-size: 9px; display: block; color: var(--muted); }
.rea-source-chain code { color: var(--teal); display: block; margin-top: 4px; font-size: 10px; overflow-wrap: anywhere; }
.rea-job-actions { display: flex; align-items: center; flex-wrap: wrap; gap: 8px 11px; }
.rea-job-actions .button { font-size: 11px; padding: 7px 9px; }
.rea-job-actions .text-button { font-size: 11px; }
.rea-reused { color: #587867; font-size: 11px; margin: 3px 0 12px; line-height: 1.7; }
.rea-origin { margin-top: 14px; border-top: 1px solid var(--line); padding-top: 10px; color: var(--muted); font-size: 10px; }
.rea-origin summary { cursor: pointer; }
.rea-origin dl { display: grid; grid-template-columns: 74px minmax(0, 1fr); gap: 9px; margin: 14px 0 0; }
.rea-origin dt, .rea-origin dd { margin: 0; min-width: 0; overflow-wrap: anywhere; line-height: 1.65; }
.rea-evidence-view { min-width: 0; }
.rea-evidence-meta { border-bottom: 1px solid var(--line); padding-bottom: 12px; color: var(--muted); font-size: 11px; }
.rea-evidence-meta code { display: block; overflow-wrap: anywhere; margin-top: 7px; font-size: 10px; }
.rea-pointer { display: flex; justify-content: space-between; gap: 12px; align-items: center; padding: 14px 0; min-width: 0; }
.rea-pointer code { color: var(--teal); overflow-wrap: anywhere; min-width: 0; }
.rea-field-picker { display: flex; flex-wrap: wrap; gap: 7px; margin-bottom: 15px; }
.rea-field-picker button { font-family: "Cascadia Code", Consolas, monospace; font-size: 10px; display: inline-flex; align-items: center; gap: 7px; padding: 5px 8px; border: 1px solid var(--line); border-radius: 4px; overflow-wrap: anywhere; max-width: 100%; }
.rea-field-picker button:hover { color: var(--teal); background: #ecf5ef; }
.rea-original-content { margin: 0; padding: 17px; background: #f1f5f2; border: 1px solid var(--line); border-radius: 5px; line-height: 1.8; font-size: 11px; max-height: 44vh; overflow: auto; white-space: pre-wrap; overflow-wrap: anywhere; }
.rea-page-controls { display: flex; align-items: center; gap: 9px; margin-top: 14px; flex-wrap: wrap; font-size: 11px; color: var(--muted); }
.rea-page-controls > span { margin-right: auto; }
@media (max-width: 800px) {
.rea-grid { grid-template-columns: minmax(0, 1fr); gap: 26px; }
.rea-registration form { padding: 15px; }
}
@media (max-width: 620px) {
.rea-heading { display: block; margin-bottom: 18px; }
.rea-heading h3 { font-size: 21px; }
.rea-availability { flex-direction: row; align-items: center; justify-content: space-between; padding-top: 14px; }
.rea-job { padding: 13px; }
.rea-job.verified { padding-left: 11px; }
.rea-job-heading { flex-wrap: wrap; gap: 8px; }
.rea-job-state { padding-top: 0; }
.rea-source-chain { gap: 4px; }
.rea-source-chain > div { gap: 4px; }
.rea-source-chain code { font-size: 9px; }
.rea-source-chain > div > svg { display: none; }
.rea-pointer { align-items: flex-start; flex-wrap: wrap; }
.rea-original-content { padding: 12px; max-height: 42vh; }
}
@media (prefers-reduced-motion: reduce) { .rea-panel .spin { animation: none; } }
@@ -0,0 +1,127 @@
import { useEffect, useRef, useState } from 'react';
import { ArrowRight, ArrowUpLeft, Download, FileSearch, Fingerprint, LoaderCircle, Play, RefreshCw, ShieldCheck, Square } from 'lucide-react';
import { api, downloadArtifact, downloadResearchDocument } from './api';
import { Modal } from './components';
import type { ArtifactPreview, Project, ReaAvailability, ResearchJob, ResearchPage, ResearchTarget, Session } from './types';
import './ResearchPanel.css';
const active = ['queued', 'connecting', 'analyzing', 'stopping'];
const operations = [
{ id: 'javascript', extensions: ['.asar'], label: 'JavaScript / Electron' },
{ id: 'pe-imports', extensions: ['.exe', '.dll'], label: 'PE 导入表' },
{ id: 'pe-resources', extensions: ['.exe', '.dll'], label: 'PE 静态资源' },
];
const states: Record<string, string> = { queued: '已排队', connecting: '核对 REA 连接', analyzing: '正在静态分析', stopping: '正在停止', completed: '原证据已核验', stale: '工件版本变化', unverified: '原响应尚未核验', failed: '分析未完成', cancelled: '已停止', unknown: '结果待核对', interrupted: '已中断' };
const date = (value: string) => new Date(value).toLocaleString('zh-CN', { month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit' });
const escapeField = (value: string) => value.replace(/~/g, '~0').replace(/\//g, '~1');
type Preview = { job: ResearchJob; kind: 'evidence' | 'raw' | 'trace'; page: ResearchPage };
export function ResearchPanel({ project, session, busy, onSession, onError }: { project: Project; session: Session; busy: boolean; onSession: (value: Session) => void; onError: (error: unknown) => void }) {
const [availability, setAvailability] = useState<ReaAvailability | null>(null);
const [filename, setFilename] = useState(''), [label, setLabel] = useState(''), [goal, setGoal] = useState('');
const [choices, setChoices] = useState<Record<string, string>>({});
const [pending, setPending] = useState(false), [checking, setChecking] = useState(false), [viewBusy, setViewBusy] = useState(false);
const [retry, setRetry] = useState<ResearchJob | null>(null), [preview, setPreview] = useState<Preview | null>(null);
const mounted = useRef(true), request = useRef(0), scope = useRef(0), viewRequest = useRef(0);
const taskId = session.execution?.task?.id ?? null;
const targets = session.execution?.researchTargets ?? [], jobs = (session.execution?.researchJobs ?? []).slice().reverse();
const running = jobs.some(job => active.includes(job.status)), disabled = busy || running || pending;
useEffect(() => { mounted.current = true; return () => { mounted.current = false; request.current++; scope.current++; viewRequest.current++; }; }, []);
useEffect(() => { scope.current++; viewRequest.current++; setPreview(null); setRetry(null); setPending(false); setViewBusy(false); }, [taskId]);
useEffect(() => { void detect(); }, []);
async function detect() {
const current = ++request.current; setChecking(true);
try { const value = await api<ReaAvailability>('/research/availability'); if (mounted.current && current === request.current) setAvailability(value); }
catch (error) { if (mounted.current && current === request.current) onError(error); }
finally { if (mounted.current && current === request.current) setChecking(false); }
}
async function register() {
const current = scope.current; setPending(true);
try {
const value = await api<{ target: ResearchTarget; session: Session }>('/sessions/' + session.id + '/research/targets',
{ path: filename.trim(), ...(label.trim() ? { label: label.trim() } : {}), ...(goal.trim() ? { goal: goal.trim() } : {}) });
if (!mounted.current || current !== scope.current) return;
onSession(value.session); setFilename(''); setLabel(''); setGoal('');
} catch (error) { if (mounted.current && current === scope.current) onError(error); }
finally { if (mounted.current && current === scope.current) setPending(false); }
}
async function analyze(targetId: string, operation: string, refresh = false) {
const current = scope.current; setPending(true);
try {
const value = await api<{ job: ResearchJob; session: Session }>('/sessions/' + session.id + '/research/jobs', { targetId, operation, refresh });
if (mounted.current && current === scope.current) { onSession(value.session); setRetry(null); }
} catch (error) { if (mounted.current && current === scope.current) onError(error); }
finally { if (mounted.current && current === scope.current) setPending(false); }
}
async function stop() {
const current = scope.current; setPending(true);
try { const value = await api<Session>('/sessions/' + session.id + '/research/stop', {}); if (mounted.current && current === scope.current) onSession(value); }
catch (error) { if (mounted.current && current === scope.current) onError(error); }
finally { if (mounted.current && current === scope.current) setPending(false); }
}
async function openView(job: ResearchJob, kind: Preview['kind'] = 'evidence', pointer = '/normalized_result', offset = 0) {
const current = ++viewRequest.current, currentScope = scope.current; setViewBusy(true);
try {
let page: ResearchPage;
if (kind === 'trace') {
const value = await api<ArtifactPreview>('/artifacts/' + job.traceArtifactId + '?session=' + session.id + '&offset=' + offset + '&limit=4000');
page = { content: value.content, offset: value.offset, next_offset: value.offset + value.content.length, total_characters: value.totalCharacters,
truncated: value.truncated, source_document_sha256: value.sha256 };
} else page = await api<ResearchPage>('/sessions/' + session.id + '/research/jobs/' + job.id + '/' + (kind === 'raw' ? 'raw' : 'evidence')
+ '?pointer=' + encodeURIComponent(pointer) + '&offset=' + offset + '&limit=4000');
if (mounted.current && currentScope === scope.current && current === viewRequest.current) setPreview({ job, kind, page });
} catch (error) { if (mounted.current && currentScope === scope.current && current === viewRequest.current) onError(error); }
finally { if (mounted.current && currentScope === scope.current && current === viewRequest.current) setViewBusy(false); }
}
async function download(job: ResearchJob, kind: Preview['kind']) {
const current = scope.current;
try { if (kind === 'trace' && job.traceArtifactId) await downloadArtifact(session.id, job.traceArtifactId, 'agent-workbench-rea-transport-' + job.id + '.json');
else await downloadResearchDocument(session.id, job.id, kind === 'raw' ? 'raw' : 'bundle'); }
catch (error) { if (mounted.current && current === scope.current) onError(error); }
}
return <div className="rea-panel">
<header className="rea-heading"><div><span className="rea-eyebrow">{project.name} · 当前任务</span><h3>从工件取得原证据</h3><p>登记一个本地工件,分析其代码、导入或资源,再把原依据交给同一编程任务。</p></div>
<div className="rea-availability"><span className={availability?.status === 'available' ? 'found' : ''}>{checking ? '正在检测' : availability?.status === 'available' ? '已找到 REA ' + availability.version : 'REA 尚未就绪'}</span>
<button type="button" className="text-button" onClick={() => void detect()} disabled={checking}><RefreshCw size={13} />重新检测</button></div></header>
{availability && availability.status !== 'available' && <div className="rea-install-note">{availability.status === 'unsupported' ? '当前分析契约使用 REA 6.8.0,请使用匹配的发行包。' : '请使用包含 REA 的工作台发行包,再重新检测本地安装。'}</div>}
<div className="rea-grid"><section className="rea-registration">
<form onSubmit={event => { event.preventDefault(); void register(); }}>
<h4><FileSearch size={16} />登记研究工件</h4>
<label className="form-field">本地工件路径<input aria-label="REA工件路径" value={filename} onChange={event => setFilename(event.target.value)} placeholder="D:\Applications\app.asar" required disabled={disabled} /></label>
<label className="form-field">工件名称<input aria-label="REA工件名称" value={label} onChange={event => setLabel(event.target.value)} placeholder="例如:代理客户端发行包" maxLength={160} disabled={disabled} /></label>
<label className="form-field">研究问题(选填)<textarea aria-label="REA研究问题" value={goal} onChange={event => setGoal(event.target.value)} placeholder="例如:工具执行与取消如何协作?" rows={3} disabled={disabled} /></label>
<p className="rea-hint">支持 ASAR、EXE 和 DLL。名称与 SHA256 将保存在本任务;首次登记会创建研究任务。</p>
<button type="submit" className="button primary" disabled={disabled || !filename.trim()}>{pending ? <LoaderCircle size={14} className="spin" /> : <Fingerprint size={14} />}登记工件</button>
</form>
<div className="rea-targets"><h4>本任务工件 <span>{targets.length}</span></h4>
{!targets.length && <p className="rea-empty">登记后,模型可以选择这个工件进行静态分析。</p>}
{targets.map(target => { const choicesForFile = operations.filter(operation => operation.extensions.includes(target.extension)), operation = choices[target.id] ?? choicesForFile[0]?.id;
return <article className="rea-target" key={target.id}><strong>{target.label}</strong><small>{target.path}</small><code title={target.sha256}>SHA256 {target.sha256}</code>
<div className="rea-target-actions"><select aria-label={'分析方式 ' + target.label} value={operation} onChange={event => setChoices(previous => ({ ...previous, [target.id]: event.target.value }))} disabled={disabled}>{choicesForFile.map(value => <option key={value.id} value={value.id}>{value.label}</option>)}</select>
<button type="button" className="button secondary" onClick={() => void analyze(target.id, operation)} disabled={disabled || availability?.status !== 'available'}><Play size={13} />分析</button></div></article>; })}
</div>
</section><section className="rea-results"><div className="rea-results-heading"><h4>分析与原依据</h4>{running && <button type="button" className="text-button" onClick={() => void stop()} disabled={pending}><Square size={13} />停止分析</button>}</div>
{!jobs.length && <div className="rea-empty-result"><FileSearch size={28} /><strong>原结果将在这里保留</strong><p>分析完成后可选择原字段、查看限制并下载完整 Evidence Bundle。</p></div>}
{jobs.map(job => { const target = targets.find(value => value.id === job.targetId), verified = job.status === 'completed' && job.evidenceBinding?.verified;
return <article className={'rea-job ' + (verified ? 'verified' : '')} key={job.id} data-research-job={job.id}><div className="rea-job-heading"><div><strong>{target?.label ?? '历史工件'}</strong><span>{operations.find(value => value.id === job.operationId)?.label ?? job.operation}</span></div><span className={'rea-job-state ' + job.status}>{active.includes(job.status) && <LoaderCircle size={12} className="spin" />}{states[job.status] ?? job.status}</span></div>
<p className="rea-job-summary">{job.summary}</p>
{verified && <div className="rea-source-chain" aria-label="已核验原证据来源"><div><Fingerprint size={13} /><span>工件 SHA<code>{job.targetSha256.slice(0, 12)}</code></span></div><ArrowRight size={12} /><div><ShieldCheck size={13} /><span>REA<code>{job.installation.version}</code></span></div><ArrowRight size={12} /><div><FileSearch size={13} /><span>原 Evidence<code>{job.evidenceId?.slice(3, 15)}</code></span></div></div>}
{job.reusedFromJobId && <p className="rea-reused">复用既有原证据,本次没有再次调用 REA。</p>}
<div className="rea-job-actions">{verified && <><button type="button" className="button secondary" onClick={() => void openView(job)} disabled={viewBusy}><FileSearch size={13} />查看原字段</button><button type="button" className="text-button" onClick={() => void openView(job, 'evidence', '/limitations')} disabled={viewBusy}>原限制</button><button type="button" className="text-button" onClick={() => void download(job, 'evidence')}><Download size={13} />完整证据</button></>}
{job.raw && <button type="button" className="text-button" onClick={() => void openView(job, 'raw')} disabled={viewBusy}>原响应</button>}
{job.traceArtifactId && <button type="button" className="text-button" onClick={() => void openView(job, 'trace')} disabled={viewBusy}>连接记录</button>}
{!active.includes(job.status) && !verified && target && <button type="button" className="text-button" onClick={() => setRetry(job)} disabled={disabled}><RefreshCw size={13} />重新分析</button>}</div>
<details className="rea-origin"><summary>{date(job.startedAt)} · 静态工件观测</summary><dl><dt>Task</dt><dd><code>{job.taskId}</code></dd><dt>Run</dt><dd><code>{job.runId}</code></dd><dt>目标 SHA256</dt><dd><code>{job.targetSha256}</code></dd>{job.evidenceId && <><dt>原 Evidence</dt><dd><code>{job.evidenceId}</code></dd></>}<dt>进程关闭</dt><dd>{job.cleanup ? job.cleanup.rootExited ? '所属根进程已退出' : '关闭结果待核对' : job.reusedFromJobId ? '复用原依据,没有新进程' : '尚未记录关闭结果'}</dd></dl></details>
</article>; })}
</section></div>
{retry && <Modal title="重新运行静态分析" description="这会创建新的分析记录。此前停止、失败或未知的原记录仍会保留。" onClose={() => setRetry(null)}><p>{targets.find(value => value.id === retry.targetId)?.label} · {operations.find(value => value.id === retry.operationId)?.label}</p><div className="modal-actions"><button className="button secondary" onClick={() => setRetry(null)}>返回原记录</button><button className="button primary" onClick={() => void analyze(retry.targetId, retry.operationId, true)} disabled={disabled}>确认重新分析</button></div></Modal>}
{preview && <Modal title={preview.kind === 'evidence' ? '原 Evidence 字段' : preview.kind === 'raw' ? 'REA 原响应' : 'REA 连接记录'} description={preview.kind === 'evidence' ? '原字段与完整证据来源已经校验。静态关系及未知覆盖以原限制为准。' : '此处保留当次实际返回记录;记录存在不表示分析已经核验完成。'} wide onClose={() => { viewRequest.current++; setPreview(null); setViewBusy(false); }}>
<div className="rea-evidence-view"><div className="rea-evidence-meta"><span>原文 SHA256</span><code>{preview.page.source_document_sha256}</code></div>
{preview.kind === 'evidence' && <><div className="rea-pointer"><code>{preview.page.pointer}</code>{preview.page.pointer !== '/normalized_result' && <button className="text-button" onClick={() => void openView(preview.job)} disabled={viewBusy}><ArrowUpLeft size={13} />返回分析字段</button>}</div>
{!!preview.page.available_fields?.length && <div className="rea-field-picker" aria-label="原Evidence字段">{preview.page.available_fields.map(field => <button key={field} type="button" onClick={() => void openView(preview.job, 'evidence', preview.page.pointer + '/' + escapeField(field))} disabled={viewBusy}>{field}<ArrowRight size={11} /></button>)}</div>}</>}
<pre className="rea-original-content" aria-label="原Evidence内容">{preview.page.content}</pre><div className="rea-page-controls"><span>{preview.page.offset.toLocaleString()}–{preview.page.next_offset.toLocaleString()} / {preview.page.total_characters.toLocaleString()} 字符</span>
<button className="button secondary" onClick={() => void openView(preview.job, preview.kind, preview.page.pointer, 0)} disabled={viewBusy || preview.page.offset === 0}>回到首页</button><button className="button secondary" onClick={() => void openView(preview.job, preview.kind, preview.page.pointer, preview.page.next_offset)} disabled={viewBusy || !preview.page.truncated}>{viewBusy ? <LoaderCircle className="spin" size={13} /> : <ArrowRight size={13} />}下一页</button></div>
<div className="modal-actions"><button className="button secondary" onClick={() => void download(preview.job, preview.kind)}><Download size={14} />{preview.kind === 'evidence' ? '下载完整 Evidence Bundle' : '下载完整原记录'}</button></div>
</div></Modal>}
</div>;
}
@@ -0,0 +1,70 @@
.skill-center { color: #27394b; --skill-line: #c8d2dc; --skill-surface: #f3f6f9; }
.skill-heading { display: flex; align-items: start; justify-content: space-between; gap: 20px; margin-bottom: 18px; }
.skill-kicker { display: flex; align-items: center; gap: 7px; color: #516d85; font-size: 11px; font-weight: 700; letter-spacing: .07em; }
.skill-heading h3 { margin: 9px 0; font: 700 23px/1.4 'Microsoft YaHei UI', 'Segoe UI', sans-serif; color: #16324c; }
.skill-heading p { max-width: 590px; margin: 0; color: #62758a; font-size: 13px; line-height: 1.7; }
.skill-heading > button { flex-shrink: 0; }
.skill-status-bar { display: flex; align-items: center; flex-wrap: wrap; gap: 12px 22px; border-block: 1px solid var(--skill-line); padding: 13px 2px; margin-bottom: 18px; font-size: 12px; color: #486077; }
.skill-status-bar > span { display: inline-flex; align-items: center; gap: 7px; }
.skill-light { width: 7px; height: 7px; background: #307f72; border-radius: 50%; }
.skill-list { display: grid; gap: 14px; }
.skill-row { border: 1px solid var(--skill-line); border-left: 4px solid #647f99; background: #fff; padding: 18px; border-radius: 6px; }
.skill-row.skill-changed, .skill-row.skill-unavailable { border-left-color: #ab712c; }
.skill-row-title { display: flex; align-items: start; gap: 11px; }
.skill-row-title > svg { margin-top: 3px; color: #4f708e; flex-shrink: 0; }
.skill-row-title > div { flex: 1; min-width: 0; }
.skill-row h4 { margin: 0 0 6px; font-size: 15px; color: #213f59; overflow-wrap: anywhere; }
.skill-row h4 span { margin-left: 9px; font: 500 11px/1.4 Consolas, monospace; color: #697e91; }
.skill-row-title p { margin: 0; font-size: 12px; color: #63788b; line-height: 1.6; overflow-wrap: anywhere; }
.skill-switch-state { border: 1px solid #d2dce5; color: #6b7d8b; padding: 4px 7px; font-size: 11px; white-space: nowrap; border-radius: 4px; }
.skill-switch-state.on { color: #266b5d; background: #edf6f2; border-color: #b7d4c9; }
.skill-source { margin: 15px 0; display: flex; align-items: center; gap: 8px 16px; flex-wrap: wrap; font-size: 11px; color: #698096; }
.skill-source code, .skill-revision-list code, .skill-snapshot > code { font: 11px/1.6 Consolas, 'Cascadia Code', monospace; overflow-wrap: anywhere; }
.skill-source-state { color: #35746a; font-weight: 600; }
.skill-source-state.changed, .skill-source-state.unavailable { color: #986324; }
.skill-path { flex: 0 0 100%; color: #5f7489; }
.skill-controls { display: flex; gap: 9px; }
.skill-revisions { border-top: 1px solid #e1e7ed; margin-top: 15px; padding-top: 12px; }
.skill-revisions summary { color: #5d7287; font-size: 12px; cursor: pointer; min-height: 25px; }
.skill-revision-list { display: grid; gap: 8px; margin: 10px 0; }
.skill-revision-list > div { display: flex; align-items: center; gap: 12px; font-size: 12px; flex-wrap: wrap; }
.skill-refresh { display: flex; align-items: end; gap: 10px; margin-top: 14px; }
.skill-refresh label { display: grid; gap: 5px; font-size: 11px; }
.skill-refresh input { max-width: 160px; }
.skill-alert, .skill-notice { display: flex; gap: 8px; align-items: start; padding: 12px; font-size: 12px; line-height: 1.6; overflow-wrap: anywhere; border: 1px solid #d7c3ba; color: #95513c; background: #fff6f1; border-radius: 4px; }
.skill-notice { color: #34695d; background: #eff7f3; border-color: #bfd8cb; }
.skill-alert svg, .skill-notice svg { flex-shrink: 0; margin-top: 2px; }
.skill-warning { color: #916126; font-size: 12px; line-height: 1.6; overflow-wrap: anywhere; }
.skill-empty { display: grid; gap: 10px; justify-items: center; text-align: center; padding: 30px 14px; color: #688098; border: 1px dashed #cad7e1; border-radius: 6px; margin: 14px 0; }
.skill-empty strong { color: #36566f; font-size: 14px; }
.skill-empty p { font-size: 12px; margin: 0; line-height: 1.7; }
.skill-register { border: 1px solid var(--skill-line); border-radius: 6px; padding: 18px; margin-top: 20px; background: var(--skill-surface); }
.skill-register-heading { display: flex; gap: 10px; align-items: center; justify-content: space-between; margin-bottom: 16px; flex-wrap: wrap; }
.skill-register-heading h4 { display: flex; align-items: center; gap: 6px; margin: 0; font-size: 14px; }
.skill-register-heading > span { font-size: 11px; color: #6f8193; }
.skill-form-grid { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, .4fr); gap: 12px; }
.skill-form-grid label { display: grid; gap: 6px; font-size: 12px; font-weight: 600; }
.skill-center input, .skill-center textarea { width: 100%; min-width: 0; background: #fff; border: 1px solid #c8d4df; border-radius: 4px; padding: 9px 10px; font: 13px/1.5 'Segoe UI', 'Microsoft YaHei UI', sans-serif; color: #263d52; }
.skill-center input:focus-visible, .skill-center textarea:focus-visible, .skill-center summary:focus-visible, .skill-snapshot pre:focus-visible { outline: 2px solid #4f7b9e; outline-offset: 2px; }
.skill-full { grid-column: 1 / -1; }
.skill-register footer { margin-top: 16px; display: flex; justify-content: space-between; align-items: center; gap: 12px; font-size: 11px; color: #6c8297; }
.skill-snapshot { margin-top: 18px; border: 1px solid #aac0d1; border-radius: 6px; overflow: hidden; }
.skill-snapshot header { display: flex; align-items: center; justify-content: space-between; padding: 10px 14px; background: #e8f0f6; font-size: 12px; gap: 8px; }
.skill-snapshot p { margin: 12px 14px; color: #63788b; font-size: 12px; line-height: 1.6; }
.skill-snapshot > code { display: block; margin: 0 14px; color: #55718b; }
.skill-snapshot pre { padding: 14px; margin: 10px 0 0; max-height: 330px; overflow: auto; white-space: pre-wrap; overflow-wrap: anywhere; font: 12px/1.8 Consolas, 'Microsoft YaHei UI', monospace; background: #f4f7fa; }
@media (max-width: 620px) {
.skill-heading { flex-direction: column; gap: 13px; }
.skill-heading h3 { font-size: 21px; }
.skill-row, .skill-register { padding: 13px; }
.skill-row-title { gap: 8px; }
.skill-row-title > svg { display: none; }
.skill-row h4 span { display: block; margin: 5px 0 0; }
.skill-status-bar { gap: 10px 16px; }
.skill-controls > button { flex: 1; }
.skill-center button, .skill-center summary { min-height: 44px; }
.skill-form-grid { grid-template-columns: minmax(0, 1fr); }
.skill-register footer { flex-direction: column; align-items: stretch; }
.skill-register footer > button { justify-content: center; }
.skill-revision-list { gap: 4px; }
}
@@ -0,0 +1,63 @@
import { useEffect, useRef, useState } from 'react';
import type { FormEvent } from 'react';
import { BookOpenText, Check, CircleAlert, FileText, LoaderCircle, Plus, Power, RefreshCw, ShieldCheck } from 'lucide-react';
import { api } from './api';
import './SkillCenter.css';
type SkillVersion = { revision: number; version: string; source: { path: string; sha256: string; bytes: number }; snapshotSha256: string; createdAt: string };
type Skill = SkillVersion & { id: string; projectId: string; name: string; description: string; enabled: boolean; configurationRevision: number; updatedAt: string; status: string; reason: string; revisions: SkillVersion[] };
type SkillView = { skills: Skill[]; projectId: string; revision: number; modelRequests: number };
type Snapshot = SkillVersion & { id: string; content: string };
const statusNames: Record<string, string> = { current: '来源一致', changed: '来源已变化', unavailable: '来源不可用' };
export function SkillCenter({ projectId, busy }: { projectId: string; busy: boolean }) {
const [view, setView] = useState<SkillView | null>(null), [working, setWorking] = useState(false);
const [error, setError] = useState(''), [notice, setNotice] = useState('');
const [snapshot, setSnapshot] = useState<Snapshot | null>(null), [versions, setVersions] = useState<Record<string, string>>({});
const [draft, setDraft] = useState({ name: '', description: '', path: '', version: '1.0.0' });
const generation = useRef(0);
const url = '/projects/' + projectId + '/skills';
const load = async (current = generation.current) => { const result = await api<SkillView>(url); if (current === generation.current) setView(result); };
useEffect(() => {
const current = ++generation.current; setView(null); setSnapshot(null); setError('');
void load(current).catch(cause => { if (current === generation.current) setError(String(cause.message ?? cause)); });
return () => { generation.current++; };
}, [projectId]);
const perform = async (action: () => Promise<unknown>, success: string) => {
const current = generation.current; setWorking(true); setError(''); setNotice('');
try { await action(); if (current === generation.current) { setNotice(success); await load(current); } }
catch (cause) { if (current === generation.current) setError(cause instanceof Error ? cause.message : String(cause)); }
finally { if (current === generation.current) setWorking(false); }
};
const register = (event: FormEvent) => {
event.preventDefault();
void perform(async () => { await api(url, draft); }, '技能已登记。审查原文后,可以为当前项目启用。');
};
const read = (skill: Skill, revision: number) => {
const current = generation.current;
void perform(async () => {
const value = await api<Snapshot>(url + '/content?id=' + skill.id + '&revision=' + revision);
if (current === generation.current) setSnapshot(value);
}, '已读取保存的原修订。');
};
const skills = view?.skills ?? [], active = skills.filter(value => value.enabled && value.status === 'current').length;
const locked = busy || working;
return <section className="skill-center" aria-label="项目技能管理" aria-busy={working}>
<header className="skill-heading"><div><span className="skill-kicker"><BookOpenText size={15} />项目能力 / SKILLS</span><h3>让工作流程有据可查</h3><p>登记本地技能,在本项目任务中按需读取。启用前先审查内容,来源改变后需要重新确认。</p></div><button type="button" className="button secondary" disabled={working} onClick={() => void perform(() => load(), '来源状态已重新核对。')}><RefreshCw size={14} className={working ? 'spin' : ''} />核对来源</button></header>
<div className="skill-status-bar"><span><i className="skill-light" />{active} 项可用</span><span>{skills.length} 项已登记</span><span><ShieldCheck size={14} />沿用项目权限与审查</span></div>
{error && <p className="skill-alert" role="alert"><CircleAlert size={16} />{error}</p>}
{notice && <p className="skill-notice" role="status"><Check size={16} />{notice}</p>}
{busy && <p className="skill-warning">项目正在执行,停止任务后可以修改技能配置。</p>}
<div className="skill-list">{skills.map(skill => <article className={'skill-row skill-' + skill.status} key={skill.id}>
<div className="skill-row-title"><BookOpenText size={19} /><div><h4>{skill.name}<span>v{skill.version}</span></h4><p>{skill.description}</p></div><span className={'skill-switch-state ' + (skill.enabled ? 'on' : '')}>{skill.enabled ? '已启用' : '已停用'}</span></div>
<div className="skill-source"><span className={'skill-source-state ' + skill.status}>{statusNames[skill.status]}</span><span>修订 {skill.revision}</span><code title={skill.source.sha256}>SHA256 {skill.source.sha256.slice(0, 16)}</code><span>{skill.source.bytes.toLocaleString()} B</span><code className="skill-path">{skill.source.path}</code></div>
{skill.reason && <p className="skill-warning">{skill.reason}</p>}
<div className="skill-controls"><button type="button" className="button secondary" disabled={working} onClick={() => read(skill, skill.revision)}><FileText size={14} />审查原文</button><button type="button" className={'button ' + (skill.enabled ? 'secondary' : 'primary')} disabled={locked || !skill.enabled && skill.status !== 'current'} onClick={() => void perform(() => api(url + '/toggle', { id: skill.id, revision: skill.revision, configurationRevision: skill.configurationRevision, enabled: !skill.enabled }), skill.enabled ? '技能已停用。' : '技能已启用,后续任务可以按需读取。')}><Power size={14} />{skill.enabled ? '停用技能' : '启用技能'}</button></div>
<details className="skill-revisions"><summary>版本与来源记录 · {skill.revisions.length} 个修订</summary><div className="skill-revision-list">{skill.revisions.map(version => <div key={version.revision}><span>r{version.revision} · {version.version}</span><code>{version.source.sha256.slice(0, 16)}</code><button type="button" className="text-button" disabled={working} onClick={() => read(skill, version.revision)}>查看该修订</button></div>)}</div><form onSubmit={event => { event.preventDefault(); void perform(() => api(url + '/refresh', { id: skill.id, revision: skill.revision, configurationRevision: skill.configurationRevision, version: versions[skill.id] || skill.version }), '新修订已登记,并已停用。请审查后重新启用。'); }} className="skill-refresh"><label>新修订版本<input aria-label={'新修订版本 ' + skill.name} value={versions[skill.id] ?? skill.version} onChange={event => setVersions({ ...versions, [skill.id]: event.target.value })} maxLength={80} /></label><button type="submit" className="button secondary" disabled={locked}><RefreshCw size={14} />登记新修订</button></form></details>
</article>)}</div>
{!view && !error && <p className="skill-empty"><LoaderCircle size={20} className="spin" />正在核对已登记技能</p>}
{view && !skills.length && <div className="skill-empty"><BookOpenText size={27} /><strong>为项目接入第一项技能</strong><p>选择你已审查的 SKILL.md,填写名称与用途。登记后默认停用。</p></div>}
{snapshot && <section className="skill-snapshot" aria-label="技能原文"><header><strong>原文审查 · {snapshot.version} / r{snapshot.revision}</strong><button type="button" className="text-button" onClick={() => setSnapshot(null)}>关闭原文</button></header><p>这是保存的技能参考流程,执行仍需遵循项目权限。附带脚本和文件不会自动运行。</p><code>快照 SHA256 {snapshot.snapshotSha256}</code><pre tabIndex={0}>{snapshot.content}</pre></section>}
<form className="skill-register" onSubmit={register}><div className="skill-register-heading"><h4><Plus size={17} />登记本地技能</h4><span>UTF-8 · SKILL.md · 最大 64KB</span></div><div className="skill-form-grid"><label>技能名称<input required value={draft.name} onChange={event => setDraft({ ...draft, name: event.target.value })} maxLength={100} placeholder="例如:工程交付检查" /></label><label>版本<input required value={draft.version} onChange={event => setDraft({ ...draft, version: event.target.value })} maxLength={80} /></label><label className="skill-full">技能文件路径<input required value={draft.path} onChange={event => setDraft({ ...draft, path: event.target.value })} placeholder="D:\skills\project-delivery\SKILL.md" /></label><label className="skill-full">用途说明<textarea required rows={2} maxLength={500} value={draft.description} onChange={event => setDraft({ ...draft, description: event.target.value })} placeholder="说明何时使用这项技能,便于任务选择。" /></label></div><footer><span>登记与核对来源不会请求模型。</span><button type="submit" className="button primary" disabled={locked || !draft.name.trim() || !draft.path.trim() || !draft.description.trim()}>{working ? <LoaderCircle size={14} className="spin" /> : <Plus size={14} />}登记技能</button></footer></form>
</section>;
}
@@ -0,0 +1,67 @@
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';
export function TaskCheckpointPanel({ session, busy, onSession, onError, openArtifact }: {
session: Session; busy: boolean; onSession: (value: Session) => void; onError: (error: unknown) => void; openArtifact: (id: string) => void;
}) {
const task = session.execution?.task, run = session.execution?.run;
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 [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++; };
}, [scope]);
if (!task || !run) return null;
async function save() {
if (!task || !run) return;
const id = ++request.current; setWorking(true); setNotice('');
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('恢复检查点已保存;继续前还会核对当前工程。');
}
} catch (error) { if (selectedScope.current === scope && request.current === id) onError(error); }
finally { if (selectedScope.current === scope && request.current === id) setWorking(false); }
}
async function inspect(checkpoint: TaskCheckpoint) {
const id = ++request.current; setWorking(true); setView(null); setNotice('');
try { const value = await api<TaskCheckpointView>(`/sessions/${session.id}/task-checkpoints/${checkpoint.id}`);
if (selectedScope.current === scope && request.current === id) setView(value);
} catch (error) { if (selectedScope.current === scope && request.current === id) onError(error); }
finally { if (selectedScope.current === scope && request.current === id) setWorking(false); }
}
async function resume() {
if (!view?.resumable) return;
const id = ++request.current; setWorking(true);
try { const value = await api<Session>(`/sessions/${session.id}/task-checkpoints/${view.checkpoint.id}/resume`, { sha256: view.checkpoint.sha256 });
if (selectedScope.current === scope && request.current === id) onSession(value);
} catch (error) { if (selectedScope.current === scope && request.current === id) onError(error); }
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>
<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>}
{records.map(checkpoint => <article className="checkpoint-card" key={checkpoint.id}>
<strong>{new Date(checkpoint.createdAt).toLocaleString('zh-CN')}</strong>
<p>{checkpoint.counts.completed} 项已完成工具 · {checkpoint.counts.unknown} 项待核对 · {checkpoint.counts.pendingChanges} 项待审查</p>
<code title={checkpoint.sha256}>SHA256 {checkpoint.sha256.slice(0, 16)}</code>
<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>)}
{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>}
</div>}
</section>;
}
@@ -0,0 +1,42 @@
import { useEffect, useState } from 'react';
import { api } from './api';
import type { DeliveryStatus, Session } from './types';
export function TaskFollowUp({ session, openArtifact }: { session: Session; openArtifact: (id: string) => void }) {
const task = session.execution?.task, run = session.execution?.run;
const [value, setValue] = useState<DeliveryStatus | null>(null), [error, setError] = useState(''), [refresh, setRefresh] = useState(0), [loading, setLoading] = useState(false);
const identity = session.id + '/' + task?.id + '/' + run?.id;
const [loadedIdentity, setLoadedIdentity] = useState('');
const active = ['running', 'awaiting_approval', 'stopping'].includes(session.status);
useEffect(() => {
let alive = true;
setError('');
if (!task || !run || active) { setLoading(false); return; }
const timer = setTimeout(() => {
setLoading(true); setError('');
api<DeliveryStatus>(`/sessions/${session.id}/delivery-status?taskId=${task.id}&runId=${run.id}`)
.then(result => { if (alive) { setValue(result); setLoadedIdentity(identity); } })
.catch(reason => { if (alive) { setError(reason instanceof Error ? reason.message : String(reason)); setValue(null); } })
.finally(() => { if (alive) setLoading(false); });
}, 160);
return () => { alive = false; clearTimeout(timer); };
}, [identity, session.revision, session.status, refresh]);
const current = loadedIdentity === identity ? value : null, diagnostic = current?.diagnostics.at(-1), context = diagnostic?.context;
return <section className="task-record-section task-follow-up" aria-label="当前缺口与下一步">
<div className="record-heading"><h3>当前缺口与下一步</h3><button className="text-button" disabled={active || loading} onClick={() => setRefresh(n => n + 1)}>{loading ? '正在核对' : '刷新当前结果'}</button></div>
{active ? <p className="record-footnote">等待所属运行、检查或审批结束,再核对当前结果。</p> : error ? <p role="alert" className="plan-problem">{error} 请刷新当前结果;原记录保留。</p> : current ? <>
<p><strong>{current.followUp.statusLabel}</strong></p>
<p className="follow-up-next">下一步:{current.followUp.nextStep}</p>
{!!current.followUp.gaps.length && <details><summary>待处理事项 · {current.followUp.gaps.length}</summary><ul>{current.followUp.gaps.map((gap, i) => <li key={gap.kind + gap.id + i}><strong>{gap.label}</strong><p>{gap.nextStep}</p></li>)}</ul></details>}
{diagnostic && context && <div className="diagnostic-origin" aria-label="诊断原执行">
<strong>最近只读诊断 · {diagnostic.status === 'completed' ? '答复已完成' : diagnostic.status === 'failed' ? '诊断失败' : '尚未完成'}</strong>
<p>{diagnostic.question}</p>
{diagnostic.failure && <p>本次诊断错误:{diagnostic.failure.message}</p>}
{context.evidenceVerified ? <><p>原执行:{context.originalRunId?.slice(0, 8) ?? '未记录'}</p><p>原错误:{context.failure?.value.message ?? '未记录具体错误;原因保持未知。'}</p>
{context.check && <p>原检查:{context.check.id.slice(0, 8)} · {context.check.status}</p>}</> : <p>{context.error ?? context.note}</p>}
{context.artifactId && <button className="text-button" onClick={() => openArtifact(context.artifactId!)}>查看诊断原绑定</button>}
</div>}
<p className="record-footnote">{current.followUp.note}</p>
</> : <p className="record-footnote">正在核对当前目标、要求和原结果。</p>}
</section>;
}
@@ -0,0 +1,107 @@
.task-record { flex: 1; min-height: 0; overflow: auto; padding: 4px 18px 20px; }
.task-record-section { padding: 18px 0; border-bottom: 1px solid var(--line); }
.record-heading { display: flex; gap: 7px; align-items: center; margin-bottom: 12px; color: var(--teal); }
.record-heading h3 { font-size: 12px; font-weight: 600; flex: 1; }
.record-heading > span:not(.status) { margin-left: auto; font-size: 11px; color: var(--muted); }
.record-heading > code { margin-left: auto; font-size: 11px; color: var(--muted); }
.task-goal { line-height: 1.85; white-space: pre-wrap; overflow-wrap: anywhere; font-size: 12px; }
.task-follow-up { font-size: 12px; line-height: 1.8; overflow-wrap: anywhere; }
.follow-up-next { margin: 10px 0; }
.task-follow-up summary { cursor: pointer; color: var(--teal); }
.task-follow-up ul { padding-left: 18px; }
.task-follow-up li { margin-top: 12px; }
.task-follow-up li p { margin-top: 3px; }
.diagnostic-origin { margin-top: 14px; padding-left: 10px; border-left: 2px solid #bd9654; }
.diagnostic-origin p { margin: 6px 0; white-space: pre-wrap; }
@media (max-width: 600px) { .task-follow-up .text-button { min-height: 44px; } }
.record-id { display: inline-block; font-size: 10px; color: var(--muted); margin-top: 9px; }
.task-instructions { margin-top: 14px; font-size: 11px; }
.task-instructions summary { cursor: pointer; color: var(--teal); }
.task-instructions p { white-space: pre-wrap; overflow-wrap: anywhere; line-height: 1.8; padding: 8px 0; }
.record-empty, .record-footnote { display: flex; gap: 7px; align-items: flex-start; color: var(--muted); font-size: 11px; line-height: 1.85; margin: 9px 0; }
.verification-note { display: flex; gap: 10px; padding: 14px 12px; margin-top: 15px; background: #faf4e8; border: 1px solid #e7d8b8; border-radius: 7px; color: #805d22; }
.verification-note strong { font-size: 12px; }
.verification-note p { font-size: 11px; line-height: 1.8; margin-top: 6px; }
.verification-note code { display: block; font-size: 10px; margin-top: 5px; }
.run-picker { display: flex; flex-direction: column; gap: 7px; color: var(--muted); font-size: 11px; }
.run-picker select { border: 1px solid var(--line); background: #fff; border-radius: 5px; padding: 8px; width: 100%; min-width: 0; font-size: 11px; }
.run-status { display: flex; justify-content: space-between; align-items: center; margin: 13px 0; }
.run-status > code { font-size: 10px; color: var(--muted); }
.record-fields { display: grid; grid-template-columns: 90px minmax(0, 1fr); gap: 9px 10px; font-size: 11px; line-height: 1.7; margin: 0; }
.record-fields dt { color: var(--muted); }
.record-fields dd { margin: 0; overflow-wrap: anywhere; }
.record-fields small { color: var(--muted); font-size: 10px; }
.record-endpoint { font-family: "Cascadia Code", Consolas, monospace; font-size: 10px; }
.run-stop { padding: 9px; margin-top: 11px; font-size: 11px; line-height: 1.7; border-left: 2px solid #bd9654; background: #faf7ef; }
.check-plan { margin-top: 14px; border-left: 2px solid #7da89c; padding-left: 12px; font-size: 11px; line-height: 1.8; }
.check-selection { border: 1px solid var(--line); border-radius: 6px; margin: 12px 0; padding: 8px 10px; min-width: 0; }
.check-selection legend { color: var(--muted); padding: 0 4px; }
.check-selection label { display: flex; align-items: center; gap: 7px; padding: 4px 0; cursor: pointer; overflow-wrap: anywhere; }
.check-selection input { accent-color: #35776b; width: 14px; height: 14px; flex: 0 0 auto; }
.check-selection p { margin: 7px 0; color: var(--muted); }
.check-baseline { display: flex; gap: 5px; align-items: flex-start; color: var(--muted); margin-top: 7px; overflow-wrap: anywhere; }
.check-baseline svg { margin-top: 4px; }
.check-plan ul { padding: 0; margin: 12px 0; list-style: none; }
.check-plan li { display: flex; flex-direction: column; gap: 4px; margin: 10px 0; }
.check-plan li code { color: var(--teal); background: #edf3f1; padding: 5px 8px; border-radius: 4px; font-size: 11px; overflow-wrap: anywhere; }
.check-job { padding: 13px 0 0; margin-top: 15px; border-top: 1px solid var(--line); font-size: 11px; line-height: 1.7; }
.check-job .record-heading { margin-bottom: 6px; flex-wrap: wrap; }
.check-job > time { color: var(--muted); font-size: 10px; }
.check-job > p { margin: 7px 0; }
.check-current { display: flex; align-items: center; gap: 6px; color: var(--teal); }
.check-result { border: 1px solid var(--line); border-radius: 6px; padding: 9px; margin-top: 10px; }
.check-result > div { display: flex; gap: 5px; align-items: center; justify-content: space-between; }
.check-result > p { margin-top: 6px; color: var(--muted); }
.check-result .text-button { margin-top: 6px; padding-left: 0; }
.artifact-list { display: flex; flex-direction: column; gap: 5px; }
.artifact-list button { width: 100%; display: flex; justify-content: space-between; align-items: center; text-align: left; border: 1px solid var(--line); border-radius: 5px; padding: 9px; font-size: 11px; }
.artifact-list button:hover { background: #edf3f1; }
.artifact-list code { display: block; color: var(--muted); font-size: 10px; margin-top: 4px; }
.artifact-list small { color: var(--muted); font-size: 10px; }
.artifact-preview { min-height: 100px; min-width: 0; max-width: 100%; overflow: auto; flex: 1; padding: 15px; background: #edf3f1; border: 1px solid var(--line); border-radius: 5px; font-size: 11px; line-height: 1.8; }
.modal-heading > div { min-width: 0; }
.modal-heading p { overflow-wrap: anywhere; }
.artifact-pagination { display: flex; align-items: center; justify-content: flex-end; gap: 8px; padding-top: 13px; font-size: 11px; flex-wrap: wrap; }
.artifact-pagination > span { margin-right: auto; color: var(--muted); }
.check-confirm { flex: 1; min-height: 0; overflow: auto; font-size: 12px; }
.check-confirm > div { margin-bottom: 14px; }
.check-confirm pre { margin: 6px 0 0; padding: 10px; background: #edf3f1; border: 1px solid var(--line); border-radius: 5px; font-size: 11px; }
.check-confirm p { color: var(--muted); line-height: 1.8; }
.check-python-runtime { margin: 9px 0; padding: 9px 11px; border-left: 2px solid #84a597; background: #f6f9f7; font-size: 11px; line-height: 1.6; }
.check-python-runtime strong, .check-python-runtime code { display: block; }
.check-python-runtime code { margin-top: 3px; font-size: 10px; color: var(--muted); overflow-wrap: anywhere; }
.status-unknown, .status-unverified, .status-stale { color: #805d22; background: #faf4e8; }
.status-passed { color: #277958; background: #edf7ef; }
.status-queued, .status-validating, .status-not_configured, .status-cancelled { color: #626c7c; background: #eef0f4; }
.tool-unknown .tool-symbol { color: #805d22; background: #faf4e8; }
.context-meter { height: 5px; margin: 15px 0; border-radius: 9px; overflow: hidden; background: #e8eeeb; }
.context-meter i { display: block; height: 100%; background: #56877b; border-radius: inherit; }
.context-sha { display: block; font-size: 10px; color: var(--muted); margin-top: 4px; overflow-wrap: anywhere; }
.context-actions { display: flex; flex-wrap: wrap; gap: 4px 12px; }
.context-actions .text-button { padding-left: 0; }
.context-history-list { flex: 1; min-height: 0; overflow: auto; padding: 1px; }
.context-history-group { padding: 13px; margin-bottom: 10px; border: 1px solid var(--line); border-radius: 6px; font-size: 11px; line-height: 1.8; }
.context-history-group > div:first-child { display: flex; flex-wrap: wrap; justify-content: space-between; gap: 4px 14px; }
.context-history-group strong { font-weight: 600; overflow-wrap: anywhere; }
.context-history-group small { color: var(--muted); font-size: 10px; }
.context-history-group > .text-button { padding-left: 0; margin-top: 6px; }
.context-history-tool { display: flex; flex-wrap: wrap; align-items: center; gap: 3px 10px; padding: 6px 0; }
.context-history-tool code { font-size: 10px; color: var(--muted); overflow-wrap: anywhere; }
.context-history-tool small { flex-basis: 100%; overflow-wrap: anywhere; }
.context-unknown { padding: 1px 6px; border-radius: 4px; color: #805d22; background: #faf4e8; font-size: 10px; }
@media (max-width: 1120px) { .inspector-tabs > button:not(.icon-button) { padding-left: 7px; padding-right: 7px; gap: 4px; } .task-record { padding-left: 13px; padding-right: 13px; } }
@media (max-width: 620px) { .toolbar-actions { gap: 1px; } .toolbar-actions .icon-button { width: 24px; } .task-record { padding: 4px 16px 20px; } .record-fields { grid-template-columns: 83px minmax(0, 1fr); } .artifact-pagination .button { height: 32px; } }
.checkpoint-card { margin-top: 12px; padding: 12px; background: var(--panel, #fff); border: 1px solid var(--border, #cbd5df); border-radius: 6px; min-width: 0; }
.checkpoint-card strong { display: block; font-size: 12px; }
.checkpoint-card p, .checkpoint-card code { display: block; margin-top: 6px; font-size: 11px; color: var(--muted); line-height: 1.7; overflow-wrap: anywhere; }
.checkpoint-assessment { margin-top: 12px; padding: 12px; border: 1px solid #b9c9da; background: #f3f7fb; border-radius: 6px; font-size: 12px; line-height: 1.8; }
.checkpoint-assessment ul { margin: 8px 0; padding-left: 18px; overflow-wrap: anywhere; }
.checkpoint-assessment .button, .task-checkpoints > .button { margin-top: 8px; height: auto; min-height: 36px; white-space: normal; }
@media (max-width: 620px) { .task-checkpoints .button, .task-checkpoints .text-button { min-height: 44px; } }
.turn-progress { margin-top: 14px; font-size: 12px; line-height: 1.65; overflow-wrap: anywhere; }
.turn-progress summary { cursor: pointer; color: #154b4a; font-weight: 600; }
.turn-progress ol { list-style: none; padding: 0; margin: 10px 0; }
.turn-progress li { border-top: 1px solid #dce7e2; padding: 10px 0; }
.turn-progress li strong { font-size: 12px; }
.turn-progress li p { margin: 4px 0; }
@media (max-width: 620px) { .turn-progress .text-button { min-height: 44px; } }
@@ -0,0 +1,184 @@
import { ModelIdentityDetails } from './ModelIdentityDetails';
import { useEffect, useRef, useState } from 'react';
import { Check, ClipboardCheck, FileText, GitBranch, LoaderCircle, Play, RefreshCw, ShieldQuestion } from 'lucide-react';
import type { ArtifactPreview, CheckPlan, Project, PythonRuntimeIdentity, Run, Session } from './types';
import { api } from './api';
import { Modal, Status } from './components';
import { DeliveryPanel } from './DeliveryPanel';
import { RequestContextPanel } from './RequestContextPanel';
import { WorkspacePanel } from './WorkspacePanel';
import { BrowserPanel } from './BrowserPanel';
import { TaskPlanPanel } from './TaskPlanPanel';
import { RequirementPanel } from './RequirementPanel';
import { TurnProgress } from './TurnProgress';
import { TaskCheckpointPanel } from './TaskCheckpointPanel';
import { McpJobHistory } from './McpJobHistory';
import './TaskPanel.css';
import { EnvironmentPanel } from './EnvironmentPanel';
import { PreviewPanel } from './PreviewPanel';
import { FileResultsPanel } from './FileResultsPanel';
import { TaskFollowUp } from './TaskFollowUp';
const stopReasons: Record<string, string> = { model_identity: '模型返回型号需要核对', no_progress: '重复读取未推进任务,请核对后继续', context_limit: '完整任务要求超过请求上下文预算', time_limit: '到达运行时间预算', token_limit: '到达本次 token 预算', task_token_limit: '到达任务累计预算', step_limit: '到达工具轮次上限', cancelled: '用户停止', model_error: '模型请求失败', interrupted: '进程中断' };
const number = (value: number | undefined) => (value ?? 0).toLocaleString('zh-CN');
stopReasons.git_review = 'Git预览已保存,等待审查与确认';
stopReasons.change_set_review = '完整文件批次已封存,等待审查与应用';
stopReasons.git_review_declined = 'Git预览已撤回,文件和检查记录保留';
stopReasons.task_plan_incomplete = '执行计划仍有未核验或失效步骤,请核对后继续';
stopReasons.diagnostic_answered = '诊断答复已完成;原任务的目标与交付状态保持';
stopReasons.verification_incomplete = '答复已收到,当前任务的工程检查尚未通过';
stopReasons.delivery_incomplete = '答复已收到,当前文件成果或要求的修改仍需核对';
const time = (value: string | null | undefined) => value ? new Date(value).toLocaleString('zh-CN', { month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit' }) : '执行中';
stopReasons.requirements_incomplete = '用户要求仍有待复核、失效或未审阅来源';
export function TaskPanel({ project, session, onSession, onError, busy, onWorkspaceRefresh, onWorkspaceNavigate, onOpenPreview }: { project: Project; session: Session; onSession: (value: Session) => void; onError: (error: unknown) => void; busy: boolean; onOpenPreview?:()=>void; onWorkspaceRefresh: (projectId: string, sessionId: string, isCurrent?: () => boolean) => Promise<void>; onWorkspaceNavigate: (projectId: string, sessionId: string, isCurrent?: () => boolean) => Promise<void> }) {
const execution = session.execution, task = execution?.task;
const [runId, setRunId] = useState('');
const [historicalRun, setHistoricalRun] = useState<Run | null>(null);
const [preview, setPreview] = useState<ArtifactPreview | null>(null);
const [previewBusy, setPreviewBusy] = useState(false);
const [planning, setPlanning] = useState(false);
const [confirmPlan, setConfirmPlan] = useState<CheckPlan | null>(null);
const [selectedChecks, setSelectedChecks] = useState<string[]>([]);
const [starting, setStarting] = useState(false);
const artifactRequest = useRef(0);
const actionScope = useRef(0);
const id = runId || execution?.run?.id || '';
const run = id === execution?.run?.id ? execution.run : historicalRun;
const plans = execution?.plans ?? [];
const latestPlan = plans.filter(plan => plan.taskId === task?.id).at(-1);
const checkChoices = latestPlan ? [...(latestPlan.project.packageManager === 'npm' ? latestPlan.project.scripts ?? [] : []), ...(latestPlan.project.python?.checks ?? [])] : [];
const checksChanged = !!latestPlan && JSON.stringify(selectedChecks.slice().sort()) !== JSON.stringify(latestPlan.checks.map(check => check.name).sort());
const jobs = execution?.checks ?? [];
const checkRunning = jobs.some(job => ['queued', 'running'].includes(job.status));
useEffect(() => { setSelectedChecks(latestPlan?.checks.map(check => check.name) ?? []); }, [latestPlan?.id]);
useEffect(() => { setRunId(''); setHistoricalRun(null); setPreview(null); setPreviewBusy(false); setConfirmPlan(null); setPlanning(false); setStarting(false); artifactRequest.current++; actionScope.current++;
return () => { artifactRequest.current++; actionScope.current++; };
}, [session.id, task?.id]);
useEffect(() => {
if (!id || id === execution?.run?.id) return;
let alive = true; setHistoricalRun(null);
api<Run>('/sessions/' + session.id + '/runs/' + id).then(value => { if (alive) setHistoricalRun(value); }).catch(error => { if (alive) onError(error); });
return () => { alive = false; };
}, [session.id, id, execution?.run?.id]);
async function openArtifact(artifactId: string, offset = 0) {
const request = ++artifactRequest.current; setPreviewBusy(true);
try {
const value = await api<ArtifactPreview>('/artifacts/' + artifactId + '?session=' + session.id + '&offset=' + offset + '&limit=16000');
if (artifactRequest.current === request) setPreview(value);
} catch (error) { if (artifactRequest.current === request) onError(error); }
finally { if (artifactRequest.current === request) setPreviewBusy(false); }
}
async function planChecks(names?: string[]) {
const scope = actionScope.current;
setPlanning(true);
try { const value = await api<Session>('/sessions/' + session.id + '/check-plans', names ? { names } : {}); if (actionScope.current === scope) onSession(value); }
catch (error) { if (actionScope.current === scope) onError(error); } finally { if (actionScope.current === scope) setPlanning(false); }
}
async function runChecks() {
if (!confirmPlan) return; setStarting(true);
const scope = actionScope.current;
try { const value = await api<Session>('/sessions/' + session.id + '/check-jobs', { planId: confirmPlan.id }); if (actionScope.current === scope) { onSession(value); setConfirmPlan(null); } }
catch (error) { if (actionScope.current === scope) onError(error); } finally { if (actionScope.current === scope) setStarting(false); }
}
async function stopCheck(jobId: string) {
const scope = actionScope.current;
try { const value = await api<Session>('/sessions/' + session.id + '/check-jobs/' + jobId + '/stop', {}); if (actionScope.current === scope) onSession(value); }
catch (error) { if (actionScope.current === scope) onError(error); }
}
return <div className="task-record" aria-label="任务记录">
<WorkspacePanel project={project} session={session} busy={busy} onRefresh={onWorkspaceRefresh} onNavigate={onWorkspaceNavigate} onError={onError} />
<section className="task-record-section">
<div className="record-heading"><ClipboardCheck size={15} /><h3>任务目标</h3>{task && <Status value={task.status} />}</div>
{task ? <><p className="task-goal">{task.contract?.goal || task.goal}</p><code className="record-id" title={task.id}>{task.id.slice(0, 8)} · 任务</code>
{task.contract?.checks === 'skip' && <p className="record-footnote">检查约定:按用户要求不自动测试。</p>}
{task.contract?.inheritedFromTaskId && <p className="record-footnote">原目标续接自 {task.contract.inheritedFromTaskId.slice(0, 8)},历史记录保留。</p>}
{task.delivery?.status === 'files_applied' && <div role="status"><strong>文件已应用</strong>{task.delivery.paths.map(path => <p key={path}><code>{path}</code></p>)}{task.delivery.checks === 'not_requested' && <p className="record-footnote">已按原要求交付文件,未运行测试。</p>}</div>}
{!!task.instructions.length && <details className="task-instructions"><summary>追加要求 · {task.instructions.length}</summary>{task.instructions.map(instruction => <p key={instruction.id}><small>{instruction.source && instruction.source !== 'user' ? '系统操作 · ' + instruction.source : '用户要求'}</small><br />{instruction.content}</p>)}</details>}
</> : <p className="record-empty">发送任务后,这里保存目标、每次运行和实际结果。</p>}
</section>
{task && <TaskFollowUp session={session} openArtifact={openArtifact} />}
{task && <FileResultsPanel session={session} busy={busy} onSession={onSession} openArtifact={openArtifact} />}
{task && <TaskPlanPanel session={session} busy={busy} onSession={onSession} onError={onError} openArtifact={openArtifact} />}
{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 && <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>
{run ? <><div className="run-status"><Status value={run.status} /><code title={run.id}>{run.id.slice(0, 8)}</code></div>
{run.status === 'needs_review' && task.delivery?.status === 'files_applied' && <p className="record-footnote">这次运行在文件审查前结束;文件此后已应用,当前交付状态见上方任务目标。</p>}
{run.purpose === 'diagnostic' && <p className="record-footnote">本次为只读诊断,运行结束仅表示答复完成;原任务状态另行保留。</p>}
{run.purpose === 'diagnostic' && run.diagnosticContext && <p className="record-footnote">原执行 {run.diagnosticContext.originalRunId?.slice(0, 8) ?? '未记录'}<button className="text-button" onClick={() => openArtifact(run.diagnosticContext!.artifactId)}>查看原绑定</button></p>}
<dl className="record-fields"><ActualModelFields run={run} session={session} />{run.workspaceIdentity && <><dt>执行目录</dt><dd className="record-endpoint">{run.workspaceIdentity.root}</dd>{run.workspaceIdentity.branch && <><dt>独立分支</dt><dd className="record-endpoint">{run.workspaceIdentity.branch}</dd></>}</>}<dt>开始 / 结束</dt><dd>{time(run.startedAt)}<br />{time(run.finishedAt)}</dd><dt>模型轮次 / 工具</dt><dd>{run.steps} / {run.toolCalls}</dd><dt>已报告用量</dt><dd>{number(run.usage?.totalTokens)} tokens<br /><small>输入 {number(run.usage?.inputTokens)} · 输出 {number(run.usage?.outputTokens)}</small></dd>
{!!run.usage?.unknownRequests && <><dt>未报告用量</dt><dd>{run.usage.unknownRequests} 次请求 · 估算 {number(run.usage.estimatedUnknownTokens)} tokens</dd></>}
<dt>本次预算</dt><dd>{number(run.budget?.maxTokens)} tokens · {Math.round((run.budget?.maxDurationMs ?? 0) / 60000)} 分钟 · {run.budget?.maxSteps} 轮</dd><dt>任务累计</dt><dd>{number(execution?.accountedTaskTokens)} / {number(task.budget.maxTokens)} tokens</dd>
</dl>{run.stopReason && <p className="run-stop">{stopReasons[run.stopReason] || run.stopReason}</p>}
<p className="record-footnote">用量按请求尝试累计,包含失败响应已报告的 tokens;未报告的请求单独估算。历史缺失不补造,tokens 不等于费用。</p>
<TurnProgress run={run} openArtifact={openArtifact} />
</> : <p className="record-empty"><LoaderCircle size={14} className="spin" />正在读取运行记录</p>}
</section>}
{run && <RequestContextPanel session={session} runId={run.id} onError={onError} openArtifact={openArtifact} />}
{task && <EnvironmentPanel project={project} session={session} busy={busy} onSession={onSession} onError={onError} openArtifact={openArtifact} />}
{task && <PreviewPanel onOpen={onOpenPreview} project={project} session={session} busy={busy} onSession={onSession} onError={onError} openArtifact={openArtifact} />}
<section className="task-record-section project-checks">
<div className="record-heading"><GitBranch size={15} /><h3>工程检查</h3><Status value={task?.verification.status || 'not_configured'} /></div>
{task?.verification.status === 'failed' && <p className="record-footnote" role="status">原工程检查有失败记录;文件应用或答复完成不代表检查通过。</p>}
{task?.contract?.checks === 'skip' && <p className="record-footnote">原任务无需测试。下方操作只在你明确选择并确认后执行。</p>}
<p className="record-footnote">检查对应当时的工程快照。先识别测试与执行环境,再确认检查;项目变化后重新检查。</p>
<button type="button" className="button secondary" disabled={!task || busy || planning || checkRunning} onClick={() => planChecks()}>{planning ? <LoaderCircle size={14} className="spin" /> : <RefreshCw size={14} />}{latestPlan ? '重新识别检查计划' : '识别工程与检查'}</button>
{latestPlan && <div className="check-plan"><p><strong>{latestPlan.project.name}</strong> · {latestPlan.project.languages.join(' / ') || '待识别'}</p><p className="check-baseline"><GitBranch size={12} />{latestPlan.project.git.available ? `${latestPlan.project.git.branch || 'detached'} · ${latestPlan.project.git.head?.slice(0, 8) || '尚无提交'}${latestPlan.project.git.dirty ? ' · 有未提交改动' : ' · 工作区干净'}` : '项目尚未启用 Git'}</p>
{latestPlan.environment&&<p className="record-footnote">环境:Node {latestPlan.environment.runtime.node.version} · npm {latestPlan.environment.runtime.npm?.version??'未找到'} · {latestPlan.environment.status==='ready'?'依赖已就绪':'依赖需要核对,请先查看上方工程环境'}{latestPlan.environment.preparation&&' · 引用依赖准备 '+latestPlan.environment.preparation.jobId.slice(0,8)}</p>}
{latestPlan.project.python?.status === 'invalid' && <p className="record-empty">{latestPlan.project.python.message}</p>}
{checkChoices.length > 0 && <fieldset className="check-selection" disabled={busy || planning || starting || checkRunning}>
<legend>选择检查范围</legend>
{checkChoices.map(check => <label key={check.name}><input type="checkbox" aria-label={'启用检查 ' + check.name} checked={selectedChecks.includes(check.name)} onChange={event => setSelectedChecks(current => event.target.checked ? [...current, check.name] : current.filter(name => name !== check.name))} /><span>{check.name}</span></label>)}
{checksChanged && <><p>按所选范围重新识别,确认后执行新计划。</p><button type="button" className="button secondary" disabled={!selectedChecks.length || selectedChecks.length > 6} onClick={() => planChecks(selectedChecks)}>重新识别所选检查</button></>}
</fieldset>}
{latestPlan.checks.length ? <><ul>{latestPlan.checks.map(check => <li key={check.id}><span>{check.name}</span><code>{check.command}</code></li>)}</ul>
{latestPlan.checks.find(check => check.python)?.python && <PythonRuntimeInfo runtime={latestPlan.checks.find(check => check.python)!.python!.runtime} />}
<button type="button" className="button primary" disabled={busy || starting || checkRunning || checksChanged} onClick={() => setConfirmPlan(latestPlan)}><Play size={14} />执行这些检查</button></> : <p className="record-empty">没有识别到可执行的检查。请配置项目测试或构建。</p>}
</div>}
{jobs.slice().reverse().map(job => <div key={job.id} className="check-job">
<div className="record-heading"><Status value={job.stale ? 'stale' : job.status} /><code title={job.id}>{job.id.slice(0, 8)}</code>{['queued', 'running'].includes(job.status) && <button type="button" className="text-button" onClick={() => stopCheck(job.id)}>停止检查</button>}</div>
<time>{time(job.startedAt)}</time>{job.currentCheck && <p className="check-current"><LoaderCircle size={12} className="spin" />正在执行 <code>{job.currentCheck.command}</code></p>}{job.summary && <p>{job.summary}</p>}
{job.results.map(result => <div key={result.id} className="check-result"><div><strong>{result.name}</strong><Status value={result.status} /></div>
<p>退出码 {result.exitCode === null ? '未返回' : result.exitCode} · {(result.durationMs / 1000).toFixed(1)} 秒{result.tests && ` · 测试 ${result.tests.passed}/${result.tests.total} 通过`}{!!result.tests?.failed && ` · 失败 ${result.tests.failed}`}{!!result.tests?.skipped && ` · 跳过 ${result.tests.skipped}`}{!!result.collectionErrors && ` · 收集错误 ${result.collectionErrors}`}</p>
{result.python && <PythonRuntimeInfo runtime={result.python.runtime} />}
{result.compilation && <p>语法编译 {result.compilation.compiled}/{result.compilation.total} 个源码文件</p>}
{result.reason && <p>{result.reason}</p>}
{result.logArtifactId && <button type="button" className="text-button" disabled={previewBusy} onClick={() => openArtifact(result.logArtifactId!)}><FileText size={13} />查看检查日志</button>}
{result.metricsArtifactId && <button type="button" className="text-button" disabled={previewBusy} onClick={() => openArtifact(result.metricsArtifactId!)}><ClipboardCheck size={13} />查看实际测试依据</button>}
</div>)}
</div>)}
</section>
{task && <BrowserPanel session={session} busy={busy} onSession={onSession} onError={onError} />}
{task && <DeliveryPanel session={session} busy={busy} onSession={onSession} onError={onError} openArtifact={openArtifact} />}
{!!execution?.artifacts.length && <section className="task-record-section"><div className="record-heading"><FileText size={15} /><h3>结果工件</h3><span>最近 {execution.artifacts.length} 项</span></div><div className="artifact-list">{execution.artifacts.filter(artifact => !artifact.mediaType?.startsWith('image/')).slice().reverse().map(artifact => <button type="button" key={artifact.id} disabled={previewBusy} onClick={() => openArtifact(artifact.id)}><span>{artifact.kind === 'browser-result' ? '原页面执行记录' : artifact.kind === 'browser-plan' ? '页面检查计划' : artifact.kind === 'browser-binding' ? '页面结果来源' : artifact.kind === 'check-log' ? '检查日志' : artifact.kind === 'check-metrics' ? '实际检查统计' : artifact.kind === 'check-input' ? '检查源码与目标' : artifact.kind === 'check-plan' ? '检查计划' : artifact.kind === 'project-inspection' ? '工程识别' : artifact.kind === 'delivery-report' ? '交付报告 · JSON' : artifact.kind === 'delivery-report-markdown' ? '交付报告 · Markdown' : artifact.kind === 'delivery-diff' ? '提交差异' : artifact.kind === 'model-request' ? '模型请求正文' : artifact.kind === 'context-plan' ? '请求计划' : artifact.kind === 'context-history-index' ? '完整历史索引' : artifact.kind === 'context-latest-tools' ? '最新工具反馈' : artifact.kind.startsWith('context-group') ? '完整历史记录' : '工具结果'}<code>{artifact.sha256.slice(0, 10)}</code></span><small>{number(artifact.bytes)} B</small></button>)}</div></section>}
{confirmPlan && <Modal title="执行工程检查" description="以下检查在当前项目执行,保存实际执行环境、退出码和结果。" onClose={() => setConfirmPlan(null)}><div className="check-confirm">{confirmPlan.checks.map(check => <div key={check.id}><strong>{check.command}</strong><pre>{check.script}{check.lifecycle?.length ? '\n\n' + check.lifecycle.map(item => item.name + ': ' + item.script).join('\n') : ''}</pre>{check.python && <PythonRuntimeInfo runtime={check.python.runtime} />}</div>)}<p>{confirmPlan.project.name}</p></div><div className="modal-actions"><button type="button" className="button secondary" disabled={starting} onClick={() => setConfirmPlan(null)}>取消</button><button type="button" className="button primary" disabled={starting} onClick={runChecks}><Check size={14} />确认执行检查</button></div></Modal>}
{preview && <Modal title="执行结果工件" description={`SHA256 ${preview.sha256}`} wide onClose={() => { artifactRequest.current++; setPreview(null); setPreviewBusy(false); }}><pre className="artifact-preview">{preview.content}</pre><div className="artifact-pagination"><span>字符 {number(preview.offset)}–{number(preview.offset + preview.content.length)} / {number(preview.totalCharacters)}</span><button type="button" className="button secondary" disabled={previewBusy || preview.offset === 0} onClick={() => openArtifact(preview.id, Math.max(0, preview.offset - 16000))}>上一段</button><button type="button" className="button secondary" disabled={previewBusy || !preview.truncated} onClick={() => openArtifact(preview.id, preview.offset + preview.content.length)}>下一段</button></div></Modal>}
</div>;
}
function ActualModelFields({ run, session }: { run: Run; session: Session }) {
const receipts = run.consumption ?? [];
const events = session.events.filter(event => event.runId === run.id && event.actualModel && event.connectionId);
const observed = receipts.length ? receipts.map(receipt => ({ id: receipt.connectionId, name: receipt.connectionName, model: receipt.model, endpoint: receipt.endpoint, identity: receipt.modelIdentity }))
: events.map(event => { const member = run.model.routing?.members?.find(member => member.id === event.connectionId); return { id: event.connectionId, name: member?.name, model: event.actualModel!, endpoint: member?.baseUrl, identity: undefined }; });
const routes = observed.filter((value, index) => observed.findIndex(candidate => candidate.id === value.id && candidate.model === value.model && candidate.endpoint === value.endpoint && JSON.stringify(candidate.identity) === JSON.stringify(value.identity)) === index);
return <><dt>启动选择</dt><dd>{run.model?.verified === false ? '历史配置未记录' : run.model?.mode === 'demo' ? '离线演示 · 固定脚本' : run.model.routing?.name || run.model.model || '未记录'}</dd>
<dt>实际调用</dt><dd>{routes.length ? routes.map((route, index) => <div key={index}><span>{route.name ? route.name + ' · ' : ''}{route.model}</span><ModelIdentityDetails identity={route.identity} requestedModel={route.model} />{route.endpoint && <small className="record-endpoint"><br />{route.endpoint}</small>}</div>) : run.model.mode === 'demo' ? '未调用模型服务' : '尚无可核对的实际连接记录'}</dd>
{!receipts.length && run.model.mode !== 'demo' && <><dt>启动接口</dt><dd className="record-endpoint">{run.model.baseUrl || '未记录'}<br /><small>启动配置不代表实际池成员</small></dd></>}
{!!receipts.length && <><dt>用量凭据</dt><dd>{receipts.length} 次请求尝试 · {receipts.filter(receipt => receipt.usageStatus === 'reported').length} 次已报告</dd></>}
</>;
}
function PythonRuntimeInfo({ runtime }: { runtime: PythonRuntimeIdentity }) {
return <div className="check-python-runtime"><strong>Python {runtime.version || (runtime.status === 'deferred' ? '执行时核对版本' : '尚未找到')}</strong>
<code>{runtime.logicalExecutable || runtime.executable || '请安装Python或配置项目虚拟环境'}</code>{runtime.message && <p>{runtime.message}</p>}</div>;
}
@@ -0,0 +1,41 @@
.task-plan-panel { --plan-teal: #154b4a; --plan-line: #dce7e2; }
.plan-toolbar, .plan-overview { display: flex; align-items: center; justify-content: space-between; gap: 10px; flex-wrap: wrap; }
.plan-toolbar { margin: 10px 0 14px; }
.plan-overview { padding: 9px 12px; background: #edf3f1; border-radius: 7px; margin-bottom: 14px; }
.plan-overview small { color: #526a70; }
.plan-steps { padding: 0; margin: 0; list-style: none; }
.plan-step { position: relative; padding: 0 0 18px 28px; }
.plan-step:not(:last-child)::before { content: ''; position: absolute; left: 9px; top: 20px; bottom: 0; border-left: 1px solid var(--plan-line); }
.plan-step-marker { position: absolute; left: 0; top: 2px; width: 20px; height: 20px; border: 1px solid #bbcfc7; border-radius: 50%; display: grid; place-items: center; color: #6a8079; background: #fcfdfc; }
.plan-step-verified .plan-step-marker { background: var(--plan-teal); color: #fff; border-color: var(--plan-teal); }
.plan-step-stale .plan-step-marker, .plan-step-unverified .plan-step-marker { color: #996527; border-color: #c69656; }
.plan-step-heading { display: flex; align-items: baseline; justify-content: space-between; gap: 8px; }
.plan-step-main { min-width: 0; }
.plan-step-heading strong { font-size: 13px; overflow-wrap: anywhere; }
.plan-step-heading .status { flex-shrink: 0; font-size: 10px; }
.plan-step-main > p { font-size: 12px; line-height: 1.6; margin: 6px 0; white-space: pre-wrap; overflow-wrap: anywhere; }
.plan-step-scope { font-size: 11px; color: #526a70; overflow-wrap: anywhere; }
.plan-step-main .plan-dependencies { color: #5b716a; font-size: 11px; }
.plan-problem { color: #9b5e23; font-size: 12px; line-height: 1.6; overflow-wrap: anywhere; }
.plan-notice { padding: 8px 10px; background: #edf3f1; border-left: 2px solid var(--plan-teal); font-size: 12px; line-height: 1.5; }
.plan-evidence, .plan-rejection { margin-top: 9px; font-size: 11px; }
.plan-evidence summary, .plan-rejection summary { cursor: pointer; color: #526a70; padding: 4px 0; }
.plan-evidence label { display: grid; gap: 5px; margin: 8px 0; color: #526a70; }
.plan-evidence select { width: 100%; min-width: 0; max-width: 100%; padding: 7px; border: 1px solid var(--plan-line); border-radius: 5px; background: #fcfdfc; color: #1c2e32; font-size: 11px; }
.plan-evidence .button { margin: 3px 8px 4px 0; }
.plan-evidence .text-button { display: inline-flex; margin: 4px 8px 0 0; }
.plan-rejection p { white-space: pre-wrap; overflow-wrap: anywhere; line-height: 1.5; color: #9b5e23; }
.plan-editor-scroll { max-height: 60vh; overflow: auto; padding: 2px 4px 12px 0; }
.plan-editor-step { margin: 0 0 16px; padding: 12px 16px; border: 1px solid #dce7e2; border-radius: 8px; min-width: 0; }
.plan-editor-step legend { padding: 0 6px; font-size: 13px; font-weight: 600; color: #154b4a; }
.plan-editor-step > label { display: grid; gap: 6px; margin-bottom: 12px; font-size: 12px; color: #526a70; }
.plan-editor-step input:not([type='checkbox']), .plan-editor-step textarea, .plan-editor-step select { width: 100%; min-width: 0; box-sizing: border-box; padding: 9px 11px; color: #1c2e32; background: #fcfdfc; border: 1px solid #cbded3; border-radius: 5px; font: inherit; }
.plan-editor-step textarea { resize: vertical; line-height: 1.6; }
.plan-editor-step:disabled { background: #f4f7f5; }
.plan-editor-step:disabled input, .plan-editor-step:disabled textarea, .plan-editor-step:disabled select { color: #526a70; opacity: 1; }
.plan-option-list { display: flex; flex-wrap: wrap; gap: 8px 14px; margin: 0 0 13px; }
.plan-option-list > span { flex-basis: 100%; font-size: 12px; color: #526a70; }
.plan-option-list label { display: inline-flex; gap: 6px; align-items: center; font-size: 12px; color: #1c2e32; }
.plan-option-list input { accent-color: #154b4a; }
.task-plan-panel button:focus-visible, .task-plan-panel select:focus-visible, .plan-editor input:focus-visible, .plan-editor textarea:focus-visible, .plan-editor select:focus-visible { outline: 2px solid #4664d9; outline-offset: 2px; }
@media (max-width: 600px) { .plan-step { padding-left: 26px; } .plan-step-heading { align-items: flex-start; } .plan-toolbar { gap: 8px; } .plan-editor-step { padding: 10px; } .plan-editor-scroll { max-height: 58vh; } }
@@ -0,0 +1,133 @@
import { useEffect, useRef, useState } from 'react';
import { Check, Circle, FileText, GitPullRequestArrow, LoaderCircle, Plus, RefreshCw } from 'lucide-react';
import { api } from './api';
import { Modal, Status } from './components';
import type { Session, TaskPlanReply, TaskPlanStep, TaskPlanView } from './types';
import './TaskPlanPanel.css';
const kinds: Record<TaskPlanStep['kind'], string> = { analysis: '读取工程', changes: '源码改动', results: '当前文件成果', checks: '工程检查', browser: '页面验收' };
const readTools = { inspect_project: '识别工程', read_file: '读取文件', list_files: '文件清单', search_files: '搜索文件', index_project: '工程索引', query_code: '定位符号', read_research_evidence: 'REA原结果', inspect_engine_checks: '引擎核验', read_browser_result: '原页面记录' };
const browserActions = { fill: '填写', select: '选择', click: '点击', assert_text: '文本断言', assert_count: '数量断言', assert_visible: '可见断言' };
const cleanStep = (step: TaskPlanStep): TaskPlanStep => ({ key: step.key, title: step.title, criterion: step.criterion, kind: step.kind, depends_on: [...step.depends_on],
...(step.kind === 'analysis' ? { tools: [...(step.tools ?? [])] } : ['changes', 'results'].includes(step.kind) ? { paths: (step.paths ?? []).map(value => value.trim()).filter(Boolean) }
: step.kind === 'checks' ? { checks: (step.checks ?? []).map(value => value.trim()).filter(Boolean) } : { viewport_width: step.viewport_width, actions: [...(step.actions ?? [])] }) });
const freshStep = (kind: TaskPlanStep['kind'] = 'analysis'): TaskPlanStep => ({ key: 'step_' + crypto.randomUUID().slice(0, 8), title: kinds[kind], criterion: '', kind, depends_on: [],
...(kind === 'analysis' ? { tools: ['inspect_project'] } : ['changes', 'results'].includes(kind) ? { paths: [] } : kind === 'checks' ? { checks: ['test', 'build'] } : { viewport_width: 1280, actions: ['assert_visible'] }) });
const scopeText = (step: TaskPlanStep) => step.kind === 'analysis' ? (step.tools ?? []).map(tool => readTools[tool as keyof typeof readTools] ?? tool).join(' / ')
: ['changes', 'results'].includes(step.kind) ? step.paths?.join('、') : step.kind === 'checks' ? step.checks?.join(' / ')
: `${step.viewport_width}px · ${(step.actions ?? []).map(action => browserActions[action as keyof typeof browserActions]).join(' / ')}`;
export function TaskPlanPanel({ session, busy, onSession, onError, openArtifact }: {
session: Session; busy: boolean; onSession: (value: Session) => void; onError: (error: unknown) => void; openArtifact: (id: string) => void;
}) {
const task = session.execution?.task, run = session.execution?.run;
const identity = `${session.projectId}/${session.id}/${task?.id}/${run?.id}`;
const selection = useRef(identity); selection.current = identity;
const requests = useRef(0);
const [view, setView] = useState<TaskPlanView | null>(null);
const [loading, setLoading] = useState(false), [mutating, setMutating] = useState(false);
const [editor, setEditor] = useState(false), [draft, setDraft] = useState<TaskPlanStep[]>([]), [fixed, setFixed] = useState(0);
const [picked, setPicked] = useState<Record<string, string>>({}), [notice, setNotice] = useState('');
const currentPlan = session.execution?.taskPlans?.at(-1)?.id, currentProof = session.execution?.taskProofs?.at(-1)?.id;
const disabled = busy || mutating || ['running', 'awaiting_approval', 'stopping'].includes(session.status);
useEffect(() => { selection.current = identity; setView(null); setLoading(false); setEditor(false); setMutating(false); setPicked({}); setNotice(''); requests.current++;
return () => { requests.current++; if (selection.current === identity) selection.current = ''; };
}, [identity]);
useEffect(() => { const timer = setTimeout(() => { void load(); }, 120); return () => clearTimeout(timer); }, [identity, currentPlan, currentProof, session.status]);
async function load() {
if (!task) return;
const request = ++requests.current, scope = identity; setLoading(true);
try { const value = await api<TaskPlanView>(`/sessions/${session.id}/task-plan?taskId=${task.id}`);
if (selection.current === scope && requests.current === request) setView(value);
} catch (error) { if (selection.current === scope && requests.current === request) onError(error); }
finally { if (selection.current === scope && requests.current === request) setLoading(false); }
}
function edit() {
const steps = view?.steps.map(cleanStep) ?? [];
setFixed(steps.length); setDraft(steps.length ? steps : [freshStep()]); setNotice(''); setEditor(true);
}
function update(index: number, patch: Partial<TaskPlanStep>) { setDraft(steps => steps.map((step, at) => at === index ? { ...step, ...patch } : step)); }
async function save() {
if (!task || !run || !view) return;
const scope = identity; setMutating(true); setNotice(''); requests.current++;
try {
const value = await api<TaskPlanReply>(`/sessions/${session.id}/task-plans`, { taskId: task.id, runId: run.id, expected_revision: view.revision, steps: draft.map(cleanStep) });
if (selection.current === scope) { onSession(value.session); setView(value.plan); setEditor(false); setNotice('执行计划已保存,按实际结果核验步骤。'); }
} catch (error) { if (selection.current === scope) onError(error); }
finally { if (selection.current === scope) { setMutating(false); setLoading(false); } }
}
async function verify(stepKey: string, evidenceId: string) {
if (!task || !run || !view?.plan_id || !evidenceId) return;
const scope = identity; setMutating(true); setNotice(''); requests.current++;
try {
const value = await api<TaskPlanReply>(`/sessions/${session.id}/task-proofs`, { taskId: task.id, runId: run.id,
plan_id: view.plan_id, expected_revision: view.revision, step_key: stepKey, evidence_id: evidenceId });
if (selection.current === scope) { onSession(value.session); setView(value.plan);
setNotice(value.verification?.status === 'completed' ? '原结果核验完成,没有再次执行工具。' : value.verification?.message ?? '核验未通过,请查看原结果。'); }
} catch (error) { if (selection.current === scope) onError(error); }
finally { if (selection.current === scope) { setMutating(false); setLoading(false); } }
}
return <section className="task-record-section task-plan-panel" aria-label="执行计划" aria-busy={loading || mutating}>
<div className="record-heading"><GitPullRequestArrow size={15} /><h3>执行计划</h3><span>{view?.configured ? `${view.verified_steps ?? 0} / ${view.total_steps ?? view.steps.length}` : '按结果核验'}</span></div>
<div className="plan-toolbar"><button type="button" className="text-button" disabled={loading || mutating} onClick={() => void load()}>
{loading ? <LoaderCircle size={13} className="spin" /> : <RefreshCw size={13} />}核对当前计划</button>
<button type="button" className="text-button" disabled={disabled || !view || task?.status === 'completed' || !!view.error} onClick={edit}><Plus size={13} />{view?.configured ? '补充步骤' : '建立计划'}</button>
</div>
{notice && <p className="plan-notice" role="status">{notice}</p>}
{!view ? <p className="record-empty">正在核对任务计划。</p> : !view.configured ? <p className="record-empty">{task?.status === 'completed' ? '本任务未设置执行计划。新任务可先固定步骤与通过条件。' : '先固定要完成的步骤,再用读取、改动、检查或页面结果核验。'}</p> : <>
<div className="plan-overview"><Status value={view.status} /><small>第 {view.revision} 版</small></div>
{view.error && <p className="plan-problem">{view.error}</p>}
{view.requirements_current === false && <p className="plan-problem">任务要求已更新。保留原步骤,补充新要求后重新核验仍有效的结果。</p>}
<ol className="plan-steps">{view.steps.map((step, index) => {
const evidenceId = picked[step.key] ?? step.evidence?.id ?? step.candidates?.find(candidate => ['completed', 'passed', 'applied'].includes(candidate.status))?.id ?? step.candidates?.[0]?.id ?? '';
const blockers = step.blockers.map(key => view.steps.find(value => value.key === key)?.title ?? key);
return <li key={step.key} className={`plan-step plan-step-${step.status}`}>
<div className="plan-step-marker" aria-hidden="true">{step.status === 'verified' ? <Check size={13} /> : <Circle size={11} />}</div>
<div className="plan-step-main"><div className="plan-step-heading"><strong>{index + 1}. {step.title}</strong><Status value={step.status} /></div>
<p>{step.criterion}</p><small className="plan-step-scope">{kinds[step.kind]} · {scopeText(step)}</small>
{!!step.depends_on.length && <p className="plan-dependencies">前置:{step.depends_on.map(key => view.steps.find(value => value.key === key)?.title ?? key).join('、')}</p>}
{!!blockers.length && <p className="plan-problem">先核验:{blockers.join('、')}</p>}
{step.error && <p className="plan-problem">{step.error}</p>}
{step.last_rejection && <details className="plan-rejection"><summary>最近一次核验未通过</summary><p>{step.last_rejection.message}</p></details>}
<details className="plan-evidence" open={['ready', 'stale', 'unverified'].includes(step.status)}><summary>{step.status === 'verified' ? '查看核验依据' : '选择实际结果'}</summary>
<label>原执行结果<select aria-label={`步骤${index + 1}原证据`} value={evidenceId} disabled={disabled} onChange={event => setPicked(values => ({ ...values, [step.key]: event.target.value }))}>
<option value="">选择此任务的实际结果</option>{step.candidates?.map(candidate => <option key={candidate.id} value={candidate.id}>{candidate.label} · {candidate.status} · {candidate.id.slice(0, 8)}</option>)}
</select></label>
<button type="button" className="button secondary" disabled={disabled || !evidenceId || !!blockers.length || view.requirements_current === false} onClick={() => void verify(step.key, evidenceId)}><Check size={13} />核验此步骤</button>
{step.proof_artifact_id && <button type="button" className="text-button" onClick={() => openArtifact(step.proof_artifact_id!)}><FileText size={13} />查看原核验记录</button>}
{step.evidence?.artifacts?.map(artifact => <button type="button" className="text-button" key={artifact.id} onClick={() => openArtifact(artifact.id)}><FileText size={13} />原依据 · {artifact.sha256.slice(0, 8)}</button>)}
</details>
</div>
</li>;
})}</ol>
{view.contract_artifact_id && <button type="button" className="text-button" onClick={() => openArtifact(view.contract_artifact_id!)}><FileText size={13} />查看原计划</button>}
<p className="record-footnote">核验依据为实际操作和当前文件;业务含义仍需独立验收。</p>
</>}
{editor && <Modal title="编辑执行计划" description="固定步骤、前置依赖和通过条件。保存计划不会运行工具。" wide onClose={() => { if (!mutating) setEditor(false); }}>
<form onSubmit={event => { event.preventDefault(); void save(); }} className="plan-editor">
<div className="plan-editor-scroll">{draft.map((step, index) => <fieldset className="plan-editor-step" key={step.key} disabled={mutating || index < fixed}>
<legend>步骤 {index + 1}{index < fixed ? ' · 已封存' : ''}</legend>
<label>步骤名称<input aria-label={`步骤${index + 1}名称`} value={step.title} maxLength={100} required onChange={event => update(index, { title: event.target.value })} /></label>
<label>通过条件<textarea aria-label={`步骤${index + 1}通过条件`} value={step.criterion} maxLength={300} required rows={2} placeholder="说明这一步完成后应该得到什么实际结果" onChange={event => update(index, { criterion: event.target.value })} /></label>
<label>结果类别<select aria-label={`步骤${index + 1}类别`} value={step.kind} onChange={event => {
const next = freshStep(event.target.value as TaskPlanStep['kind']); setDraft(steps => steps.map((value, at) => at === index ? { ...next, key: value.key, title: value.title, criterion: value.criterion, depends_on: value.depends_on } : value));
}}>{Object.entries(kinds).map(([key, label]) => <option key={key} value={key}>{label}</option>)}</select></label>
{step.kind === 'analysis' && <div className="plan-option-list"><span>可核验的读取结果(任一)</span>{Object.entries(readTools).map(([key, label]) => <label key={key}><input type="checkbox" checked={step.tools?.includes(key) ?? false} onChange={event => update(index, { tools: event.target.checked ? [...(step.tools ?? []), key] : step.tools?.filter(tool => tool !== key) })} />{label}</label>)}</div>}
{['changes', 'results'].includes(step.kind) && <label>{step.kind === 'results' ? '成果文件' : '改动文件'}(每行一项)<textarea aria-label={`步骤${index + 1}文件范围`} rows={3} value={step.paths?.join('\n') ?? ''} placeholder="src/main.tsx" onChange={event => update(index, { paths: event.target.value.split('\n') })} /></label>}
{step.kind === 'checks' && <label>检查名称(逗号分隔)<input aria-label={`步骤${index + 1}检查范围`} value={step.checks?.join(',') ?? ''} placeholder="test,build 或 python:test,python:compile" onChange={event => update(index, { checks: event.target.value.split(',') })} /></label>}
{step.kind === 'browser' && <><label>页面宽度<select aria-label={`步骤${index + 1}页面宽度`} value={step.viewport_width} onChange={event => update(index, { viewport_width: Number(event.target.value) })}><option value={1280}>桌面 · 1280px</option><option value={390}>手机 · 390px</option>{![1280, 390].includes(step.viewport_width ?? 0) && <option value={step.viewport_width}>{step.viewport_width}px</option>}</select></label>
<div className="plan-option-list"><span>必须实际完成的操作</span>{Object.entries(browserActions).map(([key, label]) => <label key={key}><input type="checkbox" checked={step.actions?.includes(key) ?? false} onChange={event => update(index, { actions: event.target.checked ? [...(step.actions ?? []), key] : step.actions?.filter(action => action !== key) })} />{label}</label>)}</div></>}
{index > 0 && <div className="plan-option-list"><span>前置步骤</span>{draft.slice(0, index).map(previous => <label key={previous.key}><input type="checkbox" checked={step.depends_on.includes(previous.key)} onChange={event => update(index, { depends_on: event.target.checked ? [...step.depends_on, previous.key] : step.depends_on.filter(key => key !== previous.key) })} />{previous.title}</label>)}</div>}
{index >= fixed && draft.length > Math.max(1, fixed) && <button type="button" className="text-button" onClick={() => setDraft(steps => steps.filter(value => value.key !== step.key).map(value => ({ ...value, depends_on: value.depends_on.filter(key => key !== step.key) })))}>移除此新步骤</button>}
</fieldset>)}
<button type="button" className="button secondary" disabled={mutating || draft.length >= 12} onClick={() => setDraft(steps => [...steps, freshStep()])}><Plus size={14} />追加步骤</button>
{fixed > 0 && <p className="record-footnote">原步骤和通过条件已封存,新增要求以追加步骤保留。</p>}
</div>
<div className="modal-actions"><button type="button" className="button secondary" disabled={mutating} onClick={() => setEditor(false)}>取消</button><button type="submit" className="button primary" disabled={mutating || draft.length > 12}>{mutating ? <LoaderCircle size={14} className="spin" /> : <Check size={14} />}保存执行计划</button></div>
</form>
</Modal>}
</section>;
}
@@ -0,0 +1,25 @@
import type { Run } from './types';
const labels: Record<string, string> = { baseline: '本次运行基线', waiting: '等待所属操作', evidence_growth: '新增外显证据', new_failure_evidence: '新增失败证据',
user_boundary: '用户边界变化', repeated_failure_candidate: '重复失败候选', repeated_read_candidate: '重复读取候选', no_observed_change: '未见新外显事实', unknown_bounded: '观察容量已满,保留未知' };
const failureLabels: Record<string, string> = { invalid_input: '参数无效', permission: '权限或审批拒绝', requires_verification: '结果待核对', network: '网络连接', service: '上游服务',
authentication: '身份验证', rate_limit: '请求限流', quota: '服务额度', tool_or_environment: '工具或环境', unknown: '尚未分类' };
export function TurnProgress({ run, openArtifact }: { run: Run; openArtifact: (id: string) => void }) {
if (!run.progressShadow && !run.progressShadowError) return null;
const shadow = run.progressShadow;
return <details className="turn-progress" aria-label="单轮观察">
<summary>单轮观察 · 仅记录{shadow ? ` · 已保留 ${shadow.turns.filter(row => row.phase === 'settled').length} 轮` : ''}</summary>
<p className="record-footnote">依据实际工具、文件范围、失败和证据变化分类;观察不改变停止、权限或预算。</p>
{run.progressShadowError && <p className="plan-problem">部分观察未能记录,原工具结果保留。</p>}
{shadow?.truncated && <p className="record-footnote">观察已达保留上限;较早收据仍在原工件中,未保留范围不推定为重复。</p>}
<ol>{shadow?.turns.map((turn, index) => <li key={`${turn.stepId}/${turn.phase}/${index}`}>
<strong>{turn.stepIndex === null ? '基线' : `第 ${turn.stepIndex} 轮`} · {labels[turn.classification] ?? turn.classification}</strong>
<p>新增读取 {turn.delta.read_characters} 字符 · 重复读取 {turn.delta.repeated_reads} 次{turn.delta.changed_files ? ` · 改动文件 ${turn.delta.changed_files}` : ''}{turn.delta.check_results ? ` · 检查结果 ${turn.delta.check_results}` : ''}{turn.delta.requirement_evidence ? ` · 要求证据 ${turn.delta.requirement_evidence}` : ''}</p>
{!!(turn.delta.new_failures || turn.delta.repeated_failures) && <p>新失败 {turn.delta.new_failures} · 重复失败 {turn.delta.repeated_failures}</p>}
{turn.reasons.some(reason => /^(new|repeated)_failure:/.test(reason)) && <p>失败类别:{[...new Set(turn.reasons.filter(reason => /^(new|repeated)_failure:/.test(reason)).map(reason => {
const kind = reason.split(':')[1]; return failureLabels[kind] ?? kind;
}))].join('、')}</p>}
{!!turn.waiting.length && <p>等待 {turn.waiting.map(row => ({ approval: '审批', check_job: '检查作业', review: '审查' }[row.kind] ?? row.kind)).join('、')}</p>}
{run.progressShadowArtifactIds?.[index] && <button className="text-button" onClick={() => openArtifact(run.progressShadowArtifactIds![index])}>查看原观察收据</button>}
</li>)}</ol>
</details>;
}
@@ -0,0 +1,68 @@
.worker-console { --worker-ink: #153047; --worker-muted: #587087; --worker-line: #c7d3de; --worker-blue: #2560a3; --worker-wash: #edf3fa; --worker-alert: #925619; color: var(--worker-ink); font-family: 'Segoe UI', 'Microsoft YaHei', sans-serif; display: grid; gap: 20px; min-width: 0; }
.worker-console h2, .worker-console h3, .worker-console p { margin: 0; }
.worker-console h2 { font-size: 21px; line-height: 1.4; font-weight: 650; letter-spacing: -.3px; }
.worker-console h3 { font-size: 16px; line-height: 1.5; }
.worker-console p { line-height: 1.65; }
.worker-console code { font-family: 'Cascadia Code', Consolas, monospace; font-size: 12px; overflow-wrap: anywhere; }
.worker-console-heading { display: flex; align-items: flex-start; justify-content: space-between; gap: 16px; }
.worker-console-heading p:not(.worker-eyebrow) { color: var(--worker-muted); margin-top: 5px; font-size: 13px; }
.worker-console .worker-eyebrow { color: var(--worker-blue); font-size: 11px; letter-spacing: .08em; font-weight: 650; margin-bottom: 5px; }
.worker-error { padding: 12px 15px; border: 1px solid #dfc4a7; border-left: 3px solid var(--worker-alert); background: #fff8ee; color: #794d21; overflow-wrap: anywhere; font-size: 13px; }
.worker-history { display: grid; grid-template-columns: auto minmax(0, 1fr); align-items: center; gap: 12px; font-size: 12px; color: var(--worker-muted); }
.worker-console input, .worker-console textarea, .worker-console select { width: 100%; border: 1px solid var(--worker-line); border-radius: 5px; background: #fff; padding: 9px 10px; color: var(--worker-ink); font-size: 13px; font-family: inherit; min-width: 0; }
.worker-console textarea { resize: vertical; line-height: 1.6; }
.worker-console input:focus-visible, .worker-console textarea:focus-visible, .worker-console select:focus-visible, .worker-console button:focus-visible { outline: 2px solid var(--worker-blue); outline-offset: 3px; }
.worker-plan-form { display: grid; gap: 18px; }
.worker-plan-form label { display: grid; gap: 7px; font-size: 12px; font-weight: 600; }
.worker-lanes { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 14px; align-items: stretch; }
.worker-lanes.single { grid-template-columns: minmax(0, 1fr); }
.worker-engine-install { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 12px; align-items: end; padding: 16px; border: 1px solid var(--worker-line); border-left: 3px solid var(--worker-blue); background: var(--worker-wash); border-radius: 6px; }
.worker-engine-install > div, .worker-engine-install > p { grid-column: 1 / -1; min-width: 0; overflow-wrap: anywhere; }
.worker-engine-install strong { font-size: 13px; }
.worker-engine-install p { margin: 5px 0 0; font-size: 12px; color: var(--worker-muted); }
.worker-console-heading > div { min-width: 0; flex: 1; }
.worker-console-heading > button { flex: 0 0 auto; min-width: 76px; white-space: nowrap; }
.worker-engine-install > button { white-space: nowrap; }
@media(max-width:620px) { .worker-engine-install { grid-template-columns:minmax(0,1fr); } .worker-console .worker-console-heading > button { min-height:42px; } }
.worker-lanes fieldset { border: 1px solid var(--worker-line); border-top: 3px solid var(--worker-blue); border-radius: 6px; padding: 16px; display: grid; gap: 13px; min-width: 0; }
.worker-lanes legend { padding: 0 8px; font-size: 12px; color: var(--worker-muted); }
.worker-budget-form { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 12px; }
.worker-parent { border: 1px solid var(--worker-line); background: var(--worker-wash); border-radius: 6px; padding: 18px 20px; display: grid; gap: 12px; }
.worker-parent-top { display: flex; justify-content: space-between; align-items: center; gap: 12px; flex-wrap: wrap; }
.worker-parent h3, .worker-goal { overflow-wrap: anywhere; white-space: pre-wrap; }
.worker-parent > p { font-size: 13px; color: var(--worker-muted); }
.worker-parent dl { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 12px 18px; border-top: 1px solid var(--worker-line); padding-top: 12px; margin: 0; }
.worker-parent dl div { min-width: 0; }
.worker-parent dt { font-size: 11px; color: var(--worker-muted); margin-bottom: 4px; }
.worker-parent dd { font-size: 12px; margin: 0; overflow-wrap: anywhere; }
.worker-lane { border: 1px solid var(--worker-line); border-top: 3px solid var(--worker-blue); border-radius: 6px; padding: 16px; background: #fff; display: flex; flex-direction: column; gap: 12px; min-width: 0; }
.worker-lane-title { display: flex; align-items: center; justify-content: space-between; gap: 8px; font-size: 11px; color: var(--worker-muted); }
.worker-status { display: inline-flex; align-items: center; background: #e2ecf6; color: var(--worker-blue); border: 1px solid #c2d5e8; border-radius: 3px; padding: 3px 7px; font-size: 11px; line-height: 1.4; white-space: nowrap; font-weight: 600; }
.worker-status.attention { color: var(--worker-alert); border-color: #dec6a8; background: #fff6e9; }
.worker-goal { font-size: 13px; flex: 1; }
.worker-engine-badge { margin:0; padding:7px 9px; background:var(--worker-wash); border-left:2px solid var(--worker-blue); font-size:11px; color:var(--worker-muted); overflow-wrap:anywhere; }
.worker-scope { border-left: 2px solid var(--worker-line); padding-left: 10px; display: grid; gap: 5px; }
.worker-scope > span, .worker-meter { font-size: 11px; color: var(--worker-muted); }
.worker-summary { color: var(--worker-muted); font-size: 12px; overflow-wrap: anywhere; }
.worker-proof { display: flex; align-items: center; gap: 6px; font-size: 11px; color: var(--worker-blue); }
.worker-actions { display: flex; gap: 10px; align-items: center; flex-wrap: wrap; }
.worker-primary-actions { padding-top: 16px; border-top: 1px solid var(--worker-line); }
.worker-console .button { font-size: 12px; min-height: 36px; }
.worker-console .worker-stop { background: #fff8ee; border-color: #dfc4a7; color: #794d21; }
.worker-review { border-left: 3px solid var(--worker-blue); padding: 2px 0 2px 15px; display: grid; gap: 12px; }
.worker-review-title { display: flex; align-items: center; gap: 8px; }
.worker-review > p { color: var(--worker-muted); font-size: 12px; }
.worker-conflicts { padding: 0; margin: 0; list-style: none; display: grid; gap: 7px; }
.worker-conflicts li { display: grid; gap: 4px; padding: 10px; background: #fff8ee; border: 1px solid #dfc4a7; font-size: 12px; overflow-wrap: anywhere; }
.worker-note, .worker-boundary { color: var(--worker-muted); font-size: 11px; }
.worker-boundary { display: flex; align-items: flex-start; gap: 7px; padding-top: 12px; border-top: 1px solid var(--worker-line); }
.worker-boundary svg { flex: 0 0 auto; margin-top: 2px; }
.worker-origin { display: flex; gap: 13px; padding: 20px; background: var(--worker-wash); border: 1px solid var(--worker-line); border-radius: 6px; }
.worker-origin div { display: grid; gap: 12px; min-width: 0; }
.worker-origin p { font-size: 13px; overflow-wrap: anywhere; }
.worker-confirm { display: grid; gap: 18px; }
.worker-confirm p { line-height: 1.7; font-size: 13px; }
.worker-confirm strong { display: block; margin-top: 12px; white-space: pre-wrap; overflow-wrap: anywhere; }
.worker-record { display: grid; gap: 12px; min-width: 0; }
.worker-record pre { font: 12px/1.6 'Cascadia Code', Consolas, monospace; white-space: pre-wrap; overflow-wrap: anywhere; max-height: 65vh; overflow: auto; padding: 14px; background: #f5f8fb; border: 1px solid #c7d3de; }
@media (max-width: 620px) { .worker-console { gap: 16px; } .worker-console h2 { font-size: 18px; } .worker-lanes { grid-template-columns: minmax(0, 1fr); } .worker-budget-form { grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); } .worker-parent { padding: 14px; } .worker-parent dl { grid-template-columns: minmax(0, 1fr); } .worker-actions .button { min-height: 42px; } .worker-console-heading { gap: 10px; } .worker-history { grid-template-columns: minmax(0, 1fr); gap: 6px; } }
@@ -0,0 +1,128 @@
import { useCallback, useEffect, useRef, useState } from 'react';
import { ArrowUpRight, Check, GitBranch, LoaderCircle, Play, RefreshCw, ShieldCheck, Square } from 'lucide-react';
import { api, downloadBlob } from './api';
import { Modal } from './components';
import { PurgeStrategyControl, emptyPurgeDraft, purgeDraftReady, purgeStrategyInput } from './PurgeStrategyControl';
import type { CollaborationGroup, Config, Session, WorkerView, ControlledEngineAvailability } from './types';
import './WorkerPanel.css';
const active = ['preparing', 'starting', 'running', 'stopping', 'collecting', 'merge_preparing', 'reconciling'];
const labels: Record<string, string> = { planned: '计划已封存', unprepared: '待创建', partially_prepared: '部分工作区已创建', ready: '就绪', preparing: '创建工作区', starting: '启动中', running: '执行中', stopping: '停止中', collecting: '核对成果', merge_preparing: '准备合并审查', reconciling: '核对现场', completed: '完成', ready_to_collect: '待核对成果', collected: '成果可审查', conflict: '需要处理冲突', merge_prepared: '等待合并审查', failed: '需要处理', paused: '已暂停', awaiting_review: '等待改动审查', needs_review: '等待改动审查', unknown: '结果待核对', stale: '来源已变化', discarded: '计划已撤销', resolved_external: '已保留现场' };
const number = (value?: number) => (value ?? 0).toLocaleString('zh-CN');
const statusLabel = (value: string) => value === 'awaiting_approval' ? '等待检查审批' : labels[value] ?? value;
const splitPaths = (value: string) => value.split(/[\n,,]/).map(path => path.trim()).filter(Boolean);
export function WorkerPanel({ session, config, busy, onSession, onNavigate, onReview }: {
session: Session; config: Config; busy: boolean; onSession: (value: Session) => void;
onNavigate: (projectId: string, sessionId: string, view?: 'task' | 'changes' | 'approval') => Promise<void>; onReview: () => void;
}) {
const [view, setView] = useState<WorkerView | null>(null), [selectedId, setSelectedId] = useState('');
const [error, setError] = useState(''), [action, setAction] = useState(''), [loading, setLoading] = useState(false);
const [goal, setGoal] = useState(''), [creating, setCreating] = useState(false);
const [engineMode, setEngineMode] = useState<'workbench' | 'deepseek'>('workbench'), [engineRoot, setEngineRoot] = useState('');
const [engineInstallation, setEngineInstallation] = useState<ControlledEngineAvailability | null>(null), [detectingEngine, setDetectingEngine] = useState(false);
const detection = useRef(0);
const [purge, setPurge] = useState(emptyPurgeDraft);
const [drafts, setDrafts] = useState([{ label: '核心实现', goal: '', paths: '' }, { label: '独立模块', goal: '', paths: '' }]);
const [tokens, setTokens] = useState(config.maxRunTokens), [steps, setSteps] = useState(Math.min(200, config.maxSteps * 2));
const [duration, setDuration] = useState(Math.floor(config.maxRunDurationMs / 60000)), [toolCalls, setToolCalls] = useState(96);
const [confirmation, setConfirmation] = useState<{ group: CollaborationGroup; operation: string; workerId?: string; retain?: boolean } | null>(null);
const [preview, setPreview] = useState<{ title: string; content: string; groupId: string } | null>(null), [readEvidenceSha, setReadEvidenceSha] = useState('');
const scope = useRef(0), requestId = useRef(0), fetchPending = useRef<number | null>(null), selectedGroup = useRef('');
const load = useCallback(async (quiet = false) => {
if (fetchPending.current !== null) return;
const generation = scope.current, request = ++requestId.current; fetchPending.current = request;
if (!quiet) setLoading(true);
try { const result = await api<WorkerView>('/sessions/' + session.id + '/collaborations'); if (generation === scope.current && request === requestId.current) setView(result); }
catch (failure) { if (generation === scope.current) setError(failure instanceof Error ? failure.message : String(failure)); }
finally { if (fetchPending.current === request) fetchPending.current = null; if (generation === scope.current) setLoading(false); }
}, [session.id]);
useEffect(() => { scope.current++; fetchPending.current = null; setView(null); setSelectedId(''); setCreating(false); setEngineInstallation(null); setEngineMode('workbench'); setDetectingEngine(false); setPurge(emptyPurgeDraft()); void load(); return () => { scope.current++; requestId.current++; detection.current++; }; }, [load]);
useEffect(() => { void load(true); }, [session.revision, load]);
const group = view?.groups.find(value => value.id === selectedId) ?? view?.groups.at(-1), running = !!group && active.includes(group.status);
selectedGroup.current = group?.id ?? '';
useEffect(() => { setError(''); setAction(''); setConfirmation(null); setPreview(null); setReadEvidenceSha(''); }, [session.id, group?.id, group?.evidence?.sha256]);
useEffect(() => { if (!running) return; const timer = setInterval(() => void load(true), 1500); return () => clearInterval(timer); }, [running, load]);
async function execute(group: CollaborationGroup, operation: string, extra: Record<string, unknown> = {}) {
if (selectedGroup.current !== group.id) return;
const generation = scope.current; setAction(operation); setError(''); setConfirmation(null);
try {
const result = await api<{ session: Session }>('/sessions/' + session.id + '/collaborations/' + group.id + '/' + operation, { fingerprint: group.fingerprint, ...extra });
if (generation !== scope.current || selectedGroup.current !== group.id) return;
onSession(result.session); await load(true);
} catch (failure) { if (generation === scope.current && selectedGroup.current === group.id) setError(failure instanceof Error ? failure.message : String(failure)); }
finally { if (generation === scope.current && selectedGroup.current === group.id) setAction(''); }
}
async function create() {
const generation = scope.current; setAction('plan'); setError('');
try {
const result = await api<{ group: CollaborationGroup; session: Session }>('/sessions/' + session.id + '/collaborations', {
goal, children: (engineMode === 'deepseek' ? drafts.slice(0, 1) : drafts).map(child => ({ label: child.label, goal: child.goal, paths: splitPaths(child.paths) })),
...(engineMode === 'deepseek' ? { engine: { id: 'deepseek-harness', root: engineInstallation?.root, controlledSha256: engineInstallation?.controlledSha256,
...(purge.enabled ? { strategy: purgeStrategyInput(purge) } : {}) } } : {}),
budget: { maxTokens: tokens, maxSteps: steps, maxToolCalls: toolCalls, maxDurationMs: duration * 60000 },
});
if (generation !== scope.current) return;
setSelectedId(result.group.id); setCreating(false); onSession(result.session); await load(true);
} catch (failure) { if (generation === scope.current) setError(failure instanceof Error ? failure.message : String(failure)); }
finally { if (generation === scope.current) setAction(''); }
}
async function detectEngine() {
const generation = scope.current, request = ++detection.current; setDetectingEngine(true); setError('');
try {
const result = await api<ControlledEngineAvailability>('/engines/deepseek/controlled-availability' + (engineRoot.trim() ? '?root=' + encodeURIComponent(engineRoot.trim()) : ''));
if (generation !== scope.current || request !== detection.current) return;
setEngineInstallation(result); if (result.root) setEngineRoot(result.root);
} catch (failure) { if (generation === scope.current && request === detection.current) setError(failure instanceof Error ? failure.message : String(failure)); }
finally { if (generation === scope.current && request === detection.current) setDetectingEngine(false); }
}
async function showRecord(group: CollaborationGroup, kind: 'collection' | 'evidence') {
const generation = scope.current; setAction('record'); setError('');
try { const result = await api<unknown>('/sessions/' + session.id + '/collaborations/' + group.id + '/' + kind); if (generation === scope.current && selectedGroup.current === group.id) { setPreview({ title: kind === 'collection' ? '原成果核对记录' : '原输入与现场核对', content: JSON.stringify(result, null, 2), groupId: group.id }); if (kind === 'evidence') setReadEvidenceSha(group.evidence?.sha256 ?? ''); } }
catch (failure) { if (generation === scope.current && selectedGroup.current === group.id) setError(failure instanceof Error ? failure.message : String(failure)); }
finally { if (generation === scope.current && selectedGroup.current === group.id) setAction(''); }
}
const canPlan = !!view && !view.worker && !busy && !action && view.groups.every(value => ['completed', 'discarded', 'resolved_external'].includes(value.status));
const engineReady = engineInstallation?.controlledStatus === 'available' && !!engineInstallation.controlledSha256;
const promptReady = purgeDraftReady(purge);
const visibleDrafts = engineMode === 'deepseek' ? drafts.slice(0, 1) : drafts;
return <div className="worker-console" aria-label="隔离协作控制台">
<div className="worker-console-heading"><div><p className="worker-eyebrow">工程执行 / 分工与引擎</p><h2>一个目标,独立执行与审查</h2><p>范围和预算固定,成果核对后进入父工程审查。</p></div><button className="button secondary" disabled={loading || !!action} onClick={() => void load()}><RefreshCw size={14} />刷新</button></div>
{error && <div className="worker-error" role="alert">{error}</div>}
{loading && !view && <p role="status"><LoaderCircle className="spin" size={16} />正在读取当前任务记录</p>}
{view?.worker ? <div className="worker-origin"><ShieldCheck size={22} /><div><h3>当前是受限子任务:{view.worker.label}</h3><p>固定范围:{view.worker.paths.join('、')}。开始、停止全部与成果合并在父目标中处理。</p><button className="button secondary" onClick={() => void onNavigate(view.worker!.parentProjectId, view.worker!.parentSessionId)}>返回父目标<ArrowUpRight size={14} /></button></div></div> : <>
{!!view?.groups.length && <label className="worker-history">协作记录<select value={group?.id ?? ''} onChange={event => { setSelectedId(event.target.value); setCreating(false); }} aria-label="选择协作记录">{view.groups.map(value => <option key={value.id} value={value.id}>{statusLabel(value.status)} · {value.goal.slice(0, 40)}</option>)}</select></label>}
{(!group || creating) && <div className="worker-plan-form">
<label>执行方式<select aria-label="执行方式" value={engineMode} onChange={event => setEngineMode(event.target.value as 'workbench' | 'deepseek')}><option value="workbench">工作台 · 两个受限子任务</option><option value="deepseek">DeepSeek Harness · 一个受控工程</option></select></label>
{engineMode === 'deepseek' && <section className="worker-engine-install" aria-label="受控引擎安装"><label>Harness 安装目录<input value={engineRoot} placeholder="留空检测已知本地安装" onChange={event => { detection.current++; setEngineRoot(event.target.value); setEngineInstallation(null); setDetectingEngine(false); }} /></label><button className="button secondary" disabled={detectingEngine || !!action} onClick={() => void detectEngine()}>{detectingEngine ? <LoaderCircle size={14} className="spin" /> : <ShieldCheck size={14} />}检测受控安装</button>{engineInstallation && <div role="status"><strong>{engineReady ? '受控安装可用' : '安装尚不可用'}</strong><p>{engineInstallation.message}</p>{engineReady && <code>Harness {engineInstallation.version} · {engineInstallation.controlledSha256?.slice(0, 16)}</code>}</div>}<p className="worker-note">模型连接由工作台使用;引擎只提交范围内的提案与检查请求,应用和检查仍需审查。</p></section>}
{engineMode === 'deepseek' && <PurgeStrategyControl value={purge} onChange={value => { setPurge(value); setError(''); }} busy={!!action} harnessRoot={engineInstallation?.root} />}
<label>父目标<textarea value={goal} onChange={event => setGoal(event.target.value)} placeholder="描述需要交付的结果与验收要求" maxLength={20000} rows={3} /></label>
<div className={'worker-lanes' + (engineMode === 'deepseek' ? ' single' : '')}>{visibleDrafts.map((child, index) => <fieldset key={index}><legend>{engineMode === 'deepseek' ? '引擎工程' : '子任务 ' + (index + 1)}</legend><label>任务名称<input value={child.label} maxLength={64} onChange={event => setDrafts(values => values.map((value, i) => i === index ? { ...value, label: event.target.value } : value))} /></label><label>独立子目标<textarea value={child.goal} maxLength={8000} rows={3} onChange={event => setDrafts(values => values.map((value, i) => i === index ? { ...value, goal: event.target.value } : value))} /></label><label>允许修改的文件或目录<textarea value={child.paths} rows={2} placeholder="例如 src/parser.mjs,每行一个相对路径" onChange={event => setDrafts(values => values.map((value, i) => i === index ? { ...value, paths: event.target.value } : value))} /></label></fieldset>)}</div>
<div className="worker-budget-form"><label>总 token 预算<input type="number" min={1000} max={config.maxRunTokens} value={tokens} onChange={event => setTokens(Number(event.target.value))} /></label><label>总请求轮次<input type="number" min={2} max={200} value={steps} onChange={event => setSteps(Number(event.target.value))} /></label><label>总工具次数<input type="number" min={2} max={512} value={toolCalls} onChange={event => setToolCalls(Number(event.target.value))} /></label><label>总时限(分钟)<input type="number" min={1} max={Math.floor(config.maxRunDurationMs / 60000)} value={duration} onChange={event => setDuration(Number(event.target.value))} /></label></div>
<p className="worker-note">{engineMode === 'deepseek' ? '这个引擎工程使用整份预算。' : '两份预算各分一半。'}续接沿用累计用量与原时限,实际模型尝试也计入轮次限制。来源只检出已提交 HEAD。</p>
<div className="worker-actions"><button className="button" disabled={!canPlan || !goal.trim() || visibleDrafts.some(child => !child.goal.trim() || !splitPaths(child.paths).length) || engineMode === 'deepseek' && (!engineReady || detectingEngine || !promptReady)} onClick={() => void create()}><ShieldCheck size={15} />封存分工计划</button>{creating && <button className="button secondary" onClick={() => setCreating(false)}>返回原协作</button>}</div>
</div>}
{group && !creating && <>
{group.children[0]?.engine?.strategy && <p className="worker-engine-badge">本计划的 Purge {group.children[0].engine.strategy.kind==='purge-original-restricted-v1'?'原版受限模式':'提示实验'} · {group.children[0].engine.strategy.source.version} · {group.children[0].engine.strategy.sha256.slice(0, 16)}</p>}
{group.evaluation && <p className="worker-note">本协作属于固定工程评测。执行与采纳请使用「工程评测」;这里保留原任务导航和中断现场核对。</p>}<section className="worker-parent"><div className="worker-parent-top"><span className={'worker-status ' + (group.requiresVerification || group.status === 'conflict' ? 'attention' : '')}>{statusLabel(group.status)}</span><code>{group.source.identity.branch} · {group.source.identity.head.slice(0, 12)}</code></div><h3>{group.goal}</h3><p>{group.summary}</p><dl><div><dt>模型</dt><dd>{group.model.mode === 'demo' ? '离线演示' : group.model.model}</dd></div><div><dt>执行方式</dt><dd>{group.children[0].engine ? "DeepSeek Harness " + group.children[0].engine.version : "工作台受限子任务"}</dd></div><div><dt>总预算</dt><dd>{number(group.budget.maxTokens)} tokens / {group.budget.maxSteps} 轮 / {group.budget.maxToolCalls} 次工具</dd></div><div><dt>累计用量</dt><dd>{number(group.usage?.accountedTokens)} tokens / {group.usage?.steps ?? 0} 轮 / {group.usage?.toolCalls ?? 0} 次工具 / {group.usage?.requests ?? 0} 次模型请求</dd></div><div><dt>原修改</dt><dd>{group.source.changedPaths.length ? group.source.changedPaths.map(value => value.path).join('、') : '无未提交修改'}</dd></div></dl></section>
<div className={"worker-lanes" + (group.children.length === 1 ? " single" : "")}>{(group.workers ?? []).map((child, index) => <section className="worker-lane" key={child.id}><div className="worker-lane-title"><span>通道 {index + 1}</span><span className={'worker-status ' + (child.requiresVerification ? 'attention' : '')}>{statusLabel(child.sessionStatus === 'awaiting_approval' ? 'awaiting_approval' : child.status)}</span></div><h3>{child.label}</h3>{child.engine && <p className="worker-engine-badge">DeepSeek Harness {child.engine.version} · 固定安装 {child.engine.controlledSha256?.slice(0, 12)}</p>}<p className="worker-goal">{child.goal}</p><div className="worker-scope"><span>允许修改</span>{child.paths.map(path => <code key={path}>{path}</code>)}</div><p className="worker-meter">{number(child.usage?.accountedTokens)} / {number(child.budget.maxTokens)} tokens · {child.usage?.steps ?? 0}/{child.budget.maxSteps} 轮</p><p className="worker-summary">{child.summary ?? '先创建独立工作区,再开始子任务。'}</p>{child.result && <div className="worker-proof"><Check size={14} />{child.result.paths.length} 个原改动 · 当前检查已封存</div>}<div className="worker-actions">{child.status !== 'unprepared' && <button className="button secondary" onClick={() => void onNavigate(child.projectId, child.sessionId, child.sessionStatus === "awaiting_approval" ? "approval" : child.sessionStatus === "needs_review" ? "changes" : "task")}>{child.sessionStatus === 'awaiting_approval' ? '查看并审批检查' : child.sessionStatus === 'needs_review' ? '审查子任务改动' : '打开子任务'}<ArrowUpRight size={13} /></button>}{!group.evaluation && ['ready', 'paused', 'failed', 'awaiting_review'].includes(child.status) && !running && child.sessionStatus !== 'needs_review' && <button className="text-button" disabled={!!action || config.mode === 'demo' || group.requiresVerification} onClick={() => setConfirmation({ group, operation: 'start', workerId: child.id })}><Play size={13} />继续子任务</button>}</div></section>)}</div>
<section className="worker-review"><div className="worker-review-title"><GitBranch size={18} /><h3>父工程成果审查</h3></div>{group.collection ? <><p>{group.collection.paths.length} 个路径已核对,原记录 <code>{group.collection.sha256.slice(0, 16)}</code></p>{group.collection.conflicts.length > 0 && <ul className="worker-conflicts">{group.collection.conflicts.map((conflict, i) => <li key={i}><code>{conflict.path}</code><span>{conflict.reason}</span></li>)}</ul>}<button className="text-button" disabled={!!action} onClick={() => void showRecord(group, 'collection')}>查看原成果记录</button></> : <p>等待 {group.children.length} 个子任务完成实际修改与检查。重叠路径、来源变化或原证据失效会阻止合并。</p>}{group.merge?.changeSetId && <button className="button secondary" onClick={onReview}>打开父工程变更集审查<ArrowUpRight size={14} /></button>}</section>
<div className="worker-actions worker-primary-actions">
{!group.evaluation && ['planned', 'partially_prepared'].includes(group.status) && <button className="button" disabled={!!action || busy} onClick={() => setConfirmation({ group, operation: 'prepare' })}><GitBranch size={15} />{group.children.length === 2 ? '创建两个工作区' : '创建引擎工作区'}</button>}
{!group.evaluation && ['ready', 'paused', 'awaiting_review'].includes(group.status) && <button className="button" disabled={!!action || running || config.mode === 'demo' || group.requiresVerification || group.workers?.some(child => child.sessionStatus === 'needs_review')} onClick={() => setConfirmation({ group, operation: 'start' })}><Play size={15} />{group.status === 'ready' ? group.children.length === 2 ? '开始两个子任务' : '开始引擎任务' : '继续未完成子任务'}</button>}
{running && <button className="button worker-stop" disabled={action === 'stop'} onClick={() => void execute(group, 'stop')}><Square size={14} />停止全部</button>}
{!group.evaluation && ['ready_to_collect', 'collected', 'conflict'].includes(group.status) && <button className="button secondary" disabled={!!action || running} onClick={() => void execute(group, 'collect')}><ShieldCheck size={15} />核对成果</button>}
{!group.evaluation && group.status === 'collected' && <button className="button" disabled={!!action} onClick={() => void execute(group, 'merge')}><GitBranch size={15} />准备合并审查</button>}
{!group.evaluation && group.merge?.changeSetId && <button className="button secondary" disabled={!!action || busy} onClick={() => void execute(group, 'finalize')}>核对检查与 Git 交付</button>}
{group.requiresVerification && <><button className="button secondary" disabled={!!action || running} onClick={() => void execute(group, 'reconcile')}>核对原输入与现场</button>{group.evidence && <><button className="text-button" disabled={!!action} onClick={() => void showRecord(group, 'evidence')}>查看核对记录</button><button className="button secondary" disabled={!!action || readEvidenceSha !== group.evidence.sha256} onClick={() => setConfirmation({ group, operation: 'acknowledge' })}>确认核对并继续</button><button className="text-button" disabled={!!action || readEvidenceSha !== group.evidence.sha256} onClick={() => setConfirmation({ group, operation: 'acknowledge', retain: true })}>确认核对并保留现场结束</button></>}</>}
{!running && !group.requiresVerification && !['completed', 'discarded', 'resolved_external'].includes(group.status) && <button className="text-button" disabled={!!action} onClick={() => setConfirmation({ group, operation: 'discard' })}>结束协作并保留现场</button>}
{canPlan && <button className="button secondary" onClick={() => { setPurge(emptyPurgeDraft()); setCreating(true); }}>创建下一父目标</button>}
</div>
{config.mode === 'demo' && ['ready', 'paused'].includes(group.status) && <p className="worker-note">当前为离线演示。请先配置可用模型,再新建使用该模型快照的协作计划。</p>}
</>}
</>}
<p className="worker-boundary"><ShieldCheck size={14} />独立工作区与受限工具用于约束任务;审批的工程程序仍以本机账户执行。</p>
{confirmation && <Modal title={confirmation.operation === 'start' ? '确认受限子执行' : confirmation.operation === 'prepare' ? '确认创建隔离工作区' : confirmation.operation === 'acknowledge' && !confirmation.retain ? '确认原结果核对' : '确认保留现场'} onClose={() => setConfirmation(null)}><div className="worker-confirm"><p>{confirmation.operation === 'start' ? '将请求已封存模型并使用剩余累计预算。每项工程检查仍在对应子任务中审批;旧工具不会重放。' : confirmation.operation === 'prepare' ? '按已封存 HEAD 创建 ' + confirmation.group.children.length + ' 个独立 Git 工作区。原暂存与未提交修改保持在来源工程。' : confirmation.operation === 'acknowledge' && !confirmation.retain ? '按已阅读的原输入与现场记录解除核对门控。原未知结果保留,继续需要新检查和审批。' : '保留实际工作区、原任务、改动与报告,撤销未执行计划并结束本次协作;本次不记为交付完成。'}<strong>{confirmation.group.goal}</strong></p><button className="button" disabled={!!action || confirmation.operation === 'acknowledge' && readEvidenceSha !== confirmation.group.evidence?.sha256} onClick={() => void execute(confirmation.group, confirmation.operation, { ...(confirmation.workerId ? { workerId: confirmation.workerId } : {}), ...(confirmation.operation === 'acknowledge' ? { evidenceSha256: readEvidenceSha, retain: !!confirmation.retain } : {}) })}>确认{confirmation.operation === 'start' ? '开始' : confirmation.operation === 'prepare' ? '创建' : confirmation.operation === 'acknowledge' && !confirmation.retain ? '核对并继续' : '保留现场结束'}</button></div></Modal>}
{preview && <Modal title={preview.title} wide onClose={() => setPreview(null)}><div className="worker-record"><button className="button secondary" onClick={() => downloadBlob(new Blob([preview.content], { type: 'application/json' }), 'agent-workbench-collaboration-' + preview.groupId + '.json')}>导出原记录</button><pre>{preview.content}</pre></div></Modal>}
</div>;
}
@@ -0,0 +1,44 @@
.workspace-panel { min-width: 0; }
.workspace-prepare { display: flex; flex-direction: column; gap: 8px; margin-top: 12px; }
.workspace-prepare label { font-size: 11px; color: var(--muted); }
.workspace-prepare input { width: 100%; min-width: 0; border: 1px solid var(--line); border-radius: 5px; padding: 9px 10px; background: #fff; font-size: 12px; }
.workspace-prepare .button { align-self: flex-start; }
.workspace-record { padding: 13px 0 0; margin-top: 16px; border-top: 1px solid var(--line); font-size: 11px; line-height: 1.8; }
.workspace-record-heading { display: flex; justify-content: space-between; align-items: flex-start; gap: 8px; }
.workspace-record-heading strong { font-size: 12px; overflow-wrap: anywhere; }
.workspace-record-heading span { color: var(--muted); font-size: 10px; flex-shrink: 0; }
.workspace-ready .workspace-record-heading span { color: var(--teal); }
.workspace-unknown .workspace-record-heading span { color: #805d22; }
.workspace-branch { display: block; margin-top: 6px; overflow-wrap: anywhere; color: var(--teal); font-size: 10px; }
.workspace-record > p { margin: 8px 0; color: var(--muted); }
.workspace-record details { margin-top: 10px; }
.workspace-record summary, .workspace-review summary { cursor: pointer; color: var(--teal); font-size: 11px; }
.workspace-fields { display: grid; grid-template-columns: 68px minmax(0, 1fr); gap: 7px 8px; margin: 10px 0; }
.workspace-fields dt { color: var(--muted); }
.workspace-fields dd { margin: 0; min-width: 0; }
.workspace-fields code { font-size: 10px; overflow-wrap: anywhere; }
.workspace-actions { display: flex; flex-wrap: wrap; align-items: center; gap: 5px 12px; margin-top: 9px; }
.workspace-actions .text-button, .workspace-current .text-button { padding-left: 0; }
.workspace-current { padding: 11px; border-left: 2px solid var(--teal); background: #edf3f1; font-size: 11px; line-height: 1.8; }
.workspace-current > span { display: block; color: var(--muted); font-size: 10px; }
.workspace-current > code { display: block; margin-top: 3px; overflow-wrap: anywhere; color: var(--teal); font-size: 10px; }
.workspace-current p { margin-top: 7px; }
.workspace-problems { display: flex; align-items: flex-start; gap: 7px; padding: 9px; background: #faf4e8; color: #805d22; border-radius: 5px; }
.workspace-problems svg { margin-top: 3px; flex-shrink: 0; }
.workspace-problems ul { margin: 0; padding-left: 14px; overflow-wrap: anywhere; }
.workspace-review { flex: 1; min-height: 0; overflow: auto; padding: 1px; font-size: 12px; line-height: 1.85; }
.workspace-review > p { margin: 12px 0; }
.workspace-track { padding: 14px; border: 1px solid var(--line); border-radius: 6px; }
.workspace-track > span { display: block; color: var(--muted); font-size: 11px; }
.workspace-track > strong { display: block; font-size: 15px; margin: 3px 0 7px; }
.workspace-track > code { display: block; font-size: 11px; overflow-wrap: anywhere; }
.workspace-track > p { margin-top: 5px; color: var(--muted); font-size: 11px; }
.workspace-track-child { border-color: #b6ccc4; background: #edf3f1; }
.workspace-track-child > code { color: var(--teal); }
.workspace-track-arrow { display: block; margin: 8px auto; color: var(--teal); }
.workspace-source-note { padding: 10px 12px; border-left: 2px solid #bd9654; background: #faf7ef; }
.workspace-source-paths { padding: 0; list-style: none; }
.workspace-source-paths li { display: flex; gap: 8px; padding: 5px 0; font-size: 11px; }
.workspace-source-paths code { white-space: pre; color: var(--muted); }
.workspace-source-paths span { overflow-wrap: anywhere; }
@media (max-width: 620px) { .workspace-review { font-size: 11px; } .workspace-track { padding: 11px; } .workspace-record-heading { flex-wrap: wrap; } }
@@ -0,0 +1,91 @@
import { useEffect, useRef, useState } from 'react';
import { ArrowDown, ArrowLeft, Check, FolderGit2, GitBranch, LoaderCircle, RefreshCw, ShieldQuestion } from 'lucide-react';
import { api } from './api';
import { Modal } from './components';
import type { Project, Session, WorkspaceRecord } from './types';
import './WorkspacePanel.css';
const active = ['creating', 'verifying', 'registering'];
const labels: Record<string, string> = { prepared: '等待确认创建', creating: '正在创建独立分支', verifying: '正在核对文件与分支', registering: '正在登记项目与会话', ready: '可以开始开发', unknown: '创建结果需要核对', resolved_external: '已保留外部状态', discarded: '计划已撤销' };
export function WorkspacePanel({ project, session, busy, onRefresh, onNavigate, onError }: {
project: Project; session: Session; busy: boolean;
onRefresh: (projectId: string, sessionId: string, isCurrent?: () => boolean) => Promise<void>;
onNavigate: (projectId: string, sessionId: string, isCurrent?: () => boolean) => Promise<void>;
onError: (error: unknown) => void;
}) {
const records = session.execution?.workspaces ?? [];
const [label, setLabel] = useState('');
const [working, setWorking] = useState('');
const [confirm, setConfirm] = useState<WorkspaceRecord | null>(null);
const [external, setExternal] = useState<WorkspaceRecord | null>(null);
const identity = useRef(0), inFlight = useRef(false);
const unresolved = records.some(value => value.requiresVerification || value.status === 'prepared' || active.includes(value.status));
useEffect(() => {
identity.current++; inFlight.current = false; setWorking(''); setLabel(''); setConfirm(null); setExternal(null);
return () => { identity.current++; };
}, [project.id, session.id]);
async function perform(action: string, record?: WorkspaceRecord) {
if (inFlight.current) return;
inFlight.current = true; const request = ++identity.current; setWorking(record?.id ?? 'prepare');
try {
const value = await api<WorkspaceRecord>(`/sessions/${session.id}/workspaces${record ? '/' + record.id + '/' + action : ''}`,
record ? { fingerprint: record.fingerprint, ...(action === 'acknowledge' ? { observationFingerprint: record.observation?.fingerprint } : {}) } : { label: label.trim() });
if (request !== identity.current) return;
await onRefresh(project.id, session.id, () => request === identity.current);
if (request !== identity.current) return;
if (action === 'prepare') { setConfirm(value); setLabel(''); }
else { setConfirm(null); setExternal(null); }
} catch (error) { if (request === identity.current) onError(error); }
finally { if (request === identity.current) { inFlight.current = false; setWorking(''); } }
}
async function navigate(projectId: string, sessionId: string, record?: WorkspaceRecord) {
if (inFlight.current) return;
inFlight.current = true; const request = ++identity.current; setWorking(record?.id ?? 'origin');
try {
if (record) await api(`/sessions/${record.sessionId}/workspaces/${record.id}/open`, {});
if (request !== identity.current) return;
await onNavigate(projectId, sessionId, () => request === identity.current);
} catch (error) { if (request === identity.current) onError(error); }
finally { if (request === identity.current) { inFlight.current = false; setWorking(''); } }
}
return <section className="task-record-section workspace-panel" aria-label="独立开发工作区">
<div className="record-heading"><FolderGit2 size={15} /><h3>独立开发工作区</h3></div>
{project.workspace && <div className="workspace-current"><span>当前独立分支</span><code>{project.workspace.branch}</code><p>修改、检查和提交都在此目录执行。交付后可以审查,再合并回来源项目。</p><button type="button" className="text-button" disabled={!!working} onClick={() => navigate(project.workspace!.sourceProjectId, project.workspace!.sourceSessionId)}><ArrowLeft size={13} />返回来源会话</button></div>}
<p className="record-footnote">从当前已提交版本创建独立目录和分支,让新任务有明确的开发范围。</p>
<form className="workspace-prepare" onSubmit={event => { event.preventDefault(); perform('prepare'); }}>
<label htmlFor={'workspace-label-' + session.id}>工作区名称</label>
<input id={'workspace-label-' + session.id} value={label} onChange={event => setLabel(event.target.value)} maxLength={64} placeholder="例如:订单导出功能" disabled={busy || !!working || unresolved} />
<button type="submit" className="button secondary" disabled={!label.trim() || busy || !!working || unresolved}>{working === 'prepare' ? <LoaderCircle size={14} className="spin" /> : <GitBranch size={14} />}准备独立工作区</button>
</form>
{records.slice().reverse().map(record => <article className={'workspace-record workspace-' + record.status} key={record.id}>
<div className="workspace-record-heading"><strong>{record.label}</strong><span>{labels[record.status] || record.status}</span></div>
<code className="workspace-branch">{record.branch}</code><p>{record.summary}</p>
{record.observation?.problems.length ? <div className="workspace-problems" role="status"><ShieldQuestion size={14} /><ul>{record.observation.problems.map((value, index) => <li key={index}>{value}</li>)}</ul></div> : null}
<details><summary>目录与来源</summary><dl className="workspace-fields"><dt>来源目录</dt><dd><code>{record.source.root}</code></dd><dt>起始提交</dt><dd><code>{record.source.head}</code></dd><dt>工作区目录</dt><dd><code>{record.root}</code></dd></dl></details>
<div className="workspace-actions">
{record.sessionId !== session.id ? <button type="button" className="text-button" disabled={!!working} onClick={() => navigate(record.projectId, record.sessionId)}>转到所属会话</button> : <>
{record.status === 'prepared' && <><button type="button" className="text-button" disabled={busy || !!working} onClick={() => setConfirm(record)}>查看创建预览</button><button type="button" className="text-button" disabled={busy || !!working} onClick={() => perform('discard', record)}>撤销计划</button></>}
{active.includes(record.status) && <button type="button" className="text-button" disabled={!!working} onClick={() => perform('stop', record)}>停止创建</button>}
{record.status === 'unknown' && <><button type="button" className="text-button" disabled={busy || !!working} onClick={() => perform('reconcile', record)}>{working === record.id ? <LoaderCircle size={13} className="spin" /> : <RefreshCw size={13} />}核对创建结果</button>{record.observation && <button type="button" className="text-button" disabled={busy || !!working} onClick={() => setExternal(record)}>保留当前外部状态</button>}</>}
{record.status === 'ready' && <button type="button" className="button secondary" disabled={!!working} onClick={() => navigate(record.childProjectId, record.childSessionId, record)}><FolderGit2 size={14} />打开此工作区</button>}
</>}
</div>
</article>)}
{confirm && <Modal title="创建独立工作区" description="核对来源版本和新目录后,再开始这个工作区的开发。" onClose={() => { if (!working) setConfirm(null); }}>
<div className="workspace-review">
<div className="workspace-track"><span>来源已提交版本</span><strong>{project.name}</strong><code>{confirm.source.branch} · {confirm.source.head.slice(0, 12)}</code><p>{confirm.source.treeFiles.length} 份文件 · {(confirm.source.committedBytes / 1024).toFixed(1)} KB</p></div>
<ArrowDown size={18} className="workspace-track-arrow" aria-hidden="true" />
<div className="workspace-track workspace-track-child"><span>新独立工作区</span><strong>{confirm.label}</strong><code>{confirm.branch}</code><code>{confirm.root}</code></div>
<p className="workspace-source-note">{confirm.source.dirty ? `来源有 ${confirm.source.changedPathCount} 项未提交改动,将保留在来源目录。新工作区使用上方已提交版本。` : '来源目录当前没有未提交改动。'}</p>
{!!confirm.source.changedPaths.length && <details><summary>查看来源已有改动</summary><ul className="workspace-source-paths">{confirm.source.changedPaths.map(value => <li key={value.path}><code>{value.status}</code><span>{value.path}</span></li>)}</ul></details>}
<p className="record-footnote">创建后打开为新的项目和会话。需要的依赖可在工作区中审查安装。</p>
</div>
<div className="modal-actions"><button type="button" className="button secondary" disabled={!!working} onClick={() => setConfirm(null)}>稍后创建</button><button type="button" className="button primary" disabled={busy || !!working} onClick={() => perform('create', confirm)}>{working ? <LoaderCircle size={14} className="spin" /> : <Check size={14} />}确认创建工作区</button></div>
</Modal>}
{external && <Modal title="保留当前外部状态" description="结束本次创建结果核对,目录与分支继续保留。" onClose={() => { if (!working) setExternal(null); }}><div className="workspace-review"><p>这次创建将记为“已保留外部状态”。需要继续开发时,请核对目录后从项目栏打开;这项操作不会把创建记为成功。</p><code className="workspace-branch">{external.root}</code>{external.observation?.problems.map((value, i) => <p key={i}>{value}</p>)}</div><div className="modal-actions"><button type="button" className="button secondary" disabled={!!working} onClick={() => setExternal(null)}>返回核对</button><button type="button" className="button primary" disabled={!!working} onClick={() => perform('acknowledge', external)}>确认保留当前状态</button></div></Modal>}
</section>;
}
@@ -0,0 +1,73 @@
let accessToken = '';
export function setToken(token: string) { accessToken = token; }
export async function api<T>(path: string, input?: unknown,method?:string): Promise<T> {
const response = await fetch('/api' + path, {
method: method??(input === undefined ? 'GET' : 'POST'),
headers: { 'Content-Type': 'application/json', ...(accessToken ? { 'X-Workbench-Token': accessToken } : {}) },
...(input === undefined ? {} : { body: JSON.stringify(input) }),
});
const body = await response.json();
if (!response.ok) throw Object.assign(new Error(body.error || '请求失败,请重试。'), { status: response.status, diagnostic: body.diagnostic ?? null });
return body as T;
}
export async function exportSession(id: string) {
const response = await fetch('/api/sessions/' + id + '/export', { headers: { 'X-Workbench-Token': accessToken } });
if (!response.ok) throw new Error('会话导出失败。');
const blob = await response.blob();
downloadBlob(blob, 'agent-workbench-session-' + id + '.json');
}
export async function browsingScreenshot(sessionId:string,observationId:string) {
const response=await fetch('/api/sessions/'+sessionId+'/browsing/observations/'+observationId+'/image',{headers:{'X-Workbench-Token':accessToken}});
if(!response.ok)throw new Error('原页面截图读取失败,请核对原观察记录。');
const bytes=await response.arrayBuffer(),digest=await crypto.subtle.digest('SHA-256',bytes),sha=Array.from(new Uint8Array(digest)).map(value=>value.toString(16).padStart(2,'0')).join('');
if(sha!==response.headers.get('X-Content-SHA256'))throw new Error('原页面截图SHA-256不一致。');
return URL.createObjectURL(new Blob([bytes],{type:'image/png'}));
}
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) {
const value = await response.json().catch(() => ({}));
throw new Error(value.error || '工件下载失败。');
}
downloadBlob(await response.blob(), name);
}
export async function downloadResearchDocument(sessionId: string, jobId: string, kind: 'bundle' | 'raw' = 'bundle') {
const response = await fetch('/api/sessions/' + sessionId + '/research/jobs/' + jobId + '/download?kind=' + kind, { 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-rea-' + kind + '-' + jobId + '.json');
}
export function downloadBlob(blob: Blob, name: string) {
const url = URL.createObjectURL(blob);
const link = document.createElement('a'); link.href = url; link.download = name; link.click();
setTimeout(() => URL.revokeObjectURL(url), 1000);
}
export async function downloadEngineReport(sessionId: string, jobId: string) {
const response = await fetch('/api/sessions/' + sessionId + '/engines/jobs/' + jobId + '/download', { 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-engine-' + jobId + '.json');
}
export async function downloadEngineRunReport(sessionId: string, jobId: string) {
const response = await fetch('/api/sessions/' + sessionId + '/engine-runs/' + jobId + '/download', { 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-engine-run-' + jobId + '.json');
}
export async function browserImageBlob(sessionId: string, jobId: string, artifactId: string): Promise<Blob> {
const response = await fetch('/api/sessions/' + sessionId + '/browser-jobs/' + jobId + '/images/' + artifactId, { headers: { 'X-Workbench-Token': accessToken } });
if (!response.ok) { const value = await response.json().catch(() => ({})); throw new Error(value.error || '页面截图读取失败。'); }
return response.blob();
}
export async function inputImageBlob(sessionId:string,image:import('./types').InputAttachment,original=false):Promise<Blob>{
const response=await fetch('/api/sessions/'+sessionId+'/input-attachments/'+image.id+'/'+(original?'original':'image'),{headers:{'X-Workbench-Token':accessToken},cache:'no-store'});
if(!response.ok){const value=await response.json().catch(()=>({}));throw new Error(value.error||'截图读取失败,请刷新核对。');}
const bytes=await response.arrayBuffer(),digest=Array.from(new Uint8Array(await crypto.subtle.digest('SHA-256',bytes)),value=>value.toString(16).padStart(2,'0')).join('');
if(digest!==(original?image.sha256:image.sentSha256))throw new Error('截图SHA-256核对失败,未展示或下载。');
return new Blob([bytes],{type:original?image.mediaType:'image/png'});
}
@@ -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}}
@@ -0,0 +1,26 @@
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 {
browserObservations?:{id:string;tabId:string;url:string;title:string;createdAt:string;revision:string;scope:{complete:boolean};screenshotSha256:string}[];
inputAttachments?: import('./types').InputAttachment[];
budgetPause?: import('./types').BudgetPause|null;
task: { id: string; goal: string; status: string; usage: MobileUsage; budget: { maxTokens: number }; verification: { status: string }; delivery?: { status: string; paths: string[]; checks: string } } | null;
fileResults?: { id: string; taskId: string; runId: string; verification: string; reason: string; contractSha256: string; files: { path: string; sha256: string; bytes: number; origin: { taskId: string; runId: string; sha256: 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;
stream?: { status: string; protocol?: string; textCharacters?: number; textPreview?: string; toolFragments?: 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; kind?: 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 }[];
}
@@ -0,0 +1,190 @@
import { useEffect, useRef } from 'react';
import type { ReactNode, ButtonHTMLAttributes } from 'react';
import { createPortal } from 'react-dom';
import { AlertTriangle, Check, ChevronRight, Circle, Clock3, FileCode2, LoaderCircle, RotateCw, ShieldQuestion, SquareTerminal, X, XCircle } from 'lucide-react';
import type { Change, ToolEvent, RuntimeFailure } from './types';
import { ModelErrorDetails } from './ModelErrorDetails';
const statusNames: Record<string, string> = {
idle: '就绪', running: '执行中', awaiting_approval: '等待确认', needs_review: '待审查', completed: '已完成',
paused: '已暂停', failed: '需要处理', stopping: '正在停止', pending: '待审查', applied: '已应用',
rejected: '已撤回', conflict: '文件已变化', waiting: '等待确认', denied: '已拒绝', interrupted: '已中断',
retrying: '自动重试',
queued: '待执行', validating: '核对中', unknown: '结果待核对', unverified: '未验证',
not_configured: '尚未检查', passed: '检查通过', cancelled: '已取消', stale: '需重新检查',
planned: '待确认', preparing: '准备提交', prepared: '准备完成', publishing: '发布本地提交', committed: '已生成提交',
reporting: '生成报告',
ready: '可核验', blocked: '等待前置', verified: '已核验', incomplete: '尚未完成', needs_update: '要求已更新', not_planned: '尚未规划',
snapshotting: '封存构建', launching: '启动浏览器', closing: '关闭浏览器', observed: '页面已观察',
applying: '应用中', rolling_back: '回退中', rolled_back: '已回退', partial: '部分结果待核对',
resolved_external: '已保留外部修改', external_preserved: '外部内容已保留',
};
export function Status({ value }: { value: string }) {
return <span className={'status status-' + value}><span className="status-dot" />{statusNames[value] || value}</span>;
}
export function IconButton({ label, children, className = '', ...props }: ButtonHTMLAttributes<HTMLButtonElement> & { label: string; children: ReactNode }) {
return <button type="button" className={'icon-button ' + className} aria-label={label} title={label} {...props}>{children}</button>;
}
export function Modal({ title, description, children, onClose, wide = false }: { title: string; description?: string; children: ReactNode; onClose: () => void; wide?: boolean }) {
const panel = useRef<HTMLDivElement>(null);
const close = useRef(onClose); close.current = onClose;
useEffect(() => {
const previous = document.activeElement as HTMLElement | null;
panel.current?.querySelector<HTMLElement>('input, select, textarea, button')?.focus();
const handle = (event: KeyboardEvent) => {
const dialogs = document.querySelectorAll('[role="dialog"][aria-modal="true"]');
if (dialogs[dialogs.length - 1] !== panel.current) return;
if (event.key === 'Escape') { event.preventDefault(); event.stopPropagation(); close.current(); }
if (event.key === 'Tab') {
const elements = Array.from(panel.current?.querySelectorAll<HTMLElement>('button, input, select, textarea, a[href]') || [])
.filter(element => !element.hasAttribute('disabled') && element.offsetParent !== null);
const first = elements[0], last = elements.at(-1);
if (event.shiftKey && document.activeElement === first) { event.preventDefault(); last?.focus(); }
else if (!event.shiftKey && document.activeElement === last) { event.preventDefault(); first?.focus(); }
}
};
document.addEventListener('keydown', handle);
return () => { document.removeEventListener('keydown', handle); if (previous?.isConnected) previous.focus(); };
}, []);
return createPortal(<div className="modal-backdrop" onMouseDown={event => { if (event.target === event.currentTarget) onClose(); }}>
<div ref={panel} role="dialog" aria-modal="true" aria-label={title} className={'modal ' + (wide ? 'modal-wide' : '')}>
<div className="modal-heading"><div><h2>{title}</h2>{description && <p>{description}</p>}</div><IconButton label="关闭窗口" onClick={onClose}><X size={18} /></IconButton></div>
{children}
</div>
</div>, document.body);
}
export function DiffView({ change }: { change: Change }) {
const viewport = useRef<HTMLDivElement>(null);
function jumpToFirstChange() {
const area = viewport.current, row = area?.querySelector<HTMLElement>('.diff-added, .diff-removed');
if (area && row) area.scrollTop += row.getBoundingClientRect().top - area.getBoundingClientRect().top - 85;
}
useEffect(() => {
const frame = requestAnimationFrame(jumpToFirstChange);
return () => cancelAnimationFrame(frame);
}, [change.id]);
let before = 1, after = 1;
const rows: { before: number | null; after: number | null; text: string; kind: string }[] = [];
for (const part of change.diff) {
const lines = part.value.split('\n');
if (lines.at(-1) === '') lines.pop();
for (const line of lines) {
rows.push({ before: part.added ? null : before++, after: part.removed ? null : after++, text: line.replace(/\r$/, ''),
kind: part.added ? 'added' : part.removed ? 'removed' : 'same' });
}
}
return <div className="diff-view" aria-label={'文件差异 ' + change.path} ref={viewport}>
<div className="diff-caption"><span>{change.baseExists ? '原文件 → 建议内容' : '新建文件'}</span><button type="button" className="diff-jump" onClick={jumpToFirstChange}>定位首处改动</button><span className="code-utility">{change.baseSha256?.slice(0, 10) || 'NEW'}</span></div>
{rows.length ? rows.map((row, index) => <div key={index} className={'diff-line diff-' + row.kind}>
<span className="line-number">{row.before}</span><span className="line-number">{row.after}</span>
<span className="diff-sign">{row.kind === 'added' ? '+' : row.kind === 'removed' ? '−' : ' '}</span><code>{row.text || ' '}</code>
</div>) : <p className="subtle empty-line">建议内容为空。</p>}
</div>;
}
export function ToolRow({ event, selected = false, onSelect }: { event: ToolEvent; selected?: boolean; onSelect: () => void }) {
const phase = event.phase;
const label = event.kind === 'model' && event.diagnostic?.kind === 'model_identity' ? event.diagnostic.title : event.label;
const Symbol = ['waiting', 'unknown', 'unverified', 'queued', 'validating'].includes(phase) ? ShieldQuestion : ['running', 'retrying'].includes(phase) ? LoaderCircle
: ['failed', 'denied', 'interrupted'].includes(phase) ? XCircle : Check;
const detail = event.tool === 'run_command' ? String(event.input?.command || '')
: ['read_file', 'propose_file', 'propose_patch'].includes(event.tool || '') ? String(event.input?.path || '')
: ['search_files', 'query_code'].includes(event.tool || '') ? String(event.input?.query || '') : event.tool === 'list_files' ? '项目目录'
: event.tool === 'index_project' ? '当前项目 · 声明与导入'
: event.tool === 'inspect_session' ? '会话 · 错误 · 当前状态' : event.kind === 'model' ? '模型服务' + (event.attempts && event.attempts > 1 ? ' · 第 ' + event.attempts + ' 次' : '') : '';
return <button type="button" onClick={onSelect} className={'tool-row ' + (selected ? 'selected ' : '') + 'tool-' + phase}>
<span className="tool-symbol"><Symbol size={14} className={['running', 'retrying'].includes(phase) ? 'spin' : ''} /></span>
<span className="tool-name"><strong>{label}</strong>{detail && <span>{detail}</span>}</span>
<span className="tool-end">{event.durationMs !== undefined ? (event.durationMs / 1000).toFixed(1) + 's' : phase === 'waiting' ? '待确认' : '…'}<ChevronRight size={13} /></span>
</button>;
}
export function ModelStreamPreview({ event }: { event: ToolEvent }) {
const stream = event.stream;
if (!stream || stream.status === 'completed') return null;
return <div className="model-stream-preview" aria-label="模型输出片段"><div><strong>{stream.status === 'receiving' ? '正在接收' : '输出未完成'}</strong><span>{stream.protocol === 'responses' ? 'Responses' : 'Chat Completions'} · {stream.textCharacters ?? 0} 字符{stream.toolFragments ? ' · ' + stream.toolFragments + ' 个工具参数片段' : ''}</span></div>
{stream.textPreview && <pre>{stream.textPreview}</pre>}<p>片段仅供查看。完整响应核对前不执行工具;中断后保留原记录。</p></div>;
}
export function FailureCard({ failure, onDiagnose, onRetry, busy = false }: { failure: RuntimeFailure; onDiagnose: () => void; onRetry?: () => void; busy?: boolean }) {
return <div className="failure-card" role="alert">
<div className="failure-heading"><AlertTriangle size={17} /><span>{failure.source === 'model_connection' ? '模型连接' : '工作台运行'}</span><strong>{failure.title}</strong></div>
<p>{failure.message}</p>
{failure.suggestion && <p className="failure-suggestion">{failure.suggestion}</p>}
<div className="failure-meta"><span>{failure.stage === 'model_request' ? '发生在请求模型响应时' : '发生在工作台任务执行时'}</span>{failure.attempts && <span>{failure.attempts} 次请求</span>}{failure.httpStatus && <code>HTTP {failure.httpStatus}</code>}{failure.code && <code>{failure.code}</code>}</div>
<ModelErrorDetails failure={failure} />
<div className="failure-actions"><button type="button" className="button secondary" onClick={onDiagnose}>查看运行诊断</button>{onRetry && <button type="button" className="button primary" onClick={onRetry} disabled={busy}><RotateCw size={14} />{failure.source === 'model_connection' ? '重试模型请求' : '继续任务'}</button>}</div>
</div>;
}
export function EmptyInspector({ kind }: { kind: 'file' | 'changes' | 'trace' }) {
const Icon = kind === 'file' ? FileCode2 : kind === 'changes' ? Check : SquareTerminal;
return <div className="empty-inspector"><span className="empty-inspector-symbol"><Icon size={25} strokeWidth={1.5} /></span>
<h3>{kind === 'file' ? '查看项目文件' : kind === 'changes' ? '这里展示待审查改动' : '执行过程会记录在这里'}</h3>
<p>{kind === 'file' ? '从左侧打开文件,或让助手先读取项目。' : kind === 'changes' ? '助手提出修改后,可以查看完整差异,再决定是否应用。' : '每次工具调用都会保留参数、结果和完成状态。'}</p>
</div>;
}
function inlineText(text: string): ReactNode[] {
const pattern = /(`[^`]+`|\*\*[^*]+\*\*|\[[^\]]+\]\([^)]+\))/g;
const nodes: ReactNode[] = [];
let previous = 0;
for (const match of text.matchAll(pattern)) {
const index = match.index!;
if (index > previous) nodes.push(text.slice(previous, index));
const token = match[0];
if (token.startsWith('`')) nodes.push(<code key={index}>{token.slice(1, -1)}</code>);
else if (token.startsWith('**')) nodes.push(<strong key={index}>{token.slice(2, -2)}</strong>);
else {
const parts = token.match(/^\[([^\]]+)\]\(([^)]+)\)$/)!;
nodes.push(/^https?:\/\//.test(parts[2]) ? <a key={index} href={parts[2]} target="_blank" rel="noreferrer">{parts[1]}</a> : <span key={index} title={parts[2]}>{parts[1]}</span>);
}
previous = index + token.length;
}
if (previous < text.length) nodes.push(text.slice(previous));
return nodes;
}
export function ResearchContent({ content }: { content: string }) {
const lines = content.replaceAll('\r', '').split('\n');
const blocks: ReactNode[] = [];
const cells = (line: string) => line.replace(/^\|/, '').replace(/\|$/, '').split('|').map(cell => cell.trim());
for (let index = 0; index < lines.length; index++) {
const line = lines[index];
if (!line.trim()) continue;
const heading = line.match(/^(#{1,4})\s+(.+)/);
if (heading) {
const Tag = heading[1].length <= 1 ? 'h2' : heading[1].length === 2 ? 'h3' : 'h4';
blocks.push(<Tag key={index}>{inlineText(heading[2])}</Tag>); continue;
}
if (line.startsWith('```')) {
const body = []; const key = index;
while (++index < lines.length && !lines[index].startsWith('```')) body.push(lines[index]);
blocks.push(<pre key={key}><code>{body.join('\n')}</code></pre>); continue;
}
if (line.includes('|') && /^\s*\|?[\s:|-]+\|?\s*$/.test(lines[index + 1] ?? '') && lines[index + 1]?.includes('---')) {
const headings = cells(line), rows = [], key = index; index++;
while (lines[index + 1]?.includes('|') && lines[index + 1].trim()) rows.push(cells(lines[++index]));
blocks.push(<div key={key} className="research-table"><table><thead><tr>{headings.map((cell, column) => <th key={column}>{inlineText(cell)}</th>)}</tr></thead><tbody>{rows.map((row, position) => <tr key={position}>{row.map((cell, column) => <td key={column}>{inlineText(cell)}</td>)}</tr>)}</tbody></table></div>); continue;
}
const list = line.match(/^\s*(-|\d+\.)\s+(.+)/);
if (list) {
const ordered = list[1] !== '-', values = [list[2]], key = index;
while (true) {
const next = lines[index + 1]?.match(/^\s*(-|\d+\.)\s+(.+)/);
if (!next || (next[1] !== '-') !== ordered) break;
values.push(next[2]); index++;
}
const Tag = ordered ? 'ol' : 'ul';
blocks.push(<Tag key={key}>{values.map((value, position) => <li key={position}>{inlineText(value)}</li>)}</Tag>); continue;
}
const body = [line], key = index;
while (lines[index + 1]?.trim() && !/^(#{1,4}\s|```|\s*(-|\d+\.)\s|\|)/.test(lines[index + 1])) body.push(lines[++index]);
blocks.push(<p key={key}>{inlineText(body.join(' '))}</p>);
}
return <div className="research-content">{blocks}</div>;
}
export function PhaseIcon({ phase }: { phase: string }) {
if (phase === 'running') return <LoaderCircle size={15} className="spin" />;
if (phase === 'waiting') return <Clock3 size={15} />;
if (phase === 'completed') return <Check size={15} />;
return <Circle size={15} />;
}
@@ -0,0 +1,7 @@
:root{font-family:"Segoe UI Variable","Segoe UI","Microsoft YaHei",sans-serif;color:#15283f;background:#e7edf2;font-size:14px;--teal:#2560a3;--ink:#15283f;--muted:#5b6d83;--line:#cbd5df;--paper:#fff;--blue:#2560a3}
.workbench{background:#e7edf2}.project-sidebar{background:#192d46;color:#dae4ef;border-color:#32465e}.brand{border-color:#35475c;min-height:82px}.brand-mark{background:#2c5d8f;border:1px solid #6583a1;border-radius:7px;font-family:Bahnschrift,sans-serif}.brand strong{color:#fff;font-size:14px}.brand div>span{color:#9dafc5;font-size:11px}.project-sidebar .icon-button,.project-sidebar .field-eyebrow,.project-sidebar .section-heading,.project-sidebar .project-root,.project-sidebar .example-tag{color:#aabed4}.project-sidebar .project-select-row{color:#edf4fb}.project-sidebar select{background:#192d46;color:#e6edf6}.project-sidebar select option{background:#fff;color:#15283f}.project-selector,.file-sidebar,.sidebar-footer{border-color:#35475c}.session-list button{color:#c8d6e6;border-radius:5px}.session-list button:hover,.session-list button.selected{background:#304a67;color:white}.new-session{border:1px solid #5b7490;background:#263e58;color:#e0ebf7;border-radius:5px;min-height:37px}.tree-item{color:#bbcce0}.tree-item:hover,.tree-item.active{background:#304962;color:white}.file-filter{background:#233a54;border:1px solid #48617d}.file-filter input{color:#edf5ff}.file-filter input::placeholder{color:#9eafc5}.sidebar-footer button{color:#bacde1;min-height:38px}.sidebar-footer button:hover{background:#2c4561}.sidebar-footer .connection{color:#9ab2cc;border-top:1px solid #35475c;padding-top:12px}.sidebar-footer .connection small{color:#9bb6d5}.sidebar-footer .connection.connected>span{background:#62b69b}
.task-pane{background:#fff;border-color:#c6d1de}.work-header{height:82px;min-height:82px;background:#fff;border-bottom:1px solid #cbd5df;padding-left:26px;padding-right:24px}.work-title h1{font-size:18px;font-weight:650;letter-spacing:-.02em;line-height:1.4}.header-breadcrumb{color:#61748d;font-size:11px}.header-symbol{color:#2560a3;border-color:#bacbdd;background:#eff4fa}.model-button{border:1px solid #bccbdb;border-radius:6px;background:#f5f8fc;min-height:35px;color:#26466a;font-size:12px;font-weight:600}.task-toolbar{background:#f1f4f8;border-bottom:1px solid #ced8e3;min-height:44px;padding-left:26px}.conversation{padding:28px 30px 22px}.message-text{color:#233b55}.tool-row{border-radius:6px;border-color:#c5d2df;background:#f5f8fb}.tool-row summary{min-height:44px}.composer-wrap{background:#f5f7fa;border-top:1px solid #cbd5df;padding:17px 24px 14px}.composer{border:1px solid #afc1d3;border-radius:8px;background:#fff;box-shadow:0 2px 5px #15283f07}.composer:focus-within{border-color:#2560a3;box-shadow:0 0 0 2px #2560a31a}.composer textarea{font-size:14px;line-height:1.8}.button{border-radius:5px;font-weight:600;min-height:34px}.button.primary{background:#2560a3;border:1px solid #20558f;color:white}.button.primary:hover{background:#1e528c}.button.secondary{background:white;color:#365570;border:1px solid #bbcad9}.button.secondary:hover{background:#edf3fa}.inspector{background:#f8fafc;border-color:#cbd5df}.inspector-tabs{background:#edf2f7;border-color:#cbd5df;min-height:49px}.inspector-tabs button{font-size:12px;color:#4e657f}.inspector-tabs button.active{color:#235e98;border-color:#2560a3}.record-heading h3,.task-record-section h3{font-size:14px;font-weight:650;color:#203e60}.task-record-section{border-color:#ccd8e4}.status{font-size:11px;border-radius:4px;font-weight:600}.modal{background:#f8fafc;border:1px solid #bdcbda;border-radius:10px;box-shadow:0 24px 90px #07172e33}.modal-header h2{color:#173653;font-size:19px}.failure-card{border-left:3px solid #bb7a31;border-radius:6px}.approval-card{border-left:3px solid #2560a3;border-radius:6px}.form-field input,.form-field select{border-color:#b8c8d8;background:white;border-radius:5px;min-height:39px}.model-launch{display:flex;gap:8px;align-items:center}.model-launch>.button{font-size:12px;white-space:nowrap}
@media(max-width:940px){.conversation{padding:23px 20px}.work-header{padding:0 18px}.task-toolbar{padding-left:18px}.model-launch .model-button{max-width:170px;overflow:hidden;text-overflow:ellipsis}}
@media(max-width:620px){.work-header{height:72px;min-height:72px;padding:0 13px}.work-title h1{font-size:15px}.header-breadcrumb{font-size:10px}.model-launch>.button span{display:none}.model-launch>.button{width:40px;height:44px;padding:8px}.model-launch .model-button{max-width:106px;font-size:11px;min-height:36px}.task-toolbar{padding-left:13px;min-height:48px}.conversation{padding:23px 15px}.composer-wrap{padding:12px}.toolbar-actions .icon-button{min-height:40px;min-width:32px}.project-sidebar button{min-height:42px}.composer textarea{font-size:14px}.work-title .header-symbol{display:none}}
.task-pane{container-type:inline-size}.work-title{flex:1}.header-breadcrumb{white-space:nowrap;overflow:hidden}.model-launch{flex-shrink:0}.task-toolbar{overflow-x:auto;overflow-y:hidden}.task-toolbar>.task-local,.task-toolbar>.status{flex-shrink:0;white-space:nowrap}.toolbar-actions{flex-shrink:0}.toolbar-actions button{white-space:nowrap;flex-shrink:0}
@container(max-width:700px){.work-header{gap:12px;padding-left:14px;padding-right:14px}.model-launch>.button span{display:none}.model-launch>.button{padding:8px}.model-launch .model-button{max-width:140px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.work-title .header-symbol{display:none}.work-title h1{font-size:15px}.task-toolbar{padding-left:14px;padding-right:14px}}
@@ -0,0 +1,22 @@
import type { Project } from './types';
export type DesktopTaskScope = { projectId: string; sessionId: string; taskId: string };
export type DesktopHostStatus = {
state: 'ready' | 'stopping' | 'not-running';
identity?: { pid: number; createdAt: string; instanceId: string; runtimeIdentity: string; version: string; dataRoot: string; runtimeRoot: string };
activity?: { active: boolean; counts: Record<string, number>; unresolvedTools: number };
desktopWindows?: { count: number };
};
type DesktopWorkbench = {
protocol: 'agent-workbench-desktop-v1';
status(): Promise<DesktopHostStatus>;
pickProject(): Promise<Project | null>;
projectFolder(projectId: string): Promise<{ opened: boolean }>;
openFilePreview?(input: { projectId: string; url: string }): Promise<{ opened: boolean }>;
reviewTask(input: DesktopTaskScope): Promise<DesktopTaskScope & { eventSeq: number }>;
revealFile(input: DesktopTaskScope & { path: string; sha256: string }): Promise<{ revealed: boolean }>;
stopHost(): Promise<{ cancelled?: boolean; state?: string; processExited?: boolean }>;
browsingLayout?(input: {projectId?:string;sessionId?:string;taskId?:string;tabId?:string;visible:boolean;bounds?:{x:number;y:number;width:number;height:number}}): Promise<{visible:boolean}>;
};
declare global { interface Window { desktopWorkbench?: DesktopWorkbench } }
export const desktop = window.desktopWorkbench?.protocol === 'agent-workbench-desktop-v1' ? window.desktopWorkbench : undefined;
@@ -0,0 +1,3 @@
.input-composer{border-bottom:1px solid var(--line,#dce7e2);padding:8px 12px}.input-composer-tools{display:flex;align-items:center;gap:10px;flex-wrap:wrap}.input-composer-tools>span{font-size:11px;color:var(--muted,#52665f)}.input-add,.input-remove,.input-route button{display:inline-flex;align-items:center;gap:6px;border:0;background:transparent;color:inherit;padding:6px;cursor:pointer}.input-add:hover,.input-remove:hover{background:#edf3f1;border-radius:4px}.input-drafts{display:grid;gap:8px;margin-top:8px;max-height:220px;overflow:auto}.input-draft{display:flex;gap:10px;align-items:center;padding:8px;border:1px solid var(--line,#dce7e2);border-radius:5px;min-width:0}.input-draft.selected{border-color:var(--teal,#154b4a)}.input-draft>label{display:flex;gap:6px;font-size:11px;align-items:center;white-space:nowrap}.input-receipt{display:flex;gap:10px;align-items:center;min-width:0;margin:8px 0}.input-receipt>div{min-width:0;display:grid;gap:3px}.input-receipt strong{font-size:12px;overflow-wrap:anywhere}.input-receipt span,.input-receipt small{font-size:11px;color:var(--muted,#52665f)}.input-thumbnail{flex-shrink:0;border:1px solid var(--line,#dce7e2);background:transparent;cursor:pointer;padding:2px;width:78px;height:54px;border-radius:3px}.input-thumbnail img{object-fit:contain;display:block}.input-route{font-size:11px;line-height:1.7;margin:8px 0 2px;overflow-wrap:anywhere}.input-route button{color:var(--blue,#4664d9);text-decoration:underline}.input-route>span{display:block;color:var(--muted,#52665f)}.input-preview{display:block;max-width:100%;max-height:60vh;object-fit:contain;margin:auto}.input-sha{font-family:var(--font-mono,monospace);font-size:11px;overflow-wrap:anywhere;line-height:1.8}.input-remove{margin-left:auto}.budget-pause{margin:16px 24px;border-left:3px solid #cba760;padding:12px 16px;background:var(--paper,#fcfdfc);font-size:12px}.budget-pause h3{font-size:14px;margin:0 0 8px}.budget-pause p{line-height:1.7;overflow-wrap:anywhere}.budget-facts{display:grid;grid-template-columns:1fr auto;gap:6px 18px;margin:12px 0}.budget-facts dt{color:var(--muted,#52665f)}.budget-facts dd{margin:0;font-variant-numeric:tabular-nums}.budget-resume-fields{display:grid;grid-template-columns:1fr 1fr;gap:12px}.budget-resume-fields label{display:grid;gap:6px;font-size:12px}.budget-resume-fields input,.budget-resume-fields select{width:100%;min-width:0;padding:9px;border:1px solid var(--line,#dce7e2);border-radius:4px;background:var(--paper,#fcfdfc);color:inherit}.budget-preview{border-top:1px solid var(--line,#dce7e2);padding-top:12px;margin-top:16px}.budget-error{color:#87500b;line-height:1.7}
@media(max-width:620px){.input-draft{flex-wrap:wrap;gap:4px 10px}.input-draft>.input-receipt{width:calc(100% - 28px)}.input-draft>label{width:100%}.input-composer{padding:8px}.budget-pause{margin:12px}.budget-resume-fields{grid-template-columns:1fr}.budget-pause .button{width:100%;justify-content:center}}
@media(max-width:620px){.input-remove{min-width:44px;min-height:44px;justify-content:center}.input-draft>label{min-height:44px}.input-add{min-height:40px}}
@@ -0,0 +1,6 @@
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
import './styles.css';
import './control-console.css';
ReactDOM.createRoot(document.getElementById('root')!).render(<React.StrictMode><App /></React.StrictMode>);
@@ -0,0 +1,139 @@
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 { mobileApi, MobileError, verifiedText, verifyDigest } from './api';
import { MobileInputImage } from './MobileInputImage';
import './file-results.css';
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.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.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>;
}
@@ -0,0 +1,14 @@
import { useEffect,useState } from 'react';
import type { MobileTask } from '../companion-types';
import { MobileError } from './api';
export function MobileBrowserObservation({sessionId,observation,onError}:{sessionId:string;observation:NonNullable<MobileTask['browserObservations']>[number];onError:(error:unknown)=>void}) {
const [image,setImage]=useState(''),[failure,setFailure]=useState('');
useEffect(()=>{let alive=true,objectUrl='';const controller=new AbortController();setImage('');setFailure('');
void(async()=>{const response=await fetch('/mobile-api/sessions/'+sessionId+'/browser-observations/'+observation.id+'/image',{credentials:'same-origin',cache:'no-store',signal:controller.signal});if(!response.ok)throw new MobileError('原网页截图读取失败。',response.status);
const bytes=await response.arrayBuffer();if(bytes.byteLength>6*1024*1024)throw new MobileError('原网页截图超过6MiB范围。');const sha=Array.from(new Uint8Array(await crypto.subtle.digest('SHA-256',bytes)),value=>value.toString(16).padStart(2,'0')).join('');
if(sha!==observation.screenshotSha256||sha!==response.headers.get('X-Content-SHA256'))throw new MobileError('原网页截图SHA-256核对失败。');
if(alive){objectUrl=URL.createObjectURL(new Blob([bytes],{type:'image/png'}));setImage(objectUrl);}})().catch(error=>{if(alive){setFailure(error.message);onError(error);}});
return()=>{alive=false;controller.abort();if(objectUrl)URL.revokeObjectURL(objectUrl);};
},[sessionId,observation.id,observation.screenshotSha256]);
return <section className="mobile-input-image"><h2>电脑网页原观察</h2><strong>{observation.title||'所属网页'}</strong><p>{image?'SHA-256 已核对':failure||'正在核对原截图…'} · {new Date(observation.createdAt).toLocaleString('zh-CN')}</p><code>{observation.url}</code>{image&&<details><summary>查看原页面截图</summary><img src={image} alt="电脑上所属标签页的原观察"/><code>{observation.screenshotSha256}</code></details>}<p className="mobile-muted">这是原采样结果。新观察和浏览器控制在电脑执行,动作审批沿用原任务权限。</p></section>;
}
@@ -0,0 +1,21 @@
import { useEffect,useState } from 'react';
import type { InputAttachment } from '../types';
import { MobileError } from './api';
async function readImage(sessionId:string,image:InputAttachment,original=false){
const controller=new AbortController(),timer=setTimeout(()=>controller.abort(),15000);
try{
const response=await fetch('/mobile-api/sessions/'+sessionId+'/input-attachments/'+image.id+'/'+(original?'original':'image'),{credentials:'same-origin',cache:'no-store',signal:controller.signal});
if(!response.ok){const value=await response.json().catch(()=>({}));throw new MobileError(value.error||'截图读取失败。',response.status);}
const bytes=await response.arrayBuffer();if(bytes.byteLength>(original?2*1024*1024:768*1024))throw new MobileError('截图超出允许大小。');
const digest=Array.from(new Uint8Array(await crypto.subtle.digest('SHA-256',bytes)),value=>value.toString(16).padStart(2,'0')).join('');
if(digest!==(original?image.sha256:image.sentSha256))throw new MobileError('截图SHA-256核对失败,请在电脑核对。');
return new Blob([bytes],{type:original?image.mediaType:'image/png'});
}finally{clearTimeout(timer);}
}
export function MobileInputImage({sessionId,image,onError}:{sessionId:string;image:InputAttachment;onError:(cause:unknown)=>void}){
const [url,setUrl]=useState(''),[error,setError]=useState(''),[busy,setBusy]=useState(false);
useEffect(()=>{let alive=true,objectUrl='';setUrl('');setError('');void readImage(sessionId,image).then(blob=>{if(alive){objectUrl=URL.createObjectURL(blob);setUrl(objectUrl);}}).catch(cause=>{if(alive){setError(cause.message);onError(cause);}});return()=>{alive=false;if(objectUrl)URL.revokeObjectURL(objectUrl);};},[sessionId,image.id,image.sentSha256]);
async function download(){setBusy(true);try{const blob=await readImage(sessionId,image,true),href=URL.createObjectURL(blob),link=document.createElement('a');link.href=href;link.download=image.name;link.click();setTimeout(()=>URL.revokeObjectURL(href),1000);}catch(cause){onError(cause);}finally{setBusy(false);}}
return <section className="mobile-input-image"><h2>本任务截图</h2><strong>{image.name}</strong><p>{url?'SHA-256 已核对':error||'正在核对截图…'} · 发送副本 {image.sentWidth} × {image.sentHeight}</p>{url&&<details><summary>查看发送给模型的截图</summary><img src={url} alt={image.name}/><code>{image.sentSha256}</code></details>}<button disabled={busy||!url} onClick={()=>void download()}>核对并下载原图</button><p className="mobile-muted">原图 {image.width} × {image.height}。手机按现有项目观察权限读取;添加截图与预算续接在电脑操作。</p></section>;
}
@@ -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('结果内容校验失败,请在电脑核对原工件。');
}
@@ -0,0 +1,6 @@
.mobile-file-results { padding: 18px; border-block: 1px solid #d8e2dc; background: #f5f8f6; }
.mobile-file-results h2 { font-size: 16px; margin: 0 0 12px; }
.mobile-file-results article { padding: 12px 0; border-bottom: 1px solid #d8e2dc; font-size: 13px; line-height: 1.65; }
.mobile-file-results p { margin: 8px 0; }
.mobile-file-results code { font-size: 11px; overflow-wrap: anywhere; word-break: break-word; }
.mobile-file-results details summary { min-height: 42px; display: flex; align-items: center; cursor: pointer; }
@@ -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
File diff suppressed because one or more lines are too long
@@ -0,0 +1,386 @@
export interface Config {
mode: 'demo' | 'compatible'; baseUrl: string; model: string;
contextLimit: number; maxSteps: number; maxOutputTokens: number; hasKey: boolean;
maxRunDurationMs: number; maxRunTokens: number; maxTaskTokens: number;
modelResponseTimeoutMs?: number; modelStreamIdleTimeoutMs?: number;
}
export interface EnvironmentFile { path:string;sha256:string;bytes:number }
export interface DependencyTree { status:string;files:number;bytes:number;sha256:string|null;message?:string }
export interface NodeEnvironmentRuntime {status:string;node:EnvironmentFile&{version:string};npm:(EnvironmentFile&{version:string;manifest:EnvironmentFile})|null}
export interface NodeEnvironmentBinding {kind:'node';identity:string;dependencyInputs:string;status:string;installed:DependencyTree;declarations:EnvironmentFile[];runtime:NodeEnvironmentRuntime}
export interface EnvironmentDiagnostic {id:string;taskId:string;runId:string;artifactId:string;artifactSha256:string;inspectedAt:string;status:string;
node:(NodeEnvironmentBinding&{manager:string;lockVersion:number|null;packageCount:number;missing:string[];mismatched:string[];sources:string[];issues:string[];preparable:boolean})|null;
python:{status:string;framework?:string;runtime:{version:string|null;logicalExecutable:string|null};pytest:{version:string|null};message:string}|null}
export interface EnvironmentPlan {id:string;taskId:string;runId:string;status:string;root:string;registry:string;scripts:'skip'|'allow';offline:boolean;packageCount:number;timeoutMs:number;fingerprint:string;
invocation:{executable:string;args:string[]};lifecycle:{name:string;script:string}[];installScriptPackages:string[]}
export interface EnvironmentJob {id:string;taskId:string;runId:string;planFingerprint:string;status:string;summary?:string;finishedAt?:string;requiresVerification:boolean;
logExcerpt?:string;logArtifactId?:string;after?:NodeEnvironmentBinding;result?:{exitCode:number|null;durationMs:number;truncated?:boolean};reconciliation?:{artifactId:string;sha256:string}}
export interface PreviewPlan {id:string;taskId:string;runId:string;root:string;url:string;port:number;fingerprint:string;status:string;nodeIdentity:string;script:string;timeoutMs:number;invocation:{executable:string;args:string[]}}
export interface PreviewJob {id:string;taskId:string;runId:string;planId:string;planFingerprint:string;status:string;url:string;port:number;summary?:string;logExcerpt?:string;logArtifactId?:string;requiresVerification?:boolean;reconciliation?:{at:string;result:string};process?:{pid:number;treeTermination?:string};readiness?:{observedAt:string;sha256:string}}
export interface ExecutionSnapshot {environmentDiagnostics?:EnvironmentDiagnostic[];environmentPlans?:EnvironmentPlan[];environmentJobs?:EnvironmentJob[];previewPlans?:PreviewPlan[];previewJobs?:PreviewJob[]}
export interface BrowsingTab {id:string;sessionId:string;projectId:string;taskId:string;runId:string;profileId:string;status:string;url:string;title?:string;origins:string[];interact:boolean;persistent:boolean;revision?:string;observationId?:string;previewOrigin?:string;error?:string}
export interface BrowsingObservation {id:string;tabId:string;revision:string;url:string;title:string;text:string;createdAt:string;scope:{complete:boolean};controls:{ref:string;tag:string;type:string;label:string;disabled:boolean;restricted?:boolean;href?:string}[];screenshotArtifactId:string;screenshotSha256:string;artifactId:string}
export interface BrowsingAction {id:string;tabId:string;kind:string;status:string;createdAt:string;input:{action?:string;ref?:string;value?:string;url?:string};error?:string;artifactId?:string;downloadArtifactId?:string;downloadSha256?:string;reconciliation?:{at:string}}
export interface BrowsingSnapshot {available:boolean;tabs:BrowsingTab[];observations:BrowsingObservation[];actions:BrowsingAction[];profiles:{id:string;origins:string[];status:string}[]}
export interface ExecutionSnapshot {browsingTabs?:BrowsingTab[];browsingActions?:BrowsingAction[]}
export interface CheckPlan {environment?:NodeEnvironmentBinding|null}
export interface CheckJob {environment?:NodeEnvironmentBinding|null}
export interface Approval {environmentPlanId?:string}
export interface Approval {browsingTabId?:string;mcpRegistrationId?:string}
export interface Approval {environmentSummary?:Pick<EnvironmentPlan,'root'|'registry'|'scripts'|'offline'|'timeoutMs'|'lifecycle'|'installScriptPackages'>}
export interface NodeEnvironmentBinding {preparation?:{jobId:string;planId:string;sessionId:string;logArtifactId:string;logSha256:string}|null}
export interface ModelSelection { type: 'legacy' | 'connection' | 'pool'; id: string; name: string }
export interface WorkspaceOrigin { id: string; sourceProjectId: string; sourceSessionId: string; sourceRoot: string; sourceWorkspaceId: string | null; baseCommit: string; branch: string; commonGitDir: string; gitDir: string; fingerprint: string }
export interface WorkspaceIdentity { kind: 'local-project' | 'managed-worktree'; projectId: string; root: string; workspaceId?: string; sourceProjectId?: string; sourceSessionId?: string; sourceRoot?: string; sourceWorkspaceId?: string | null; baseCommit?: string; branch?: string; commonGitDir?: string; gitDir?: string; fingerprint?: string }
export interface Project { id: string; root: string; name: string; addedAt: string; workspace?: WorkspaceOrigin }
export interface WorkspaceRecord {
id: string; projectId: string; sessionId: string; taskId: string | null; runId: string | null; label: string; root: string; branch: string;
childProjectId: string; childSessionId: string; status: string; phase: string; fingerprint: string;
createdAt: string; updatedAt: string; finishedAt: string | null; creationAttempted: boolean; requiresVerification: boolean;
ownerPid: number | null; gitPid: number | null; summary: string;
source: { root: string; head: string; branch: string; dirty: boolean; changedPathCount: number; changedPaths: { status: string; path: string; originalPath?: string }[]; fingerprint: string; committedBytes: number; treeFiles: { mode: string; blob: string; bytes: number; path: string }[] };
observation?: { rootState: string; branchHead: string | null; workspaceHead: string | null; workspaceBranch: string | null; registered: boolean; clean: boolean; contentsVerified: boolean; sourcePreserved: boolean; ready: boolean; fingerprint: string; observedAt: string; problems: string[] } | null;
}
export interface SessionBrief { id: string; projectId: string; title: string; status: string; revision: number; updatedAt: string; changeCount: number }
export interface Message { id: string; role: string; content: string; createdAt: string; attachmentIds?: string[] }
export interface InputAttachment { id:string;name:string;status:string;mediaType:string;taskId:string|null;runId:string|null;sha256:string;bytes:number;sentSha256:string;sentBytes:number;width:number;height:number;sentWidth:number;sentHeight:number;orientation:number }
export interface BudgetPause { reason:string;requiredInputTokens?:number;contextLimit?:number;inputBudget?:number;outputReservation?:number;safetyTokens?:number;runRemainingTokens?:number|null;taskRemainingTokens?:number|null;imageReservationTokens?:number;breakdown?:Record<string,number> }
export interface Run { budgetPause?:BudgetPause }
export interface BudgetPause { originalInputTokens?:number;transportReservationTokens?:number }
export interface BudgetPause { limitingReason?:string;pauseKind?:string }
export interface BudgetPause { modelFailure?:RuntimeFailure }
export interface TokenBudgetCounter { maximumTokens:number;reportedTokens:number;unknownRequests:number;estimatedUnknownTokens:number;accountedTokens:number;remainingTokens:number|null;exceededTokens:number }
export interface BudgetPause { remainingTokens?:number;tokenReservation?:{schemaVersion:number;reservedTokens:number;routes:{sources:{runId:string;attemptId:string}[]}[]};tokenAccounting?:{schemaVersion:number;singleInFlightResponseMayExceed:boolean;run:TokenBudgetCounter;task:TokenBudgetCounter} }
export interface ToolEvent {
id: string; kind: string; label: string; phase: string; createdAt: string; tool?: string;
input?: Record<string, unknown>; output?: string; durationMs?: number; startedAt?: string; finishedAt?: string;
source?: string; attempts?: number; diagnostic?: RuntimeFailure; exitCode?: number;
taskId?: string; runId?: string; invocationId?: string; artifactId?: string;
connectionId?: string; actualModel?: string;
stream?: { status: string; protocol?: string; sequence?: number; bytes?: number; textCharacters?: number; textPreview?: string; toolFragments?: number };
}
export interface DiffPart { value: string; count: number; added?: boolean; removed?: boolean }
export interface Change {
taskId?: string | null; runId?: string | null;
changeSetId?: string; rolledBackAt?: string;
id: string; path: string; reason: string; status: string; baseExists: boolean; baseSha256: string | null;
baseContent: string; content: string; sha256: string; diff: DiffPart[]; additions: number; deletions: number;
createdAt: string; appliedAt?: string;
editKind?: 'exact-patch';
patch?: { edits: number; lineEnding: 'lf' | 'crlf' | 'mixed'; preservedBom: boolean; ranges: { startLine: number; endLine: number; anchorSha256: string; replacementSha256: string }[] };
}
export interface Approval { id: string; command: string; reason: string; cwd: string; shell?: string; status: string; createdAt: string; browserPlanId?: string; browserSummary?: { buildDirectory: string; buildSha256: string; viewport: { width: number; height: number }; steps: BrowserStep[] }; checkPlanId?: string; checkScripts?: { name: string; script: string; lifecycle: { name: string; script: string }[]; python?: { mode: string; runtime: PythonRuntimeIdentity } }[] }
export interface Session {
id: string; projectId: string; title: string; status: string; revision: number; updatedAt: string; createdAt: string;
messages: Message[]; events: ToolEvent[]; changes: Change[]; approvals: Approval[];
compactions: number; estimatedTokens: number; usage: { prompt_tokens?: number; completion_tokens?: number } | null;
archived: boolean; recoveryNotice?: string | null; executionMode?: string;
failure?: RuntimeFailure | null; lastFailure?: RuntimeFailure | null;
execution?: ExecutionSnapshot;
inputAttachments?: InputAttachment[];
}
export interface RuntimeFailure {
modelIdentity?: import('../shared/contracts/model-identity.mjs').ModelIdentity;
source: string; stage: string; kind: string; title: string; message: string; messageId?: string;
detail?: string; suggestion?: string; attempts?: number; httpStatus?: number; code?: string | null;
occurredAt?: string; retryable?: boolean; historical?: boolean; endpoint?: string; model?: string;
requestUrl?: string; responseUrl?: string | null; redirected?: boolean; redirectMode?: string;
origin?: 'upstream' | 'local'; route?: string; type?: string | null; wireAttemptId?: string; upstreamRequestId?: string | null; retryAfterMs?: number; retryDecision?: string; limitReason?: string | null;
upstream?: { schema: number; scope: string; httpStatus?: number; code?: string | null; type?: string | null; message?: string | null; param?: string | null;
requestId?: string | null; responseId?: string | null; eventType?: string | null; reason?: string | null; headers?: Record<string, string>; retryAfter?: string | null;
retryAfterMs?: number | null; retryAfterInvalid?: boolean; rawPreview?: string; previewTruncated?: boolean; shortenedFields?: string[];
artifactId?: string; artifactSha256?: string; artifactScope?: string; sessionId?: string;
capture?: { scope: string; receivedBytes: number; capturedBytes: number; storedBytes: number; retention?: string; complete: boolean; truncated: boolean; interrupted: boolean; redacted: boolean; sha256: string; capturedRange: number[] } };
}
export interface ExecutionEnvironment { platform: string; node: string; shell: string; encoding: string; shellSyntax: string }
export interface RuntimeDiagnostics {
version: string; environment: ExecutionEnvironment;
projectCache?: ProjectCacheStatus;
connection: { mode: string; endpoint: string; model: string; hasKey: boolean; lastRequest: { status?: string; attempts?: number; durationMs?: number } | null };
session: {
project: { name: string; root: string }; session: { id: string; status: string; revision: number };
lastFailure: RuntimeFailure | null;
changes: { id: string; path: string; status: string }[];
recentTools: { tool: string; phase: string; outputExcerpt: string; exitCode: number | null }[];
} | null;
}
export interface FileEntry { path: string; name: string; kind: string; bytes: number }
export interface OpenFile { path: string; content: string; sha256: string; bytes: number; bom?: boolean }
export interface Bootstrap { token: string; version: string; config: Config; modelSelection?: ModelSelection; projects: Project[]; sessions: SessionBrief[]; exampleProjectId: string | null; environment?: ExecutionEnvironment; eventCursor?: number; storage?: { engine: string; schemaVersion: number }; runtimeRoot?: string }
export interface ResearchDoc { id: string; title: string; description: string }
export type CodeQueryKind = 'all' | 'symbols' | 'imports' | 'files';
export interface ProjectCacheMetrics {
enabled: boolean; persistent: boolean; checkedAt: string; sourceVerified: boolean; origin: string; invalidation: string | null;
reusedFiles: number; rebuiltFiles: number; parsedFiles: number; invalidatedFiles: number; removedFiles: number;
verifiedFiles: number; verificationPasses: number; sourceBytesRead: number; parseMs: number; durationMs: number;
stored: boolean; storageReason: string; evictedProjects: number; diskProjects: number; diskBytes: number;
maximumProjects: number; maximumBytes: number; maximumEntryBytes: number; error: string | null;
}
export interface ProjectCacheStatus {
enabled: boolean; persistent: boolean; diskProjects: number; diskBytes: number; maximumProjects: number; maximumBytes: number;
maximumEntryBytes: number; error: string | null; memoryProjects?: number; memoryBytes?: number; pending?: number;
latest?: ProjectCacheMetrics | null; clearedAt?: string; removedProjects?: number;
}
export interface CodeIndexSummary {
schemaVersion: number; projectId: string; projectName: string; parser: string; generatedAt: string; sourceFingerprint: string; indexFingerprint: string;
coverage: { snapshotComplete: boolean; fileCount: number; symbolCount: number; importCount: number; astFiles: number; pythonCandidateFiles: number; unindexedFiles: number; truncated: boolean; maximumFileBytes: number; maximumSymbols: number };
refresh: { updatedFiles: number; reusedFiles: number; removedFiles: number };
sourceScope: { complete: boolean; scannedFiles: number; bytes: number; maximumFiles: number; maximumBytes: number; excludedFiles: number; note: string };
warnings: { path: string; sha256: string; status: string; message: string; line: number }[]; notes: string[];
cache?: ProjectCacheMetrics;
}
export interface CodeResult {
resultKind: 'symbol' | 'import' | 'file'; path: string; line: number; sha256: string; name: string; kind: string;
qualifiedName?: string; signature?: string; evidenceMethod: string; exported?: boolean; status?: string; target?: string | null;
}
export interface CodeQuery { query: string; kind: CodeQueryKind; results: CodeResult[]; totalMatches: number; truncated: boolean; index: CodeIndexSummary }
export interface ModelSnapshot { mode: string; model: string; baseUrl: string; verified?: boolean; contextLimit?: number; maxOutputTokens?: number; routing?: { type: string; name: string; members: { id: string; name: string; model: string; baseUrl: string }[] } }
export interface ModelConsumption { modelIdentity?: import('../shared/contracts/model-identity.mjs').ModelIdentity; attemptId: string; requestId: string | null; connectionId: string | null; connectionName: string | null; model: string; endpoint: string; protocol: string; usageStatus: string; outcome: string; usage: { prompt_tokens?: number; completion_tokens?: number; total_tokens?: number } | null; estimatedUnknownTokens: number }
export interface Usage { requests: number; inputTokens: number; outputTokens: number; totalTokens: number; unknownRequests: number; estimatedUnknownTokens: number }
export interface RunBudget { maxSteps: number; maxDurationMs: number; maxTokens: number; maxTaskTokens: number }
export interface RunBrief { id: string; taskId: string; status: string; startedAt: string; finishedAt: string | null; steps: number; toolCalls: number; usage: Usage; stopReason: string | null; model: ModelSnapshot; budget: RunBudget; resumeOf: string | null; workspaceIdentity?: WorkspaceIdentity }
export interface Run extends RunBrief { engine: string; review?: { kind: string; planId: string; status: string; preparedAt?: string; resolvedAt?: string }; currentContextPlanId?: string; checkpoint: { completedToolIds: string[]; pendingToolIds: string[]; requiresVerification: string[] } }
export interface TurnObservation {
stepId: string | null; stepIndex: number | null; phase: string; classification: string; reasons: string[]; truncated: boolean;
delta: { read_characters: number; repeated_reads: number; changed_files: number; check_results: number; requirement_evidence: number; new_failures: number; repeated_failures: number };
waiting: { kind: string; id: string }[];
}
export interface Run { progressShadow?: { mode: 'shadow'; observations: number; truncated: boolean; turns: TurnObservation[] }; progressShadowArtifactIds?: string[]; progressShadowError?: { kind: string; phase: string } }
export interface RunBrief { purpose?: 'execution' | 'diagnostic'; source?: string; taskStatusBefore?: string; consumption?: ModelConsumption[] }
export interface Run { question?: string; diagnosticContext?: { artifactId: string; sha256: string; originalRunId: string | null } }
export interface DiagnosticContext {
artifactId?: string; originalRunId?: string | null; evidenceVerified: boolean; historical?: boolean; note?: string; error?: string;
failure?: { id: string; eventId: string; runId: string; sha256: string; value: RuntimeFailure } | null;
check?: { id: string; runId: string; status: string } | null;
}
export interface DeliveryStatus {
requirementsRevision: number;
followUp: { taskId: string; runId: string; goal: string; taskStatus: string; status: string; statusLabel: string; nextStep: string; note: string;
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 TaskCheckpoint {
id: string; sessionId: string; projectId: string; taskId: string; runId: string; createdAt: string;
status: string; artifactId: string; sha256: string; sourceFingerprint: string; requirementsSha256: string;
counts: { tools: number; completed: number; unknown: number; pendingChanges: number };
}
export interface TaskCheckpointView {
checkpoint: TaskCheckpoint; integrity: string; checkedAt: string; resumable: boolean; reasons: string[]; currentSourceFingerprint: string;
}
export interface ContextPlan {
id: string; sessionId: string; projectId: string; taskId: string; runId: string; stepId: string; requestIndex?: number; status: string;
createdAt: string; finishedAt: string | null; requestSha256: string; requestBytes: number; requestArtifactId: string; artifactId: string;
estimatedInputTokens: number; beforeInputTokens: number; beforeBytes: number; estimateMethod: string;
originalMessages: number; retainedMessages: number; archivedGroups: number; historyIndexArtifactId: string | null; historyIndexSha256: string | null;
workingSetArtifactId?: string | null; workingSetSha256?: string | null; workingSetEntries?: number;
workingSetViewVersion?: number; workingRetentionTokens?: number;
latestToolsArtifactId?: string | null; latestToolsSha256?: string | null; latestToolsEntries?: number;
projectMemoryArtifactId?: string | null; projectMemorySha256?: string | null; projectMemoryEntries?: number;
skillCatalogArtifactId?: string | null; skillCatalogSha256?: string | null; skillCatalogEntries?: number;
actualUsage: { prompt_tokens?: number; completion_tokens?: number; total_tokens?: number } | null; requestAttempts: number; error?: string;
budget: { contextLimit: number; outputReservation: number; safetyTokens: number; inputBudget: number; targetInputTokens: number; runRemainingTokens: number | null; taskRemainingTokens: number | null };
}
export interface ContextHistoryGroup {
index: number; startMessage: number; endMessage: number; sha256: string; roles: string[];
tools?: { call_id: string; name: string; result: { status?: string; path?: string; requires_verification?: boolean }; recorded_state?: string; requires_verification?: boolean; result_artifact_id?: string }[];
archive: { artifact_id: string; sha256: string; bytes: number; chunks?: number };
}
export interface ContextHistory { planId: string; groups: ContextHistoryGroup[]; offset: number; totalGroups: number; truncated: boolean }
export interface Task { id: string; goal: string; status: string; instructions: { id: string; content: string; createdAt: string; source?: string }[]; usage: Usage; budget: { maxTokens: number }; verification: { status: string; checkJobId: string | null }; origin: string; workspaceIdentity?: WorkspaceIdentity }
export interface Task { contract?: { schemaVersion: number; goal: string; checks: string; inheritedFromTaskId?: string }; delivery?: { status: string; paths: string[]; at: string; checks: string } }
export interface FileResultView {
id: string; taskId: string; runId: string; source: string; reason: string; createdAt: string; verification: 'current' | 'stale' | 'invalid'; error: string | null;
contractArtifactId: string; contractSha256: string; files: { path: string; sha256: string; bytes: number; origin: { taskId: string; runId: string; resultId: string; sha256: string } | null }[];
}
export interface ExecutionSnapshot { fileResults?: Omit<FileResultView, 'verification' | 'error'>[] }
export interface Artifact { id: string; taskId: string | null; runId: string | null; kind: string; mediaType: string; sha256: string; bytes: number; createdAt: string; status: string }
export interface ArtifactPreview extends Artifact { content: string; offset: number; totalCharacters: number; truncated: boolean }
export interface ProjectMemorySource { kind: 'project' | 'file' | 'artifact' | 'session' | 'task' | 'run'; id?: string; path?: string; sha256?: string; sourceFingerprint: string; label?: string; artifactKind?: string }
export interface ProjectMemory { schemaVersion: number; id: string; projectId: string; sessionId: string; taskId: string | null; runId: string | null; title: string; content: string; tags: string[]; source: ProjectMemorySource; sourceFingerprint: string; status: 'current' | 'unverified' | 'expired' | 'archived'; createdAt: string; updatedAt: string; expiresAt: string | null; expiredAt?: string | null; expiredReason?: string | null; archivedAt?: string; origin: string }
export interface ProjectMemoryView { projectId: string; sourceFingerprint: string; inspectedAt: string; scope: { complete: boolean; scannedFiles: number; bytes: number; excludedFiles: number; maximumFiles: number; maximumBytes: number; note: string }; memories: ProjectMemory[]; summary: { current: number; unverified: number; expired: number; archived: number; total: number; invalidated: number }; rule: string }
export interface PythonRuntimeIdentity { status: string; logicalExecutable?: string | null; executable: string | null; version: string | null; sha256?: string; baseExecutable?: string; baseSha256?: string; message?: string; probe?: string }
export interface CheckResult { id: string; name: string; kind: string; command: string; status: string; exitCode: number | null; durationMs: number; tests: { total: number; passed: number; failed: number; skipped: number; cancelled: number } | null; logArtifactId?: string; reason?: string;
engine?: string; python?: { mode: string; runtime: PythonRuntimeIdentity; invocationId: string; inputSha256: string; runner: { path: string; sha256: string } };
compilation?: { total: number; compiled: number; failures: { path: string; line?: number; message: string }[] } | null; collectionErrors?: number | null;
metricsArtifactId?: string; metricsSha256?: string; inputArtifactId?: string; evidenceValidated?: boolean }
export interface CheckJob { id: string; taskId: string; runId: string; planId: string; status: string; startedAt: string; finishedAt: string | null; results: CheckResult[]; summary?: string; stale?: boolean; currentCheck?: { name: string; command: string; startedAt: string } | null; baseline?: { head: string | null; dirty: boolean; branch: string | null }; fingerprint?: string; sourceFingerprint?: string }
export interface CheckPlan { id: string; taskId: string; runId: string; status: string; fingerprint: string; createdAt: string; checks: { id: string; name: string; kind: string; command: string; script: string; lifecycle: { name: string; script: string }[]; python?: { mode: string; runtime: PythonRuntimeIdentity } }[]; project: { name: string; languages: string[]; packageManager: string; scripts?: { name: string; kind: string }[]; rules: { path: string; sha256: string; excerpt: string }[]; python?: { status: string; framework?: string; message?: string; checks?: { name: string; kind: string }[] }; scope: { complete: boolean; scannedFiles: number }; git: { available: boolean; head: string | null; dirty: boolean; branch: string | null; status: string } } }
export interface DeliveryPlan {
preparedBy?: 'agent' | 'user';
id: string; sessionId: string; projectId: string; taskId: string; runId: string; status: string; message: string;
author: { name: string; email: string; source: string }; baseline: { head: string; branch: string; reference: string };
paths: string[]; files: { path: string; changeIds: string[]; mode: string; sha256: string; additions: number; deletions: number; reason: string; diff: string }[];
checkJobId: string; checkSummary: { name: string; command: string; exitCode: number; tests: CheckResult['tests']; logArtifactId: string }[];
sourceFingerprint: string; diffArtifactId: string; policy: { note: string; hooks: string; signing: string };
}
export interface DeliveryJob {
id: string; sessionId: string; taskId: string; runId: string; planId: string; status: string; parent: string; branch: string; paths: string[];
commit: string | null; expectedCommit?: string | null; summary?: string; requiresVerification: boolean; startedAt: string; finishedAt: string | null;
reportArtifactId?: string; reportMarkdownArtifactId?: string; reportError?: string; indexPreserved?: boolean; workspacePreserved?: boolean;
}
export interface ChangeSet {
id: string; taskId: string; runId: string; sessionId: string; projectId: string; fingerprint: string;
status: string; requiresVerification: boolean; summary: string; createdAt: string; finishedAt?: string;
baseline: { available: boolean; head: string | null; branch: string | null }; observationFingerprint?: string;
files: { changeId: string; path: string; baseExists: boolean; baseSha256: string | null; sha256: string; bytes: number;
baseBytes: number; mode: number; reason: string; state: string; writeAttempted: boolean; restoreAttempted: boolean;
snapshotArtifactId: string; sourceRunId: string; restoreError?: string }[];
observations?: { path: string; state: string; exists: boolean | null; actualSha256: string | null; problem?: string }[];
}
export interface TaskPlanStep {
key: string; title: string; criterion: string; kind: 'analysis' | 'changes' | 'results' | 'checks' | 'browser'; depends_on: string[];
tools?: string[]; paths?: string[]; checks?: string[]; viewport_width?: number; actions?: string[];
}
export interface TaskPlanRecord { id: string; taskId: string; runId: string; revision: number; parentPlanId: string | null; steps: TaskPlanStep[]; contractArtifactId: string; contractSha256: string }
export interface TaskPlanStepView extends TaskPlanStep {
status: string; blockers: string[]; evidence_verified: boolean; proof_id: string | null; proof_artifact_id: string | null; error: string | null;
evidence: { id: string; runId: string; artifacts?: { id: string; kind: string; sha256: string }[] } | null;
last_rejection?: { id: string; message: string; at: string };
candidates?: { id: string; status: string; label: string; runId: string }[];
}
export interface TaskPlanView {
configured: boolean; task_id: string; plan_id?: string; revision: number; status: string; steps: TaskPlanStepView[]; all_verified: boolean;
verified_steps?: number; total_steps?: number; ready_steps?: string[]; remaining_steps?: string[]; requirements_current?: boolean;
contract_artifact_id?: string; contract_sha256?: string; checked_at?: string; error?: string;
}
export interface TaskPlanReply { session: Session; plan: TaskPlanView; verification?: { status: string; reused?: boolean; proof_id: string; message?: string } }
export interface RequirementSource { kind: 'goal' | 'instruction'; id: string; text: string; sha256: string; at: string | null }
export interface RequirementItem extends TaskPlanStep {
role?: 'requirement' | 'reference' | 'prohibition' | 'unknown';
method: 'evidence' | 'user' | 'not_requested' | 'scope'; source: { kind: string; id: string; start: number; end: number; quote?: string; sourceSha256?: string; at?: string | null };
revision?: number; status?: string; error?: string | null; proof_id?: string | null; proof_artifact_id?: string | null; user_note?: string | null;
evidence?: TaskPlanStepView['evidence']; candidates?: TaskPlanStepView['candidates']; last_rejection?: { message: string } | null;
}
export interface RequirementView {
configured: boolean; task_id: string; revision: number; status: string; items: RequirementItem[]; sources: RequirementSource[]; source_set_sha256: string;
all_resolved: boolean; unreviewed_sources?: string[]; error?: string; note: string; contract_artifact_id?: string;
history?: { id: string; key: string; revision: number; status: string; error: string | null; at: string; artifact_id: string }[];
}
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 WorkerBudget { maxTokens: number; maxSteps: number; maxToolCalls: number }
export interface WorkerDefinition { id: string; label: string; goal: string; paths: string[]; budget: WorkerBudget; workspaceId: string; projectId: string; sessionId: string; taskId: string; engine?: ControlledEngineAvailability }
export interface WorkerRecord extends WorkerDefinition {
collaborationId: string; parentProjectId: string; parentSessionId: string; parentTaskId: string; parentRunId: string;
runId: string; currentRunId: string | null; runIds: string[]; baseCommit: string; fingerprint: string; status: string; requiresVerification: boolean;
startedAt: string | null; finishedAt: string | null; summary: string; result: { artifactId: string; sha256: string; checkJobId: string; paths: string[] } | null;
usage?: Usage & { accountedTokens: number; steps: number; toolCalls: number }; sessionStatus?: string;
}
export interface WorkerConflict { path: string; reason: string; workerIds: string[] }
export interface CollaborationGroup {
id: string; taskId: string; runId: string; projectId: string; sessionId: string; goal: string; fingerprint: string;
status: string; phase?: string; requiresVerification: boolean; summary: string; createdAt: string; startedAt: string | null; finishedAt: string | null; deadline: number | null;
model: { mode: string; model: string; baseUrl: string }; budget: WorkerBudget & { maxDurationMs: number };
source: { identity: { root: string; head: string; branch: string; indexSha256: string }; dirty: boolean; changedPaths: { path: string; status: string }[] };
children: WorkerDefinition[]; workers?: WorkerRecord[]; usage?: { accountedTokens: number; steps: number; toolCalls: number; requests?: number; unknownRequests: number };
collection: { artifactId: string; sha256: string; conflicts: WorkerConflict[]; paths: string[] } | null;
merge: { changeSetId?: string; fingerprint?: string; changeIds?: string[] } | null;
evidence?: { artifactId: string; sha256: string } | null;
}
export interface WorkerView { groups: CollaborationGroup[]; worker: WorkerRecord | null }
export interface CollaborationGroup { evaluation?: { batchId: string; sampleId: string } }
export interface WorkerDefinition { evaluation?: { batchId: string; sampleId: string; role: 'original' | 'candidate' } }
export interface EvaluationRole {
outcome: string; reason?: string; evidenceError?: string; workerStatus?: string; startedAt?: string; finishedAt?: string;
usage: { requests: number; totalTokens: number; unknownRequests?: number; estimatedUnknownTokens?: number; reported: boolean; cost?: number | null } | null;
attempts: { id: string; status: string; summary?: string; results: { name: string; command?: string; status?: string; exitCode?: number; durationMs?: number; tests?: CheckResult['tests']; logArtifactId: string; logSha256?: string }[] }[];
approvals?: { id: string; status: string; decidedAt?: string }[]; changes?: { id: string; path: string; status: string }[];
}
export interface EvaluationReport {
schemaVersion: number; batchId: string; sampleId: string; label: string; goal: string; criteria: string; source: { head: string };
inputVerified: boolean; inputError?: string; summary: { original: string; candidate: string }; original: EvaluationRole; candidate: EvaluationRole;
evidenceMode: string; note: string; sealedAt: string;
}
export interface EvaluationSample {
id: string; label: string; goal: string; criteria: string; paths: string[]; checks: string[]; status: string; groupId?: string; error?: string;
baselineAttemptedAt?: string; baselineJobId?: string; contractSha256?: string;
commands?: { name: string; command: string; script: string; lifecycle?: { name: string; script: string }[] }[];
report: { artifactId: string; sha256: string; summary: { original: string; candidate: string } } | null; workers?: WorkerRecord[];
}
export interface EvaluationBatch {
id: string; title: string; fingerprint: string; status: string; source: { head: string; branch: string }; model: ModelSnapshot;
message: string; evidenceMode: string; samples: EvaluationSample[]; budget: WorkerBudget & { maxDurationMs: number }; deadline: number | null;
adoption: { sampleId: string; status: string; delivery?: { commit: string } } | null;
summary: { samples: number; finished: number; candidate: Record<string, number>; scope: string };
}
export interface McpTool { name: string; description: string; inputSchema: Record<string, unknown>; unsupported?: string }
export interface McpRegistration {
id: string; projectId: string; name: string; launch: { executable: { path: string; sha256: string; bytes: number }; entry: { path: string; sha256: string; bytes: number } | null; args: string[]; environment: string; identityScope: string };
timeoutMs: number; configurationRevision: number; enabled: boolean; allowedTools: string[];
contract: { artifactId: string; sha256: string } | null; createdAt: string; updatedAt: string; status: string; reason: string; tools: McpTool[];
}
export interface McpJob {
id: string; sessionId: string; projectId: string; taskId: string; runId: string; registrationId: string; configurationRevision: number;
invocationId?: string | null; reviewedAt?: string; reviewedBy?: string; evidenceSha256?: string;
operation: 'probe' | 'call'; status: string; startedAt: string; finishedAt: string | null; requiresVerification: boolean; dispatched: boolean; processStarted: boolean;
input?: { launch?: unknown; protocolVersion?: string; contractSha256?: string | null; call?: { tool: string; arguments: Record<string, unknown> }; timeoutMs?: number }; inputArtifactId?: string; inputSha256?: string; pid?: number;
reportArtifactId?: string; reportSha256?: string; cleanup?: { connectionId?: string; pid: number | null; rootExited: boolean; forced?: boolean; scope?: string; exit?: { code: number | null; signal: string | null } | null };
error?: { code: string; message: string } | null;
}
export interface EngineAvailability {
engineId: string; name: string; status: string; root: string | null; profile: string; expectedVersion: string; version?: string; message: string;
identitySha256?: string; node?: { path: string; version: string; sha256: string };
serverInfo?: { name: string; version: string }; limitations: string[];
capabilities: { connectionProbe: boolean; projectExecution: boolean; prompt: boolean; singleSessionCancel: boolean; cancellationUnit: string; tokenStreaming: boolean };
}
export interface EngineJob {
id: string; sessionId: string; projectId: string; taskId: string; runId: string; engineId: string; scope: string;
installation: EngineAvailability; sdkSessionId: string; status: string; summary: string; requiresVerification: boolean;
startedAt: string; finishedAt: string | null; pid?: number; connectionId?: string;
readiness?: { pid: number; signal: string; readyAt: string }; serverInfo?: { name: string; version: string };
verification?: { verified: boolean; rootExited: boolean; modelRequests: number } | null;
reportArtifactId?: string; reportSha256?: string; contractSha256: string;
reportSummary?: { status: string; modelRequests: number | null; observedResponses: number; rootExited: boolean | null } | null;
}
export interface ControlledEngineAvailability extends EngineAvailability {
controlledStatus: string; controlledSha256?: string; scope: string; bridgeSha256?: string;
controlledCapabilities?: { text: boolean; nativeSessionResume: boolean; nativeModelCredentials: boolean; cancellationUnit: string };
strategy?: PurgePromptStrategy | PurgeOriginalStrategy;
}
export interface PurgeSourceAvailability {
status: string; root: string | null; message: string; version?: string; sourceSha256?: string;
defaultEnabled: boolean; defaultPrompt: string; supportedVersions: string[];
inputs?: { relative: string; path: string; bytes: number; sha256: string }[];
kind?: 'purge-prompt-experiment' | 'purge-original-restricted-v1'; runtimeSha256?: string; runtimeInputs?: number;
}
export interface PurgePromptStrategy {
kind: 'purge-prompt-experiment'; enabled: true; sha256: string; prompt: string; promptSha256: string;
source: { root: string; version: string; sourceSha256: string };
section: { name: string; order: number; interpolate: false; text: string; textSha256: string };
}
export interface PurgeOriginalStrategy {
kind: 'purge-original-restricted-v1'; enabled: true; sha256: string; prompt: string; promptSha256: string;
source: { root: string; version: string; sourceSha256: string };
runtime: { root: string; sha256: string; inputs: { path: string; sha256: string }[]; nativeAddons: { path: string; sha256: string }[] };
originalConfig: { autoRetry: false; autoContinue: false; hooksDenyBypass: false; postPrompt: string };
}
export interface EngineRunView {
id: string; projectId: string; sessionId: string; taskId: string; runId: string; workerId: string; collaborationId: string;
installation: ControlledEngineAvailability; sdkSessionId: string; status: string; requiresVerification: boolean; verified: boolean;
startedAt: string; finishedAt: string | null; error?: string | null; inputArtifactId: string; inputSha256: string;
reportArtifactId?: string; reportSha256?: string; modelRequests: number; toolRequests: number; notificationCount?: number;
nativeSummary: { status: string | null; pid: number | null; rootExited: boolean | null; treeConfirmed?: boolean | null; receipt: { messageId: string } | null; notifications: number };
review?: { source: string; evidenceSha256: string; reviewedAt: string; result: string };
}
export interface ReaAvailability { status: string; version?: string; declaredVersion?: string; message?: string; packageRoot?: string; protocolVersion?: string; operations?: { id: string; name: string; extensions: string[]; label: string }[] }
export interface ResearchTarget { id: string; taskId: string; runId: string; projectId: string; sessionId: string; path: string; sha256: string; bytes: number; extension: string; label: string; source: string; registeredAt: string }
export interface ResearchJob {
id: string; taskId: string; runId: string; targetId: string; targetSha256: string; operation: string; operationId: string;
status: string; summary: string; startedAt: string; finishedAt: string | null; evidenceId?: string; reusedFromJobId?: string;
evidenceBinding?: { verified: boolean; statistics?: Record<string, unknown>; limitations: string[]; scope: string } | null;
installation: ReaAvailability; before?: { path: string }; raw?: { id: string; documentSha256: string }; traceArtifactId?: string;
cleanup?: { rootExited: boolean }; requiresVerification: boolean;
}
export interface ResearchPage { content: string; offset: number; next_offset: number; total_characters: number; truncated: boolean; pointer?: string;
evidence_id?: string; target_sha256?: string; source_document_sha256: string; available_fields?: string[] }
export interface BrowserStep { action: 'fill' | 'select' | 'click' | 'assert_text' | 'assert_count' | 'assert_visible'; selector: string; value?: string; text?: string; count?: number; visible?: boolean; contains?: boolean }
export interface BrowserPlan { id: string; taskId: string; runId: string; status: string; fingerprint: string; sourceFingerprint: string; build: { directory: string; files: number; bytes: number; sha256: string }; path: string; viewport: { width: number; height: number }; steps: BrowserStep[] }
export interface BrowserJob { id: string; taskId: string; runId: string; planId: string; planFingerprint: string; sourceFingerprint: string; buildSha256: string; status: string; startedAt: string; finishedAt: string | null; summary: string; resultArtifactId?: string; resultSha256?: string; assertions: { total: number; passed: number; failed: number }; requiresVerification: boolean; cleanup?: { exited: boolean; pid: number | null }; steps: (BrowserStep & { status: string; error?: string; actual?: unknown })[]; screenshots: { artifactId: string; sha256: string; bytes: number; width: number; height: number; label: string }[] }
export interface EvaluationReport {environmentComparison?:{dependencyInputs:string;matched:boolean}}
@@ -0,0 +1,217 @@
import fs from 'node:fs';
import path from 'node:path';
import http from 'node:http';
import { createRequire } from 'node:module';
import { randomUUID } from 'node:crypto';
import { setTimeout as pause } from 'node:timers/promises';
import { PREVIEW_MIME } from './build-snapshot.mjs';
import { BROWSER_LIMITS, browserError, browserHash } from '../../shared/contracts/browser.mjs';
const at = () => new Date().toISOString();
const identity = file => {
if (fs.lstatSync(file).isSymbolicLink() || !fs.statSync(file).isFile()) throw browserError('浏览器运行输入不能是链接或非常规文件。');
return { path: fs.realpathSync.native(file), sha256: browserHash(fs.readFileSync(file)) };
};
export function browserInstallation(appDirectory = process.cwd()) {
try {
const moduleRoot = [path.join(appDirectory, 'runtime', 'node_modules'), path.join(appDirectory, 'node_modules')]
.find(root => fs.existsSync(path.join(root, 'playwright', 'index.js')) && fs.existsSync(path.join(root, 'playwright-core', 'index.js')));
if (!moduleRoot) throw new Error('缺少随包Playwright1.64.1运行库。');
const pkg = JSON.parse(fs.readFileSync(path.join(moduleRoot, 'playwright', 'package.json'), 'utf8'));
const core = JSON.parse(fs.readFileSync(path.join(moduleRoot, 'playwright-core', 'package.json'), 'utf8'));
if (pkg.version !== '1.64.1' || core.version !== pkg.version) throw new Error('浏览器运行库版本需要固定为Playwright1.64.1。');
const executable = [process.env['ProgramFiles(x86)'], process.env.ProgramFiles, process.env.LOCALAPPDATA].filter(Boolean)
.map(root => path.join(root, 'Microsoft', 'Edge', 'Application', 'msedge.exe')).find(file => fs.existsSync(file));
if (process.platform !== 'win32' || !executable) throw new Error('未检测到本机Microsoft Edge,请安装Edge后重新准备浏览器检查。');
const inputs = ['playwright/package.json', 'playwright/index.js', 'playwright-core/package.json', 'playwright-core/index.js',
'playwright-core/lib/bootstrap.js', 'playwright-core/lib/coreBundle.js', 'playwright-core/lib/utilsBundle.js', 'playwright-core/lib/serverRegistry.js', 'playwright-core/browsers.json']
.map(file => identity(path.join(moduleRoot, file)));
return { status: 'available', engine: 'Microsoft Edge', playwrightVersion: pkg.version, modulePath: inputs[1].path,
executable: identity(executable), node: identity(process.execPath), inputs, fingerprint: browserHash(inputs) };
} catch (error) { return { status: 'missing', message: error.message, engine: 'Microsoft Edge', playwrightVersion: '1.64.1' }; }
}
export function verifyBrowserInstallation(installation) {
if (installation.status !== 'available') throw browserError(installation.message ?? '浏览器运行库不可用。');
for (const input of [...installation.inputs, installation.executable, installation.node]) {
const current = identity(input.path);
if (current.path !== input.path || current.sha256 !== input.sha256) throw browserError('浏览器或运行库在计划后变化,请重新准备浏览器检查。');
}
}
const browserEnvironment = () => Object.fromEntries(Object.entries(process.env).filter(([key]) =>
/^(PATH|SYSTEMROOT|WINDIR|TEMP|TMP|LOCALAPPDATA|PROGRAMFILES|PROGRAMFILES\(X86\)|PROGRAMW6432|USERPROFILE|COMSPEC)$/i.test(key)));
async function startPreview(snapshot, plan) {
const nonce = randomUUID(), files = new Map(plan.build.files.map(file => [file.path, file]));
const server = http.createServer((request, response) => {
try {
if (!['GET', 'HEAD'].includes(request.method) || request.headers.host !== '127.0.0.1:' + server.address().port || request.headers['x-workbench-preview'] !== nonce) {
response.writeHead(403); response.end(); return;
}
const pathname = decodeURIComponent(new URL(request.url, 'http://127.0.0.1').pathname);
if (/[\\\0]/.test(pathname) || pathname.split('/').includes('..')) { response.writeHead(400); response.end(); return; }
let name = pathname.replace(/^\/+/, '') || 'index.html';
if (name === 'favicon.ico' && !files.has(name)) { response.writeHead(204); response.end(); return; }
if (!files.has(name) && !path.extname(name) && String(request.headers.accept ?? '').includes('text/html')) name = 'index.html';
const manifest = files.get(name);
if (!manifest) { response.writeHead(404); response.end(); return; }
const target = path.resolve(snapshot.directory, name);
if (!target.startsWith(snapshot.directory + path.sep) || fs.lstatSync(target).isSymbolicLink()) { response.writeHead(403); response.end(); return; }
const bytes = fs.readFileSync(target);
if (bytes.length !== manifest.bytes || browserHash(bytes) !== manifest.sha256) { response.writeHead(409); response.end(); return; }
response.writeHead(200, { 'Content-Type': PREVIEW_MIME[path.extname(name).toLowerCase()], 'Cache-Control': 'no-store',
'X-Content-Type-Options': 'nosniff', 'Referrer-Policy': 'no-referrer',
'Content-Security-Policy': "object-src 'none'; frame-src 'none'; worker-src 'none'; base-uri 'self'; form-action 'self'" });
response.end(request.method === 'HEAD' ? undefined : bytes);
} catch { if (!response.headersSent) response.writeHead(400); response.end(); }
});
await new Promise((resolve, reject) => { server.once('error', reject); server.listen(0, '127.0.0.1', resolve); });
return { origin: 'http://127.0.0.1:' + server.address().port, nonce, server,
async close() { server.closeAllConnections(); await new Promise(resolve => server.close(resolve)); } };
}
async function observe(page) {
return page.evaluate(({ textLimit }) => {
const body = document.body, text = body?.innerText ?? '';
const controls = [...document.querySelectorAll('button,input,select,textarea,a,[role="button"],[data-testid]')];
const uniqueSelector = node => {
const unique = selector => {
if (!selector || selector.length > 300) return false;
try { const matches = document.querySelectorAll(selector); return matches.length === 1 && matches[0] === node; } catch { return false; }
};
const candidates = node.id ? ['#' + CSS.escape(node.id)] : [];
for (const attribute of ['data-testid', 'aria-label', 'name']) {
const value = node.getAttribute(attribute);
if (value) candidates.push(node.tagName.toLowerCase() + '[' + attribute + '="' + CSS.escape(value) + '"]');
}
for (const selector of candidates) if (unique(selector)) return { selector, selectorMatches: 1, selectorEvidence: 'observed-dom-query' };
let current = node, parts = [];
for (let depth = 0; current?.parentElement && depth < 12; depth++, current = current.parentElement) {
const siblings = [...current.parentElement.children].filter(value => value.tagName === current.tagName);
parts.unshift(current.tagName.toLowerCase() + ':nth-of-type(' + (siblings.indexOf(current) + 1) + ')');
const selector = parts.join(' > ');
if (unique(selector)) return { selector, selectorMatches: 1, selectorEvidence: 'observed-dom-query' };
}
return { selector: null, selectorMatches: null, selectorEvidence: 'unavailable' };
};
return { url: location.href, title: document.title.slice(0, 300), text: text.slice(0, textLimit), textCharacters: text.length,
textTruncated: text.length > textLimit, viewport: { width: innerWidth, height: innerHeight, scrollWidth: body?.scrollWidth ?? 0 },
controls: controls.slice(0, 80).map(node => ({ ...uniqueSelector(node), tag: node.tagName.toLowerCase(), id: node.id?.slice(0, 200) ?? '',
role: node.getAttribute('role'), label: node.getAttribute('aria-label')?.slice(0, 300) ?? '',
text: (node.innerText ?? '').slice(0, 300), type: node.getAttribute('type'), testId: node.getAttribute('data-testid'),
value: typeof node.value === 'string' ? node.value.slice(0, 1000) : null, disabled: !!node.disabled,
options: node.tagName === 'SELECT' ? [...node.options].slice(0, 30).map(option => ({ value: option.value.slice(0, 200), text: option.text.slice(0, 300) })) : undefined })),
controlsTruncated: controls.length > 80 };
}, { textLimit: BROWSER_LIMITS.text });
}
async function untilActual(read, matches, signal) {
const deadline = Date.now() + BROWSER_LIMITS.stepTimeoutMs; let actual;
do {
signal.throwIfAborted(); actual = await read(); if (matches(actual)) return actual;
if (Date.now() < deadline) await pause(50, undefined, { signal });
} while (Date.now() < deadline);
throw Object.assign(new Error('页面断言未满足预期,实际值:' + JSON.stringify(actual).slice(0, 600)), { actual });
}
async function perform(page, step, signal) {
const locator = page.locator(step.selector);
if (step.action === 'assert_count') return untilActual(() => locator.count(), value => value === step.count, signal);
if (step.action === 'assert_visible') return untilActual(() => locator.isVisible(), value => value === (step.visible ?? true), signal);
if (step.action === 'assert_text') return untilActual(() => locator.innerText({ timeout: BROWSER_LIMITS.stepTimeoutMs }),
value => step.contains ? value.includes(step.text) : value.trim() === step.text, signal);
if (await locator.count() !== 1) throw new Error('交互选择器必须唯一,请根据实际DOM重新定位:' + step.selector);
if (step.action === 'fill') { await locator.fill(step.value); return await locator.inputValue(); }
if (step.action === 'select') return await locator.selectOption(step.value);
await locator.click({ noWaitAfter: true }); return { clicked: true };
}
export class BrowserDriver {
async run(snapshot, plan, { signal, onConnection = () => {}, onPhase = () => {}, onStep = () => {} } = {}) {
const result = { schemaVersion: 1, kind: 'browser-execution', startedAt: at(), status: 'failed', steps: [], pages: [], console: [],
pageErrors: [], requests: [], requestFailures: [], blockedRequests: [], policyEvents: [], screenshots: [], cleanup: null, limits: { ...BROWSER_LIMITS } };
let preview, browserServer, browser, page, processExit, closePromise, launchDispatched = false; const images = [];
const append = (key, value) => {
if (result[key].length < BROWSER_LIMITS.records) result[key].push(value);
else result.outputTruncated = true;
};
const closeBrowser = async () => {
if (!browserServer) return;
return closePromise ??= browserServer.close().catch(error => { result.closeError = error.message.slice(0, 1000); });
};
const abort = () => { closeBrowser().catch(() => {}); };
const capture = async label => {
if (!page || page.isClosed() || signal.aborted) return;
const observed = await observe(page); observed.label = label; result.pages.push(observed);
const bytes = await page.screenshot({ type: 'png', fullPage: false, animations: 'disabled', scale: 'css', timeout: BROWSER_LIMITS.stepTimeoutMs });
if (bytes.length > BROWSER_LIMITS.fileBytes) throw new Error('页面截图超过8MB保存上限。');
const image = { label, bytes, sha256: browserHash(bytes), width: plan.viewport.width, height: plan.viewport.height };
images.push(image); result.screenshots.push({ label, sha256: image.sha256, bytes: bytes.length, width: image.width, height: image.height });
};
try {
signal.throwIfAborted(); verifyBrowserInstallation(plan.installation);
preview = await startPreview(snapshot, plan); result.origin = preview.origin;
onPhase('launching');
const { chromium } = createRequire(plan.installation.modulePath)(plan.installation.modulePath);
launchDispatched = true;
browserServer = await chromium.launchServer({ executablePath: plan.installation.executable.path, headless: true, timeout: 15000,
host: '127.0.0.1', port: 0, env: browserEnvironment() });
const child = browserServer.process(); result.connection = { pid: child.pid, startedAt: at(), executable: plan.installation.executable, isolatedProfile: true };
processExit = child.exitCode !== null ? Promise.resolve() : new Promise(resolve => child.once('exit', resolve)); onConnection(result.connection);
signal.addEventListener('abort', abort, { once: true }); signal.throwIfAborted();
browser = await chromium.connect(browserServer.wsEndpoint()); result.browserVersion = browser.version();
const context = await browser.newContext({ viewport: plan.viewport, deviceScaleFactor: 1, serviceWorkers: 'block', acceptDownloads: false,
extraHTTPHeaders: { 'X-Workbench-Preview': preview.nonce }, locale: 'zh-CN', reducedMotion: 'reduce' });
await context.route('**/*', route => {
const request = route.request(), url = new URL(request.url());
if (url.origin !== preview.origin || !['GET', 'HEAD'].includes(request.method())) {
append('blockedRequests', { url: request.url().slice(0, 700), method: request.method(), at: at(), reason: 'outside-owned-static-preview' });
return route.abort('blockedbyclient').catch(() => {});
}
return route.continue().catch(() => {});
});
await context.routeWebSocket('**/*', socket => { append('policyEvents', { type: 'websocket', url: socket.url().slice(0, 700), at: at() }); socket.close(); });
context.on('page', opened => { if (page && opened !== page) { append('policyEvents', { type: 'popup', at: at() }); opened.close().catch(() => {}); } });
page = await context.newPage(); page.setDefaultTimeout(BROWSER_LIMITS.stepTimeoutMs); page.setDefaultNavigationTimeout(10000);
page.on('console', message => append('console', { type: message.type(), text: message.text().slice(0, 2000), at: at() }));
page.on('pageerror', error => append('pageErrors', { message: error.message.slice(0, 2000), at: at() }));
page.on('response', response => append('requests', { url: response.url().slice(0, 700), status: response.status(), at: at() }));
page.on('requestfailed', request => append('requestFailures', { url: request.url().slice(0, 700), error: request.failure()?.errorText ?? '', at: at() }));
page.on('download', download => { append('policyEvents', { type: 'download', at: at() }); download.cancel().catch(() => {}); });
page.on('dialog', dialog => { append('policyEvents', { type: 'dialog', message: dialog.message().slice(0, 600), at: at() }); dialog.dismiss().catch(() => {}); });
onPhase('running'); await page.goto(preview.origin + plan.path, { waitUntil: 'networkidle', timeout: 10000 }); signal.throwIfAborted(); await capture('initial');
for (let index = 0; index < plan.steps.length; index++) {
signal.throwIfAborted(); const step = plan.steps[index], record = { index, ...step, startedAt: at(), status: 'failed' };
try { record.actual = await perform(page, step, signal); record.status = 'passed'; }
catch (error) { record.error = error.message.slice(0, 1200); if (error.actual !== undefined) record.actual = error.actual; }
if (typeof record.actual === 'string' && record.actual.length > 4000) { record.actualSha256 = browserHash(record.actual); record.actual = record.actual.slice(0, 4000); record.actualTruncated = true; }
record.finishedAt = at(); result.steps.push(record); await onStep(record);
if (record.status !== 'passed') throw new Error('第' + (index + 1) + '步失败:' + record.error);
}
await page.waitForLoadState('networkidle', { timeout: BROWSER_LIMITS.stepTimeoutMs }); await capture('final');
result.assertions = { total: result.steps.filter(step => step.action.startsWith('assert_')).length,
passed: result.steps.filter(step => step.action.startsWith('assert_') && step.status === 'passed').length,
failed: result.steps.filter(step => step.action.startsWith('assert_') && step.status !== 'passed').length };
const problems = result.pageErrors.length || result.console.some(item => item.type === 'error') || result.requestFailures.length
|| result.blockedRequests.length || result.requests.some(item => item.status >= 400) || result.policyEvents.length || result.outputTruncated;
result.status = problems ? 'failed' : result.assertions.total ? 'passed' : 'observed';
if (problems) result.error = '页面出现脚本、控制台、请求或执行范围错误,请查看原记录。';
} catch (error) {
result.status = signal.aborted ? signal.reason?.name === 'TimeoutError' ? 'failed' : 'interrupted' : 'failed';
result.timedOut = signal.aborted && signal.reason?.name === 'TimeoutError'; result.error = error.message.slice(0, 2000);
try { if (result.pages.length < 2) await capture('failure'); } catch (captureError) { result.captureError = captureError.message.slice(0, 600); }
} finally {
signal.removeEventListener('abort', abort);
try { onPhase('closing'); } catch (error) { result.phaseError = error.message.slice(0, 1000); }
await closeBrowser();
if (browserServer) {
const child = browserServer.process(); await Promise.race([processExit, pause(5000, undefined, { ref: false })]);
if (child.exitCode === null && child.signalCode === null) { try { child.kill(); } catch {} await Promise.race([processExit, pause(1000, undefined, { ref: false })]); }
result.cleanup = { pid: child.pid, exited: child.exitCode !== null || child.signalCode !== null, exitCode: child.exitCode, signal: child.signalCode, finishedAt: at() };
} else result.cleanup = { pid: null, exited: !launchDispatched, launched: launchDispatched ? 'unknown' : false, finishedAt: at() };
if (preview) { await preview.close(); result.cleanup.previewClosed = true; }
result.finishedAt = at();
}
result.assertions ??= { total: result.steps.filter(step => step.action.startsWith('assert_')).length,
passed: result.steps.filter(step => step.action.startsWith('assert_') && step.status === 'passed').length,
failed: result.steps.filter(step => step.action.startsWith('assert_') && step.status !== 'passed').length };
return { record: result, images };
}
}
@@ -0,0 +1,235 @@
import { randomUUID } from 'node:crypto';
import fs from 'node:fs';
import { safePath } from '../../server/files.mjs';
import { BrowserDriver, browserInstallation, verifyBrowserInstallation } from './browser-driver.mjs';
import { inspectBuild, snapshotBuild } from './build-snapshot.mjs';
import { inspectProject } from '../project-inspector.mjs';
import { verifyWorkspaceProject } from '../workspaces/git-workspaces.mjs';
import { assertChangeSetsResolved } from '../../shared/contracts/change-sets.mjs';
import { assertWorkspacesResolved } from '../../shared/contracts/workspaces.mjs';
import { BROWSER_LIMITS, browserError, browserHash, browserPlanInput, browserPlanContract, assertBrowserResolved } from '../../shared/contracts/browser.mjs';
import { artifactPage } from '../context/read-budget.mjs';
import { assertMcpResolved } from '../tools/mcp-contract.mjs';
const at = () => new Date().toISOString();
export const publicBrowserPlan = plan => ({ id: plan.id, sessionId: plan.sessionId, projectId: plan.projectId, taskId: plan.taskId, runId: plan.runId,
status: plan.status, createdAt: plan.createdAt, fingerprint: plan.fingerprint, sourceFingerprint: plan.sourceFingerprint,
build: { directory: plan.build.directory, files: plan.build.files.length, bytes: plan.build.bytes, sha256: plan.build.sha256 },
path: plan.path, viewport: plan.viewport, steps: plan.steps, limits: plan.limits, contractArtifactId: plan.contractArtifactId,
installation: { status: plan.installation.status, engine: plan.installation.engine, playwrightVersion: plan.installation.playwrightVersion,
executableSha256: plan.installation.executable?.sha256 }, source: plan.source });
const jobBinding = job => ({ schemaVersion: 1, kind: 'browser-result-binding', id: job.id, sessionId: job.sessionId, projectId: job.projectId,
taskId: job.taskId, runId: job.runId, planId: job.planId, planFingerprint: job.planFingerprint, sourceFingerprint: job.sourceFingerprint,
buildSha256: job.buildSha256, status: job.status, resultArtifactId: job.resultArtifactId, resultSha256: job.resultSha256,
screenshots: job.screenshots, assertions: job.assertions, cleanup: job.cleanup, before: job.before, after: job.after });
export function browserPlanFor(store, session, id, { currentTask = true } = {}) {
const plan = store.owned('browser_plan', id, session.id);
if (currentTask && plan.taskId !== session.taskId) throw browserError('浏览器计划属于此前Task,请在当前任务重新准备。');
const artifact = store.owned('artifact', plan.contractArtifactId, session.id);
if (artifact.kind !== 'browser-plan' || artifact.taskId !== plan.taskId || artifact.runId !== plan.runId || artifact.sha256 !== plan.contractSha256
|| store.artifactStore.read(artifact) !== JSON.stringify(browserPlanContract(plan))) throw browserError('浏览器计划与封存的输入、视口或交互不一致。');
return plan;
}
export function verifyBrowserJob(store, session, job) {
store.owned('browser_job', job.id, session.id);
const plan = browserPlanFor(store, session, job.planId, { currentTask: false });
if (plan.taskId !== job.taskId || plan.projectId !== job.projectId || plan.fingerprint !== job.planFingerprint || plan.sourceFingerprint !== job.sourceFingerprint
|| plan.build.sha256 !== job.buildSha256) throw browserError('浏览器结果与原Task、计划或工程输入不匹配。');
const binding = store.owned('artifact', job.bindingArtifactId, session.id), artifact = store.owned('artifact', job.resultArtifactId, session.id);
if (binding.kind !== 'browser-binding' || binding.sha256 !== job.bindingSha256 || binding.taskId !== job.taskId || binding.runId !== job.runId
|| store.artifactStore.read(binding) !== JSON.stringify(jobBinding(job))) throw browserError('浏览器结果与封存绑定不一致。');
if (artifact.kind !== 'browser-result' || artifact.sha256 !== job.resultSha256 || artifact.taskId !== job.taskId || artifact.runId !== job.runId) throw browserError('浏览器原结果工件归属无效。');
const result = JSON.parse(store.artifactStore.read(artifact));
if (result.kind !== 'browser-execution' || result.schemaVersion !== 1 || result.jobId !== job.id || result.taskId !== job.taskId || result.runId !== job.runId
|| result.projectId !== job.projectId || result.planId !== job.planId || result.planFingerprint !== job.planFingerprint || result.buildSha256 !== job.buildSha256
|| result.sourceFingerprint !== job.sourceFingerprint || JSON.stringify(result.screenshots) !== JSON.stringify(job.screenshots)
|| JSON.stringify(result.assertions) !== JSON.stringify(job.assertions) || JSON.stringify(result.cleanup) !== JSON.stringify(job.cleanup)) throw browserError('浏览器原返回与执行身份或统计不一致。');
for (const image of result.screenshots) {
const stored = store.owned('artifact', image.artifactId, session.id);
if (stored.kind !== 'browser-screenshot' || stored.mediaType !== 'image/png' || stored.taskId !== job.taskId || stored.runId !== job.runId
|| stored.sha256 !== image.sha256 || stored.bytes !== image.bytes) throw browserError('浏览器截图与所属任务或原字节不一致。');
const bytes = store.artifactStore.readBytes(stored);
if (bytes.length < 24 || !bytes.subarray(0, 8).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]))
|| bytes.readUInt32BE(16) !== image.width || bytes.readUInt32BE(20) !== image.height) throw browserError('浏览器原截图格式或尺寸无法核对。');
}
if (result.status === 'passed' && (!result.cleanup?.exited || !result.assertions?.total || result.assertions.passed !== result.assertions.total
|| result.assertions.failed || result.steps.length !== plan.steps.length || result.steps.some((step, index) => step.status !== 'passed'
|| Object.keys(plan.steps[index]).some(key => JSON.stringify(step[key]) !== JSON.stringify(plan.steps[index][key]))))) throw browserError('浏览器通过状态缺少完整实际步骤、断言或进程结束依据。');
return result;
}
export async function currentBrowserVerification(store, session, inspection = null) {
const plan = [...store.core.browser_plan.values()].findLast(value => value.sessionId === session.id && value.taskId === session.taskId);
if (!plan) return { required: false, status: 'not_requested' };
const job = [...store.core.browser_job.values()].findLast(value => value.sessionId === session.id && value.taskId === session.taskId && value.planId === plan.id);
const result = { required: true, planId: plan.id, jobId: job?.id ?? null, status: job?.status ?? 'not_run', evidenceVerified: false,
sourceFingerprint: plan.sourceFingerprint, buildSha256: plan.build.sha256 };
try {
browserPlanFor(store, session, plan.id);
if (!job?.resultArtifactId) return result;
const original = verifyBrowserJob(store, session, job); result.evidenceVerified = true; result.assertions = original.assertions;
result.resultArtifactId = job.resultArtifactId; result.screenshots = job.screenshots;
inspection ??= await inspectProject(store.project(session.projectId));
const build = await inspectBuild(store.project(session.projectId), plan.build.directory);
if (inspection.sourceFingerprint !== job.sourceFingerprint || !inspection.scope.complete || build.sha256 !== job.buildSha256) result.status = 'stale';
if (!original.cleanup?.exited) result.status = 'unknown';
if (result.status === 'passed' && original.status !== 'passed') result.status = 'unverified';
} catch (error) { result.status = 'unverified'; result.error = error.message; }
return result;
}
export class BrowserManager {
constructor(store, { appDirectory = process.cwd(), installation = null, driverFactory = () => new BrowserDriver(), projectBusy = () => false,
redact = value => String(value) } = {}) {
this.store = store; this.appDirectory = appDirectory; this.installation = installation; this.driverFactory = driverFactory;
this.projectBusy = projectBusy; this.redact = redact; this.active = new Map(); this.projects = new Map();
}
availability() { const value = this.installation ?? browserInstallation(this.appDirectory); return value; }
builds(project) { return ['dist', 'build', 'out'].filter(name => { try { return fs.existsSync(safePath(project, name + '/index.html', true)); } catch { return false; } }); }
isActive(sessionId) { return [...this.active.values()].some(value => value.sessionId === sessionId); }
projectActive(projectId) { return this.projects.has(projectId); }
plans(session) { return [...this.store.core.browser_plan.values()].filter(plan => plan.sessionId === session.id && plan.taskId === session.taskId).slice(-5).map(publicBrowserPlan); }
jobs(session) { return [...this.store.core.browser_job.values()].filter(job => job.sessionId === session.id && (job.taskId === session.taskId || job.requiresVerification)).slice(-12); }
assertReady(session, source = 'user') {
assertMcpResolved(this.store, session.projectId);
assertChangeSetsResolved(this.store, session.projectId, { includePrepared: true }); assertWorkspacesResolved(this.store, session.projectId, { includePrepared: true });
if (!session.taskId || !session.runId) throw browserError('先创建当前工程Task,再准备浏览器检查。');
if (session.changes.some(change => ['pending', 'conflict'].includes(change.status))) throw browserError('请先审查应用或撤回待处理改动,再检查实际页面。');
if (this.projectActive(session.projectId) || this.projectBusy(session.projectId, source === 'agent' ? session.id : null)) throw browserError('同一项目还有任务或检查在执行,请等待结束。');
}
async plan(session, input, { source = 'user' } = {}) {
this.assertReady(session, source); const normalized = browserPlanInput(input), identity = { taskId: session.taskId, runId: session.runId };
const project = this.store.project(session.projectId); await verifyWorkspaceProject(this.store, project);
const inspection = await inspectProject(project); if (!inspection.scope.complete) throw browserError('工程源码快照不完整,请缩小工程范围后再准备浏览器检查。');
const build = await inspectBuild(project, normalized.buildDirectory), installation = this.availability();
if (installation.status !== 'available') throw browserError(installation.message);
if (identity.taskId !== session.taskId || identity.runId !== session.runId) throw browserError('准备浏览器计划期间Task/Run已切换,请重新准备。');
const run = this.store.owned('run', identity.runId, session.id);
const plan = { schemaVersion: 1, id: randomUUID(), sessionId: session.id, projectId: project.id, taskId: identity.taskId, runId: identity.runId,
projectRoot: project.root, sourceFingerprint: inspection.sourceFingerprint, build, path: normalized.path, viewport: normalized.viewport,
steps: normalized.steps, installation, limits: { ...BROWSER_LIMITS }, status: 'planned', createdAt: at(), source };
plan.fingerprint = browserHash({ projectRoot: plan.projectRoot, sourceFingerprint: plan.sourceFingerprint, build, path: plan.path,
viewport: plan.viewport, steps: plan.steps, installation, limits: plan.limits });
const contract = this.store.artifactStore.write(session, run, browserPlanContract(plan), { kind: 'browser-plan' });
this.store.core.artifact.set(contract.id, contract); plan.contractArtifactId = contract.id; plan.contractSha256 = contract.sha256;
return this.store.putRecord('browser_plan', session, plan, 'browser.plan');
}
planFor(session, id) { return browserPlanFor(this.store, session, id); }
start(session, id, { source = 'user', signal } = {}) {
this.assertReady(session, source); assertBrowserResolved(this.store, session.projectId); const plan = this.planFor(session, id);
const previous = [...this.store.core.browser_job.values()].findLast(job => job.sessionId === session.id && job.taskId === session.taskId && job.planId === plan.id);
if (previous && !['passed', 'observed'].includes(previous.status)) throw browserError('这份计划已有失败或中断原记录,请查看后重新准备计划;不会自动重放。');
const jobId = randomUUID(), controller = new AbortController(), combined = signal ? AbortSignal.any([signal, controller.signal]) : controller.signal;
const active = { sessionId: session.id, projectId: session.projectId, controller, signal: combined, promise: null };
this.active.set(jobId, active); this.projects.set(session.projectId, jobId);
if (previous) {
active.promise = (async () => { const inspection = await inspectProject(this.store.project(session.projectId)), build = await inspectBuild(this.store.project(session.projectId), plan.build.directory);
if (inspection.sourceFingerprint !== previous.sourceFingerprint || build.sha256 !== previous.buildSha256) throw browserError('已完成浏览器结果对应旧输入,请按当前工程重新准备计划。');
verifyBrowserJob(this.store, session, previous); return previous; })().finally(() => this.release(jobId, active));
active.promise.catch(() => {}); return { job: previous, promise: active.promise, reused: true };
}
const run = this.store.owned('run', session.runId, session.id);
const job = { schemaVersion: 1, id: jobId, sessionId: session.id, projectId: session.projectId, taskId: run.taskId, runId: run.id,
planId: plan.id, planFingerprint: plan.fingerprint, sourceFingerprint: plan.sourceFingerprint, buildSha256: plan.build.sha256,
status: 'queued', source, startedAt: at(), finishedAt: null, steps: [], screenshots: [], assertions: { total: 0, passed: 0, failed: 0 },
requiresVerification: false, browserDispatched: false, summary: '浏览器检查已排队,尚未运行页面。', originalSessionStatus: session.status };
const event = this.store.event(session, { kind: 'browser', tool: 'browser_check', label: '验证工程页面', phase: 'queued',
input: { planId: plan.id, fingerprint: plan.fingerprint, buildDirectory: plan.build.directory, viewport: plan.viewport, steps: plan.steps.length } }); job.eventId = event.id;
try {
this.store.putRecord('browser_job', session, job, 'browser.queued');
active.promise = this.execute(session, plan, job, run, active).finally(() => this.release(jobId, active)); active.promise.catch(() => {});
return { job, promise: active.promise, reused: false };
} catch (error) { this.release(jobId, active); throw error; }
}
release(id, active) { this.active.delete(id); if (this.projects.get(active.projectId) === id) this.projects.delete(active.projectId); }
async execute(session, plan, job, run, active) {
let snapshot; const event = session.events.find(value => value.id === job.eventId), project = this.store.project(session.projectId);
const phase = status => { job.status = status; if (status === 'launching') job.browserDispatched = true; event.phase = status;
if (job.source === 'user' && session.taskId === job.taskId && session.runId === job.runId) session.status = 'running';
this.store.save(session, { type: 'browser.' + status, detail: { jobId: job.id, taskId: job.taskId, runId: job.runId } }); };
try {
await verifyWorkspaceProject(this.store, project); active.signal.throwIfAborted();
const inspection = await inspectProject(project), build = await inspectBuild(project, plan.build.directory, { signal: active.signal });
if (project.root !== plan.projectRoot || !inspection.scope.complete || inspection.sourceFingerprint !== plan.sourceFingerprint || build.sha256 !== plan.build.sha256) throw browserError('工程源码或构建在计划后变化,未启动浏览器,请重新准备。');
verifyBrowserInstallation(plan.installation); job.before = { sourceFingerprint: inspection.sourceFingerprint, buildSha256: build.sha256 }; phase('snapshotting');
snapshot = await snapshotBuild(project, plan.build, { signal: active.signal }); active.signal.throwIfAborted();
const signal = AbortSignal.any([active.signal, AbortSignal.timeout(BROWSER_LIMITS.durationMs)]);
const returned = await this.driverFactory().run(snapshot, plan, { signal, onPhase: phase,
onConnection: connection => { job.connection = connection; this.store.save(session, { type: 'browser.connection_owned', detail: { jobId: job.id, pid: connection.pid } }); },
onStep: record => { job.steps.push(JSON.parse(this.redact(JSON.stringify(record)))); this.store.save(session, { type: 'browser.step', detail: { jobId: job.id, index: record.index, status: record.status } }); } });
const record = returned.record; job.cleanup = record.cleanup;
if (!active.signal.aborted) {
try { const afterInspection = await inspectProject(project), afterBuild = await inspectBuild(project, plan.build.directory);
job.after = { sourceFingerprint: afterInspection.sourceFingerprint, buildSha256: afterBuild.sha256, complete: afterInspection.scope.complete }; }
catch (error) { job.after = { error: error.message, complete: false }; }
} else job.after = { complete: false, interrupted: true };
await snapshot.dispose(); snapshot = null; job.cleanup.snapshotDisposed = true;
for (const image of returned.images) {
const artifact = this.store.artifactStore.write(session, run, image.bytes, { kind: 'browser-screenshot', mediaType: 'image/png' }); this.store.core.artifact.set(artifact.id, artifact);
job.screenshots.push({ artifactId: artifact.id, sha256: artifact.sha256, bytes: artifact.bytes, width: image.width, height: image.height, label: image.label });
}
job.assertions = record.assertions; job.status = record.status;
if (!record.cleanup?.exited) { job.status = 'unknown'; job.requiresVerification = true; }
else if (!active.signal.aborted && (job.after?.sourceFingerprint !== job.sourceFingerprint || job.after?.buildSha256 !== job.buildSha256 || !job.after?.complete)) job.status = 'stale';
const value = JSON.parse(this.redact(JSON.stringify({ ...record, jobId: job.id, sessionId: job.sessionId, projectId: job.projectId, taskId: job.taskId, runId: job.runId,
planId: plan.id, planFingerprint: plan.fingerprint, sourceFingerprint: job.sourceFingerprint, buildSha256: job.buildSha256, screenshots: job.screenshots,
inputValidation: { before: job.before, after: job.after } })));
const artifact = this.store.artifactStore.write(session, run, value, { kind: 'browser-result' }); this.store.core.artifact.set(artifact.id, artifact);
job.resultArtifactId = artifact.id; job.resultSha256 = artifact.sha256; job.finishedAt = at();
job.summary = job.status === 'passed' ? '实际页面断言全部通过,原DOM、请求、截图和进程结束已保存。' : job.status === 'observed' ? '实际页面已读取,尚未配置验收断言。'
: job.status === 'stale' ? '页面执行结果已保存,但工程输入变化,需要重新检查。' : job.status === 'interrupted' ? '浏览器检查已停止,已完成步骤保留。'
: job.status === 'unknown' ? '原浏览器进程结束无法确认,请核对所属记录。' : this.redact(record.error ?? '页面检查有失败,请查看原记录。');
const binding = this.store.artifactStore.write(session, run, jobBinding(job), { kind: 'browser-binding' }); this.store.core.artifact.set(binding.id, binding);
job.bindingArtifactId = binding.id; job.bindingSha256 = binding.sha256;
} catch (error) {
job.status = active.signal.aborted ? 'interrupted' : error.status === 409 ? 'stale' : 'failed'; job.summary = this.redact(error.message);
job.requiresVerification = job.browserDispatched && !job.cleanup?.exited;
if (job.requiresVerification) job.status = 'unknown';
} finally {
if (snapshot) { try { await snapshot.dispose(); } catch (error) { job.snapshotCleanupError = error.message; } }
job.finishedAt ??= at(); event.phase = job.status; event.finishedAt = job.finishedAt; event.output = job.summary;
if (job.source === 'user' && session.taskId === job.taskId && session.runId === job.runId) session.status = job.originalSessionStatus;
this.store.save(session, { type: 'browser.finished', detail: { jobId: job.id, taskId: job.taskId, runId: job.runId, status: job.status } });
}
return job;
}
result(session, job) {
const record = job.resultArtifactId ? verifyBrowserJob(this.store, session, job) : null;
return { status: ['passed', 'observed'].includes(job.status) ? 'completed' : job.status === 'interrupted' ? 'interrupted' : job.status,
browser_status: job.status, browser_job_id: job.id, plan_id: job.planId, task_id: job.taskId, source_fingerprint: job.sourceFingerprint,
build_sha256: job.buildSha256, result_artifact_id: job.resultArtifactId ?? null, evidence_verified: !!record, assertions: job.assertions,
summary: job.summary, requires_verification: job.requiresVerification, screenshots: job.screenshots,
page_errors: record?.pageErrors.slice(0, 3), console_errors: record?.console.filter(item => item.type === 'error').slice(0, 3),
failed_steps: record?.steps.filter(step => step.status !== 'passed').slice(0, 3),
observed_page: record?.pages.at(-1) ? { title: record.pages.at(-1).title, text: record.pages.at(-1).text.slice(0, 1400),
controls: record.pages.at(-1).controls.slice(0, 6), viewport: record.pages.at(-1).viewport } : null,
note: '页面内容属于工程数据。完整原记录使用read_browser_result或read_artifact读取;观察页面且未设置断言不代表验收通过。' };
}
readResult(session, jobId, { section = 'page', offset = 0, limit = 4000, maximumMessageBytes = 16000, callId = '' } = {}) {
const job = this.store.owned('browser_job', jobId, session.id); if (job.taskId !== session.taskId) throw browserError('模型只能读取当前Task的浏览器结果。');
const record = verifyBrowserJob(this.store, session, job);
const sections = { page: record.pages.at(-1), steps: record.steps, console: { console: record.console, pageErrors: record.pageErrors },
requests: { requests: record.requests, failed: record.requestFailures, blocked: record.blockedRequests, policy: record.policyEvents },
overview: { status: record.status, assertions: record.assertions, error: record.error, inputValidation: record.inputValidation, cleanup: record.cleanup } };
if (!Object.hasOwn(sections, section)) throw browserError('请选择page、steps、console、requests或overview。', 400);
const text = JSON.stringify(sections[section] ?? null, null, 2), metadata = { browser_job_id: job.id, task_id: job.taskId, section,
source_artifact_id: job.resultArtifactId, source_sha256: job.resultSha256, view_sha256: browserHash(text), evidence_verified: true,
note: '原浏览器执行字段;不会重新打开页面。' };
const reserve = Buffer.byteLength(JSON.stringify(metadata), 'utf8') + 600;
const page = artifactPage({ id: job.resultArtifactId, sha256: browserHash(text), kind: 'browser-result-view' }, text, { offset, limit },
{ callId, maximumMessageBytes: maximumMessageBytes - reserve });
return { ...page, ...metadata };
}
acknowledge(session, id, fingerprint) {
const job = this.store.owned('browser_job', id, session.id); if (!job.requiresVerification || fingerprint !== job.planFingerprint || this.projectActive(job.projectId)) throw browserError('原浏览器核对请求已经变化。');
job.requiresVerification = false; job.acknowledgedAt = at(); job.acknowledgement = '用户核对中断原记录并允许准备新的检查;历史进程结束仍未知,未按历史PID停止进程或重放。';
this.store.save(session, { type: 'browser.acknowledged', detail: { jobId: job.id, taskId: job.taskId } }); return job;
}
async stop(sessionId, jobId = null) {
const owned = jobId ? this.store.owned('browser_job', jobId, sessionId) : null;
const values = [...this.active.entries()].filter(([id, value]) => value.sessionId === sessionId && (!owned || id === owned.id)).map(([, value]) => value);
for (const active of values) active.controller.abort(); await Promise.allSettled(values.map(value => value.promise));
}
async stopAll() { for (const active of this.active.values()) active.controller.abort(); await Promise.allSettled([...this.active.values()].map(value => value.promise)); }
}
@@ -0,0 +1,192 @@
import { randomUUID, randomBytes } from 'node:crypto';
import { browsingUrl, browsingAction, browsingError as conflict } from '../../shared/contracts/browsing.mjs';
const at = () => new Date().toISOString();
// Desktop content has no workbench preload. Only Electron main consumes this
// fixed command queue; webpage text and observations cannot create grants.
export class BrowsingManager {
constructor(store, { redact = String, allowHttpLoopback = false, workbenchOrigin = null, commandTimeoutMs = 20000 } = {}) {
Object.assign(this, { store, redact, allowHttpLoopback, workbenchOrigin, commandTimeoutMs });
this.active = new Map(); this.windows = new Map();
}
available() { return [...this.windows.entries()].filter(([, value]) => Date.now() - value.seenAt < 5000).map(([id]) => id); }
isActive(sessionId) { return [...this.active.values()].some(value => value.job.sessionId === sessionId); }
projectActive(projectId) { return [...this.active.values()].some(value => value.job.projectId === projectId); }
artifact(session, runId, value, kind, mediaType = 'application/json') {
const artifact = this.store.artifactStore.write(session, this.store.owned('run', runId, session.id),
Buffer.isBuffer(value) ? value : JSON.parse(this.redact(JSON.stringify(value))), { kind, mediaType });
this.store.core.artifact.set(artifact.id, artifact); return artifact;
}
own(session, id, { allowClosed = false } = {}) {
const tab = this.store.owned('browsing_tab', id, session.id);
if (tab.taskId !== session.taskId || !allowClosed && tab.status !== 'open') throw conflict('标签页不属于当前Task,或已关闭/撤销。请明确打开新标签页。');
return tab;
}
scope(tab) { return { origins: tab.origins, previewOrigin: tab.previewOrigin, allowHttpLoopback: this.allowHttpLoopback, workbenchOrigin: this.workbenchOrigin }; }
async open(session, input) {
const fields = ['url','previewJobId','origins','interact','persistent','profileId','approved'];
if (!input || Array.isArray(input) || Object.keys(input).some(key => !fields.includes(key)) || input.approved !== true) throw conflict('打开网站需要明确地址、来源范围及用户批准。');
if (!session.taskId || !session.runId) throw conflict('先建立任务,再授权浏览器目标。');
if ([...this.store.core.browsing_tab.values()].filter(tab => tab.sessionId === session.id && tab.status === 'open').length >= 8) throw conflict('每个会话最多8个打开的标签页。');
const windowId = this.available()[0]; if (!windowId) throw conflict('请先打开本工作台桌面端。网页端可以查看原观察和审批。');
let previewOrigin = null;
if (input.previewJobId) {
const preview = this.store.owned('preview_job', input.previewJobId, session.id);
if (preview.taskId !== session.taskId || preview.status !== 'ready') throw conflict('所属预览尚未就绪。');
previewOrigin = new URL(preview.url).origin;
}
const url = browsingUrl(input.url, { previewOrigin, allowHttpLoopback: this.allowHttpLoopback, workbenchOrigin: this.workbenchOrigin });
if (input.origins !== undefined && (!Array.isArray(input.origins) || input.origins.length > 8 || input.origins.some(value => typeof value !== 'string'))) throw conflict('最多明确授权8个网站来源。');
const origins = [...new Set([url.origin, ...(input.origins ?? []).map(value => browsingUrl(value, { previewOrigin, allowHttpLoopback: this.allowHttpLoopback, workbenchOrigin: this.workbenchOrigin }).origin)])];
if (input.interact !== undefined && typeof input.interact !== 'boolean' || input.persistent !== undefined && typeof input.persistent !== 'boolean') throw conflict('浏览授权选项无效。');
let profile;
if (input.profileId) {
profile = this.store.owned('browsing_profile', input.profileId, session.id);
if (!profile.persistent || profile.status !== 'active' || JSON.stringify(profile.origins) !== JSON.stringify(origins)) throw conflict('原登录资料的授权来源已变化或已清除。');
} else {
profile = { id: randomUUID(), sessionId: session.id, projectId: session.projectId, taskId: session.taskId, runId: session.runId,
persistent: input.persistent === true, origins, status: 'active', createdAt: at() };
this.store.putRecord('browsing_profile', session, profile, 'browsing.profile_created');
}
const tab = { id: randomUUID(), sessionId: session.id, projectId: session.projectId, taskId: session.taskId, runId: session.runId, windowId,
profileId: profile.id, persistent: profile.persistent, origins, previewOrigin, interact: input.interact === true, status: 'open', url: url.href, createdAt: at(), grantRevision: randomUUID() };
this.store.putRecord('browsing_tab', session, tab, 'browsing.open_requested');
try { await this.request(session, tab, 'open', { url: url.href }); return tab; }
catch (error) { tab.status = 'unavailable'; tab.error = error.message; this.store.save(session, { type: 'browsing.open_failed' }); throw error; }
}
async observe(session, id) { const tab = this.own(session, id); return this.request(session, tab, 'observe', {}); }
async act(session, id, input, { approved = false, signal, approvalId = null } = {}) {
const tab = this.own(session, id), action = browsingAction(input);
if (signal?.aborted) throw conflict('原浏览动作已停止。');
const observation = this.store.owned('browsing_observation', action.observationId, session.id);
if (observation.tabId !== tab.id || observation.revision !== action.revision || tab.observationId !== observation.id) throw conflict('原页面观察已失效,请重新观察再操作。');
if (['click','fill'].includes(action.action) && !observation.controls.some(control => control.ref === action.ref && !control.disabled && control.type !== 'password' && control.type !== 'file')) throw conflict('原可见控件不存在、已禁用或属于受限输入。');
if (!['scroll','wait'].includes(action.action) && (approved !== true || !tab.interact)) throw conflict('页面交互与下载需要原授权范围和本次明确批准。');
if (approvalId) {
const approval = session.approvals.find(value => value.id === approvalId);
if (!approval || approval.status !== 'approved' || approval.taskId !== session.taskId || approval.runId !== session.runId || approval.browsingTabId !== id
|| JSON.stringify(approval.browsingInput) !== JSON.stringify(action)) throw conflict('原浏览动作审批的Task、Run或具体输入已变化。');
}
if (action.url) browsingUrl(action.url, this.scope(tab));
const original = [...this.store.core.browsing_action.values()].some(job => job.tabId === tab.id && job.kind === 'act'
&& (job.status === 'completed' && job.input.observationId === action.observationId || job.status === 'unknown' && !job.reconciliation));
if (original) throw conflict('该观察已有结果未知的原动作,请先核对原页面和回执并明确保留现场;不能重复提交。');
return this.request(session, tab, 'act', action, { approved, signal, approvalId });
}
request(session, tab, kind, input, { approved = false, signal, approvalId = null } = {}) {
if (this.active.size >= 8 || [...this.active.values()].some(value => value.job.tabId === tab.id)) throw conflict('原标签页已有待完成动作,请等待原回执。');
if (!this.available().includes(tab.windowId)) throw conflict('所属桌面浏览区已断开,不自动重放原动作。');
const job = { id: randomUUID(), sessionId: session.id, projectId: session.projectId, taskId: session.taskId, runId: session.runId,
tabId: tab.id, windowId: tab.windowId, kind, input, approved, approvalId, source: approvalId ? 'agent' : 'user', grantRevision: tab.grantRevision, status: 'queued', createdAt: at() };
this.store.putRecord('browsing_action', session, job, 'browsing.queued');
const nonce = randomBytes(24).toString('hex');
return new Promise((resolve, reject) => {
const fail = reason => {
const pending = this.active.get(job.id); if (!pending) return;
this.active.delete(job.id); clearTimeout(pending.timer); signal?.removeEventListener('abort', pending.abort);
job.status = job.dispatchedAt && kind === 'act' ? 'unknown' : 'failed'; job.requiresVerification = job.status === 'unknown'; job.finishedAt = at(); job.error = reason;
try {
const receipt = this.artifact(session, job.runId, { ...job }, 'browsing-action-receipt'); job.artifactId = receipt.id; job.artifactSha256 = receipt.sha256;
} catch (error) { job.evidenceError = this.redact(error.message); }
try { this.store.save(session, { type: 'browsing.interrupted' }); }
catch (error) { job.persistenceError = this.redact(error.message); }
reject(conflict(reason));
};
const abort = () => fail('原浏览动作被停止;已派发副作用需要先核对原页面,不能自动重放。');
const timer = setTimeout(() => fail('桌面浏览器未返回原回执,请核对原页面及动作记录。'), this.commandTimeoutMs);
this.active.set(job.id, { job, nonce, resolve, reject, fail, timer, abort, signal }); signal?.addEventListener('abort', abort, { once: true }); if (signal?.aborted) abort();
});
}
poll(windowId, states = []) {
this.windows.set(windowId, { seenAt: Date.now() });
if (Array.isArray(states) && states.length <= 64) for (const state of states) {
const tab = this.store.core.browsing_tab.get(state.id);
if (!tab || tab.windowId !== windowId || tab.status !== 'open' || typeof state.url !== 'string' || tab.url === state.url) continue;
try { tab.url = browsingUrl(state.url, this.scope(tab)).href; tab.title = String(state.title ?? '').slice(0,300); this.store.save(this.store.session(tab.sessionId), { type: 'browsing.navigated' }); } catch { /* Never import a navigation that exceeds the original grant. */ }
}
const commands = [...this.active.values()].filter(value => value.job.windowId === windowId && !value.job.dispatchedAt).slice(0, 4).map(value => {
value.job.status = 'dispatched'; value.job.dispatchedAt = at(); const tab = this.store.core.browsing_tab.get(value.job.tabId);
this.store.save(this.store.session(value.job.sessionId), { type: 'browsing.dispatched' });
return { id: value.job.id, nonce: value.nonce, tab: { ...tab, scope: this.scope(tab) }, kind: value.job.kind, input: value.job.input };
});
return { commands, retainedTabs: [...this.store.core.browsing_tab.values()].filter(tab => tab.windowId === windowId && tab.status === 'open').map(tab => tab.id) };
}
complete(windowId, input) {
if (!input || typeof input.id !== 'string') throw conflict('桌面回执缺少原动作身份。');
const active = this.active.get(input.id);
if (!active || active.job.windowId !== windowId || input.nonce !== active.nonce || !active.job.dispatchedAt) throw conflict('原桌面动作已结束或回执身份不匹配;迟到结果不会覆盖。');
const { job } = active, session = this.store.session(job.sessionId), tab = this.store.owned('browsing_tab', job.tabId, session.id);
let result;
try {
if (input.error) { job.status = input.uncertain ? 'unknown' : 'failed'; job.requiresVerification = !!input.uncertain; job.error = this.redact(String(input.error).slice(0, 2000)); }
else {
if (job.grantRevision !== tab.grantRevision && !['close','clear'].includes(job.kind)) throw conflict('原页面授权已撤销,不能接收为成功动作。');
const value = input.result;
if (!value || typeof value !== 'object' || JSON.stringify(value).length > 10 * 1024 * 1024) throw conflict('桌面回执格式或大小无效。');
if (value.observation) {
const observation = value.observation; browsingUrl(observation.url, this.scope(tab));
if (typeof observation.revision !== 'string' || observation.revision.length > 100 || typeof observation.text !== 'string' || observation.text.length > 18000 || !Array.isArray(observation.controls) || observation.controls.length > 120) throw conflict('页面观察超过固定范围。');
const png = Buffer.from(value.png ?? '', 'base64');
if (png.length < 8 || png.length > 6 * 1024 * 1024 || png.subarray(0, 8).toString('hex') !== '89504e470d0a1a0a') throw conflict('原页面截图格式或大小无法核对。');
const image = this.artifact(session, job.runId, png, 'browsing-screenshot', 'image/png');
const record = { ...observation, id: randomUUID(), sessionId: session.id, projectId: session.projectId, taskId: job.taskId, runId: job.runId,
tabId: tab.id, actionId: job.id, createdAt: at(), screenshotArtifactId: image.id, screenshotSha256: image.sha256, untrusted: true };
const artifact = this.artifact(session, job.runId, record, 'browsing-observation'); record.artifactId = artifact.id; record.artifactSha256 = artifact.sha256;
this.store.putRecord('browsing_observation', session, record, 'browsing.observed'); tab.url = record.url; tab.title = record.title; tab.observationId = record.id; tab.revision = record.revision; result = record;
}
if (value.download) {
if (job.kind !== 'act' || job.input.action !== 'download' || !job.approved) throw conflict('下载缺少原明确审批。');
const bytes = Buffer.from(value.download.bytes ?? '', 'base64'); if (bytes.length > 6 * 1024 * 1024) throw conflict('下载超过6MiB范围。');
browsingUrl(value.download.url, this.scope(tab)); if (value.download.url !== job.input.url) throw conflict('实际下载地址与原审批不符。');
const artifact = this.artifact(session, job.runId, bytes, 'browsing-download', 'application/octet-stream'); job.downloadArtifactId = artifact.id; job.downloadSha256 = artifact.sha256;
result = { artifactId: artifact.id, sha256: artifact.sha256, bytes: bytes.length, url: value.download.url };
}
job.status = 'completed'; job.result = result ?? value;
}
job.finishedAt = at(); const receipt = this.artifact(session, job.runId, { ...job }, 'browsing-action-receipt'); job.artifactId = receipt.id; job.artifactSha256 = receipt.sha256;
this.store.save(session, { type: 'browsing.finished' });
} catch (error) { active.fail(error.message); return { accepted: false }; }
this.active.delete(job.id); clearTimeout(active.timer); active.signal?.removeEventListener('abort', active.abort);
if (job.status === 'completed') active.resolve(result ?? job.result); else active.reject(conflict(job.error));
return { accepted: true };
}
async close(session, id, { clear = false } = {}) {
const tab = this.own(session, id, { allowClosed: true });
const affected = [...this.store.core.browsing_tab.values()].filter(value => value.id === id || clear && value.profileId === tab.profileId);
for (const value of this.active.values()) if (affected.some(tab => tab.id === value.job.tabId)) value.fail('标签页授权撤销,原未确认动作保持待核对。');
for (const value of affected) if (value.id !== id) { value.status = 'revoked'; value.grantRevision = randomUUID(); value.closedAt = at(); }
tab.status = clear ? 'revoked' : 'closed'; tab.grantRevision = randomUUID(); tab.closedAt = at(); this.store.save(session, { type: 'browsing.revoked' });
if (this.available().includes(tab.windowId)) await this.request(session, tab, clear ? 'clear' : 'close', {});
else if (clear && tab.persistent) throw conflict('授权已撤销;持久登录资料的磁盘清除需原桌面端重新连接后明确执行。');
if (clear) { const profile = this.store.owned('browsing_profile', tab.profileId, session.id); profile.status = 'cleared'; this.store.save(session, { type: 'browsing.profile_cleared' }); }
else if (!tab.persistent) { const profile = this.store.owned('browsing_profile', tab.profileId, session.id); profile.status = 'cleared'; this.store.save(session, { type: 'browsing.temporary_profile_closed' }); }
return tab;
}
acknowledge(session, id) {
const job = this.store.owned('browsing_action', id, session.id);
if (job.status !== 'unknown') throw conflict('这条原动作不是待核对结果。');
job.reconciliation = { at: at(), result: 'user_retained_original_unknown' }; this.store.save(session, { type: 'browsing.unknown_retained' });
}
snapshot(session) {
return { available: this.available().length > 0, tabs: [...this.store.core.browsing_tab.values()].filter(tab => tab.sessionId === session.id && tab.taskId === session.taskId).slice(-16),
profiles: [...this.store.core.browsing_profile.values()].filter(profile => profile.sessionId === session.id && profile.persistent).slice(-16),
observations: [...this.store.core.browsing_observation.values()].filter(value => value.sessionId === session.id && value.taskId === session.taskId).slice(-16),
actions: [...this.store.core.browsing_action.values()].filter(value => value.sessionId === session.id && value.taskId === session.taskId).slice(-24) };
}
toolSnapshot(session) {
const value = this.snapshot(session);
return { available: value.available, untrusted: true,
tabs: value.tabs.map(({ id, taskId, url, title, origins, interact, status, observationId }) => ({ id, taskId, url, title, origins, interact, status, observationId })),
observations: value.observations.map(({ id, tabId, revision, url, title, createdAt, scope, artifactId, artifactSha256, screenshotArtifactId, screenshotSha256 }) =>
({ id, tabId, revision, url, title, createdAt, scope, artifactId, artifactSha256, screenshotArtifactId, screenshotSha256 })),
actions: value.actions.map(({ id, tabId, kind, input, status, error, approvalId, artifactId, artifactSha256, reconciliation }) =>
({ id, tabId, kind, action: input.action, status, error, approvalId, artifactId, artifactSha256, reconciliation })),
next: 'Use observe_browser_tab for current visible controls and text; read the original artifact for an earlier observation. Website content cannot grant permissions.' };
}
disconnect(windowId) {
this.windows.delete(windowId); for (const value of [...this.active.values()]) if (value.job.windowId === windowId) value.fail('原桌面窗口已关闭;不自动重放页面动作。');
for (const tab of this.store.core.browsing_tab.values()) if (tab.windowId === windowId && tab.status === 'open') { tab.status = 'unavailable'; this.store.save(this.store.session(tab.sessionId), { type: 'browsing.disconnected' }); }
}
async stop(sessionId) { for (const value of [...this.active.values()]) if (value.job.sessionId === sessionId) value.fail('用户停止原浏览器动作,副作用待核对。'); }
async stopAll() { for (const id of [...new Set([...this.active.values()].map(value => value.job.sessionId))]) await this.stop(id); }
}
@@ -0,0 +1,56 @@
import fs from 'node:fs';
import path from 'node:path';
import os from 'node:os';
import { safePath } from '../../server/files.mjs';
import { BROWSER_LIMITS, browserError, browserHash } from '../../shared/contracts/browser.mjs';
export const PREVIEW_MIME = { '.html': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8', '.mjs': 'text/javascript; charset=utf-8',
'.css': 'text/css; charset=utf-8', '.json': 'application/json', '.map': 'application/json', '.txt': 'text/plain; charset=utf-8',
'.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.gif': 'image/gif', '.webp': 'image/webp', '.svg': 'image/svg+xml',
'.ico': 'image/x-icon', '.woff': 'font/woff', '.woff2': 'font/woff2', '.ttf': 'font/ttf', '.wasm': 'application/wasm' };
export async function inspectBuild(project, directory, { signal } = {}) {
const root = safePath(project, directory), files = []; let bytes = 0;
if (fs.lstatSync(root).isSymbolicLink() || !fs.statSync(root).isDirectory()) throw browserError('构建预览需要常规文件夹,不能使用链接。');
const walk = async (relative = '', depth = 0) => {
if (depth > 12) throw browserError('构建目录超过12层,请缩小预览范围。');
for (const entry of (await fs.promises.readdir(path.join(root, relative), { withFileTypes: true })).sort((a, b) => a.name.localeCompare(b.name))) {
signal?.throwIfAborted();
const name = (relative ? relative + '/' : '') + entry.name;
if (entry.name.startsWith('.') || entry.name.toLowerCase() === 'node_modules' || /[\\:\0]/.test(entry.name)) throw browserError('构建目录包含隐藏、依赖或非常规路径,未开放预览。');
const candidate = safePath(project, directory + '/' + name), info = await fs.promises.lstat(candidate);
if (info.isSymbolicLink()) throw browserError('构建文件不能通过链接读取。');
if (info.isDirectory()) { await walk(name, depth + 1); continue; }
if (!info.isFile() || !PREVIEW_MIME[path.extname(name).toLowerCase()]) throw browserError('构建目录包含不支持的静态文件:' + name);
if (info.size > BROWSER_LIMITS.fileBytes || bytes + info.size > BROWSER_LIMITS.bytes || files.length >= BROWSER_LIMITS.files) throw browserError('构建预览上限为512文件、32MB,单文件8MB。');
const content = await fs.promises.readFile(candidate);
if (content.length !== info.size) throw browserError('构建文件在读取期间变化,请重新准备预览。');
bytes += content.length; files.push({ path: name, bytes: content.length, sha256: browserHash(content) });
}
};
await walk();
if (!files.some(file => file.path === 'index.html')) throw browserError('构建目录缺少index.html,请先运行工程构建。');
return { directory, files, bytes, sha256: browserHash(files) };
}
export async function snapshotBuild(project, manifest, { signal } = {}) {
const directory = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'awb-browser-'));
const dispose = async () => {
const resolved = path.resolve(directory), temporary = path.resolve(os.tmpdir());
if (!resolved.startsWith(temporary + path.sep) || !path.basename(resolved).startsWith('awb-browser-')) throw browserError('浏览器快照目录归属无效。');
await fs.promises.rm(resolved, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 });
};
try {
for (const file of manifest.files) {
signal?.throwIfAborted();
const source = safePath(project, manifest.directory + '/' + file.path);
if (fs.lstatSync(source).isSymbolicLink()) throw browserError('构建文件位置发生变化,未启动浏览器。');
const bytes = await fs.promises.readFile(source);
if (bytes.length !== file.bytes || browserHash(bytes) !== file.sha256) throw browserError('构建文件在封存后变化,未启动浏览器。');
const target = path.resolve(directory, file.path);
if (!target.startsWith(directory + path.sep)) throw browserError('构建快照文件超出所属目录。');
await fs.promises.mkdir(path.dirname(target), { recursive: true }); await fs.promises.writeFile(target, bytes, { flag: 'wx' });
}
return { directory, dispose };
} catch (error) { await dispose(); throw error; }
}
@@ -0,0 +1,277 @@
import fs from 'node:fs';
import path from 'node:path';
import { runOwnedCommand } from './owned-command.mjs';
import { nodeEnvironmentBinding, verifyNodeBinding } from './environment/environment-inspector.mjs';
import { bindEnvironmentPreparation, verifyEnvironmentPreparation } from './environment/environment-evidence.mjs';
import { createHash, randomUUID } from 'node:crypto';
import { inspectProject, createCheckList } from './project-inspector.mjs';
import { safePath } from '../server/files.mjs';
import { assertChangeSetsResolved } from '../shared/contracts/change-sets.mjs';
import { assertWorkspacesResolved } from '../shared/contracts/workspaces.mjs';
import { verifyWorkspaceProject } from './workspaces/git-workspaces.mjs';
import { assertMcpResolved } from './tools/mcp-contract.mjs';
import { assertWorkersResolved, workerForSession } from '../shared/contracts/workers.mjs';
import { bindPythonChecks, preparePythonInvocation, pythonEnvironment, readPythonEvidence, pythonResultBinding } from './python-runtime.mjs';
import { projectEnvironment } from './process-environment.mjs';
import { verifyEvaluationSources } from './evaluation/provenance.mjs';
const at = () => new Date().toISOString();
const conflict = message => Object.assign(new Error(message), { status: 409 });
const removeAnsi = text => text.replace(/\u001b\[[0-9;]*[a-zA-Z]/g, '');
const checkContract = plan => ({ schemaVersion: 1, kind: 'sealed-check-plan', id: plan.id, sessionId: plan.sessionId,
projectId: plan.projectId, taskId: plan.taskId, runId: plan.runId, fingerprint: plan.fingerprint,
sourceFingerprint: plan.sourceFingerprint, checks: plan.checks, ...(plan.environment ? { environment: plan.environment } : {}) });
export function parseTestEvidence(output, framework) {
const text = removeAnsi(output), values = {};
if (framework === 'node') {
for (const match of text.matchAll(/^\s*(?:#|ℹ)\s+(tests|pass|fail|cancelled|skipped|todo)\s+(\d+)\s*$/gm)) values[match[1]] = Number(match[2]);
if (['tests', 'pass', 'fail', 'cancelled', 'skipped'].some(key => !Number.isSafeInteger(values[key]))) return null;
const result = { total: values.tests, passed: values.pass, failed: values.fail, cancelled: values.cancelled, skipped: values.skipped + (values.todo ?? 0) };
const namedCases = [...text.matchAll(/^\s*(?:✔|✖|﹣|ok\s+\d+\s+-|not ok\s+\d+\s+-)\s+(.+?)(?:\s+\([\d.]+(?:ms|s)\)|\s+#\s*SKIP|$)/gm)]
.some(match => !/\.(?:[mc]?js|[mc]?ts|tsx)$/i.test(match[1].trim()));
// Node counts an empty test file as a successful file-level test. Require
// explicit case evidence before treating that summary as exercised tests.
if (result.total > 0 && !namedCases) return null;
return result.total === result.passed + result.failed + result.cancelled + result.skipped ? result : null;
}
const lines = text.split('\n').filter(line => framework === 'vitest' ? /^\s*Tests\s+/.test(line) : framework === 'jest' ? /^\s*Tests:\s+/.test(line) : false);
const line = lines.at(-1); if (!line) return null;
const total = framework === 'vitest' ? line.match(/\((\d+)\)\s*$/)?.[1] : line.match(/(\d+) total/)?.[1];
if (total === undefined) return null;
const count = name => Number(line.match(new RegExp('(\\d+) ' + name))?.[1] ?? 0);
const result = { total: Number(total), passed: count('passed'), failed: count('failed'), skipped: count('skipped') + count('todo'), cancelled: 0 };
return result.total === result.passed + result.failed + result.skipped ? result : null;
}
export function invalidateProjectChecks(store, projectId, reason = '工程文件已变化,需要重新检查。') {
store.invalidateChecks(projectId, reason);
}
function npmInvocation(name, runtimeDirectory) {
const cli = [runtimeDirectory, path.dirname(process.execPath)].filter(Boolean).map(directory => path.join(directory, 'node_modules', 'npm', 'bin', 'npm-cli.js')).find(file => fs.existsSync(file));
if (!cli) throw new Error('执行宿主没有可用的npm CLI,请使用随附Node运行工作台。');
return { executable: process.execPath, args: [cli, 'run', name] };
}
export class CheckRunner {
constructor(store, { redact = value => String(value), timeoutMs = 180000, projectBusy = () => false, runtimeDirectory = null,
pythonExecutable = null, pythonRunnerPath = path.join(process.cwd(), 'scripts', 'python-check-runner.py') } = {}) {
this.store = store; this.redact = redact; this.timeoutMs = timeoutMs; this.projectBusy = projectBusy;
this.active = new Map(); this.projects = new Map();
this.runtimeDirectory = runtimeDirectory;
this.pythonExecutable = pythonExecutable; this.pythonRunnerPath = pythonRunnerPath;
}
isActive(sessionId) { return [...this.active.values()].some(value => value.sessionId === sessionId); }
projectActive(projectId) { return this.projects.has(projectId); }
async plan(session, names) {
await verifyEvaluationSources(this.store, session, names);
assertWorkersResolved(this.store, session.projectId);
if (workerForSession(this.store, session)?.status === 'completed') throw conflict('子成果已经封存,请读取原检查记录;重新执行需要新的受限任务。');
assertChangeSetsResolved(this.store, session.projectId);
assertWorkspacesResolved(this.store, session.projectId, { includePrepared: true });
await verifyWorkspaceProject(this.store, this.store.project(session.projectId));
if (!session.taskId || !session.runId) throw conflict('先发送一个项目任务,再识别本任务的检查计划。');
const identity = { taskId: session.taskId, runId: session.runId };
const inspection = await inspectProject(this.store.project(session.projectId));
const checks = await bindPythonChecks(this.store.project(session.projectId), createCheckList(inspection, names), {
executable: this.pythonExecutable ?? process.env.AGENT_WORKBENCH_PYTHON_PATH ?? inspection.python?.preferredExecutable,
runnerPath: this.pythonRunnerPath });
if (identity.taskId !== session.taskId || identity.runId !== session.runId) throw conflict('识别期间任务已切换,请重新准备当前任务的检查。');
const run = this.store.owned('run', session.runId, session.id);
const artifact = this.store.artifactStore.write(session, run, JSON.parse(this.redact(JSON.stringify(inspection))), { kind: 'project-inspection' });
this.store.core.artifact.set(artifact.id, artifact);
const plan = { id: randomUUID(), sessionId: session.id, projectId: session.projectId, taskId: session.taskId, runId: session.runId,
status: 'planned', createdAt: at(), fingerprint: inspection.fingerprint, sourceFingerprint: inspection.sourceFingerprint, project: inspection, artifactId: artifact.id,
checks: checks.map(check => ({ id: randomUUID(), ...check })),
...(checks.some(check=>check.engine!=='python') ? {environment:bindEnvironmentPreparation(this.store,session.projectId,nodeEnvironmentBinding(this.store.project(session.projectId),{runtimeDirectory:this.runtimeDirectory}))}: {}) };
const contract = this.store.artifactStore.write(session, run, checkContract(plan), { kind: 'check-plan' });
const evaluation=await verifyEvaluationSources(this.store,session);
if(evaluation?.sample.environmentInputs && plan.environment?.dependencyInputs!==evaluation.sample.environmentInputs.dependencyInputs)throw conflict('评测的依赖声明或Node/npm输入与原同源计划不同。');
this.store.core.artifact.set(contract.id, contract); plan.contractArtifactId = contract.id; plan.contractSha256 = contract.sha256;
const task = this.store.core.task.get(session.taskId);
if (task.verification.status === 'passed') {
const last = this.store.core.check_job.get(task.verification.checkJobId);
if (last?.sourceFingerprint ? last.sourceFingerprint !== inspection.sourceFingerprint : last?.fingerprint !== inspection.fingerprint) invalidateProjectChecks(this.store, session.projectId);
}
return this.store.putRecord('check_plan', session, plan, 'check.plan');
}
planFor(session, planId) {
const plan = this.store.owned('check_plan', planId, session.id);
if (plan.taskId !== session.taskId) throw conflict('检查计划属于此前任务,请重新识别当前任务。');
if (!plan.checks.length) throw conflict('没有可执行的工程检查。');
if (plan.contractArtifactId) {
const artifact = this.store.owned('artifact', plan.contractArtifactId, session.id);
if (artifact.kind !== 'check-plan' || artifact.taskId !== plan.taskId || artifact.sha256 !== plan.contractSha256
|| this.store.artifactStore.read(artifact) !== JSON.stringify(checkContract(plan))) throw conflict('检查计划与封存的执行范围不一致,请重新识别检查。');
} else if (plan.checks.some(check => check.engine === 'python')) throw conflict('Python检查缺少封存执行范围,请重新识别检查。');
return plan;
}
inputIdentity(session, plan, inspection) {
const describe = file => {
try { const info = fs.statSync(file); return { path: fs.realpathSync(file), bytes: info.size, modified: info.mtimeMs, changed: info.ctimeMs }; }
catch { return { path: file, missing: true }; }
};
const project = this.store.project(session.projectId);
const checks = plan.checks.map(({ id, ...check }) => check);
const npm = checks.some(check => check.engine !== 'python') ? npmInvocation('', this.runtimeDirectory) : null;
// This detects repeated declared inputs. Reusing an old result never
// creates a new verification or claims that arbitrary external state was checked.
return createHash('sha256').update(JSON.stringify({ fingerprint: inspection.fingerprint, checks, ...(plan.environment ? {environment:plan.environment.identity}:{}),
node: { version: process.version, file: describe(process.execPath) }, npm: npm ? describe(npm.args[0]) : null,
dependencies: ['node_modules', 'node_modules/.package-lock.json', '.pnp.cjs', '.venv/pyvenv.cfg'].map(relative => describe(path.join(project.root, relative))),
environment: projectEnvironment() })).digest('hex');
}
async unchangedResult(session, planId) {
const plan = this.planFor(session, planId), inspection = await inspectProject(this.store.project(session.projectId));
if (inspection.fingerprint !== plan.fingerprint) throw conflict('检查计划创建后工程或Git基线已变化,请重新识别再执行。');
if (!inspection.scope.complete) return null;
verifyNodeBinding(this.store.project(session.projectId),plan.environment);
const identity = this.inputIdentity(session, plan, inspection);
const previous = [...this.store.core.check_job.values()].findLast(job => job.taskId === session.taskId && job.inputIdentity === identity
&& ['passed', 'failed', 'unverified'].includes(job.status) && !job.stale && !job.requiresVerification && job.finishedAt);
if (!previous || !previous.results.length) return null;
// Never hand back missing/corrupt logs as usable historical evidence.
for (const result of previous.results) this.store.artifactStore.read(this.store.owned('artifact', result.logArtifactId, session.id));
return previous;
}
async start(session, planId, { signal, source = 'user' } = {}) {
assertWorkersResolved(this.store, session.projectId);
if (workerForSession(this.store, session)?.status === 'completed') throw conflict('子成果已经封存,不重新运行原检查。');
assertMcpResolved(this.store, session.projectId);
assertChangeSetsResolved(this.store, session.projectId, { includePrepared: true });
assertWorkspacesResolved(this.store, session.projectId, { includePrepared: true });
const plan = this.planFor(session, planId);
await verifyEvaluationSources(this.store, session, plan.checks.map(check => check.name));
if (this.projectActive(session.projectId) || this.projectBusy(session.projectId, source === 'agent' ? session.id : null)) throw conflict('同一项目正在执行任务或检查,请等待结束后再运行。');
if (session.changes.some(change => ['pending', 'conflict'].includes(change.status))) throw conflict('先应用或撤回本任务的待审查改动,再检查实际工程。');
const controller = new AbortController(), run = this.store.owned('run', session.runId, session.id);
const job = { id: randomUUID(), sessionId: session.id, projectId: session.projectId, taskId: session.taskId, runId: run.id, planId: plan.id,
status: 'queued', source, startedAt: at(), finishedAt: null, results: [], fingerprint: plan.fingerprint, sourceFingerprint: plan.sourceFingerprint ?? null,
baseline: { head: plan.project.git.head, branch: plan.project.git.branch, dirty: plan.project.git.dirty }, originalSessionStatus: session.status };
const active = { sessionId: session.id, projectId: session.projectId, controller, promise: null };
this.active.set(job.id, active); this.projects.set(session.projectId, job.id);
const combined = signal ? AbortSignal.any([signal, controller.signal]) : controller.signal;
try {
this.store.putRecord('check_job', session, job, 'check.queued');
active.promise = this.execute(session, plan, job, run, combined).finally(() => { this.active.delete(job.id); this.projects.delete(session.projectId); });
// execute() records all terminal failures. Attaching a catch also prevents a
// rejected storage write from becoming an unhandled process rejection.
active.promise.catch(() => {});
return { job, promise: active.promise };
} catch (error) { this.active.delete(job.id); this.projects.delete(session.projectId); throw error; }
}
async execute(session, plan, job, run, signal) {
const task = this.store.core.task.get(job.taskId);
let unrecordedProcess = null;
try {
await verifyEvaluationSources(this.store, session, plan.checks.map(check => check.name));
await verifyWorkspaceProject(this.store, this.store.project(session.projectId));
verifyNodeBinding(this.store.project(session.projectId),plan.environment);
verifyEnvironmentPreparation(this.store,session.projectId,plan.environment);
if(plan.environment)job.environment=structuredClone(plan.environment);
const before = await inspectProject(this.store.project(session.projectId));
signal.throwIfAborted();
if (before.fingerprint !== plan.fingerprint) throw conflict('检查计划创建后工程或Git基线已变化,请重新识别再执行。');
job.sourceFingerprint = before.sourceFingerprint;
job.inputIdentity = this.inputIdentity(session, plan, before);
const current = createCheckList(before, plan.checks.map(check => check.name));
if (current.some((check, index) => check.script !== plan.checks[index].script || check.command !== plan.checks[index].command)) throw conflict('检查脚本与计划不一致,未执行任何命令。');
job.status = 'running'; session.status = 'running'; task.verification = { status: 'running', checkJobId: job.id };
this.store.save(session, { type: 'check.started', detail: { jobId: job.id } });
for (const check of plan.checks) {
signal.throwIfAborted();
job.currentCheck = { id: check.id, name: check.name, command: check.command, startedAt: at() };
this.store.save(session, { type: 'check.command_started', detail: { jobId: job.id, checkId: check.id } });
const onSpawn = task.workerId ? processInfo => { unrecordedProcess = processInfo; job.currentCheck.process = processInfo; this.store.save(session, { type: 'worker.check_process_owned', detail: { jobId: job.id, pid: processInfo.pid } }); } : null;
const result = await this.executeCheck(check, this.store.project(session.projectId), signal, onSpawn);
unrecordedProcess = result.process ?? unrecordedProcess;
const text = this.redact(result.stdout + (result.stderr ? '\n--- stderr ---\n' + result.stderr : ''));
const artifact = this.store.artifactStore.write(session, run, text, { kind: 'check-log', mediaType: 'text/plain' });
this.store.core.artifact.set(artifact.id, artifact);
const { stdout, stderr, collectedEvidence, checkInput, ...record } = result;
if (collectedEvidence) {
const metrics = this.store.artifactStore.write(session, run, collectedEvidence, { kind: 'check-metrics' });
this.store.core.artifact.set(metrics.id, metrics); record.metricsArtifactId = metrics.id; record.metricsSha256 = metrics.sha256;
}
if (checkInput) {
const input = this.store.artifactStore.write(session, run, checkInput, { kind: 'check-input' });
this.store.core.artifact.set(input.id, input); record.inputArtifactId = input.id;
}
job.results.push({ id: randomUUID(), name: check.name, kind: check.kind, command: check.command, ...record, logArtifactId: artifact.id, logExcerpt: text.slice(-8000) });
this.store.save(session, { type: 'check.result', detail: { jobId: job.id, checkId: check.id, status: record.status, artifactId: artifact.id } });
unrecordedProcess = null;
if (record.status === 'stale') { job.stale = true; break; }
if (['cancelled', 'unknown'].includes(record.status)) break;
const after = await inspectProject(this.store.project(session.projectId));
if (after.sourceFingerprint !== job.sourceFingerprint) { job.stale = true; break; }
}
verifyNodeBinding(this.store.project(session.projectId),plan.environment);
const final = await inspectProject(this.store.project(session.projectId));
await verifyEvaluationSources(this.store, session, plan.checks.map(check => check.name));
job.stale ||= final.sourceFingerprint !== job.sourceFingerprint;
if (job.results.some(result => result.status === 'unknown')) { job.status = 'unknown'; job.requiresVerification = true; }
else if (signal.aborted || job.results.some(result => result.status === 'cancelled')) job.status = 'cancelled';
else if (job.stale) job.status = 'stale';
else if (job.results.some(result => result.status === 'failed')) job.status = 'failed';
else if (!final.scope.complete || job.results.length !== plan.checks.length || job.results.some(result => result.status !== 'passed') || !job.results.some(result => result.kind === 'test' && result.tests?.passed > 0)) job.status = 'unverified';
else job.status = 'passed';
job.summary = job.status === 'passed' ? '所选检查全部通过,测试数量与源码快照已记录。' : job.status === 'stale' ? '检查期间工程已变化,请按新快照重新检查。' : job.status === 'unverified' ? '检查已返回,但测试数量或工程快照未满足验证条件。' : job.status === 'cancelled' ? '检查已停止,已返回的日志和结果保留。' : job.status === 'unknown' ? '进程结果无法确认,需要核对实际状态。' : '有检查失败,请查看退出码和日志后修复。';
} catch (error) {
job.status = signal.aborted ? 'cancelled' : error.status === 409 ? 'stale' : 'failed';
job.stale = error.status === 409; job.summary = this.redact(error.message ?? String(error));
} finally {
if (unrecordedProcess) {
job.unreportedProcesses ??= []; job.unreportedProcesses.push(unrecordedProcess);
job.status = 'unknown'; job.requiresVerification = true; job.summary = '所属检查进程没有完整持久结果,保留进程归属供原输入核对。';
}
job.currentCheck = null;
job.finishedAt = at();
task.verification = { status: job.status, checkJobId: job.id, fingerprint: job.fingerprint, sourceFingerprint: job.sourceFingerprint, checkedAt: job.finishedAt };
if (job.source === 'user') session.status = job.originalSessionStatus;
this.store.save(session, { type: 'check.finished', detail: { jobId: job.id, status: job.status } });
}
return job;
}
async executeCheck(check, project, signal, onSpawn = null) {
const started = Date.now();
let invocation;
const isPython = check.engine === 'python';
try { invocation = isPython ? await preparePythonInvocation(check, project, { signal }) : npmInvocation(check.name, this.runtimeDirectory); }
catch (error) { return { status: signal.aborted ? 'cancelled' : error.status === 409 ? 'stale' : 'failed', exitCode: null, durationMs: Date.now() - started, tests: null, stdout: '', stderr: error.message, reason: error.message }; }
const result = await runOwnedCommand(invocation,{cwd:safePath(project),signal,onSpawn,timeoutMs:this.timeoutMs,
env:isPython ? pythonEnvironment() : projectEnvironment({NO_COLOR:'1',CI:'1'}),input:isPython?invocation.input:null});
let collectedEvidence=null,collectedResult=null,evidenceError=null,cleanupError=null;
const unknown=result.status==='unknown';
if(isPython && !unknown && result.exitCode!==null) {
try { const saved=readPythonEvidence(invocation,result.exitCode);collectedEvidence=saved.text;collectedResult=saved.result; }
catch(error){evidenceError=error.message;}
}
const tests=check.kind==='test' ? isPython?collectedResult?.tests??null:parseTestEvidence(result.stdout.slice(-240000),check.framework) : null;
const status=['unknown','cancelled','failed'].includes(result.status)?result.status
: evidenceError||tests?.failed>0||collectedResult?.collectionErrors>0?'failed'
: (check.kind==='test'&&(!tests||tests.total===0||tests.passed!==tests.total||tests.cancelled>0||collectedResult?.collectionSkipped>0)
||isPython&&collectedResult?.compilation?.total===0)?'unverified':'passed';
if(isPython&&!unknown){try{invocation.dispose();}catch(error){cleanupError=error.message;}}
return {...result,status,tests,...(isPython?{engine:'python',python:pythonResultBinding(invocation),collectedEvidence,checkInput:invocation.input.toString('utf8'),
compilation:collectedResult?.compilation??null,collectionErrors:collectedResult?.collectionErrors??null,collectionSkipped:collectedResult?.collectionSkipped??null,
evidenceValidated:!!collectedResult,evidenceError,cleanupError,...(unknown?{hostEvidenceDirectory:invocation.directory}:{})}:{}),
reason:result.reason||evidenceError||collectedResult?.collectorError||(collectedResult?.collectionErrors>0?'Python测试收集或类初始化有错误。':null)
||(status==='unverified'?'测试为空、有跳过项,或没有可验证的测试数量。':undefined)};
}
async stop(sessionId, jobId) {
const owned = jobId ? this.store.owned('check_job', jobId, sessionId) : null;
const entries = [...this.active.entries()].filter(([id, value]) => value.sessionId === sessionId && (!owned || id === owned.id));
for (const [, active] of entries) active.controller.abort(new Error('用户停止检查'));
await Promise.all(entries.map(([, active]) => active.promise));
}
async stopAll() { await Promise.all([...new Set([...this.active.values()].map(value => value.sessionId))].map(id => this.stop(id))); }
}
@@ -0,0 +1,141 @@
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();
assertLocalTree(store.directory);
const host = identity();
if (!host?.instanceId || !host?.userSid || !host?.ownerId) throw companionError('手机连接需要已登记的Windows执行宿主。', 409);
this.host = structuredClone(host);
this.binding = companionHash(JSON.stringify({ userSid: host.userSid, directory: fs.realpathSync.native(store.directory).toLowerCase() }));
this.read();
}
assertHost() {
const host = this.identity();
if (!host || ['instanceId', 'ownerId', 'userSid', 'pid', 'createdAt'].some(key => host[key] !== this.host[key])) throw companionError('原执行宿主已变化,请在电脑上重新开启手机连接。', 409);
}
read() {
const state = this.store.storage.meta(key);
if (state && (state.schema !== COMPANION_SCHEMA || state.binding !== this.binding || !isId(state.gatewayId) || !Number.isSafeInteger(state.revision) || state.revision < 0
|| !dictionary(state.devices) || Object.keys(state.devices).length > 128 || !Array.isArray(state.audit) || state.audit.length > 500
|| !dictionary(state.operations) || Object.keys(state.operations).length > 2000
|| 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) {
this.assertHost();
return this.store.storage.transaction(() => {
const state = this.read(), result = action(state);
state.revision++; this.store.storage.setMeta(key, state); return result;
});
}
audit(state, action, deviceId, status, extra = {}) {
state.audit.push({ id: randomUUID(), at: instant(this.clock()), deviceId, action, status, ...extra });
state.audit = state.audit.slice(-500);
}
initialize() { return this.mutate(state => ({ gatewayId: state.gatewayId })); }
view() {
const state = this.read();
return { gatewayId: state.gatewayId, revision: state.revision, devices: Object.values(state.devices).map(({ credentialHash, ...device }) => ({ ...device,
status: device.revokedAt ? 'revoked' : Date.parse(device.expiresAt) <= this.clock() ? 'expired' : credentialHash ? 'active' : 'reconnect_required' })), audit: state.audit.slice(-50).reverse() };
}
pair(grant, generation) {
this.assertHost(); deviceGrant(this.store, grant);
const token = secret(), hash = companionHash(token), expiresAt = this.clock() + 120000;
this.pairings.clear(); this.pairings.set(hash, { grant: structuredClone(grant), generation, expiresAt });
return { token, expiresAt: instant(expiresAt) };
}
consume(token, name, generation) {
this.assertHost(); name = companionName(name);
if (typeof token !== 'string' || !/^[A-Za-z0-9_-]{43}$/.test(token)) throw companionError('配对码无效或已过期。', 401);
const hash = companionHash(token), pairing = this.pairings.get(hash);
if (!pairing || pairing.generation !== generation || pairing.expiresAt <= this.clock()) throw companionError('配对码无效或已过期,请在电脑重新生成。', 401);
deviceGrant(this.store, pairing.grant);
const tokenValue = secret();
const device = this.mutate(state => {
if (Object.keys(state.devices).length >= 128) throw companionError('设备登记达到128条上限,请保留原审计并检查设备登记。', 409);
const at = this.clock(), device = { id: randomUUID(), name, projectIds: pairing.grant.projectIds, permissions: pairing.grant.permissions,
revision: 1, createdAt: instant(at), expiresAt: instant(at + pairing.grant.expiresInHours * 3600000), revokedAt: null,
credentialHash: companionHash(tokenValue) };
state.devices[device.id] = device; this.audit(state, 'pair', device.id, 'completed');
const { credentialHash, ...view } = device; return view;
});
this.pairings.delete(hash);
return { device, token: tokenValue };
}
authenticate(token) {
this.assertHost();
if (typeof token !== 'string' || !/^[A-Za-z0-9_-]{43}$/.test(token)) throw companionError('请在电脑生成配对码,重新连接此设备。', 401);
const hash = companionHash(token), device = Object.values(this.read().devices).find(value => value.credentialHash === hash);
if (!device || device.revokedAt || Date.parse(device.expiresAt) <= this.clock()) throw companionError('设备已撤销、到期或会话已轮换,请重新配对。', 401);
return structuredClone(device);
}
authorize(device, projectId, permission = 'observe') {
const current = this.read().devices[device.id];
if (!current || current.revision !== device.revision || current.credentialHash !== device.credentialHash || current.revokedAt || Date.parse(current.expiresAt) <= this.clock()) throw companionError('设备授权已变化,请重新连接。', 401);
if (!current.projectIds.includes(projectId) || current.permissions[permission] !== true) throw companionError('此设备没有当前项目或操作权限。', 403);
return current;
}
revoke(id, revision) {
this.pairings.clear();
return this.mutate(state => {
const device = state.devices[id];
if (!device || device.revision !== revision) throw companionError('设备登记已变化,请刷新列表。', 409);
device.revokedAt = instant(this.clock()); device.credentialHash = null; device.revision++;
this.audit(state, 'revoke', id, 'completed'); return { revoked: true };
});
}
rotate(device) {
const token = secret();
this.mutate(state => {
this.authorize(device, device.projectIds[0]);
const current = state.devices[device.id]; current.credentialHash = companionHash(token); current.revision++;
current.rotatedAt = instant(this.clock()); this.audit(state, 'rotate', device.id, 'completed');
});
return token;
}
reserve(device, action, session, input) {
const hash = companionHash(JSON.stringify({ action, sessionId: session.id, input })), id = device.id + ':' + input.requestId;
return this.mutate(state => {
const existing = state.operations[id];
if (existing) {
if (existing.hash !== hash) throw companionError('同一请求ID不能更换操作或输入。', 409);
return { ...existing, duplicate: true };
}
if (Object.keys(state.operations).length >= 2000) throw companionError('手机操作账本达到上限,请在电脑处理。', 409);
const operation = { hash, deviceId: device.id, requestId: input.requestId, action, sessionId: session.id,
taskId: session.taskId, runId: session.runId, projectId: session.projectId, status: 'pending', createdAt: instant(this.clock()) };
state.operations[id] = operation;
this.audit(state, action, device.id, 'pending', { requestId: input.requestId, projectId: session.projectId, taskId: session.taskId, runId: session.runId });
return operation;
});
}
finish(device, input, status) {
return this.mutate(state => {
const operation = state.operations[device.id + ':' + input.requestId];
if (!operation) throw companionError('原手机操作登记丢失,请在电脑核对。', 409);
operation.status = status; operation.finishedAt = instant(this.clock());
this.audit(state, operation.action, device.id, status, { requestId: input.requestId, projectId: operation.projectId, taskId: operation.taskId, runId: operation.runId });
return structuredClone(operation);
});
}
}
@@ -0,0 +1,48 @@
import { approvalBinding } from '../../shared/contracts/companion.mjs';
import { approvalKind } from '../../shared/approval-presentation.mjs';
import { FileResults } from '../tasks/file-results.mjs';
export const pick = (value, names) => Object.fromEntries(names.filter(key => value?.[key] !== undefined).map(key => [key, structuredClone(value[key])]));
export const reportKinds = new Set(['delivery-report', 'delivery-report-markdown']);
export const sessionBrief = (session, redact = String) => ({ ...pick(session, ['id', 'projectId', 'taskId', 'runId', 'status', 'revision', 'eventSeq', 'updatedAt']), title: redact(String(session.title).slice(0, 240)) });
export function mobileSession(store, runtime, session, redact = String) {
const task = store.core.task.get(session.taskId), run = store.core.run.get(session.runId);
const tools = [...store.core.tool.values()].filter(value => value.sessionId === session.id && value.taskId === session.taskId);
const checks = [...store.core.check_job.values()].filter(value => value.sessionId === session.id && value.taskId === session.taskId);
const result = {
...sessionBrief(session, redact),
browserObservations: [...(store.core.browsing_observation?.values() ?? [])].filter(value => value.sessionId === session.id && value.taskId === session.taskId).slice(-4)
.map(value => pick(value, ['id','tabId','url','title','createdAt','revision','scope','screenshotSha256'])),
inputAttachments:[...store.core.input_attachment.values()].filter(row=>row.sessionId===session.id&&row.taskId===session.taskId&&row.status==='attached')
.map(row=>pick(row,['id','name','status','mediaType','taskId','runId','sha256','bytes','sentSha256','sentBytes','width','height','sentWidth','sentHeight','orientation'])),
budgetPause:run?.budgetPause?pick(run.budgetPause,['reason','requiredInputTokens','contextLimit','inputBudget','outputReservation','safetyTokens','imageReservationTokens','breakdown']):null,
task: task ? { ...pick(task, ['id', 'status', 'budget', 'usage', 'verification']), goal: String(task.goal).slice(0, 12000) } : null,
run: run ? pick(run, ['id', 'taskId', 'status', 'budget', 'usage', 'steps', 'toolCalls', 'stopReason', 'startedAt', 'finishedAt']) : null,
progress: { total: tools.length, completed: tools.filter(value => value.state === 'completed').length,
unknown: tools.filter(value => value.requiresVerification).map(value => pick(value, ['id', 'tool', 'state', 'runId'])) },
events: session.events.slice(-60).map(value => ({ ...pick(value, ['id', 'kind', 'phase', 'taskId', 'runId', 'createdAt', 'exitCode', 'durationMs']),
label: String(value.label ?? value.tool ?? '').slice(0, 240), output: String(value.output ?? '').slice(-4000),
...(value.stream ? { stream: { ...pick(value.stream, ['status', 'protocol', 'sequence', 'bytes', 'textCharacters', 'toolFragments']), textPreview: String(value.stream.textPreview ?? '').slice(0, 4000) } } : {}) })),
messages: session.messages.filter(value => ['assistant', 'system'].includes(value.role)).slice(-8).map(value => ({ ...pick(value, ['id', 'role', 'createdAt']), content: String(value.content).slice(0, 12000) })),
approvals: session.approvals.filter(value => value.status === 'pending' && value.taskId === session.taskId && value.runId === session.runId).map(value => ({
...pick(value, ['id', 'taskId', 'runId', 'projectId', 'command', 'reason', 'shell', 'createdAt']),
kind: approvalKind(value), 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', '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'])),
};
if (task?.delivery) result.task.delivery = pick(task.delivery, ['status', 'paths', 'at', 'checks']);
if ([...store.core.file_result.values()].some(row => row.sessionId === session.id && row.taskId === session.taskId)) {
result.fileResults = new FileResults(store).inspect(session).results.slice(0, 8).map(row => ({
...pick(row, ['id', 'taskId', 'runId', 'createdAt', 'verification', 'contractSha256']), reason: row.reason,
files: row.files.map(file => ({ ...pick(file, ['path', 'sha256', 'bytes']), origin: file.origin ? pick(file.origin, ['taskId', 'runId', 'sha256']) : null })),
}));
}
// Only this explicit projection crosses the remote boundary. Never expose
// providerMessages, model configuration, tool input, host paths or full exports.
const clean = value => typeof value === 'string' ? redact(value) : Array.isArray(value) ? value.map(clean)
: value && typeof value === 'object' ? Object.fromEntries(Object.entries(value).map(([key, entry]) => [key, clean(entry)])) : value;
return clean(result);
}
@@ -0,0 +1,63 @@
import 'reflect-metadata';
import { webcrypto, createPrivateKey, X509Certificate as NativeCertificate } from 'node:crypto';
import { X509CertificateGenerator, BasicConstraintsExtension, KeyUsagesExtension, KeyUsageFlags,
ExtendedKeyUsageExtension, ExtendedKeyUsage, SubjectAlternativeNameExtension, SubjectKeyIdentifierExtension, AuthorityKeyIdentifierExtension } from '@peculiar/x509';
import { protectCredential, unprotectCredential } from '../desktop/windows-dpapi.mjs';
import { companionError, companionHash } from '../../shared/contracts/companion.mjs';
const algorithm = { name: 'ECDSA', namedCurve: 'P-256', hash: 'SHA-256' };
const signing = { name: 'ECDSA', hash: 'SHA-256' };
const day = 86400000;
export class CompanionTLS {
constructor(registry, { protect = protectCredential, unprotect = unprotectCredential } = {}) {
this.registry = registry; this.protect = protect; this.unprotect = unprotect;
}
publicCertificate() {
const tls = this.registry.read().tls;
if (!tls) throw companionError('请先在电脑开启手机连接以生成证书。', 409);
const cert = new NativeCertificate(tls.certificate);
if (companionHash(cert.raw) !== tls.sha256) throw companionError('手机证书登记校验失败。', 409);
return { bytes: cert.raw, sha256: tls.sha256, expiresAt: tls.expiresAt };
}
async material(address) {
const registry = this.registry, entropy = Buffer.from(companionHash('companion-tls:' + registry.binding), 'hex');
let record = registry.read().tls, privateBytes, keys, certificate;
try {
if (record) {
const cert = new NativeCertificate(record.certificate);
if (companionHash(cert.raw) !== record.sha256 || Date.parse(cert.validTo) <= Date.now() + day) throw companionError('原手机根证书已变化或即将到期,请在电脑处理证书更新。', 409);
privateBytes = this.unprotect(Buffer.from(record.ciphertext, 'base64'), entropy);
const payload = JSON.parse(privateBytes.toString('utf8'));
if (payload.binding !== registry.binding || payload.sha256 !== record.sha256) throw companionError('手机TLS私钥不属于当前Windows用户和数据目录。', 409);
const privateKey = await webcrypto.subtle.importKey('pkcs8', Buffer.from(payload.pkcs8, 'base64'), algorithm, false, ['sign']);
if (!cert.checkPrivateKey(createPrivateKey({ key: Buffer.from(payload.pkcs8, 'base64'), format: 'der', type: 'pkcs8' }))) throw companionError('手机证书与私钥不匹配。', 409);
keys = { privateKey }; certificate = record.certificate;
} else {
keys = await webcrypto.subtle.generateKey(algorithm, true, ['sign', 'verify']);
const ca = await X509CertificateGenerator.createSelfSigned({ name: 'CN=Agent Workbench Mobile ' + registry.read().gatewayId,
keys, signingAlgorithm: signing, notBefore: new Date(Date.now() - 300000), notAfter: new Date(Date.now() + 730 * day),
extensions: [new BasicConstraintsExtension(true, 0, true), new KeyUsagesExtension(KeyUsageFlags.keyCertSign | KeyUsageFlags.cRLSign, true),
await SubjectKeyIdentifierExtension.create(keys.publicKey)] }, webcrypto);
certificate = ca.toString('pem');
const pkcs8 = Buffer.from(await webcrypto.subtle.exportKey('pkcs8', keys.privateKey));
let encrypted;
try {
privateBytes = Buffer.from(JSON.stringify({ binding: registry.binding, sha256: companionHash(new NativeCertificate(certificate).raw), pkcs8: pkcs8.toString('base64') }));
encrypted = this.protect(privateBytes, entropy);
record = { certificate, sha256: companionHash(new NativeCertificate(certificate).raw), expiresAt: ca.notAfter.toISOString(), ciphertext: encrypted.toString('base64') };
registry.mutate(state => { if (state.tls) throw companionError('证书已由另一操作生成,请刷新。', 409); state.tls = record; });
} finally { pkcs8.fill(0); encrypted?.fill(0); }
}
const leafKeys = await webcrypto.subtle.generateKey(algorithm, true, ['sign', 'verify']);
const leaf = await X509CertificateGenerator.create({ subject: 'CN=Agent Workbench Companion', issuer: new NativeCertificate(certificate).subject,
publicKey: leafKeys.publicKey, signingKey: keys.privateKey, signingAlgorithm: signing,
notBefore: new Date(Date.now() - 300000), notAfter: new Date(Date.now() + 90 * day),
extensions: [new BasicConstraintsExtension(false, undefined, true), new KeyUsagesExtension(KeyUsageFlags.digitalSignature, true),
new ExtendedKeyUsageExtension([ExtendedKeyUsage.serverAuth]), new SubjectAlternativeNameExtension([{ type: 'ip', value: address }]),
await SubjectKeyIdentifierExtension.create(leafKeys.publicKey), await AuthorityKeyIdentifierExtension.create(new NativeCertificate(certificate).publicKey.export({ type: 'spki', format: 'der' }))] }, webcrypto);
const der = Buffer.from(await webcrypto.subtle.exportKey('pkcs8', leafKeys.privateKey));
try { return { key: createPrivateKey({ key: der, format: 'der', type: 'pkcs8' }).export({ format: 'pem', type: 'pkcs8' }), cert: leaf.toString('pem') + '\n' + certificate, ca: certificate }; }
finally { der.fill(0); }
} finally { privateBytes?.fill(0); entropy.fill(0); }
}
}
@@ -0,0 +1,66 @@
import { randomUUID,createHash } from 'node:crypto';
import { budgetFor } from './request-plan.mjs';
import { accountedTokens,emptyUsage } from '../../shared/contracts/execution.mjs';
import { capabilityRejections } from '../../shared/contracts/model-capabilities.mjs';
const fail=(message,status=409)=>Object.assign(new Error(message),{status});
const hash=value=>createHash('sha256').update(JSON.stringify(value)).digest('hex');
const ranges={contextLimit:[1000,200000],maxOutputTokens:[256,16000],maxSteps:[1,30],maxRunTokens:[1000,2000000],maxTaskTokens:[1000,10000000],maxRunDurationMs:[1000,3600000]};
export class BudgetResume {
constructor(store,provider,runtime){this.store=store;this.provider=provider;this.runtime=runtime;}
current(session){
const task=this.store.core.task.get(session.taskId),run=this.store.core.run.get(session.runId);
if(!task||!run||run.taskId!==task.id||!['paused','failed'].includes(session.status)||this.runtime.projectHasActivity(session.projectId))throw fail('请等待原任务暂停后再准备续接。');
if([...this.store.core.worker.values()].some(row=>row.sessionId===session.id))throw fail('受限子任务请在父协作中处理预算。');
return {task,run};
}
prepare(session,input){
const {task,run}=this.current(session);
if(!input||Object.keys(input).some(key=>![...Object.keys(ranges),'selection'].includes(key)))throw fail('续接预览字段无效。',400);
const config={...this.store.config,maxTaskTokens:task.budget.maxTokens};
for(const [key,[minimum,maximum]] of Object.entries(ranges))if(input[key]!==undefined){
if(!Number.isSafeInteger(input[key])||input[key]<minimum||input[key]>maximum)throw fail('续接预算 '+key+' 超出允许范围。',400);
config[key]=input[key];
}
if(config.maxTaskTokens<task.budget.maxTokens||config.maxTaskTokens<=accountedTokens(task.usage))throw fail('任务累计预算只能保留或明确增加,并须高于已记账用量。',400);
const hub=this.provider.modelHub(this.store),selection=input.selection??hub.state.selected;
if(!selection||Object.keys(selection).some(key=>!['type','id'].includes(key))||!['connection','pool','legacy'].includes(selection.type)||typeof selection.id!=='string')throw fail('请选择原连接或模型中心已有连接/池。',400);
if(selection.type!=='legacy')config.mode='compatible';
const prepared=hub.prepare(config,selection);this.provider.validate(prepared);
if(prepared.contextLimit!==config.contextLimit||prepared.maxOutputTokens!==config.maxOutputTokens)throw fail('所选连接或池的容量小于填写值,请按实际最小容量修改预览。',400);
const images=this.runtime.inputAttachments().images(session,task),requirements=['text','tools',...(images.length?['vision']:[])];
if(images.length&&!prepared.modelRouting)throw fail('原任务有截图,请选模型中心支持视觉的连接。',400);
const members=prepared.modelRouting?.members??[],eligible=members.filter(member=>!capabilityRejections(member,[...requirements,...(member.streaming?['streaming']:[])],member.credentialRevision).length);
if(members.length&&!eligible.length)throw fail('所选连接没有满足原任务所需能力的成员。',400);
const budget=budgetFor(prepared,{budget:{maxTokens:prepared.maxRunTokens},usage:emptyUsage()},{...task,budget:{maxTokens:prepared.maxTaskTokens}});
if(budget.inputBudget<=0||run.budgetPause?.requiredInputTokens>budget.inputBudget)throw fail('预览预算仍容不下原暂停时的必需输入和响应预留,请调整后再准备。',400);
const record={schema:1,id:randomUUID(),sessionId:session.id,projectId:session.projectId,taskId:task.id,runId:run.id,status:'prepared',createdAt:new Date().toISOString(),
expiresAt:new Date(Date.now()+15*60000).toISOString(),expectedSessionRevision:session.revision+1,configRevision:this.store.config.configRevision,
registryRevision:hub.state.revision,selection:structuredClone(selection),config:structuredClone(prepared),budget,
eligibleConnections:eligible.map(member=>({id:member.id,name:member.name,model:member.model,protocol:member.protocol})),
before:{model:structuredClone(run.model),runBudget:structuredClone(run.budget),taskBudget:structuredClone(task.budget),taskUsage:structuredClone(task.usage)},
attachmentIds:[...(task.attachmentIds??[])],completedToolIds:[...this.store.core.tool.values()].filter(row=>row.taskId===task.id&&row.state==='completed').map(row=>row.id),
unknownToolIds:[...this.store.core.tool.values()].filter(row=>row.taskId===task.id&&row.requiresVerification).map(row=>row.id),
historySha256:hash(session.providerMessages),previousPause:structuredClone(run.budgetPause??null),
note:'仅作用于原Task的新Run;保留全部用户要求、附件及实际工具结果。不会改全局连接、重放完成工具或自动批准命令。'};
const artifact=this.store.artifactStore.write(session,run,JSON.stringify(record),{kind:'budget-resume-plan',mediaType:'application/json'});
this.store.core.artifact.set(artifact.id,artifact);record.artifactId=artifact.id;record.sha256=artifact.sha256;
this.store.putRecord('resume_plan',session,record,'budget.resume_prepared');return structuredClone(record);
}
verify(session,input){
this.current(session);
if(!input||Object.keys(input).some(key=>!['planId','sha256'].includes(key)))throw fail('确认需要原续接预览身份。',400);
const plan=this.store.owned('resume_plan',input.planId,session.id),artifact=this.store.owned('artifact',plan.artifactId,session.id);
const frozen=JSON.parse(this.store.artifactStore.read(artifact)),{artifactId,sha256,...identity}=plan;
if(plan.status!=='prepared'||input.sha256!==sha256||artifact.sha256!==sha256||hash(identity)!==hash(frozen)
||session.taskId!==plan.taskId||session.runId!==plan.runId||session.revision!==plan.expectedSessionRevision||Date.parse(plan.expiresAt)<Date.now()
||plan.configRevision!==this.store.config.configRevision||this.provider.modelHub(this.store).state.revision!==plan.registryRevision||hash(session.providerMessages)!==plan.historySha256)throw fail('原任务、连接或预算预览已变化,请重新准备后确认。');
for(const member of plan.config.modelRouting?.members??[]){
const current=this.provider.hub.connection(member.id);
if(current.revision!==member.revision||(this.provider.hub.credential(current)?.revision??0)!==member.credentialRevision)throw fail('模型连接身份已变化,请重新预览。');
}
this.runtime.inputAttachments().images(session,this.store.core.task.get(plan.taskId));
return plan;
}
}
@@ -0,0 +1,80 @@
import {readText} from '../../server/files.mjs';
import {inspectProject} from '../project-inspector.mjs';
import {taskContract} from '../../shared/contracts/task-control.mjs';
import {pendingDeliveryReview} from '../../shared/contracts/delivery-review.mjs';
// A fresh, bounded observation for the next request. It grants no permission:
// checks, proofs and Git still validate their original contracts at execution.
export async function taskDeliveryProgress(store,session,run,{checks,worker=false,taskPlan=null}={}){
if(run.purpose==='diagnostic')return null;
const task=store.owned('task',run.taskId,session.id),project=store.project(session.projectId);
const changes=session.changes.filter(change=>change.taskId===task.id&&change.status==='applied');
const owned=value=>value.taskId===task.id&&value.sessionId===session.id&&value.projectId===session.projectId;
const plans=[...store.core.check_plan.values()].filter(owned),jobs=[...store.core.check_job.values()].filter(owned);
const observations=[...store.core.tool.values()].filter(owned);
if(!changes.length&&!plans.length&&!jobs.length&&!observations.some(value=>
value.tool==='inspect_project'&&value.state==='completed'&&!value.requiresVerification))return null;
const latest=[...new Map(changes.map(change=>[change.path,change])).values()];
const files=latest.slice(-24).map(change=>{
let currentSha256=null,error=null;try{currentSha256=readText(project,change.path).sha256;}catch(cause){error=cause.message;}
return {path:change.path,change_id:change.id,change_set_id:change.changeSetId??null,applied_sha256:change.sha256,
current_sha256:currentSha256,current:currentSha256===change.sha256,...(error?{error}:{})};
});
const inspection=await inspectProject(project);
const latestPlan=plans.at(-1),latestJob=jobs.at(-1);
let planCurrent=false,planError=null;
if(latestPlan)try{checks.planFor(session,latestPlan.id);planCurrent=latestPlan.fingerprint===inspection.fingerprint;}
catch(cause){planError=cause.message;}
let sourceCurrent=!!latestJob&&inspection.scope.complete&&!latestJob.stale&&!latestJob.requiresVerification
&&['passed','failed','unverified'].includes(latestJob.status)&&!!latestJob.finishedAt
&&(latestJob.sourceFingerprint?latestJob.sourceFingerprint===inspection.sourceFingerprint:latestJob.fingerprint===inspection.fingerprint);
let evidenceError=null;
if(sourceCurrent)try{
for(const result of latestJob.results){
const artifact=store.owned('artifact',result.logArtifactId,session.id);
if(artifact.kind!=='check-log'||artifact.taskId!==task.id||artifact.runId!==latestJob.runId)throw new Error('检查日志的原任务或运行归属不匹配。');
store.artifactStore.read(artifact);
}
}catch(cause){sourceCurrent=false;evidenceError=cause.message;}
const unknown=[...store.core.tool.values()].filter(value=>owned(value)&&value.requiresVerification).map(value=>value.id);
const pending=session.changes.filter(change=>['pending','conflict'].includes(change.status)).map(change=>({id:change.id,path:change.path,status:change.status}));
const review=pendingDeliveryReview(store,session),contract=taskContract(task);
const snapshot={schemaVersion:2,kind:'task-delivery-progress',task_id:task.id,run_id:run.id,source_fingerprint:inspection.sourceFingerprint,
semantics:'current_observations_not_authorization_or_delivery_proof',files,total_files:latest.length,files_truncated:latest.length>files.length,
has_applied_changes:changes.length>0,
checks_policy:contract.checks,check_plan:latestPlan?{id:latestPlan.id,current:planCurrent,checks:latestPlan.checks.map(value=>value.name),error:planError}:null,
latest_check:latestJob?{id:latestJob.id,plan_id:latestJob.planId,status:latestJob.status,current_source:sourceCurrent,
stale:!!latestJob.stale||!sourceCurrent,results:latestJob.results.map(value=>({name:value.name,status:value.status,tests:value.tests,
log_artifact_id:value.logArtifactId,log_sha256:store.core.artifact.get(value.logArtifactId)?.sha256??null}))}:null,
remaining_plan_steps:taskPlan?.remaining_steps??[],plan_steps:taskPlan?.steps.map(step=>({key:step.key,kind:step.kind,status:step.status,blockers:step.blockers,proof_id:step.proof_id}))??[],
pending_changes:pending,unknown_tool_ids:unknown,...(evidenceError?{evidence_error:evidenceError}:{}),
stage:null,next_action:null,execution_note:'建议只依据当前事实;实际操作仍核对原计划和权限,执行检查等待审批,Git只准备预览并交还审查。'};
const next=(stage,tool,args={})=>{snapshot.stage=stage;snapshot.next_action=tool?{tool,arguments:args}:null;return snapshot;};
if(pending.length||unknown.length||review)return next('awaiting_review_or_verification');
if(evidenceError)return next('requires_current_evidence_verification');
if(snapshot.files_truncated||files.some(file=>!file.current))return next('applied_files_need_review');
// A baseline observation is useful before implementation, but cannot
// certify an empty delivery or bypass the existing review/Git contracts.
if(!changes.length){
if(contract.checks==='skip')return next('observed_without_changes');
if(sourceCurrent&&latestJob)return next(latestJob.status==='passed'?'baseline_passed_without_changes':'checks_need_repair');
if(planCurrent)return next('ready_for_checks','run_checks',{plan_id:latestPlan.id});
return next('observed_without_current_checks');
}
if(contract.checks==='skip')return next('checks_not_requested',worker?null:'delivery_report');
if(!sourceCurrent||!latestJob){
if(planCurrent)return next('ready_for_checks','run_checks',{plan_id:latestPlan.id});
return next('needs_current_check_plan','plan_checks',latestPlan?.checks.length?{names:latestPlan.checks.map(value=>value.name)}:{});
}
if(latestJob.status!=='passed')return next('checks_need_repair');
if(taskPlan?.configured&&!taskPlan.all_verified){
for(const step of taskPlan.steps.filter(value=>value.status!=='verified'&&!value.blockers.length)){
const evidence=step.kind==='checks'?latestJob:step.kind==='changes'?[...store.core.change_set.values()].findLast(value=>owned(value)
&&value.direction==='apply'&&value.status==='completed'&&step.paths.every(path=>value.files.some(file=>file.path===path&&file.state==='after'))):null;
if(evidence)return next('needs_plan_evidence','verify_task_step',{plan_id:taskPlan.plan_id,expected_revision:taskPlan.revision,step_key:step.key,evidence_id:evidence.id});
}
return next('needs_plan_evidence');
}
if(worker)return next('ready_for_parent_review');
return next('ready_for_git_preview','plan_delivery');
}
@@ -0,0 +1,126 @@
import fs from 'node:fs';
import path from 'node:path';
import { createHash, randomUUID } from 'node:crypto';
const hash = value => createHash('sha256').update(value).digest('hex');
const samePath = (a, b) => process.platform === 'win32' ? a.toLowerCase() === b.toLowerCase() : a === b;
const recordName = /^[a-f0-9]{64}\.json$/;
const failure = () => new Error('派生缓存目录或文件无法核对,已回退当前源码重建。');
// Stores only derived declarations/imports. Never stores source bodies, requests,
// credentials, execution results or recovery state. Every hit needs a fresh SHA.
export class IndexCache {
constructor({ directory, maximumProjects = 8, maximumBytes = 32 * 1024 * 1024, maximumEntryBytes = 8 * 1024 * 1024 } = {}) {
this.directory = directory ? path.resolve(directory) : null;
this.maximumProjects = maximumProjects; this.maximumBytes = maximumBytes; this.maximumEntryBytes = maximumEntryBytes;
this.enabled = true; this.error = null;
if (this.directory) {
try {
this.assertDirectory();
const filename = path.join(this.directory, 'settings.json');
if (fs.existsSync(filename)) {
this.assertFile(filename, 1024);
const settings = JSON.parse(fs.readFileSync(filename, 'utf8'));
if (settings.schemaVersion !== 1 || typeof settings.enabled !== 'boolean') throw failure();
this.enabled = settings.enabled;
}
this.trim();
} catch { this.enabled = false; this.error = '缓存设置无法核对,缓存已关闭;可修复目录后重新启用。'; }
}
}
key(project) { return hash(project.id + '\0' + project.root); }
assertDirectory() {
fs.mkdirSync(this.directory, { recursive: true, mode: 0o700 });
const stat = fs.lstatSync(this.directory);
if (!stat.isDirectory() || stat.isSymbolicLink() || !samePath(fs.realpathSync.native(this.directory), this.directory)) throw failure();
}
assertFile(filename, maximum = this.maximumEntryBytes) {
const stat = fs.lstatSync(filename);
if (!stat.isFile() || stat.isSymbolicLink() || stat.nlink !== 1 || stat.size > maximum) throw failure();
return stat;
}
write(filename, value) {
this.assertDirectory();
if (fs.existsSync(filename)) this.assertFile(filename, Number.MAX_SAFE_INTEGER);
const temporary = path.join(this.directory, '.write-' + randomUUID() + '.tmp');
try {
fs.writeFileSync(temporary, value, { flag: 'wx', mode: 0o600 });
this.assertDirectory();
if (fs.existsSync(filename)) this.assertFile(filename, Number.MAX_SAFE_INTEGER);
fs.renameSync(temporary, filename);
} finally { if (fs.existsSync(temporary)) fs.unlinkSync(temporary); }
}
load(project, identity) {
if (!this.enabled || !this.directory) return { entries: null, reason: this.enabled ? 'process-only' : 'disabled' };
try {
this.assertDirectory();
const filename = path.join(this.directory, this.key(project) + '.json');
if (!fs.existsSync(filename)) return { entries: null, reason: 'cold' };
this.assertFile(filename);
const envelope = JSON.parse(fs.readFileSync(filename, 'utf8'));
if (envelope.schemaVersion !== 1 || hash(JSON.stringify(envelope.payload)) !== envelope.sha256) return { entries: null, reason: 'corrupt' };
const payload = envelope.payload;
if (JSON.stringify(payload.identity) !== JSON.stringify(identity)) return { entries: null, reason: 'identity-changed' };
if (!Array.isArray(payload.entries) || payload.entries.length > 1000) return { entries: null, reason: 'corrupt' };
return { entries: new Map(payload.entries.map(entry => [entry.path, entry])), reason: 'disk' };
} catch { this.error = '派生缓存读取失败;本次从当前源码重建。'; return { entries: null, reason: 'unavailable' }; }
}
save(project, identity, entries) {
if (!this.enabled || !this.directory) return { stored: false, reason: this.enabled ? 'process-only' : 'disabled' };
try {
const payload = { identity, entries: [...entries.values()] };
const text = JSON.stringify({ schemaVersion: 1, sha256: hash(JSON.stringify(payload)), payload });
if (Buffer.byteLength(text) > Math.min(this.maximumEntryBytes, this.maximumBytes)) {
this.clear(project); return { stored: false, reason: 'capacity' };
}
this.write(path.join(this.directory, this.key(project) + '.json'), text);
const evictedProjects = this.trim(); this.error = null;
return { stored: true, reason: 'stored', evictedProjects };
} catch { this.error = '派生缓存写入失败;当前索引仍来自本次源码核对。'; return { stored: false, reason: 'unavailable' }; }
}
touch(project) {
if (!this.enabled || !this.directory) return { stored: false, reason: this.enabled ? 'process-only' : 'disabled' };
try {
this.assertDirectory(); const filename = path.join(this.directory, this.key(project) + '.json');
if (!fs.existsSync(filename)) return { stored: false, reason: 'cold' };
this.assertFile(filename); const at = new Date(); fs.utimesSync(filename, at, at);
return { stored: true, reason: 'stored', evictedProjects: this.trim() };
} catch { this.error = '派生缓存不可用;当前索引来自本次源码核对。'; return { stored: false, reason: 'unavailable' }; }
}
records() {
if (!this.directory) return [];
this.assertDirectory();
return fs.readdirSync(this.directory).filter(name => recordName.test(name)).map(name => {
const filename = path.join(this.directory, name), stat = this.assertFile(filename, Number.MAX_SAFE_INTEGER);
return { filename, bytes: stat.size, touched: stat.mtimeMs };
});
}
trim() {
const records = this.records().sort((a, b) => a.touched - b.touched || a.filename.localeCompare(b.filename));
let bytes = records.reduce((sum, value) => sum + value.bytes, 0), evicted = 0;
while (records.length > this.maximumProjects || bytes > this.maximumBytes) {
const record = records.shift(); this.assertFile(record.filename); fs.unlinkSync(record.filename); bytes -= record.bytes; evicted++;
}
return evicted;
}
clear(project) {
if (!this.directory) return 0;
this.assertDirectory();
const names = project ? [path.join(this.directory, this.key(project) + '.json')] : this.records().map(value => value.filename);
let removed = 0;
for (const filename of names) if (fs.existsSync(filename)) { this.assertFile(filename, Number.MAX_SAFE_INTEGER); fs.unlinkSync(filename); removed++; }
return removed;
}
configure(enabled) {
if (typeof enabled !== 'boolean') throw new Error('缓存开关需要布尔值。');
if (this.directory) this.write(path.join(this.directory, 'settings.json'), JSON.stringify({ schemaVersion: 1, enabled }));
this.enabled = enabled; this.error = null;
}
status() {
let diskProjects = 0, diskBytes = 0;
try { const records = this.records(); diskProjects = records.length; diskBytes = records.reduce((sum, value) => sum + value.bytes, 0); }
catch { this.error = '派生缓存目录或文件无法核对;读取失败时将重建。'; }
return { enabled: this.enabled, persistent: !!this.directory, diskProjects, diskBytes, maximumProjects: this.maximumProjects,
maximumBytes: this.maximumBytes, maximumEntryBytes: this.maximumEntryBytes, error: this.error };
}
}
@@ -0,0 +1,141 @@
import { randomUUID } from 'node:crypto';
import { PNG } from 'pngjs';
import jpeg from 'jpeg-js';
export const IMAGE_LIMITS = { bytes: 2 * 1024 * 1024, pixels: 16 * 1024 * 1024, dimension: 8192, sentDimension: 1024, sentBytes: 768 * 1024, perTask: 1, drafts: 8 };
const reject = (message, status = 400) => Object.assign(new Error(message), { status });
function dimensions(bytes, type) {
if (type === 'image/png' && bytes.length >= 33 && bytes.subarray(0, 8).equals(Buffer.from([137,80,78,71,13,10,26,10]))
&& bytes.readUInt32BE(8) === 13 && bytes.toString('ascii', 12, 16) === 'IHDR') {
let ended = false;
for (let offset = 8; offset < bytes.length;) {
if (offset + 12 > bytes.length) throw reject('PNG区块不完整。');
const length = bytes.readUInt32BE(offset), name = bytes.toString('ascii', offset + 4, offset + 8);
if (offset + length + 12 > bytes.length || ['acTL','fcTL','fdAT'].includes(name)) throw reject('只支持完整的静态PNG图片。');
offset += length + 12;
if (name === 'IEND') { ended = length === 0 && offset === bytes.length; break; }
}
if (!ended) throw reject('PNG结束区块或尾部内容无效。');
return { width: bytes.readUInt32BE(16), height: bytes.readUInt32BE(20), orientation: 1 };
}
if (type === 'image/jpeg' && bytes[0] === 255 && bytes[1] === 216 && bytes.at(-2) === 255 && bytes.at(-1) === 217) {
let size, orientation = 1;
for (let p = 2; p < bytes.length;) {
if (bytes[p++] !== 255) break;
while (bytes[p] === 255) p++;
const marker = bytes[p++];
if (marker === 217 && p === bytes.length && size) return { ...size, orientation };
if (p + 2 > bytes.length || marker === 216 || marker === 217) break;
const length = bytes.readUInt16BE(p);
if (length < 2 || p + length > bytes.length) break;
if ([192,193,194].includes(marker) && length >= 8) size = { width: bytes.readUInt16BE(p + 5), height: bytes.readUInt16BE(p + 3) };
if (marker === 225 && bytes.toString('ascii',p+2,p+8) === 'Exif\0\0') orientation = exifOrientation(bytes.subarray(p+8,p+length));
p += length;
if (marker === 218) {
// Scan data may contain escaped FF bytes and restart markers; the next
// real marker must still be parsed, including progressive scan headers.
while (p < bytes.length) {
if (bytes[p++] !== 255) continue;
const start = p - 1;
while (bytes[p] === 255) p++;
if (bytes[p] === 0 || bytes[p] >= 208 && bytes[p] <= 215) { p++; continue; }
p = start; break;
}
}
}
}
throw reject('图片内容与PNG/JPEG类型不符,或图片已损坏。');
}
function exifOrientation(bytes) {
try {
const little = bytes.toString('ascii',0,2) === 'II';
if (!little && bytes.toString('ascii',0,2) !== 'MM') throw new Error();
const u16 = offset => little ? bytes.readUInt16LE(offset) : bytes.readUInt16BE(offset);
const u32 = offset => little ? bytes.readUInt32LE(offset) : bytes.readUInt32BE(offset);
if (u16(2) !== 42) throw new Error();
const offset = u32(4), count = u16(offset);
if (offset < 8 || offset + 2 + count * 12 + 4 > bytes.length) throw new Error();
for (let i=0;i<count;i++) {
const entry=offset+2+i*12;
if (u16(entry)!==274) continue;
if(u16(entry+2)!==3 || u32(entry+4)!==1) throw new Error();
const value=u16(entry+8); if(value<1 || value>8) throw new Error(); return value;
}
return 1;
} catch { throw reject('JPEG方向元数据已损坏,请重新导出图片。'); }
}
function sentImage(decoded, orientation, maximum) {
const rotated = orientation >= 5;
const w = rotated ? decoded.height : decoded.width, h = rotated ? decoded.width : decoded.height;
const ratio = Math.min(1,maximum/Math.max(w,h)), width=Math.max(1,Math.round(w*ratio)), height=Math.max(1,Math.round(h*ratio));
const output = new PNG({width,height});
for(let y=0;y<height;y++) for(let x=0;x<width;x++) {
const u=Math.min(w-1,Math.floor(x*w/width)),v=Math.min(h-1,Math.floor(y*h/height));
const [sx,sy] = orientation===2 ? [decoded.width-1-u,v] : orientation===3 ? [decoded.width-1-u,decoded.height-1-v]
: orientation===4 ? [u,decoded.height-1-v] : orientation===5 ? [v,u] : orientation===6 ? [v,decoded.height-1-u]
: orientation===7 ? [decoded.width-1-v,decoded.height-1-u] : orientation===8 ? [decoded.width-1-v,u] : [u,v];
output.data.set(decoded.data.subarray((sy*decoded.width+sx)*4,(sy*decoded.width+sx)*4+4),(y*width+x)*4);
}
return { bytes:PNG.sync.write(output),width,height };
}
export function validateImage(input) {
if (!input || Object.keys(input).some(key => !['name','mediaType','base64'].includes(key)) || typeof input.name !== 'string' || !input.name.trim() || input.name.length > 160
|| /[\\/\x00-\x1f]/.test(input.name) || !['image/png','image/jpeg'].includes(input.mediaType) || typeof input.base64 !== 'string') throw reject('请选择PNG或JPEG图片,文件名不能包含路径。');
if (input.base64.length > Math.ceil(IMAGE_LIMITS.bytes / 3) * 4) throw reject('单张图片最多2MB,请先裁剪或压缩。',413);
if (!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(input.base64)) throw reject('图片编码无效。');
const bytes = Buffer.from(input.base64,'base64');
if (bytes.length > IMAGE_LIMITS.bytes) throw reject('单张图片最多2MB,请先裁剪或压缩。',413);
if (!bytes.length || bytes.toString('base64') !== input.base64) throw reject('图片编码或大小无效。');
const size = dimensions(bytes,input.mediaType);
if (!size.width || !size.height || Math.max(size.width,size.height)>IMAGE_LIMITS.dimension || size.width*size.height>IMAGE_LIMITS.pixels) throw reject('图片尺寸过大,请裁剪后再添加。',413);
let decoded;
try { decoded = input.mediaType==='image/png' ? PNG.sync.read(bytes,{checkCRC:true}) : jpeg.decode(bytes,{useTArray:true,tolerantDecoding:false,maxResolutionInMP:16.8,maxMemoryUsageInMB:160}); }
catch { throw reject('图片无法完整解码,请重新导出PNG/JPEG。'); }
if (decoded.width!==size.width || decoded.height!==size.height) throw reject('图片实际尺寸不一致。');
let maximum = IMAGE_LIMITS.sentDimension, sent = sentImage(decoded,size.orientation,maximum);
while(sent.bytes.length>IMAGE_LIMITS.sentBytes && maximum>64) { maximum=Math.floor(maximum*0.75);sent=sentImage(decoded,size.orientation,maximum); }
if(sent.bytes.length>IMAGE_LIMITS.sentBytes)throw reject('图片发送副本超过大小限制,请先裁剪。',413);
return { bytes, sent:sent.bytes, width:size.width,height:size.height,orientation:size.orientation,sentWidth:sent.width,sentHeight:sent.height };
}
export class InputAttachments {
constructor(store, { busy=()=>false }={}) { this.store=store;this.busy=busy; }
list(session) { return [...this.store.core.input_attachment.values()].filter(row=>row.sessionId===session.id && ['draft','attached'].includes(row.status)).map(row=>structuredClone(row)); }
upload(session,input) {
if(this.busy(session.projectId))throw reject('请等待当前项目执行结束后再添加附件。',409);
if(this.list(session).filter(row=>row.status==='draft').length>=IMAGE_LIMITS.drafts)throw reject('待发送图片已满,请先移除不用的图片。',409);
const value=validateImage(input),identity={id:session.id,projectId:session.projectId,taskId:null,runId:null};
const original=this.store.artifactStore.write(identity,null,value.bytes,{kind:'input-image-original',mediaType:input.mediaType});
const sent=this.store.artifactStore.write(identity,null,value.sent,{kind:'input-image-sent',mediaType:'image/png'});
this.store.core.artifact.set(original.id,original);this.store.core.artifact.set(sent.id,sent);
const record={id:randomUUID(),sessionId:session.id,projectId:session.projectId,taskId:null,runId:null,status:'draft',name:input.name.trim(),mediaType:input.mediaType,
originalArtifactId:original.id,sentArtifactId:sent.id,sha256:original.sha256,bytes:original.bytes,sentSha256:sent.sha256,sentBytes:sent.bytes,
width:value.width,height:value.height,orientation:value.orientation,sentWidth:value.sentWidth,sentHeight:value.sentHeight,createdAt:new Date().toISOString()};
this.store.putRecord('input_attachment',session,record,'input_attachment.uploaded');return structuredClone(record);
}
get(session,id) { return this.store.owned('input_attachment',id,session.id); }
remove(session,id) {
const row=this.get(session,id);
if(row.status!=='draft'||this.busy(session.projectId))throw reject('已发送附件保留在原任务中;只能移除尚未发送的图片。',409);
row.status='withdrawn';this.store.save(session,{type:'input_attachment.withdrawn'});return this.list(session);
}
validateSelection(session,ids) {
if(!Array.isArray(ids)||ids.length>IMAGE_LIMITS.perTask||new Set(ids).size!==ids.length)throw reject('每个任务当前支持一张图片。');
return ids.map(id=>{const row=this.get(session,id);if(row.status!=='draft')throw reject('图片已发送或移除,请重新选择。',409);this.read(session,id);this.read(session,id,{original:true});return row;});
}
read(session,id,{original=false}={}) {
const row=this.get(session,id);if(row.status==='withdrawn')throw reject('这张待发送图片已移除。',410);
const artifact=this.store.owned('artifact',original?row.originalArtifactId:row.sentArtifactId,session.id);
if(row.projectId!==session.projectId || artifact.taskId!==row.taskId||artifact.runId!==row.runId||artifact.sha256!==(original?row.sha256:row.sentSha256)
||artifact.kind!==(original?'input-image-original':'input-image-sent') || artifact.mediaType!==(original?row.mediaType:'image/png') || artifact.bytes!==(original?row.bytes:row.sentBytes))throw reject('附件身份已变化,请核对原记录。',409);
if(row.status==='attached'){
const task=this.store.owned('task',row.taskId,session.id),run=this.store.owned('run',row.runId,session.id);
if(run.taskId!==task.id||!task.attachmentIds?.includes(row.id))throw reject('附件不属于原Task/Run。',409);
}
return {row,artifact,bytes:this.store.artifactStore.readBytes(artifact)};
}
images(session,task) {
return (task.attachmentIds??[]).map(id=>{const {row,bytes}=this.read(session,id);this.read(session,id,{original:true});if(row.taskId!==task.id||row.status!=='attached')throw reject('附件不属于当前任务。',409);
return {id:row.id,sha256:row.sentSha256,width:row.sentWidth,height:row.sentHeight,dataUrl:'data:image/png;base64,'+bytes.toString('base64')};});
}
}

Some files were not shown because too many files have changed in this diff Show More