pmx-canvas 0.9.2 → 0.10.0

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.
Files changed (87) hide show
  1. package/.github/extensions/pmx-canvas/extension.mjs +9 -3
  2. package/.github/extensions/pmx-canvas/runtime.json +1 -1
  3. package/.github/extensions/pmx-canvas/tools.json +9278 -2014
  4. package/CHANGELOG.md +34 -1
  5. package/dist/canvas/global.css +12 -17
  6. package/dist/canvas/index.js +58 -58
  7. package/dist/canvas/mcp-app.html +75 -80
  8. package/dist/types/client/canvas/submit-without-navigation.d.ts +3 -0
  9. package/dist/types/client/state/intent-bridge.d.ts +0 -3
  10. package/dist/types/client/state/presence-store.d.ts +3 -3
  11. package/dist/types/client/types.d.ts +1 -1
  12. package/dist/types/mcp/canvas-access.d.ts +1 -12
  13. package/dist/types/mcp/resource-subscriptions.d.ts +7 -0
  14. package/dist/types/mcp/server.d.ts +2 -0
  15. package/dist/types/server/ax-wait.d.ts +1 -0
  16. package/dist/types/server/canvas-operations.d.ts +1 -0
  17. package/dist/types/server/canvas-state.d.ts +2 -0
  18. package/dist/types/server/index.d.ts +5 -5
  19. package/dist/types/server/knowledge-lifecycle.d.ts +11 -2
  20. package/dist/types/server/lifecycle-status.d.ts +3 -1
  21. package/dist/types/server/operations/http.d.ts +10 -0
  22. package/dist/types/server/operations/index.d.ts +2 -2
  23. package/dist/types/server/operations/invoker.d.ts +4 -3
  24. package/dist/types/server/operations/mcp-contracts.d.ts +20 -0
  25. package/dist/types/server/operations/mcp.d.ts +2 -0
  26. package/dist/types/server/operations/ops/batch.d.ts +1 -0
  27. package/dist/types/server/operations/registry.d.ts +2 -2
  28. package/dist/types/server/operations/types.d.ts +12 -2
  29. package/dist/types/server/server.d.ts +2 -0
  30. package/dist/types/server/tour-control.d.ts +6 -3
  31. package/dist/types/server/webpage-node.d.ts +1 -0
  32. package/docs/api-reference.md +2 -2
  33. package/docs/cli.md +10 -1
  34. package/docs/design/Chrome.dc.html +1 -0
  35. package/docs/design.md +3 -1
  36. package/docs/http-api.md +31 -0
  37. package/docs/mcp.md +98 -22
  38. package/docs/node-types.md +3 -0
  39. package/docs/plans/plan-019-post-0.9-roadmap.md +187 -11
  40. package/docs/sdk.md +10 -0
  41. package/package.json +1 -1
  42. package/plugins/pmx-canvas/com.github.copilot/extensions/pmx-canvas/extension.mjs +9 -3
  43. package/plugins/pmx-canvas/com.github.copilot/extensions/pmx-canvas/runtime.json +1 -1
  44. package/plugins/pmx-canvas/plugin.json +1 -1
  45. package/plugins/pmx-canvas/runtime.json +1 -1
  46. package/plugins/pmx-canvas/tools.json +9278 -2014
  47. package/skills/pmx-canvas/SKILL.md +12 -7
  48. package/skills/pmx-canvas/references/full-reference.md +35 -2
  49. package/skills/pmx-canvas/references/github-copilot-app-adapter.md +2 -2
  50. package/skills/pmx-canvas/references/installing-pmx-canvas.md +7 -7
  51. package/src/client/canvas/BoardCopyDialog.tsx +2 -1
  52. package/src/client/canvas/KnowledgeDialog.tsx +3 -0
  53. package/src/client/canvas/LifecyclePanel.tsx +4 -0
  54. package/src/client/canvas/RelationPresetsDialog.tsx +2 -0
  55. package/src/client/canvas/ToolRail.tsx +2 -0
  56. package/src/client/canvas/submit-without-navigation.ts +14 -0
  57. package/src/client/state/canvas-store.ts +12 -24
  58. package/src/client/state/intent-bridge.ts +0 -6
  59. package/src/client/state/presence-store.ts +3 -3
  60. package/src/client/state/sse-bridge.ts +11 -6
  61. package/src/client/theme/global.css +12 -17
  62. package/src/mcp/canvas-access.ts +6 -47
  63. package/src/mcp/resource-subscriptions.ts +181 -0
  64. package/src/mcp/server.ts +185 -219
  65. package/src/server/ax-wait.ts +21 -6
  66. package/src/server/canvas-operations.ts +6 -2
  67. package/src/server/canvas-state.ts +10 -0
  68. package/src/server/index.ts +20 -32
  69. package/src/server/knowledge-lifecycle.ts +66 -0
  70. package/src/server/lifecycle-status.ts +79 -7
  71. package/src/server/operations/http.ts +69 -21
  72. package/src/server/operations/index.ts +8 -1
  73. package/src/server/operations/invoker.ts +53 -5
  74. package/src/server/operations/mcp-contracts.ts +339 -0
  75. package/src/server/operations/mcp.ts +153 -18
  76. package/src/server/operations/ops/ax-await.ts +18 -10
  77. package/src/server/operations/ops/ax-read.ts +2 -0
  78. package/src/server/operations/ops/ax-timeline.ts +2 -2
  79. package/src/server/operations/ops/batch.ts +27 -8
  80. package/src/server/operations/ops/lifecycle.ts +3 -7
  81. package/src/server/operations/ops/nodes.ts +20 -8
  82. package/src/server/operations/ops/viewport.ts +3 -7
  83. package/src/server/operations/registry.ts +24 -4
  84. package/src/server/operations/types.ts +16 -2
  85. package/src/server/server.ts +23 -10
  86. package/src/server/tour-control.ts +17 -8
  87. package/src/server/webpage-node.ts +9 -4
@@ -341,7 +341,7 @@ const axDeliveryPendingOperation = defineOperation<z.infer<typeof axDeliveryPend
341
341
  // `consumer` is a loop-safety scope, not a source label — never defaulted.
342
342
  formatResult: axJsonResult,
343
343
  },
344
- handler: async (input) => {
344
+ handler: async (input, ctx) => {
345
345
  const consumer = typeof input.consumer === 'string' ? input.consumer : undefined;
346
346
  // A claim is proof this consumer polls steering — its presence (session or
347
347
  // external writer) becomes a legitimate composer steer target.
@@ -363,7 +363,7 @@ const axDeliveryPendingOperation = defineOperation<z.infer<typeof axDeliveryPend
363
363
  // Long-poll: hosts that cannot be woken from outside (Copilot, Codex —
364
364
  // their model runs only while the host gives it a turn) park here and
365
365
  // wake the moment steering lands, instead of burning the turn polling.
366
- await waitForAxCondition({ ready: () => readPending().length > 0, timeoutMs });
366
+ await waitForAxCondition({ ready: () => readPending().length > 0, timeoutMs, signal: ctx.signal });
367
367
  pending = readPending();
368
368
  }
369
369
  // The MCP tool aggregated pendingActivity; one wire body now serves it over
@@ -44,6 +44,7 @@ export interface BatchEnvelope {
44
44
  refs: Record<string, unknown>;
45
45
  failedIndex?: number;
46
46
  error?: string;
47
+ cancelled?: boolean;
47
48
  }
48
49
 
49
50
  const SUPPORTED_BATCH_OPS = new Set([
@@ -220,7 +221,7 @@ function shapeBatchEntry(op: string, result: unknown, creationReceipt = false):
220
221
  return body;
221
222
  }
222
223
 
223
- async function runBatch(operations: BatchEntry[]): Promise<BatchEnvelope> {
224
+ async function runBatch(operations: BatchEntry[], ctx: OperationContext): Promise<BatchEnvelope> {
224
225
  const refs: Record<string, unknown> = {};
225
226
  const results: Array<Record<string, unknown>> = [];
226
227
 
@@ -231,6 +232,15 @@ async function runBatch(operations: BatchEntry[]): Promise<BatchEnvelope> {
231
232
  return { ok: false, failedIndex: index, error: `Operation ${index} has invalid args.`, results, refs };
232
233
  }
233
234
  try {
235
+ ctx.signal?.throwIfAborted();
236
+ if (ctx.onProgress) {
237
+ const boardGeneration = canvasState.boardGeneration;
238
+ await ctx.onProgress({ progress: index, total: operations.length, message: operation.op });
239
+ if (canvasState.boardGeneration !== boardGeneration) {
240
+ throw new Error('The board changed while the batch was running.');
241
+ }
242
+ }
243
+ ctx.signal?.throwIfAborted();
234
244
  if (!SUPPORTED_BATCH_OPS.has(operation.op)) {
235
245
  return {
236
246
  ok: false,
@@ -259,35 +269,43 @@ async function runBatch(operations: BatchEntry[]): Promise<BatchEnvelope> {
259
269
  // ghost-cursor exemption for batch operations). No `fromWorkbench`: the
260
270
  // browser never issues batches, so inner writes are agent writes and the
261
271
  // scope fence applies to each of them.
262
- const pending = executeOperation(dispatch.name, dispatch.args, { suppressAutoGhost: true });
272
+ const pending = executeOperation(dispatch.name, dispatch.args, {
273
+ suppressAutoGhost: true,
274
+ signal: ctx.signal,
275
+ onProgress: ctx.onProgress
276
+ ? (progress) => ctx.onProgress!({ progress: index, total: operations.length, message: progress.message })
277
+ : undefined,
278
+ });
263
279
  // The first write may synchronously open a board from Home. Capture after
264
280
  // dispatch, then refuse to continue a partially completed batch elsewhere.
265
281
  const boardGeneration = canvasState.boardGeneration;
266
282
  const raw = await pending;
267
- if (canvasState.boardGeneration !== boardGeneration) {
268
- throw new Error('The board changed while the batch was running.');
269
- }
283
+ const boardChanged = canvasState.boardGeneration !== boardGeneration;
270
284
  const result = shapeBatchEntry(
271
285
  operation.op,
272
286
  raw,
273
- ['node.add', 'group.create', 'edge.add'].includes(operation.op) &&
274
- (args.requestId !== undefined || args.destinationBoardId !== undefined),
287
+ boardChanged ||
288
+ (['node.add', 'group.create', 'edge.add'].includes(operation.op) &&
289
+ (args.requestId !== undefined || args.destinationBoardId !== undefined)),
275
290
  );
276
291
  results.push(result);
277
292
  if (typeof operation.assign === 'string' && operation.assign.trim().length > 0) {
278
293
  refs[operation.assign] = result;
279
294
  }
295
+ if (boardChanged) throw new Error('The board changed while the batch was running.');
280
296
  } catch (error) {
281
297
  return {
282
298
  ok: false,
283
299
  failedIndex: index,
284
300
  error: error instanceof Error ? error.message : String(error),
301
+ ...(ctx.signal?.aborted ? { cancelled: true } : {}),
285
302
  results,
286
303
  refs,
287
304
  };
288
305
  }
289
306
  }
290
307
 
308
+ await ctx.onProgress?.({ progress: operations.length, total: operations.length, message: 'Batch complete' });
291
309
  return { ok: true, results, refs };
292
310
  }
293
311
 
@@ -356,6 +374,7 @@ function compactBatchResult(result: BatchEnvelope): Record<string, unknown> {
356
374
  ok: result.ok,
357
375
  ...(result.failedIndex !== undefined ? { failedIndex: result.failedIndex } : {}),
358
376
  ...(result.error ? { error: result.error } : {}),
377
+ ...(result.cancelled ? { cancelled: true } : {}),
359
378
  results: result.results.map((entry) => compactBatchValue(entry)),
360
379
  refs: Object.fromEntries(Object.entries(result.refs).map(([key, value]) => [key, compactBatchValue(value)])),
361
380
  };
@@ -406,7 +425,7 @@ const batchOperation = defineOperation<z.infer<typeof batchSchema>, BatchEnvelop
406
425
  // Suppress every per-entry SSE frame (auto layout emit + each handler's
407
426
  // ctx.emit). After the loop completes, emit ONE final canvas-layout-update.
408
427
  const revision = canvasState.getContentRevision().revision;
409
- const envelope = await runWithSuppressedEmits(() => runBatch(operations));
428
+ const envelope = await runWithSuppressedEmits(() => runBatch(operations, ctx));
410
429
  if (
411
430
  revision !== canvasState.getContentRevision().revision ||
412
431
  operations.some(
@@ -3,8 +3,7 @@ import { canvasState } from '../../canvas-state.js';
3
3
  import { categorySchema, folderPropertiesSchema, lifecycleSchema } from '../../knowledge-lifecycle.js';
4
4
  import { defineOperation, OperationError, type Operation } from '../types.js';
5
5
  import { readTargetBoard } from './boards.js';
6
- import { lifecycleQualifications, lifecycleSnapshot } from '../../lifecycle-status.js';
7
- import { memoryKey } from '../../../shared/memory-graph.js';
6
+ import { lifecycleQualification, lifecycleSnapshot } from '../../lifecycle-status.js';
8
7
  import { folderAncestors } from '../../../shared/boards.js';
9
8
  import { relationPresetSchema } from '../../../shared/relations.js';
10
9
 
@@ -155,9 +154,7 @@ export const lifecycleOperations: Operation[] = [
155
154
  contentRevision: node.contentRevision ?? 0,
156
155
  ...canvasState.knowledge.resolveCard(folder, node),
157
156
  ...canvasState.knowledge.reviews(read.boardId, input.id),
158
- qualification: lifecycleQualifications(Date.now(), [{ boardId: read.boardId, cardId: input.id }])[
159
- memoryKey({ boardId: read.boardId, cardId: input.id })
160
- ],
157
+ qualification: lifecycleQualification({ boardId: read.boardId, cardId: input.id }),
161
158
  };
162
159
  },
163
160
  }),
@@ -216,8 +213,7 @@ export const lifecycleOperations: Operation[] = [
216
213
  if (!canvasState.getNode(input.id) || !canvasState.activeBoardId)
217
214
  throw new OperationError('Card not found.', 404);
218
215
  const observations =
219
- lifecycleQualifications()[memoryKey({ boardId: canvasState.activeBoardId, cardId: input.id })]?.observations ??
220
- {};
216
+ lifecycleQualification({ boardId: canvasState.activeBoardId, cardId: input.id })?.observations ?? {};
221
217
  const validates =
222
218
  input.applied && input.evidence.trim() && ['retain', 'revise', 'externalize'].includes(input.outcome);
223
219
  if (validates) {
@@ -55,8 +55,7 @@ import {
55
55
  import { WEBPAGE_NODE_DEFAULT_SIZE, normalizeWebpageUrl } from '../../webpage-node.js';
56
56
  import { defineOperation, OperationError, type Operation, type OperationContext } from '../types.js';
57
57
  import { readTargetBoard } from './boards.js';
58
- import { lifecycleQualifications } from '../../lifecycle-status.js';
59
- import { memoryKey } from '../../../shared/memory-graph.js';
58
+ import { lifecycleQualification } from '../../lifecycle-status.js';
60
59
 
61
60
  // ── Node types ────────────────────────────────────────────────
62
61
  // Single definition site for the basic node-type list: drives the HTTP type
@@ -634,6 +633,7 @@ async function createWebpageNode(body: Record<string, unknown>, ctx: OperationCo
634
633
 
635
634
  const extraData = isRecord(body.data) ? body.data : undefined;
636
635
  const geometry = resolveCreateGeometry(body);
636
+ ctx.signal?.throwIfAborted();
637
637
  const { id, node, sizeAdjustment } = addCanvasNode({
638
638
  type: 'webpage',
639
639
  ...(typeof body.title === 'string' ? { title: body.title } : {}),
@@ -649,7 +649,21 @@ async function createWebpageNode(body: Record<string, unknown>, ctx: OperationCo
649
649
  // registry emits the final layout update after the handler returns.
650
650
  ctx.emit('canvas-layout-update', { layout: canvasState.getLayout() });
651
651
  const boardGeneration = canvasState.boardGeneration;
652
- const refreshed = await refreshCanvasWebpageNode(id);
652
+ let refreshed: Awaited<ReturnType<typeof refreshCanvasWebpageNode>>;
653
+ try {
654
+ refreshed = await refreshCanvasWebpageNode(id, { signal: ctx.signal });
655
+ } catch (error) {
656
+ if (!ctx.signal?.aborted) throw error;
657
+ // Creation already committed. Return its receipt without writing an error
658
+ // status; batches retain this node and stop before their next entry.
659
+ return {
660
+ node,
661
+ extras: {
662
+ fetch: { ok: false, cancelled: true, error: 'Webpage fetch cancelled.' },
663
+ ...(sizeAdjustment ? { sizeAdjustment } : {}),
664
+ },
665
+ };
666
+ }
653
667
  if (canvasState.boardGeneration !== boardGeneration) {
654
668
  throw new OperationError('The board changed while the webpage was loading.', 409);
655
669
  }
@@ -1005,9 +1019,7 @@ const nodeGetOperation = defineOperation<z.infer<typeof nodeGetSchema>, Serializ
1005
1019
  const full = includeBlobs === true || includeBlobs === 'true';
1006
1020
  const qualify = (node: CanvasNodeState, boardId: string | null) => ({
1007
1021
  ...(full ? serializeCanvasNode(node) : serializeCanvasNodeWithBlobSummaries(node)),
1008
- qualification: boardId
1009
- ? lifecycleQualifications(Date.now(), [{ boardId, cardId: id }])[memoryKey({ boardId, cardId: id })]
1010
- : undefined,
1022
+ qualification: boardId ? lifecycleQualification({ boardId, cardId: id }) : undefined,
1011
1023
  });
1012
1024
  if (typeof board === 'string' && board.trim()) {
1013
1025
  const target = readTargetBoard(board, full);
@@ -1189,7 +1201,7 @@ const nodeUpdateOperation = defineOperation<z.infer<typeof nodeUpdateSchema>, Re
1189
1201
  throw new OperationError(error instanceof Error ? error.message : 'Invalid webpage URL.');
1190
1202
  }
1191
1203
  }
1192
- const result = await refreshCanvasWebpageNode(id, { ...(url ? { url } : {}) });
1204
+ const result = await refreshCanvasWebpageNode(id, { ...(url ? { url } : {}), signal: ctx.signal });
1193
1205
  return result as unknown as Record<string, unknown>;
1194
1206
  }
1195
1207
 
@@ -1445,7 +1457,7 @@ const nodeRefreshOperation = defineOperation<z.infer<typeof nodeRefreshSchema>,
1445
1457
  }
1446
1458
  // Legacy wire: the layout update fires after every completed refresh
1447
1459
  // attempt, success or failure (the node may have partial refresh state).
1448
- const result = await refreshCanvasWebpageNode(nodeId, { ...(url ? { url } : {}) });
1460
+ const result = await refreshCanvasWebpageNode(nodeId, { ...(url ? { url } : {}), signal: ctx.signal });
1449
1461
  ctx.emit('canvas-layout-update', { layout: canvasState.getLayout() });
1450
1462
  return result as unknown as Record<string, unknown>;
1451
1463
  },
@@ -13,7 +13,7 @@
13
13
  * This module must never import server.ts or index.ts.
14
14
  */
15
15
  import { z } from 'zod';
16
- import { tourSchema, derivedTour, rectSchema, cameraSchema, tourStopSchema } from '../../../shared/tour.js';
16
+ import { tourSchema, rectSchema, cameraSchema, tourStopSchema } from '../../../shared/tour.js';
17
17
  import { canvasState } from '../../canvas-state.js';
18
18
  import {
19
19
  arrangeCanvasNodes,
@@ -23,7 +23,7 @@ import {
23
23
  setClientViewportSize,
24
24
  } from '../../canvas-operations.js';
25
25
  import { validateCanvasLayout } from '../../canvas-validation.js';
26
- import { exitTour, goToTourStop, moveCamera, tourPosition } from '../../tour-control.js';
26
+ import { currentTour, exitTour, goToTourStop, moveCamera } from '../../tour-control.js';
27
27
  import { defineOperation, OperationError, type Operation } from '../types.js';
28
28
  import { closeNodeAppSession, isRecord } from './nodes.js';
29
29
 
@@ -329,11 +329,7 @@ const tourGetOperation = defineOperation({
329
329
  toolName: 'canvas_get_tour',
330
330
  description: 'Read the board tour, deriving groups in reading order when absent.',
331
331
  },
332
- handler: () => ({
333
- tour: canvasState.getTour() ?? derivedTour(canvasState.getLayout().nodes),
334
- derived: !canvasState.getTour(),
335
- position: tourPosition(),
336
- }),
332
+ handler: () => currentTour(),
337
333
  });
338
334
 
339
335
  // ── tour.go / tour.exit / camera.move ────────────────────────
@@ -20,7 +20,7 @@ import type { MemoryGraph } from '../../shared/memory-graph.js';
20
20
  import { openBoardForWrite } from '../canvas-operations.js';
21
21
  import { boardsPayload } from './ops/boards.js';
22
22
  import type { PmxAxIntent, PmxAxIntentKind } from '../../shared/ax-intent.js';
23
- import { OperationError, type Operation, type OperationContext } from './types.js';
23
+ import { OperationError, type Operation, type OperationContext, type OperationExecutionOptions } from './types.js';
24
24
 
25
25
  const operations = new Map<string, Operation>();
26
26
 
@@ -75,8 +75,6 @@ export async function runWithSuppressedEmits<T>(fn: () => Promise<T>): Promise<T
75
75
  return suppressedEmits.run(true, fn);
76
76
  }
77
77
 
78
- const operationContext: OperationContext = { emit: emitOperationEvent };
79
-
80
78
  const INTENT_KINDS_BY_OPERATION: Record<string, readonly PmxAxIntentKind[]> = {
81
79
  'node.add': ['create'],
82
80
  'jsonrender.add': ['create'],
@@ -204,7 +202,7 @@ function autoGhostInput(name: string, rawInput: unknown, kind: string): Record<s
204
202
  }
205
203
  }
206
204
 
207
- export interface ExecuteOperationMeta {
205
+ export interface ExecuteOperationMeta extends OperationExecutionOptions {
208
206
  /**
209
207
  * Skip the synthesized auto-ghost: set by the workbench's own HTTP calls
210
208
  * (a human dragging a node is not agent activity) and by canvas.batch for
@@ -395,6 +393,8 @@ export async function executeOperation(
395
393
  rawInput: unknown,
396
394
  meta: ExecuteOperationMeta = {},
397
395
  ): Promise<unknown> {
396
+ // Check before attribution, board auto-open, ghosts, or any handler writes.
397
+ meta.signal?.throwIfAborted();
398
398
  // Attribution follows this call chain across awaits and nested operations.
399
399
  const inputAgentId = asRecord(rawInput).agentId;
400
400
  return withCurrentActor(
@@ -479,6 +479,22 @@ function needsOpenBoard(op: Operation): boolean {
479
479
  }
480
480
 
481
481
  async function executeOperationInner(name: string, rawInput: unknown, meta: ExecuteOperationMeta): Promise<unknown> {
482
+ meta.signal?.throwIfAborted();
483
+ const operationContext: OperationContext = {
484
+ emit: emitOperationEvent,
485
+ signal: meta.signal,
486
+ // Progress is observational. A disconnected observer must not erase the
487
+ // receipt of a completed write or strand a batch's final layout emit.
488
+ onProgress: meta.onProgress
489
+ ? async (progress) => {
490
+ try {
491
+ await meta.onProgress!(progress);
492
+ } catch (error) {
493
+ if (!meta.signal?.aborted) console.error(`[operation] progress callback failed for ${name}:`, error);
494
+ }
495
+ }
496
+ : undefined,
497
+ };
482
498
  const op = getOperation(name);
483
499
  const storedCreation =
484
500
  ['node.add', 'group.create', 'edge.add'].includes(name) &&
@@ -543,6 +559,7 @@ async function executeOperationInner(name: string, rawInput: unknown, meta: Exec
543
559
  }
544
560
  if (storedCreation) {
545
561
  const revision = canvasState.getContentRevision().revision;
562
+ meta.signal?.throwIfAborted();
546
563
  const result = await op.execute(rawInput, operationContext);
547
564
  const destination = asRecord(rawInput).destinationBoardId ?? canvasState.activeBoardId;
548
565
  if (destination === canvasState.activeBoardId || revision !== canvasState.getContentRevision().revision)
@@ -566,6 +583,7 @@ async function executeOperationInner(name: string, rawInput: unknown, meta: Exec
566
583
  intentId,
567
584
  allowedKinds!,
568
585
  async () => {
586
+ meta.signal?.throwIfAborted();
569
587
  const result = await op.execute(input, operationContext);
570
588
  if (op.mutates) {
571
589
  emitOperationEvent('canvas-layout-update', { layout: canvasState.getLayout() });
@@ -606,6 +624,7 @@ async function executeOperationInner(name: string, rawInput: unknown, meta: Exec
606
624
  if (ghost) {
607
625
  const ghostId = ghost.id;
608
626
  try {
627
+ meta.signal?.throwIfAborted();
609
628
  const result = await op.execute(rawInput, operationContext);
610
629
  if (op.mutates) emitOperationEvent('canvas-layout-update', { layout: canvasState.getLayout() });
611
630
  intentRegistry.clear(ghostId, { settledNodeId: settledNodeId(result, ghost) ?? undefined });
@@ -621,6 +640,7 @@ async function executeOperationInner(name: string, rawInput: unknown, meta: Exec
621
640
  const beforeBoard = canvasState.activeBoardId;
622
641
  const beforeRevision =
623
642
  name === 'board.create-from' || name === 'board.delete' ? canvasState.getContentRevision().revision : null;
643
+ meta.signal?.throwIfAborted();
624
644
  const result = await op.execute(rawInput, operationContext);
625
645
  // Library writes can invalidate relations on the open board without being
626
646
  // layout mutations themselves. Publish those clocks once, after the write.
@@ -29,7 +29,19 @@ export class OperationError extends Error {
29
29
  }
30
30
  }
31
31
 
32
- export interface OperationContext {
32
+ export interface OperationProgress {
33
+ progress: number;
34
+ total?: number;
35
+ message?: string;
36
+ }
37
+
38
+ /** Cooperative cancellation: completed writes are never rolled back. */
39
+ export interface OperationExecutionOptions {
40
+ signal?: AbortSignal;
41
+ onProgress?: (progress: OperationProgress) => void | Promise<void>;
42
+ }
43
+
44
+ export interface OperationContext extends OperationExecutionOptions {
33
45
  /** Emit a workbench SSE event (e.g. extra `canvas-layout-update` frames, focus, viewport). */
34
46
  emit(event: string, payload?: Record<string, unknown>): void;
35
47
  }
@@ -67,7 +79,9 @@ export interface OperationMcpToolHost {
67
79
  * Used by formatters that need a follow-up read (undo/redo history flags,
68
80
  * restore summary).
69
81
  */
70
- invoker(): { invoke(name: string, input: Record<string, unknown>): Promise<unknown> };
82
+ invoker(): {
83
+ invoke(name: string, input: Record<string, unknown>, options?: OperationExecutionOptions): Promise<unknown>;
84
+ };
71
85
  }
72
86
 
73
87
  export interface OperationMcpTool {
@@ -930,6 +930,15 @@ let workbenchEventSeq = 0;
930
930
  const workbenchEventRing: Array<{ seq: number; event: string; payload: PrimaryWorkbenchEventPayload }> = [];
931
931
  const workbenchPollWaiters = new Set<() => void>();
932
932
  let remoteEdgesSignature = '';
933
+ const workbenchEventListeners = new Set<(event: string) => void>();
934
+
935
+ /** In-process invalidation observers share the same events as daemon SSE clients. */
936
+ export function onWorkbenchEvent(listener: (event: string) => void): () => void {
937
+ workbenchEventListeners.add(listener);
938
+ return () => {
939
+ workbenchEventListeners.delete(listener);
940
+ };
941
+ }
933
942
 
934
943
  function broadcastWorkbenchEvent(event: string, payload: PrimaryWorkbenchEventPayload): void {
935
944
  let remoteEdgesChanged = false;
@@ -975,6 +984,7 @@ function broadcastWorkbenchEvent(event: string, payload: PrimaryWorkbenchEventPa
975
984
  syncCanvasBrowserOpenedFromSubscribers();
976
985
  }
977
986
  }
987
+ for (const listener of workbenchEventListeners) listener(event);
978
988
  if (remoteEdgesChanged) emitPrimaryWorkbenchEvent('boards-changed', boardsPayload());
979
989
  }
980
990
 
@@ -2483,16 +2493,19 @@ async function handleRender(req: Request): Promise<Response> {
2483
2493
  // The editor sends its draft through this same endpoint. Only changed/unsaved
2484
2494
  // text may resolve titles; persisted text must replay even unresolved bindings.
2485
2495
  const persisted = node?.type === 'markdown' && node.data.content === markdown;
2486
- const initializedRefs =
2487
- node?.type === 'markdown' && node.data.wikiLinks !== undefined && typeof node.data.content === 'string'
2488
- ? wikiReferences(node.data.content)
2489
- : [];
2490
- const refs = wikiReferences(markdown).filter(
2491
- (ref) => !initializedRefs.includes(ref) || previous.some((link) => link.ref === ref),
2492
- );
2493
- const needsResolution = !persisted && refs.some((ref) => !previous.some((link) => link.ref === ref && link.target));
2494
- const catalog = needsResolution ? canvasState.wikiCatalog() : [];
2495
- const links = persisted ? previous : refs.map((ref) => resolveWikiLinks(`[[${ref}]]`, previous, catalog)[0]);
2496
+ let links = previous;
2497
+ if (!persisted) {
2498
+ const initializedRefs =
2499
+ node?.type === 'markdown' && node.data.wikiLinks !== undefined && typeof node.data.content === 'string'
2500
+ ? wikiReferences(node.data.content)
2501
+ : [];
2502
+ const refs = wikiReferences(markdown).filter(
2503
+ (ref) => !initializedRefs.includes(ref) || previous.some((link) => link.ref === ref),
2504
+ );
2505
+ const needsResolution = refs.some((ref) => !previous.some((link) => link.ref === ref && link.target));
2506
+ const catalog = needsResolution ? canvasState.wikiCatalog() : [];
2507
+ links = refs.map((ref) => resolveWikiLinks(`[[${ref}]]`, previous, catalog)[0]);
2508
+ }
2496
2509
  const targets = new Map<string, ReturnType<typeof canvasState.readBoard>>();
2497
2510
  const html = renderWikiMarkdown(normalizeMarkdownExternalUrls(markdown), links, (target) => {
2498
2511
  if (!targets.has(target.boardId)) targets.set(target.boardId, canvasState.readBoard(target.boardId, false));
@@ -21,14 +21,22 @@ export interface TourStepResult {
21
21
  stop: TourStop;
22
22
  }
23
23
 
24
+ export interface TourState {
25
+ tour: Tour;
26
+ derived: boolean;
27
+ position: number | null;
28
+ }
29
+
24
30
  let cursor: { boardGeneration: number; tour: string; index: number } | null = null;
25
31
 
26
- export function currentTour(): Tour {
27
- return canvasState.getTour() ?? derivedTour(canvasState.getLayout().nodes);
32
+ export function currentTour(): TourState {
33
+ const saved = canvasState.getTour();
34
+ const tour = saved ?? derivedTour(canvasState.nodeGeometry());
35
+ return { tour, derived: !saved, position: tourPosition(tour) };
28
36
  }
29
37
 
30
38
  /** The stop the tour is on for the active board, or null when not touring. */
31
- export function tourPosition(tour: Tour = currentTour()): number | null {
39
+ function tourPosition(tour: Tour): number | null {
32
40
  if (cursor && (cursor.boardGeneration !== canvasState.boardGeneration || cursor.tour !== JSON.stringify(tour))) {
33
41
  cursor = null;
34
42
  }
@@ -37,9 +45,8 @@ export function tourPosition(tour: Tour = currentTour()): number | null {
37
45
 
38
46
  /** Move the shared cursor. `next`/`previous` clamp at the ends; an explicit index must exist. */
39
47
  export function goToTourStop(step: TourStep): TourStepResult {
40
- const tour = currentTour();
48
+ const { tour, position: at } = currentTour();
41
49
  const { stops } = tour;
42
- const at = tourPosition(tour);
43
50
  if (stops.length === 0) {
44
51
  throw new OperationError('This board has no tour stops. Save a tour or add groups.', 400);
45
52
  }
@@ -67,13 +74,15 @@ export function moveCamera(input: unknown): { stop: TourStop; viewport: Camera }
67
74
  throw new OperationError('Give exactly one of nodeId, rect {x,y,width,height} or viewport {x,y,scale}.', 400);
68
75
  }
69
76
  const stop = parsed.data;
70
- if ('nodeId' in stop.target && !canvasState.getNode(stop.target.nodeId)) {
71
- throw new OperationError(`Node "${stop.target.nodeId}" not found.`, 404);
77
+ const nodes = 'nodeId' in stop.target ? canvasState.nodeGeometry() : [];
78
+ const target = stop.target;
79
+ if ('nodeId' in target && !nodes.some((node) => node.id === target.nodeId)) {
80
+ throw new OperationError(`Node "${target.nodeId}" not found.`, 404);
72
81
  }
73
82
  const size = getClientViewportSize() ?? { width: 1440, height: 900 };
74
83
  let viewport: Camera;
75
84
  try {
76
- viewport = resolveStop(stop, canvasState.getLayout().nodes, size.width, size.height);
85
+ viewport = resolveStop(stop, nodes, size.width, size.height);
77
86
  } catch (error) {
78
87
  throw new OperationError(error instanceof Error ? error.message : String(error), 400);
79
88
  }
@@ -386,34 +386,37 @@ export function checkWebpageHop(originScope: AddressScope, hopScope: AddressScop
386
386
 
387
387
  export async function fetchWebpageSnapshot(
388
388
  inputUrl: string,
389
- options: { resolveHost?: ResolveHost; timeoutMs?: number } = {},
389
+ options: { resolveHost?: ResolveHost; timeoutMs?: number; signal?: AbortSignal } = {},
390
390
  ): Promise<WebpageSnapshot> {
391
+ options.signal?.throwIfAborted();
391
392
  const url = normalizeWebpageUrl(inputUrl);
392
393
  const controller = new AbortController();
394
+ const signal = options.signal ? AbortSignal.any([options.signal, controller.signal]) : controller.signal;
393
395
  const timeoutMs = options.timeoutMs ?? FETCH_TIMEOUT_MS;
394
396
  const timeout = setTimeout(() => controller.abort(), timeoutMs);
395
397
  const resolveHost = options.resolveHost ?? ((host) => lookup(host, { all: true }));
396
398
 
397
399
  try {
398
400
  // Redirects are followed by hand so every hop's host is checked before it is fetched.
399
- let resolved = await abortable(resolveHop(new URL(url), resolveHost), controller.signal);
401
+ let resolved = await abortable(resolveHop(new URL(url), resolveHost), signal);
400
402
  const originScope = resolved.scope;
401
403
  let hopUrl = url;
402
404
  let response: Response;
403
405
  for (let hop = 0; ; hop++) {
404
406
  checkWebpageHop(originScope, resolved.scope, hopUrl);
405
- response = await requestHop(new URL(hopUrl), resolved, controller.signal);
407
+ response = await requestHop(new URL(hopUrl), resolved, signal);
406
408
  const location = response.headers.get('location');
407
409
  if (response.status < 300 || response.status >= 400 || !location) break;
408
410
  await response.body?.cancel();
409
411
  if (hop === MAX_REDIRECTS) throw new WebpageFetchError(`Too many redirects while fetching ${url}.`);
410
412
  hopUrl = normalizeWebpageUrl(new URL(location, hopUrl).toString());
411
- resolved = await abortable(resolveHop(new URL(hopUrl), resolveHost), controller.signal);
413
+ resolved = await abortable(resolveHop(new URL(hopUrl), resolveHost), signal);
412
414
  }
413
415
 
414
416
  const contentType = response.headers.get('content-type');
415
417
  const responseUrl = hopUrl;
416
418
  const body = await readBoundedBody(response);
419
+ signal.throwIfAborted();
417
420
 
418
421
  if (!response.ok) {
419
422
  throw new WebpageFetchError(`Request failed with ${response.status} ${response.statusText}`.trim(), {
@@ -450,6 +453,8 @@ export async function fetchWebpageSnapshot(
450
453
  frameBlockedReason,
451
454
  };
452
455
  } catch (error) {
456
+ // Caller cancellation is not a fetch failure or our internal timeout.
457
+ options.signal?.throwIfAborted();
453
458
  if (error instanceof WebpageFetchError) throw error;
454
459
  if (error instanceof Error && error.name === 'AbortError') {
455
460
  throw new WebpageFetchError(`Timed out after ${timeoutMs}ms while fetching ${url}.`);