feat: ship isolated workspace review and navigation in 1.6.0

This commit is contained in:
Agent Workbench Dev
2026-10-29 23:45:32 +08:00
parent 7d9bfb85da
commit bb48f69f25
39 changed files with 841 additions and 35 deletions
+38 -5
View File
@@ -13,7 +13,7 @@ const defaultConfig: Config = { mode: 'demo', baseUrl: 'http://127.0.0.1:11434/v
export default function App() {
const [token, setAccess] = useState('');
const [version, setVersion] = useState('1.5.0');
const [version, setVersion] = useState('1.6.0');
const [diagnosticsOpen, setDiagnosticsOpen] = useState(false);
const [diagnostics, setDiagnostics] = useState<RuntimeDiagnostics | null>(null);
const [diagnosticsBusy, setDiagnosticsBusy] = useState(false);
@@ -75,11 +75,13 @@ export default function App() {
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?.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?.changeSets?.some(set => ['applying', 'rolling_back'].includes(set.status)) === true
|| session.execution?.workspaces?.some(value => ['creating', 'verifying', 'registering'].includes(value.status)) === true);
const anyRunning = isRunning || briefs.some(item => activeStates.includes(item.status));
const pending = session?.changes.filter(change => ['pending', 'conflict'].includes(change.status)) || [];
const reviewedRun = session?.execution?.run;
@@ -117,7 +119,7 @@ export default function App() {
function failure(error: unknown) { notify(error instanceof Error ? error.message : String(error)); }
function selectSession(id: string) {
if (selectedSessionRef.current === id) return;
selectedSessionRef.current = id; setSessionId(id); setSession(null); setToast('');
workspaceRequest.current++; selectedSessionRef.current = id; setSessionId(id); setSession(null); setToast('');
localStorage.setItem('awb-session', id); setChangeId(''); setEventId('');
}
function acceptSession(updated: Session) {
@@ -149,7 +151,7 @@ export default function App() {
}
async function chooseProject(id: string, preferredSession?: string) {
if (selectedProjectRef.current !== id) setToast('');
selectedProjectRef.current = id; setProjectId(id); localStorage.setItem('awb-project', id);
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 || '';
@@ -162,6 +164,28 @@ export default function App() {
} 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) {
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); showInspector('task');
}
async function newSession() {
if (sessionCreation.current) return sessionCreation.current;
if (!projectId) { setProjectOpen(true); return null; }
@@ -348,6 +372,15 @@ export default function App() {
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;
@@ -478,7 +511,7 @@ export default function App() {
{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><IconButton label="复制文件内容" onClick={() => navigator.clipboard.writeText(openFile.content).then(() => notify('已复制文件内容。')).catch(failure)}><Copy size={14} /></IconButton><IconButton label={editing ? '取消编辑' : '编辑文件'} onClick={() => { 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></> : <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={failure} 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 ? <TaskPanel key={session.id} session={session} onSession={acceptSession} onError={failure} busy={isRunning} /> : <EmptyInspector kind="trace" />)}
{tab === 'task' && (session && selectedProject ? <TaskPanel key={session.id} project={selectedProject} session={session} onSession={acceptSession} onError={failure} busy={isRunning} onWorkspaceRefresh={refreshWorkspaceState} onWorkspaceNavigate={navigateWorkspace} /> : <EmptyInspector kind="trace" />)}
{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>
+5 -3
View File
@@ -1,10 +1,11 @@
import { useEffect, useRef, useState } from 'react';
import { Check, ClipboardCheck, FileText, GitBranch, LoaderCircle, Play, RefreshCw, ShieldQuestion } from 'lucide-react';
import type { ArtifactPreview, CheckPlan, Run, Session } from './types';
import type { ArtifactPreview, CheckPlan, Project, 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 './TaskPanel.css';
const stopReasons: Record<string, string> = { no_progress: '重复读取未推进任务,请核对后继续', context_limit: '完整任务要求超过请求上下文预算', time_limit: '到达运行时间预算', token_limit: '到达本次 token 预算', task_token_limit: '到达任务累计预算', step_limit: '到达工具轮次上限', cancelled: '用户停止', model_error: '模型请求失败', interrupted: '进程中断' };
@@ -13,7 +14,7 @@ stopReasons.git_review = 'Git预览已保存,等待审查与确认';
stopReasons.git_review_declined = 'Git预览已撤回,文件和检查记录保留';
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' }) : '执行中';
export function TaskPanel({ session, onSession, onError, busy }: { session: Session; onSession: (value: Session) => void; onError: (error: unknown) => void; busy: boolean }) {
export function TaskPanel({ project, session, onSession, onError, busy, onWorkspaceRefresh, onWorkspaceNavigate }: { project: Project; session: Session; onSession: (value: Session) => void; onError: (error: unknown) => void; busy: boolean; 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);
@@ -60,6 +61,7 @@ export function TaskPanel({ session, onSession, onError, busy }: { session: Sess
}
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.goal}</p><code className="record-id" title={task.id}>{task.id.slice(0, 8)} · 任务</code>
@@ -71,7 +73,7 @@ export function TaskPanel({ session, onSession, onError, busy }: { session: Sess
<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>
<dl className="record-fields"><dt>实际模型</dt><dd>{run.model?.verified === false ? '历史模型信息未记录' : run.model?.mode === 'demo' ? '离线演示 · 固定脚本' : run.model?.model || '未记录'}</dd><dt>接口</dt><dd className="record-endpoint">{run.model?.verified === false ? '未记录' : run.model?.baseUrl || '本地演示'}</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>
<dl className="record-fields"><dt>实际模型</dt><dd>{run.model?.verified === false ? '历史模型信息未记录' : run.model?.mode === 'demo' ? '离线演示 · 固定脚本' : run.model?.model || '未记录'}</dd><dt>接口</dt><dd className="record-endpoint">{run.model?.verified === false ? '未记录' : run.model?.baseUrl || '本地演示'}</dd>{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>}
+44
View File
@@ -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; } }
+91
View File
@@ -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>;
}
+14 -4
View File
@@ -3,7 +3,17 @@ export interface Config {
contextLimit: number; maxSteps: number; maxOutputTokens: number; hasKey: boolean;
maxRunDurationMs: number; maxRunTokens: number; maxTaskTokens: number;
}
export interface Project { id: string; root: string; name: string; addedAt: 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 }
export interface ToolEvent {
@@ -69,7 +79,7 @@ export interface CodeQuery { query: string; kind: CodeQueryKind; results: CodeRe
export interface ModelSnapshot { mode: string; model: string; baseUrl: string; verified?: boolean; contextLimit?: number; maxOutputTokens?: 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 }
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 ContextPlan {
id: string; sessionId: string; projectId: string; taskId: string; runId: string; stepId: string; requestIndex?: number; status: string;
@@ -85,7 +95,7 @@ export interface ContextHistoryGroup {
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 }
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 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 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 }
@@ -113,4 +123,4 @@ export interface ChangeSet {
snapshotArtifactId: string; sourceRunId: string; restoreError?: string }[];
observations?: { path: string; state: string; exists: boolean | null; actualSha256: string | null; problem?: 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[]; plans?: CheckPlan[]; deliveries?: DeliveryJob[]; deliveryPlans?: DeliveryPlan[]; changeSets?: ChangeSet[]; contextPlans?: ContextPlan[]; accountedTaskTokens: number }
export interface ExecutionSnapshot { schemaVersion: number; task: Task | null; run: Run | null; runs: RunBrief[]; progress: { totalTools: number; completedTools: number; requiresVerification: { id: string; tool: string; state: string; callId: string }[] }; artifacts: Artifact[]; checks: CheckJob[]; plans?: CheckPlan[]; deliveries?: DeliveryJob[]; deliveryPlans?: DeliveryPlan[]; changeSets?: ChangeSet[]; contextPlans?: ContextPlan[]; workspaces?: WorkspaceRecord[]; workspaceIdentity?: WorkspaceIdentity; accountedTaskTokens: number }