@flowdrop/flowdrop 2.16.0 → 2.18.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 (130) hide show
  1. package/CHANGELOG.md +95 -0
  2. package/README.md +6 -1
  3. package/dist/api/enhanced-client.d.ts +3 -1
  4. package/dist/api/enhanced-client.js +4 -2
  5. package/dist/commands/executor.js +9 -0
  6. package/dist/commands/storeIntegration.svelte.js +6 -0
  7. package/dist/commands/types.d.ts +8 -0
  8. package/dist/components/App.svelte +414 -105
  9. package/dist/components/App.svelte.d.ts +31 -0
  10. package/dist/components/CanvasToolbar.svelte +40 -3
  11. package/dist/components/CanvasToolbar.svelte.d.ts +5 -1
  12. package/dist/components/ConnectPortPicker.svelte +8 -4
  13. package/dist/components/DoctorMenu.svelte +208 -126
  14. package/dist/components/FlowDropZone.svelte +7 -1
  15. package/dist/components/FlowDropZone.svelte.d.ts +5 -0
  16. package/dist/components/ImpactConfirm.svelte +554 -0
  17. package/dist/components/ImpactConfirm.svelte.d.ts +22 -0
  18. package/dist/components/Input.svelte +8 -2
  19. package/dist/components/LockBanner.svelte +76 -0
  20. package/dist/components/LockBanner.svelte.d.ts +14 -0
  21. package/dist/components/LockFence.svelte +33 -0
  22. package/dist/components/LockFence.svelte.d.ts +19 -0
  23. package/dist/components/Navbar.svelte +77 -9
  24. package/dist/components/Navbar.svelte.d.ts +10 -0
  25. package/dist/components/NodeSidebar.svelte +36 -15
  26. package/dist/components/NodeSidebar.svelte.d.ts +2 -0
  27. package/dist/components/NodeSwapPicker.svelte +4 -14
  28. package/dist/components/RunBar.svelte +50 -3
  29. package/dist/components/RunBar.svelte.d.ts +5 -0
  30. package/dist/components/RunInputsDialog.svelte +198 -0
  31. package/dist/components/RunInputsDialog.svelte.d.ts +34 -0
  32. package/dist/components/Textarea.svelte +7 -1
  33. package/dist/components/WorkflowCompareDialog.svelte +177 -0
  34. package/dist/components/WorkflowCompareDialog.svelte.d.ts +10 -0
  35. package/dist/components/WorkflowEditor.svelte +120 -15
  36. package/dist/components/WorkflowEditor.svelte.d.ts +6 -0
  37. package/dist/components/WorkflowInterfaceEditor.svelte +17 -4
  38. package/dist/components/WorkflowInterfaceEntryCard.svelte +40 -7
  39. package/dist/components/WorkflowInterfaceEntryCard.svelte.d.ts +2 -0
  40. package/dist/components/WorkflowPlaygroundSettings.svelte +9 -1
  41. package/dist/components/form/FieldFactory.svelte +13 -6
  42. package/dist/components/form/FormArray.svelte +0 -1
  43. package/dist/components/form/FormArrayRows.svelte +4 -4
  44. package/dist/components/form/FormCodeEditor.svelte +18 -2
  45. package/dist/components/form/FormMarkdownEditor.svelte +22 -8
  46. package/dist/components/form/FormTemplateEditor.svelte +17 -1
  47. package/dist/components/form/readOnly.d.ts +13 -0
  48. package/dist/components/form/readOnly.js +18 -0
  49. package/dist/components/nodes/CaptionNode.svelte +1 -0
  50. package/dist/components/nodes/NodeCard.svelte +2 -2
  51. package/dist/components/primitives/Checkbox.svelte +5 -1
  52. package/dist/components/primitives/Select.svelte +6 -1
  53. package/dist/components/primitives/Switch.svelte +5 -1
  54. package/dist/components/toast/DismissibleToast.svelte +25 -6
  55. package/dist/components/toast/DismissibleToast.svelte.d.ts +3 -0
  56. package/dist/config/endpoints.d.ts +7 -0
  57. package/dist/config/endpoints.js +2 -1
  58. package/dist/editor/connectCandidates.d.ts +3 -0
  59. package/dist/editor/connectCandidates.js +14 -5
  60. package/dist/editor/index.d.ts +2 -1
  61. package/dist/editor/index.js +1 -1
  62. package/dist/helpers/workflowEditorHelper.d.ts +15 -0
  63. package/dist/helpers/workflowEditorHelper.js +9 -0
  64. package/dist/index.d.ts +2 -0
  65. package/dist/messages/defaults.d.ts +145 -0
  66. package/dist/messages/defaults.js +139 -1
  67. package/dist/openapi/v1/openapi.yaml +492 -0
  68. package/dist/registry/nodeComponentRegistry.d.ts +5 -0
  69. package/dist/schemas/v1/workflow.schema.json +2 -0
  70. package/dist/services/draftStorage.d.ts +24 -10
  71. package/dist/services/draftStorage.js +60 -35
  72. package/dist/services/globalSave.d.ts +45 -10
  73. package/dist/services/globalSave.js +296 -32
  74. package/dist/services/impactGate.d.ts +38 -0
  75. package/dist/services/impactGate.js +72 -0
  76. package/dist/services/impactService.d.ts +45 -0
  77. package/dist/services/impactService.js +157 -0
  78. package/dist/services/runsService.d.ts +9 -0
  79. package/dist/services/runsService.js +13 -0
  80. package/dist/services/toastQueue.d.ts +9 -0
  81. package/dist/services/toastService.d.ts +4 -0
  82. package/dist/services/toastService.js +9 -3
  83. package/dist/services/workflowLaunchService.d.ts +6 -0
  84. package/dist/services/workflowLaunchService.js +5 -1
  85. package/dist/settings/index.d.ts +2 -2
  86. package/dist/settings/index.js +1 -1
  87. package/dist/stores/doctorStore.svelte.d.ts +24 -1
  88. package/dist/stores/doctorStore.svelte.js +105 -2
  89. package/dist/stores/historyStore.svelte.d.ts +12 -2
  90. package/dist/stores/historyStore.svelte.js +25 -2
  91. package/dist/stores/instanceContainer.svelte.d.ts +23 -0
  92. package/dist/stores/instanceContainer.svelte.js +32 -2
  93. package/dist/stores/lockStore.svelte.d.ts +39 -0
  94. package/dist/stores/lockStore.svelte.js +109 -0
  95. package/dist/stores/runController.svelte.d.ts +2 -0
  96. package/dist/stores/runController.svelte.js +27 -11
  97. package/dist/stores/saveConflictStore.svelte.d.ts +62 -0
  98. package/dist/stores/saveConflictStore.svelte.js +169 -0
  99. package/dist/stores/workflowStore.svelte.d.ts +14 -4
  100. package/dist/stores/workflowStore.svelte.js +55 -18
  101. package/dist/styles/base.css +6 -0
  102. package/dist/styles/toast.css +10 -1
  103. package/dist/svelte-app.d.ts +33 -0
  104. package/dist/svelte-app.js +178 -22
  105. package/dist/types/doctor.d.ts +3 -1
  106. package/dist/types/events.d.ts +37 -0
  107. package/dist/types/events.js +2 -0
  108. package/dist/types/impact.d.ts +77 -0
  109. package/dist/types/impact.js +7 -0
  110. package/dist/types/lock.d.ts +35 -0
  111. package/dist/types/lock.js +13 -0
  112. package/dist/types/navbar.d.ts +6 -0
  113. package/dist/types/settings.d.ts +31 -0
  114. package/dist/types/settings.js +132 -0
  115. package/dist/utils/draftRestore.d.ts +27 -0
  116. package/dist/utils/draftRestore.js +36 -0
  117. package/dist/utils/interfaceTags.js +4 -1
  118. package/dist/utils/links.d.ts +29 -0
  119. package/dist/utils/links.js +63 -0
  120. package/dist/utils/nodeSearch.d.ts +10 -0
  121. package/dist/utils/nodeSearch.js +37 -0
  122. package/dist/utils/runOffer.d.ts +21 -0
  123. package/dist/utils/runOffer.js +13 -0
  124. package/dist/utils/workflowCompare.d.ts +35 -0
  125. package/dist/utils/workflowCompare.js +84 -0
  126. package/dist/utils/workflowInterface.d.ts +26 -1
  127. package/dist/utils/workflowInterface.js +91 -11
  128. package/dist/webmcp/runtime.js +16 -3
  129. package/dist/webmcp/types.d.ts +11 -1
  130. package/package.json +3 -2
@@ -168,7 +168,10 @@ export function saveDraft(workflow, storageKey, storage = activeAdapter) {
168
168
  metadata: {
169
169
  savedAt: new Date().toISOString(),
170
170
  workflowId: workflow.id,
171
- workflowName: workflow.name
171
+ workflowName: workflow.name,
172
+ ...(workflow.revision !== undefined && workflow.revision !== null
173
+ ? { baseRevision: String(workflow.revision) }
174
+ : {})
172
175
  }
173
176
  };
174
177
  storage.setItem(storageKey, JSON.stringify(draft));
@@ -284,6 +287,35 @@ export function clearAllDrafts(extraKeys = [], storage = activeAdapter) {
284
287
  return 0;
285
288
  }
286
289
  }
290
+ /**
291
+ * Fingerprint of everything a draft preserves, for change detection.
292
+ *
293
+ * Covers name, description, nodes, edges, the workflow interface and the
294
+ * Playground settings. Not cryptographic, just a stable string to compare.
295
+ *
296
+ * @param workflow - The workflow to fingerprint
297
+ * @returns A string that changes whenever a draft-relevant part changes
298
+ */
299
+ export function draftFingerprint(workflow) {
300
+ return JSON.stringify({
301
+ name: workflow.name,
302
+ description: workflow.description,
303
+ nodes: workflow.nodes.map((n) => ({
304
+ id: n.id,
305
+ position: n.position,
306
+ data: n.data
307
+ })),
308
+ edges: workflow.edges.map((e) => ({
309
+ id: e.id,
310
+ source: e.source,
311
+ target: e.target,
312
+ sourceHandle: e.sourceHandle,
313
+ targetHandle: e.targetHandle
314
+ })),
315
+ interface: workflow.interface,
316
+ playground: workflow.playground
317
+ });
318
+ }
287
319
  /**
288
320
  * Draft auto-save manager
289
321
  *
@@ -316,6 +348,8 @@ export class DraftAutoSaveManager {
316
348
  storage;
317
349
  /** Last saved workflow hash (for change detection) */
318
350
  lastSavedHash = null;
351
+ /** Open draft offers: while any is open, a clean tick keeps the stored draft. */
352
+ holds = new Set();
319
353
  /**
320
354
  * Create a new DraftAutoSaveManager
321
355
  *
@@ -351,6 +385,21 @@ export class DraftAutoSaveManager {
351
385
  clearInterval(this.intervalId);
352
386
  this.intervalId = null;
353
387
  }
388
+ this.holds.clear();
389
+ }
390
+ /**
391
+ * Keep the stored draft while an offer to restore it is open. A tick that
392
+ * finds the workflow clean would otherwise delete it behind the offer.
393
+ *
394
+ * @returns a function that ends the hold; Restore and Discard call it, and
395
+ * `stop()` ends every hold
396
+ */
397
+ holdDraft() {
398
+ const hold = Symbol('draft-offer');
399
+ this.holds.add(hold);
400
+ return () => {
401
+ this.holds.delete(hold);
402
+ };
354
403
  }
355
404
  /**
356
405
  * Save draft if there are unsaved changes
@@ -365,12 +414,15 @@ export class DraftAutoSaveManager {
365
414
  if (!workflow) {
366
415
  return false;
367
416
  }
368
- // Only save if dirty
417
+ // A saved workflow has no draft
369
418
  if (!this.isDirty()) {
419
+ if (this.holds.size === 0 && hasDraft(this.storageKey, this.storage)) {
420
+ deleteDraft(this.storageKey, this.storage);
421
+ }
370
422
  return false;
371
423
  }
372
424
  // Check if workflow has actually changed since last save
373
- const currentHash = this.hashWorkflow(workflow);
425
+ const currentHash = draftFingerprint(workflow);
374
426
  if (currentHash === this.lastSavedHash) {
375
427
  return false;
376
428
  }
@@ -397,7 +449,7 @@ export class DraftAutoSaveManager {
397
449
  }
398
450
  const saved = saveDraft(workflow, this.storageKey, this.storage);
399
451
  if (saved) {
400
- this.lastSavedHash = this.hashWorkflow(workflow);
452
+ this.lastSavedHash = draftFingerprint(workflow);
401
453
  }
402
454
  return saved;
403
455
  }
@@ -411,12 +463,14 @@ export class DraftAutoSaveManager {
411
463
  /**
412
464
  * Mark the current state as saved
413
465
  *
414
- * Updates the hash so the next saveIfDirty won't save unless there are new changes.
466
+ * Updates the hash so the next saveIfDirty won't save unless there are new
467
+ * changes, and removes the stored draft (a saved workflow has none).
415
468
  */
416
469
  markAsSaved() {
470
+ deleteDraft(this.storageKey, this.storage);
417
471
  const workflow = this.getWorkflow();
418
472
  if (workflow) {
419
- this.lastSavedHash = this.hashWorkflow(workflow);
473
+ this.lastSavedHash = draftFingerprint(workflow);
420
474
  }
421
475
  }
422
476
  /**
@@ -439,35 +493,6 @@ export class DraftAutoSaveManager {
439
493
  }
440
494
  this.storageKey = newKey;
441
495
  }
442
- /**
443
- * Simple hash function for change detection
444
- *
445
- * Not cryptographically secure, just for detecting changes.
446
- *
447
- * @param workflow - The workflow to hash
448
- * @returns A simple hash string
449
- */
450
- hashWorkflow(workflow) {
451
- // Use a simple stringification for change detection
452
- // We only need nodes, edges, name, and description for change detection
453
- const toHash = {
454
- name: workflow.name,
455
- description: workflow.description,
456
- nodes: workflow.nodes.map((n) => ({
457
- id: n.id,
458
- position: n.position,
459
- data: n.data
460
- })),
461
- edges: workflow.edges.map((e) => ({
462
- id: e.id,
463
- source: e.source,
464
- target: e.target,
465
- sourceHandle: e.sourceHandle,
466
- targetHandle: e.targetHandle
467
- }))
468
- };
469
- return JSON.stringify(toHash);
470
- }
471
496
  /**
472
497
  * Check if auto-save is currently running
473
498
  */
@@ -23,8 +23,10 @@ export interface GlobalSaveOptions {
23
23
  /**
24
24
  * Callback invoked after a successful save to clear the dirty state.
25
25
  * Pass workflowStore's markAsSaved here when calling from App.svelte.
26
+ * Receives the `editVersion` read when the saved snapshot was taken: pass it
27
+ * on, so an edit made while the save was in flight stays dirty.
26
28
  */
27
- onMarkAsSaved?: () => void;
29
+ onMarkAsSaved?: (version: number) => void;
28
30
  /**
29
31
  * Callback invoked after a successful save with the persisted workflow.
30
32
  * Receives the server-returned workflow (which may have a different ID than
@@ -37,7 +39,30 @@ export interface GlobalSaveOptions {
37
39
  * Defaults to the page-default instance when omitted.
38
40
  */
39
41
  instance?: FlowDropInstance;
42
+ /**
43
+ * Whether the save may ask the person a question (the impact dialog).
44
+ * Default `true`. Autosave passes `false`: a save that needs an answer is not
45
+ * made, returns `false` and the workflow stays dirty.
46
+ */
47
+ interactive?: boolean;
48
+ /**
49
+ * Called when the unsaved edits are gone for good: the editor is about to
50
+ * follow a saved copy to its editor URL (no `onSavedAsCopy` handler), or the
51
+ * person chose "Discard my changes" and the saved version was loaded. Use it
52
+ * to drop the stored draft, so a reload does not offer those edits again.
53
+ */
54
+ onDiscardDraft?: () => void;
55
+ /**
56
+ * Called when the backend refused the save because things use the workflow
57
+ * and the change breaks them (a `refused` impact check, or a save answered
58
+ * with `WORKFLOW_IN_USE_BREAKING`), after the person answered the dialog:
59
+ * `copied` (saved as a new workflow), `discarded` (the saved version was
60
+ * loaded) or `kept` (they kept editing). The save itself resolves `false`.
61
+ */
62
+ onRefused?: (outcome: SaveRefusalOutcome) => void;
40
63
  }
64
+ /** What the person did about a refused save. */
65
+ export type SaveRefusalOutcome = 'copied' | 'discarded' | 'kept';
41
66
  /**
42
67
  * Options accepted by globalExportWorkflow().
43
68
  */
@@ -56,18 +81,28 @@ export interface GlobalExportOptions {
56
81
  * This is the single source of truth for save logic. App.svelte delegates
57
82
  * to this function rather than reimplementing the steps.
58
83
  *
84
+ * Joining: a call made while a save of the same instance is in flight (double
85
+ * Cmd+S, autosave plus a manual save) returns that save's promise instead of
86
+ * starting another, which would send the superseded revision and be refused as
87
+ * a conflict. Edits made meanwhile stay dirty and go with the next save.
88
+ *
59
89
  * Steps performed:
90
+ * 0. Join a save already in flight, or drop the call while the impact question is open
60
91
  * 1. Flush pending form changes (blur active element + tick)
61
- * 2. Optionally call onBeforeSave — return false cancels the save
62
- * 3. Build the canonical Workflow object (preserving metadata, format, etc.)
63
- * 4. Persist via the instance's API client (fd.api.client)
64
- * 5. Update the store if the server assigned a new ID
65
- * 6. Call onMarkAsSaved / onAfterSave hooks
66
- * 7. Show toast notifications (respecting features.showToasts)
67
- */
68
- /**
92
+ * 2. Build the canonical Workflow object (preserving metadata, format, etc.)
93
+ * and note the edit version it was taken at
94
+ * 3. Ask the backend what the save changes for the workflow's users; ask the
95
+ * person when something breaks or changes (autosave does not ask: it waits
96
+ * for a person, and says so once)
97
+ * 4. Optionally call onBeforeSave — return false cancels the save
98
+ * 5. Persist via the instance's API client (fd.api.client)
99
+ * 6. Update the store if the server assigned a new ID
100
+ * 7. Call onMarkAsSaved (up to the version noted in step 2) / onAfterSave hooks
101
+ * 8. Show toast notifications (respecting features.showToasts)
102
+ *
69
103
  * Resolves `true` when the workflow was written, `false` when nothing was
70
- * saved because there was no workflow or `onBeforeSave` cancelled. A failed
104
+ * saved because there was no workflow, `onBeforeSave` cancelled or the person
105
+ * cancelled the impact question. A failed
71
106
  * request throws. Callers that relay the outcome (the WebMCP `save` tool)
72
107
  * must not read a quiet return as a save.
73
108
  */
@@ -15,8 +15,19 @@ import { DEFAULT_WORKFLOW_FORMAT } from '../types/index.js';
15
15
  import { stripExecutionInfo } from '../utils/nodeStatus.js';
16
16
  import { playgroundForSave } from '../utils/playgroundChat.js';
17
17
  import { buildSaveBody } from '../utils/workflowDraft.js';
18
- import { apiToasts, workflowToasts, dismissToast } from './toastService.js';
18
+ import { apiToasts, workflowToasts, dismissToast, showInfo, showSuccess } from './toastService.js';
19
+ import { logger } from '../utils/logger.js';
20
+ import { checkImpact, impactSupported, isSafeCopyUrl, parseImpactItems, saveAsCopy } from './impactService.js';
21
+ import { confirmImpact, impactPending } from './impactGate.js';
22
+ import { scopeSelector } from '../themes/scopedSkinCss.js';
19
23
  import { DEFAULT_FEATURES } from '../types/events.js';
24
+ function refusalOutcome(answer) {
25
+ return answer.action === 'copied'
26
+ ? 'copied'
27
+ : answer.action === 'discarded'
28
+ ? 'discarded'
29
+ : 'kept';
30
+ }
20
31
  // ---------------------------------------------------------------------------
21
32
  // Internal helpers
22
33
  // ---------------------------------------------------------------------------
@@ -44,6 +55,37 @@ function ensureApiConfiguration(fd) {
44
55
  });
45
56
  fd.api.configure(config);
46
57
  }
58
+ /** The error code of a save refused because things use the workflow and the change breaks them. */
59
+ const IN_USE_BREAKING = 'WORKFLOW_IN_USE_BREAKING';
60
+ /**
61
+ * The refused-state report for a save the backend refused with
62
+ * WORKFLOW_IN_USE_BREAKING, or `null` for any other error. What the refusal
63
+ * does not carry (the items, the copy URL) comes from the earlier check.
64
+ */
65
+ function inUseRefusal(error, earlier) {
66
+ const e = error;
67
+ if (e?.errorData?.error_code !== IN_USE_BREAKING)
68
+ return null;
69
+ const data = e.errorData;
70
+ const details = data.details;
71
+ const fromError = parseImpactItems(Array.isArray(details) ? details : (details?.items ?? data.items));
72
+ const copyUrl = data.copyUrl ?? data.copy_url;
73
+ return {
74
+ confirm: true,
75
+ interfaceLevel: earlier?.interfaceLevel ?? '',
76
+ interfaceBreaking: earlier?.interfaceBreaking ?? true,
77
+ items: fromError.length > 0 ? fromError : (earlier?.items ?? []),
78
+ refused: true,
79
+ refusedMessage: typeof data.error === 'string' && data.error ? data.error : null,
80
+ copyUrl: typeof copyUrl === 'string' && copyUrl ? copyUrl : (earlier?.copyUrl ?? null),
81
+ renames: []
82
+ };
83
+ }
84
+ /** The error when a save was refused because the workflow changed on the server meanwhile. */
85
+ function isSaveConflict(error) {
86
+ const e = error;
87
+ return e?.status === 409 && e.errorData?.error_code === 'CONFLICT' ? error : null;
88
+ }
47
89
  /**
48
90
  * Flush any pending form changes by blurring the active element.
49
91
  * This ensures focusout handlers (like ConfigForm's handleFormBlur)
@@ -61,34 +103,88 @@ async function flushPendingFormChanges() {
61
103
  // ---------------------------------------------------------------------------
62
104
  // Public API
63
105
  // ---------------------------------------------------------------------------
106
+ /** The save running now, per instance: a second call joins it. */
107
+ const inFlight = new WeakMap();
108
+ /** The editVersion at which a non-interactive save was last refused for needing an answer. */
109
+ const autosaveRefusedAt = new WeakMap();
110
+ /** Stable toast id so the autosave notice never stacks. */
111
+ function autosaveToastId(fd) {
112
+ return `flowdrop:autosave-waiting:${fd.skinScope ?? ''}`;
113
+ }
64
114
  /**
65
115
  * Save the current workflow to the backend.
66
116
  *
67
117
  * This is the single source of truth for save logic. App.svelte delegates
68
118
  * to this function rather than reimplementing the steps.
69
119
  *
120
+ * Joining: a call made while a save of the same instance is in flight (double
121
+ * Cmd+S, autosave plus a manual save) returns that save's promise instead of
122
+ * starting another, which would send the superseded revision and be refused as
123
+ * a conflict. Edits made meanwhile stay dirty and go with the next save.
124
+ *
70
125
  * Steps performed:
126
+ * 0. Join a save already in flight, or drop the call while the impact question is open
71
127
  * 1. Flush pending form changes (blur active element + tick)
72
- * 2. Optionally call onBeforeSave — return false cancels the save
73
- * 3. Build the canonical Workflow object (preserving metadata, format, etc.)
74
- * 4. Persist via the instance's API client (fd.api.client)
75
- * 5. Update the store if the server assigned a new ID
76
- * 6. Call onMarkAsSaved / onAfterSave hooks
77
- * 7. Show toast notifications (respecting features.showToasts)
78
- */
79
- /**
128
+ * 2. Build the canonical Workflow object (preserving metadata, format, etc.)
129
+ * and note the edit version it was taken at
130
+ * 3. Ask the backend what the save changes for the workflow's users; ask the
131
+ * person when something breaks or changes (autosave does not ask: it waits
132
+ * for a person, and says so once)
133
+ * 4. Optionally call onBeforeSave — return false cancels the save
134
+ * 5. Persist via the instance's API client (fd.api.client)
135
+ * 6. Update the store if the server assigned a new ID
136
+ * 7. Call onMarkAsSaved (up to the version noted in step 2) / onAfterSave hooks
137
+ * 8. Show toast notifications (respecting features.showToasts)
138
+ *
80
139
  * Resolves `true` when the workflow was written, `false` when nothing was
81
- * saved because there was no workflow or `onBeforeSave` cancelled. A failed
140
+ * saved because there was no workflow, `onBeforeSave` cancelled or the person
141
+ * cancelled the impact question. A failed
82
142
  * request throws. Callers that relay the outcome (the WebMCP `save` tool)
83
143
  * must not read a quiet return as a save.
84
144
  */
85
- export async function globalSaveWorkflow(options = {}) {
145
+ export function globalSaveWorkflow(options = {}) {
146
+ const fd = options.instance ?? getDefaultInstance();
147
+ const running = inFlight.get(fd);
148
+ if (running) {
149
+ // A person's save that lands on an autosave waits for it, then asks itself
150
+ // when the autosave did not write (it never asks the impact question).
151
+ if (options.interactive === false || running.interactive)
152
+ return running.promise;
153
+ return running.promise.then((saved) => saved && !fd.workflow.isDirty ? true : globalSaveWorkflow(options));
154
+ }
155
+ const promise = runSave(fd, options).finally(() => {
156
+ if (inFlight.get(fd)?.promise === promise)
157
+ inFlight.delete(fd);
158
+ });
159
+ inFlight.set(fd, { promise, interactive: options.interactive !== false });
160
+ return promise;
161
+ }
162
+ async function runSave(fd, options) {
86
163
  const { eventHandlers, onMarkAsSaved, onSaved } = options;
87
164
  const features = { ...DEFAULT_FEATURES, ...options.features };
88
- // Resolve the target instance; defaults to the page-default instance.
89
- const fd = options.instance ?? getDefaultInstance();
90
165
  const readWorkflow = () => fd.workflow.current;
91
- // Step 1 — Flush pending form changes (single location for this logic)
166
+ // What the impact check said, and whether the person asked renames to be followed.
167
+ let lastReport;
168
+ let followRenames;
169
+ let draftForCopy;
170
+ // The edit version the snapshot was taken at (set once the body is built).
171
+ let snapshotVersion;
172
+ // A save while the impact question is open is dropped, not queued: the open
173
+ // dialog is the one answer. Checked before the flush, which would blur its
174
+ // focused button.
175
+ if (impactPending(fd))
176
+ return false;
177
+ // A locked workflow is not saved: it cannot have changed, and the host asked for no edits.
178
+ // A person's save says so: a host's own Save button is not disabled by the lock.
179
+ if (fd.workflow.locked) {
180
+ if (options.interactive !== false && features.showToasts) {
181
+ showInfo(fd.messages().lock.saveRefused, {
182
+ id: `flowdrop:save-locked:${fd.skinScope ?? ''}`
183
+ });
184
+ }
185
+ return false;
186
+ }
187
+ // Flush pending form changes (single location for this logic)
92
188
  await flushPendingFormChanges();
93
189
  // Get current workflow from the instance's store after flush
94
190
  const currentWorkflow = readWorkflow();
@@ -98,18 +194,16 @@ export async function globalSaveWorkflow(options = {}) {
98
194
  }
99
195
  return false;
100
196
  }
101
- // Step 2 — Allow the parent to cancel the save
102
- if (eventHandlers?.onBeforeSave) {
103
- const shouldContinue = await eventHandlers.onBeforeSave(currentWorkflow);
104
- if (shouldContinue === false) {
105
- return false;
106
- }
107
- }
108
- const loadingToast = features.showToasts ? apiToasts.loading('Saving workflow') : null;
197
+ // Autosave already declined this very version: nothing changed, so asking
198
+ // the backend again would only repeat the refusal.
199
+ const interactive = options.interactive !== false;
200
+ if (!interactive && autosaveRefusedAt.get(fd) === fd.workflow.editVersion)
201
+ return false;
202
+ let loadingToast = null;
109
203
  try {
110
204
  // Ensure API configuration is initialised (needed when called outside App.svelte)
111
205
  ensureApiConfiguration(fd);
112
- // Step 3 — Build the canonical workflow object.
206
+ // Build the canonical workflow object.
113
207
  // Preserve all existing metadata fields (format, tags, etc.) so nothing is dropped.
114
208
  //
115
209
  // Determine new vs existing BEFORE the uuidv4() fallback: if the store already
@@ -118,14 +212,77 @@ export async function globalSaveWorkflow(options = {}) {
118
212
  const isExistingWorkflow = !!currentWorkflow.id;
119
213
  const workflowId = currentWorkflow.id || uuidv4();
120
214
  const finalWorkflow = buildSaveBody(currentWorkflow, workflowId);
121
- // Step 4 — Persist via this instance's API client.
215
+ // What this snapshot contains: only up to here may be marked saved.
216
+ let savedVersion = fd.workflow.editVersion;
217
+ draftForCopy = finalWorkflow;
218
+ snapshotVersion = savedVersion;
219
+ // Ask what this save changes for what uses the workflow. A backend
220
+ // without the route (or that does not know the workflow) leaves the save
221
+ // unasked; a failed check is shown and the person decides.
222
+ const apiConfig = fd.api.config;
223
+ if (isExistingWorkflow && apiConfig && impactSupported(apiConfig)) {
224
+ const result = await checkImpact(apiConfig, fd.api.authProvider, finalWorkflow.id, finalWorkflow);
225
+ // This instance's editor (a page may hold several), for the dialog's skin.
226
+ const host = (fd.skinScope ? document.querySelector(scopeSelector(fd.skinScope)) : null) ??
227
+ document.body;
228
+ if (result.status === 'ok')
229
+ lastReport = result.report;
230
+ const needsAnswer = (result.status === 'ok' &&
231
+ (result.report.confirm ||
232
+ result.report.refused === true ||
233
+ (result.report.renames ?? []).some((r) => r.places.length > 0))) ||
234
+ result.status === 'error';
235
+ if (needsAnswer) {
236
+ if (!interactive) {
237
+ // Say so once per version, then stay quiet until something changes.
238
+ if (autosaveRefusedAt.get(fd) !== savedVersion && features.showToasts) {
239
+ showInfo(fd.messages().autoSave.waiting, { id: autosaveToastId(fd) });
240
+ }
241
+ autosaveRefusedAt.set(fd, savedVersion);
242
+ return false;
243
+ }
244
+ const answer = await confirmImpact({
245
+ report: result.status === 'ok' ? result.report : undefined,
246
+ error: result.status === 'error' ? result.message : undefined,
247
+ host,
248
+ instance: fd,
249
+ messages: fd.messages,
250
+ ...refusalActions(fd, options, result.status === 'ok' ? result.report : undefined, finalWorkflow)
251
+ });
252
+ if (result.status === 'ok' && result.report.refused === true) {
253
+ options.onRefused?.(refusalOutcome(answer));
254
+ }
255
+ if (answer.action === 'copied') {
256
+ await afterSavedAsCopy(answer.copy, finalWorkflow, fd, options, features.showToasts);
257
+ return false;
258
+ }
259
+ if (answer.action !== 'save')
260
+ return false;
261
+ followRenames = answer.followRenames;
262
+ }
263
+ }
264
+ // Allow the parent to cancel the save (after the impact question, so a
265
+ // cancelled question leaves no onBeforeSave without an outcome hook).
266
+ if (eventHandlers?.onBeforeSave) {
267
+ const shouldContinue = await eventHandlers.onBeforeSave(currentWorkflow);
268
+ if (shouldContinue === false) {
269
+ return false;
270
+ }
271
+ }
272
+ loadingToast = features.showToasts ? apiToasts.loading('Saving workflow') : null;
273
+ // Persist via this instance's API client.
122
274
  // id-presence (computed above) decides update vs create — never UUID-regex.
123
275
  const apiClient = fd.api.client;
124
276
  const savedWorkflow = isExistingWorkflow
125
- ? await apiClient.updateWorkflow(finalWorkflow.id, finalWorkflow)
277
+ ? followRenames === undefined
278
+ ? await apiClient.updateWorkflow(finalWorkflow.id, finalWorkflow)
279
+ : await apiClient.updateWorkflow(finalWorkflow.id, finalWorkflow, { followRenames })
126
280
  : await apiClient.saveWorkflow(finalWorkflow);
127
- // Step 5 — If the server assigned a new ID, sync the store
281
+ // If the server assigned a new ID, sync the store
128
282
  if (savedWorkflow.id && savedWorkflow.id !== finalWorkflow.id) {
283
+ // The sync bumps editVersion itself; it counts as saved, but only when
284
+ // nothing else changed the workflow before it.
285
+ const cleanBeforeSync = fd.workflow.editVersion === savedVersion;
129
286
  fd.workflow.batchUpdate({
130
287
  nodes: finalWorkflow.nodes,
131
288
  edges: finalWorkflow.edges,
@@ -135,18 +292,22 @@ export async function globalSaveWorkflow(options = {}) {
135
292
  ...savedWorkflow.metadata
136
293
  }
137
294
  });
295
+ if (cleanBeforeSync)
296
+ savedVersion = fd.workflow.editVersion;
138
297
  }
139
- // Step 5b — The save minted a new revision (and may have refreshed what the
298
+ // The save minted a new revision (and may have refreshed what the
140
299
  // user may do); take the server's word so the next save sends the current
141
300
  // stamp rather than the one this save just superseded.
142
301
  fd.workflow.acknowledgeServer({ revision: savedWorkflow.revision, can: savedWorkflow.can });
143
- // Step 6a — Mark dirty state as clean
302
+ // Mark dirty state as clean
144
303
  if (onMarkAsSaved) {
145
- onMarkAsSaved();
304
+ onMarkAsSaved(savedVersion);
146
305
  }
147
306
  else {
148
- fd.workflow.markAsSaved();
307
+ fd.workflow.markAsSaved(savedVersion);
149
308
  }
309
+ autosaveRefusedAt.delete(fd);
310
+ dismissToast(autosaveToastId(fd));
150
311
  // A conversation open in the editor's Playground marks the new version.
151
312
  // Not awaited: it asks the server which version this save made.
152
313
  void fd.runs.noteWorkflowSaved();
@@ -160,7 +321,7 @@ export async function globalSaveWorkflow(options = {}) {
160
321
  if (features.showToasts) {
161
322
  workflowToasts.saved(finalWorkflow.name);
162
323
  }
163
- // Step 6b — After-save hook
324
+ // After-save hook
164
325
  if (eventHandlers?.onAfterSave) {
165
326
  await eventHandlers.onAfterSave(savedWorkflow);
166
327
  }
@@ -170,6 +331,36 @@ export async function globalSaveWorkflow(options = {}) {
170
331
  if (loadingToast)
171
332
  dismissToast(loadingToast);
172
333
  const errorObj = error instanceof Error ? error : new Error('Unknown error occurred');
334
+ // Things use the workflow and this change breaks them: say so, instead of
335
+ // a failure toast. The refusal is decided before anything reports a failed
336
+ // save, because it is an answer, not a failure, and is not rethrown.
337
+ const refusal = draftForCopy ? inUseRefusal(error, lastReport) : null;
338
+ if (refusal && draftForCopy) {
339
+ if (!interactive) {
340
+ // Autosave never asks: say so once per version, then stay quiet until
341
+ // something changes (the same as a check that needs an answer).
342
+ const version = snapshotVersion;
343
+ if (autosaveRefusedAt.get(fd) !== version && features.showToasts) {
344
+ showInfo(fd.messages().autoSave.waiting, { id: autosaveToastId(fd) });
345
+ }
346
+ autosaveRefusedAt.set(fd, version);
347
+ return false;
348
+ }
349
+ const host = (fd.skinScope ? document.querySelector(scopeSelector(fd.skinScope)) : null) ??
350
+ document.body;
351
+ const answer = await confirmImpact({
352
+ report: refusal,
353
+ host,
354
+ instance: fd,
355
+ messages: fd.messages,
356
+ ...refusalActions(fd, options, refusal, draftForCopy)
357
+ });
358
+ options.onRefused?.(refusalOutcome(answer));
359
+ if (answer.action === 'copied') {
360
+ await afterSavedAsCopy(answer.copy, draftForCopy, fd, options, features.showToasts);
361
+ }
362
+ return false;
363
+ }
173
364
  // onSaveError hook
174
365
  const currentWorkflowForError = readWorkflow();
175
366
  if (eventHandlers?.onSaveError && currentWorkflowForError) {
@@ -180,7 +371,19 @@ export async function globalSaveWorkflow(options = {}) {
180
371
  if (eventHandlers?.onApiError) {
181
372
  suppressToast = eventHandlers.onApiError(errorObj, 'save') === true;
182
373
  }
183
- if (features.showToasts && !suppressToast) {
374
+ // Someone else saved first: offer Keep mine / Load saved version / Compare
375
+ // instead of the generic error. Other 409s (a taken id) keep the normal toast.
376
+ // The choices are reported even when toasts are off, only the toast is not.
377
+ const conflict = isSaveConflict(error);
378
+ if (conflict) {
379
+ const details = conflict.errorData.details;
380
+ const current = details?.current;
381
+ fd.saveConflict.report({
382
+ currentRevision: current === undefined || current === null || current === '' ? null : String(current),
383
+ retry: () => globalSaveWorkflow(options)
384
+ }, features.showToasts && !suppressToast);
385
+ }
386
+ else if (features.showToasts && !suppressToast) {
184
387
  // The error object, not its message: an ApiError carries the server's
185
388
  // reasons as `details`, and the toast renders them as a list.
186
389
  // "Show problems" opens the navbar's problems popover, when there are
@@ -192,6 +395,67 @@ export async function globalSaveWorkflow(options = {}) {
192
395
  throw error;
193
396
  }
194
397
  }
398
+ /**
399
+ * What the refused state offers: "Save as a copy" when the backend named a
400
+ * safe `copyUrl`, "Discard my changes" when the draft has an id to load the
401
+ * saved version by. Discarding drops every unsaved edit and the undo history.
402
+ */
403
+ function refusalActions(fd, options, report, draft) {
404
+ const config = fd.api.config;
405
+ const copyUrl = report?.copyUrl;
406
+ return {
407
+ saveAsCopy: report?.refused && copyUrl && config && isSafeCopyUrl(config, copyUrl)
408
+ ? () => saveAsCopy(config, fd.api.authProvider, copyUrl, draft)
409
+ : undefined,
410
+ discard: report?.refused && draft.id
411
+ ? async () => {
412
+ const loaded = await fd.api.client.loadWorkflow(draft.id);
413
+ fd.workflow.initialize(loaded);
414
+ // Discarding resets the edit versions, so a refusal remembered
415
+ // for a version number no longer describes anything.
416
+ autosaveRefusedAt.delete(fd);
417
+ dismissToast(autosaveToastId(fd));
418
+ fd.doctor.schedule();
419
+ // The edits are gone: so is their stored draft. The host hears of the load as of any other.
420
+ options.onDiscardDraft?.();
421
+ options.eventHandlers?.onWorkflowLoad?.(loaded);
422
+ }
423
+ : undefined
424
+ };
425
+ }
426
+ /**
427
+ * The draft now lives on as a new workflow. The host's `onSavedAsCopy` takes
428
+ * over when it has one. Otherwise the editor follows the copy's editor URL,
429
+ * after clearing the unsaved state so the leave guard stays quiet and the
430
+ * original's draft is not offered again; with no URL it says the copy exists
431
+ * and stays as it is. A failure here never counts as a failed save: the copy
432
+ * exists.
433
+ */
434
+ async function afterSavedAsCopy(copy, draft, fd, options, showToasts) {
435
+ try {
436
+ const handler = options.eventHandlers?.onSavedAsCopy;
437
+ if (handler) {
438
+ await handler(copy, draft);
439
+ return;
440
+ }
441
+ if (copy.editorUrl && typeof window !== 'undefined') {
442
+ const version = fd.workflow.editVersion;
443
+ if (options.onMarkAsSaved)
444
+ options.onMarkAsSaved(version);
445
+ else
446
+ fd.workflow.markAsSaved(version);
447
+ options.onDiscardDraft?.();
448
+ window.location.assign(copy.editorUrl);
449
+ return;
450
+ }
451
+ if (showToasts) {
452
+ showSuccess(fd.messages().impact.refused.copied);
453
+ }
454
+ }
455
+ catch (error) {
456
+ logger.error('Handling the saved copy failed', error);
457
+ }
458
+ }
195
459
  /**
196
460
  * Export the current workflow as a downloadable JSON file.
197
461
  *