dsh-progress-union 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/client.js ADDED
@@ -0,0 +1,2330 @@
1
+ window.__ModuleLoader__.load({
2
+ id: 'dsh-progress-union',
3
+ factory(require) {
4
+ const React = require('react')
5
+ const h = React.createElement
6
+ const { useCallback, useEffect, useMemo, useRef, useState } = React
7
+
8
+ const NS = 'progressUnion'
9
+ const API = '/progress-union'
10
+ const STATUS_API = '/dsh-progress/status'
11
+ const PANEL_ID = 'progress-union'
12
+ const RIGHT_TAB_ID = 'dsh-progress-union'
13
+ const RIGHT_TAB_KIND = 'progress-union'
14
+ const PROGRESS_EVENT = 'progress-union:changed'
15
+
16
+ function broadcastProgress(sessionId, snapshot) {
17
+ if (typeof window === 'undefined' || !snapshot) return
18
+ window.dispatchEvent(new CustomEvent(PROGRESS_EVENT, { detail: { sessionId, snapshot } }))
19
+ }
20
+
21
+ /*
22
+ * DeepSeek list prices in CNY per 1M tokens (api-docs.deepseek.com,
23
+ * 2026-11). Peak hours are Beijing time Mon–Fri 09:00–12:00 and
24
+ * 14:00–18:00; everything else (including weekends) is idle, at half the
25
+ * peak price. Public holidays are not tracked, so the estimate can be
26
+ * slightly high on a holiday weekday. The bill remains authoritative.
27
+ */
28
+ const TOKEN_PRICING = {
29
+ fallbackModel: 'deepseek-flash',
30
+ models: {
31
+ 'deepseek-flash': {
32
+ name: 'DeepSeek-V4.1-Flash',
33
+ peak: { cacheRead: 0.04, input: 2, output: 8 },
34
+ idle: { cacheRead: 0.02, input: 1, output: 4 },
35
+ },
36
+ 'deepseek-v4-pro': {
37
+ name: 'DeepSeek-V4-Pro',
38
+ peak: { cacheRead: 0.3, input: 9, output: 27 },
39
+ idle: { cacheRead: 0.15, input: 4.5, output: 13.5 },
40
+ },
41
+ },
42
+ }
43
+
44
+ function isPeakNow(now = new Date()) {
45
+ const china = new Date(now.getTime() + (now.getTimezoneOffset() + 480) * 60 * 1000)
46
+ const day = china.getDay()
47
+ if (day === 0 || day === 6) return false
48
+ const minutes = china.getHours() * 60 + china.getMinutes()
49
+ return (minutes >= 9 * 60 && minutes < 12 * 60) || (minutes >= 14 * 60 && minutes < 18 * 60)
50
+ }
51
+
52
+ function usageTotals(usage) {
53
+ const input = Number(usage?.uncachedInputTokens) || 0
54
+ const cacheRead = Number(usage?.cacheReadTokens) || 0
55
+ const cacheWrite = Number(usage?.cacheWriteTokens) || 0
56
+ const output = Number(usage?.outputTokens) || 0
57
+ return { input, cacheRead, cacheWrite, output, total: input + cacheRead + cacheWrite + output }
58
+ }
59
+
60
+ function estimateCost(totals, model, peak) {
61
+ const pricing = TOKEN_PRICING.models[model] || TOKEN_PRICING.models[TOKEN_PRICING.fallbackModel]
62
+ const rate = peak ? pricing.peak : pricing.idle
63
+ // Cache writes are billed at the cache-miss input rate on DeepSeek.
64
+ return (
65
+ (totals.input * rate.input +
66
+ totals.cacheRead * rate.cacheRead +
67
+ totals.cacheWrite * rate.input +
68
+ totals.output * rate.output) /
69
+ 1e6
70
+ )
71
+ }
72
+
73
+ function usageSummary(state) {
74
+ const usage = state?.usage
75
+ if (!usage) return null
76
+ const totals = usageTotals(usage)
77
+ if (totals.total <= 0) return null
78
+ const model = state.model || TOKEN_PRICING.fallbackModel
79
+ const provider = state.provider || ''
80
+ const pricing = TOKEN_PRICING.models[model] || TOKEN_PRICING.models[TOKEN_PRICING.fallbackModel]
81
+ const peak = isPeakNow()
82
+ // DeepSeek is the only route this table prices; other providers show
83
+ // tokens without a currency figure rather than a wrong one.
84
+ const priced = provider === '' || /deepseek/i.test(provider)
85
+ const cost = priced ? estimateCost(totals, model, peak) : null
86
+ return { ...totals, model, displayName: pricing.name, peak, cost, priced }
87
+ }
88
+
89
+ function formatTokens(value) {
90
+ if (value >= 1e6) return `${(value / 1e6).toFixed(value >= 1e7 ? 0 : 2)}M`
91
+ if (value >= 1e3) return `${(value / 1e3).toFixed(value >= 1e5 ? 0 : 1)}k`
92
+ return String(value)
93
+ }
94
+
95
+ function formatCny(value) {
96
+ if (!Number.isFinite(value) || value <= 0) return '¥0'
97
+ return `¥${value < 0.01 ? value.toFixed(4) : value.toFixed(2)}`
98
+ }
99
+
100
+ function usageLabel(view) {
101
+ if (!view) return ''
102
+ const tokens = `${formatTokens(view.total)} tok`
103
+ return view.cost == null ? tokens : `${tokens} · ≈${formatCny(view.cost)}`
104
+ }
105
+
106
+ function usageTooltip(view, t) {
107
+ if (!view) return t('usageHint')
108
+ return `${t('usageHint')}\n${view.displayName} · ${view.peak ? t('usagePeak') : t('usageIdle')} · ${t('usageInput')} ${view.input.toLocaleString()} · ${t('usageCache')} ${view.cacheRead.toLocaleString()} · ${t('usageOutput')} ${view.output.toLocaleString()}`
109
+ }
110
+
111
+ function useSessionUsage(sessionId, usageApi) {
112
+ const [state, setState] = useState(null)
113
+ useEffect(() => {
114
+ if (!sessionId || !usageApi) {
115
+ setState(null)
116
+ return undefined
117
+ }
118
+ let alive = true
119
+ const read = () => {
120
+ if (!alive) return
121
+ try {
122
+ setState(usageApi.read(sessionId))
123
+ } catch (_error) {
124
+ setState(null)
125
+ }
126
+ }
127
+ read()
128
+ const off = usageApi.subscribe(sessionId, read)
129
+ return () => {
130
+ alive = false
131
+ try {
132
+ off?.()
133
+ } catch (_error) {
134
+ // Projection teardown is best-effort.
135
+ }
136
+ }
137
+ }, [sessionId, usageApi])
138
+ return state
139
+ }
140
+
141
+ const zh = {
142
+ nav: '进度板',
143
+ title: '进度板',
144
+ subtitle: '你可以直接修改;Agent 只会在下一步读取你改动的那一部分。',
145
+ live: '实时同步',
146
+ saving: '保存中…',
147
+ loading: '正在读取进度…',
148
+ noSessionTitle: '先打开一个会话',
149
+ noSessionBody: '进度板按会话独立保存。在左侧打开一个会话后,这里会显示它的工作进度。',
150
+ emptyTitle: '进度板还是空的',
151
+ emptyBody: '在下面添加任务,或让 Agent 开始工作时用 progress_update 建立任务清单。',
152
+ addPlaceholder: '添加一个可交付的任务…',
153
+ add: '添加',
154
+ adding: '添加中…',
155
+ retry: '重试',
156
+ refresh: '刷新',
157
+ pending: '待同步改动',
158
+ saved: '已持久化',
159
+ memoryOnly: '仅本次运行',
160
+ lastUpdate: '更新于',
161
+ revision: '版本',
162
+ statusTodo: '未开始',
163
+ statusDoing: '进行中',
164
+ statusDone: '已完成',
165
+ statusBlocked: '等待确认',
166
+ doingTitle: '正在做',
167
+ todoTitle: '尚未开始',
168
+ blockedTitle: '等待你确认',
169
+ doneTitle: '已完成',
170
+ overall: '总进度',
171
+ current: '当前动作',
172
+ next: '下一步',
173
+ approach: '当前思路与实现',
174
+ approachPh: '为什么这样做、当前实现路径…',
175
+ note: '备注',
176
+ addNote: '添加备注',
177
+ hideNote: '收起备注',
178
+ titlePh: '任务标题',
179
+ currentPh: '现在在做什么',
180
+ nextPh: '下一步做什么',
181
+ notePh: '假设、阻塞原因、补充说明…',
182
+ delete: '删除',
183
+ confirmDelete: '确认删除',
184
+ moveUp: '上移',
185
+ moveDown: '下移',
186
+ agent: 'Agent',
187
+ you: '你',
188
+ blockedHint: '这些任务在等你确认。Agent 应在对话中提出选项化的问题;你回答后它会恢复。',
189
+ emptyDoing: '当前没有标记为进行中的任务。',
190
+ emptyTodo: '没有待办任务。',
191
+ emptyBlocked: '没有等待确认的任务。',
192
+ readError: '读取进度失败:',
193
+ saveError: '保存失败:',
194
+ storageWarn: '进度存储不可用,当前改动只保存在本次运行中。',
195
+ footerHint: '约每 3 秒同步一次;输入框失焦后自动保存。',
196
+ editHint: '标题、当前动作、下一步和备注都可以直接编辑。',
197
+ doneCount: '项已完成',
198
+ taskCount: '项任务',
199
+ allDone: '全部完成',
200
+ noDoing: '当前没有进行中的任务。',
201
+ blockedCount: '项等待确认',
202
+ percent: '进度',
203
+ dockHint: '点击打开完整进度板',
204
+ dockExpand: '展开',
205
+ dockCollapse: '收起',
206
+ dockEdit: '编辑',
207
+ dockOpenFull: '打开完整进度板',
208
+ dockAllDone: '全部完成',
209
+ llmTitle: '进度辅助 LLM(审查/监视)',
210
+ llmOn: '已启用',
211
+ llmOff: '未启用:观察者为规则版(零 LLM 费用)。启用后由辅助模型按最近输出/动作校准 current/next/percent。',
212
+ llmAuto: ',自动落地',
213
+ llmHint: '建议直连本地/局域网 OpenAI 兼容端点(Ollama、LM Studio、自建 llama.cpp、vLLM、SGLang、Strata、Ninfer 等):profile 里配 assistant.mode: direct + baseUrl + model。仅滞后时触发,每回合至多一次,只改 current/next/percent。',
214
+ etaLeft: '预计剩',
215
+ etaOver: '已超预估',
216
+ staleTag: '中断',
217
+ dockNext: '下一步',
218
+ dockPending: '待同步',
219
+ autoOn: 'Agent 更新:开',
220
+ autoOff: 'Agent 更新:关',
221
+ autoWarn: 'Agent 自动更新已关闭;你在主界面发消息时进度板不会自动更新。',
222
+ autoEnable: '开启自动更新',
223
+ autoHint: '关闭后 Agent 不再加载进度工具;手动编辑仍会保存。',
224
+ usageTotal: '本会话用量',
225
+ usageHint: '本会话累计 token 与按 DeepSeek 公开单价估算的人民币费用;高峰/空闲时段按当前北京时间判断,实际以账单为准。',
226
+ usagePeak: '高峰',
227
+ usageIdle: '空闲',
228
+ usageInput: '输入',
229
+ usageCache: '缓存命中',
230
+ usageOutput: '输出',
231
+ sideCompleted: '已完成的任务',
232
+ sideLatest: '最新完成',
233
+ sideDetails: '详情',
234
+ sideCurrentTask: '当前任务',
235
+ sidePending: '待完成',
236
+ sideCollapse: '收起',
237
+ sideFull: '全面展开',
238
+ lastSync: '同步于',
239
+ syncFailed: '同步失败',
240
+ sideHalf: '恢复半开',
241
+ sideOpenFull: '完整面板',
242
+ sideEditable: '可直接修改',
243
+ sideEmptyDone: '还没有完成的任务',
244
+ sideEmptyPending: '没有待完成的任务',
245
+ sideApproachEmpty: '还没有记录实现思路',
246
+ sideProgress: '进度',
247
+ sideDone: '完成',
248
+ sideAllDone: '其他已完成',
249
+ }
250
+
251
+ const en = {
252
+ nav: 'Progress board',
253
+ title: 'Progress board',
254
+ subtitle: 'Edit anything directly; the agent reads only the changed part at its next step.',
255
+ live: 'Live sync',
256
+ saving: 'Saving…',
257
+ loading: 'Loading progress…',
258
+ noSessionTitle: 'Open a session first',
259
+ noSessionBody: 'The board is stored per session. Open a session from the sidebar and its progress will appear here.',
260
+ emptyTitle: 'The board is empty',
261
+ emptyBody: 'Add a task below, or let the agent create the list with progress_update when work starts.',
262
+ addPlaceholder: 'Add a deliverable task…',
263
+ add: 'Add',
264
+ adding: 'Adding…',
265
+ retry: 'Retry',
266
+ refresh: 'Refresh',
267
+ pending: 'Pending edits',
268
+ saved: 'Saved',
269
+ memoryOnly: 'This run only',
270
+ lastUpdate: 'Updated',
271
+ revision: 'Revision',
272
+ statusTodo: 'Not started',
273
+ statusDoing: 'In progress',
274
+ statusDone: 'Done',
275
+ statusBlocked: 'Needs you',
276
+ doingTitle: 'In progress',
277
+ todoTitle: 'Not started',
278
+ blockedTitle: 'Waiting for you',
279
+ doneTitle: 'Done',
280
+ overall: 'Overall',
281
+ current: 'Current',
282
+ next: 'Next',
283
+ approach: 'Approach',
284
+ approachPh: 'Why this way, current implementation path…',
285
+ note: 'Note',
286
+ addNote: 'Add note',
287
+ hideNote: 'Hide note',
288
+ titlePh: 'Task title',
289
+ currentPh: 'What is happening now',
290
+ nextPh: 'What happens next',
291
+ notePh: 'Assumptions, blockers, context…',
292
+ delete: 'Delete',
293
+ confirmDelete: 'Confirm delete',
294
+ moveUp: 'Move up',
295
+ moveDown: 'Move down',
296
+ agent: 'Agent',
297
+ you: 'You',
298
+ blockedHint: 'These tasks wait for you. The agent should ask an option-based question in chat and resume after your answer.',
299
+ emptyDoing: 'No task is marked in progress.',
300
+ emptyTodo: 'No pending tasks.',
301
+ emptyBlocked: 'Nothing is waiting for you.',
302
+ readError: 'Could not read progress: ',
303
+ saveError: 'Could not save: ',
304
+ storageWarn: 'Progress storage is unavailable; edits live only in this run.',
305
+ footerHint: 'Syncs about every 3 s; edits save when the field loses focus.',
306
+ editHint: 'Title, current, next, and note are directly editable.',
307
+ doneCount: 'done',
308
+ taskCount: 'tasks',
309
+ allDone: 'All done',
310
+ noDoing: 'Nothing is in progress right now.',
311
+ blockedCount: 'waiting for you',
312
+ percent: 'Progress',
313
+ dockHint: 'Open the full progress board',
314
+ dockExpand: 'Expand',
315
+ dockCollapse: 'Collapse',
316
+ dockEdit: 'Edit',
317
+ dockOpenFull: 'Open full board',
318
+ dockAllDone: 'All done',
319
+ llmTitle: 'Progress assistant LLM (audit/watch)',
320
+ llmOn: 'Enabled',
321
+ llmOff: 'Disabled: the observer is rule-based (zero LLM cost). When enabled, an auxiliary model recalibrates current/next/percent from recent output/actions.',
322
+ llmAuto: ', auto-applied',
323
+ llmHint: 'Prefer a local/LAN self-hosted OpenAI-compatible endpoint (Ollama, LM Studio, self-hosted llama.cpp, vLLM, SGLang, Strata, Ninfer, …): set assistant.mode: direct + baseUrl + model in the profile. Triggered only while overdue, at most once per turn, and only current/next/percent are changed.',
324
+ etaLeft: '~',
325
+ etaOver: 'over by',
326
+ staleTag: 'idle',
327
+ dockNext: 'Next',
328
+ dockPending: 'pending',
329
+ autoOn: 'Agent updates: on',
330
+ autoOff: 'Agent updates: off',
331
+ autoWarn: 'Agent auto-update is off; messages sent from the main composer will not refresh the board.',
332
+ autoEnable: 'Turn on auto-update',
333
+ autoHint: 'While off, the agent does not load the progress tool. Manual edits are still saved.',
334
+ usageTotal: 'Session usage',
335
+ usageHint: 'Cumulative session tokens and an RMB estimate at DeepSeek list prices; peak/idle is based on the current Beijing time. The bill is authoritative.',
336
+ usagePeak: 'peak',
337
+ usageIdle: 'idle',
338
+ usageInput: 'input',
339
+ usageCache: 'cache hit',
340
+ usageOutput: 'output',
341
+ sideCompleted: 'Completed',
342
+ sideLatest: 'Latest completed',
343
+ sideDetails: 'Details',
344
+ sideCurrentTask: 'Current task',
345
+ sidePending: 'Pending',
346
+ sideCollapse: 'Collapse',
347
+ sideFull: 'Fullscreen',
348
+ lastSync: 'Synced',
349
+ syncFailed: 'Sync failed',
350
+ sideHalf: 'Half width',
351
+ sideOpenFull: 'Full board',
352
+ sideEditable: 'Editable',
353
+ sideEmptyDone: 'Nothing completed yet',
354
+ sideEmptyPending: 'Nothing pending',
355
+ sideApproachEmpty: 'No approach recorded yet',
356
+ sideProgress: 'Progress',
357
+ sideDone: 'Done',
358
+ sideAllDone: 'Other completed',
359
+ }
360
+
361
+ const STATUS_KEYS = ['todo', 'doing', 'done', 'blocked']
362
+ const STATUS_LABEL = {
363
+ todo: 'statusTodo',
364
+ doing: 'statusDoing',
365
+ done: 'statusDone',
366
+ blocked: 'statusBlocked',
367
+ }
368
+
369
+ const CSS = `
370
+ .pb-root {
371
+ box-sizing: border-box;
372
+ height: 100%;
373
+ min-height: 100%;
374
+ overflow: auto;
375
+ padding: 28px 32px 56px;
376
+ color: var(--dsw-alias-label-primary);
377
+ background: var(--dsw-alias-bg-base);
378
+ font-family: inherit;
379
+ font-size: 14px;
380
+ line-height: 1.5;
381
+ }
382
+ .pb-inner { width: 100%; max-width: 1040px; margin: 0 auto; }
383
+ .pb-head { display: flex; align-items: flex-start; justify-content: space-between; gap: 20px; margin-bottom: 22px; }
384
+ .pb-title { margin: 0; font-size: 22px; line-height: 1.25; font-weight: 650; letter-spacing: -.01em; }
385
+ .pb-sub { margin: 6px 0 0; max-width: 680px; color: var(--dsw-alias-label-secondary); font-size: 13px; }
386
+ .pb-head-right { display: flex; align-items: center; gap: 10px; flex: none; padding-top: 3px; }
387
+ .pb-usage {
388
+ display: flex; align-items: center; gap: 6px; min-width: 0;
389
+ color: var(--dsw-alias-label-secondary); font-size: 11px; line-height: 1.4;
390
+ }
391
+ .pb-usage b { color: var(--dsw-alias-label-primary); font-size: 12px; font-weight: 600; font-variant-numeric: tabular-nums; }
392
+ .pb-usage-label { color: var(--dsw-alias-label-tertiary); }
393
+ .pb-usage-cost { color: var(--dsw-alias-brand-primary); font-weight: 600; font-variant-numeric: tabular-nums; }
394
+ .pb-usage-inline {
395
+ flex: none; padding: 3px 8px; border: 1px solid var(--dsw-alias-border-l1);
396
+ border-radius: 999px; background: var(--dsw-alias-bg-layer-1);
397
+ }
398
+ .pb-side > .pb-usage {
399
+ margin: -4px 0 12px; padding: 7px 9px; border: 1px solid var(--dsw-alias-border-l1);
400
+ border-radius: var(--dsw-radius-md, 8px); background: var(--dsw-alias-bg-layer-1);
401
+ }
402
+ .pb-live { display: inline-flex; align-items: center; gap: 6px; color: var(--dsw-alias-label-secondary); font-size: 12px; white-space: nowrap; }
403
+ .pb-dot { width: 7px; height: 7px; border-radius: 999px; background: var(--dsw-alias-state-success-primary); box-shadow: 0 0 0 3px color-mix(in srgb, var(--dsw-alias-state-success-primary) 16%, transparent); }
404
+ .pb-saving { color: var(--dsw-alias-label-secondary); font-size: 12px; }
405
+ .pb-btn {
406
+ appearance: none; border: 1px solid var(--dsw-alias-border-l1); border-radius: 8px;
407
+ background: var(--dsw-alias-bg-layer-1); color: var(--dsw-alias-label-primary);
408
+ padding: 5px 10px; font: inherit; font-size: 12px; line-height: 1.4; cursor: pointer;
409
+ }
410
+ .pb-btn:hover:not(:disabled) { border-color: var(--dsw-alias-border-l2); }
411
+ .pb-btn:disabled { opacity: .42; cursor: not-allowed; }
412
+ .pb-btn-primary { background: var(--dsw-alias-brand-primary); border-color: var(--dsw-alias-brand-primary); color: var(--dsw-alias-bg-base); font-weight: 600; }
413
+ .pb-btn-danger { color: var(--dsw-alias-state-error-primary); }
414
+ .pb-icon-btn { min-width: 28px; padding: 4px 7px; }
415
+ .pb-overview {
416
+ position: relative; border: 1px solid var(--dsw-alias-border-l1); border-radius: 14px;
417
+ background: var(--dsw-alias-bg-layer-1); padding: 18px 20px; margin-bottom: 22px;
418
+ }
419
+ .pb-overview-top { display: flex; align-items: flex-end; justify-content: space-between; gap: 20px; }
420
+ .pb-big { font-size: 34px; line-height: 1; font-weight: 680; letter-spacing: -.03em; font-variant-numeric: tabular-nums; }
421
+ .pb-big small { margin-left: 3px; font-size: 15px; font-weight: 500; color: var(--dsw-alias-label-secondary); }
422
+ .pb-counts { display: flex; flex-wrap: wrap; gap: 6px; justify-content: flex-end; }
423
+ .pb-chip { display: inline-flex; align-items: center; gap: 5px; border-radius: 999px; background: var(--dsw-alias-bg-layer-2); padding: 3px 9px; color: var(--dsw-alias-label-secondary); font-size: 12px; white-space: nowrap; }
424
+ .pb-chip strong { color: var(--dsw-alias-label-primary); font-weight: 600; font-variant-numeric: tabular-nums; }
425
+ .pb-bar { height: 8px; margin: 15px 0 0; border-radius: 999px; overflow: hidden; background: var(--dsw-alias-bg-layer-2); }
426
+ .pb-bar > i { display: block; height: 100%; border-radius: inherit; background: var(--dsw-alias-brand-primary); transition: width .25s ease; }
427
+ .pb-focus { display: flex; align-items: center; gap: 9px; margin-top: 13px; color: var(--dsw-alias-label-secondary); font-size: 13px; }
428
+ .pb-focus b { color: var(--dsw-alias-label-primary); font-weight: 600; }
429
+ .pb-badge-pending { display: inline-flex; align-items: center; border-radius: 999px; padding: 3px 8px; font-size: 11px; color: var(--dsw-alias-state-warn-primary); background: color-mix(in srgb, var(--dsw-alias-state-warn-primary) 12%, transparent); }
430
+ .pb-warn {
431
+ margin: 0 0 18px; border: 1px solid color-mix(in srgb, var(--dsw-alias-state-warn-primary) 45%, var(--dsw-alias-border-l1));
432
+ border-radius: 10px; background: color-mix(in srgb, var(--dsw-alias-state-warn-primary) 9%, var(--dsw-alias-bg-layer-1));
433
+ padding: 10px 12px; color: var(--dsw-alias-label-primary); font-size: 12px;
434
+ }
435
+ .pb-warn-error { border-color: color-mix(in srgb, var(--dsw-alias-state-error-primary) 45%, var(--dsw-alias-border-l1)); background: color-mix(in srgb, var(--dsw-alias-state-error-primary) 8%, var(--dsw-alias-bg-layer-1)); }
436
+ .pb-section { margin-top: 22px; }
437
+ .pb-section-head { display: flex; align-items: baseline; gap: 9px; margin: 0 0 9px; }
438
+ .pb-section-title { margin: 0; font-size: 13px; font-weight: 650; letter-spacing: .01em; }
439
+ .pb-section-count { color: var(--dsw-alias-label-secondary); font-size: 12px; font-variant-numeric: tabular-nums; }
440
+ .pb-list { display: flex; flex-direction: column; gap: 8px; }
441
+ .pb-item {
442
+ border: 1px solid var(--dsw-alias-border-l1); border-radius: 11px;
443
+ background: var(--dsw-alias-bg-layer-1); padding: 11px 13px 10px;
444
+ }
445
+ .pb-item.pb-doing { border-color: color-mix(in srgb, var(--dsw-alias-brand-primary) 38%, var(--dsw-alias-border-l1)); }
446
+ .pb-item.pb-blocked { border-left: 3px solid var(--dsw-alias-state-warn-primary); }
447
+ .pb-item.pb-done { opacity: .72; }
448
+ .pb-item-head { display: grid; grid-template-columns: 98px minmax(0, 1fr) 70px auto; align-items: center; gap: 8px; }
449
+ .pb-status {
450
+ width: 100%; appearance: none; border: 1px solid var(--dsw-alias-border-l1); border-radius: 7px;
451
+ background: var(--dsw-alias-bg-base); color: var(--dsw-alias-label-primary);
452
+ padding: 5px 7px; font: inherit; font-size: 12px; line-height: 1.35;
453
+ }
454
+ .pb-status:focus, .pb-input:focus, .pb-note:focus, .pb-percent input:focus { outline: none; border-color: var(--dsw-alias-brand-primary); box-shadow: 0 0 0 2px color-mix(in srgb, var(--dsw-alias-brand-primary) 18%, transparent); }
455
+ .pb-status.pb-s-doing { color: var(--dsw-alias-brand-primary); font-weight: 600; }
456
+ .pb-status.pb-s-done { color: var(--dsw-alias-state-success-primary); }
457
+ .pb-status.pb-s-blocked { color: var(--dsw-alias-state-warn-primary); }
458
+ .pb-input {
459
+ box-sizing: border-box; width: 100%; min-width: 0; border: 1px solid transparent; border-radius: 7px;
460
+ background: transparent; color: var(--dsw-alias-label-primary); padding: 5px 7px; font: inherit; line-height: 1.4;
461
+ }
462
+ .pb-input:hover { border-color: var(--dsw-alias-border-l1); }
463
+ .pb-input.pb-title-input { font-weight: 600; }
464
+ .pb-input::placeholder, .pb-note::placeholder { color: var(--dsw-alias-label-secondary); opacity: .72; }
465
+ .pb-percent { display: flex; align-items: center; justify-content: flex-end; gap: 4px; color: var(--dsw-alias-label-secondary); font-size: 12px; }
466
+ .pb-percent input {
467
+ width: 44px; box-sizing: border-box; border: 1px solid transparent; border-radius: 6px;
468
+ background: transparent; color: var(--dsw-alias-label-primary); padding: 3px 2px; font: inherit; font-size: 12px; text-align: right;
469
+ font-variant-numeric: tabular-nums;
470
+ }
471
+ .pb-percent input:hover { border-color: var(--dsw-alias-border-l1); }
472
+ .pb-actions { display: flex; align-items: center; gap: 2px; opacity: .55; transition: opacity .15s; }
473
+ .pb-item:hover .pb-actions, .pb-actions:focus-within { opacity: 1; }
474
+ .pb-subgrid { display: grid; grid-template-columns: 1fr 1fr; gap: 4px 12px; margin: 5px 0 0 98px; }
475
+ .pb-field-label { display: block; margin: 0 0 1px; color: var(--dsw-alias-label-secondary); font-size: 10px; letter-spacing: .03em; text-transform: uppercase; }
476
+ .pb-approach {
477
+ box-sizing: border-box; width: calc(100% - 98px); min-height: 38px; resize: vertical;
478
+ margin: 6px 0 0 98px; border: 1px solid var(--dsw-alias-border-l1); border-radius: 7px;
479
+ background: var(--dsw-alias-bg-base); color: var(--dsw-alias-label-primary);
480
+ padding: 6px 8px; font: inherit; font-size: 12px; line-height: 1.45;
481
+ }
482
+ .pb-approach-label { margin: 7px 0 0 98px; }
483
+ .pb-note {
484
+ box-sizing: border-box; width: calc(100% - 98px); min-height: 44px; resize: vertical;
485
+ margin: 6px 0 0 98px; border: 1px solid var(--dsw-alias-border-l1); border-radius: 7px;
486
+ background: var(--dsw-alias-bg-base); color: var(--dsw-alias-label-primary);
487
+ padding: 6px 8px; font: inherit; font-size: 12px; line-height: 1.45;
488
+ }
489
+ .pb-meta { display: flex; align-items: center; justify-content: space-between; gap: 10px; margin: 7px 0 0 98px; color: var(--dsw-alias-label-secondary); font-size: 11px; }
490
+ .pb-meta-left { display: flex; align-items: center; gap: 8px; min-width: 0; }
491
+ .pb-by { border-radius: 999px; background: var(--dsw-alias-bg-layer-2); padding: 1px 6px; }
492
+ .pb-note-toggle { border: 0; background: transparent; color: var(--dsw-alias-label-secondary); padding: 1px 0; font: inherit; font-size: 11px; cursor: pointer; }
493
+ .pb-note-toggle:hover { color: var(--dsw-alias-label-primary); }
494
+ .pb-empty { border: 1px dashed var(--dsw-alias-border-l2); border-radius: 12px; padding: 22px 18px; text-align: center; background: var(--dsw-alias-bg-layer-1); }
495
+ .pb-empty h2 { margin: 0 0 5px; font-size: 15px; }
496
+ .pb-empty p { margin: 0 auto; max-width: 540px; color: var(--dsw-alias-label-secondary); font-size: 12px; }
497
+ .pb-add { display: flex; gap: 8px; margin-top: 20px; }
498
+ .pb-add .pb-input { flex: 1; min-width: 0; border-color: var(--dsw-alias-border-l1); background: var(--dsw-alias-bg-layer-1); padding: 9px 11px; }
499
+ .pb-add .pb-btn { flex: none; white-space: nowrap; padding: 8px 14px; font-size: 13px; }
500
+ .pb-done-box { margin-top: 22px; }
501
+ .pb-done-box > summary { cursor: pointer; color: var(--dsw-alias-label-secondary); font-size: 12px; padding: 4px 0; user-select: none; }
502
+ .pb-done-box > summary:hover { color: var(--dsw-alias-label-primary); }
503
+ .pb-done-box .pb-list { margin-top: 8px; }
504
+ .pb-footer { display: flex; flex-wrap: wrap; align-items: center; gap: 8px 14px; margin-top: 26px; padding-top: 12px; border-top: 1px solid var(--dsw-alias-border-l1); color: var(--dsw-alias-label-secondary); font-size: 11px; }
505
+ .pb-footer span { white-space: nowrap; }
506
+ .pb-sep { opacity: .45; }
507
+ .pb-blocked-hint { margin: 0 0 8px; color: var(--dsw-alias-state-warn-primary); font-size: 12px; }
508
+ .pb-llm { margin: 10px 0 0; padding: 10px 12px; border: 1px solid rgba(217,119,6,.35); border-left: 3px solid #d97706; border-radius: 8px; background: rgba(217,119,6,.06); }
509
+ .pb-llm-off { opacity: .92; }
510
+ .pb-llm-title { font-size: 12px; font-weight: 650; }
511
+ .pb-llm-line { margin-top: 4px; font-size: 12px; line-height: 1.5; }
512
+ .pb-llm-hint { margin-top: 4px; font-size: 11px; line-height: 1.5; opacity: .75; }
513
+ .pb-header-btn {
514
+ display: inline-flex; align-items: center; justify-content: center; width: 28px; height: 28px;
515
+ border: 1px solid transparent; border-radius: 6px; background: transparent;
516
+ color: var(--dsw-alias-label-secondary); cursor: pointer; padding: 0;
517
+ }
518
+ .pb-header-btn:hover { background: var(--dsw-alias-bg-layer-2); color: var(--dsw-alias-label-primary); }
519
+ .pb-dock-wrap { display: flex; justify-content: center; width: 100%; }
520
+ .pb-dock {
521
+ box-sizing: border-box; width: calc(100% + var(--dsh-composer-dock-inset, 8px) + var(--dsh-composer-dock-inset, 8px) + var(--dsh-composer-dock-inset, 8px) + var(--dsh-composer-dock-inset, 8px));
522
+ max-width: var(--dsh-composer-card-max-width, none);
523
+ flex: none;
524
+ border: 1px solid var(--dsw-alias-border-l1);
525
+ border-radius: 10px; background: var(--dsw-alias-bg-layer-1); padding: 7px 9px;
526
+ color: var(--dsw-alias-label-primary); font-family: inherit; font-size: 12px;
527
+ }
528
+ .pb-dock-row { display: flex; align-items: center; gap: 9px; }
529
+ .pb-dock-main {
530
+ flex: 1; min-width: 0; display: flex; align-items: center; gap: 9px;
531
+ border: 0; background: transparent; color: inherit; font: inherit; padding: 0;
532
+ cursor: pointer; text-align: left;
533
+ }
534
+ .pb-dock-main:hover .pb-dock-title { color: var(--dsw-alias-brand-primary); }
535
+ .pb-dock-percent { flex: none; min-width: 34px; font-size: 13px; font-weight: 650; font-variant-numeric: tabular-nums; }
536
+ .pb-dock-bar { flex: none; width: 64px; height: 5px; border-radius: 999px; overflow: hidden; background: var(--dsw-alias-bg-layer-2); }
537
+ .pb-dock-bar > i { display: block; height: 100%; border-radius: inherit; background: var(--dsw-alias-brand-primary); transition: width .25s ease; }
538
+ .pb-dock-body { flex: 1; min-width: 0; line-height: 1.3; }
539
+ .pb-dock-title { display: block; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; font-size: 12px; font-weight: 600; transition: color .15s; }
540
+ .pb-dock-sub { display: block; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; margin-top: 1px; color: var(--dsw-alias-label-secondary); font-size: 11px; }
541
+ .pb-dock-actions { flex: none; display: flex; align-items: center; gap: 4px; }
542
+ .pb-dock-btn {
543
+ appearance: none; border: 1px solid var(--dsw-alias-border-l1); border-radius: 6px;
544
+ background: var(--dsw-alias-bg-base); color: var(--dsw-alias-label-secondary);
545
+ padding: 2px 7px; font: inherit; font-size: 11px; line-height: 1.4; cursor: pointer;
546
+ }
547
+ .pb-dock-btn:hover { border-color: var(--dsw-alias-border-l2); color: var(--dsw-alias-label-primary); }
548
+ .pb-dock-expanded {
549
+ display: flex; flex-direction: column; gap: 3px; margin-top: 7px; padding-top: 7px;
550
+ border-top: 1px solid var(--dsw-alias-border-l1); max-height: 180px; overflow: auto;
551
+ }
552
+ .pb-dock-item { display: flex; align-items: center; gap: 7px; min-width: 0; padding: 3px 1px; }
553
+ .pb-dock-dot { flex: none; width: 6px; height: 6px; border-radius: 999px; background: var(--dsw-alias-state-idle-primary); }
554
+ .pb-dock-dot.doing { background: var(--dsw-alias-brand-primary); }
555
+ .pb-dock-dot.done { background: var(--dsw-alias-state-success-primary); }
556
+ .pb-dock-dot.blocked { background: var(--dsw-alias-state-warn-primary); }
557
+ .pb-dock-item-title { flex: 1; min-width: 0; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; font-size: 12px; }
558
+ .pb-dock-item-meta { flex: none; color: var(--dsw-alias-label-secondary); font-size: 11px; font-variant-numeric: tabular-nums; }
559
+ .pb-dock-more { border: 0; background: transparent; color: var(--dsw-alias-brand-primary); padding: 4px 1px; font: inherit; font-size: 11px; text-align: left; cursor: pointer; }
560
+ .pb-side {
561
+ box-sizing: border-box; height: 100%; overflow: auto; padding: 14px 14px 28px;
562
+ color: var(--dsw-alias-label-primary); background: var(--dsw-alias-bg-base);
563
+ font-family: inherit; font-size: 13px; line-height: 1.45;
564
+ }
565
+ .pb-side-head { display: flex; align-items: flex-start; justify-content: space-between; gap: 8px; margin-bottom: 14px; }
566
+ .pb-side-head-actions { display: flex; align-items: center; gap: 4px; flex: none; flex-wrap: wrap; justify-content: flex-end; }
567
+ .pb-side-title { margin: 0; font-size: 16px; font-weight: 650; letter-spacing: -.01em; }
568
+ .pb-side-sub { margin: 3px 0 0; color: var(--dsw-alias-label-secondary); font-size: 11px; line-height: 1.4; }
569
+ .pb-side-section { margin-top: 15px; }
570
+ .pb-side-label { display: flex; align-items: center; justify-content: space-between; gap: 8px; margin-bottom: 6px; color: var(--dsw-alias-label-secondary); font-size: 10px; letter-spacing: .04em; text-transform: uppercase; }
571
+ .pb-side-card { border: 1px solid var(--dsw-alias-border-l1); border-radius: 9px; background: var(--dsw-alias-bg-layer-1); padding: 9px 10px; }
572
+ .pb-side-card + .pb-side-card { margin-top: 6px; }
573
+ .pb-side-done-card { border-color: color-mix(in srgb, var(--dsw-alias-state-success-primary) 32%, var(--dsw-alias-border-l1)); }
574
+ .pb-side-check { color: var(--dsw-alias-state-success-primary); font-weight: 700; }
575
+ .pb-side-done-title { flex: 1; min-width: 0; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; font-size: 12px; font-weight: 600; }
576
+ .pb-side-meta { flex: none; color: var(--dsw-alias-label-secondary); font-size: 11px; font-variant-numeric: tabular-nums; }
577
+ .pb-side-note { margin: 5px 0 0; color: var(--dsw-alias-label-secondary); font-size: 11px; line-height: 1.45; white-space: pre-wrap; overflow-wrap: anywhere; }
578
+ .pb-side-bar { height: 5px; margin-top: 7px; border-radius: 999px; overflow: hidden; background: var(--dsw-alias-bg-layer-2); }
579
+ .pb-side-bar > i { display: block; height: 100%; border-radius: inherit; background: var(--dsw-alias-brand-primary); transition: width .25s ease; }
580
+ .pb-side-task-head { display: flex; align-items: center; gap: 5px; }
581
+ .pb-side-task-head .pb-status { flex: none; width: 88px; }
582
+ .pb-side-task-head .pb-input { flex: 1; font-weight: 600; }
583
+ .pb-side-task-head .pb-percent { flex: none; }
584
+ .pb-side-field { display: block; margin-top: 6px; }
585
+ .pb-side-field .pb-field-label { margin-bottom: 2px; }
586
+ .pb-side-input, .pb-side-textarea {
587
+ box-sizing: border-box; width: 100%; border: 1px solid var(--dsw-alias-border-l1); border-radius: 6px;
588
+ background: var(--dsw-alias-bg-base); color: var(--dsw-alias-label-primary);
589
+ padding: 5px 7px; font: inherit; font-size: 12px; line-height: 1.45;
590
+ }
591
+ .pb-side-textarea { min-height: 48px; resize: vertical; }
592
+ .pb-side-input:focus, .pb-side-textarea:focus { outline: none; border-color: var(--dsw-alias-brand-primary); box-shadow: 0 0 0 2px color-mix(in srgb, var(--dsw-alias-brand-primary) 18%, transparent); }
593
+ .pb-side-done-all { margin-top: 6px; }
594
+ .pb-side-done-all > summary { cursor: pointer; color: var(--dsw-alias-label-secondary); font-size: 11px; padding: 4px 0; user-select: none; }
595
+ .pb-side-done-all > summary:hover { color: var(--dsw-alias-label-primary); }
596
+ .pb-side-done-item { border-top: 1px solid var(--dsw-alias-border-l1); padding: 5px 0; }
597
+ .pb-side-done-item > summary { display: flex; align-items: center; gap: 6px; cursor: pointer; list-style: none; }
598
+ .pb-side-done-item > summary::-webkit-details-marker { display: none; }
599
+ .pb-side-done-item .pb-side-done-title { font-weight: 500; font-size: 11px; }
600
+ .pb-side-done-item .pb-side-detail-line, .pb-side-done-item .pb-side-note { margin-left: 12px; }
601
+ .pb-side-detail-line { margin-top: 6px; color: var(--dsw-alias-label-secondary); font-size: 11px; line-height: 1.45; white-space: pre-wrap; overflow-wrap: anywhere; }
602
+ .pb-side-detail-line b { color: var(--dsw-alias-label-primary); font-weight: 600; }
603
+ .pb-side-empty { border: 1px dashed var(--dsw-alias-border-l2); border-radius: 9px; padding: 12px 10px; text-align: center; color: var(--dsw-alias-label-secondary); font-size: 11px; }
604
+ .pb-side-footer { display: flex; flex-wrap: wrap; align-items: center; gap: 6px 10px; margin-top: 16px; padding-top: 10px; border-top: 1px solid var(--dsw-alias-border-l1); color: var(--dsw-alias-label-secondary); font-size: 11px; }
605
+ .pb-side-link { border: 0; background: transparent; color: var(--dsw-alias-brand-primary); padding: 0; font: inherit; font-size: 11px; cursor: pointer; }
606
+ .pb-side-error { margin-bottom: 10px; border: 1px solid color-mix(in srgb, var(--dsw-alias-state-error-primary) 45%, var(--dsw-alias-border-l1)); border-radius: 8px; background: color-mix(in srgb, var(--dsw-alias-state-error-primary) 8%, var(--dsw-alias-bg-layer-1)); padding: 7px 8px; color: var(--dsw-alias-label-primary); font-size: 11px; }
607
+ .pb-loading { padding: 46px 0; text-align: center; color: var(--dsw-alias-label-secondary); font-size: 13px; }
608
+ @media (max-width: 760px) {
609
+ .pb-dock-bar { display: none; }
610
+ .pb-dock-sub { max-width: 42vw; }
611
+ .pb-root { padding: 20px 16px 44px; }
612
+ .pb-head { flex-direction: column; gap: 10px; }
613
+ .pb-overview-top { align-items: flex-start; flex-direction: column; gap: 10px; }
614
+ .pb-counts { justify-content: flex-start; }
615
+ .pb-item-head { grid-template-columns: 92px minmax(0, 1fr) 64px; }
616
+ .pb-actions { grid-column: 1 / -1; justify-content: flex-end; }
617
+ .pb-subgrid { grid-template-columns: 1fr; margin-left: 0; }
618
+ .pb-approach { width: 100%; margin-left: 0; }
619
+ .pb-approach-label { margin-left: 0; }
620
+ .pb-note { width: 100%; margin-left: 0; }
621
+ .pb-meta { margin-left: 0; }
622
+ .pb-side { padding: 12px 10px 24px; }
623
+ .pb-side-task-head { flex-wrap: wrap; }
624
+ .pb-side-task-head .pb-status { width: 100%; }
625
+ }
626
+ `
627
+
628
+ function makeT(props) {
629
+ return (key) => {
630
+ try {
631
+ const value = props.t ? props.t(key) : undefined
632
+ if (typeof value === 'string' && value) return value
633
+ } catch (_error) {
634
+ // Fall through to the built-in Chinese dictionary.
635
+ }
636
+ return zh[key] || key
637
+ }
638
+ }
639
+
640
+ function statusLabel(t, status) {
641
+ return t(STATUS_LABEL[status] || status)
642
+ }
643
+
644
+ function errorText(error) {
645
+ return error instanceof Error ? error.message : String(error)
646
+ }
647
+
648
+ async function postChanges(sessionId, expectedRevision, changes) {
649
+ const response = await fetch(`${API}/action`, {
650
+ method: 'POST',
651
+ credentials: 'same-origin',
652
+ headers: { 'content-type': 'application/json' },
653
+ body: JSON.stringify({ sessionId, expectedRevision, changes }),
654
+ })
655
+ const body = await response.json().catch(() => null)
656
+ return { response, body }
657
+ }
658
+
659
+ async function setPanelActive(sessionId, active, source = 'panel') {
660
+ try {
661
+ const response = await fetch(`${API}/active`, {
662
+ method: 'POST',
663
+ credentials: 'same-origin',
664
+ headers: { 'content-type': 'application/json' },
665
+ body: JSON.stringify({ sessionId, active, source }),
666
+ })
667
+ return await response.json().catch(() => null)
668
+ } catch (_error) {
669
+ // The board still works; only automatic Agent updates are unavailable.
670
+ return null
671
+ }
672
+ }
673
+
674
+ /** Persist "the agent should keep this board up to date" for one session. */
675
+ async function setAgentEnabled(sessionId, enabled) {
676
+ const body = await setPanelActive(sessionId, enabled, 'user')
677
+ return body && body.ok === true ? body : null
678
+ }
679
+
680
+ function ProgressNavIcon({ size = 20 }) {
681
+ return h(
682
+ 'svg',
683
+ {
684
+ width: size,
685
+ height: size,
686
+ viewBox: '0 0 24 24',
687
+ fill: 'none',
688
+ 'aria-hidden': true,
689
+ style: { display: 'block' },
690
+ },
691
+ h('path', {
692
+ d: 'M4 7.2h8.2M4 12h11.2M4 16.8h6.2',
693
+ stroke: 'currentColor',
694
+ strokeWidth: 1.7,
695
+ strokeLinecap: 'round',
696
+ }),
697
+ h('circle', { cx: 18.1, cy: 7.2, r: 2.25, stroke: 'currentColor', strokeWidth: 1.7 }),
698
+ h('path', {
699
+ d: 'M17.2 7.2l.7.7 1.4-1.5',
700
+ stroke: 'currentColor',
701
+ strokeWidth: 1.5,
702
+ strokeLinecap: 'round',
703
+ strokeLinejoin: 'round',
704
+ }),
705
+ h('circle', { cx: 18.1, cy: 16.8, r: 2.25, stroke: 'currentColor', strokeWidth: 1.7 }),
706
+ )
707
+ }
708
+
709
+ function ProgressHeaderButton(props) {
710
+ const t = makeT(props)
711
+ return h(
712
+ 'button',
713
+ {
714
+ type: 'button',
715
+ className: 'pb-header-btn',
716
+ title: t('nav'),
717
+ 'aria-label': t('nav'),
718
+ onClick: () => {
719
+ try {
720
+ props.openPanel?.()
721
+ } catch (_error) {
722
+ // The mini bar and sidebar remain available.
723
+ }
724
+ },
725
+ },
726
+ h(ProgressNavIcon, { size: 17 }),
727
+ )
728
+ }
729
+
730
+ function EditableText({ value, placeholder, onCommit, multiline, className, disabled, ariaLabel }) {
731
+ const [draft, setDraft] = useState(value || '')
732
+ const [focused, setFocused] = useState(false)
733
+ useEffect(() => {
734
+ if (!focused) setDraft(value || '')
735
+ }, [value, focused])
736
+
737
+ const commit = () => {
738
+ setFocused(false)
739
+ const next = draft.trim()
740
+ setDraft(next)
741
+ if (next !== (value || '')) onCommit(next)
742
+ }
743
+
744
+ const shared = {
745
+ value: draft,
746
+ placeholder,
747
+ disabled,
748
+ className,
749
+ 'aria-label': ariaLabel || placeholder,
750
+ onFocus: () => setFocused(true),
751
+ onChange: (event) => setDraft(event.target.value),
752
+ onBlur: commit,
753
+ }
754
+
755
+ if (multiline) {
756
+ return h('textarea', {
757
+ ...shared,
758
+ rows: 2,
759
+ onKeyDown: (event) => {
760
+ if (event.key === 'Escape') {
761
+ setDraft(value || '')
762
+ event.currentTarget.blur()
763
+ }
764
+ if (event.key === 'Enter' && (event.metaKey || event.ctrlKey)) {
765
+ event.preventDefault()
766
+ event.currentTarget.blur()
767
+ }
768
+ },
769
+ })
770
+ }
771
+
772
+ return h('input', {
773
+ ...shared,
774
+ type: 'text',
775
+ onKeyDown: (event) => {
776
+ if (event.key === 'Enter') {
777
+ event.preventDefault()
778
+ event.currentTarget.blur()
779
+ }
780
+ if (event.key === 'Escape') {
781
+ setDraft(value || '')
782
+ event.currentTarget.blur()
783
+ }
784
+ },
785
+ })
786
+ }
787
+
788
+ function PercentEditor({ value, onCommit, disabled, label }) {
789
+ const [draft, setDraft] = useState(String(value))
790
+ const [focused, setFocused] = useState(false)
791
+ useEffect(() => {
792
+ if (!focused) setDraft(String(value))
793
+ }, [value, focused])
794
+
795
+ const commit = () => {
796
+ setFocused(false)
797
+ const number = Number(draft)
798
+ if (!Number.isFinite(number)) {
799
+ setDraft(String(value))
800
+ return
801
+ }
802
+ const next = Math.max(0, Math.min(100, Math.round(number)))
803
+ setDraft(String(next))
804
+ if (next !== value) onCommit(next)
805
+ }
806
+
807
+ return h(
808
+ 'label',
809
+ { className: 'pb-percent', title: label },
810
+ h('input', {
811
+ type: 'number',
812
+ min: 0,
813
+ max: 100,
814
+ step: 1,
815
+ value: draft,
816
+ disabled,
817
+ 'aria-label': label,
818
+ onFocus: () => setFocused(true),
819
+ onChange: (event) => setDraft(event.target.value),
820
+ onBlur: commit,
821
+ onKeyDown: (event) => {
822
+ if (event.key === 'Enter') {
823
+ event.preventDefault()
824
+ event.currentTarget.blur()
825
+ }
826
+ },
827
+ }),
828
+ h('span', null, '%'),
829
+ )
830
+ }
831
+
832
+ function ItemCard({ item, t, disabled, canMoveUp, canMoveDown, onPatch, onRemove, onMove }) {
833
+ const [showNote, setShowNote] = useState(Boolean(item.note))
834
+ const [confirmDelete, setConfirmDelete] = useState(false)
835
+ useEffect(() => {
836
+ if (item.note) setShowNote(true)
837
+ }, [item.note])
838
+ useEffect(() => {
839
+ setConfirmDelete(false)
840
+ }, [item.status, item.title])
841
+
842
+ return h(
843
+ 'article',
844
+ { className: `pb-item pb-${item.status}` },
845
+ h(
846
+ 'div',
847
+ { className: 'pb-item-head' },
848
+ h(
849
+ 'select',
850
+ {
851
+ className: `pb-status pb-s-${item.status}`,
852
+ value: item.status,
853
+ disabled,
854
+ 'aria-label': t('statusTodo'),
855
+ onChange: (event) => onPatch({ status: event.target.value }),
856
+ },
857
+ STATUS_KEYS.map((status) =>
858
+ h('option', { key: status, value: status }, statusLabel(t, status)),
859
+ ),
860
+ ),
861
+ h(EditableText, {
862
+ value: item.title,
863
+ placeholder: t('titlePh'),
864
+ disabled,
865
+ className: 'pb-input pb-title-input',
866
+ ariaLabel: t('titlePh'),
867
+ onCommit: (value) => onPatch({ title: value }),
868
+ }),
869
+ h(PercentEditor, {
870
+ value: item.percent,
871
+ disabled,
872
+ label: t('percent'),
873
+ onCommit: (value) => onPatch({ percent: value }),
874
+ }),
875
+ h(
876
+ 'div',
877
+ { className: 'pb-actions' },
878
+ h(
879
+ 'button',
880
+ {
881
+ type: 'button',
882
+ className: 'pb-btn pb-icon-btn',
883
+ title: t('moveUp'),
884
+ 'aria-label': t('moveUp'),
885
+ disabled: disabled || !canMoveUp,
886
+ onClick: () => onMove(-1),
887
+ },
888
+ '↑',
889
+ ),
890
+ h(
891
+ 'button',
892
+ {
893
+ type: 'button',
894
+ className: 'pb-btn pb-icon-btn',
895
+ title: t('moveDown'),
896
+ 'aria-label': t('moveDown'),
897
+ disabled: disabled || !canMoveDown,
898
+ onClick: () => onMove(1),
899
+ },
900
+ '↓',
901
+ ),
902
+ h(
903
+ 'button',
904
+ {
905
+ type: 'button',
906
+ className: `pb-btn pb-icon-btn ${confirmDelete ? 'pb-btn-danger' : ''}`,
907
+ title: confirmDelete ? t('confirmDelete') : t('delete'),
908
+ 'aria-label': confirmDelete ? t('confirmDelete') : t('delete'),
909
+ disabled,
910
+ onClick: () => {
911
+ if (confirmDelete) {
912
+ setConfirmDelete(false)
913
+ onRemove()
914
+ } else {
915
+ setConfirmDelete(true)
916
+ }
917
+ },
918
+ },
919
+ confirmDelete ? '!' : '×',
920
+ ),
921
+ ),
922
+ ),
923
+ h(
924
+ 'div',
925
+ { className: 'pb-subgrid' },
926
+ h(
927
+ 'label',
928
+ null,
929
+ h('span', { className: 'pb-field-label' }, t('current')),
930
+ h(EditableText, {
931
+ value: item.current,
932
+ placeholder: t('currentPh'),
933
+ disabled,
934
+ className: 'pb-input',
935
+ ariaLabel: t('current'),
936
+ onCommit: (value) => onPatch({ current: value }),
937
+ }),
938
+ ),
939
+ h(
940
+ 'label',
941
+ null,
942
+ h('span', { className: 'pb-field-label' }, t('next')),
943
+ h(EditableText, {
944
+ value: item.next,
945
+ placeholder: t('nextPh'),
946
+ disabled,
947
+ className: 'pb-input',
948
+ ariaLabel: t('next'),
949
+ onCommit: (value) => onPatch({ next: value }),
950
+ }),
951
+ ),
952
+ ),
953
+ h(
954
+ 'label',
955
+ { className: 'pb-approach-label' },
956
+ h('span', { className: 'pb-field-label' }, t('approach')),
957
+ h(EditableText, {
958
+ value: item.approach || '',
959
+ placeholder: t('approachPh'),
960
+ disabled,
961
+ multiline: true,
962
+ className: 'pb-approach',
963
+ ariaLabel: t('approach'),
964
+ onCommit: (value) => onPatch({ approach: value }),
965
+ }),
966
+ ),
967
+ showNote
968
+ ? h(EditableText, {
969
+ value: item.note,
970
+ placeholder: t('notePh'),
971
+ disabled,
972
+ multiline: true,
973
+ className: 'pb-note',
974
+ ariaLabel: t('note'),
975
+ onCommit: (value) => onPatch({ note: value }),
976
+ })
977
+ : null,
978
+ h(
979
+ 'div',
980
+ { className: 'pb-meta' },
981
+ h(
982
+ 'div',
983
+ { className: 'pb-meta-left' },
984
+ h('span', { className: 'pb-by' }, item.updatedBy === 'user' ? t('you') : t('agent')),
985
+ h('span', null, new Date(item.updatedAt).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })),
986
+ h(
987
+ 'button',
988
+ {
989
+ type: 'button',
990
+ className: 'pb-note-toggle',
991
+ onClick: () => setShowNote((visible) => !visible),
992
+ },
993
+ showNote ? t('hideNote') : t('addNote'),
994
+ ),
995
+ ),
996
+ h('span', null, `${item.percent}%`),
997
+ ),
998
+ )
999
+ }
1000
+
1001
+ function AddTask({ t, disabled, onAdd }) {
1002
+ const [title, setTitle] = useState('')
1003
+ const [adding, setAdding] = useState(false)
1004
+
1005
+ const submit = async (event) => {
1006
+ event.preventDefault()
1007
+ const next = title.trim()
1008
+ if (!next || adding) return
1009
+ setAdding(true)
1010
+ try {
1011
+ const ok = await onAdd(next)
1012
+ if (ok) setTitle('')
1013
+ } finally {
1014
+ setAdding(false)
1015
+ }
1016
+ }
1017
+
1018
+ return h(
1019
+ 'form',
1020
+ { className: 'pb-add', onSubmit: submit },
1021
+ h('input', {
1022
+ className: 'pb-input',
1023
+ type: 'text',
1024
+ value: title,
1025
+ placeholder: t('addPlaceholder'),
1026
+ disabled: disabled || adding,
1027
+ 'aria-label': t('addPlaceholder'),
1028
+ onChange: (event) => setTitle(event.target.value),
1029
+ }),
1030
+ h(
1031
+ 'button',
1032
+ { className: 'pb-btn pb-btn-primary', type: 'submit', disabled: disabled || adding || !title.trim() },
1033
+ adding ? t('adding') : t('add'),
1034
+ ),
1035
+ )
1036
+ }
1037
+
1038
+ function Section({ title, count, hint, children }) {
1039
+ return h(
1040
+ 'section',
1041
+ { className: 'pb-section' },
1042
+ h(
1043
+ 'div',
1044
+ { className: 'pb-section-head' },
1045
+ h('h2', { className: 'pb-section-title' }, title),
1046
+ h('span', { className: 'pb-section-count' }, String(count)),
1047
+ ),
1048
+ hint ? h('p', { className: 'pb-blocked-hint' }, hint) : null,
1049
+ h('div', { className: 'pb-list' }, children),
1050
+ )
1051
+ }
1052
+
1053
+ function useProgressData(sessionId) {
1054
+ const [snapshot, setSnapshot] = useState(null)
1055
+ const [error, setError] = useState('')
1056
+ const [lastSyncAt, setLastSyncAt] = useState(0)
1057
+ const [refreshTick, setRefreshTick] = useState(0)
1058
+ const sessionRef = useRef(sessionId)
1059
+
1060
+ useEffect(() => {
1061
+ if (!sessionId) {
1062
+ sessionRef.current = undefined
1063
+ setSnapshot(null)
1064
+ setError('')
1065
+ setLastSyncAt(0)
1066
+ return undefined
1067
+ }
1068
+
1069
+ const sessionChanged = sessionRef.current !== sessionId
1070
+ sessionRef.current = sessionId
1071
+ if (sessionChanged) {
1072
+ setSnapshot(null)
1073
+ setLastSyncAt(0)
1074
+ }
1075
+ setError('')
1076
+
1077
+ let active = true
1078
+ let controller
1079
+
1080
+ const load = async () => {
1081
+ if (controller) controller.abort()
1082
+ const ownController = (controller = new AbortController())
1083
+ try {
1084
+ const response = await fetch(
1085
+ `${API}/snapshot?sessionId=${encodeURIComponent(sessionId)}`,
1086
+ { credentials: 'same-origin', cache: 'no-store', signal: ownController.signal },
1087
+ )
1088
+ if (!response.ok) throw new Error(`HTTP ${response.status}`)
1089
+ const next = await response.json()
1090
+ if (!active) return
1091
+ setSnapshot(next)
1092
+ setError('')
1093
+ setLastSyncAt(Date.now())
1094
+ } catch (caught) {
1095
+ if (!active || caught?.name === 'AbortError') return
1096
+ setError(errorText(caught))
1097
+ }
1098
+ }
1099
+
1100
+ const onProgressChange = (event) => {
1101
+ const detail = event.detail
1102
+ if (!detail || detail.sessionId !== sessionId || !detail.snapshot) return
1103
+ setSnapshot(detail.snapshot)
1104
+ setError('')
1105
+ setLastSyncAt(Date.now())
1106
+ }
1107
+ window.addEventListener(PROGRESS_EVENT, onProgressChange)
1108
+
1109
+ load()
1110
+ const interval = window.setInterval(load, 3000)
1111
+ const onVisibility = () => {
1112
+ if (document.visibilityState === 'visible') load()
1113
+ }
1114
+ document.addEventListener('visibilitychange', onVisibility)
1115
+
1116
+ return () => {
1117
+ active = false
1118
+ window.clearInterval(interval)
1119
+ controller?.abort()
1120
+ window.removeEventListener(PROGRESS_EVENT, onProgressChange)
1121
+ document.removeEventListener('visibilitychange', onVisibility)
1122
+ }
1123
+ }, [sessionId, refreshTick])
1124
+
1125
+ return {
1126
+ snapshot,
1127
+ setSnapshot,
1128
+ error,
1129
+ lastSyncAt,
1130
+ refresh: () => setRefreshTick((value) => value + 1),
1131
+ }
1132
+ }
1133
+
1134
+ /*
1135
+ * 鲸程时间面:轮询 /dsh-progress/status 取本会话活跃任务的 etaMin/overMin/
1136
+ * staleMin——板给语义(到哪一步),时间层给还要多久。失败静默(只少一行)。
1137
+ */
1138
+ function useUnionTiming(sessionId) {
1139
+ const [timing, setTiming] = useState(null)
1140
+ useEffect(() => {
1141
+ if (!sessionId) {
1142
+ setTiming(null)
1143
+ return undefined
1144
+ }
1145
+ let active = true
1146
+ const load = async () => {
1147
+ try {
1148
+ const response = await fetch(STATUS_API, { credentials: 'same-origin', cache: 'no-store' })
1149
+ if (!response.ok) throw new Error(`HTTP ${response.status}`)
1150
+ const body = await response.json()
1151
+ if (!active) return
1152
+ const list = Array.isArray(body.tasks) ? body.tasks : []
1153
+ const mine = list.find((x) => x && String(x.id) === String(sessionId)) || (body.task && body.task.id ? body.task : list[0])
1154
+ setTiming(mine ? { steps: mine.steps || 0, etaMin: mine.etaMin || 0, overMin: mine.overMin || 0, staleMin: mine.staleMin || 0, etaBasis: mine.etaBasis || 'prior', elapsedSec: mine.elapsedSec || 0 } : null)
1155
+ } catch (_caught) {
1156
+ // 时间面缺席不影响板本体(capability absence 降级)
1157
+ }
1158
+ }
1159
+ load()
1160
+ const interval = window.setInterval(load, 3000)
1161
+ return () => {
1162
+ active = false
1163
+ window.clearInterval(interval)
1164
+ }
1165
+ }, [sessionId])
1166
+ return timing
1167
+ }
1168
+
1169
+ function ProgressDock(props) {
1170
+ const t = makeT(props)
1171
+ const { sessionId } = props
1172
+ const { snapshot, error: readError, refresh } = useProgressData(sessionId)
1173
+ const timing = useUnionTiming(sessionId)
1174
+ const usageView = usageSummary(useSessionUsage(sessionId, props.usage))
1175
+ const [expanded, setExpanded] = useState(false)
1176
+
1177
+ useEffect(() => {
1178
+ setExpanded(false)
1179
+ }, [sessionId])
1180
+
1181
+ if (!sessionId || !snapshot || !snapshot.items || snapshot.items.length === 0) return null
1182
+
1183
+ const summary = snapshot.summary || { total: 0, done: 0, doing: 0, todo: 0, blocked: 0, percent: 0 }
1184
+ const items = snapshot.items
1185
+ const doing = items.find((item) => item.status === 'doing')
1186
+ const blocked = items.find((item) => item.status === 'blocked')
1187
+ const todo = items.find((item) => item.status === "todo")
1188
+
1189
+ let focusLine = t('dockAllDone')
1190
+ if (doing) focusLine = `${t('doingTitle')}:${doing.title}`
1191
+ else if (blocked) focusLine = `${t('blockedTitle')}:${blocked.title}`
1192
+ else if (todo) focusLine = `${t('dockNext')}:${todo.title}`
1193
+
1194
+ const sub = [`${summary.done}/${summary.total} ${t('doneCount')}`]
1195
+ if (summary.blocked) sub.push(`${summary.blocked} ${t('blockedCount')}`)
1196
+ if (timing && timing.overMin > 0) sub.push(`${t('etaOver')} ${timing.overMin} min`)
1197
+ else if (timing && timing.staleMin > 0) sub.push(`${t('staleTag')} ${timing.staleMin} min`)
1198
+ else if (timing && timing.etaMin > 0) sub.push(`${t('etaLeft')} ${timing.etaMin} min`)
1199
+ if (snapshot.pendingUserChanges) sub.push(`${snapshot.pendingUserChanges} ${t('dockPending')}`)
1200
+ if (snapshot.enabled === false) sub.push(t('autoOff'))
1201
+ if (usageView) sub.splice(1, 0, usageLabel(usageView))
1202
+ if (readError) sub.push(t('syncFailed'))
1203
+ sub.push(t('dockHint'))
1204
+
1205
+ const enableAuto = async () => {
1206
+ await setAgentEnabled(sessionId, true)
1207
+ refresh()
1208
+ }
1209
+
1210
+ const openPanel = () => {
1211
+ try {
1212
+ props.openPanel?.()
1213
+ } catch (_error) {
1214
+ // The full panel remains reachable from the sidebar.
1215
+ }
1216
+ }
1217
+
1218
+ const togglePanel = () => {
1219
+ try {
1220
+ props.togglePanel?.()
1221
+ } catch (_error) {
1222
+ // The right sidebar chrome remains available.
1223
+ }
1224
+ }
1225
+
1226
+ const priority = { doing: 0, blocked: 1, todo: 2, done: 3 }
1227
+ const ordered = items
1228
+ .slice()
1229
+ .sort((a, b) => (priority[a.status] ?? 9) - (priority[b.status] ?? 9) || a.order - b.order)
1230
+ .slice(0, 8)
1231
+
1232
+ return h(
1233
+ React.Fragment,
1234
+ null,
1235
+ h('style', null, CSS),
1236
+ h(
1237
+ 'div',
1238
+ { className: 'pb-dock-wrap' },
1239
+ h(
1240
+ 'div',
1241
+ { className: 'pb-dock' },
1242
+ h(
1243
+ 'div',
1244
+ { className: 'pb-dock-row' },
1245
+ h(
1246
+ 'button',
1247
+ {
1248
+ type: 'button',
1249
+ className: 'pb-dock-main',
1250
+ title: t('dockHint'),
1251
+ onClick: togglePanel,
1252
+ },
1253
+ h('span', { className: 'pb-dock-percent' }, `${summary.percent}%`),
1254
+ h('span', { className: 'pb-dock-bar' }, h('i', { style: { width: `${summary.percent}%` } })),
1255
+ h(
1256
+ 'span',
1257
+ { className: 'pb-dock-body' },
1258
+ h('span', { className: 'pb-dock-title' }, focusLine),
1259
+ h('span', { className: 'pb-dock-sub', title: usageView ? usageTooltip(usageView, t) : undefined }, sub.join(' · ')),
1260
+ ),
1261
+ ),
1262
+ h(
1263
+ 'div',
1264
+ { className: 'pb-dock-actions' },
1265
+ readError
1266
+ ? h(
1267
+ 'button',
1268
+ {
1269
+ type: 'button',
1270
+ className: 'pb-dock-btn',
1271
+ title: t('refresh'),
1272
+ 'aria-label': t('refresh'),
1273
+ onClick: refresh,
1274
+ },
1275
+ '↻',
1276
+ )
1277
+ : null,
1278
+ snapshot.enabled === false
1279
+ ? h(
1280
+ 'button',
1281
+ {
1282
+ type: 'button',
1283
+ className: 'pb-dock-btn pb-dock-enable',
1284
+ title: t('autoHint'),
1285
+ onClick: enableAuto,
1286
+ },
1287
+ t('autoEnable'),
1288
+ )
1289
+ : null,
1290
+ h(
1291
+ 'button',
1292
+ {
1293
+ type: 'button',
1294
+ className: 'pb-dock-btn',
1295
+ onClick: () => setExpanded((value) => !value),
1296
+ },
1297
+ expanded ? t('dockCollapse') : t('dockExpand'),
1298
+ ),
1299
+ h(
1300
+ 'button',
1301
+ { type: 'button', className: 'pb-dock-btn', onClick: openPanel },
1302
+ t('dockEdit'),
1303
+ ),
1304
+ ),
1305
+ ),
1306
+ expanded
1307
+ ? h(
1308
+ 'div',
1309
+ { className: 'pb-dock-expanded' },
1310
+ ordered.map((item) =>
1311
+ h(
1312
+ 'div',
1313
+ { key: item.id, className: 'pb-dock-item' },
1314
+ h('i', { className: `pb-dock-dot ${item.status}` }),
1315
+ h('span', { className: 'pb-dock-item-title' }, item.title),
1316
+ h('span', { className: 'pb-dock-item-meta' }, `${item.percent}%`),
1317
+ ),
1318
+ ),
1319
+ h(
1320
+ 'button',
1321
+ { type: 'button', className: 'pb-dock-more', onClick: openPanel },
1322
+ t('dockOpenFull'),
1323
+ ),
1324
+ )
1325
+ : null,
1326
+ ),
1327
+ ),
1328
+ )
1329
+ }
1330
+
1331
+ function SideTaskEditor({ item, t, disabled, onPatch }) {
1332
+ const [showNote, setShowNote] = useState(Boolean(item.note))
1333
+ useEffect(() => {
1334
+ if (item.note) setShowNote(true)
1335
+ }, [item.note])
1336
+
1337
+ return h(
1338
+ 'div',
1339
+ { className: 'pb-side-card' },
1340
+ h(
1341
+ 'div',
1342
+ { className: 'pb-side-task-head' },
1343
+ h(
1344
+ 'select',
1345
+ {
1346
+ className: `pb-status pb-s-${item.status}`,
1347
+ value: item.status,
1348
+ disabled,
1349
+ 'aria-label': t('statusTodo'),
1350
+ onChange: (event) => onPatch({ status: event.target.value }),
1351
+ },
1352
+ STATUS_KEYS.map((status) => h('option', { key: status, value: status }, statusLabel(t, status))),
1353
+ ),
1354
+ h(EditableText, {
1355
+ value: item.title,
1356
+ placeholder: t('titlePh'),
1357
+ disabled,
1358
+ className: 'pb-side-input',
1359
+ ariaLabel: t('titlePh'),
1360
+ onCommit: (value) => onPatch({ title: value }),
1361
+ }),
1362
+ h(PercentEditor, {
1363
+ value: item.percent,
1364
+ disabled,
1365
+ label: t('percent'),
1366
+ onCommit: (value) => onPatch({ percent: value }),
1367
+ }),
1368
+ ),
1369
+ h('div', { className: 'pb-side-bar' }, h('i', { style: { width: `${item.percent}%` } })),
1370
+ h(
1371
+ 'label',
1372
+ { className: 'pb-side-field' },
1373
+ h('span', { className: 'pb-field-label' }, t('current')),
1374
+ h(EditableText, {
1375
+ value: item.current,
1376
+ placeholder: t('currentPh'),
1377
+ disabled,
1378
+ className: 'pb-side-input',
1379
+ ariaLabel: t('current'),
1380
+ onCommit: (value) => onPatch({ current: value }),
1381
+ }),
1382
+ ),
1383
+ h(
1384
+ 'label',
1385
+ { className: 'pb-side-field' },
1386
+ h('span', { className: 'pb-field-label' }, t('approach')),
1387
+ h(EditableText, {
1388
+ value: item.approach || '',
1389
+ placeholder: t('approachPh'),
1390
+ disabled,
1391
+ multiline: true,
1392
+ className: 'pb-side-textarea',
1393
+ ariaLabel: t('approach'),
1394
+ onCommit: (value) => onPatch({ approach: value }),
1395
+ }),
1396
+ ),
1397
+ h(
1398
+ 'label',
1399
+ { className: 'pb-side-field' },
1400
+ h('span', { className: 'pb-field-label' }, t('next')),
1401
+ h(EditableText, {
1402
+ value: item.next,
1403
+ placeholder: t('nextPh'),
1404
+ disabled,
1405
+ className: 'pb-side-input',
1406
+ ariaLabel: t('next'),
1407
+ onCommit: (value) => onPatch({ next: value }),
1408
+ }),
1409
+ ),
1410
+ showNote
1411
+ ? h(EditableText, {
1412
+ value: item.note,
1413
+ placeholder: t('notePh'),
1414
+ disabled,
1415
+ multiline: true,
1416
+ className: 'pb-side-textarea',
1417
+ ariaLabel: t('note'),
1418
+ onCommit: (value) => onPatch({ note: value }),
1419
+ })
1420
+ : h(
1421
+ 'button',
1422
+ {
1423
+ type: 'button',
1424
+ className: 'pb-side-link',
1425
+ style: { marginTop: '6px' },
1426
+ onClick: () => setShowNote(true),
1427
+ },
1428
+ t('addNote'),
1429
+ ),
1430
+ )
1431
+ }
1432
+
1433
+ function LlmAssistNotice(props) {
1434
+ const t = makeT(props)
1435
+ const a = props.assistant
1436
+ if (!a) return null
1437
+ const on = a.enabled === true
1438
+ return h(
1439
+ 'div',
1440
+ { className: on ? 'pb-llm' : 'pb-llm pb-llm-off' },
1441
+ h('div', { className: 'pb-llm-title' }, t('llmTitle')),
1442
+ h(
1443
+ 'div',
1444
+ { className: 'pb-llm-line' },
1445
+ on
1446
+ ? `${t('llmOn')}:${a.baseUrl} · ${a.model}(≤${Math.max(1, Math.round((a.minIntervalMs || 0) / 60000))} min/次${a.autoApply ? t('llmAuto') : ''})`
1447
+ : t('llmOff'),
1448
+ ),
1449
+ h('div', { className: 'pb-llm-hint' }, t('llmHint')),
1450
+ )
1451
+ }
1452
+
1453
+ function ProgressSidePanel(props) {
1454
+ const t = makeT(props)
1455
+ const { sessionId } = props
1456
+ const useTabInfo = props.useTabInfo
1457
+ const tabInfo = useTabInfo ? useTabInfo() : undefined
1458
+ const { snapshot, setSnapshot, error: readError, lastSyncAt, refresh } = useProgressData(sessionId)
1459
+ const usageView = usageSummary(useSessionUsage(sessionId, props.usage))
1460
+ const [saving, setSaving] = useState(false)
1461
+ const [actionError, setActionError] = useState('')
1462
+ const revisionRef = useRef(0)
1463
+
1464
+ useEffect(() => {
1465
+ if (!sessionId) return undefined
1466
+ // Opening the board enables agent updates for this session. There is
1467
+ // deliberately no cleanup: collapsing the sidebar, switching tabs or
1468
+ // opening the full main panel must not silently disable the tool.
1469
+ setPanelActive(sessionId, true)
1470
+ return undefined
1471
+ }, [sessionId])
1472
+
1473
+ const enableAuto = async () => {
1474
+ await setAgentEnabled(sessionId, true)
1475
+ refresh()
1476
+ }
1477
+
1478
+ useEffect(() => {
1479
+ revisionRef.current = snapshot?.revision ?? 0
1480
+ }, [snapshot?.revision])
1481
+
1482
+ const mutate = useCallback(
1483
+ async (changes) => {
1484
+ if (!sessionId) return false
1485
+ setSaving(true)
1486
+ setActionError('')
1487
+ try {
1488
+ let result = await postChanges(sessionId, revisionRef.current, changes)
1489
+ if (result.response.status === 409 && result.body?.snapshot) {
1490
+ revisionRef.current = result.body.snapshot.revision
1491
+ setSnapshot(result.body.snapshot)
1492
+ result = await postChanges(sessionId, revisionRef.current, changes)
1493
+ }
1494
+ const { response, body } = result
1495
+ if (!response.ok || !body || body.ok === false) {
1496
+ if (body?.snapshot) {
1497
+ revisionRef.current = body.snapshot.revision
1498
+ setSnapshot(body.snapshot)
1499
+ }
1500
+ throw new Error(body?.error || `HTTP ${response.status}`)
1501
+ }
1502
+ revisionRef.current = body.revision
1503
+ setSnapshot(body)
1504
+ broadcastProgress(sessionId, body)
1505
+ const addedTitles = (Array.isArray(changes) ? changes : [])
1506
+ .filter((change) => change && !change.id && !change.remove && typeof change.title === 'string')
1507
+ .map((change) => change.title.trim())
1508
+ .filter(Boolean)
1509
+ if (addedTitles.length > 0) {
1510
+ props.wakeAgent?.(
1511
+ sessionId,
1512
+ `我在进度板新增了任务。请按新任务推进。`,
1513
+ )
1514
+ }
1515
+ return true
1516
+ } catch (caught) {
1517
+ setActionError(errorText(caught))
1518
+ return false
1519
+ } finally {
1520
+ setSaving(false)
1521
+ }
1522
+ },
1523
+ [sessionId, setSnapshot],
1524
+ )
1525
+
1526
+ const collapse = () => {
1527
+ try {
1528
+ props.collapse?.()
1529
+ } catch (_error) {
1530
+ // The chrome control remains available.
1531
+ }
1532
+ }
1533
+
1534
+ const openFull = () => {
1535
+ try {
1536
+ props.openFullPanel?.()
1537
+ } catch (_error) {
1538
+ // The sidebar icon remains available.
1539
+ }
1540
+ }
1541
+
1542
+ const items = snapshot?.items || []
1543
+ const latestDone = items
1544
+ .filter((item) => item.status === 'done')
1545
+ .slice()
1546
+ .sort((a, b) => b.updatedAt - a.updatedAt)[0]
1547
+ const otherDone = items
1548
+ .filter((item) => item.status === 'done' && item.id !== latestDone?.id)
1549
+ .slice()
1550
+ .sort((a, b) => b.updatedAt - a.updatedAt)
1551
+ const current = items.find((item) => item.status === 'doing') || items.find((item) => item.status === 'blocked')
1552
+ const pending = items.filter(
1553
+ (item) => (item.status === 'todo' || item.status === 'blocked') && item.id !== current?.id,
1554
+ )
1555
+
1556
+ if (!sessionId) {
1557
+ return h(
1558
+ 'div',
1559
+ { className: 'pb-side' },
1560
+ h('style', null, CSS),
1561
+ h('div', { className: 'pb-side-empty' }, t('noSessionBody')),
1562
+ )
1563
+ }
1564
+
1565
+ return h(
1566
+ React.Fragment,
1567
+ null,
1568
+ h('style', null, CSS),
1569
+ h(
1570
+ 'div',
1571
+ { className: 'pb-side' },
1572
+ h(
1573
+ 'div',
1574
+ { className: 'pb-side-head' },
1575
+ h(
1576
+ 'div',
1577
+ null,
1578
+ h('h2', { className: 'pb-side-title' }, t('nav')),
1579
+ h('p', { className: 'pb-side-sub' }, t('subtitle')),
1580
+ ),
1581
+ h(
1582
+ 'div',
1583
+ { className: 'pb-side-head-actions' },
1584
+ h(
1585
+ 'button',
1586
+ {
1587
+ type: 'button',
1588
+ className: snapshot?.enabled === false ? 'pb-btn pb-btn-primary' : 'pb-btn',
1589
+ title: t('autoHint'),
1590
+ onClick: async () => {
1591
+ await setAgentEnabled(sessionId, snapshot?.enabled === false)
1592
+ refresh()
1593
+ },
1594
+ },
1595
+ snapshot?.enabled === false ? t('autoOff') : t('autoOn'),
1596
+ ),
1597
+ h(
1598
+ 'button',
1599
+ { type: 'button', className: 'pb-btn', onClick: () => props.toggleFullscreen?.() },
1600
+ tabInfo?.sidebar?.fullscreen ? t('sideHalf') : t('sideFull'),
1601
+ ),
1602
+ h('button', { type: 'button', className: 'pb-btn', onClick: collapse }, t('sideCollapse')),
1603
+ ),
1604
+ ),
1605
+ readError ? h('div', { className: 'pb-side-error' }, `${t('readError')}${readError}`) : null,
1606
+ h(LlmAssistNotice, { assistant: snapshot?.assistant, t: props.t }),
1607
+ actionError ? h('div', { className: 'pb-side-error' }, `${t('saveError')}${actionError}`) : null,
1608
+ usageView
1609
+ ? h(
1610
+ 'div',
1611
+ { className: 'pb-usage', title: usageTooltip(usageView, t) },
1612
+ h('span', { className: 'pb-usage-label' }, t('usageTotal')),
1613
+ h('b', null, `${formatTokens(usageView.total)} tok`),
1614
+ usageView.cost == null
1615
+ ? null
1616
+ : h('span', { className: 'pb-usage-cost' }, `≈ ${formatCny(usageView.cost)}`),
1617
+ )
1618
+ : null,
1619
+ snapshot?.enabled === false
1620
+ ? h(
1621
+ 'div',
1622
+ { className: 'pb-side-error' },
1623
+ `${t('autoWarn')} `,
1624
+ h('button', { type: 'button', className: 'pb-side-link', onClick: enableAuto }, t('autoEnable')),
1625
+ )
1626
+ : null,
1627
+ !snapshot
1628
+ ? h('div', { className: 'pb-loading' }, t('loading'))
1629
+ : h(
1630
+ React.Fragment,
1631
+ null,
1632
+ h(
1633
+ 'section',
1634
+ { className: 'pb-side-section' },
1635
+ h(
1636
+ 'div',
1637
+ { className: 'pb-side-label' },
1638
+ h('span', null, t('sideCompleted')),
1639
+ h('span', null, `${items.filter((item) => item.status === 'done').length}`),
1640
+ ),
1641
+ latestDone
1642
+ ? h(
1643
+ 'div',
1644
+ { className: 'pb-side-card pb-side-done-card' },
1645
+ h(
1646
+ 'div',
1647
+ { className: 'pb-side-task-head' },
1648
+ h('span', { className: 'pb-side-check' }, '✓'),
1649
+ h('span', { className: 'pb-side-done-title' }, latestDone.title),
1650
+ h('span', { className: 'pb-side-meta' }, '100%'),
1651
+ ),
1652
+ latestDone.approach
1653
+ ? h(
1654
+ 'div',
1655
+ { className: 'pb-side-detail-line' },
1656
+ h('b', null, t('approach')),
1657
+ `:${latestDone.approach}`,
1658
+ )
1659
+ : null,
1660
+ latestDone.note ? h('p', { className: 'pb-side-note' }, latestDone.note) : null,
1661
+ h(
1662
+ 'div',
1663
+ { className: 'pb-side-detail-line' },
1664
+ `${t('lastUpdate')} ${new Date(latestDone.updatedAt).toLocaleString()}`,
1665
+ ),
1666
+ )
1667
+ : h('div', { className: 'pb-side-empty' }, t('sideEmptyDone')),
1668
+ otherDone.length
1669
+ ? h(
1670
+ 'details',
1671
+ { className: 'pb-side-done-all' },
1672
+ h('summary', null, `${t('sideAllDone')} (${otherDone.length})`),
1673
+ otherDone.map((item) =>
1674
+ h(
1675
+ 'details',
1676
+ { key: item.id, className: 'pb-side-done-item' },
1677
+ h(
1678
+ 'summary',
1679
+ null,
1680
+ h('span', { className: 'pb-side-check' }, '✓'),
1681
+ h('span', { className: 'pb-side-done-title' }, item.title),
1682
+ h('span', { className: 'pb-side-meta' }, '100%'),
1683
+ ),
1684
+ item.approach
1685
+ ? h(
1686
+ 'div',
1687
+ { className: 'pb-side-detail-line' },
1688
+ h('b', null, t('approach')),
1689
+ `:${item.approach}`,
1690
+ )
1691
+ : null,
1692
+ item.note ? h('p', { className: 'pb-side-note' }, item.note) : null,
1693
+ h(
1694
+ 'div',
1695
+ { className: 'pb-side-detail-line' },
1696
+ `${t('lastUpdate')} ${new Date(item.updatedAt).toLocaleString()}`,
1697
+ ),
1698
+ ),
1699
+ ),
1700
+ )
1701
+ : null,
1702
+ ),
1703
+ h(
1704
+ 'section',
1705
+ { className: 'pb-side-section' },
1706
+ h(
1707
+ 'div',
1708
+ { className: 'pb-side-label' },
1709
+ h('span', null, t('sideDetails')),
1710
+ current ? h('span', null, `${current.percent}%`) : null,
1711
+ ),
1712
+ current
1713
+ ? h(SideTaskEditor, {
1714
+ key: current.id,
1715
+ item: current,
1716
+ t,
1717
+ disabled: saving,
1718
+ onPatch: (fields) => mutate([{ id: current.id, ...fields }]),
1719
+ })
1720
+ : h('div', { className: 'pb-side-empty' }, t('noDoing')),
1721
+ ),
1722
+ h(
1723
+ 'section',
1724
+ { className: 'pb-side-section' },
1725
+ h(
1726
+ 'div',
1727
+ { className: 'pb-side-label' },
1728
+ h('span', null, t('sidePending')),
1729
+ h('span', null, `${pending.length}`),
1730
+ ),
1731
+ pending.length
1732
+ ? pending.map((item) =>
1733
+ h(SideTaskEditor, {
1734
+ key: item.id,
1735
+ item,
1736
+ t,
1737
+ disabled: saving,
1738
+ onPatch: (fields) => mutate([{ id: item.id, ...fields }]),
1739
+ }),
1740
+ )
1741
+ : h('div', { className: 'pb-side-empty' }, t('sideEmptyPending')),
1742
+ ),
1743
+ h(AddTask, {
1744
+ t,
1745
+ disabled: saving,
1746
+ onAdd: (title) =>
1747
+ mutate([{ title, status: 'todo', percent: 0, current: '', next: '', approach: '', note: '' }]),
1748
+ }),
1749
+ h(
1750
+ 'footer',
1751
+ { className: 'pb-side-footer' },
1752
+ h('button', { type: 'button', className: 'pb-side-link', onClick: openFull }, t('sideOpenFull')),
1753
+ h('button', { type: 'button', className: 'pb-side-link', onClick: refresh }, t('refresh')),
1754
+ h('span', null, `${t('revision')} ${snapshot.revision}`),
1755
+ h(
1756
+ 'span',
1757
+ null,
1758
+ `${t('lastSync')} ${
1759
+ lastSyncAt
1760
+ ? new Date(lastSyncAt).toLocaleTimeString([], {
1761
+ hour: '2-digit',
1762
+ minute: '2-digit',
1763
+ second: '2-digit',
1764
+ })
1765
+ : '—'
1766
+ }`,
1767
+ ),
1768
+ h('span', null, snapshot.persistent ? t('saved') : t('memoryOnly')),
1769
+ ),
1770
+ ),
1771
+ ),
1772
+ )
1773
+ }
1774
+
1775
+ function ProgressPanel(props) {
1776
+ const t = makeT(props)
1777
+ const sessionId = props.useSessions
1778
+ ? props.useSessions((state) => {
1779
+ const rows = Object.values(state.byId || {})
1780
+ const current = rows.find((row) => (row.retainedBy?.mainView ?? 0) > 0)
1781
+ return current?.id
1782
+ })
1783
+ : undefined
1784
+
1785
+ const [snapshot, setSnapshot] = useState(null)
1786
+ const usageView = usageSummary(useSessionUsage(sessionId, props.usage))
1787
+ const [loading, setLoading] = useState(true)
1788
+ const [saving, setSaving] = useState(false)
1789
+ const [loadError, setLoadError] = useState('')
1790
+ const [actionError, setActionError] = useState('')
1791
+ const [tick, setTick] = useState(0)
1792
+ const revisionRef = useRef(0)
1793
+
1794
+ useEffect(() => {
1795
+ revisionRef.current = snapshot?.revision ?? 0
1796
+ }, [snapshot?.revision])
1797
+
1798
+ useEffect(() => {
1799
+ if (!sessionId) return undefined
1800
+ // The full main panel keeps agent updates on just like the sidebar
1801
+ // body; there is no cleanup, so leaving the panel does not disable it.
1802
+ setPanelActive(sessionId, true)
1803
+ return undefined
1804
+ }, [sessionId])
1805
+
1806
+ const enableAuto = async () => {
1807
+ if (!sessionId) return
1808
+ await setAgentEnabled(sessionId, true)
1809
+ setTick((value) => value + 1)
1810
+ }
1811
+
1812
+ useEffect(() => {
1813
+ if (!sessionId) {
1814
+ setSnapshot(null)
1815
+ setLoading(false)
1816
+ return undefined
1817
+ }
1818
+
1819
+ let active = true
1820
+ let controller
1821
+ setLoading(true)
1822
+
1823
+ const load = async () => {
1824
+ if (controller) controller.abort()
1825
+ const ownController = (controller = new AbortController())
1826
+ try {
1827
+ const response = await fetch(
1828
+ `${API}/snapshot?sessionId=${encodeURIComponent(sessionId)}`,
1829
+ { credentials: 'same-origin', cache: 'no-store', signal: ownController.signal },
1830
+ )
1831
+ if (!response.ok) throw new Error(`HTTP ${response.status}`)
1832
+ const next = await response.json()
1833
+ if (!active) return
1834
+ revisionRef.current = next.revision
1835
+ setSnapshot(next)
1836
+ setLoadError('')
1837
+ setLoading(false)
1838
+ } catch (error) {
1839
+ if (!active || error?.name === 'AbortError') return
1840
+ setLoadError(errorText(error))
1841
+ setLoading(false)
1842
+ }
1843
+ }
1844
+
1845
+ load()
1846
+ const interval = window.setInterval(load, 3000)
1847
+ const onVisibility = () => {
1848
+ if (document.visibilityState === 'visible') load()
1849
+ }
1850
+ document.addEventListener('visibilitychange', onVisibility)
1851
+
1852
+ return () => {
1853
+ active = false
1854
+ window.clearInterval(interval)
1855
+ controller?.abort()
1856
+ document.removeEventListener('visibilitychange', onVisibility)
1857
+ }
1858
+ }, [sessionId, tick])
1859
+
1860
+ const mutate = useCallback(
1861
+ async (changes) => {
1862
+ if (!sessionId) return false
1863
+ setSaving(true)
1864
+ setActionError('')
1865
+ try {
1866
+ let result = await postChanges(sessionId, revisionRef.current, changes)
1867
+ if (result.response.status === 409 && result.body?.snapshot) {
1868
+ revisionRef.current = result.body.snapshot.revision
1869
+ setSnapshot(result.body.snapshot)
1870
+ result = await postChanges(sessionId, revisionRef.current, changes)
1871
+ }
1872
+ const { response, body } = result
1873
+ if (!response.ok || !body || body.ok === false) {
1874
+ if (body?.snapshot) {
1875
+ revisionRef.current = body.snapshot.revision
1876
+ setSnapshot(body.snapshot)
1877
+ }
1878
+ throw new Error(body?.error || `HTTP ${response.status}`)
1879
+ }
1880
+ revisionRef.current = body.revision
1881
+ setSnapshot(body)
1882
+ broadcastProgress(sessionId, body)
1883
+ const addedTitles = (Array.isArray(changes) ? changes : [])
1884
+ .filter((change) => change && !change.id && !change.remove && typeof change.title === 'string')
1885
+ .map((change) => change.title.trim())
1886
+ .filter(Boolean)
1887
+ if (addedTitles.length > 0) {
1888
+ props.wakeAgent?.(
1889
+ sessionId,
1890
+ `我在进度板新增了任务${addedTitles.map((title) => `「${title}」`).join('、')}。请按新任务推进。`,
1891
+ )
1892
+ }
1893
+ return true
1894
+ } catch (error) {
1895
+ setActionError(errorText(error))
1896
+ return false
1897
+ } finally {
1898
+ setSaving(false)
1899
+ }
1900
+ },
1901
+ [sessionId],
1902
+ )
1903
+
1904
+ const patch = useCallback(
1905
+ (item, fields) => mutate([{ id: item.id, ...fields }]),
1906
+ [mutate],
1907
+ )
1908
+
1909
+ const items = snapshot?.items || []
1910
+ const summary = snapshot?.summary || { total: 0, done: 0, doing: 0, todo: 0, blocked: 0, percent: 0 }
1911
+ const doing = items.filter((item) => item.status === 'doing')
1912
+ const todo = items.filter((item) => item.status === 'todo')
1913
+ const blocked = items.filter((item) => item.status === 'blocked')
1914
+ const done = items.filter((item) => item.status === 'done')
1915
+
1916
+ const move = (item, direction) => {
1917
+ const index = items.findIndex((candidate) => candidate.id === item.id)
1918
+ const neighbor = items[index + direction]
1919
+ if (!neighbor) return
1920
+ mutate([
1921
+ { id: item.id, order: neighbor.order },
1922
+ { id: neighbor.id, order: item.order },
1923
+ ])
1924
+ }
1925
+
1926
+ const renderItem = (item) => {
1927
+ const index = items.findIndex((candidate) => candidate.id === item.id)
1928
+ return h(ItemCard, {
1929
+ key: item.id,
1930
+ item,
1931
+ t,
1932
+ disabled: saving,
1933
+ canMoveUp: index > 0,
1934
+ canMoveDown: index >= 0 && index < items.length - 1,
1935
+ onPatch: (fields) => patch(item, fields),
1936
+ onRemove: () => mutate([{ id: item.id, remove: true }]),
1937
+ onMove: (direction) => move(item, direction),
1938
+ })
1939
+ }
1940
+
1941
+ if (!sessionId) {
1942
+ return h(
1943
+ 'div',
1944
+ { className: 'pb-root' },
1945
+ h('style', null, CSS),
1946
+ h(
1947
+ 'div',
1948
+ { className: 'pb-inner' },
1949
+ h(
1950
+ 'header',
1951
+ { className: 'pb-head' },
1952
+ h(
1953
+ 'div',
1954
+ null,
1955
+ h('h1', { className: 'pb-title' }, t('title')),
1956
+ h('p', { className: 'pb-sub' }, t('subtitle')),
1957
+ ),
1958
+ ),
1959
+ h(
1960
+ 'div',
1961
+ { className: 'pb-empty' },
1962
+ h('h2', null, t('noSessionTitle')),
1963
+ h('p', null, t('noSessionBody')),
1964
+ ),
1965
+ ),
1966
+ )
1967
+ }
1968
+
1969
+ const focus = doing[0] || null
1970
+ const updated = snapshot ? new Date(snapshot.updatedAt).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }) : ''
1971
+
1972
+ return h(
1973
+ 'div',
1974
+ { className: 'pb-root' },
1975
+ h('style', null, CSS),
1976
+ h(
1977
+ 'div',
1978
+ { className: 'pb-inner' },
1979
+ h(
1980
+ 'header',
1981
+ { className: 'pb-head' },
1982
+ h(
1983
+ 'div',
1984
+ null,
1985
+ h('h1', { className: 'pb-title' }, t('title')),
1986
+ h('p', { className: 'pb-sub' }, t('subtitle')),
1987
+ ),
1988
+ h(
1989
+ 'div',
1990
+ { className: 'pb-head-right' },
1991
+ saving ? h('span', { className: 'pb-saving' }, t('saving')) : null,
1992
+ snapshot?.pendingUserChanges
1993
+ ? h('span', { className: 'pb-badge-pending' }, `${t('pending')} · ${snapshot.pendingUserChanges}`)
1994
+ : null,
1995
+ usageView
1996
+ ? h(
1997
+ 'span',
1998
+ { className: 'pb-usage pb-usage-inline', title: usageTooltip(usageView, t) },
1999
+ `${formatTokens(usageView.total)} tok${
2000
+ usageView.cost == null ? '' : ` · ≈${formatCny(usageView.cost)}`
2001
+ }`,
2002
+ )
2003
+ : null,
2004
+ h(
2005
+ 'button',
2006
+ {
2007
+ type: 'button',
2008
+ className: snapshot?.enabled === false ? 'pb-btn pb-btn-primary' : 'pb-btn',
2009
+ title: t('autoHint'),
2010
+ onClick: async () => {
2011
+ if (!sessionId) return
2012
+ await setAgentEnabled(sessionId, snapshot?.enabled === false)
2013
+ setTick((value) => value + 1)
2014
+ },
2015
+ },
2016
+ snapshot?.enabled === false ? t('autoOff') : t('autoOn'),
2017
+ ),
2018
+ h(
2019
+ 'span',
2020
+ { className: 'pb-live', title: t('footerHint') },
2021
+ h('i', { className: 'pb-dot' }),
2022
+ t('live'),
2023
+ ),
2024
+ ),
2025
+ ),
2026
+ h(LlmAssistNotice, { assistant: snapshot?.assistant, t: props.t }),
2027
+ snapshot?.enabled === false
2028
+ ? h(
2029
+ 'div',
2030
+ { className: 'pb-warn' },
2031
+ `${t('autoWarn')} `,
2032
+ h(
2033
+ 'button',
2034
+ { type: 'button', className: 'pb-btn', onClick: enableAuto },
2035
+ t('autoEnable'),
2036
+ ),
2037
+ )
2038
+ : null,
2039
+ loadError
2040
+ ? h(
2041
+ 'div',
2042
+ { className: 'pb-warn pb-warn-error' },
2043
+ `${t('readError')}${loadError} `,
2044
+ h(
2045
+ 'button',
2046
+ { type: 'button', className: 'pb-btn', onClick: () => setTick((value) => value + 1) },
2047
+ t('retry'),
2048
+ ),
2049
+ )
2050
+ : null,
2051
+ actionError
2052
+ ? h(
2053
+ 'div',
2054
+ { className: 'pb-warn pb-warn-error' },
2055
+ `${t('saveError')}${actionError}`,
2056
+ )
2057
+ : null,
2058
+ snapshot?.storageError
2059
+ ? h('div', { className: 'pb-warn' }, `${t('storageWarn')} ${snapshot.storageError}`)
2060
+ : null,
2061
+ loading && !snapshot
2062
+ ? h('div', { className: 'pb-loading' }, t('loading'))
2063
+ : h(
2064
+ React.Fragment,
2065
+ null,
2066
+ h(
2067
+ 'section',
2068
+ { className: 'pb-overview' },
2069
+ h(
2070
+ 'div',
2071
+ { className: 'pb-overview-top' },
2072
+ h(
2073
+ 'div',
2074
+ { className: 'pb-big' },
2075
+ String(summary.percent),
2076
+ h('small', null, '%'),
2077
+ ),
2078
+ h(
2079
+ 'div',
2080
+ { className: 'pb-counts' },
2081
+ h('span', { className: 'pb-chip' }, t('statusDone'), h('strong', null, summary.done)),
2082
+ h('span', { className: 'pb-chip' }, t('statusDoing'), h('strong', null, summary.doing)),
2083
+ h('span', { className: 'pb-chip' }, t('statusTodo'), h('strong', null, summary.todo)),
2084
+ h('span', { className: 'pb-chip' }, t('statusBlocked'), h('strong', null, summary.blocked)),
2085
+ ),
2086
+ ),
2087
+ h('div', { className: 'pb-bar' }, h('i', { style: { width: `${summary.percent}%` } })),
2088
+ h(
2089
+ 'div',
2090
+ { className: 'pb-focus' },
2091
+ focus
2092
+ ? h(
2093
+ React.Fragment,
2094
+ null,
2095
+ h('span', null, `${t('doingTitle')}:`),
2096
+ h('b', null, focus.title),
2097
+ focus.current ? h('span', null, ` · ${focus.current}`) : null,
2098
+ )
2099
+ : h('span', null, summary.total > 0 && summary.done === summary.total ? t('allDone') : t('noDoing')),
2100
+ summary.blocked > 0 ? h('span', { className: 'pb-badge-pending' }, `${summary.blocked} ${t('blockedCount')}`) : null,
2101
+ ),
2102
+ ),
2103
+ snapshot?.items?.length === 0
2104
+ ? h(
2105
+ 'div',
2106
+ { className: 'pb-empty' },
2107
+ h('h2', null, t('emptyTitle')),
2108
+ h('p', null, t('emptyBody')),
2109
+ )
2110
+ : h(
2111
+ React.Fragment,
2112
+ null,
2113
+ doing.length
2114
+ ? h(Section, { title: t('doingTitle'), count: doing.length }, doing.map(renderItem))
2115
+ : h(
2116
+ 'section',
2117
+ { className: 'pb-section' },
2118
+ h('p', { className: 'pb-loading', style: { padding: '14px 0' } }, t('emptyDoing')),
2119
+ ),
2120
+ todo.length
2121
+ ? h(Section, { title: t('todoTitle'), count: todo.length }, todo.map(renderItem))
2122
+ : null,
2123
+ blocked.length
2124
+ ? h(
2125
+ Section,
2126
+ { title: t('blockedTitle'), count: blocked.length, hint: t('blockedHint') },
2127
+ blocked.map(renderItem),
2128
+ )
2129
+ : null,
2130
+ done.length
2131
+ ? h(
2132
+ 'details',
2133
+ { className: 'pb-done-box' },
2134
+ h('summary', null, `${t('doneTitle')} · ${done.length} ${t('doneCount')}`),
2135
+ h('div', { className: 'pb-list' }, done.map(renderItem)),
2136
+ )
2137
+ : null,
2138
+ ),
2139
+ h(AddTask, {
2140
+ t,
2141
+ disabled: saving,
2142
+ onAdd: (title) =>
2143
+ mutate([{ title, status: 'todo', percent: 0, current: '', next: '', approach: '', note: '' }]),
2144
+ }),
2145
+ h(
2146
+ 'footer',
2147
+ { className: 'pb-footer' },
2148
+ h('span', null, `${t('editHint')}`),
2149
+ h('span', { className: 'pb-sep' }, '·'),
2150
+ h('span', null, `${t('footerHint')}`),
2151
+ h('span', { className: 'pb-sep' }, '·'),
2152
+ h('span', null, `${t('lastUpdate')} ${updated}`),
2153
+ h('span', null, `${t('revision')} ${snapshot?.revision ?? 0}`),
2154
+ h('span', null, snapshot?.persistent ? t('saved') : t('memoryOnly')),
2155
+ ),
2156
+ ),
2157
+ ),
2158
+ )
2159
+ }
2160
+
2161
+ return {
2162
+ inject: ['slots', 'locale', 'layout', 'sidebarRight', 'sidebarRightTabs', 'sessions'],
2163
+ apply(ctx) {
2164
+ ctx.effect(
2165
+ () =>
2166
+ ctx.locale.register(NS, {
2167
+ zh,
2168
+ en,
2169
+ }),
2170
+ 'progress-union: locale',
2171
+ )
2172
+
2173
+ const t = ctx.locale.bind(NS)
2174
+ const wakeAgent = (sessionId, text) => {
2175
+ try {
2176
+ const binding = ctx.sessions.binding(sessionId)
2177
+ if (!binding) return
2178
+ binding.session.prompt([{ type: 'text', text }], 'queue').catch(() => {})
2179
+ } catch (_error) {
2180
+ // The task is saved; waking is best-effort.
2181
+ }
2182
+ }
2183
+ const openPanel = () => ctx.sidebarRight.openTab(RIGHT_TAB_KIND)
2184
+
2185
+ /*
2186
+ * Live token accounting for one Session. The token-meter unit publishes
2187
+ * `tokenUsage` as a host-computed Session projection, and model
2188
+ * selection is a second projection; reading both faces keeps the
2189
+ * figure current without adding it to the board's 3s HTTP poll.
2190
+ */
2191
+ const usageApi = {
2192
+ read(sessionId) {
2193
+ try {
2194
+ const projectionStore = ctx.sessions.binding(sessionId)?.session?.projections
2195
+ if (!projectionStore?.faceOf) return null
2196
+ const usage = projectionStore.faceOf('tokenUsage')?.getSnapshot?.() ?? null
2197
+ const selection = projectionStore.faceOf('modelSelection')?.getSnapshot?.() ?? null
2198
+ return {
2199
+ usage,
2200
+ model: selection?.lastUsed?.model || selection?.next?.model || null,
2201
+ provider: selection?.lastUsed?.provider || selection?.next?.provider || null,
2202
+ }
2203
+ } catch (_error) {
2204
+ return null
2205
+ }
2206
+ },
2207
+ subscribe(sessionId, listener) {
2208
+ try {
2209
+ const projectionStore = ctx.sessions.binding(sessionId)?.session?.projections
2210
+ if (!projectionStore?.faceOf) return () => {}
2211
+ const offs = []
2212
+ for (const key of ['tokenUsage', 'modelSelection']) {
2213
+ const face = projectionStore.faceOf(key)
2214
+ if (face?.subscribe) offs.push(face.subscribe(listener))
2215
+ }
2216
+ return () => {
2217
+ for (const off of offs) {
2218
+ try {
2219
+ off?.()
2220
+ } catch (_error) {
2221
+ // Projection faces are torn down with the Session.
2222
+ }
2223
+ }
2224
+ }
2225
+ } catch (_error) {
2226
+ return () => {}
2227
+ }
2228
+ },
2229
+ }
2230
+
2231
+ const togglePanel = () => {
2232
+ const active = ctx.sidebarRight.active()
2233
+ if (ctx.sidebarRight.isExpanded() && active?.kind === RIGHT_TAB_KIND) {
2234
+ ctx.sidebarRight.toggleExpanded()
2235
+ return
2236
+ }
2237
+ ctx.sidebarRight.openTab(RIGHT_TAB_KIND)
2238
+ }
2239
+ const openFullPanel = () => ctx.layout.selectPanel(PANEL_ID)
2240
+ const toggleFullscreen = () => {
2241
+ const target = ctx.sidebarRight.focusedTarget() ?? ctx.sidebarRight.commandTarget()
2242
+ if (target) ctx.sidebarRight.toggleFullscreen(target)
2243
+ }
2244
+
2245
+ ctx.effect(
2246
+ () =>
2247
+ ctx.sidebarRightTabs.register({
2248
+ id: RIGHT_TAB_ID,
2249
+ kind: RIGHT_TAB_KIND,
2250
+ priority: 'extension',
2251
+ title: () => t('nav'),
2252
+ }),
2253
+ 'progress-union: right sidebar type',
2254
+ )
2255
+
2256
+ ctx.effect(
2257
+ () =>
2258
+ ctx.slots.inject('sidebar.right.pane.tab', () =>
2259
+ ctx.slots.register(
2260
+ {
2261
+ name: 'sidebar.right.pane.tab',
2262
+ key: RIGHT_TAB_ID,
2263
+ locale: NS,
2264
+ inject: () => ({
2265
+ collapse: () => ctx.sidebarRight.toggleExpanded(),
2266
+ toggleFullscreen,
2267
+ openFullPanel,
2268
+ wakeAgent,
2269
+ usage: usageApi,
2270
+ }),
2271
+ },
2272
+ ProgressSidePanel,
2273
+ ),
2274
+ ),
2275
+ 'progress-union: right sidebar body',
2276
+ )
2277
+
2278
+ ctx.effect(
2279
+ () =>
2280
+ ctx.slots.inject('main', () =>
2281
+ ctx.slots.register(
2282
+ {
2283
+ name: 'main',
2284
+ key: PANEL_ID,
2285
+ locale: NS,
2286
+ inject: () => ({ wakeAgent, usage: usageApi }),
2287
+ },
2288
+ ProgressPanel,
2289
+ ),
2290
+ ),
2291
+ 'progress-union: full panel',
2292
+ )
2293
+
2294
+ ctx.effect(
2295
+ () =>
2296
+ ctx.slots.inject('conversation.session.header.utilities', () =>
2297
+ ctx.slots.register(
2298
+ {
2299
+ name: 'conversation.session.header.utilities',
2300
+ id: 'progress-union-header',
2301
+ order: 12,
2302
+ locale: NS,
2303
+ inject: () => ({ openPanel: togglePanel }),
2304
+ },
2305
+ ProgressHeaderButton,
2306
+ ),
2307
+ ),
2308
+ 'progress-union: header button',
2309
+ )
2310
+
2311
+ ctx.effect(
2312
+ () =>
2313
+ ctx.slots.inject('conversation.input.dock', () =>
2314
+ ctx.slots.register(
2315
+ {
2316
+ name: 'conversation.input.dock',
2317
+ id: 'progress-union-dock',
2318
+ order: 5,
2319
+ locale: NS,
2320
+ inject: () => ({ openPanel, togglePanel, usage: usageApi }),
2321
+ },
2322
+ ProgressDock,
2323
+ ),
2324
+ ),
2325
+ 'progress-union: composer dock',
2326
+ )
2327
+ },
2328
+ }
2329
+ },
2330
+ })