dsh-plugin-inspiration-workbench 0.9.0 → 0.13.2

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.
@@ -0,0 +1,1688 @@
1
+ import { icon } from './icons';
2
+
3
+ const STATUS_ORDER = ['needs_input', 'blocked', 'review', 'running', 'idle', 'done'];
4
+ const STATUS_RANK = Object.fromEntries(STATUS_ORDER.map((status, index) => [status, index]));
5
+ const PRIORITY_RANK = { urgent: 0, high: 1, normal: 2, medium: 2, low: 3 };
6
+
7
+ const COPY = {
8
+ title: ['任务中心', 'Task center'],
9
+ scan: ['整理会话', 'Organize sessions'],
10
+ plan: ['规划需求', 'Plan requirement'],
11
+ refresh: ['刷新', 'Refresh'],
12
+ count: ['{shown} / {total} 项任务', '{shown} / {total} tasks'],
13
+ canvasCount: ['{n} 张画布', '{n} canvases'],
14
+ filter: ['筛选状态', 'Filter by status'],
15
+ filterAll: ['全部任务', 'All tasks'],
16
+ filterAttention: ['待处理', 'Needs attention'],
17
+ sort: ['排序', 'Sort'],
18
+ sortSmart: ['智能排序 · 待处理优先', 'Smart · Actionable first'],
19
+ sortUpdated: ['最近更新', 'Recently updated'],
20
+ sortPriority: ['优先级', 'Priority'],
21
+ sortTitle: ['标题', 'Title'],
22
+ loading: ['正在读取任务…', 'Loading tasks…'],
23
+ loadingDetail: ['正在准备任务详情…', 'Preparing task details…'],
24
+ retry: ['重试', 'Retry'],
25
+ dismiss: ['关闭提示', 'Dismiss message'],
26
+ loadError: ['任务读取失败', 'Could not load tasks'],
27
+ emptyTitle: ['还没有任务', 'No tasks yet'],
28
+ emptyBody: ['整理现有会话,或输入一个需求来生成执行拓扑。', 'Organize existing sessions, or describe a requirement to build an execution topology.'],
29
+ emptyFilter: ['当前筛选下没有任务', 'No tasks match this filter'],
30
+ emptyFilterBody: ['换一个状态筛选,或创建一项新任务。', 'Try another status filter, or create a new task.'],
31
+ noSelection: ['选择一项任务', 'Select a task'],
32
+ noSelectionBody: ['在左侧选择任务,查看目标、待处理事项和交付物。', 'Choose a task on the left to inspect its goal, pending items, and deliverables.'],
33
+ untitled: ['未命名任务', 'Untitled task'],
34
+ noSummary: ['还没有任务摘要。', 'No task summary yet.'],
35
+ goal: ['目标', 'Goal'],
36
+ summary: ['摘要', 'Summary'],
37
+ pending: ['待处理事项', 'Pending items'],
38
+ acceptance: ['验收标准', 'Acceptance criteria'],
39
+ deliverables: ['交付物', 'Deliverables'],
40
+ nodeProgress: ['节点进度', 'Node progress'],
41
+ nodeDoneCount: ['{done}/{total} 个节点已完成', '{done}/{total} nodes completed'],
42
+ sessions: ['关联会话', 'Linked sessions'],
43
+ canvases: ['关联画布', 'Linked canvases'],
44
+ source: ['来源', 'Source'],
45
+ events: ['最近动态', 'Recent activity'],
46
+ none: ['暂无', 'None'],
47
+ updated: ['更新于 {time}', 'Updated {time}'],
48
+ itemCount: ['{n} 项', '{n} items'],
49
+ open: ['进入现场', 'Open workspace'],
50
+ continue: ['续做', 'Continue'],
51
+ continueDone: ['已完成的任务无需续做', 'Completed tasks do not need continuation'],
52
+ accept: ['通过验收', 'Accept'],
53
+ reject: ['返修', 'Request changes'],
54
+ createCanvas: ['生成画布', 'Create canvas'],
55
+ delete: ['删除任务', 'Delete task'],
56
+ editStatus: ['任务状态(自动更新)', 'Task status (auto)'],
57
+ autoStatus: ['自动更新', 'Auto'],
58
+ editPriority: ['优先级', 'Priority'],
59
+ openSession: ['打开会话', 'Open session'],
60
+ handle: ['处理', 'Handle'],
61
+ moreEvents: ['仅显示最近 {shown} 条,共 {total} 条', 'Showing the latest {shown} of {total} events'],
62
+ updatedTask: ['任务已更新', 'Task updated'],
63
+ reviewedAccept: ['已通过验收', 'Task accepted'],
64
+ reviewedReject: ['已退回返修', 'Changes requested'],
65
+ canvasCreated: ['任务画布已创建', 'Task canvas created'],
66
+ deleted: ['任务已删除', 'Task deleted'],
67
+ deleteTitle: ['删除这项任务?', 'Delete this task?'],
68
+ deleteBody: ['将删除「{name}」及其任务记录,关联会话和画布本身不会被删除。', 'Delete “{name}” and its task record. Linked sessions and canvases themselves will not be deleted.'],
69
+ cancel: ['取消', 'Cancel'],
70
+ close: ['关闭', 'Close'],
71
+ confirmDelete: ['确认删除', 'Delete task'],
72
+ actionMissing: ['当前环境未提供 {name} 操作', 'The {name} action is unavailable in this environment'],
73
+ actionFailed: ['操作失败,请重试', 'The action failed. Please try again'],
74
+ selected: ['已选择 {n} 项', '{n} selected'],
75
+ selectAll: ['全选', 'Select all'],
76
+ useAI: ['使用 AI 辅助分析', 'Use AI-assisted analysis'],
77
+ scanTitle: ['从会话整理任务', 'Organize tasks from sessions'],
78
+ scanIntro: ['选择要整理的会话。扫描后可以先检查草案,再决定哪些进入任务中心。', 'Choose sessions to organize. Review the drafts before adding them to the task center.'],
79
+ sessionsLoading: ['正在读取会话列表…', 'Loading sessions…'],
80
+ sessionsEmpty: ['没有可整理的会话', 'No sessions available'],
81
+ sessionsEmptyBody: ['先开始一个会话,再回来整理任务。', 'Start a session first, then come back to organize it.'],
82
+ sessionsError: ['会话列表读取失败', 'Could not load sessions'],
83
+ reloadSessions: ['重新读取', 'Reload sessions'],
84
+ scanRun: ['扫描并生成草案', 'Scan and create drafts'],
85
+ scanning: ['正在分析会话并提炼任务…', 'Analyzing sessions and extracting tasks…'],
86
+ scanError: ['会话整理失败', 'Could not organize sessions'],
87
+ draftsTitle: ['选择任务草案', 'Choose task drafts'],
88
+ draftsEmpty: ['没有发现可新增的任务', 'No new tasks found'],
89
+ draftsEmptyBody: ['可以返回选择其它会话,或改用需求规划。', 'Go back to choose other sessions, or plan a requirement instead.'],
90
+ back: ['返回', 'Back'],
91
+ addTasks: ['添加 {n} 项任务', 'Add {n} tasks'],
92
+ tasksAdded: ['已添加 {n} 项任务', 'Added {n} tasks'],
93
+ noSessionSelection: ['请至少选择一个会话', 'Select at least one session'],
94
+ scanLimit: ['一次最多整理 12 个会话,请减少选择', 'Select no more than 12 sessions at a time'],
95
+ noDraftSelection: ['请至少选择一个草案', 'Select at least one draft'],
96
+ planTitle: ['把需求拆成执行拓扑', 'Turn a requirement into an execution topology'],
97
+ planIntro: ['描述目标、约束和期望交付物。生成后可以检查节点与依赖,再选择要落地的草案。', 'Describe the goal, constraints, and expected deliverables. Review nodes and dependencies before materializing the selected drafts.'],
98
+ requirement: ['需求描述', 'Requirement'],
99
+ requirementPlaceholder: ['例如:为插件增加任务模式,拆分界面、持久化和测试,并给出验收标准…', 'Example: Add a task mode to the plugin, split UI, persistence and tests, and define acceptance criteria…'],
100
+ workspaceId: ['工作区', 'Workspace'],
101
+ model: ['规划模型', 'Planning model'],
102
+ modelDefault: ['跟随 DSH 默认模型', 'Use DSH default'],
103
+ workspacePlaceholder: ['留空使用当前工作区', 'Leave blank to use the current workspace'],
104
+ workspaceEmpty: ['暂无工作区,请先在 DSH 中添加', 'No workspaces. Add one in DSH first'],
105
+ workspaceRequired: ['当前没有可用工作区,请先在 DSH 中添加后再创建会话', 'Add a workspace in DSH before creating sessions'],
106
+ createWorkspace: ['新建工作区', 'Create workspace'],
107
+ workspacePath: ['工作区绝对路径', 'Absolute workspace path'],
108
+ workspacePathPlaceholder: ['例如:/Users/name/project', 'For example: /Users/name/project'],
109
+ createWorkspaceConfirm: ['创建并选中', 'Create and select'],
110
+ createWorkspaceCancel: ['取消新建', 'Cancel'],
111
+ generatePlan: ['生成拓扑草案', 'Generate topology'],
112
+ planning: ['正在分析需求并规划依赖…', 'Analyzing the requirement and planning dependencies…'],
113
+ planError: ['需求规划失败', 'Could not plan the requirement'],
114
+ requirementRequired: ['请先填写需求描述', 'Describe the requirement first'],
115
+ planEmpty: ['没有生成可落地的节点', 'No materializable nodes were generated'],
116
+ planEmptyBody: ['返回补充目标和交付物,然后重新生成。', 'Go back to add goals and deliverables, then generate again.'],
117
+ planReview: ['检查拓扑与草案', 'Review topology and drafts'],
118
+ startAfter: ['创建后立即开始执行', 'Start immediately after creation'],
119
+ materialize: ['创建 {n} 项任务', 'Create {n} tasks'],
120
+ materialized: ['任务拓扑已创建', 'Task topology created'],
121
+ editRequirement: ['修改需求', 'Edit requirement'],
122
+ node: ['节点 {n}', 'Node {n}'],
123
+ dependencies: ['依赖:{name}', 'Depends on: {name}'],
124
+ noDependencies: ['无前置依赖', 'No dependencies'],
125
+ edges: ['依赖连接', 'Dependency edges'],
126
+ noEdges: ['节点之间没有额外连接', 'No additional links between nodes'],
127
+ sessionNode: ['会话', 'Session'],
128
+ noteNode: ['便签', 'Note'],
129
+ taskNode: ['任务', 'Task'],
130
+ 'status.needs_input': ['待输入', 'Needs input'],
131
+ 'status.blocked': ['受阻', 'Blocked'],
132
+ 'status.review': ['待验收', 'In review'],
133
+ 'status.running': ['进行中', 'Running'],
134
+ 'status.idle': ['待开始', 'Idle'],
135
+ 'status.done': ['已完成', 'Done'],
136
+ 'status.attention': ['待处理', 'Needs attention'],
137
+ 'review.pending': ['尚未提交验收', 'Not submitted for review'],
138
+ 'review.review': ['等待验收', 'Waiting for review'],
139
+ 'review.accepted': ['验收已通过', 'Accepted'],
140
+ 'review.rejected': ['已退回返修', 'Changes requested'],
141
+ 'priority.urgent': ['紧急', 'Urgent'],
142
+ 'priority.high': ['高优先级', 'High'],
143
+ 'priority.normal': ['普通', 'Normal'],
144
+ 'priority.medium': ['普通', 'Normal'],
145
+ 'priority.low': ['低优先级', 'Low'],
146
+ };
147
+
148
+ function token(value) {
149
+ return String(value ?? '').trim().toLowerCase().replace(/[\s-]+/g, '_');
150
+ }
151
+
152
+ function text(value) {
153
+ if (typeof value === 'string') return value.trim();
154
+ if (typeof value === 'number' && Number.isFinite(value)) return String(value);
155
+ return '';
156
+ }
157
+
158
+ function array(value) {
159
+ return Array.isArray(value) ? value : [];
160
+ }
161
+
162
+ function timestamp(value) {
163
+ if (typeof value === 'number' && Number.isFinite(value)) return value;
164
+ const raw = text(value);
165
+ if (!raw) return 0;
166
+ if (Number.isFinite(Number(raw))) return Number(raw);
167
+ const parsed = Date.parse(raw);
168
+ return Number.isFinite(parsed) ? parsed : 0;
169
+ }
170
+
171
+ function errorText(error) {
172
+ if (error instanceof Error && error.message) return error.message;
173
+ if (typeof error === 'string' && error.trim()) return error;
174
+ return '';
175
+ }
176
+
177
+ function itemText(item) {
178
+ if (typeof item === 'string' || typeof item === 'number') return text(item);
179
+ if (!item || typeof item !== 'object') return '';
180
+ return text(item.title ?? item.text ?? item.label ?? item.message ?? item.summary ?? item.goal ?? item.name ?? item.path ?? item.url ?? item.kind ?? item.type);
181
+ }
182
+
183
+ function endpointId(endpoint) {
184
+ if (endpoint && typeof endpoint === 'object') return text(endpoint.id ?? endpoint.nodeId ?? endpoint.taskId);
185
+ return text(endpoint);
186
+ }
187
+
188
+ export function createTaskView({ host, t, el, getSnapshot, actions = {}, toast }) {
189
+ const doc = host?.ownerDocument || document;
190
+ const make = el || ((tag, className, html) => {
191
+ const node = doc.createElement(tag);
192
+ if (className) node.className = className;
193
+ if (html != null) node.innerHTML = html;
194
+ return node;
195
+ });
196
+ const localeTitle = typeof t === 'function' ? t('title') : '';
197
+ const english = /inspiration|english/i.test(localeTitle) || /^en(?:-|$)/i.test(doc.documentElement?.lang || '');
198
+ const copy = (key, variables = {}) => {
199
+ const translationKey = 'task.' + key;
200
+ let value = typeof t === 'function' ? t(translationKey) : '';
201
+ if (!value || value === translationKey) value = (COPY[key] || [key, key])[english ? 1 : 0];
202
+ return String(value).replace(/\{(\w+)\}/g, (match, name) => variables[name] == null ? match : String(variables[name]));
203
+ };
204
+ const notify = (message) => {
205
+ if (!message || typeof toast !== 'function') return;
206
+ try { toast(message); } catch { /* a toast must never interrupt an action */ }
207
+ };
208
+
209
+ const state = {
210
+ tasks: [],
211
+ canvases: [],
212
+ selectedId: null,
213
+ filter: 'all',
214
+ sort: 'smart',
215
+ loading: true,
216
+ loaded: false,
217
+ error: '',
218
+ };
219
+ const busy = new Set();
220
+ const dialogBusy = new WeakMap();
221
+ const dialogs = new Set();
222
+ let disposed = false;
223
+ let refreshVersion = 0;
224
+ let dialogSequence = 0;
225
+
226
+ const root = make('div', 'iwb-root iwb-task-view');
227
+ root.setAttribute('aria-label', copy('title'));
228
+ const toolbar = make('div', 'iwb-toolbar iwb-task-toolbar');
229
+ const titles = make('div', 'iwb-titles');
230
+ const titleNode = make('div', 'iwb-title');
231
+ titleNode.textContent = copy('title');
232
+ const countsNode = make('div', 'iwb-counts');
233
+ titles.append(titleNode, countsNode);
234
+ const toolbarActions = make('div', 'iwb-toolbar-actions');
235
+ toolbar.append(titles, toolbarActions);
236
+ root.appendChild(toolbar);
237
+
238
+ function button(label, options = {}) {
239
+ const node = make('button', 'iwb-btn' + (options.className ? ' ' + options.className : ''));
240
+ node.type = 'button';
241
+ if (options.icon) node.innerHTML = icon(options.icon, 13);
242
+ const caption = make('span');
243
+ caption.textContent = label;
244
+ node.appendChild(caption);
245
+ if (options.action) node.dataset.action = options.action;
246
+ if (options.taskId != null) node.dataset.taskId = String(options.taskId);
247
+ if (options.busyKey) node.dataset.busyKey = options.busyKey;
248
+ if (options.busyScope) node.dataset.busyScope = options.busyScope;
249
+ if (options.focusKey) node.dataset.focusKey = options.focusKey;
250
+ if (options.async !== false) node.dataset.async = 'true';
251
+ if (options.disabled) node.dataset.staticDisabled = 'true';
252
+ if (options.title) node.title = options.title;
253
+ if (options.label) node.setAttribute('aria-label', options.label);
254
+ return node;
255
+ }
256
+
257
+ const scanButton = button(copy('scan'), { icon: 'list', busyScope: 'scan', action: 'scan', title: copy('scanTitle') });
258
+ const planButton = button(copy('plan'), { icon: 'sparkle', className: 'primary', busyScope: 'plan', action: 'plan', title: copy('planTitle') });
259
+ toolbarActions.append(scanButton, planButton);
260
+
261
+ const controls = make('div', 'iwb-task-controls');
262
+ const filterField = make('label', 'iwb-task-control');
263
+ const filterLabel = make('span', 'iwb-task-control-label');
264
+ filterLabel.textContent = copy('filter');
265
+ const filterSelect = make('select', 'iwb-task-select-control');
266
+ filterSelect.dataset.focusKey = 'filter';
267
+ filterSelect.setAttribute('aria-label', copy('filter'));
268
+ const filterOptions = [
269
+ ['all', copy('filterAll')],
270
+ ['attention', copy('filterAttention')],
271
+ ...STATUS_ORDER.map((status) => [status, copy('status.' + status)]),
272
+ ];
273
+ for (const [value, label] of filterOptions) {
274
+ const option = make('option');
275
+ option.value = value;
276
+ option.textContent = label;
277
+ filterSelect.appendChild(option);
278
+ }
279
+ filterField.append(filterLabel, filterSelect);
280
+
281
+ const sortField = make('label', 'iwb-task-control');
282
+ const sortLabel = make('span', 'iwb-task-control-label');
283
+ sortLabel.textContent = copy('sort');
284
+ const sortSelect = make('select', 'iwb-task-select-control');
285
+ sortSelect.dataset.focusKey = 'sort';
286
+ sortSelect.setAttribute('aria-label', copy('sort'));
287
+ for (const [value, key] of [['smart', 'sortSmart'], ['updated', 'sortUpdated'], ['priority', 'sortPriority'], ['title', 'sortTitle']]) {
288
+ const option = make('option');
289
+ option.value = value;
290
+ option.textContent = copy(key);
291
+ sortSelect.appendChild(option);
292
+ }
293
+ sortField.append(sortLabel, sortSelect);
294
+ const refreshButton = button(copy('refresh'), { icon: 'arrange', async: false, action: 'refresh', className: 'iwb-task-refresh', focusKey: 'refresh' });
295
+ controls.append(filterField, sortField, refreshButton);
296
+ root.appendChild(controls);
297
+
298
+ const alertNode = make('div', 'iwb-task-alert');
299
+ alertNode.setAttribute('role', 'alert');
300
+ const alertText = make('span', 'iwb-task-alert-text');
301
+ const alertClose = button('', { icon: 'close', async: false, className: 'icon', label: copy('dismiss'), title: copy('dismiss') });
302
+ alertNode.append(alertText, alertClose);
303
+ alertNode.hidden = true;
304
+ root.appendChild(alertNode);
305
+
306
+ const layout = make('div', 'iwb-task-layout');
307
+ const listPanel = make('section', 'iwb-task-list-panel');
308
+ listPanel.setAttribute('aria-label', copy('filterAll'));
309
+ const listHead = make('div', 'iwb-task-list-head');
310
+ const listCount = make('span', 'iwb-task-list-count');
311
+ listHead.appendChild(listCount);
312
+ const listNode = make('div', 'iwb-task-list');
313
+ listNode.setAttribute('role', 'list');
314
+ listPanel.append(listHead, listNode);
315
+ const detailNode = make('section', 'iwb-task-detail');
316
+ detailNode.setAttribute('aria-label', copy('noSelection'));
317
+ layout.append(listPanel, detailNode);
318
+ root.appendChild(layout);
319
+
320
+ function priorityOf(task) {
321
+ const raw = task.priority && typeof task.priority === 'object' ? task.priority.value ?? task.priority.level : task.priority;
322
+ if (typeof raw === 'number') return raw <= 0 ? 'urgent' : raw === 1 ? 'high' : raw >= 3 ? 'low' : 'normal';
323
+ const value = token(raw);
324
+ return Object.hasOwn(PRIORITY_RANK, value) ? value : 'normal';
325
+ }
326
+
327
+ function reviewOf(task) {
328
+ const value = token(task.reviewStatus ?? task.acceptanceStatus ?? task.acceptance?.status);
329
+ if (['review', 'in_review', 'awaiting_review'].includes(value)) return 'review';
330
+ if (['accepted', 'approved', 'passed', 'not_required'].includes(value)) return 'accepted';
331
+ if (['rejected', 'denied', 'changes_requested'].includes(value)) return 'rejected';
332
+ return 'pending';
333
+ }
334
+
335
+ function statusOf(task) {
336
+ const overall = token(task.status);
337
+ if (Object.hasOwn(STATUS_RANK, overall)) return overall;
338
+ const execution = token(task.executionStatus ?? task.execution?.status);
339
+ const review = reviewOf(task);
340
+ if (['needs_input', 'need_input', 'waiting_input', 'awaiting_input', 'question', 'approval'].includes(execution)) return 'needs_input';
341
+ if (['blocked', 'failed', 'failure', 'error'].includes(execution)) return 'blocked';
342
+ if (review === 'review' || overall === 'review') return 'review';
343
+ if (['running', 'active', 'in_progress'].includes(execution)) return 'running';
344
+ if (['done', 'complete', 'completed', 'succeeded'].includes(execution) || overall === 'done') {
345
+ return review === 'accepted' ? 'done' : 'review';
346
+ }
347
+ return 'idle';
348
+ }
349
+
350
+ function viewOf(task, index) {
351
+ const id = text(task?.id) || 'task-' + index;
352
+ const pending = array(task?.pending);
353
+ const canvasIds = array(task?.canvasIds).map(String);
354
+ const canvasNames = array(task?.canvasNames).map(itemText).filter(Boolean);
355
+ for (const canvasId of canvasIds) {
356
+ const canvas = state.canvases.find((entry) => String(entry?.id ?? entry?.canvasId) === canvasId);
357
+ const name = itemText(canvas);
358
+ if (name && !canvasNames.includes(name)) canvasNames.push(name);
359
+ }
360
+ return {
361
+ raw: task,
362
+ index,
363
+ id,
364
+ title: text(task?.title) || copy('untitled'),
365
+ goal: text(task?.goal),
366
+ summary: text(task?.summary),
367
+ status: statusOf(task || {}),
368
+ reviewStatus: reviewOf(task || {}),
369
+ priority: priorityOf(task || {}),
370
+ pending,
371
+ sessionIds: array(task?.sessionIds).map(String).filter(Boolean),
372
+ canvasIds,
373
+ canvasNames,
374
+ acceptanceCriteria: array(task?.acceptanceCriteria),
375
+ deliverables: array(task?.deliverables),
376
+ updatedAt: timestamp(task?.updatedAt ?? task?.createdAt),
377
+ source: task?.source,
378
+ events: array(task?.events),
379
+ nodes: array(task?.nodes),
380
+ };
381
+ }
382
+
383
+ function needsAttention(task) {
384
+ return task.pending.length > 0 || ['needs_input', 'blocked', 'review'].includes(task.status);
385
+ }
386
+
387
+ function visibleTasks() {
388
+ const filtered = state.tasks.filter((task) => {
389
+ if (state.filter === 'all') return true;
390
+ if (state.filter === 'attention') return needsAttention(task);
391
+ return task.status === state.filter;
392
+ });
393
+ return filtered.sort((left, right) => {
394
+ if (state.sort === 'title') return left.title.localeCompare(right.title) || left.index - right.index;
395
+ if (state.sort === 'updated') return right.updatedAt - left.updatedAt || left.index - right.index;
396
+ if (state.sort === 'priority') {
397
+ return (PRIORITY_RANK[left.priority] - PRIORITY_RANK[right.priority])
398
+ || (Number(needsAttention(right)) - Number(needsAttention(left)))
399
+ || (right.updatedAt - left.updatedAt)
400
+ || (left.index - right.index);
401
+ }
402
+ return (Number(needsAttention(right)) - Number(needsAttention(left)))
403
+ || (STATUS_RANK[left.status] - STATUS_RANK[right.status])
404
+ || (PRIORITY_RANK[left.priority] - PRIORITY_RANK[right.priority])
405
+ || (right.updatedAt - left.updatedAt)
406
+ || (left.index - right.index);
407
+ });
408
+ }
409
+
410
+ function selectedTask() {
411
+ return state.tasks.find((task) => task.id === state.selectedId) || null;
412
+ }
413
+
414
+ function formatTime(value, full = false) {
415
+ const time = timestamp(value);
416
+ if (!time) return '—';
417
+ try {
418
+ return new Intl.DateTimeFormat(english ? 'en-US' : 'zh-CN', full
419
+ ? { dateStyle: 'medium', timeStyle: 'short' }
420
+ : { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' }).format(new Date(time));
421
+ } catch {
422
+ return new Date(time).toLocaleString();
423
+ }
424
+ }
425
+
426
+ function statusBadge(task) {
427
+ const badge = make('span', 'iwb-task-status is-' + task.status);
428
+ badge.textContent = copy('status.' + task.status);
429
+ return badge;
430
+ }
431
+
432
+ function priorityBadge(task) {
433
+ const badge = make('span', 'iwb-task-priority is-' + task.priority);
434
+ badge.textContent = copy('priority.' + task.priority);
435
+ return badge;
436
+ }
437
+
438
+ function stateBlock(kind, title, body, action) {
439
+ const block = make('div', 'iwb-task-state is-' + kind);
440
+ block.setAttribute('role', kind === 'error' ? 'alert' : 'status');
441
+ if (kind === 'loading') {
442
+ const spinner = make('span', 'iwb-task-spinner');
443
+ spinner.setAttribute('aria-hidden', 'true');
444
+ block.appendChild(spinner);
445
+ }
446
+ const heading = make('div', 'iwb-task-state-title');
447
+ heading.textContent = title;
448
+ block.appendChild(heading);
449
+ if (body) {
450
+ const description = make('div', 'iwb-task-state-body');
451
+ description.textContent = body;
452
+ block.appendChild(description);
453
+ }
454
+ if (action) block.appendChild(action);
455
+ return block;
456
+ }
457
+
458
+ function renderAlert() {
459
+ alertNode.hidden = !state.error;
460
+ alertText.textContent = state.error;
461
+ }
462
+
463
+ function taskBusy(taskId) {
464
+ const prefix = 'task:' + taskId + ':';
465
+ return [...busy].some((key) => key.startsWith(prefix));
466
+ }
467
+
468
+ function scopeBusy(scope) {
469
+ if (scope === 'scan') return [...busy].some((key) => key.startsWith('scan:') || key === 'sessions:list');
470
+ if (scope === 'plan') return [...busy].some((key) => key.startsWith('plan:'));
471
+ return false;
472
+ }
473
+
474
+ function syncBusy() {
475
+ if (disposed) return;
476
+ root.setAttribute('aria-busy', String(state.loading));
477
+ const containers = [root, ...[...dialogs].map((entry) => entry.dialog)];
478
+ for (const container of containers) {
479
+ const localBusy = container === root ? null : (dialogBusy.get(container) || new Set());
480
+ for (const control of container.querySelectorAll('button, input, select, textarea')) {
481
+ const isAsync = control.dataset.async === 'true';
482
+ let active = false;
483
+ if (container !== root) active = localBusy.size > 0;
484
+ else if (isAsync && control.dataset.taskId != null) active = taskBusy(control.dataset.taskId);
485
+ else if (isAsync && control.dataset.busyScope) active = scopeBusy(control.dataset.busyScope);
486
+ else if (isAsync && control.dataset.busyKey) active = busy.has(control.dataset.busyKey);
487
+ if (control.dataset.action === 'refresh' && state.loading) active = true;
488
+ control.disabled = control.dataset.staticDisabled === 'true' || active;
489
+ control.classList.toggle('iwb-task-is-loading', Boolean(control.dataset.busyKey && busy.has(control.dataset.busyKey)));
490
+ }
491
+ if (container !== root) container.setAttribute('aria-busy', String(localBusy.size > 0));
492
+ }
493
+ for (const row of listNode.querySelectorAll('[data-task-row]')) {
494
+ row.setAttribute('aria-busy', String(taskBusy(row.dataset.taskRow)));
495
+ }
496
+ const detail = detailNode.querySelector('.iwb-task-detail-inner');
497
+ if (detail) detail.setAttribute('aria-busy', String(Boolean(state.selectedId && taskBusy(state.selectedId))));
498
+ }
499
+
500
+ function rememberFocus() {
501
+ const active = doc.activeElement;
502
+ return active && root.contains(active) ? active.dataset?.focusKey || '' : '';
503
+ }
504
+
505
+ function restoreFocus(focusKey) {
506
+ if (!focusKey) return;
507
+ const target = [...root.querySelectorAll('[data-focus-key]')].find((node) => node.dataset.focusKey === focusKey);
508
+ if (target && !target.disabled) target.focus({ preventScroll: true });
509
+ }
510
+
511
+ function renderList(tasks) {
512
+ listNode.replaceChildren();
513
+ listCount.textContent = copy('count', { shown: tasks.length, total: state.tasks.length });
514
+ if (state.loading) {
515
+ listNode.appendChild(stateBlock('loading', copy('loading')));
516
+ return;
517
+ }
518
+ if (!tasks.length) {
519
+ const filtered = state.tasks.length > 0;
520
+ const retry = !filtered && state.error ? button(copy('retry'), { async: false, action: 'retry' }) : null;
521
+ if (retry) retry.addEventListener('click', () => { void refresh(); });
522
+ listNode.appendChild(stateBlock(
523
+ state.error && !filtered ? 'error' : 'empty',
524
+ state.error && !filtered ? copy('loadError') : filtered ? copy('emptyFilter') : copy('emptyTitle'),
525
+ state.error && !filtered ? state.error : filtered ? copy('emptyFilterBody') : copy('emptyBody'),
526
+ retry
527
+ ));
528
+ return;
529
+ }
530
+ for (const task of tasks) {
531
+ const row = make('article', 'iwb-task-list-item' + (task.id === state.selectedId ? ' is-selected' : ''));
532
+ row.dataset.taskRow = task.id;
533
+ row.setAttribute('role', 'listitem');
534
+ const select = make('button', 'iwb-task-list-select');
535
+ select.type = 'button';
536
+ select.dataset.focusKey = 'list:' + task.id;
537
+ select.setAttribute('aria-current', task.id === state.selectedId ? 'true' : 'false');
538
+ const top = make('span', 'iwb-task-list-top');
539
+ const heading = make('span', 'iwb-task-list-title');
540
+ heading.textContent = task.title;
541
+ top.append(heading, statusBadge(task));
542
+ const summary = make('span', 'iwb-task-list-summary');
543
+ summary.textContent = task.summary || task.goal || copy('noSummary');
544
+ const meta = make('span', 'iwb-task-list-meta');
545
+ const priority = priorityBadge(task);
546
+ const time = make('span', 'iwb-task-list-time');
547
+ time.textContent = formatTime(task.updatedAt);
548
+ time.title = formatTime(task.updatedAt, true);
549
+ meta.append(priority, time);
550
+ if (task.pending.length) {
551
+ const pending = make('span', 'iwb-task-pending-badge');
552
+ pending.textContent = copy('itemCount', { n: task.pending.length });
553
+ pending.title = copy('pending');
554
+ meta.appendChild(pending);
555
+ }
556
+ select.append(top, summary, meta);
557
+ select.addEventListener('click', () => {
558
+ state.selectedId = task.id;
559
+ render();
560
+ });
561
+ select.addEventListener('dblclick', (event) => {
562
+ event.preventDefault();
563
+ void runTaskAction(task, 'openTask');
564
+ });
565
+ row.appendChild(select);
566
+ listNode.appendChild(row);
567
+ }
568
+ }
569
+
570
+ function section(title, items, className) {
571
+ const container = make('section', 'iwb-task-section' + (className ? ' ' + className : ''));
572
+ const heading = make('h3', 'iwb-task-section-title');
573
+ heading.textContent = title;
574
+ container.appendChild(heading);
575
+ if (!items.length) {
576
+ const empty = make('div', 'iwb-task-inline-empty');
577
+ empty.textContent = copy('none');
578
+ container.appendChild(empty);
579
+ return container;
580
+ }
581
+ const list = make('ul', 'iwb-task-fact-list');
582
+ for (const item of items) {
583
+ const row = make('li', 'iwb-task-fact');
584
+ const marker = make('span', 'iwb-task-fact-marker');
585
+ marker.setAttribute('aria-hidden', 'true');
586
+ const content = make('div', 'iwb-task-fact-content');
587
+ const label = make('div', 'iwb-task-fact-text');
588
+ label.textContent = itemText(item) || copy('none');
589
+ content.appendChild(label);
590
+ const detail = item && typeof item === 'object' ? text(item.description ?? item.detail ?? item.reason) : '';
591
+ if (detail && detail !== label.textContent) {
592
+ const description = make('div', 'iwb-task-fact-detail');
593
+ description.textContent = detail;
594
+ content.appendChild(description);
595
+ }
596
+ row.append(marker, content);
597
+ list.appendChild(row);
598
+ }
599
+ container.appendChild(list);
600
+ return container;
601
+ }
602
+
603
+ function renderPending(task) {
604
+ const container = section(copy('pending'), task.pending, 'iwb-task-pending-section');
605
+ const rows = container.querySelectorAll('.iwb-task-fact');
606
+ task.pending.forEach((pending, index) => {
607
+ const sessionId = text(pending?.sessionId ?? pending?.session?.id);
608
+ if (!sessionId || !rows[index]) return;
609
+ const open = button(copy('handle'), {
610
+ icon: 'open', taskId: task.id, className: 'iwb-task-small-action',
611
+ title: copy('openSession') + ' · ' + sessionId,
612
+ });
613
+ open.addEventListener('click', () => { void runTaskAction(task, 'openSession', [sessionId]); });
614
+ rows[index].appendChild(open);
615
+ });
616
+ return container;
617
+ }
618
+
619
+ function renderDetail(task) {
620
+ detailNode.replaceChildren();
621
+ if (state.loading) {
622
+ detailNode.appendChild(stateBlock('loading', copy('loadingDetail')));
623
+ return;
624
+ }
625
+ if (!task) {
626
+ detailNode.appendChild(stateBlock('empty', copy('noSelection'), copy('noSelectionBody')));
627
+ return;
628
+ }
629
+ detailNode.setAttribute('aria-label', task.title);
630
+ const inner = make('div', 'iwb-task-detail-inner');
631
+ inner.setAttribute('aria-busy', String(taskBusy(task.id)));
632
+ const head = make('header', 'iwb-task-detail-head');
633
+ const badges = make('div', 'iwb-task-detail-badges');
634
+ badges.append(statusBadge(task), priorityBadge(task));
635
+ const heading = make('h2', 'iwb-task-detail-title');
636
+ heading.textContent = task.title;
637
+ const time = make('div', 'iwb-task-detail-time');
638
+ time.textContent = copy('updated', { time: formatTime(task.updatedAt) });
639
+ time.title = formatTime(task.updatedAt, true);
640
+ head.append(badges, heading, time);
641
+ inner.appendChild(head);
642
+
643
+ const actionBar = make('div', 'iwb-task-detail-actions');
644
+ const open = button(copy('open'), { icon: 'open', className: 'primary', taskId: task.id, focusKey: 'open:' + task.id });
645
+ open.addEventListener('click', () => { void runTaskAction(task, 'openTask'); });
646
+ const resume = button(copy('continue'), {
647
+ icon: 'flow', taskId: task.id, disabled: task.status === 'done',
648
+ title: task.status === 'done' ? copy('continueDone') : copy('continue'), focusKey: 'continue:' + task.id,
649
+ });
650
+ resume.addEventListener('click', async () => {
651
+ const outcome = await runTaskAction(task, 'continueTask');
652
+ if (outcome.ok) notify(copy('updatedTask'));
653
+ });
654
+ actionBar.append(open, resume);
655
+ if (task.status === 'review' || task.reviewStatus === 'review') {
656
+ const reject = button(copy('reject'), { icon: 'close', taskId: task.id, focusKey: 'reject:' + task.id });
657
+ reject.addEventListener('click', async () => {
658
+ const outcome = await runTaskAction(task, 'reviewTask', [false]);
659
+ if (outcome.ok) notify(copy('reviewedReject'));
660
+ });
661
+ const accept = button(copy('accept'), { icon: 'eye', className: 'iwb-task-accept', taskId: task.id, focusKey: 'accept:' + task.id });
662
+ accept.addEventListener('click', async () => {
663
+ const outcome = await runTaskAction(task, 'reviewTask', [true]);
664
+ if (outcome.ok) notify(copy('reviewedAccept'));
665
+ });
666
+ actionBar.append(reject, accept);
667
+ }
668
+ const canvas = button(copy('createCanvas'), { icon: 'canvas', taskId: task.id, focusKey: 'canvas:' + task.id });
669
+ canvas.addEventListener('click', async () => {
670
+ const outcome = await runTaskAction(task, 'createCanvas');
671
+ if (outcome.ok) notify(copy('canvasCreated'));
672
+ });
673
+ actionBar.appendChild(canvas);
674
+ inner.appendChild(actionBar);
675
+
676
+ const editors = make('div', 'iwb-task-editors');
677
+ const statusField = make('label', 'iwb-task-editor');
678
+ const statusText = make('span', 'iwb-task-editor-label');
679
+ statusText.textContent = copy('editStatus');
680
+ const statusSelect = make('span', 'iwb-task-auto-status');
681
+ statusSelect.dataset.taskId = task.id;
682
+ statusSelect.textContent = copy('status.' + task.status) + ' · ' + copy('autoStatus');
683
+ statusSelect.setAttribute('aria-label', copy('status.' + task.status) + ' · ' + copy('autoStatus'));
684
+ statusField.append(statusText, statusSelect);
685
+
686
+ const priorityField = make('label', 'iwb-task-editor');
687
+ const priorityText = make('span', 'iwb-task-editor-label');
688
+ priorityText.textContent = copy('editPriority');
689
+ const prioritySelect = make('select', 'iwb-task-select-control');
690
+ prioritySelect.dataset.async = 'true';
691
+ prioritySelect.dataset.taskId = task.id;
692
+ prioritySelect.dataset.focusKey = 'priority:' + task.id;
693
+ for (const priority of ['urgent', 'high', 'normal', 'low']) {
694
+ const option = make('option');
695
+ option.value = priority;
696
+ option.textContent = copy('priority.' + priority);
697
+ prioritySelect.appendChild(option);
698
+ }
699
+ prioritySelect.value = task.priority === 'medium' ? 'normal' : task.priority;
700
+ prioritySelect.addEventListener('change', async () => {
701
+ const next = prioritySelect.value;
702
+ const outcome = await runTaskAction(task, 'updateTask', [{ priority: next }]);
703
+ if (outcome.ok) notify(copy('updatedTask'));
704
+ else prioritySelect.value = task.priority;
705
+ });
706
+ priorityField.append(priorityText, prioritySelect);
707
+ const spacer = make('span', 'iwb-task-editor-spacer');
708
+ const remove = button(copy('delete'), {
709
+ icon: 'close', className: 'iwb-task-danger', taskId: task.id, focusKey: 'delete:' + task.id,
710
+ });
711
+ remove.addEventListener('click', () => { openDeleteDialog(task, remove); });
712
+ editors.append(statusField, priorityField, spacer, remove);
713
+ inner.appendChild(editors);
714
+
715
+ if (task.goal) {
716
+ const goal = make('section', 'iwb-task-goal');
717
+ const label = make('h3', 'iwb-task-section-title');
718
+ label.textContent = copy('goal');
719
+ const content = make('p');
720
+ content.textContent = task.goal;
721
+ goal.append(label, content);
722
+ inner.appendChild(goal);
723
+ }
724
+ const summary = make('section', 'iwb-task-summary');
725
+ const summaryTitle = make('h3', 'iwb-task-section-title');
726
+ summaryTitle.textContent = copy('summary');
727
+ const summaryText = make('p');
728
+ summaryText.textContent = task.summary || copy('noSummary');
729
+ summary.append(summaryTitle, summaryText);
730
+ inner.appendChild(summary);
731
+ if (task.nodes?.length) {
732
+ const nodes = make('section', 'iwb-task-section iwb-task-nodes');
733
+ const title = make('h3', 'iwb-task-section-title');
734
+ const doneCount = task.nodes.filter((node) => node.status === 'done').length;
735
+ title.textContent = copy('nodeProgress') + ' · ' + copy('nodeDoneCount', { done: doneCount, total: task.nodes.length });
736
+ const list = make('div', 'iwb-task-node-list');
737
+ for (const node of task.nodes) {
738
+ const row = make('div', 'iwb-task-node-row');
739
+ const info = make('div', 'iwb-task-node-info');
740
+ const name = make('span', 'iwb-task-node-title');
741
+ name.textContent = node.title || node.id;
742
+ const kind = make('span', 'iwb-task-node-kind');
743
+ kind.textContent = node.kind === 'note' ? copy('noteNode') : copy('sessionNode');
744
+ const status = make('span', 'iwb-task-node-status is-' + (node.status || 'idle'));
745
+ status.textContent = copy('status.' + (node.status || 'idle'));
746
+ info.append(name, kind);
747
+ row.append(info, status);
748
+ list.appendChild(row);
749
+ }
750
+ nodes.append(title, list);
751
+ inner.appendChild(nodes);
752
+ }
753
+ if (task.pending.length) inner.appendChild(renderPending(task));
754
+ inner.appendChild(section(copy('acceptance'), task.acceptanceCriteria));
755
+ inner.appendChild(section(copy('deliverables'), task.deliverables, 'iwb-task-deliverables'));
756
+
757
+ const links = make('div', 'iwb-task-links-grid');
758
+ const sessionSection = make('section', 'iwb-task-section');
759
+ const sessionTitle = make('h3', 'iwb-task-section-title');
760
+ sessionTitle.textContent = copy('sessions');
761
+ const sessionList = make('div', 'iwb-task-chip-list');
762
+ if (!task.sessionIds.length) {
763
+ const empty = make('span', 'iwb-task-inline-empty');
764
+ empty.textContent = copy('none');
765
+ sessionList.appendChild(empty);
766
+ }
767
+ for (const sessionId of task.sessionIds) {
768
+ const chip = button(sessionId, {
769
+ icon: 'open', className: 'iwb-task-chip', taskId: task.id,
770
+ title: copy('openSession') + ' · ' + sessionId,
771
+ });
772
+ chip.addEventListener('click', () => { void runTaskAction(task, 'openSession', [sessionId]); });
773
+ sessionList.appendChild(chip);
774
+ }
775
+ sessionSection.append(sessionTitle, sessionList);
776
+ const canvasSection = make('section', 'iwb-task-section');
777
+ const canvasTitle = make('h3', 'iwb-task-section-title');
778
+ canvasTitle.textContent = copy('canvases');
779
+ const canvasList = make('div', 'iwb-task-chip-list');
780
+ if (!task.canvasNames.length) {
781
+ const empty = make('span', 'iwb-task-inline-empty');
782
+ empty.textContent = copy('none');
783
+ canvasList.appendChild(empty);
784
+ }
785
+ for (const name of task.canvasNames) {
786
+ const chip = make('span', 'iwb-task-chip is-static');
787
+ chip.textContent = name;
788
+ canvasList.appendChild(chip);
789
+ }
790
+ canvasSection.append(canvasTitle, canvasList);
791
+ links.append(sessionSection, canvasSection);
792
+ inner.appendChild(links);
793
+
794
+ const sourceText = itemText(task.source);
795
+ if (sourceText) {
796
+ const source = make('div', 'iwb-task-source');
797
+ const label = make('span');
798
+ label.textContent = copy('source');
799
+ const value = make('span');
800
+ value.textContent = sourceText;
801
+ source.append(label, value);
802
+ inner.appendChild(source);
803
+ }
804
+ if (task.events.length) {
805
+ const eventSection = make('section', 'iwb-task-section iwb-task-events');
806
+ const eventTitle = make('h3', 'iwb-task-section-title');
807
+ eventTitle.textContent = copy('events');
808
+ const eventList = make('ol', 'iwb-task-event-list');
809
+ const events = task.events.slice(-6).reverse();
810
+ for (const event of events) {
811
+ const row = make('li', 'iwb-task-event');
812
+ const marker = make('span', 'iwb-task-event-marker');
813
+ marker.setAttribute('aria-hidden', 'true');
814
+ const body = make('div', 'iwb-task-event-body');
815
+ const eventLabel = make('div', 'iwb-task-event-title');
816
+ const stateLabel = text(event?.state ?? event?.status ?? event?.type ?? event?.action);
817
+ eventLabel.textContent = itemText(event) || stateLabel || copy('updatedTask');
818
+ const eventTime = make('time', 'iwb-task-event-time');
819
+ const at = event?.timestamp ?? event?.at ?? event?.updatedAt ?? event?.createdAt;
820
+ eventTime.textContent = formatTime(at);
821
+ eventTime.title = formatTime(at, true);
822
+ body.append(eventLabel, eventTime);
823
+ row.append(marker, body);
824
+ eventList.appendChild(row);
825
+ }
826
+ eventSection.append(eventTitle, eventList);
827
+ if (task.events.length > events.length) {
828
+ const note = make('div', 'iwb-task-event-note');
829
+ note.textContent = copy('moreEvents', { shown: events.length, total: task.events.length });
830
+ eventSection.appendChild(note);
831
+ }
832
+ inner.appendChild(eventSection);
833
+ }
834
+ detailNode.appendChild(inner);
835
+ }
836
+
837
+ function render() {
838
+ if (disposed) return;
839
+ const focusKey = rememberFocus();
840
+ const tasks = visibleTasks();
841
+ if (!tasks.some((task) => task.id === state.selectedId)) state.selectedId = tasks[0]?.id || null;
842
+ countsNode.textContent = copy('count', { shown: tasks.length, total: state.tasks.length })
843
+ + ' · ' + copy('canvasCount', { n: state.canvases.length });
844
+ filterSelect.value = state.filter;
845
+ sortSelect.value = state.sort;
846
+ renderAlert();
847
+ renderList(tasks);
848
+ renderDetail(selectedTask());
849
+ syncBusy();
850
+ restoreFocus(focusKey);
851
+ }
852
+
853
+ function applySnapshot(snapshot) {
854
+ const value = snapshot && typeof snapshot === 'object' ? snapshot : {};
855
+ state.canvases = array(value.canvases);
856
+ state.tasks = array(value.tasks).map((task, index) => viewOf(task || {}, index));
857
+ state.loading = false;
858
+ state.loaded = true;
859
+ state.error = '';
860
+ render();
861
+ return snapshot;
862
+ }
863
+
864
+ function failSnapshot(error) {
865
+ state.loading = false;
866
+ state.loaded = true;
867
+ state.error = errorText(error) || copy('loadError');
868
+ render();
869
+ return null;
870
+ }
871
+
872
+ function refresh() {
873
+ if (disposed) return null;
874
+ const version = ++refreshVersion;
875
+ let snapshot;
876
+ try {
877
+ snapshot = typeof getSnapshot === 'function' ? getSnapshot() : {};
878
+ } catch (error) {
879
+ return failSnapshot(error);
880
+ }
881
+ if (snapshot && typeof snapshot.then === 'function') {
882
+ state.loading = true;
883
+ render();
884
+ return Promise.resolve(snapshot)
885
+ .then((value) => version === refreshVersion && !disposed ? applySnapshot(value) : null)
886
+ .catch((error) => version === refreshVersion && !disposed ? failSnapshot(error) : null);
887
+ }
888
+ return applySnapshot(snapshot);
889
+ }
890
+
891
+ function requireAction(name) {
892
+ const action = actions?.[name];
893
+ if (typeof action !== 'function') throw new Error(copy('actionMissing', { name }));
894
+ return action;
895
+ }
896
+
897
+ function clearError(dialog) {
898
+ if (dialog) dialog.clearError();
899
+ else {
900
+ state.error = '';
901
+ renderAlert();
902
+ }
903
+ }
904
+
905
+ async function runBusy(key, operation, options = {}) {
906
+ if (disposed || busy.has(key)) return { ok: false, cancelled: true };
907
+ const dialog = options.dialog || null;
908
+ busy.add(key);
909
+ if (dialog) {
910
+ const keys = dialogBusy.get(dialog.dialog) || new Set();
911
+ keys.add(key);
912
+ dialogBusy.set(dialog.dialog, keys);
913
+ }
914
+ clearError(dialog);
915
+ syncBusy();
916
+ try {
917
+ const value = await Promise.resolve().then(operation);
918
+ if (value && value.ok === false) throw new Error(errorText(value.error) || copy('actionFailed'));
919
+ if (options.refresh && !disposed) await refresh();
920
+ return { ok: true, value };
921
+ } catch (error) {
922
+ const message = errorText(error) || copy('actionFailed');
923
+ if (!disposed) {
924
+ if (dialog?.isOpen()) dialog.setError(message);
925
+ else {
926
+ state.error = message;
927
+ renderAlert();
928
+ }
929
+ notify(message);
930
+ }
931
+ return { ok: false, error };
932
+ } finally {
933
+ busy.delete(key);
934
+ if (dialog) {
935
+ const keys = dialogBusy.get(dialog.dialog);
936
+ keys?.delete(key);
937
+ }
938
+ syncBusy();
939
+ }
940
+ }
941
+
942
+ function runTaskAction(task, name, args = [], dialog = null, refreshAction = true) {
943
+ return runBusy('task:' + task.id + ':' + name, () => requireAction(name)(task.raw, ...args), {
944
+ dialog,
945
+ refresh: refreshAction,
946
+ });
947
+ }
948
+
949
+ function openDialog(title, trigger, kind = '') {
950
+ const previousFocus = trigger || doc.activeElement;
951
+ const dialog = make('dialog', 'iwb-task-dialog' + (kind ? ' iwb-task-dialog-' + kind : ''));
952
+ const titleId = 'iwb-task-dialog-title-' + (++dialogSequence);
953
+ dialog.setAttribute('aria-labelledby', titleId);
954
+ const head = make('header', 'iwb-task-dialog-head');
955
+ const heading = make('h2', 'iwb-task-dialog-title');
956
+ heading.id = titleId;
957
+ heading.textContent = title;
958
+ const closeButton = button('', { icon: 'close', async: false, className: 'icon', label: copy('close'), title: copy('close') });
959
+ head.append(heading, closeButton);
960
+ const body = make('div', 'iwb-task-dialog-body');
961
+ const errorNode = make('div', 'iwb-task-dialog-error');
962
+ errorNode.setAttribute('role', 'alert');
963
+ errorNode.hidden = true;
964
+ const footer = make('footer', 'iwb-task-dialog-footer');
965
+ dialog.append(head, body, errorNode, footer);
966
+ let cleaned = false;
967
+ const entry = {
968
+ dialog,
969
+ body,
970
+ footer,
971
+ isOpen: () => !cleaned && dialog.isConnected,
972
+ clearError() {
973
+ errorNode.hidden = true;
974
+ errorNode.textContent = '';
975
+ },
976
+ setError(message) {
977
+ errorNode.textContent = message;
978
+ errorNode.hidden = false;
979
+ },
980
+ close(force = false) {
981
+ if (cleaned || (!force && (dialogBusy.get(dialog)?.size || 0) > 0)) return;
982
+ if (dialog.open && typeof dialog.close === 'function') dialog.close();
983
+ else cleanup();
984
+ },
985
+ };
986
+ const cleanup = () => {
987
+ if (cleaned) return;
988
+ cleaned = true;
989
+ dialogs.delete(entry);
990
+ dialog.remove();
991
+ if (!disposed && previousFocus?.isConnected && typeof previousFocus.focus === 'function') {
992
+ previousFocus.focus({ preventScroll: true });
993
+ }
994
+ };
995
+ closeButton.addEventListener('click', () => entry.close());
996
+ dialog.addEventListener('close', cleanup);
997
+ dialog.addEventListener('cancel', (event) => {
998
+ if ((dialogBusy.get(dialog)?.size || 0) > 0) event.preventDefault();
999
+ });
1000
+ dialog.addEventListener('click', (event) => {
1001
+ if (event.target !== dialog) return;
1002
+ const rect = dialog.getBoundingClientRect();
1003
+ const outside = event.clientX < rect.left || event.clientX > rect.right || event.clientY < rect.top || event.clientY > rect.bottom;
1004
+ if (outside) entry.close();
1005
+ });
1006
+ dialogs.add(entry);
1007
+ (doc.body || host).appendChild(dialog);
1008
+ try {
1009
+ if (typeof dialog.showModal === 'function') dialog.showModal();
1010
+ else dialog.setAttribute('open', '');
1011
+ } catch {
1012
+ dialog.setAttribute('open', '');
1013
+ }
1014
+ const focusTarget = dialog.querySelector('[autofocus]') || dialog.querySelector('textarea, input, select, button');
1015
+ focusTarget?.focus({ preventScroll: true });
1016
+ return entry;
1017
+ }
1018
+
1019
+ function dialogFooterButton(dialog, label, options, handler) {
1020
+ const node = button(label, options);
1021
+ node.addEventListener('click', handler);
1022
+ dialog.footer.appendChild(node);
1023
+ return node;
1024
+ }
1025
+
1026
+ function normalizeSessions(value) {
1027
+ const rows = Array.isArray(value) ? value : array(value?.sessions ?? value?.items ?? value?.value);
1028
+ return rows.map((session, index) => ({
1029
+ raw: session,
1030
+ index,
1031
+ id: text(session?.id ?? session?.sessionId),
1032
+ title: text(session?.displayTitle ?? session?.title ?? session?.name) || text(session?.id ?? session?.sessionId) || 'Session ' + (index + 1),
1033
+ workspace: text(session?.workspaceName ?? session?.workspaceId) || text(session?.workspace?.title ?? session?.workspace),
1034
+ updatedAt: timestamp(session?.updatedAt ?? session?.activityAt ?? session?.lastActiveAt ?? session?.createdAt),
1035
+ })).filter((session) => session.id);
1036
+ }
1037
+
1038
+ function draftRows(value, keys = ['drafts', 'tasks', 'items', 'value']) {
1039
+ if (Array.isArray(value)) return { items: value, key: null };
1040
+ for (const key of keys) {
1041
+ if (Array.isArray(value?.[key])) return { items: value[key], key };
1042
+ }
1043
+ return { items: [], key: null };
1044
+ }
1045
+
1046
+ function openScanDialog(trigger) {
1047
+ const dialog = openDialog(copy('scanTitle'), trigger, 'scan');
1048
+ const model = { sessions: [], selectedSessions: new Set(), useAI: true, drafts: [], selectedDrafts: new Set(), phase: 'loading' };
1049
+
1050
+ function staticDisabled(node, disabled) {
1051
+ if (disabled) node.dataset.staticDisabled = 'true';
1052
+ else delete node.dataset.staticDisabled;
1053
+ syncBusy();
1054
+ }
1055
+
1056
+ function renderSessionRows() {
1057
+ dialog.body.replaceChildren();
1058
+ const intro = make('p', 'iwb-task-dialog-intro');
1059
+ intro.textContent = copy('scanIntro') + ' · ' + copy('selected', { n: model.selectedSessions.size });
1060
+ dialog.body.appendChild(intro);
1061
+ if (!model.sessions.length) {
1062
+ dialog.body.appendChild(stateBlock('empty', copy('sessionsEmpty'), copy('sessionsEmptyBody')));
1063
+ return;
1064
+ }
1065
+ const options = make('div', 'iwb-task-dialog-options');
1066
+ const allLabel = make('label', 'iwb-task-check iwb-task-select-all');
1067
+ const all = make('input');
1068
+ all.type = 'checkbox';
1069
+ all.checked = model.selectedSessions.size === model.sessions.length && model.sessions.length > 0;
1070
+ all.indeterminate = model.selectedSessions.size > 0 && model.selectedSessions.size < model.sessions.length;
1071
+ const allText = make('span');
1072
+ allText.textContent = copy('selectAll');
1073
+ allLabel.append(all, allText);
1074
+ all.addEventListener('change', () => {
1075
+ model.selectedSessions = all.checked ? new Set(model.sessions.map((session) => session.id)) : new Set();
1076
+ renderSessions();
1077
+ dialog.body.querySelector('.iwb-task-select-all input')?.focus({ preventScroll: true });
1078
+ });
1079
+ const aiLabel = make('label', 'iwb-task-check');
1080
+ const ai = make('input');
1081
+ ai.type = 'checkbox';
1082
+ ai.checked = model.useAI;
1083
+ const aiText = make('span');
1084
+ aiText.textContent = copy('useAI');
1085
+ aiLabel.append(ai, aiText);
1086
+ ai.addEventListener('change', () => { model.useAI = ai.checked; });
1087
+ options.append(allLabel, aiLabel);
1088
+ dialog.body.appendChild(options);
1089
+ const list = make('div', 'iwb-task-session-list');
1090
+ for (const session of model.sessions) {
1091
+ const label = make('label', 'iwb-task-session-item');
1092
+ const checkbox = make('input');
1093
+ checkbox.type = 'checkbox';
1094
+ checkbox.checked = model.selectedSessions.has(session.id);
1095
+ checkbox.setAttribute('aria-label', session.title);
1096
+ checkbox.addEventListener('change', () => {
1097
+ if (checkbox.checked) model.selectedSessions.add(session.id);
1098
+ else model.selectedSessions.delete(session.id);
1099
+ renderSessions();
1100
+ const index = model.sessions.findIndex((item) => item.id === session.id);
1101
+ dialog.body.querySelectorAll('.iwb-task-session-item input')[index]?.focus({ preventScroll: true });
1102
+ });
1103
+ const content = make('span', 'iwb-task-session-content');
1104
+ const title = make('span', 'iwb-task-session-title');
1105
+ title.textContent = session.title;
1106
+ const meta = make('span', 'iwb-task-session-meta');
1107
+ meta.textContent = [session.workspace, formatTime(session.updatedAt)].filter((value) => value && value !== '—').join(' · ') || session.id;
1108
+ content.append(title, meta);
1109
+ label.append(checkbox, content);
1110
+ list.appendChild(label);
1111
+ }
1112
+ dialog.body.appendChild(list);
1113
+ }
1114
+
1115
+ function renderSessions() {
1116
+ model.phase = 'sessions';
1117
+ renderSessionRows();
1118
+ dialog.footer.replaceChildren();
1119
+ dialogFooterButton(dialog, copy('cancel'), { async: false }, () => dialog.close());
1120
+ dialogFooterButton(dialog, copy('reloadSessions'), { busyKey: 'sessions:list' }, () => { void loadSessions(); });
1121
+ const run = dialogFooterButton(dialog, copy('scanRun'), { className: 'primary', busyKey: 'scan:run' }, () => { void scan(); });
1122
+ staticDisabled(run, model.selectedSessions.size === 0);
1123
+ }
1124
+
1125
+ function renderDrafts() {
1126
+ model.phase = 'drafts';
1127
+ dialog.body.replaceChildren();
1128
+ const intro = make('p', 'iwb-task-dialog-intro');
1129
+ intro.textContent = copy('draftsTitle') + ' · ' + copy('selected', { n: model.selectedDrafts.size });
1130
+ dialog.body.appendChild(intro);
1131
+ if (!model.drafts.length) {
1132
+ dialog.body.appendChild(stateBlock('empty', copy('draftsEmpty'), copy('draftsEmptyBody')));
1133
+ } else {
1134
+ const options = make('div', 'iwb-task-dialog-options');
1135
+ const allLabel = make('label', 'iwb-task-check iwb-task-select-all');
1136
+ const all = make('input');
1137
+ all.type = 'checkbox';
1138
+ all.checked = model.selectedDrafts.size === model.drafts.length;
1139
+ all.indeterminate = model.selectedDrafts.size > 0 && model.selectedDrafts.size < model.drafts.length;
1140
+ const allText = make('span');
1141
+ allText.textContent = copy('selectAll');
1142
+ allLabel.append(all, allText);
1143
+ all.addEventListener('change', () => {
1144
+ model.selectedDrafts = all.checked ? new Set(model.drafts.map((draft, index) => index)) : new Set();
1145
+ renderDrafts();
1146
+ dialog.body.querySelector('.iwb-task-select-all input')?.focus({ preventScroll: true });
1147
+ });
1148
+ options.appendChild(allLabel);
1149
+ dialog.body.appendChild(options);
1150
+ const list = make('div', 'iwb-task-draft-list');
1151
+ model.drafts.forEach((draft, index) => {
1152
+ const label = make('label', 'iwb-task-draft-item');
1153
+ const checkbox = make('input');
1154
+ checkbox.type = 'checkbox';
1155
+ checkbox.checked = model.selectedDrafts.has(index);
1156
+ checkbox.addEventListener('change', () => {
1157
+ if (checkbox.checked) model.selectedDrafts.add(index);
1158
+ else model.selectedDrafts.delete(index);
1159
+ renderDrafts();
1160
+ dialog.body.querySelectorAll('.iwb-task-draft-item input')[index]?.focus({ preventScroll: true });
1161
+ });
1162
+ const content = make('span', 'iwb-task-draft-content');
1163
+ const top = make('span', 'iwb-task-draft-top');
1164
+ const title = make('span', 'iwb-task-draft-title');
1165
+ title.textContent = text(draft?.title) || copy('untitled');
1166
+ const priority = make('span', 'iwb-task-priority is-' + priorityOf(draft || {}));
1167
+ priority.textContent = copy('priority.' + priorityOf(draft || {}));
1168
+ top.append(title, priority);
1169
+ const summary = make('span', 'iwb-task-draft-summary');
1170
+ summary.textContent = text(draft?.summary ?? draft?.goal ?? draft?.description) || copy('noSummary');
1171
+ const meta = make('span', 'iwb-task-draft-meta');
1172
+ const facts = [];
1173
+ if (array(draft?.acceptanceCriteria).length) facts.push(copy('acceptance') + ' ' + array(draft.acceptanceCriteria).length);
1174
+ if (array(draft?.sessionIds).length) facts.push(copy('sessions') + ' ' + array(draft.sessionIds).length);
1175
+ meta.textContent = facts.join(' · ');
1176
+ content.append(top, summary, meta);
1177
+ label.append(checkbox, content);
1178
+ list.appendChild(label);
1179
+ });
1180
+ dialog.body.appendChild(list);
1181
+ }
1182
+ dialog.footer.replaceChildren();
1183
+ dialogFooterButton(dialog, copy('back'), { async: false }, () => renderSessions());
1184
+ dialogFooterButton(dialog, copy('cancel'), { async: false }, () => dialog.close());
1185
+ const add = dialogFooterButton(dialog, copy('addTasks', { n: model.selectedDrafts.size }), { className: 'primary', busyKey: 'scan:add' }, () => { void addTasks(); });
1186
+ staticDisabled(add, model.selectedDrafts.size === 0);
1187
+ }
1188
+
1189
+ async function loadSessions() {
1190
+ model.phase = 'loading';
1191
+ dialog.body.replaceChildren(stateBlock('loading', copy('sessionsLoading')));
1192
+ dialog.footer.replaceChildren();
1193
+ const outcome = await runBusy('sessions:list', () => requireAction('listSessions')(), { dialog, refresh: false });
1194
+ if (!dialog.isOpen()) return;
1195
+ if (!outcome.ok) {
1196
+ dialog.body.replaceChildren(stateBlock('error', copy('sessionsError'), errorText(outcome.error) || copy('actionFailed')));
1197
+ dialogFooterButton(dialog, copy('cancel'), { async: false }, () => dialog.close());
1198
+ dialogFooterButton(dialog, copy('retry'), { className: 'primary', busyKey: 'sessions:list' }, () => { void loadSessions(); });
1199
+ return;
1200
+ }
1201
+ model.sessions = normalizeSessions(outcome.value);
1202
+ model.selectedSessions = new Set(model.sessions.slice(0, 12).map((session) => session.id));
1203
+ renderSessions();
1204
+ dialog.body.querySelector('.iwb-task-session-item input')?.focus({ preventScroll: true });
1205
+ }
1206
+
1207
+ async function scan() {
1208
+ if (!model.selectedSessions.size) {
1209
+ dialog.setError(copy('noSessionSelection'));
1210
+ return;
1211
+ }
1212
+ if (model.selectedSessions.size > 12) {
1213
+ dialog.setError(copy('scanLimit'));
1214
+ return;
1215
+ }
1216
+ model.phase = 'scanning';
1217
+ dialog.body.replaceChildren(stateBlock('loading', copy('scanning')));
1218
+ dialog.footer.replaceChildren();
1219
+ const outcome = await runBusy('scan:run', () => requireAction('scan')({
1220
+ sessionIds: [...model.selectedSessions],
1221
+ useAI: model.useAI,
1222
+ }), { dialog, refresh: false });
1223
+ if (!dialog.isOpen()) return;
1224
+ if (!outcome.ok) {
1225
+ renderSessions();
1226
+ dialog.setError(errorText(outcome.error) || copy('scanError'));
1227
+ return;
1228
+ }
1229
+ model.drafts = draftRows(outcome.value, ['drafts', 'tasks', 'items', 'value']).items;
1230
+ model.selectedDrafts = new Set(model.drafts.map((draft, index) => index));
1231
+ renderDrafts();
1232
+ dialog.body.querySelector('.iwb-task-draft-item input')?.focus({ preventScroll: true });
1233
+ }
1234
+
1235
+ async function addTasks() {
1236
+ const selected = model.drafts.filter((draft, index) => model.selectedDrafts.has(index));
1237
+ if (!selected.length) {
1238
+ dialog.setError(copy('noDraftSelection'));
1239
+ return;
1240
+ }
1241
+ const outcome = await runBusy('scan:add', () => requireAction('addTasks')(selected), { dialog, refresh: true });
1242
+ if (outcome.ok && dialog.isOpen()) {
1243
+ notify(copy('tasksAdded', { n: selected.length }));
1244
+ dialog.close(true);
1245
+ }
1246
+ }
1247
+
1248
+ void loadSessions();
1249
+ }
1250
+
1251
+ function planParts(plan) {
1252
+ return draftRows(plan, ['drafts', 'tasks', 'nodes']);
1253
+ }
1254
+
1255
+ function openPlanDialog(trigger) {
1256
+ const dialog = openDialog(copy('planTitle'), trigger, 'plan');
1257
+ const availableWorkspaces = typeof actions?.listWorkspaces === 'function' ? actions.listWorkspaces() : [];
1258
+ const model = {
1259
+ requirement: '',
1260
+ workspaceId: text(host?.dataset?.workspaceId) || text(availableWorkspaces?.[0]?.id),
1261
+ workspaces: Array.isArray(availableWorkspaces) ? availableWorkspaces : [],
1262
+ creatingWorkspace: false,
1263
+ models: [],
1264
+ modelId: '',
1265
+ defaultModel: null,
1266
+ useAI: true,
1267
+ start: true,
1268
+ plan: null,
1269
+ drafts: [],
1270
+ draftKey: null,
1271
+ selectedDrafts: new Set(),
1272
+ };
1273
+
1274
+ function renderForm() {
1275
+ dialog.body.replaceChildren();
1276
+ const intro = make('p', 'iwb-task-dialog-intro');
1277
+ intro.textContent = copy('planIntro');
1278
+ const form = make('form', 'iwb-task-plan-form');
1279
+ const requirementField = make('label', 'iwb-task-field');
1280
+ const requirementLabel = make('span', 'iwb-task-field-label');
1281
+ requirementLabel.textContent = copy('requirement');
1282
+ const requirement = make('textarea', 'iwb-task-textarea');
1283
+ requirement.id = 'iwb-task-requirement-' + dialogSequence;
1284
+ requirement.rows = 6;
1285
+ requirement.required = true;
1286
+ requirement.autofocus = true;
1287
+ requirement.placeholder = copy('requirementPlaceholder');
1288
+ requirement.value = model.requirement;
1289
+ requirement.addEventListener('input', () => { model.requirement = requirement.value; });
1290
+ requirementField.append(requirementLabel, requirement);
1291
+ const workspaceField = make('label', 'iwb-task-field');
1292
+ const workspaceLabel = make('span', 'iwb-task-field-label');
1293
+ workspaceLabel.textContent = copy('workspaceId');
1294
+ const workspace = make('select', 'iwb-task-select-control iwb-task-workspace-select');
1295
+ workspace.setAttribute('aria-label', copy('workspaceId'));
1296
+ for (const item of model.workspaces) {
1297
+ const option = make('option');
1298
+ option.value = text(item?.id);
1299
+ option.textContent = text(item?.title, '未命名工作区') + (item?.path ? ' · ' + item.path : '');
1300
+ workspace.appendChild(option);
1301
+ }
1302
+ if (!model.workspaces.length) {
1303
+ const option = make('option');
1304
+ option.value = '';
1305
+ option.textContent = copy('workspaceEmpty');
1306
+ workspace.appendChild(option);
1307
+ workspace.disabled = true;
1308
+ }
1309
+ workspace.value = model.workspaceId;
1310
+ workspace.addEventListener('change', () => { model.workspaceId = workspace.value; });
1311
+ workspaceField.append(workspaceLabel, workspace);
1312
+ if (!model.workspaces.length) {
1313
+ const workspaceHint = make('p', 'iwb-task-dialog-intro iwb-task-workspace-required');
1314
+ workspaceHint.textContent = copy('workspaceRequired');
1315
+ workspaceField.appendChild(workspaceHint);
1316
+ if (!model.creatingWorkspace) {
1317
+ const create = make('button', 'iwb-btn iwb-task-workspace-create');
1318
+ create.type = 'button';
1319
+ create.textContent = copy('createWorkspace');
1320
+ create.addEventListener('click', () => { model.creatingWorkspace = true; renderForm(); });
1321
+ workspaceField.appendChild(create);
1322
+ } else {
1323
+ const path = make('input', 'iwb-task-input iwb-task-workspace-path');
1324
+ path.placeholder = copy('workspacePathPlaceholder');
1325
+ path.setAttribute('aria-label', copy('workspacePath'));
1326
+ path.value = model.workspacePath || '';
1327
+ path.addEventListener('input', () => { model.workspacePath = path.value; });
1328
+ workspaceField.appendChild(path);
1329
+ const actions = make('div', 'iwb-task-dialog-options');
1330
+ const confirm = make('button', 'iwb-btn primary iwb-task-workspace-confirm');
1331
+ confirm.type = 'button';
1332
+ confirm.textContent = copy('createWorkspaceConfirm');
1333
+ confirm.addEventListener('click', async () => {
1334
+ const value = path.value.trim();
1335
+ if (!/^\/|^[A-Za-z]:[\\/]/.test(value)) {
1336
+ dialog.setError(copy('workspacePath'));
1337
+ return;
1338
+ }
1339
+ const outcome = await runBusy('workspace:create', () => requireAction('createWorkspace')({ path: value }), { dialog, refresh: false });
1340
+ if (outcome.ok) {
1341
+ model.workspaces = [outcome.value, ...model.workspaces.filter((item) => item.id !== outcome.value.id)];
1342
+ model.workspaceId = outcome.value.id;
1343
+ model.creatingWorkspace = false;
1344
+ renderForm();
1345
+ } else {
1346
+ dialog.setError(errorText(outcome.error) || copy('actionFailed'));
1347
+ }
1348
+ });
1349
+ const cancel = make('button', 'iwb-btn iwb-task-workspace-cancel');
1350
+ cancel.type = 'button';
1351
+ cancel.textContent = copy('createWorkspaceCancel');
1352
+ cancel.addEventListener('click', () => { model.creatingWorkspace = false; renderForm(); });
1353
+ actions.append(confirm, cancel);
1354
+ workspaceField.appendChild(actions);
1355
+ path.focus({ preventScroll: true });
1356
+ }
1357
+ }
1358
+ const modelField = make('label', 'iwb-task-field');
1359
+ const modelLabel = make('span', 'iwb-task-field-label');
1360
+ modelLabel.textContent = copy('model');
1361
+ const modelSelect = make('select', 'iwb-task-select-control iwb-task-model-select');
1362
+ modelSelect.setAttribute('aria-label', copy('model'));
1363
+ const defaultOption = make('option');
1364
+ defaultOption.value = '';
1365
+ defaultOption.textContent = model.defaultModel?.model ? copy('modelDefault') + '(' + model.defaultModel.model + ')' : copy('modelDefault');
1366
+ modelSelect.appendChild(defaultOption);
1367
+ for (const item of model.models) {
1368
+ const option = make('option');
1369
+ option.value = item.id;
1370
+ option.textContent = item.name + (item.provider ? ' · ' + item.provider : '');
1371
+ modelSelect.appendChild(option);
1372
+ }
1373
+ modelSelect.value = model.modelId;
1374
+ modelSelect.addEventListener('change', () => { model.modelId = modelSelect.value; });
1375
+ modelField.append(modelLabel, modelSelect);
1376
+ const aiLabel = make('label', 'iwb-task-check');
1377
+ const ai = make('input');
1378
+ ai.type = 'checkbox';
1379
+ ai.checked = model.useAI;
1380
+ const aiText = make('span');
1381
+ aiText.textContent = copy('useAI');
1382
+ aiLabel.append(ai, aiText);
1383
+ ai.addEventListener('change', () => { model.useAI = ai.checked; });
1384
+ form.append(requirementField, workspaceField, modelField, aiLabel);
1385
+ form.addEventListener('submit', (event) => {
1386
+ event.preventDefault();
1387
+ model.requirement = requirement.value;
1388
+ model.workspaceId = workspace.value;
1389
+ void generate();
1390
+ });
1391
+ dialog.body.append(intro, form);
1392
+ dialog.footer.replaceChildren();
1393
+ dialogFooterButton(dialog, copy('cancel'), { async: false }, () => dialog.close());
1394
+ const generateButton = dialogFooterButton(dialog, copy('generatePlan'), { className: 'primary', busyKey: 'plan:generate' }, () => {
1395
+ model.requirement = requirement.value;
1396
+ model.workspaceId = workspace.value;
1397
+ if (typeof form.requestSubmit === 'function') form.requestSubmit();
1398
+ else void generate();
1399
+ });
1400
+ generateButton.setAttribute('aria-controls', requirement.id);
1401
+ if (!model.workspaces.length) generateButton.dataset.staticDisabled = 'true';
1402
+ requirement.focus({ preventScroll: true });
1403
+ }
1404
+
1405
+ function draftName(draft, index) {
1406
+ return text(draft?.title ?? draft?.name ?? draft?.goal) || copy('node', { n: index + 1 });
1407
+ }
1408
+
1409
+ function dependenciesOf(draft) {
1410
+ return array(draft?.dependsOn ?? draft?.dependencies ?? draft?.needs).map(endpointId).filter(Boolean);
1411
+ }
1412
+
1413
+ function renderEdges() {
1414
+ const edges = array(model.plan?.edges ?? model.plan?.links);
1415
+ const container = make('section', 'iwb-task-plan-edges');
1416
+ const title = make('h3', 'iwb-task-section-title');
1417
+ title.textContent = copy('edges');
1418
+ container.appendChild(title);
1419
+ if (!edges.length) {
1420
+ const empty = make('div', 'iwb-task-inline-empty');
1421
+ empty.textContent = copy('noEdges');
1422
+ container.appendChild(empty);
1423
+ return container;
1424
+ }
1425
+ const list = make('ul', 'iwb-task-plan-edge-list');
1426
+ for (const edge of edges) {
1427
+ const from = endpointId(edge?.from ?? edge?.source ?? edge?.sourceId ?? edge?.fromNodeId);
1428
+ const to = endpointId(edge?.to ?? edge?.target ?? edge?.targetId ?? edge?.toNodeId);
1429
+ const sourceIndex = model.drafts.findIndex((draft, index) => text(draft?.id ?? draft?.nodeId) === to || String(index) === to);
1430
+ const targetIndex = model.drafts.findIndex((draft, index) => text(draft?.id ?? draft?.nodeId) === from || String(index) === from);
1431
+ const row = make('li', 'iwb-task-plan-edge');
1432
+ const source = make('span');
1433
+ source.textContent = sourceIndex >= 0 ? draftName(model.drafts[sourceIndex], sourceIndex) : to || '—';
1434
+ const arrow = make('span', 'iwb-task-plan-arrow');
1435
+ arrow.textContent = '→';
1436
+ arrow.setAttribute('aria-hidden', 'true');
1437
+ const target = make('span');
1438
+ target.textContent = targetIndex >= 0 ? draftName(model.drafts[targetIndex], targetIndex) : from || '—';
1439
+ row.append(source, arrow, target);
1440
+ list.appendChild(row);
1441
+ }
1442
+ container.appendChild(list);
1443
+ return container;
1444
+ }
1445
+
1446
+ function draftIdAt(index) {
1447
+ return text(model.drafts[index]?.id ?? model.drafts[index]?.nodeId) || String(index);
1448
+ }
1449
+
1450
+ function setPlanDraftSelected(index, selected) {
1451
+ if (selected) {
1452
+ const visit = (current) => {
1453
+ if (model.selectedDrafts.has(current)) return;
1454
+ model.selectedDrafts.add(current);
1455
+ const dependencies = dependenciesOf(model.drafts[current]);
1456
+ model.drafts.forEach((draft, candidate) => {
1457
+ if (dependencies.includes(draftIdAt(candidate))) visit(candidate);
1458
+ });
1459
+ };
1460
+ visit(index);
1461
+ } else {
1462
+ const removed = new Set([index]);
1463
+ let changed = true;
1464
+ while (changed) {
1465
+ changed = false;
1466
+ const removedIds = new Set([...removed].map(draftIdAt));
1467
+ for (const candidate of model.selectedDrafts) {
1468
+ if (removed.has(candidate)) continue;
1469
+ if (dependenciesOf(model.drafts[candidate]).some((id) => removedIds.has(id))) {
1470
+ removed.add(candidate);
1471
+ changed = true;
1472
+ }
1473
+ }
1474
+ }
1475
+ for (const candidate of removed) model.selectedDrafts.delete(candidate);
1476
+ }
1477
+ renderPlan();
1478
+ dialog.body.querySelectorAll('.iwb-task-plan-node input')[index]?.focus({ preventScroll: true });
1479
+ }
1480
+
1481
+ function renderPlan() {
1482
+ dialog.body.replaceChildren();
1483
+ const intro = make('p', 'iwb-task-dialog-intro');
1484
+ intro.textContent = copy('planReview') + ' · ' + copy('selected', { n: model.selectedDrafts.size });
1485
+ dialog.body.appendChild(intro);
1486
+ if (!model.drafts.length) {
1487
+ dialog.body.appendChild(stateBlock('empty', copy('planEmpty'), copy('planEmptyBody')));
1488
+ } else {
1489
+ const list = make('div', 'iwb-task-plan-nodes');
1490
+ model.drafts.forEach((draft, index) => {
1491
+ const card = make('article', 'iwb-task-plan-node');
1492
+ const select = make('label', 'iwb-task-plan-select');
1493
+ const checkbox = make('input');
1494
+ checkbox.type = 'checkbox';
1495
+ checkbox.checked = model.selectedDrafts.has(index);
1496
+ checkbox.setAttribute('aria-label', draftName(draft, index));
1497
+ checkbox.addEventListener('change', () => {
1498
+ setPlanDraftSelected(index, checkbox.checked);
1499
+ });
1500
+ const number = make('span', 'iwb-task-plan-number');
1501
+ number.textContent = String(index + 1).padStart(2, '0');
1502
+ const head = make('div', 'iwb-task-plan-node-head');
1503
+ const title = make('h3', 'iwb-task-plan-node-title');
1504
+ title.textContent = draftName(draft, index);
1505
+ const kindValue = token(draft?.kind ?? draft?.type);
1506
+ const kindKey = kindValue === 'session' ? 'sessionNode' : kindValue === 'note' ? 'noteNode' : 'taskNode';
1507
+ const kind = make('span', 'iwb-task-plan-kind is-' + kindValue);
1508
+ kind.textContent = copy(kindKey);
1509
+ head.append(title, kind);
1510
+ const summary = make('p', 'iwb-task-plan-node-summary');
1511
+ summary.textContent = text(draft?.goal ?? draft?.summary ?? draft?.prompt ?? draft?.note ?? draft?.description) || copy('noSummary');
1512
+ const dependencies = dependenciesOf(draft);
1513
+ const dependency = make('div', 'iwb-task-plan-dependency');
1514
+ dependency.textContent = dependencies.length ? copy('dependencies', { name: dependencies.join(', ') }) : copy('noDependencies');
1515
+ select.append(checkbox, number);
1516
+ card.append(select, head, summary, dependency);
1517
+ list.appendChild(card);
1518
+ });
1519
+ dialog.body.append(list, renderEdges());
1520
+ }
1521
+ const startLabel = make('label', 'iwb-task-check iwb-task-plan-start');
1522
+ const start = make('input');
1523
+ start.type = 'checkbox';
1524
+ start.checked = model.start;
1525
+ const startText = make('span');
1526
+ startText.textContent = copy('startAfter');
1527
+ startLabel.append(start, startText);
1528
+ start.addEventListener('change', () => { model.start = start.checked; });
1529
+ dialog.body.appendChild(startLabel);
1530
+ dialog.footer.replaceChildren();
1531
+ dialogFooterButton(dialog, copy('editRequirement'), { async: false }, () => renderForm());
1532
+ dialogFooterButton(dialog, copy('cancel'), { async: false }, () => dialog.close());
1533
+ const create = dialogFooterButton(dialog, copy('materialize', { n: model.selectedDrafts.size }), { className: 'primary', busyKey: 'plan:materialize' }, () => { void materialize(); });
1534
+ if (!model.selectedDrafts.size) create.dataset.staticDisabled = 'true';
1535
+ syncBusy();
1536
+ }
1537
+
1538
+ function selectedPlan() {
1539
+ const chosen = model.drafts
1540
+ .map((draft, index) => ({ draft, index }))
1541
+ .filter(({ index }) => model.selectedDrafts.has(index));
1542
+ const selected = chosen.map(({ draft }) => draft);
1543
+ if (Array.isArray(model.plan)) return selected;
1544
+ if (!model.plan || !model.draftKey) return model.plan;
1545
+ const result = { ...model.plan, [model.draftKey]: selected };
1546
+ if (model.draftKey === 'nodes') {
1547
+ const ids = new Set(chosen.map(({ index }) => draftIdAt(index)));
1548
+ result.nodes = chosen.map(({ draft }) => ({
1549
+ ...draft,
1550
+ dependsOn: dependenciesOf(draft).filter((id) => ids.has(id)),
1551
+ }));
1552
+ if (Array.isArray(model.plan.edges)) {
1553
+ result.edges = model.plan.edges.filter((edge) => {
1554
+ const from = endpointId(edge?.from ?? edge?.source ?? edge?.sourceId ?? edge?.fromNodeId);
1555
+ const to = endpointId(edge?.to ?? edge?.target ?? edge?.targetId ?? edge?.toNodeId);
1556
+ return ids.has(from) && ids.has(to);
1557
+ });
1558
+ }
1559
+ }
1560
+ return result;
1561
+ }
1562
+
1563
+ async function generate() {
1564
+ if (!model.requirement.trim()) {
1565
+ dialog.setError(copy('requirementRequired'));
1566
+ return;
1567
+ }
1568
+ dialog.body.replaceChildren(stateBlock('loading', copy('planning')));
1569
+ dialog.footer.replaceChildren();
1570
+ const outcome = await runBusy('plan:generate', () => requireAction('plan')({
1571
+ requirement: model.requirement.trim(),
1572
+ workspaceId: model.workspaceId.trim() || undefined,
1573
+ useAI: model.useAI,
1574
+ model: model.modelId ? model.models.find((item) => item.id === model.modelId) : undefined,
1575
+ }), { dialog, refresh: false });
1576
+ if (!dialog.isOpen()) return;
1577
+ if (!outcome.ok) {
1578
+ renderForm();
1579
+ dialog.setError(errorText(outcome.error) || copy('planError'));
1580
+ return;
1581
+ }
1582
+ model.plan = outcome.value;
1583
+ const parts = planParts(model.plan);
1584
+ model.drafts = parts.items;
1585
+ model.draftKey = parts.key;
1586
+ model.selectedDrafts = new Set(model.drafts.map((draft, index) => index));
1587
+ renderPlan();
1588
+ }
1589
+
1590
+ async function materialize() {
1591
+ if (!model.selectedDrafts.size && model.drafts.length) {
1592
+ dialog.setError(copy('noDraftSelection'));
1593
+ return;
1594
+ }
1595
+ const plan = selectedPlan();
1596
+ const outcome = await runBusy('plan:materialize', () => requireAction('materializePlan')(plan, { start: model.start }), { dialog, refresh: true });
1597
+ if (outcome.ok && dialog.isOpen()) {
1598
+ notify(copy('materialized'));
1599
+ dialog.close(true);
1600
+ }
1601
+ }
1602
+
1603
+ renderForm();
1604
+ void requireAction('listModels')().then((value) => {
1605
+ model.models = value?.models || [];
1606
+ model.defaultModel = value?.defaultModel || null;
1607
+ renderForm();
1608
+ }).catch((error) => {
1609
+ notify(errorText(error) || copy('actionFailed'));
1610
+ });
1611
+ }
1612
+
1613
+ function openDeleteDialog(task, trigger) {
1614
+ const dialog = openDialog(copy('deleteTitle'), trigger, 'confirm');
1615
+ const message = make('p', 'iwb-task-confirm-message');
1616
+ message.textContent = copy('deleteBody', { name: task.title });
1617
+ dialog.body.appendChild(message);
1618
+ dialogFooterButton(dialog, copy('cancel'), { async: false }, () => dialog.close());
1619
+ dialogFooterButton(dialog, copy('confirmDelete'), { className: 'iwb-task-danger', busyKey: 'task:' + task.id + ':deleteTask' }, async () => {
1620
+ const outcome = await runTaskAction(task, 'deleteTask', [], dialog);
1621
+ if (outcome.ok && dialog.isOpen()) {
1622
+ if (state.selectedId === task.id) state.selectedId = null;
1623
+ notify(copy('deleted'));
1624
+ dialog.close(true);
1625
+ }
1626
+ });
1627
+ }
1628
+
1629
+ filterSelect.addEventListener('change', () => {
1630
+ state.filter = filterSelect.value;
1631
+ render();
1632
+ });
1633
+ sortSelect.addEventListener('change', () => {
1634
+ state.sort = sortSelect.value;
1635
+ render();
1636
+ });
1637
+ refreshButton.addEventListener('click', () => { void refresh(); });
1638
+ alertClose.addEventListener('click', () => {
1639
+ state.error = '';
1640
+ renderAlert();
1641
+ refreshButton.focus();
1642
+ });
1643
+ scanButton.addEventListener('click', () => openScanDialog(scanButton));
1644
+ planButton.addEventListener('click', () => openPlanDialog(planButton));
1645
+ listNode.addEventListener('keydown', (event) => {
1646
+ if (!['ArrowDown', 'ArrowUp', 'Home', 'End'].includes(event.key)) return;
1647
+ const buttons = [...listNode.querySelectorAll('.iwb-task-list-select')];
1648
+ if (!buttons.length) return;
1649
+ const current = buttons.indexOf(doc.activeElement);
1650
+ let next = current;
1651
+ if (event.key === 'Home') next = 0;
1652
+ else if (event.key === 'End') next = buttons.length - 1;
1653
+ else if (event.key === 'ArrowDown') next = Math.min(buttons.length - 1, Math.max(0, current + 1));
1654
+ else next = Math.max(0, current < 0 ? 0 : current - 1);
1655
+ event.preventDefault();
1656
+ buttons[next]?.focus();
1657
+ buttons[next]?.click();
1658
+ });
1659
+ root.addEventListener('keydown', (event) => {
1660
+ if (event.key !== 'Escape' || dialogs.size) return;
1661
+ if (state.error) {
1662
+ state.error = '';
1663
+ renderAlert();
1664
+ event.preventDefault();
1665
+ return;
1666
+ }
1667
+ const selected = [...listNode.querySelectorAll('.iwb-task-list-select')].find((node) => node.dataset.focusKey === 'list:' + state.selectedId);
1668
+ if (selected && doc.activeElement !== selected) {
1669
+ selected.focus();
1670
+ event.preventDefault();
1671
+ }
1672
+ });
1673
+
1674
+ host?.appendChild(root);
1675
+ refresh();
1676
+
1677
+ return {
1678
+ root,
1679
+ refresh,
1680
+ dispose() {
1681
+ if (disposed) return;
1682
+ disposed = true;
1683
+ refreshVersion += 1;
1684
+ for (const dialog of [...dialogs]) dialog.close(true);
1685
+ root.remove();
1686
+ },
1687
+ };
1688
+ }