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.
@@ -15,6 +15,12 @@ import { createMarkdown } from './markdown';
15
15
  import { createRenderers } from './render';
16
16
  import { createCardTools } from './card-tools';
17
17
  import { createModelMenu, createArrangeMenu, createSettingsMenu, createWorkspaceMenu } from './popovers';
18
+ import { createFlowRecorder } from './flow-recorder';
19
+ import { createTaskStore } from './task-store';
20
+ import { createTaskController } from './task-controller.js';
21
+ import { createTaskView } from './task-view.js';
22
+ import { createFileStore } from './file-store.js';
23
+ import { openFilePreview, fileKind, formatBytes } from './file-preview.js';
18
24
 
19
25
  const STORAGE_KEY = 'dsh.inspiration-workbench.v1';
20
26
  const CANVAS_KEY = 'dsh.inspiration-workbench.canvases.v1';
@@ -29,6 +35,8 @@ function formatElapsed(ms) {
29
35
  return Math.floor(seconds / 60) + 'm' + String(seconds % 60).padStart(2, '0') + 's';
30
36
  }
31
37
 
38
+
39
+
32
40
  export function createBoard({ host, adapter, approvals, t, onOpenSession }) {
33
41
  const { appendMarkdownLite } = createMarkdown({ t });
34
42
  const state = {
@@ -38,7 +46,7 @@ export function createBoard({ host, adapter, approvals, t, onOpenSession }) {
38
46
  stacks: [],
39
47
  seq: 0,
40
48
  stackSeq: 0,
41
- settings: { inlineApprovals: false, chainWheel: true },
49
+ settings: { inlineApprovals: false, chainWheel: false },
42
50
  selected: new Set(),
43
51
  zTop: 20,
44
52
  focusedId: null,
@@ -46,8 +54,20 @@ export function createBoard({ host, adapter, approvals, t, onOpenSession }) {
46
54
  board: { active: false, key: 'status', saved: new Map() },
47
55
  canvases: [],
48
56
  activeCanvas: null,
57
+ mode: 'canvas',
49
58
  };
50
59
 
60
+ const taskStore = createTaskStore();
61
+ const fileStore = createFileStore();
62
+ const flow = createFlowRecorder({
63
+ onChange: (events) => taskStore.setFlowEvents(events),
64
+ });
65
+ const taskLoadPromise = taskStore.load().then((saved) => {
66
+ flow.replace(saved.flowEvents);
67
+ schedulePipelines();
68
+ return saved;
69
+ }).catch(() => null);
70
+
51
71
  // Turn expansion survives a remote layout apply (which rebuilds card DOM):
52
72
  // the state lives on the board keyed by session + turn, not on the card object.
53
73
  const expandedTurns = new Map();
@@ -58,6 +78,7 @@ export function createBoard({ host, adapter, approvals, t, onOpenSession }) {
58
78
  toggleSearch,
59
79
  runSearch,
60
80
  stepSearch,
81
+ highlight,
61
82
  closeOutline,
62
83
  openOutline,
63
84
  closeRefPicker,
@@ -121,6 +142,13 @@ export function createBoard({ host, adapter, approvals, t, onOpenSession }) {
121
142
  btnNew.type = 'button';
122
143
  const btnCanvas = el('button', 'iwb-btn', icon('canvas', 13) + '<span>' + t('canvas') + '</span>');
123
144
  btnCanvas.type = 'button';
145
+ const btnBlank = el('button', 'iwb-btn iwb-btn-icon', icon('plus', 13));
146
+ btnBlank.type = 'button';
147
+ btnBlank.title = '新建空白画布(自动保存当前画布)';
148
+ btnBlank.setAttribute('aria-label', '新建空白画布');
149
+ const btnFile = el('button', 'iwb-btn', icon('clip', 13) + '<span>文件</span>');
150
+ btnFile.type = 'button';
151
+ btnFile.title = '添加图片或文件到画布';
124
152
  const btnArrange = el('button', 'iwb-btn', icon('arrange', 13) + '<span>' + t('arrange') + '</span>');
125
153
  btnArrange.type = 'button';
126
154
  const btnBoard = el('button', 'iwb-btn', icon('board', 13) + '<span>' + t('boardMode') + '</span>');
@@ -137,8 +165,32 @@ export function createBoard({ host, adapter, approvals, t, onOpenSession }) {
137
165
  const btnSettings = el('button', 'iwb-btn', icon('sliders', 13) + '<span>' + t('settings') + '</span>');
138
166
  btnSettings.type = 'button';
139
167
  const actions = el('div', 'iwb-toolbar-actions');
140
- actions.append(todoBar, btnNew, btnNote, btnCanvas, btnArrange, btnBoard, btnFit, btnCollapse, btnSettings);
141
- toolbar.append(titles, hint, actions);
168
+ actions.append(todoBar, btnNew, btnNote, btnFile, btnCanvas, btnBlank, btnArrange, btnBoard, btnFit, btnCollapse, btnSettings);
169
+ const modeSwitch = el('div', 'iwb-mode-switch');
170
+ modeSwitch.setAttribute('role', 'tablist');
171
+ modeSwitch.setAttribute('aria-label', '工作视图');
172
+ const btnCanvasMode = el('button', 'iwb-mode-tab active', '<span>画布</span>');
173
+ btnCanvasMode.type = 'button';
174
+ btnCanvasMode.setAttribute('role', 'tab');
175
+ btnCanvasMode.setAttribute('aria-selected', 'true');
176
+ const btnTaskMode = el('button', 'iwb-mode-tab', '<span>任务</span>');
177
+ btnTaskMode.type = 'button';
178
+ btnTaskMode.setAttribute('role', 'tab');
179
+ btnTaskMode.setAttribute('aria-selected', 'false');
180
+ modeSwitch.append(btnCanvasMode, btnTaskMode);
181
+ toolbar.append(titles, modeSwitch, hint, actions);
182
+
183
+ const fileInput = document.createElement('input');
184
+ fileInput.type = 'file';
185
+ fileInput.multiple = true;
186
+ fileInput.hidden = true;
187
+ fileInput.accept = 'image/*,.pdf,.docx,.pptx,.txt,.md,.markdown,.json,.jsonl,.csv,.log,.html,.css,.js,.ts,.tsx,.jsx,.py,.java,.go,.rs,.sql,.sh,.yaml,.yml';
188
+ fileInput.addEventListener('change', async () => {
189
+ for (const file of [...fileInput.files]) await addFileCard(file);
190
+ fileInput.value = '';
191
+ });
192
+ document.body.appendChild(fileInput);
193
+ btnFile.addEventListener('click', () => fileInput.click());
142
194
 
143
195
  const canvas = el('div', 'iwb-canvas');
144
196
  canvas.tabIndex = 0;
@@ -527,26 +579,158 @@ export function createBoard({ host, adapter, approvals, t, onOpenSession }) {
527
579
  function noteBody(card) {
528
580
  const body = card.el.querySelector('.iwb-body');
529
581
  body.textContent = '';
530
- const wrap = el('div', 'iwb-note');
582
+ card.viewMode = card.viewMode || 'preview';
583
+
584
+ const toggle = el('div', 'iwb-note-toggle');
585
+ const previewButton = el('button', 'iwb-note-toggle-button', '预览');
586
+ previewButton.type = 'button';
587
+ previewButton.title = '查看 Markdown 渲染效果';
588
+ const sourceButton = el('button', 'iwb-note-toggle-button', '源码');
589
+ sourceButton.type = 'button';
590
+ sourceButton.title = '查看 Markdown 源码';
591
+ toggle.append(previewButton, sourceButton);
592
+ body.appendChild(toggle);
593
+
594
+ const preview = el('div', 'iwb-note-preview');
595
+ body.appendChild(preview);
531
596
  const area = document.createElement('textarea');
532
597
  area.className = 'iwb-note-input';
533
598
  area.value = card.note || '';
534
599
  area.placeholder = t('note.placeholder');
600
+ body.appendChild(area);
601
+
602
+ const sync = () => {
603
+ preview.hidden = card.viewMode === 'source';
604
+ area.hidden = card.viewMode !== 'source';
605
+ previewButton.classList.toggle('active', card.viewMode === 'preview');
606
+ sourceButton.classList.toggle('active', card.viewMode === 'source');
607
+ previewButton.setAttribute('aria-pressed', String(card.viewMode === 'preview'));
608
+ sourceButton.setAttribute('aria-pressed', String(card.viewMode === 'source'));
609
+ if (card.viewMode === 'preview') {
610
+ preview.textContent = '';
611
+ appendMarkdownLite(preview, card.note || '');
612
+ }
613
+ };
614
+ previewButton.addEventListener('click', () => {
615
+ card.viewMode = 'preview';
616
+ sync();
617
+ saveSoon();
618
+ });
619
+ sourceButton.addEventListener('click', () => {
620
+ card.viewMode = 'source';
621
+ sync();
622
+ saveSoon();
623
+ });
535
624
  area.addEventListener('input', () => {
536
625
  card.note = area.value;
626
+ sync();
537
627
  saveSoon();
538
628
  });
539
- wrap.appendChild(area);
629
+ sync();
630
+ }
631
+
632
+ function fileCardBody(card) {
633
+ const body = card.el.querySelector('.iwb-body');
634
+ body.textContent = '';
635
+ const wrap = el('div', 'iwb-file-body');
636
+ const kind = fileKind({ name: card.title, type: card.type });
637
+ if (kind === 'image') {
638
+ const image = el('img', 'iwb-file-thumb');
639
+ image.alt = card.title || '图片文件';
640
+ wrap.appendChild(image);
641
+ fileStore.get(card.fileId).then((record) => {
642
+ if (record?.blob) image.src = URL.createObjectURL(record.blob);
643
+ });
644
+ } else {
645
+ const iconNode = el('div', 'iwb-file-icon', fileKindIcon(kind));
646
+ wrap.appendChild(iconNode);
647
+ }
648
+ const name = el('div', 'iwb-file-name');
649
+ name.textContent = card.title || '未命名文件';
650
+ const meta = el('div', 'iwb-file-meta');
651
+ meta.textContent = (card.type || kind.toUpperCase()) + ' · ' + formatBytes(card.size);
652
+ const open = el('button', 'iwb-btn primary iwb-file-open', icon('eye', 13) + '<span>预览</span>');
653
+ open.type = 'button';
654
+ open.addEventListener('click', (event) => {
655
+ event.stopPropagation();
656
+ void openStoredFile(card);
657
+ });
658
+ wrap.append(name, meta, open);
540
659
  body.appendChild(wrap);
541
660
  }
542
661
 
543
- function addNote({ id, note, title, x, y, w, h, focus }) {
662
+ function fileKindIcon(kind) {
663
+ return ({ image: 'IMG', pdf: 'PDF', docx: 'DOC', pptx: 'PPT', html: 'HTML', text: 'TXT', other: 'FILE' })[kind] || 'FILE';
664
+ }
665
+
666
+ async function openStoredFile(card) {
667
+ const record = await fileStore.get(card.fileId);
668
+ if (!record) {
669
+ toast('文件内容不可用,请重新添加');
670
+ return;
671
+ }
672
+ openFilePreview({ ...record, name: card.title, type: card.type, size: card.size });
673
+ }
674
+
675
+ async function addFileCard(fileOrMeta) {
676
+ const fileId = fileOrMeta.fileId || await fileStore.put(fileOrMeta);
677
+ const kind = fileKind(fileOrMeta);
678
+ const card = {
679
+ id: 'f' + ++state.seq,
680
+ kind: 'file',
681
+ fileId,
682
+ title: fileOrMeta.name || fileOrMeta.title || '未命名文件',
683
+ type: fileOrMeta.type || kind,
684
+ size: Number(fileOrMeta.size) || 0,
685
+ x: typeof fileOrMeta.x === 'number' ? fileOrMeta.x : nextSlot().x,
686
+ y: typeof fileOrMeta.y === 'number' ? fileOrMeta.y : nextSlot().y,
687
+ w: fileOrMeta.w || DEFAULT_W,
688
+ h: fileOrMeta.h || DEFAULT_H,
689
+ stackId: null,
690
+ running: false,
691
+ composerDraft: '',
692
+ pipeline: null,
693
+ };
694
+ const node = el('article', 'iwb-card iwb-file-card', cardMarkup(card));
695
+ node.tabIndex = -1;
696
+ node.setAttribute('role', 'listitem');
697
+ node.style.left = card.x + 'px';
698
+ node.style.top = card.y + 'px';
699
+ node.style.width = card.w + 'px';
700
+ node.style.height = card.h + 'px';
701
+ card.el = node;
702
+ world.appendChild(node);
703
+ node.querySelector('.iwb-card-title').textContent = card.title;
704
+ for (const selector of ['.iwb-meta', '.iwb-elapsed', '.iwb-foot', '.iwb-pipe-badge', '[data-act="search"]', '[data-act="outline"]', '[data-act="pipe"]']) {
705
+ node.querySelector(selector)?.remove();
706
+ }
707
+ const previewButton = el('button', 'iwb-file-preview-button', icon('eye', 13));
708
+ previewButton.type = 'button';
709
+ previewButton.title = '预览文件';
710
+ previewButton.setAttribute('aria-label', '预览文件');
711
+ previewButton.addEventListener('click', (event) => {
712
+ event.stopPropagation();
713
+ void openStoredFile(card);
714
+ });
715
+ node.querySelector('.iwb-actions').insertBefore(previewButton, node.querySelector('[data-act="close"]'));
716
+ bindCard(card);
717
+ fileCardBody(card);
718
+ state.cards.push(card);
719
+ updateCounts();
720
+ updateEmptyState();
721
+ saveSoon();
722
+ if (fileOrMeta.focus !== false) centerCard(card);
723
+ return card;
724
+ }
725
+
726
+ function addNote({ id, note, title, x, y, w, h, focus, viewMode }) {
544
727
  if (disposed) return null;
545
728
  const slot = nextSlot();
546
729
  const card = {
547
730
  id: id || 'n' + ++state.seq,
548
731
  kind: 'note',
549
732
  note: note || '',
733
+ viewMode: viewMode || 'preview',
550
734
  title: title || t('note.title'),
551
735
  x: typeof x === 'number' ? x : slot.x,
552
736
  y: typeof y === 'number' ? y : slot.y,
@@ -584,7 +768,7 @@ export function createBoard({ host, adapter, approvals, t, onOpenSession }) {
584
768
  return card;
585
769
  }
586
770
 
587
- function addSession({ sessionId, title, workspace, x, y, w, h, focus, pipeline }) {
771
+ function addSession({ sessionId, title, workspace, x, y, w, h, focus, pipeline, composerDraft }) {
588
772
  if (disposed) return null;
589
773
  const existing = state.cards.find((card) => card.sessionId === sessionId);
590
774
  if (existing) {
@@ -604,9 +788,10 @@ export function createBoard({ host, adapter, approvals, t, onOpenSession }) {
604
788
  w: w || DEFAULT_W,
605
789
  h: h || DEFAULT_H,
606
790
  stackId: null,
791
+ kind: 'session',
607
792
  running: false,
608
793
  startedAt: 0,
609
- composerDraft: '',
794
+ composerDraft: composerDraft || '',
610
795
  toolOpen: new Map(),
611
796
  view: null,
612
797
  pipeline: pipeline || null,
@@ -967,6 +1152,28 @@ export function createBoard({ host, adapter, approvals, t, onOpenSession }) {
967
1152
 
968
1153
  // ── named canvases ───────────────────────────────────────────────────
969
1154
  let canvasPop = null;
1155
+ let taskView = null;
1156
+ let taskController = null;
1157
+ let canvasSaveTimer = 0;
1158
+ let switchingCanvas = false;
1159
+
1160
+ function syncActiveCanvas() {
1161
+ clearTimeout(canvasSaveTimer);
1162
+ canvasSaveTimer = 0;
1163
+ if (switchingCanvas || !state.activeCanvas) return false;
1164
+ const active = syncCanvases().find((canvas) => canvas.id === state.activeCanvas);
1165
+ if (!active) return false;
1166
+ active.layout = layoutPayload();
1167
+ active.savedAt = Date.now();
1168
+ storeCanvases();
1169
+ return true;
1170
+ }
1171
+
1172
+ function scheduleActiveCanvasSave() {
1173
+ if (switchingCanvas || !state.activeCanvas) return;
1174
+ clearTimeout(canvasSaveTimer);
1175
+ canvasSaveTimer = setTimeout(syncActiveCanvas, 450);
1176
+ }
970
1177
 
971
1178
  function closeCanvasMenu() {
972
1179
  canvasPop?.remove();
@@ -1008,6 +1215,7 @@ export function createBoard({ host, adapter, approvals, t, onOpenSession }) {
1008
1215
  btnCanvas.querySelector('span').textContent = active ? t('canvas') + ' · ' + active.name : t('canvas');
1009
1216
  btnCanvas.title = active ? t('canvas.active').replace('{name}', active.name) : t('canvas.title');
1010
1217
  btnCanvas.classList.toggle('iwb-btn-active', Boolean(active));
1218
+ if (state.mode === 'task') taskView?.refresh();
1011
1219
  }
1012
1220
 
1013
1221
  /** Only canvases that actually carry a board are switchable. */
@@ -1078,15 +1286,9 @@ export function createBoard({ host, adapter, approvals, t, onOpenSession }) {
1078
1286
 
1079
1287
  function switchCanvas(id) {
1080
1288
  const target = syncCanvases().find((canvas) => canvas.id === id);
1081
- if (!target) return;
1082
- // Keep unsaved work: fold the current board back into its canvas first.
1083
- if (state.activeCanvas && state.activeCanvas !== id) {
1084
- const current = syncCanvases().find((canvas) => canvas.id === state.activeCanvas);
1085
- if (current) {
1086
- current.layout = layoutPayload();
1087
- current.savedAt = Date.now();
1088
- }
1089
- }
1289
+ if (!target || switchingCanvas) return;
1290
+ if (state.activeCanvas && state.activeCanvas !== id) syncActiveCanvas();
1291
+ switchingCanvas = true;
1090
1292
  state.activeCanvas = id;
1091
1293
  storeCanvases();
1092
1294
  closeCanvasMenu();
@@ -1096,9 +1298,90 @@ export function createBoard({ host, adapter, approvals, t, onOpenSession }) {
1096
1298
  void fitView();
1097
1299
  } catch {
1098
1300
  toast(t('canvas.broken'));
1301
+ } finally {
1302
+ switchingCanvas = false;
1099
1303
  }
1100
1304
  }
1101
1305
 
1306
+ function createBlankCanvas() {
1307
+ if (state.activeCanvas) syncActiveCanvas();
1308
+ switchingCanvas = true;
1309
+ try {
1310
+ state.activeCanvas = null;
1311
+ reset();
1312
+ state.zoom = 1;
1313
+ state.pan = { x: 24, y: 24 };
1314
+ applyView();
1315
+ storeCanvases();
1316
+ save();
1317
+ toast('已新建空白画布,原画布仍保留在画布列表中');
1318
+ } finally {
1319
+ switchingCanvas = false;
1320
+ }
1321
+ }
1322
+
1323
+ function confirmUnsavedCanvas() {
1324
+ return new Promise((resolve) => {
1325
+ const dialog = document.createElement('dialog');
1326
+ dialog.className = 'iwb-confirm-dialog';
1327
+ dialog.setAttribute('aria-labelledby', 'iwb-unsaved-title');
1328
+ dialog.innerHTML = `
1329
+ <form method="dialog" class="iwb-confirm-form">
1330
+ <h2 id="iwb-unsaved-title">保存当前画布?</h2>
1331
+ <p>当前画布还没有命名。继续后会清空当前视图,但不会停止或删除任何 DSH 会话。</p>
1332
+ <label>画布名称<input name="canvasName" maxlength="60" value="未命名画布" autocomplete="off"></label>
1333
+ <div class="iwb-confirm-actions">
1334
+ <button type="button" data-choice="cancel">取消</button>
1335
+ <button type="button" data-choice="discard">不保存,继续</button>
1336
+ <button type="button" class="primary" data-choice="save">保存并继续</button>
1337
+ </div>
1338
+ </form>`;
1339
+ document.body.appendChild(dialog);
1340
+ const finish = (choice) => {
1341
+ const name = dialog.querySelector('input').value.trim();
1342
+ if (choice === 'save' && !name) {
1343
+ dialog.querySelector('input').focus();
1344
+ return;
1345
+ }
1346
+ dialog.remove();
1347
+ resolve({ choice, name });
1348
+ };
1349
+ dialog.querySelector('[data-choice="cancel"]').addEventListener('click', () => finish('cancel'));
1350
+ dialog.querySelector('[data-choice="discard"]').addEventListener('click', () => finish('discard'));
1351
+ dialog.querySelector('[data-choice="save"]').addEventListener('click', () => finish('save'));
1352
+ dialog.addEventListener('cancel', (event) => {
1353
+ event.preventDefault();
1354
+ finish('cancel');
1355
+ });
1356
+ dialog.showModal();
1357
+ const input = dialog.querySelector('input');
1358
+ input.focus();
1359
+ input.select();
1360
+ });
1361
+ }
1362
+
1363
+ async function requestNewBlankCanvas() {
1364
+ if (state.activeCanvas || !state.cards.length) {
1365
+ createBlankCanvas();
1366
+ return true;
1367
+ }
1368
+ const result = await confirmUnsavedCanvas();
1369
+ if (result.choice === 'cancel') return false;
1370
+ if (result.choice === 'save' && !saveCanvasAs(result.name)) return false;
1371
+ createBlankCanvas();
1372
+ return true;
1373
+ }
1374
+
1375
+ async function requestSwitchCanvas(id) {
1376
+ if (!state.activeCanvas && state.cards.length) {
1377
+ const result = await confirmUnsavedCanvas();
1378
+ if (result.choice === 'cancel') return false;
1379
+ if (result.choice === 'save' && !saveCanvasAs(result.name)) return false;
1380
+ }
1381
+ switchCanvas(id);
1382
+ return true;
1383
+ }
1384
+
1102
1385
  function deleteCanvas(id) {
1103
1386
  const target = syncCanvases().find((canvas) => canvas.id === id);
1104
1387
  state.canvases = syncCanvases().filter((canvas) => canvas.id !== id);
@@ -1182,7 +1465,7 @@ export function createBoard({ host, adapter, approvals, t, onOpenSession }) {
1182
1465
  .replace('{time}', canvas.savedAt ? canvasStamp(canvas.savedAt) : '');
1183
1466
  pick.addEventListener('click', (event) => {
1184
1467
  event.stopPropagation();
1185
- switchCanvas(canvas.id);
1468
+ void requestSwitchCanvas(canvas.id);
1186
1469
  });
1187
1470
  const remove = el('button', 'iwb-canvas-remove');
1188
1471
  remove.type = 'button';
@@ -1442,14 +1725,32 @@ export function createBoard({ host, adapter, approvals, t, onOpenSession }) {
1442
1725
  return target?.id || '';
1443
1726
  }
1444
1727
 
1728
+ function recordFlow(card, target, status, extra) {
1729
+ const active = syncCanvases().find((canvas) => canvas.id === state.activeCanvas);
1730
+ const event = flow.record({
1731
+ sourceSessionId: card.sessionId,
1732
+ targetId: target.id,
1733
+ targetKind: target.kind === 'note' ? 'note' : 'session',
1734
+ canvasId: state.activeCanvas || '',
1735
+ taskId: active?.taskId || '',
1736
+ status,
1737
+ mode: target.mode === 'draft' ? 'draft' : 'send',
1738
+ ...extra,
1739
+ });
1740
+ schedulePipelines();
1741
+ return event;
1742
+ }
1743
+
1445
1744
  function addPipeTarget(card, targetCard, fromSide) {
1446
1745
  const kind = targetCard.kind === 'note' ? 'note' : 'session';
1447
1746
  const id = kind === 'note' ? targetCard.id : targetCard.sessionId;
1448
1747
  if (!id || targetCard === card) return false;
1449
1748
  const targets = pipeTargets(card).filter((target) => !(target.kind === kind && target.id === id));
1450
1749
  const expanded = targets.length !== pipeTargets(card).length;
1451
- targets.push({ kind, id, mode: 'send', from: fromSide || 'right' });
1750
+ const target = { kind, id, mode: 'send', from: fromSide || 'right' };
1751
+ targets.push(target);
1452
1752
  setPipeTargets(card, targets);
1753
+ if (!expanded) recordFlow(card, target, 'waiting', { message: '连线已创建,等待上游完成' });
1453
1754
  return !expanded;
1454
1755
  }
1455
1756
 
@@ -1517,7 +1818,17 @@ export function createBoard({ host, adapter, approvals, t, onOpenSession }) {
1517
1818
  });
1518
1819
  const path = document.createElementNS(SVG_NS, 'path');
1519
1820
  path.setAttribute('d', d);
1520
- path.setAttribute('class', 'iwb-link' + (card.running ? ' iwb-link-active' : ''));
1821
+ const edgeKey = card.sessionId + '=>' + (target.kind === 'note' ? 'note' : 'session') + ':' + target.id;
1822
+ const latest = flow.latestByEdge().get(edgeKey);
1823
+ const flowStatus = latest?.status || 'waiting';
1824
+ path.setAttribute('class', 'iwb-link iwb-link-' + flowStatus + (card.running ? ' iwb-link-active' : ''));
1825
+ path.setAttribute('data-flow-status', flowStatus);
1826
+ path.setAttribute('data-edge-key', edgeKey);
1827
+ if (latest?.message) {
1828
+ const title = document.createElementNS(SVG_NS, 'title');
1829
+ title.textContent = latest.message + (latest.at ? ' · ' + new Date(latest.at).toLocaleString() : '');
1830
+ path.appendChild(title);
1831
+ }
1521
1832
  if (target.mode === 'draft') path.setAttribute('stroke-dasharray', '4 4');
1522
1833
  const arrow = document.createElementNS(SVG_NS, 'path');
1523
1834
  arrow.setAttribute('d', arrowPath(edgeAnchor(targetCard, toSide), toSide));
@@ -1683,6 +1994,22 @@ export function createBoard({ host, adapter, approvals, t, onOpenSession }) {
1683
1994
  }
1684
1995
  }
1685
1996
 
1997
+ function maybeDeliverCompleted(card) {
1998
+ if (card.running || card.kind === 'note') return;
1999
+ const text = lastAssistantText(card);
2000
+ if (!text) return;
2001
+ const fingerprint = text.slice(0, 160);
2002
+ if (card.catchUpFingerprint === fingerprint) return;
2003
+ const pending = pipeTargets(card).some((target) => (card.pipedFingerprints || {})[target.kind + ':' + target.id] !== fingerprint);
2004
+ if (!pending) return;
2005
+ card.catchUpFingerprint = fingerprint;
2006
+ // A completed upstream can predate the edge or a page restore. Deliver it once
2007
+ // instead of requiring a new running → idle transition.
2008
+ setTimeout(() => {
2009
+ if (!disposed && !card.running) void deliverPipeline(card);
2010
+ }, 0);
2011
+ }
2012
+
1686
2013
  async function deliverPipeline(card) {
1687
2014
  const targets = pipeTargets(card);
1688
2015
  if (!targets.length) return;
@@ -1719,6 +2046,7 @@ export function createBoard({ host, adapter, approvals, t, onOpenSession }) {
1719
2046
  area.dispatchEvent(new Event('input', { bubbles: true }));
1720
2047
  targetCard.pipeDepth = depth;
1721
2048
  card.pipedFingerprints[key] = fingerprint;
2049
+ recordFlow(card, target, 'delivered', { fingerprint, message: '结果已写入便签' });
1722
2050
  ensureVisible(targetCard);
1723
2051
  toast(t(replace ? 'pipe.notedReplaced' : 'pipe.noted').replace('{name}', targetCard.title || t('untitled')));
1724
2052
  continue;
@@ -1732,16 +2060,20 @@ export function createBoard({ host, adapter, approvals, t, onOpenSession }) {
1732
2060
  ensureVisible(targetCard);
1733
2061
  targetCard.pipeDepth = depth;
1734
2062
  card.pipedFingerprints[key] = fingerprint;
2063
+ recordFlow(card, target, 'drafted', { fingerprint, message: '已生成草稿,等待用户发送' });
1735
2064
  toast(t('pipe.drafted').replace('{name}', pipeTargetLabel(target)));
1736
2065
  continue;
1737
2066
  }
1738
2067
 
1739
2068
  try {
2069
+ recordFlow(card, target, 'delivering', { fingerprint, message: '正在投递到目标会话' });
1740
2070
  await adapter.prompt(target.id, text, 'queue');
1741
2071
  card.pipedFingerprints[key] = fingerprint;
1742
2072
  if (targetCard) targetCard.pipeDepth = depth;
2073
+ recordFlow(card, target, 'delivered', { fingerprint, message: '已发送到目标会话' });
1743
2074
  toast(t('pipe.sent').replace('{name}', pipeTargetLabel(target)));
1744
2075
  } catch (error) {
2076
+ recordFlow(card, target, 'failed', { fingerprint, message: error?.message || '投递失败' });
1745
2077
  toast(t('pipe.failed').replace('{error}', error?.message || ''));
1746
2078
  }
1747
2079
  }
@@ -1864,6 +2196,7 @@ export function createBoard({ host, adapter, approvals, t, onOpenSession }) {
1864
2196
  } catch {
1865
2197
  /* ignore */
1866
2198
  }
2199
+ if (card.kind === 'file') void fileStore.remove(card.fileId);
1867
2200
  card.el.remove();
1868
2201
  try {
1869
2202
  card.detachApprovals?.();
@@ -1882,7 +2215,7 @@ export function createBoard({ host, adapter, approvals, t, onOpenSession }) {
1882
2215
  renderPipeBadge(other);
1883
2216
  }
1884
2217
  }
1885
- schedulePipelines();
2218
+ renderPipelines();
1886
2219
  if (state.selected.delete(card.id)) renderBatchBar();
1887
2220
  if (state.focusedId === card.id) {
1888
2221
  state.focusedId = null;
@@ -1903,6 +2236,7 @@ export function createBoard({ host, adapter, approvals, t, onOpenSession }) {
1903
2236
  }
1904
2237
 
1905
2238
  function markDirty(card) {
2239
+ hydratePending = false;
1906
2240
  if (disposed) return;
1907
2241
  dirty.add(card);
1908
2242
  if (frame) return;
@@ -1920,7 +2254,7 @@ export function createBoard({ host, adapter, approvals, t, onOpenSession }) {
1920
2254
  }
1921
2255
 
1922
2256
  function renderCard(card) {
1923
- if (card.kind === 'note') return;
2257
+ if (card.kind === 'note' || card.kind === 'file') return;
1924
2258
  let view;
1925
2259
  try {
1926
2260
  view = adapter.read(card.sessionId);
@@ -2029,6 +2363,8 @@ export function createBoard({ host, adapter, approvals, t, onOpenSession }) {
2029
2363
 
2030
2364
  renderBody(card, view);
2031
2365
  renderQueue(card, view);
2366
+ if (!card.running) maybeDeliverCompleted(card);
2367
+ taskController?.noteSessionRuntime(card);
2032
2368
  if (wasRunning !== card.running) {
2033
2369
  renderFoot(card);
2034
2370
  if (wasRunning && !card.running) void deliverPipeline(card);
@@ -2392,8 +2728,14 @@ export function createBoard({ host, adapter, approvals, t, onOpenSession }) {
2392
2728
  switch (event.key) {
2393
2729
  case 'Enter':
2394
2730
  event.preventDefault();
2395
- if (card.kind === 'note') node.querySelector('.iwb-note-input')?.focus();
2396
- else node.querySelector('.iwb-foot textarea')?.focus();
2731
+ if (card.kind === 'note') {
2732
+ if (card.viewMode !== 'source') {
2733
+ card.viewMode = 'source';
2734
+ noteBody(card);
2735
+ saveSoon();
2736
+ }
2737
+ node.querySelector('.iwb-note-input')?.focus();
2738
+ } else node.querySelector('.iwb-foot textarea')?.focus();
2397
2739
  break;
2398
2740
  case 'Escape':
2399
2741
  event.preventDefault();
@@ -2646,6 +2988,12 @@ export function createBoard({ host, adapter, approvals, t, onOpenSession }) {
2646
2988
  }
2647
2989
 
2648
2990
  function updateCounts() {
2991
+ if (state.mode === 'task') {
2992
+ const tasks = taskController?.snapshot().tasks || [];
2993
+ const actionable = tasks.filter((task) => ['needs_input', 'blocked', 'review'].includes(task.status)).length;
2994
+ countsNode.textContent = tasks.length + ' 项任务' + (actionable ? ' · ' + actionable + ' 项待处理' : '');
2995
+ return;
2996
+ }
2649
2997
  const running = state.cards.filter((c) => c.running).length;
2650
2998
  const parts = [t('count.cards').replace('{n}', String(state.cards.length))];
2651
2999
  if (running) parts.push(t('count.running').replace('{n}', String(running)));
@@ -2666,10 +3014,12 @@ export function createBoard({ host, adapter, approvals, t, onOpenSession }) {
2666
3014
 
2667
3015
  function save() {
2668
3016
  if (disposed || suppressSave) return;
3017
+ if (hydratePending) return;
2669
3018
  try {
2670
3019
  const payload = layoutPayload();
2671
3020
  localUpdatedAt = payload.updatedAt;
2672
3021
  window.localStorage.setItem(STORAGE_KEY, JSON.stringify(payload));
3022
+ scheduleActiveCanvasSave();
2673
3023
  if (!applyingRemote) {
2674
3024
  void pushRemoteLayout(payload, clientId).then((result) => {
2675
3025
  if (result?.rev) remoteRev = result.rev;
@@ -2680,7 +3030,7 @@ export function createBoard({ host, adapter, approvals, t, onOpenSession }) {
2680
3030
  }
2681
3031
  }
2682
3032
 
2683
- function restore() {
3033
+ async function restore() {
2684
3034
  if (restoreDone) return;
2685
3035
  restoreDone = true;
2686
3036
  let saved = null;
@@ -2694,8 +3044,16 @@ export function createBoard({ host, adapter, approvals, t, onOpenSession }) {
2694
3044
  }
2695
3045
  approvals?.setEnabled?.(state.settings.inlineApprovals);
2696
3046
  if (!saved || !Array.isArray(saved.cards)) {
3047
+ hydratePending = true;
2697
3048
  syncApprovalSessions();
2698
- void syncFromRemote().then(() => startRemoteSync());
3049
+ void syncFromRemote().then((applied) => {
3050
+ hydratePending = false;
3051
+ if (!applied && !saveTimer) {
3052
+ // Host had nothing (or was unreachable): the empty board is legitimately
3053
+ // ours now, so the next interaction may persist it.
3054
+ }
3055
+ startRemoteSync();
3056
+ });
2699
3057
  void loadCanvases();
2700
3058
  return false;
2701
3059
  }
@@ -2717,6 +3075,10 @@ export function createBoard({ host, adapter, approvals, t, onOpenSession }) {
2717
3075
  }
2718
3076
  continue;
2719
3077
  }
3078
+ if (card?.kind === 'file') {
3079
+ await addFileCard({ ...card, focus: false });
3080
+ continue;
3081
+ }
2720
3082
  if (!card?.sessionId) continue;
2721
3083
  addSession({
2722
3084
  sessionId: card.sessionId,
@@ -2772,6 +3134,11 @@ export function createBoard({ host, adapter, approvals, t, onOpenSession }) {
2772
3134
  workspace: card.workspace || '',
2773
3135
  kind: card.kind || 'session',
2774
3136
  note: card.note || '',
3137
+ viewMode: card.viewMode || 'preview',
3138
+ fileId: card.fileId || '',
3139
+ type: card.type || '',
3140
+ size: Number(card.size) || 0,
3141
+ composerDraft: card.composerDraft || '',
2775
3142
  pinned: Boolean(card.pinned),
2776
3143
  pipeline: pipeTargets(card).length ? { targets: pipeTargets(card) } : null,
2777
3144
  x: card.x,
@@ -2803,7 +3170,7 @@ export function createBoard({ host, adapter, approvals, t, onOpenSession }) {
2803
3170
  }
2804
3171
 
2805
3172
  /** Replace the whole board with a saved layout document. */
2806
- function applyLayout(saved, options) {
3173
+ async function applyLayout(saved, options) {
2807
3174
  if (!saved || !Array.isArray(saved.cards)) throw new Error(t('settings.importInvalid'));
2808
3175
  reset();
2809
3176
  if (typeof saved.zoom === 'number') state.zoom = clamp(saved.zoom, 0.3, 1.6);
@@ -2816,6 +3183,8 @@ export function createBoard({ host, adapter, approvals, t, onOpenSession }) {
2816
3183
  note.pinned = true;
2817
3184
  note.el?.classList.add('iwb-pinned');
2818
3185
  }
3186
+ } else if (card?.kind === 'file') {
3187
+ await addFileCard({ ...card, focus: false });
2819
3188
  } else if (card.sessionId) {
2820
3189
  addSession({ ...card });
2821
3190
  }
@@ -2841,6 +3210,9 @@ export function createBoard({ host, adapter, approvals, t, onOpenSession }) {
2841
3210
  let interactionActive = false;
2842
3211
  let remoteRev = 0;
2843
3212
  let localUpdatedAt = 0;
3213
+ // True between "no local cache" and the first Host sync: saving in that window
3214
+ // would push an empty board over the Host copy (real data loss).
3215
+ let hydratePending = false;
2844
3216
  let applyingRemote = false;
2845
3217
  let firstRemoteSync = true;
2846
3218
  // Own writes echo back over the event stream; the id lets us ignore them so a
@@ -2914,6 +3286,9 @@ export function createBoard({ host, adapter, approvals, t, onOpenSession }) {
2914
3286
  });
2915
3287
  state.cards = [];
2916
3288
  state.stacks = [];
3289
+ if (pipelineFrame) cancelAnimationFrame(pipelineFrame);
3290
+ pipelineFrame = 0;
3291
+ renderPipelines();
2917
3292
  try {
2918
3293
  window.localStorage.removeItem(STORAGE_KEY);
2919
3294
  } catch {
@@ -2940,6 +3315,23 @@ export function createBoard({ host, adapter, approvals, t, onOpenSession }) {
2940
3315
  focusCard(current || cardOrder()[0], { announce: false });
2941
3316
  });
2942
3317
 
3318
+ canvas.addEventListener('paste', (event) => {
3319
+ if (event.target.closest('textarea')) return;
3320
+ const files = [...(event.clipboardData?.files || [])];
3321
+ if (!files.length) return;
3322
+ event.preventDefault();
3323
+ for (const file of files) void addFileCard(file);
3324
+ });
3325
+ canvas.addEventListener('dragover', (event) => {
3326
+ if (event.dataTransfer?.types?.includes('Files')) event.preventDefault();
3327
+ });
3328
+ canvas.addEventListener('drop', (event) => {
3329
+ const files = [...(event.dataTransfer?.files || [])];
3330
+ if (!files.length) return;
3331
+ event.preventDefault();
3332
+ for (const file of files) void addFileCard(file);
3333
+ });
3334
+
2943
3335
  canvas.addEventListener('pointerdown', (event) => {
2944
3336
  if (event.target.closest('.iwb-card') || event.target.closest('.iwb-zoom')) return;
2945
3337
  if (event.button !== 0 && event.button !== 1) return;
@@ -2969,15 +3361,20 @@ export function createBoard({ host, adapter, approvals, t, onOpenSession }) {
2969
3361
  (event) => {
2970
3362
  const overCard = Boolean(event.target?.closest?.('.iwb-card'));
2971
3363
  if (overCard && !(event.ctrlKey || event.metaKey)) {
2972
- // In-card scrolling belongs to the browser. Once the transcript is at the
2973
- // edge the wheel chains back to the canvas, so paging never dead-ends.
3364
+ // Native card scrolling always wins. By default the canvas must not jump
3365
+ // when a transcript or note reaches its vertical edge. The legacy chain
3366
+ // remains available only as an explicit settings opt-in.
2974
3367
  const body = event.target.closest('.iwb-body');
2975
3368
  if (body && state.settings.chainWheel) {
2976
3369
  const atTop = body.scrollTop <= 0;
2977
3370
  const atBottom = body.scrollTop + body.clientHeight >= body.scrollHeight - 1;
2978
3371
  const scrollingUp = event.deltaY < 0;
2979
- if (!(atTop && scrollingUp) && !(atBottom && !scrollingUp)) return;
3372
+ if (!(atTop && scrollingUp) && !(atBottom && !scrollingUp)) {
3373
+ event.stopPropagation();
3374
+ return;
3375
+ }
2980
3376
  } else {
3377
+ event.stopPropagation();
2981
3378
  return;
2982
3379
  }
2983
3380
  }
@@ -3032,6 +3429,11 @@ export function createBoard({ host, adapter, approvals, t, onOpenSession }) {
3032
3429
  openCanvasMenu();
3033
3430
  });
3034
3431
 
3432
+ btnBlank.addEventListener('click', (event) => {
3433
+ event.stopPropagation();
3434
+ void requestNewBlankCanvas();
3435
+ });
3436
+
3035
3437
  const onCanvasPointerDown = (event) => {
3036
3438
  if (!canvasPop) return;
3037
3439
  if (event.target?.closest?.('.iwb-canvas-menu') || event.target?.closest?.('.iwb-toolbar')) return;
@@ -3088,6 +3490,68 @@ export function createBoard({ host, adapter, approvals, t, onOpenSession }) {
3088
3490
  };
3089
3491
  document.addEventListener('keydown', onKey);
3090
3492
 
3493
+ function setMode(mode) {
3494
+ state.mode = mode === 'task' ? 'task' : 'canvas';
3495
+ const isTask = state.mode === 'task';
3496
+ canvas.hidden = isTask;
3497
+ if (taskView) taskView.root.hidden = !isTask;
3498
+ for (const control of [btnNew, btnNote, btnCanvas, btnBlank, btnArrange, btnBoard, btnFit, btnCollapse, hint, todoBar]) {
3499
+ control.hidden = isTask;
3500
+ }
3501
+ btnCanvasMode.classList.toggle('active', !isTask);
3502
+ btnTaskMode.classList.toggle('active', isTask);
3503
+ btnCanvasMode.setAttribute('aria-selected', String(!isTask));
3504
+ btnTaskMode.setAttribute('aria-selected', String(isTask));
3505
+ if (isTask) taskView?.refresh();
3506
+ updateCounts();
3507
+ }
3508
+
3509
+ taskController = createTaskController({
3510
+ adapter,
3511
+ taskStore,
3512
+ flow,
3513
+ t,
3514
+ toast,
3515
+ bridge: {
3516
+ getCards: () => state.cards,
3517
+ getCanvases: syncCanvases,
3518
+ getActiveCanvas: () => state.activeCanvas,
3519
+ requestNewBlankCanvas,
3520
+ requestSwitchCanvas,
3521
+ saveCanvasAs,
3522
+ storeCanvases,
3523
+ addSession,
3524
+ addNote,
3525
+ setPipeTargets,
3526
+ renderFoot,
3527
+ fitView,
3528
+ centerCard,
3529
+ flash,
3530
+ switchCanvas,
3531
+ setMode,
3532
+ save,
3533
+ schedulePipelines,
3534
+ recordFlow,
3535
+ },
3536
+ });
3537
+ taskView = createTaskView({
3538
+ host: root,
3539
+ t,
3540
+ el,
3541
+ getSnapshot: () => taskController.snapshot(),
3542
+ actions: taskController,
3543
+ toast,
3544
+ });
3545
+ taskStore.subscribe(() => {
3546
+ if (state.mode === 'task') taskView.refresh();
3547
+ });
3548
+ taskLoadPromise.then(() => {
3549
+ if (state.mode === 'task') taskView.refresh();
3550
+ });
3551
+ btnCanvasMode.addEventListener('click', () => setMode('canvas'));
3552
+ btnTaskMode.addEventListener('click', () => setMode('task'));
3553
+ setMode('canvas');
3554
+
3091
3555
  applyView();
3092
3556
  updateEmptyState();
3093
3557
 
@@ -3118,6 +3582,8 @@ export function createBoard({ host, adapter, approvals, t, onOpenSession }) {
3118
3582
  addSession,
3119
3583
  restore,
3120
3584
  reset,
3585
+ setMode,
3586
+ getTaskSnapshot: () => taskController?.snapshot(),
3121
3587
  dispose() {
3122
3588
  disposed = true;
3123
3589
  // Unmount happens while the host is tearing the page down: a throw here
@@ -3125,7 +3591,11 @@ export function createBoard({ host, adapter, approvals, t, onOpenSession }) {
3125
3591
  try {
3126
3592
  clearInterval(ticker);
3127
3593
  clearTimeout(saveTimer);
3594
+ clearTimeout(canvasSaveTimer);
3128
3595
  clearTimeout(toastTimer);
3596
+ taskStore.dispose();
3597
+ taskController?.dispose();
3598
+ taskView?.dispose();
3129
3599
  settingsMenu.close();
3130
3600
  tools.dispose();
3131
3601
  stopApprovalWatch?.();