diff --git a/src/dashboard-page.ts b/src/dashboard-page.ts
index 8f818c7..a652a4c 100644
--- a/src/dashboard-page.ts
+++ b/src/dashboard-page.ts
@@ -1,19 +1,20 @@
export const dashboardHtml = String.raw`
-
Agent Loop · Worker 看板
+Agent Loop · 项目看板
-
DASHBOARD V1Worker 执行看板
正在连接只读
- 看见 Worker 的每一步。
连续显示可见执行说明、阶段、工具摘要、等待和证据。
+
+ 看清每项工作的状态。
按协调者与项目查看任务、最近活动和工作汇报。服务心跳单独显示。
- ↳
等待第一个 Worker
选择左侧 Worker 后查看连续执行叙事。看板只显示允许的可见说明,不显示隐藏推理、原始工具输出或密钥。
-
-
+
+ ↳
选择任务查看详情
选择项目中的任务后查看连续执行叙事。看板只显示允许的可见说明,不显示隐藏推理、原始工具输出或密钥。
+
+
@@ -22,33 +23,146 @@ export const dashboardHtml = String.raw`
export const dashboardCss = String.raw`
:root{color-scheme:light;--bg:#f7f8fa;--surface:#fff;--line:#e5e9ed;--text:#202833;--muted:#7a8492;--green:#16846a;--blue:#456be8;--red:#d14c51;--amber:#b17b1f;--mono:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;font-family:-apple-system,BlinkMacSystemFont,"Segoe UI","PingFang SC",sans-serif;font-size:14px}*{box-sizing:border-box}body{margin:0;background:var(--bg);color:var(--text)}button,input,select{font:inherit}button,a,input,select{outline-offset:4px}button{cursor:pointer}a{color:inherit;text-decoration:none}[hidden]{display:none!important}.shell{display:flex;min-height:100vh}.sidebar{width:276px;flex-shrink:0;background:#fff;border-right:1px solid var(--line);height:100vh;position:sticky;top:0;display:flex;flex-direction:column;padding:28px 18px 18px}.brand{display:flex;gap:12px;align-items:center;padding:0 10px 36px;font-size:21px;font-weight:650;letter-spacing:-.7px}.brand small{display:block;letter-spacing:1.5px;font-size:8px;color:var(--muted);margin-top:5px;font-weight:600}.brand-mark{background:#24352f;color:#e4f6ba;width:38px;height:38px;border-radius:11px;display:flex;align-items:center;justify-content:center;font-size:25px;position:relative}.brand-mark span{font-size:17px;position:absolute;right:3px;top:1px}.sidebar-heading{display:flex;justify-content:space-between;align-items:center;padding:0 11px 15px;font-weight:600}.count{font:11px var(--mono);background:#f1f3f5;color:#7b8591;padding:3px 7px;border-radius:5px}.search{display:flex;align-items:center;gap:8px;background:#f7f8fa;border:1px solid var(--line);border-radius:7px;padding:8px 10px}.search>span{font-size:21px;line-height:1;color:var(--muted)}.search input{width:100%;border:0;background:none;outline:none;font-size:12px;min-width:0}.filters{display:flex;gap:7px}.filters select{flex:1;min-width:0}select{margin:10px 0 18px;border:1px solid var(--line);border-radius:6px;padding:7px 8px;background:white;color:#677180;font-size:12px}#task-list{flex:1;overflow-y:auto;min-height:0}.worker-item{display:block;text-align:left;width:100%;border:1px solid transparent;background:none;border-radius:8px;padding:13px 11px;margin-bottom:5px;color:var(--text)}.worker-item:hover{background:#f5f7fa}.worker-item.selected{background:#edf3f0;border-color:#dae7e0}.worker-top{display:flex;align-items:center;gap:7px;font-size:11px;color:var(--muted);margin-bottom:8px}.worker-name{display:block;font-weight:550;line-height:1.6;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-size:13px}.worker-id{display:block;font-size:10px;color:#9ba3ad;font-family:var(--mono);margin-top:7px}.sidebar-empty{color:var(--muted);font-size:12px;text-align:center;padding:25px 5px;line-height:1.8;white-space:pre-line}.sidebar-footer{border-top:1px solid var(--line);padding:18px 10px 0;font-size:11px}.sidebar-footer>div{display:flex;gap:8px;align-items:center}.sidebar-footer strong{font-weight:500}.sidebar-footer p{color:var(--muted);margin:7px 0 19px;padding-left:15px;line-height:1.7}.footer-label{display:block;font-size:10px;color:#9ba3ad;margin-bottom:6px}.sidebar-footer code{display:block;word-break:break-all;font-size:10px;line-height:1.7;color:var(--muted)}main{flex:1;min-width:0;padding:0 42px 36px;max-width:1800px}.topbar{height:77px;display:flex;justify-content:space-between;align-items:center;border-bottom:1px solid var(--line)}.eyebrow{font-size:10px;font-weight:650;letter-spacing:1.4px;color:var(--muted)}.topbar-title{font-size:12px;color:#5d6876;margin-left:20px}.connection{display:flex;align-items:center;gap:7px;font-size:11px;color:#687382}.local-tag{font-size:10px;background:#edf0f3;border:1px solid #e2e6eb;border-radius:5px;padding:5px 8px;margin-left:12px;color:#6a7684}.dot{display:inline-block;width:6px;height:6px;border-radius:50%;background:#a7b0bc;flex-shrink:0}.dot.green{background:var(--green);box-shadow:0 0 0 3px #16846a0d}.dot.red{background:var(--red)}.dot.amber{background:var(--amber)}.overview{display:flex;align-items:center;justify-content:space-between;gap:20px;padding:35px 0 32px}h1{font-size:26px;letter-spacing:-.8px;margin:0;font-weight:600}h1 span{color:var(--green)}.overview p{font-size:12px;color:var(--muted);margin:12px 0 0}.metrics{display:flex;gap:34px}.metrics>div{display:flex;flex-direction:column;gap:8px;min-width:55px}.metrics strong{font-size:27px;font-weight:500;font-variant-numeric:tabular-nums}.metrics span{font-size:10px;color:var(--muted);white-space:nowrap;display:flex;align-items:center;gap:7px}.task-heading{display:flex;justify-content:space-between;gap:20px;align-items:center;border-top:1px solid var(--line);padding:24px 0 18px}.task-heading-line{display:flex;gap:12px;align-items:center}h2{font-size:20px;font-weight:600;margin:12px 0;line-height:1.5}.badge{font-size:10px;color:var(--green);background:#e8f3ee;padding:4px 7px;border-radius:4px;white-space:nowrap}.badge.failed{color:var(--red);background:#fceced}.badge.idle,.badge.pending{background:#edf0f4;color:#6b7685}.badge.paused{color:#9c741f;background:#faf1dd}.task-identifiers{display:flex;gap:16px;color:#98a1ac;align-items:center;font-size:10px}.task-identifiers code{font-family:var(--mono)}.source-link{border:1px solid var(--line);border-radius:6px;padding:8px 11px;font-size:11px;white-space:nowrap;background:#fff}.workspace-grid{display:grid;grid-template-columns:minmax(0,1fr) 235px;gap:16px;align-items:start}.console{background:#fff;border:1px solid #dde2e8;border-radius:10px;overflow:hidden;box-shadow:0 3px 14px #1d2b3c03}.console-toolbar{min-height:57px;display:flex;justify-content:space-between;gap:10px;align-items:center;border-bottom:1px solid var(--line);padding:0 20px}.tabs{display:flex;align-items:stretch;gap:24px;height:57px}.tab{background:none;border:0;border-bottom:2px solid transparent;padding:0 1px;font-size:12px;color:var(--muted);display:flex;align-items:center;gap:8px}.tab.active{color:#2b3c36;font-weight:600;border-color:#2e755d}.live-dot{display:inline-block;width:5px;height:5px;background:var(--green);border-radius:50%}.console-actions{display:flex;align-items:center;gap:16px;font-size:10px;color:var(--muted);white-space:nowrap}.console-actions label{display:flex;align-items:center;gap:3px;cursor:pointer}.console-actions input{accent-color:var(--green);width:12px;height:12px}.quiet-button{font-size:10px;background:none;border:1px solid var(--line);border-radius:5px;color:#667383;padding:6px 8px}.live-toolbar{display:flex;justify-content:space-between;align-items:center;gap:12px;background:#fcfcfd;padding:9px 19px;border-bottom:1px solid #f0f2f5;font-size:10px;color:#9ba3ae}.event-filters{display:flex;gap:3px;flex-wrap:wrap}.filter{border:0;background:none;font:10px var(--mono);color:#83909e;padding:5px 7px;border-radius:4px}.filter.active{background:#ebeff3;color:#485869}.output{height:clamp(360px,58vh,760px);overflow:auto;padding:20px 24px;scroll-behavior:auto}.output:focus-visible{outline:2px solid #8eb5a3;outline-offset:-3px}.stage{margin:0 0 19px;border:1px solid #edf0f3;border-radius:8px;background:#fff}.stage>summary{cursor:pointer;list-style:none;padding:10px 14px;background:#fcfcfd;border-bottom:1px solid #f0f2f5;font:11px var(--mono);color:#6a7886}.stage>summary::-webkit-details-marker{display:none}.stage>summary:before{content:'▸';display:inline-block;margin-right:8px;color:#a0aab4}.stage[open]>summary:before{content:'▾'}.event{margin:0;padding:13px 14px 13px 17px;border-left:2px solid #e7ece9}.event+.event{border-top:1px solid #f2f3f5}.event[data-type=TOOL_CALL]{border-color:#dce5f8}.event[data-type=BLOCKER],.event[data-type=RETRY]{border-color:#e7a0a3;background:#fff7f7}.event[data-type=WAITING]{border-color:#e5c982;background:#fffaf0}.event[data-type=OUTPUT],.event[data-type=EVIDENCE]{border-color:#b8dccb;background:#f8fcfa}.event-header{display:flex;align-items:center;gap:10px;font-size:10px;color:#8a96a2;margin-bottom:8px}.event-type{font:600 10px var(--mono);color:#47816b}.event[data-type=TOOL_CALL] .event-type{color:#5c76ae}.event[data-type=BLOCKER] .event-type,.event[data-type=RETRY] .event-type{color:#c95b62}.event[data-type=WAITING] .event-type{color:#9b7729}.event[data-type=OUTPUT] .event-type,.event[data-type=EVIDENCE] .event-type{color:#2e8062}.event-header time{font:9px var(--mono)}.event-header code{font-size:9px;color:#b0b8c2}.event pre{margin:0;white-space:pre-wrap;word-break:break-word;font:12px/1.8 var(--mono);color:#374554}.event[data-type=NARRATIVE] pre{font-family:inherit;font-size:13px;line-height:1.8}.collapsed{font:10px var(--mono);color:#9ba3ae;padding:5px 14px 10px 17px}.worker-meta{background:#fff;border:1px solid var(--line);border-radius:9px;padding:17px 16px;position:sticky;top:18px}.meta-heading{display:flex;justify-content:space-between;align-items:center}.worker-meta h3{font-size:15px;margin:19px 0 4px}.worker-meta>p{color:var(--muted);font-size:11px;margin:0 0 18px}.worker-meta dl{display:grid;gap:13px;margin:0}.worker-meta dt{font-size:10px;color:#9ba3ae;margin-bottom:4px}.worker-meta dd{font:10px/1.5 var(--mono);margin:0;word-break:break-word;color:#53616f}.console-footer{height:35px;border-top:1px solid var(--line);background:#fcfcfd;display:flex;justify-content:space-between;align-items:center;padding:0 19px;gap:15px;font:9px var(--mono);color:#97a2af}.banner{border:1px solid #ead9ad;background:#fffaf0;color:#956e28;border-radius:6px;padding:12px 15px;font-size:12px;line-height:1.8;margin-bottom:16px;white-space:pre-wrap;word-break:break-word}.banner.error{color:#b34d55;border-color:#efd6d8;background:#fff5f6}.empty-state{min-height:460px;display:flex;align-items:center;justify-content:center;flex-direction:column;border:1px dashed #dce1e6;border-radius:10px;background:#ffffff80;text-align:center;padding:25px}.empty-icon{font:36px var(--mono);color:#8ba397;background:#edf2ef;border:1px solid #e0e9e3;width:64px;height:64px;border-radius:17px;display:grid;place-items:center;margin-bottom:8px}.empty-state h2{font-size:17px}.empty-state p{color:var(--muted);font-size:12px;line-height:2;max-width:520px}.history-message{border-bottom:1px solid #edf0f3;padding:14px 0}.history-message pre{white-space:pre-wrap;word-break:break-word;font:12px/1.9 var(--mono);margin:8px 0}.history-message small{color:var(--muted);font-size:10px}.history-label{font-size:11px;font-weight:600;color:#5d7669}.diagnostic{padding:12px 0;border-bottom:1px solid var(--line);font:11px/1.8 var(--mono);white-space:pre-wrap;word-break:break-word;color:#9a5d63}.diagnostic time{display:block;color:var(--muted);font-size:10px;margin-bottom:5px}@media(max-width:1100px){main{padding:0 24px 25px}.sidebar{width:236px}.workspace-grid{grid-template-columns:minmax(0,1fr) 205px}.metrics{gap:18px}.topbar-title{display:none}.console-actions{gap:8px}.tabs{gap:17px}.live-toolbar{align-items:flex-start;flex-direction:column}}@media(max-width:760px){.shell{display:block}.sidebar{position:relative;width:100%;height:auto;padding:17px}.brand{padding:0 0 18px}.sidebar-heading{padding-left:0}.sidebar-footer{display:none}#task-list{display:block;flex:none;max-height:40vh}.search{margin-bottom:10px}.filters select{margin:0 0 10px;width:100%}main{padding:0 16px 24px}.topbar{height:58px}.overview{padding:23px 0;align-items:flex-start;flex-direction:column}h1{font-size:23px}.metrics{gap:45px}.metrics strong{font-size:23px}.task-heading{padding-top:18px}.workspace-grid{display:block}.worker-meta{position:static;margin-top:12px}.console-toolbar{flex-wrap:wrap;padding:0 12px 10px}.tabs{height:48px}.console-actions{width:100%;justify-content:space-between}.output{padding:16px;height:52vh}.local-tag{margin-left:4px}}
+
+.overview{flex-wrap:wrap}.task-identifiers{flex-wrap:wrap;overflow-wrap:anywhere}#project-overview{margin-bottom:28px}.overview-disclosure>summary{cursor:pointer;font-weight:600;padding:14px 0;line-height:1.7}.coordinator-group{border-top:1px solid var(--line);padding:8px 0 20px}.project-group{padding:0 0 8px 18px;border-left:2px solid #dce7e1;margin:16px 0 0 8px}.project-directory{font:11px/1.6 var(--mono);color:var(--muted);word-break:break-all;margin:0 0 14px}.task-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(min(100%,310px),1fr));gap:12px}.worker-card{background:#fff;border:1px solid var(--line);border-radius:8px;padding:16px;min-width:0}.worker-card.selected{border-color:var(--green)}.worker-card>.worker-top{overflow-wrap:anywhere}.task-open{border:0;background:none;padding:0;color:var(--blue);text-align:left;font-weight:600;line-height:1.7;font-size:15px;overflow-wrap:anywhere}.task-states{font-size:12px;color:#586473;line-height:1.8;margin:10px 0}.summary-source,.record-time{font-size:11px;color:var(--muted);line-height:1.8;white-space:pre-wrap}.summary-text,.waiting-fact,.lifecycle-fact,.delivery-reference{font-size:12px;line-height:1.8;white-space:pre-wrap;overflow-wrap:anywhere;margin:8px 0}.waiting-fact{color:#956e28}.record-time{margin-top:12px;overflow-wrap:anywhere}.report-facts>summary{font-size:11px;font-weight:500;color:#62766a;padding:8px 0}.report-fields{display:grid;grid-template-columns:65px minmax(0,1fr);gap:7px;font-size:12px;line-height:1.7;margin:8px 0}.report-fields dt{color:var(--muted)}.report-fields dd{margin:0;white-space:pre-wrap;overflow-wrap:anywhere}.task-history{margin-top:14px}.task-history>summary{font-size:12px;color:#677483}.project-nav{display:block;padding:10px 8px;line-height:1.7;font-size:12px;overflow-wrap:anywhere}.project-nav:hover{background:#f5f7fa}.project-nav-child{padding:3px 8px 12px 22px;color:var(--muted)}#task-summary{padding:16px;background:#fff;border:1px solid var(--line);border-radius:8px;margin-bottom:16px}.badge{white-space:normal;line-height:1.7}.task-heading-line{flex-wrap:wrap}@media(max-width:760px){.sidebar-footer{display:block}.project-group{padding-left:10px;margin-left:0}.task-grid{display:block}.task-grid>.worker-card{margin-bottom:10px}}
`;
export const dashboardScript = String.raw`
'use strict';
const $ = id => document.getElementById(id);
const labels = { pending: '待启动', running: '执行中', idle: '等待输入', paused: '已暂停', failed: '执行失败' };
-const roleLabels = { coordinator: '协调者', worker: 'Worker', intake: 'intake' };
+const roleLabels = { coordinator: '协调者', worker: 'Worker', intake: '接单请求' };
+const executionLabels = { unbound: '未启动', idle: '空闲', running: '正在执行', completed: '本轮已完成', interrupted: '已中断', failed: '执行失败', unknown: '未知' };
const typeLabels = { INPUT: 'INPUT', PHASE: 'PHASE', NARRATIVE: 'NARRATIVE', TOOL_CALL: 'TOOL CALL', WAITING: 'WAITING', BLOCKER: 'BLOCKER', OUTPUT: 'OUTPUT', EVIDENCE: 'EVIDENCE', RETRY: 'RETRY' };
let snapshot = null, selectedId = null, stream = null, filter = 'all', lastSeq = 0, polling = false, entries = [], detail = null, selectionGeneration = 0;
let detailRetryAt = 0, detailRetryDelay = 1000, detailLoading = false, needsDetail = false;
-const stageDisclosure = new Map();
-const time = value => new Date(value).toLocaleTimeString('zh-CN', { hour12: false });
+const stageDisclosure = new Map(), overviewDisclosure = new Map();
+let snapshotStale = false, snapshotReceivedAt = 0, overviewKey = null;
+const time = value => value === null || value === undefined ? '时间未知' : new Date(value).toLocaleString('zh-CN', { hour12: false });
const node = (tag, className, text) => { const el = document.createElement(tag); if (className) el.className = className; if (text !== undefined) el.textContent = text; return el; };
const allTasks = () => snapshot ? [...new Map([...(snapshot.tasks || []), ...(snapshot.projects || []).flatMap(project => project.tasks || [])].map(task => [task.id, task])).values()] : [];
const projectName = id => snapshot?.projects?.find(project => project.id === id)?.name || '未关联项目';
const statusClass = status => 'dot' + (status === 'running' ? ' green' : status === 'failed' ? ' red' : status === 'paused' ? ' amber' : '');
function connection(ok, text) { $('connection-dot').className = 'dot' + (ok ? ' green' : ' amber'); $('connection-text').textContent = text; }
function showError(message) { $('page-error').hidden = !message; $('page-error').textContent = message; }
-function renderRuntime() { const runtime = snapshot.runtime, age = runtime ? snapshot.now - runtime.lastSeenAt : null, alive = runtime && runtime.status === 'running' && age < Math.max(15000, runtime.intervalMs * 3); $('runtime-dot').className = 'dot' + (alive ? ' green' : ''); $('runtime-status').textContent = alive ? '服务心跳正常' : runtime && runtime.status === 'running' ? '服务心跳已过期' : '服务未运行'; $('runtime-detail').textContent = runtime ? 'PID ' + runtime.pid + ' · 最后心跳 ' + time(runtime.lastSeenAt) : '启动 run 后显示执行服务心跳'; $('data-dir').textContent = snapshot.dataDir; }
-function renderWorkers() { const query = $('search').value.trim().toLowerCase(), status = $('status-filter').value, role = $('role-filter').value, tasks = allTasks().filter(task => (!status || task.status === status) && (!role || task.role === role) && [task.title, task.id, task.role, task.sourceLabel, task.repository].filter(Boolean).join(' ').toLowerCase().includes(query)).sort((a,b) => b.updatedAt - a.updatedAt || a.id.localeCompare(b.id)); $('task-count').textContent = allTasks().length; for (const key of ['running','idle','failed']) $('metric-' + key).textContent = allTasks().filter(task => task.status === key).length; const list = $('task-list'), fragment = document.createDocumentFragment(); for (const task of tasks) { const button = node('button', 'worker-item' + (task.id === selectedId ? ' selected' : '')); const top = node('span', 'worker-top'); top.append(node('i', statusClass(task.status)), node('span', '', labels[task.status] || task.status), node('span', '', ' / ' + roleLabels[task.role])); button.append(top, node('span', 'worker-name', task.title), node('span', 'worker-id', task.id.slice(0, 12))); button.addEventListener('click', () => selectTask(task.id)); fragment.append(button); } if (!tasks.length) fragment.append(node('div', 'sidebar-empty', allTasks().length ? '没有匹配的 Worker' : '还没有 Worker\n新任务会自动出现在这里')); list.replaceChildren(fragment); }
+function renderRuntime() {
+ if (!snapshot) return;
+ const runtime = snapshot.runtime;
+ const now = snapshot.now + Math.max(0, Date.now() - snapshotReceivedAt);
+ const age = runtime ? now - runtime.lastSeenAt : null;
+ const alive = runtime && runtime.status === 'running' && age < Math.max(15000, runtime.intervalMs * 3);
+ $('runtime-dot').className = 'dot' + (alive ? ' green' : '');
+ $('runtime-status').textContent = (alive ? '服务心跳正常' : runtime?.status === 'running' ? '服务心跳已过期' : runtime ? '服务已停止' : '服务心跳未知') + (snapshotStale ? ' · 最后已知记录' : '');
+ $('runtime-detail').textContent = runtime ? '全局 Runtime · PID ' + runtime.pid + ' · 最后心跳 ' + time(runtime.lastSeenAt) : '没有可用的全局 Runtime 心跳记录';
+ $('data-dir').textContent = snapshot.dataDir;
+}
+function disclosure(key, title, open = true) {
+ const el = node('details', 'overview-disclosure');
+ el.open = overviewDisclosure.get(key) ?? open;
+ el.append(node('summary', '', title));
+ el.addEventListener('toggle', () => { if (el.isConnected) overviewDisclosure.set(key, el.open); });
+ return el;
+}
+function taskStatus(task) {
+ return (snapshotStale ? '最后已知 · ' : '') + '任务状态 · ' + (labels[task.status] || '未知') + ' / 执行状态 · ' + (executionLabels[task.executionStatus] || '未知');
+}
+function workFacts(task, location) {
+ const facts = node('div', 'work-facts'), summary = task.workSummary || { kind: 'no-record' };
+ let source = '无可用记录', text = '', at = null;
+ if (summary.kind === 'event') { source = '最近可见事件 · ' + summary.event.label; text = summary.event.text; at = summary.event.createdAt; }
+ else if (summary.kind === 'report') { source = '最近工作汇报'; text = summary.report.currentStep || summary.report.text; at = summary.report.createdAt; }
+ else if (summary.kind === 'waiting') { source = '等待或阻塞原因'; text = summary.text; }
+ facts.append(node('div', 'summary-source', source + ' · ' + time(at)));
+ if (text) facts.append(node('p', 'summary-text', text));
+ const reasons = [...new Set([task.reason, ...((task.requests || []).length ? [] : [task.waitingReason]), ...(task.requests || []).map(request => (request.kind === 'question' ? '等待回答:' : '等待审批:') + request.prompt)].filter(Boolean))];
+ if (reasons.length) facts.append(node('p', 'waiting-fact', reasons.join('\n')));
+ const report = task.latestReport;
+ if (report) {
+ const el = disclosure('report:' + location + ':' + task.id, '工作汇报 · ' + time(report.createdAt), summary.kind === 'report');
+ el.classList.add('report-facts');
+ if (summary.kind !== 'report' || report.currentStep) el.append(node('p', 'summary-text', report.text));
+ const fields = [['当前步骤', report.currentStep], ['下一步', report.nextStep], ['阻塞', report.blockers], ['证据', report.evidence]];
+ const dl = node('dl', 'report-fields');
+ for (const [label, value] of fields) if (value !== undefined) dl.append(node('dt', '', label), node('dd', '', Array.isArray(value) ? value.join('\n') || '无' : value));
+ el.append(dl); facts.append(el);
+ }
+ facts.append(node('div', 'record-time', '当前 Turn · ' + (task.currentTurn || '未知') + '\n任务记录更新 · ' + time(task.updatedAt)));
+ if (task.lifecycle?.kind === 'completed') {
+ facts.append(node('p', 'lifecycle-fact', (task.lifecycle.outcome === 'delivered' ? '已正式交付结束' : '已明确终止') + ' · ' + time(task.lifecycle.at) + '\n' + task.lifecycle.summary));
+ for (const reference of task.lifecycle.deliveryReferences) facts.append(node('p', 'delivery-reference', reference));
+ }
+ return facts;
+}
+function taskCard(task) {
+ const card = node('article', 'worker-card' + (task.id === selectedId ? ' selected' : ''));
+ card.dataset.taskId = task.id;
+ const button = node('button', 'task-open', task.title);
+ button.addEventListener('click', () => selectTask(task.id));
+ card.append(node('div', 'worker-top', (roleLabels[task.role] || '未关联角色') + ' · ' + task.id), button, node('p', 'task-states', taskStatus(task)), workFacts(task, 'overview'));
+ return card;
+}
+function renderWorkers() {
+ const query = $('search').value.trim().toLowerCase(), status = $('status-filter').value, role = $('role-filter').value;
+ const tasks = allTasks();
+ $('task-count').textContent = tasks.length;
+ for (const key of ['running','idle','failed']) $('metric-' + key).textContent = tasks.filter(task => task.lifecycle?.kind !== 'completed' && task.status === key).length;
+ const key = JSON.stringify([snapshot?.projects, tasks, selectedId, query, status, role, snapshotStale]);
+ if (key === overviewKey) return;
+ overviewKey = key;
+ const matches = task => (!status || task.status === status) && (!role || task.role === role) && [task.title, task.id, task.role, task.sourceLabel, task.repository, projectName(task.projectId)].filter(Boolean).join(' ').toLowerCase().includes(query);
+ const appendTasks = (target, values, groupKey) => {
+ const open = values.filter(task => task.lifecycle?.kind !== 'completed'), history = values.filter(task => task.lifecycle?.kind === 'completed');
+ const grid = node('div', 'task-grid');
+ for (const task of open.filter(matches)) grid.append(taskCard(task));
+ if (!grid.childNodes.length) grid.append(node('p', 'sidebar-empty', open.length ? '没有匹配的未结束任务' : '没有未结束任务'));
+ target.append(grid);
+ if (history.length) {
+ const past = disclosure('history:' + groupKey, '已结束历史 · ' + history.length + ' 项', false), list = node('div', 'task-grid');
+ for (const task of history.filter(matches)) list.append(taskCard(task));
+ if (!list.childNodes.length) list.append(node('p', 'sidebar-empty', '没有匹配的历史任务'));
+ past.classList.add('task-history'); past.append(list); target.append(past);
+ }
+ };
+ const fragment = document.createDocumentFragment(), nav = document.createDocumentFragment(), coordinators = new Map();
+ for (const project of snapshot?.projects || []) {
+ const list = coordinators.get(project.coordinatorTaskId) || [];
+ list.push(project); coordinators.set(project.coordinatorTaskId, list);
+ }
+ for (const [id, projects] of coordinators) {
+ const coordinator = tasks.find(task => task.id === id), title = coordinator?.title || id;
+ const group = disclosure('coordinator:' + id, '协调者 · ' + title);
+ group.id = 'coordinator-' + id;
+ group.classList.add('coordinator-group');
+ if (coordinator) group.append(taskCard(coordinator));
+ else group.append(node('p', 'sidebar-empty', '协调者状态未知'));
+ const navLink = node('a', 'project-nav', '协调者 · ' + title); navLink.href = '#' + group.id; nav.append(navLink);
+ for (const project of projects) {
+ const area = disclosure('project:' + project.id, '项目 · ' + project.name);
+ area.classList.add('project-group'); area.dataset.projectId = project.id;
+ area.append(node('p', 'project-directory', project.directory));
+ appendTasks(area, project.tasks.filter(task => task.id !== id), project.id);
+ group.append(area);
+ const link = node('a', 'project-nav project-nav-child', project.name); link.href = '#' + group.id; nav.append(link);
+ }
+ fragment.append(group);
+ }
+ const associated = new Set((snapshot?.projects || []).flatMap(project => project.tasks.map(task => task.id)));
+ const unassociated = tasks.filter(task => !associated.has(task.id));
+ if (unassociated.length) {
+ const group = disclosure('unassociated', '未关联协调项目 · ' + unassociated.length + ' 项');
+ group.id = 'unassociated'; appendTasks(group, unassociated, 'unassociated'); fragment.append(group);
+ const link = node('a', 'project-nav', '未关联协调项目'); link.href = '#unassociated'; nav.append(link);
+ }
+ if (!fragment.childNodes.length) fragment.append(node('p', 'sidebar-empty', '没有可用的协调项目或任务记录'));
+ $('project-overview').replaceChildren(fragment); $('task-list').replaceChildren(nav);
+}
function currentTask() { return allTasks().find(task => task.id === selectedId) || detail?.task || null; }
-function renderMetadata() { const task = currentTask(); if (!task) return; $('meta-role').textContent = roleLabels[task.role] || 'Worker'; $('meta-status').textContent = labels[task.status] || task.status; $('meta-status-dot').className = statusClass(task.status); const resources = task.resources || []; const values = [['Worker ID', task.id], ['项目', task.projectId ? projectName(task.projectId) : '未关联项目'], ['Thread', task.threadId], ['Turn', task.turnId || task.currentTurn], ['任务群', task.chatId], ['仓库', task.repository], ['当前工作', task.completion?.kind === 'completed' ? '已记录完成,仍可继续' : '处理中'], ['完成记录', (task.completionHistory || []).map(item => time(item.at) + ' · ' + item.summary).join('\n') || '尚无记录'], ['资源清理', (task.cleanup || []).map(item => item.scopeId + ' · ' + ({ pending: '等待清理', removed: '已清理', protected: '受保护', retained: '已保留' }[item.state] || item.state) + (item.reason ? ' · ' + item.reason : '')).join('\n') || '未请求清理'], ...resources.map(resource => [resource.kind === 'project' ? '项目工作区' : '仓库工作区', resource.workspace]), ['更新时间', time(task.updatedAt)]]; const dl = document.createDocumentFragment(); for (const [label, value] of values) { dl.append(node('dt','',label), node('dd','',value || '尚未关联')); } $('metadata-list').replaceChildren(dl); }
-function renderTaskHeader() { const task = currentTask(); $('empty').hidden = !!task; $('task-panel').hidden = !task; if (!task) return; $('source-kind').textContent = task.sourceKind === 'github' ? 'GITHUB ISSUE' : task.sourceKind === 'cli' ? 'CLI SUBMISSION' : 'WORKER TASK'; $('task-badge').className = 'badge ' + task.status; $('task-badge').textContent = labels[task.status] || task.status; $('task-title').textContent = task.title; $('task-id').textContent = task.id; $('updated-at').textContent = '状态更新 ' + time(task.updatedAt); const source = $('source-link'); source.hidden = !task.sourceUrl; if (task.sourceUrl && /^https?:\/\//.test(task.sourceUrl)) source.href = task.sourceUrl; else source.removeAttribute('href'); const alerts = []; if (task.reason) alerts.push(task.reason); for (const request of task.requests || []) alerts.push((request.kind === 'question' ? '等待回答:' : '等待审批:') + request.prompt); $('task-alert').hidden = !alerts.length; $('task-alert').textContent = alerts.join('\n'); $('task-alert').className = 'banner' + (task.status === 'failed' ? ' error' : ''); renderMetadata(); }
+function renderMetadata() { const task = currentTask(); if (!task) return; $('meta-role').textContent = roleLabels[task.role] || '未关联角色'; $('meta-status').textContent = taskStatus(task); $('meta-status-dot').className = statusClass(task.status); const resources = task.resources || []; const values = [['Worker ID', task.id], ['项目', task.projectId ? projectName(task.projectId) : '未关联项目'], ['Thread', task.threadId], ['Turn', task.turnId || task.currentTurn], ['任务群', task.chatId], ['仓库', task.repository], ['当前工作', task.completion?.kind === 'completed' ? '已记录完成,仍可继续' : '处理中'], ['完成记录', (task.completionHistory || []).map(item => time(item.at) + ' · ' + item.summary).join('\n') || '尚无记录'], ['资源清理', (task.cleanup || []).map(item => item.scopeId + ' · ' + ({ pending: '等待清理', removed: '已清理', protected: '受保护', retained: '已保留' }[item.state] || item.state) + (item.reason ? ' · ' + item.reason : '')).join('\n') || '未请求清理'], ...resources.map(resource => [resource.kind === 'project' ? '项目工作区' : '仓库工作区', resource.workspace]), ['任务记录更新', time(task.updatedAt)]]; const dl = document.createDocumentFragment(); for (const [label, value] of values) { dl.append(node('dt','',label), node('dd','',value || '尚未关联')); } $('metadata-list').replaceChildren(dl); }
+function renderTaskHeader() { const task = currentTask(); $('empty').hidden = !!task; $('task-panel').hidden = !task; if (!task) return; $('source-kind').textContent = task.sourceKind === 'github' ? 'GITHUB ISSUE' : task.sourceKind === 'cli' ? 'CLI SUBMISSION' : 'WORKER TASK'; $('task-badge').className = 'badge ' + task.status; $('task-badge').textContent = taskStatus(task); $('task-title').textContent = task.title; $('task-id').textContent = task.id; $('updated-at').textContent = '任务记录更新 ' + time(task.updatedAt); const source = $('source-link'); source.hidden = !task.sourceUrl; if (task.sourceUrl && /^https?:\/\//.test(task.sourceUrl)) source.href = task.sourceUrl; else source.removeAttribute('href'); const alerts = []; if (task.reason) alerts.push(task.reason); for (const request of task.requests || []) alerts.push((request.kind === 'question' ? '等待回答:' : '等待审批:') + request.prompt); $('task-alert').hidden = !alerts.length; $('task-alert').textContent = alerts.join('\n'); $('task-alert').className = 'banner' + (task.status === 'failed' ? ' error' : ''); $('task-summary').replaceChildren(workFacts(task, 'detail')); renderMetadata(); }
function normalizeEntry(entry) { return { ...entry, type: entry.type || (entry.kind === 'agent_message' ? 'OUTPUT' : entry.kind === 'agent_delta' ? 'NARRATIVE' : entry.kind?.startsWith('tool_') ? 'TOOL_CALL' : entry.kind === 'error' ? 'BLOCKER' : 'PHASE') }; }
function collapse(list) { return list; }
function renderTimeline() { const stages = new Set(entries.map(entry => entry.phase || (entry.turnId ? 'TURN ' + entry.turnId.slice(0,8) : '执行记录'))); for (const key of stageDisclosure.keys()) if (!stages.has(key)) stageDisclosure.delete(key); const target = $('output'), visible = collapse(entries.filter(entry => filter === 'all' || entry.type === filter)); if (!visible.length) { target.replaceChildren(node('div','sidebar-empty', entries.length ? '没有匹配的事件' : '等待执行输出')); $('event-count').textContent = '0 条事件'; return; } const groups = []; for (const entry of visible) { const key = entry.phase || (entry.turnId ? 'TURN ' + entry.turnId.slice(0,8) : '执行记录'); let group = groups.at(-1); if (!group || group.key !== key) { group = { key, entries: [] }; groups.push(group); } group.entries.push(entry); } const fragment = document.createDocumentFragment(); for (const group of groups) { const stage = document.createElement('details'); stage.className = 'stage'; stage.open = stageDisclosure.get(group.key) ?? true; stage.addEventListener('toggle', () => stageDisclosure.set(group.key, stage.open)); const summary = node('summary','',group.key); stage.append(summary); for (const entry of group.entries) { const el = node('article','event'); el.dataset.type = entry.type; const head = node('div','event-header'); head.append(node('span','event-type',typeLabels[entry.type] || entry.type), node('span','',entry.label || ''), node('time','',entry.createdAt === null ? '时间未知' : time(entry.createdAt)), node('code','',entry.turnId || '')); el.append(head,node('pre','',entry.text || '')); if (entry.collapsedCount > 1) el.append(node('div','collapsed',entry.collapsedCount + ' 条相邻叙事已折叠')); stage.append(el); } fragment.append(stage); } target.replaceChildren(fragment); $('event-count').textContent = visible.length + ' 条事件'; if ($('auto-scroll').checked) target.scrollTop = target.scrollHeight; }
-function mergeEvent(event) { if (event.taskId !== selectedId) return; const id = 'event:' + event.key; const index = entries.findIndex(entry => entry.id === id); const next = normalizeEntry({ ...event, id }); if (index < 0) entries.push(next); else entries[index] = next; entries = entries.slice(-500); renderTimeline(); $('last-event').textContent = '最后事件 ' + time(event.createdAt); }
+function mergeEvent(event) { if (event.taskId !== selectedId || event.threadId !== detail?.threadId) return; const id = 'event:' + event.key; const index = entries.findIndex(entry => entry.id === id); const next = normalizeEntry({ ...event, id }); if (index < 0) entries.push(next); else entries[index] = next; entries = entries.slice(-500); renderTimeline(); $('last-event').textContent = '最后事件 ' + time(event.createdAt); }
function retryDetail() { needsDetail = true; detailRetryAt = Date.now() + detailRetryDelay; detailRetryDelay = Math.min(detailRetryDelay * 2, 30000); }
async function loadDetail(id, generation) {
const response = await fetch('/api/tasks/' + encodeURIComponent(id));
@@ -63,17 +177,25 @@ async function loadDetail(id, generation) {
entries = (detail.history?.kind === 'unavailable' ? [...new Map([...entries, ...timeline].map(entry => [entry.id, entry])).values()] : timeline).slice(-500);
lastSeq = detail.cursor;
if (detail.history?.kind === 'unavailable') retryDetail(); else { needsDetail = false; detailRetryDelay = 1000; }
- showError(detail.history?.kind === 'unavailable' ? 'Codex 历史暂不可用;业务记录和实时更新仍可查看' : '');
+ showError(detail.history?.kind === 'unavailable' ? (detail.history.reason || 'Codex 历史暂不可用') + ';业务记录仍可查看' : '');
renderTaskHeader(); renderTimeline(); renderHistory(); renderDiagnostics(); return true;
}
-function renderHistory() { const target = $('history'); if (!detail) return; const fragment = document.createDocumentFragment(); for (const input of detail.inputs || []) fragment.append(node('article','history-message',input.text)); for (const output of detail.outputs || []) fragment.append(node('article','history-message',output.text)); if (!fragment.childNodes.length) fragment.append(node('div','sidebar-empty','还没有消息')); target.replaceChildren(fragment); }
+function renderHistory() { const target = $('history'); if (!detail) { target.replaceChildren(); return; } const fragment = document.createDocumentFragment(); for (const input of detail.inputs || []) fragment.append(node('article','history-message',input.text)); for (const output of detail.outputs || []) fragment.append(node('article','history-message',output.text)); if (!fragment.childNodes.length) fragment.append(node('div','sidebar-empty','还没有消息')); target.replaceChildren(fragment); }
function renderDiagnostics() { const target = $('diagnostics'), rows = (detail?.diagnostics || []); if (!rows.length) { target.replaceChildren(node('div','sidebar-empty','没有诊断异常')); return; } const fragment = document.createDocumentFragment(); for (const row of rows) { const el = node('div','diagnostic'); el.append(node('time','',time(row.created_at) + ' · ' + row.scope),node('span','',row.message)); fragment.append(el); } target.replaceChildren(fragment); }
async function selectTask(id, recovering = false) {
const generation = ++selectionGeneration;
if (stream) stream.close(); stream = null;
selectedId = id; detailLoading = true;
if (!recovering) { detail = null; entries = []; lastSeq = 0; stageDisclosure.clear(); needsDetail = false; detailRetryDelay = 1000; }
+ else if (detail?.threadId !== currentTask()?.threadId) {
+ detail = detail ? { ...detail, threadId: currentTask()?.threadId, history: { kind: 'unavailable', reason: 'Thread 已变更,正在重新读取 Codex 历史' }, timeline: [], events: [] } : null;
+ entries = []; lastSeq = 0; stageDisclosure.clear();
+ connection(false, 'Thread 已变更,正在重新读取'); $('stream-status').textContent = 'RECONNECTING · 重新读取执行记录';
+ showError('Thread 已变更,正在重新读取 Codex 历史;业务记录仍可查看');
+ }
+ renderTimeline(); renderHistory(); renderDiagnostics();
renderWorkers(); renderTaskHeader();
+ if (!recovering) $('task-panel').scrollIntoView({ behavior: 'smooth', block: 'start' });
$('event-count').textContent = entries.length + ' 条事件'; $('last-event').textContent = '只保留可见执行说明';
try { if (!await loadDetail(id, generation) || generation !== selectionGeneration || selectedId !== id) return; }
catch (error) { if (generation !== selectionGeneration || selectedId !== id) return; showError(error.message); retryDetail(); return; }
@@ -82,25 +204,34 @@ async function selectTask(id, recovering = false) {
stream = new EventSource('/api/events?taskId=' + encodeURIComponent(id) + '&after=' + encodeURIComponent(lastSeq) + '&threadId=' + encodeURIComponent(detail.threadId || ''));
stream.onopen = () => { if (generation !== selectionGeneration || selectedId !== id) return; connection(true,'实时连接已建立'); $('stream-status').textContent = 'LIVE · 接收执行事件'; };
stream.onerror = () => { if (generation !== selectionGeneration || selectedId !== id) return; connection(false,'连接中断,正在重连'); $('stream-status').textContent = 'RECONNECTING · 自动续接'; };
- stream.addEventListener('reset', () => { if (generation !== selectionGeneration || selectedId !== id) return; if (stream) stream.close(); stream = null; if (!needsDetail) retryDetail(); });
+ stream.addEventListener('reset', () => {
+ if (generation !== selectionGeneration || selectedId !== id) return;
+ ++selectionGeneration;
+ stream.close(); stream = null;
+ detail = { ...detail, history: { kind: 'unavailable', reason: '执行记录已重置,正在重新读取 Codex 历史' }, timeline: [], events: [] };
+ entries = []; stageDisclosure.clear(); renderTimeline(); renderHistory();
+ connection(false, '执行记录已重置,正在重新读取'); $('stream-status').textContent = 'RECONNECTING · 重新读取执行记录';
+ showError(detail.history.reason + ';业务记录仍可查看');
+ if (!needsDetail) retryDetail();
+ });
stream.addEventListener('execution', message => { if (generation !== selectionGeneration || selectedId !== id) return; try { mergeEvent(JSON.parse(message.data)); } catch (error) { showError('事件读取失败:' + error.message); } });
}
async function refresh() {
if (polling) return; polling = true;
try {
const response = await fetch('/api/snapshot'); if (!response.ok) throw new Error('读取看板失败 · HTTP ' + response.status);
- snapshot = await response.json();
- showError(detail?.history?.kind === 'unavailable' ? 'Codex 历史暂不可用;业务记录和实时更新仍可查看' : ''); renderRuntime(); renderWorkers();
+ snapshot = await response.json(); snapshotStale = false; snapshotReceivedAt = Date.now();
+ showError(detail?.history?.kind === 'unavailable' ? (detail.history.reason || 'Codex 历史暂不可用') + ';业务记录仍可查看' : ''); renderRuntime(); renderWorkers();
if (selectedId && !allTasks().some(task => task.id === selectedId)) { if (stream) stream.close(); stream = null; selectedId = null; detail = null; entries = []; needsDetail = false; ++selectionGeneration; detailLoading = false; }
- if (!selectedId && allTasks().length) await selectTask(allTasks()[0].id);
- else if (selectedId && !detailLoading && ((needsDetail && Date.now() >= detailRetryAt) || (detail && allTasks().find(task => task.id === selectedId)?.threadId !== detail.threadId))) await selectTask(selectedId, true);
+ if (selectedId && detail && allTasks().find(task => task.id === selectedId)?.threadId !== detail.threadId) await selectTask(selectedId, true);
+ else if (selectedId && !detailLoading && needsDetail && Date.now() >= detailRetryAt) await selectTask(selectedId, true);
else renderTaskHeader();
if (!selectedId) connection(true,'看板已连接');
- } catch (error) { connection(false,'连接失败'); showError(error.message); }
+ } catch (error) { snapshotStale = true; connection(false,'数据不可用 · 最后已知状态'); showError(error.message + (snapshot ? ';以下显示最后已知状态' : ';尚无可用记录')); renderRuntime(); renderWorkers(); renderTaskHeader(); }
finally { polling = false; }
}
$('search').addEventListener('input', renderWorkers); $('status-filter').addEventListener('change', renderWorkers); $('role-filter').addEventListener('change', renderWorkers);
for (const button of document.querySelectorAll('[data-filter]')) button.addEventListener('click', () => { filter = button.dataset.filter; for (const option of document.querySelectorAll('[data-filter]')) option.classList.toggle('active', option === button); renderTimeline(); });
for (const name of ['live','history','diagnostics']) $('tab-' + name).addEventListener('click', () => { for (const view of ['live','history','diagnostics']) { $('tab-' + view).classList.toggle('active', view === name); $(view === 'live' ? 'output' : view).hidden = view !== name; } $('live-toolbar').hidden = name !== 'live'; });
-$('copy').addEventListener('click', async () => { const target = !$('history').hidden ? $('history') : !$('diagnostics').hidden ? $('diagnostics') : $('output'); try { await navigator.clipboard.writeText(target.innerText); $('copy').textContent = '已复制'; } catch { $('copy').textContent = '复制失败'; } window.setTimeout(() => $('copy').textContent = '复制记录', 1500); }); window.addEventListener('beforeunload', () => stream && stream.close()); refresh(); window.setInterval(refresh, 1000);
+$('copy').addEventListener('click', async () => { const target = !$('history').hidden ? $('history') : !$('diagnostics').hidden ? $('diagnostics') : $('output'); try { await navigator.clipboard.writeText(target.innerText); $('copy').textContent = '已复制'; } catch { $('copy').textContent = '复制失败'; } window.setTimeout(() => $('copy').textContent = '复制记录', 1500); }); window.addEventListener('beforeunload', () => stream && stream.close()); refresh(); window.setInterval(() => { renderRuntime(); refresh(); }, 1000);
`;
diff --git a/src/dashboard-reader.ts b/src/dashboard-reader.ts
index 647a663..9a1a16b 100644
--- a/src/dashboard-reader.ts
+++ b/src/dashboard-reader.ts
@@ -1,5 +1,5 @@
-import { taskCloseoutSchema } from './task-closeout.js';
import { LiveExecution, type ExecutionObservation } from './live-execution.js';
+import { readTaskCloseout } from './task-closeout.js';
import { intakeRouteSchema, presentTaskSource, type InputProvenance, type ReportEscalation, type ReportRouting, type ReportSource, type Task, type TaskResource } from './domain.js';
import { ProjectLedger, type ProjectState } from './project.js';
import { Store, type Inbox } from './store.js';
@@ -70,10 +70,16 @@ export interface DashboardTimelineEntry {
phase: string | null;
}
+export type DashboardWorkSummary =
+ | { kind: 'event'; event: DashboardExecutionEvent }
+ | { kind: 'report'; report: DashboardReport }
+ | { kind: 'waiting'; text: string; createdAt: null }
+ | { kind: 'no-record' };
+
export interface ProjectTaskCard {
id: string;
- projectId: string;
- role: 'coordinator' | 'worker' | 'intake';
+ projectId: string | null;
+ role: 'coordinator' | 'worker' | 'intake' | null;
title: string;
sourceLabel: string;
sourceKind: Task['source']['kind'];
@@ -82,6 +88,9 @@ export interface ProjectTaskCard {
issueId: string | null;
status: Task['status'];
executionStatus: Task['executionStatus'];
+ reason: string | null;
+ lifecycle: ReturnType['lifecycle'];
+ workSummary: DashboardWorkSummary;
threadId: string | null;
turnId: string | null;
chatId: string | null;
@@ -94,8 +103,8 @@ export interface ProjectTaskCard {
createdAt: number;
updatedAt: number;
latestReport: DashboardReport | null;
- completion: z.infer['lifecycle'];
- completionHistory: z.infer['completionHistory'];
+ completion: ReturnType['lifecycle'];
+ completionHistory: ReturnType['completionHistory'];
cleanup: { operationId: string; kind: string; scopeId: string; state: string; reason: string | null; directoryRemoved: boolean; branchRemoved: boolean }[];
}
@@ -160,13 +169,12 @@ function dashboardEvent(event: VisibleExecution): DashboardExecutionEvent | null
return { ...event, type: eventType(event), text: boundedDashboardText(text) } as DashboardExecutionEvent;
}
-type DashboardOwnership = { projectId: string; role: ProjectTaskCard['role'] };
+type DashboardOwnership = { projectId: string; role: NonNullable };
interface DashboardContext {
tasks: Task[];
states: Map;
ownership: Map;
reportsByTask: Map;
- latestActivity: Map;
}
const membershipMetadataSchema = z.strictObject({ projectId: z.string(), role: z.enum(['coordinator', 'worker']) });
@@ -219,7 +227,8 @@ export class ProjectDashboardReader {
const list = reportsByTask.get(input.provenance.taskId) ?? [];
list.push(report); reportsByTask.set(input.provenance.taskId, list);
}
- return { tasks, states, ownership, reportsByTask, latestActivity: new Map(tasks.flatMap(task => { const event = this.execution.current(task.id, task.threadId).at(-1); return event ? [[task.id, event]] : []; })) };
+ for (const reports of reportsByTask.values()) reports.sort((a, b) => a.createdAt - b.createdAt);
+ return { tasks, states, ownership, reportsByTask };
}
private reportsForTask(taskId: string, context: DashboardContext): DashboardReport[] {
@@ -229,45 +238,50 @@ export class ProjectDashboardReader {
return context.reportsByTask.get(taskId) ?? [];
}
- private card(task: Task, projectId: string, role: ProjectTaskCard['role'], context: DashboardContext, issueId: string | null = null): ProjectTaskCard {
- const latestActivity = context.latestActivity.get(task.id) ?? null;
+ private card(task: Task, context: DashboardContext, issueId: string | null = null): ProjectTaskCard {
+ const ownership = context.ownership.get(task.id);
+ const latestActivity = this.execution.latestPublished(task.id, task.threadId);
const visibleActivity = latestActivity ? dashboardEvent(latestActivity) : null;
const reports = this.reportsForTask(task.id, context);
const waiting = task.requests.map(request => `${request.kind}: ${boundedDashboardText(request.prompt)}`);
+ const waitingReason = waiting[0] ?? (task.reason ? boundedDashboardText(task.reason) : null) ?? (task.recovery.lastError ? boundedDashboardText(task.recovery.lastError) : null);
+ const latestReport = reports.at(-1) ?? null;
+ const workSummary: DashboardWorkSummary = visibleActivity ? { kind: 'event', event: visibleActivity }
+ : latestReport ? { kind: 'report', report: latestReport }
+ : waitingReason ? { kind: 'waiting', text: waitingReason, createdAt: null } : { kind: 'no-record' };
const source = presentTaskSource(task.source, 200);
const repository = task.source.kind === 'github' ? task.source.issue.repository : task.resources.find(resource => resource.kind !== 'project')?.repository.name ?? null;
- const rawCloseout = this.store.meta(`task-closeout:${task.id}`);
- const closeout = rawCloseout ? taskCloseoutSchema.parse(JSON.parse(rawCloseout)) : null;
+ const closeout = readTaskCloseout(this.store, task.id);
return {
- completion: closeout?.lifecycle ?? { kind: 'open' }, completionHistory: closeout?.completionHistory ?? [],
- cleanup: closeout?.operations.flatMap(operation => operation.targets.map(target => ({ operationId: operation.id, kind: operation.kind, scopeId: target.scope.id, state: target.state, reason: target.reason, directoryRemoved: target.directoryRemoved, branchRemoved: target.branchRemoved }))) ?? [],
- id: task.id, projectId, role, title: source.title, sourceLabel: source.label, sourceKind: task.source.kind, sourceUrl: source.url, repository,
+ completion: closeout.lifecycle,
+ completionHistory: closeout.completionHistory,
+ cleanup: closeout.operations.flatMap(operation => operation.targets.map(target => ({ operationId: operation.id, kind: operation.kind, scopeId: target.scope.id, state: target.state, reason: target.reason, directoryRemoved: target.directoryRemoved, branchRemoved: target.branchRemoved }))),
+ id: task.id, projectId: ownership?.projectId ?? null, role: ownership?.role ?? null, title: source.title, sourceLabel: source.label, sourceKind: task.source.kind, sourceUrl: source.url, repository,
issueId: issueId ?? (task.source.kind === 'github' ? task.source.issue.id : null),
- status: task.status, executionStatus: task.executionStatus, currentTurn: task.turnId ?? visibleActivity?.turnId ?? null,
+ status: task.status, executionStatus: task.executionStatus, currentTurn: task.turnId,
+ reason: task.reason ? boundedDashboardText(task.reason) : null, lifecycle: closeout.lifecycle, workSummary,
threadId: task.threadId, turnId: task.turnId, chatId: task.chatId, resources: dashboardResources(task.resources),
- latestActivity: visibleActivity, waitingReason: waiting[0] ?? (task.reason ? boundedDashboardText(task.reason) : null) ?? (task.recovery.lastError ? boundedDashboardText(task.recovery.lastError) : null), requests: task.requests.map(request => ({ kind: request.kind, prompt: boundedDashboardText(request.prompt) })),
- recovery: task.recovery, createdAt: task.createdAt, updatedAt: task.updatedAt, latestReport: reports.at(-1) ?? null,
+ latestActivity: visibleActivity, waitingReason, requests: task.requests.map(request => ({ kind: request.kind, prompt: boundedDashboardText(request.prompt) })),
+ recovery: task.recovery, createdAt: task.createdAt, updatedAt: task.updatedAt, latestReport,
};
}
- projects(tasks = this.store.tasks()): ProjectDashboard[] {
+ overview(tasks = this.store.tasks()): { tasks: ProjectTaskCard[]; projects: ProjectDashboard[] } {
const context = this.context(tasks);
- const cards = new Map();
- for (const task of tasks) {
+ const projected = tasks.map(task => {
const ownership = context.ownership.get(task.id);
- if (!ownership) continue;
- const state = context.states.get(ownership.projectId);
- if (!state) continue;
- const issueId = state.members.find(member => member.taskId === task.id)?.issueId ?? null;
- const list = cards.get(state.id) ?? [];
- list.push(this.card(task, state.id, ownership.role, context, issueId)); cards.set(state.id, list);
- }
- return [...context.states.values()].sort((a, b) => a.name.localeCompare(b.name)).map(state => ({
+ const state = ownership ? context.states.get(ownership.projectId) : null;
+ return this.card(task, context, state?.members.find(member => member.taskId === task.id)?.issueId ?? null);
+ });
+ const projects = [...context.states.values()].sort((a, b) => a.name.localeCompare(b.name)).map(state => ({
id: state.id, name: state.name, directory: state.directory, coordinatorTaskId: state.coordinatorTaskId,
- members: state.members, tasks: (cards.get(state.id) ?? []).sort((a, b) => b.updatedAt - a.updatedAt || a.id.localeCompare(b.id)),
+ members: state.members, tasks: projected.filter(task => task.projectId === state.id).sort((a, b) => b.updatedAt - a.updatedAt || a.id.localeCompare(b.id)),
}));
+ return { tasks: projected, projects };
}
+ projects(tasks = this.store.tasks()): ProjectDashboard[] { return this.overview(tasks).projects; }
+
project(projectId: string): ProjectDashboard | null { return this.projects().find(project => project.id === projectId) ?? null; }
timeline(taskId: string, events: VisibleExecution[] = [], limit = 500): DashboardTimelineEntry[] {
@@ -313,7 +327,7 @@ export class ProjectDashboardReader {
const project = ownership ? context.states.get(ownership.projectId) : null;
const reports = this.reportsForTask(taskId, context);
return {
- task: ownership && project ? this.card(task, project.id, ownership.role, context, project.members.find(member => member.taskId === taskId)?.issueId ?? null) : null,
+ task: this.card(task, context, project?.members.find(member => member.taskId === taskId)?.issueId ?? null),
threadId: task.threadId, projectId: ownership?.projectId ?? null,
inputs: this.store.inputs(taskId), outputs: this.store.outputs(taskId), cursor: observation.cursor, history: observation.history, events: observation.entries.flatMap(event => { const visible = dashboardEvent(event); return visible ? [visible] : []; }), timeline: this.timeline(taskId, observation.entries), reports,
diagnostics: this.store.diagnostics().filter(row => row.scope === taskId || row.scope.endsWith(':' + taskId)),
diff --git a/src/dashboard.ts b/src/dashboard.ts
index 53cf964..3ac4d28 100644
--- a/src/dashboard.ts
+++ b/src/dashboard.ts
@@ -5,8 +5,8 @@ import { join } from 'node:path';
import { hostname, networkInterfaces } from 'node:os';
import { z } from 'zod';
import { Store } from './store.js';
-import { boundedDashboardText, dashboardResources, ProjectDashboardReader } from './dashboard-reader.js';
-import { errorMessage, presentTaskSource } from './domain.js';
+import { boundedDashboardText, ProjectDashboardReader } from './dashboard-reader.js';
+import { errorMessage } from './domain.js';
import { dashboardHtml, dashboardCss, dashboardScript } from './dashboard-page.js';
const heartbeatSchema = z.object({ pid: z.number(), lastSeenAt: z.number(), intervalMs: z.number(), status: z.enum(['running', 'stopped']) });
@@ -19,13 +19,11 @@ export async function startDashboard(options: { execution?: LiveExecution; dataD
const clients = new Set();
let dashboardReader: ProjectDashboardReader | null = null;
const readerFor = (db: Store) => dashboardReader ??= new ProjectDashboardReader(db, execution);
- let readModelCache: { version: number; cursor: string; expiresAt: number; tasks: ReturnType; projects: ReturnType; diagnostics: ReturnType } | null = null;
+ let readModelCache: { version: number; cursor: string; expiresAt: number; tasks: ReturnType['tasks']; projects: ReturnType; diagnostics: ReturnType } | null = null;
const readStore = () => {
if (!store && existsSync(join(options.dataDir, 'tasks.sqlite'))) store = new Store(options.dataDir, { readOnly: true });
return store;
};
- // Open the read-only connection before listening so the first API request measures the
- // dashboard query rather than SQLite connection and schema setup.
readStore();
const json = (response: ServerResponse, status: number, value: unknown) => {
response.writeHead(status, { 'content-type': 'application/json; charset=utf-8' });
@@ -36,8 +34,7 @@ export async function startDashboard(options: { execution?: LiveExecution; dataD
const db = readStore();
const version = db?.dataVersion() ?? 0;
if (readModelCache && readModelCache.version === version && readModelCache.cursor === execution.cursor && readModelCache.expiresAt > now) return readModelCache;
- const tasks = db?.tasks() ?? [];
- const projects = db ? readerFor(db).projects(tasks) : [];
+ const { tasks, projects } = db ? readerFor(db).overview() : { tasks: [], projects: [] };
const diagnostics = db?.diagnostics() ?? [];
readModelCache = { version, cursor: execution.cursor, expiresAt: now + 250, tasks, projects, diagnostics };
return readModelCache;
@@ -50,16 +47,7 @@ export async function startDashboard(options: { execution?: LiveExecution; dataD
const heartbeat = rawHeartbeat ? heartbeatSchema.safeParse(JSON.parse(rawHeartbeat)) : null;
const value = {
dataDir: options.dataDir, now, runtime: heartbeat?.success ? heartbeat.data : null,
- tasks: model.tasks.map(task => ({
- id: task.id, title: presentTaskSource(task.source, 200).title,
- sourceLabel: presentTaskSource(task.source, 200).label,
- sourceKind: task.source.kind, sourceUrl: task.source.kind === 'github' ? task.source.issue.url : null,
- status: task.status, executionStatus: task.executionStatus, reason: task.reason,
- threadId: task.threadId, turnId: task.turnId, chatId: task.chatId,
- createdAt: task.createdAt, updatedAt: task.updatedAt, recovery: task.recovery,
- requests: task.requests.map(request => ({ kind: request.kind, prompt: boundedDashboardText(request.prompt) })),
- resources: dashboardResources(task.resources),
- })), projects: model.projects, diagnostics: model.diagnostics,
+ tasks: model.tasks, projects: model.projects, diagnostics: model.diagnostics,
};
return value;
};
diff --git a/src/live-execution.ts b/src/live-execution.ts
index f2ff98f..70df116 100644
--- a/src/live-execution.ts
+++ b/src/live-execution.ts
@@ -79,6 +79,9 @@ export class LiveExecution {
current(taskId: string, threadId?: string | null): VisibleExecution[] {
return [...this.items.values()].flatMap(item => item.kind === 'snapshot' && item.event.taskId === taskId && (threadId === undefined || item.event.threadId === threadId) ? [item.event] : []);
}
+ latestPublished(taskId: string, threadId: string | null): VisibleExecution | null {
+ return this.changes.findLast(change => change.event.taskId === taskId && change.event.threadId === threadId)?.event ?? null;
+ }
revision(taskId: string, threadId?: string | null): number {
return Math.max(0, ...[...this.items.values()].map(item => item.kind === 'snapshot' ? item.event : item).filter(item => item.taskId === taskId && (threadId === undefined || item.threadId === threadId)).map(item => item.seq));
}
diff --git a/src/task-closeout.ts b/src/task-closeout.ts
index 3e4c301..749e67e 100644
--- a/src/task-closeout.ts
+++ b/src/task-closeout.ts
@@ -31,6 +31,10 @@ export const taskCloseoutSchema = z.strictObject({ version: z.number().default(1
lifecycle: z.discriminatedUnion('kind', [z.strictObject({ kind: z.literal('open') }), completionSchema]),
scopes: z.array(scopeSchema), operations: z.array(operationSchema), predecessorTaskId: z.string().nullable() });
type Ledger = z.infer;
+export function readTaskCloseout(store: Store, taskId: string): Ledger {
+ const value = store.meta(`task-closeout:${taskId}`);
+ return value ? taskCloseoutSchema.parse(JSON.parse(value)) : { version: 2, completionHistory: [], taskId, projectId: null, lifecycle: { kind: 'open' }, scopes: [], operations: [], predecessorTaskId: null };
+}
type Scope = z.infer;
type Target = z.infer;
export type CloseoutOperation = z.infer;
@@ -129,8 +133,7 @@ export class TaskCloseout {
protectedPaths(): string[];
}) { this.migrate(); }
read(taskId: string): Ledger {
- const value = this.store.meta(`task-closeout:${taskId}`);
- return value ? taskCloseoutSchema.parse(JSON.parse(value)) : { version: 2, completionHistory: [], taskId, projectId: null, lifecycle: { kind: 'open' }, scopes: [], operations: [], predecessorTaskId: null };
+ return readTaskCloseout(this.store, taskId);
}
private save(value: Ledger) { this.store.setMeta(`task-closeout:${value.taskId}`, JSON.stringify(taskCloseoutSchema.parse(value))); }
private status(taskId: string) {
diff --git a/test/dashboard-coordinator.test.ts b/test/dashboard-coordinator.test.ts
index af5556c..ea34897 100644
--- a/test/dashboard-coordinator.test.ts
+++ b/test/dashboard-coordinator.test.ts
@@ -5,10 +5,11 @@ import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { test } from 'node:test';
import { startDashboard } from '../src/dashboard.js';
-import { ProjectDashboardReader } from '../src/dashboard-reader.js';
+import { ProjectDashboardReader, type ProjectDashboard, type ProjectTaskCard } from '../src/dashboard-reader.js';
import { Store } from '../src/store.js';
import { ProjectLedger } from '../src/project.js';
import { repositorySchema, taskSchema, type Task } from '../src/domain.js';
+import { taskCloseoutSchema } from '../src/task-closeout.js';
function task(id: string, title: string, purpose: 'execution' | 'intake' = 'execution', resources: Task['resources'] = []) {
const now = Date.now();
@@ -53,6 +54,108 @@ test('dashboard resource DTO keeps project card repositories usable by the clien
assert.deepEqual(snapshotTask.resources, [{ repository: 'example/project', workspace: '/tmp/worker-workspace' }]);
});
+test('overview retains every explicit coordinator, open task state and formal completion outcome', async t => {
+ const root = await mkdtemp(join(tmpdir(), 'dashboard-overview-lifecycle-'));
+ const store = new Store(root), source = new ExecutionFixture();
+ t.after(async () => { store.close(); await rm(root, { recursive: true, force: true }); });
+ const coordinator = { ...task('coordinator', 'Coordinator A'), status: 'idle', executionStatus: 'idle' } satisfies Task;
+ const empty = { ...task('empty-coordinator', 'Coordinator B'), status: 'paused', executionStatus: 'unknown' } satisfies Task;
+ const states = [
+ { id: 'pending', status: 'pending', executionStatus: 'unbound' },
+ { id: 'running', status: 'running', executionStatus: 'running' },
+ { id: 'idle', status: 'idle', executionStatus: 'idle' },
+ { id: 'paused', status: 'paused', executionStatus: 'interrupted' },
+ { id: 'failed', status: 'failed', executionStatus: 'failed' },
+ { id: 'turn-complete', status: 'idle', executionStatus: 'completed' },
+ { id: 'unknown', status: 'idle', executionStatus: 'unknown' },
+ ] satisfies Pick[];
+ const ledger = new ProjectLedger(store);
+ store.saveTask(coordinator); store.saveTask(empty);
+ ledger.create({ id: 'project-a', name: 'Project A', directory: root, repositories: [], instructions: '' }, coordinator.id);
+ ledger.create({ id: 'project-b', name: 'Project B', directory: root, repositories: [], instructions: '' }, empty.id);
+ for (const state of states) {
+ store.saveTask({ ...task(state.id, state.id), ...state });
+ ledger.addMember('project-a', state.id, 'worker');
+ }
+ for (const outcome of ['delivered', 'terminated'] as const) {
+ const value = task(outcome, outcome); store.saveTask(value); ledger.addMember('project-a', value.id, 'worker');
+ store.setMeta('task-closeout:' + value.id, JSON.stringify(taskCloseoutSchema.parse({ taskId: value.id, projectId: 'project-a',
+ lifecycle: { kind: 'completed', outcome, summary: outcome + ' fact', deliveryReferences: [outcome + ' reference'], at: 20, operationId: 'closeout-' + outcome }, scopes: [], operations: [], predecessorTaskId: null })));
+ }
+ store.saveTask(task('unassociated', 'Same directory, no membership'));
+ const dashboard = await startDashboard({ execution: source.execution, dataDir: root, port: 0, host: '127.0.0.1' });
+ t.after(() => dashboard.close());
+ const snapshot: { tasks: ProjectTaskCard[]; projects: ProjectDashboard[] } = await (await fetch(dashboard.url + '/api/snapshot')).json();
+ assert.deepEqual(snapshot.projects.map(project => project.coordinatorTaskId).sort(), [coordinator.id, empty.id].sort());
+ assert.deepEqual(snapshot.projects.find(project => project.id === 'project-b')?.tasks.map(value => value.id), [empty.id]);
+ const project = snapshot.projects.find(project => project.id === 'project-a'); assert.ok(project);
+ for (const state of states) {
+ const card: ProjectTaskCard | undefined = project.tasks.find(value => value.id === state.id); assert.ok(card);
+ assert.equal(card.status, state.status); assert.equal(card.executionStatus, state.executionStatus);
+ assert.deepEqual(card.lifecycle, { kind: 'open' });
+ assert.deepEqual(snapshot.tasks.find(value => value.id === card.id), card);
+ }
+ for (const outcome of ['delivered', 'terminated'] as const) {
+ const card: ProjectTaskCard | undefined = project.tasks.find(value => value.id === outcome); assert.ok(card?.lifecycle.kind === 'completed');
+ assert.equal(card.lifecycle.outcome, outcome); assert.equal(card.lifecycle.at, 20);
+ const detail = await (await fetch(dashboard.url + '/api/tasks/' + outcome)).json();
+ assert.deepEqual(detail.task.lifecycle, card.lifecycle);
+ }
+ const unassociated = snapshot.tasks.find(value => value.id === 'unassociated'); assert.ok(unassociated);
+ assert.equal(unassociated.projectId, null); assert.equal(unassociated.role, null);
+ assert.equal(snapshot.projects.some(value => value.tasks.some(card => card.id === unassociated.id)), false);
+ assert.deepEqual(source.reads.sort(), ['thread:delivered', 'thread:terminated'].sort());
+});
+
+test('work summaries use published current Thread events, reports, reasons and no record without inventing times', async t => {
+ const root = await mkdtemp(join(tmpdir(), 'dashboard-work-summary-'));
+ const store = new Store(root), source = new ExecutionFixture();
+ t.after(async () => { store.close(); await rm(root, { recursive: true, force: true }); });
+ const coordinator = task('coordinator', 'Coordinator'); store.saveTask(coordinator);
+ const ledger = new ProjectLedger(store);
+ ledger.create({ id: 'project-a', name: 'Project A', directory: root, repositories: [], instructions: '' }, coordinator.id);
+ const workers = ['live', 'report', 'reason', 'empty', 'historical', 'plain-report'].map(id => task(id, id));
+ for (const worker of workers) { store.saveTask(worker); ledger.addMember('project-a', worker.id, 'worker'); }
+ const historical = workers.find(worker => worker.id === 'historical'); assert.ok(historical?.threadId);
+ source.publish(historical.id, { threadId: historical.threadId, turnId: 'old-turn', itemId: 'history', kind: 'agent_message', label: 'Agent', text: 'Canonical history only', createdAt: 10 });
+ source.restart();
+ for (const id of ['live', 'report', 'plain-report']) store.receive(coordinator.id, {
+ id: 'report-' + id, chatId: coordinator.chatId!, chatType: 'group', senderId: 'runtime:project', text: id + ' report body', attachments: [], createdAt: 15,
+ }, 'source', { kind: 'agent', projectId: 'project-a', taskId: id, eventId: 'report:' + id, category: 'update',
+ ...(id === 'plain-report' ? {} : { currentStep: 'Review reader', nextStep: 'Verify browser', blockers: ['Waiting on review'], evidence: ['PR reference'] }) });
+ const live = store.task('live'); live.status = 'paused'; live.reason = 'Operator pause'; live.updatedAt = 9000; store.saveTask(live);
+ const reason = store.task('reason'); reason.reason = 'Needs input'; reason.updatedAt = 8000; store.saveTask(reason);
+ source.publish('live', { threadId: live.threadId!, turnId: live.turnId, itemId: 'live', kind: 'tool_end', label: '命令 · completed', text: '$ npm test\nPRIVATE_OUTPUT', createdAt: 21 });
+ source.publish('report', { threadId: 'previous-thread', turnId: 'previous-turn', itemId: 'old', kind: 'agent_message', label: 'Agent', text: 'Obsolete Thread event', createdAt: 99 });
+ const reader = new ProjectDashboardReader(store, source.execution);
+ const card = (id: string) => { const result = reader.overview().tasks.find(value => value.id === id); assert.ok(result); return result; };
+ assert.deepEqual(source.reads, []);
+ const liveCard = card('live'); assert.equal(liveCard.workSummary.kind, 'event');
+ if (liveCard.workSummary.kind === 'event') {
+ assert.equal(liveCard.workSummary.event.createdAt, 21);
+ assert.equal(liveCard.workSummary.event.text, '$ npm test');
+ }
+ assert.equal(liveCard.status, 'paused'); assert.equal(liveCard.waitingReason, 'Operator pause');
+ assert.equal(liveCard.latestReport?.nextStep, 'Verify browser');
+ assert.deepEqual(liveCard.latestReport?.blockers, ['Waiting on review']);
+ assert.deepEqual(liveCard.latestReport?.evidence, ['PR reference']);
+ assert.equal(card('report').workSummary.kind, 'report'); assert.equal(card('report').latestActivity, null);
+ const plain = card('plain-report').workSummary; assert.equal(plain.kind, 'report');
+ if (plain.kind === 'report') { assert.equal(plain.report.text, 'plain-report report body'); assert.equal(plain.report.currentStep, undefined); assert.equal(plain.report.createdAt, 15); }
+ assert.deepEqual(card('reason').workSummary, { kind: 'waiting', text: 'Needs input', createdAt: null });
+ assert.deepEqual(card('empty').workSummary, { kind: 'no-record' });
+ assert.deepEqual(card('historical').workSummary, { kind: 'no-record' });
+ const detail = await reader.taskDetail(historical.id); assert.ok(detail);
+ assert.match(JSON.stringify(detail.timeline), /Canonical history only/);
+ assert.deepEqual(card('historical').workSummary, { kind: 'no-record' });
+ assert.equal(card('historical').latestActivity, null);
+ const rebound = store.task('live'); rebound.threadId = 'replacement'; store.saveTask(rebound);
+ assert.equal(card('live').workSummary.kind, 'report');
+ source.execution.reset();
+ assert.equal(card('live').workSummary.kind, 'report');
+ assert.deepEqual(source.reads, [historical.threadId]);
+});
+
test('project dashboard uses ledger membership, reports, and redacted task events', async t => {
const root = await mkdtemp(join(tmpdir(), 'agent-dashboard-coordinator-'));
const store = new Store(root); const source = new ExecutionFixture();
diff --git a/test/dashboard-recovery.test.ts b/test/dashboard-recovery.test.ts
index ccb884a..a1c2493 100644
--- a/test/dashboard-recovery.test.ts
+++ b/test/dashboard-recovery.test.ts
@@ -11,28 +11,32 @@ class Element {
hidden = false;
checked = false;
dataset = {};
- classList = { toggle() {} };
+ classList = { toggle() {}, add() {} };
append(...children: Element[]) { this.childNodes.push(...children); }
replaceChildren(...children: Element[]) { this.childNodes = children; }
addEventListener() {}
removeAttribute() {}
+ scrollIntoView() {}
+ get innerText(): string { return [this.textContent, ...this.childNodes.map(child => child.innerText)].join('\n'); }
}
-async function browser(options: { threadId: string | null; unavailable?: boolean }) {
+async function browser(options: { threadId: string | null; unavailable?: boolean; beforeDetail?: () => Promise; runtime?: { pid: number; lastSeenAt: number; intervalMs: number; status: 'running' | 'stopped' } }) {
const elements = new Map();
const element = (id: string) => { let result = elements.get(id); if (!result) { result = new Element(); elements.set(id, result); } return result; };
const requests: string[] = [];
const streams: Stream[] = [];
class Stream {
closed = false;
+ onopen = () => {};
+ onerror = () => {};
listeners = new Map void>();
constructor(readonly url: string) { streams.push(this); }
close() { this.closed = true; }
addEventListener(name: string, listener: (message: { data: string }) => void) { this.listeners.set(name, listener); }
emit(name: string, value: unknown = {}) { this.listeners.get(name)?.({ data: JSON.stringify(value) }); }
}
- let now = 0, unavailable = options.unavailable ?? false;
- const task = { id: 'task', title: 'Task', threadId: options.threadId, status: 'running', role: 'worker', updatedAt: 0 };
+ let now = 0, unavailable = options.unavailable ?? false, snapshotUnavailable = false;
+ const task = { id: 'task', title: 'Task', threadId: options.threadId, status: 'running', role: 'worker', updatedAt: 0, latestReport: { text: 'Business report', createdAt: 0 } };
const context = createContext({
document: { getElementById: element, createElement: () => new Element(), createDocumentFragment: () => new Element(), querySelectorAll: () => [] },
EventSource: Stream,
@@ -40,15 +44,20 @@ async function browser(options: { threadId: string | null; unavailable?: boolean
window: { addEventListener() {}, setInterval() {}, setTimeout() {} },
fetch: async (url: string) => {
requests.push(url);
+ if (url === '/api/snapshot' && snapshotUnavailable) throw new Error('Snapshot unavailable');
+ if (url !== '/api/snapshot') await options.beforeDetail?.();
return { ok: true, status: 200, json: async () => url === '/api/snapshot'
- ? { tasks: [task], projects: [], now, runtime: null, dataDir: '/test' }
- : { task, threadId: task.threadId, cursor: 'epoch:0', history: { kind: unavailable ? 'unavailable' : 'available' }, timeline: unavailable ? [] : [{ id: 'historical', kind: 'agent_message', text: 'Recovered answer', createdAt: 0 }], inputs: [], outputs: [], diagnostics: [] } };
+ ? { tasks: [task], projects: [], now, runtime: options.runtime ?? null, dataDir: '/test' }
+ : { task, threadId: task.threadId, cursor: 'epoch:0', history: { kind: unavailable ? 'unavailable' : 'available' }, timeline: unavailable ? [] : [{ id: 'historical', kind: 'agent_message', text: 'Recovered answer', createdAt: 0 }], inputs: [{ text: 'Business input' }], outputs: [{ text: 'Business output' }], diagnostics: [] } };
},
});
runInContext(dashboardScript, context);
await new Promise(resolve => setImmediate(resolve));
return {
streams, requests, element,
+ async select() { await runInContext('selectTask("task")', context); },
+ failSnapshot() { snapshotUnavailable = true; },
+ recoverSnapshot() { snapshotUnavailable = false; },
recover() { unavailable = false; },
rebind(threadId: string) { task.threadId = threadId; unavailable = true; },
async refresh(elapsed = 0) { now += elapsed; await runInContext('refresh()', context); },
@@ -57,6 +66,7 @@ async function browser(options: { threadId: string | null; unavailable?: boolean
test('the selected bound task retries unavailable history with backoff and recovers without another selection', async () => {
const page = await browser({ threadId: 'thread', unavailable: true });
+ await page.select();
const reads = () => page.requests.filter(url => url === '/api/tasks/task').length;
assert.equal(reads(), 1);
await page.refresh(500); assert.equal(reads(), 1);
@@ -71,6 +81,7 @@ test('the selected bound task retries unavailable history with backoff and recov
test('reset notifications do not create an immediate detail subscription loop for an unbound task', async () => {
const page = await browser({ threadId: null });
+ await page.select();
assert.equal(page.streams.length, 1);
const first = page.streams[0]!;
assert.match(first.url, /threadId=$/);
@@ -84,20 +95,135 @@ test('reset notifications do not create an immediate detail subscription loop fo
assert.equal(page.streams.length, 2);
});
+test('reset retains business messages and shows recovery through snapshot polling before retry', async () => {
+ const page = await browser({ threadId: 'thread' });
+ await page.select();
+ const first = page.streams[0]!;
+ first.onopen();
+ assert.match(page.element('stream-status').textContent, /LIVE/);
+ assert.match(page.element('output').innerText, /Recovered answer/);
+ first.emit('reset');
+ await page.refresh(500);
+ assert.match(page.element('history').innerText, /Business input/);
+ assert.match(page.element('history').innerText, /Business output/);
+ assert.match(page.element('task-summary').innerText, /Business report/);
+ assert.equal(page.element('event-count').textContent, '0 条事件');
+ assert.doesNotMatch(page.element('output').innerText, /Recovered answer/);
+ assert.equal(page.element('page-error').hidden, false);
+ assert.match(page.element('page-error').textContent, /不可用|重新读取/);
+ assert.match(page.element('connection-text').textContent, /重连|重新读取/);
+ assert.match(page.element('stream-status').textContent, /RECONNECTING/);
+ assert.equal(first.closed, true);
+ assert.equal(page.streams.length, 1);
+ assert.equal(page.requests.filter(url => url === '/api/tasks/task').length, 1);
+
+ first.onopen();
+ assert.match(page.element('stream-status').textContent, /RECONNECTING/);
+ first.onerror();
+ first.emit('execution', { taskId: 'task', threadId: 'thread', key: 'late', turnId: 'turn', kind: 'agent_message', text: 'Closed stream answer', createdAt: 1 });
+ assert.equal(page.element('event-count').textContent, '0 条事件');
+ assert.match(page.element('stream-status').textContent, /RECONNECTING/);
+
+ await page.refresh(500);
+ assert.equal(page.streams.length, 2);
+ page.streams[1]!.onopen();
+ assert.equal(page.element('page-error').hidden, true);
+ assert.match(page.element('stream-status').textContent, /LIVE/);
+ assert.match(page.element('output').innerText, /Recovered answer/);
+ assert.doesNotMatch(page.element('output').innerText, /Closed stream answer/);
+});
+
+test('Thread rebind during reset recovery retains business facts while the new detail is loading', async () => {
+ let detailReady = Promise.resolve(), releaseDetail = () => {};
+ const page = await browser({ threadId: 'thread-a', beforeDetail: () => detailReady });
+ await page.select();
+ const first = page.streams[0]!;
+ first.onopen();
+ first.emit('reset');
+ detailReady = new Promise(resolve => { releaseDetail = resolve; });
+ page.rebind('thread-b');
+ const refresh = page.refresh(500);
+ await new Promise(resolve => setImmediate(resolve));
+ try {
+ assert.match(page.element('history').innerText, /Business input/);
+ assert.match(page.element('history').innerText, /Business output/);
+ assert.match(page.element('task-summary').innerText, /Business report/);
+ assert.equal(page.element('event-count').textContent, '0 条事件');
+ assert.doesNotMatch(page.element('output').innerText, /Recovered answer/);
+ assert.equal(page.element('page-error').hidden, false);
+ assert.match(page.element('page-error').textContent, /重新读取/);
+ first.onopen();
+ first.emit('execution', { taskId: 'task', threadId: 'thread-a', key: 'late', turnId: 'turn', kind: 'agent_message', text: 'Previous Thread answer', createdAt: 1 });
+ assert.equal(page.element('event-count').textContent, '0 条事件');
+ assert.match(page.element('stream-status').textContent, /RECONNECTING/);
+ } finally {
+ releaseDetail();
+ await refresh;
+ }
+ assert.match(page.streams[1]!.url, /threadId=thread-b/);
+ assert.equal(page.element('event-count').textContent, '0 条事件');
+ assert.match(page.element('history').innerText, /Business input/);
+ page.recover();
+ await page.refresh(1000);
+ assert.equal(page.streams.length, 2);
+ await page.refresh(1000);
+ page.streams[2]!.onopen();
+ assert.equal(page.element('page-error').hidden, true);
+ assert.match(page.element('stream-status').textContent, /LIVE/);
+ assert.doesNotMatch(page.element('output').innerText, /Previous Thread answer/);
+});
+
test('live item upserts retain at most five hundred visible timeline entries', async () => {
const page = await browser({ threadId: 'thread' });
+ await page.select();
const stream = page.streams[0]!;
- for (let index = 0; index < 510; index++) stream.emit('execution', { taskId: 'task', key: String(index), turnId: 'turn', kind: 'agent_message', text: 'Message ' + index, createdAt: index });
+ for (let index = 0; index < 510; index++) stream.emit('execution', { taskId: 'task', threadId: 'thread', key: String(index), turnId: 'turn', kind: 'agent_message', text: 'Message ' + index, createdAt: index });
assert.equal(page.element('event-count').textContent, '500 条事件');
- stream.emit('execution', { taskId: 'task', key: '509', turnId: 'turn', kind: 'agent_message', text: 'Updated message', createdAt: 509 });
+ stream.emit('execution', { taskId: 'task', threadId: 'thread', key: '509', turnId: 'turn', kind: 'agent_message', text: 'Updated message', createdAt: 509 });
assert.equal(page.element('event-count').textContent, '500 条事件');
});
test('unavailable history after Thread rebind does not preserve the previous Thread timeline', async () => {
const page = await browser({ threadId: 'thread-a' });
+ await page.select();
assert.equal(page.element('event-count').textContent, '1 条事件');
page.rebind('thread-b');
await page.refresh(1000);
assert.equal(page.element('event-count').textContent, '0 条事件');
assert.equal(page.element('page-error').hidden, false);
});
+
+test('overview polling reads no task history before explicit task selection', async () => {
+ const page = await browser({ threadId: 'thread' });
+ await page.refresh(1000);
+ await page.refresh(1000);
+ assert.deepEqual(page.requests, ['/api/snapshot', '/api/snapshot', '/api/snapshot']);
+ assert.equal(page.streams.length, 0);
+ await page.select();
+ assert.equal(page.requests.filter(url => url === '/api/tasks/task').length, 1);
+ await page.refresh(1000);
+ assert.equal(page.requests.filter(url => url === '/api/tasks/task').length, 1);
+});
+
+test('snapshot failures mark task status as last known while heartbeat age keeps advancing', async () => {
+ const page = await browser({ threadId: 'thread', runtime: { pid: 10, status: 'running', lastSeenAt: 0, intervalMs: 1000 } });
+ await page.select();
+ assert.equal(page.element('runtime-status').textContent, '服务心跳正常');
+ page.failSnapshot();
+ await page.refresh(16000);
+ assert.match(page.element('runtime-status').textContent, /服务心跳已过期/);
+ assert.match(page.element('task-badge').textContent, /最后已知/);
+ assert.match(page.element('page-error').textContent, /最后已知状态/);
+ page.recoverSnapshot(); await page.refresh(1000);
+ assert.doesNotMatch(page.element('task-badge').textContent, /最后已知/);
+ assert.equal(page.element('page-error').hidden, true);
+});
+
+test('selected detail ignores an execution event from a different Thread', async () => {
+ const page = await browser({ threadId: 'thread' }); await page.select();
+ const stream = page.streams[0]!;
+ stream.emit('execution', { taskId: 'task', threadId: 'previous-thread', key: 'old', turnId: 'turn', kind: 'agent_message', text: 'Old Thread', createdAt: 1 });
+ assert.equal(page.element('event-count').textContent, '1 条事件');
+ stream.emit('execution', { taskId: 'task', threadId: 'thread', key: 'new', turnId: 'turn', kind: 'agent_message', text: 'Current Thread', createdAt: 2 });
+ assert.equal(page.element('event-count').textContent, '2 条事件');
+});