@flowdrop/flowdrop 2.0.0-beta.9 → 2.0.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 (74) hide show
  1. package/CHANGELOG.md +81 -0
  2. package/dist/chat/batchFeedback.js +1 -1
  3. package/dist/chat/commandClassifier.d.ts +11 -0
  4. package/dist/chat/commandClassifier.js +20 -0
  5. package/dist/chat/historyBuilder.d.ts +39 -0
  6. package/dist/chat/historyBuilder.js +82 -0
  7. package/dist/chat/index.d.ts +2 -1
  8. package/dist/chat/index.js +2 -1
  9. package/dist/chat/responseParser.js +16 -12
  10. package/dist/commands/parser.d.ts +12 -0
  11. package/dist/commands/parser.js +33 -6
  12. package/dist/commands/storeIntegration.svelte.js +11 -1
  13. package/dist/components/App.svelte +56 -17
  14. package/dist/components/ConfigForm.svelte +98 -23
  15. package/dist/components/ConfigForm.svelte.d.ts +21 -2
  16. package/dist/components/ConfigModal.svelte +9 -0
  17. package/dist/components/ConfigPanel.svelte +0 -1
  18. package/dist/components/SettingsPanel.svelte +9 -0
  19. package/dist/components/WorkflowEditor.svelte +5 -2
  20. package/dist/components/chat/AIChatPanel.svelte +42 -6
  21. package/dist/components/chat/CommandPreview.svelte +10 -1
  22. package/dist/components/form/FormPorts.svelte +21 -3
  23. package/dist/components/form/FormRangeField.svelte +5 -3
  24. package/dist/components/form/FormToggle.svelte +27 -2
  25. package/dist/components/form/FormToggle.svelte.d.ts +5 -0
  26. package/dist/components/playground/ChatInput.svelte +316 -26
  27. package/dist/components/playground/ChatInput.svelte.d.ts +31 -1
  28. package/dist/components/playground/ControlPanel.svelte +22 -0
  29. package/dist/components/playground/ControlPanel.svelte.d.ts +13 -0
  30. package/dist/components/playground/Playground.svelte +217 -4
  31. package/dist/components/surfaces/SurfaceOverlay.svelte +0 -1
  32. package/dist/config/endpoints.d.ts +48 -1
  33. package/dist/config/endpoints.js +18 -5
  34. package/dist/messages/defaults.d.ts +98 -0
  35. package/dist/messages/defaults.js +58 -1
  36. package/dist/playground/commands/args.d.ts +32 -0
  37. package/dist/playground/commands/args.js +50 -0
  38. package/dist/playground/commands/dispatch.d.ts +143 -0
  39. package/dist/playground/commands/dispatch.js +162 -0
  40. package/dist/playground/commands/index.d.ts +14 -0
  41. package/dist/playground/commands/index.js +10 -0
  42. package/dist/playground/commands/parser.d.ts +38 -0
  43. package/dist/playground/commands/parser.js +163 -0
  44. package/dist/playground/commands/registry.d.ts +42 -0
  45. package/dist/playground/commands/registry.js +122 -0
  46. package/dist/playground/commands/suggest.d.ts +37 -0
  47. package/dist/playground/commands/suggest.js +46 -0
  48. package/dist/playground/commands/types.d.ts +111 -0
  49. package/dist/playground/commands/types.js +15 -0
  50. package/dist/playground/index.d.ts +19 -0
  51. package/dist/playground/index.js +25 -0
  52. package/dist/playground/runAction.d.ts +48 -0
  53. package/dist/playground/runAction.js +31 -0
  54. package/dist/services/historyService.d.ts +30 -8
  55. package/dist/services/historyService.js +51 -15
  56. package/dist/services/pipelineSignalService.d.ts +97 -0
  57. package/dist/services/pipelineSignalService.js +94 -0
  58. package/dist/services/playgroundService.d.ts +12 -0
  59. package/dist/services/playgroundService.js +22 -0
  60. package/dist/services/workflowLaunchService.d.ts +74 -0
  61. package/dist/services/workflowLaunchService.js +74 -0
  62. package/dist/stores/historyStore.svelte.d.ts +17 -3
  63. package/dist/stores/historyStore.svelte.js +30 -3
  64. package/dist/stores/instanceContainer.svelte.js +5 -0
  65. package/dist/stores/workflowStore.svelte.d.ts +41 -4
  66. package/dist/stores/workflowStore.svelte.js +103 -13
  67. package/dist/types/chat.d.ts +5 -1
  68. package/dist/types/settings.d.ts +11 -0
  69. package/dist/types/settings.js +2 -1
  70. package/dist/utils/canvasSelection.d.ts +25 -0
  71. package/dist/utils/canvasSelection.js +37 -0
  72. package/dist/utils/nodeFormSchema.d.ts +51 -0
  73. package/dist/utils/nodeFormSchema.js +87 -0
  74. package/package.json +1 -1
package/CHANGELOG.md CHANGED
@@ -7,6 +7,87 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [2.0.0] - 2026-08-04
11
+
12
+ **FlowDrop 2.0 GA.** The `latest` dist-tag moves from 1.15.0 to 2.0.0; `npm install @flowdrop/flowdrop` now installs 2.x. Upgrading from 1.x is a breaking change — read [MIGRATION-2.0.md](./MIGRATION-2.0.md) first.
13
+
14
+ Code-identical to `2.0.0-beta.11` apart from a lint-hygiene fix (two `svelte-ignore` comments that no longer suppressed anything). The eleven betas published between 2026-06-07 and 2026-07-31 are the release notes for this version — each is kept below, and the full breaking-change list with per-item migration steps is in [2.0.0-beta.1](#200-beta1---2026-06-07).
15
+
16
+ ### What 2.0 is
17
+
18
+ - **The explicit-instance era.** Every mount creates an isolated `FlowDropInstance` — workflow, history, playground, interrupts, categories, API config, registries, port compatibility. Multiple editors coexist on one page without clobbering each other, and SSR no longer leaks state across requests. The ~95 module-level delegates that made a page-default singleton the de-facto API are gone; state comes from `mountFlowDropApp(...).instance` or `getInstance()`.
19
+ - **An API surface that tells the truth.** Props the components never read are deleted rather than silently ignored, documented options that did nothing (`height`/`width`, `workflow` on `mountWorkflowEditor`, `spellChecker`, `required`, `placeholder`) now work, the main entry is a minimal front door instead of an `export *`, and each name has exactly one home.
20
+ - **A playground you can operate.** Slash commands, pipeline signals (`pause`/`resume`/`cancel`), message-free run launches, session reset, µs-precision job durations, and full job-detail expansion — added across the beta line.
21
+ - **Authentication through providers.** `EndpointConfig.auth` is replaced by an `AuthProvider` (`StaticAuthProvider`, `CallbackAuthProvider`, `NoAuthProvider`), and draft storage is configurable (`draftStorage`) with an end-user opt-out.
22
+
23
+ ### Breaking Changes since 1.15.0
24
+
25
+ Summarized here; each item is documented in full under [2.0.0-beta.1](#200-beta1---2026-06-07) with its migration path.
26
+
27
+ - Module-level store APIs removed — instances are the API.
28
+ - API access, registries, and port compatibility are instance-scoped (`fd.api`, `fd.nodes`/`fd.fields`/`fd.formats`, `fd.portCompatibility`).
29
+ - `EndpointConfig.auth` removed — use an `AuthProvider`.
30
+ - The main entry exports only the bootstrap surface; barrels no longer re-export each other's names.
31
+ - `mode` prop replaces `readOnly` + `lockWorkflow`; `<App>` event handlers are flat `on*` props.
32
+ - v1.8-deprecated message props and the `ChatPanel` `showChatInput`/`showRunButton`/`showLogs` flags are removed.
33
+ - Workflow `metadata` is required and `metadata.version` is now `metadata.schemaVersion` (1.x JSON heals on load).
34
+ - localStorage keys are instance-scoped (existing drafts migrate on first read).
35
+ - `mountWorkflowEditor` drops `nodes`; `WorkflowEditor` drops six never-read props.
36
+
37
+ ### Fixed
38
+
39
+ - Two `svelte-ignore a11y_click_events_have_key_events` comments in `ConfigPanel` and `SurfaceOverlay` suppressed a warning that no longer fires (both backdrops handle `onkeydown`), tripping `svelte/no-unused-svelte-ignore`. Removed; no runtime change.
40
+
41
+ ## [2.0.0-beta.11] - 2026-07-31
42
+
43
+ Eleventh 2.0 beta, published under the npm `beta` dist-tag (`npm install @flowdrop/flowdrop@beta`). `latest` remains 1.15.0 until 2.0.0 GA. This release gives the playground an **operator control lane**: slash commands typed in the composer act on a session or on a running pipeline without entering the conversation as chat turns, and a run can now be started without fabricating a user message. It also stops the AI assistant re-arranging hand-made layouts unasked, tells it what actually happened to the commands it emitted, and fixes an empty config panel for node types that contribute no schema.
44
+
45
+ ### Added
46
+
47
+ - **Slash commands in the playground composer.** A leading `/` routes input to the control plane instead of the pipeline, so composer input stops meaning exactly one thing ("launch a run with this as input"). Ships `/help`, `/run`, `/new`, `/stop`, `/reset`, `/delete`, `/pause`, `/resume` and `/cancel`. Commands never become session messages — control traffic that entered the conversation would be replayed as chat input on the following turn — and their results render as transient composer feedback instead. Opt-in per surface via `enableCommands` (default `false`), because the lane is only safe where the send handler actually dispatches commands: a surface that forwards input straight to a backend would post `/stop` as literal text. `//` escapes a literal leading slash, consuming exactly one so the rule composes, and an unrecognised command reports itself as unknown with distance-1 suggestions rather than being forwarded as a message — a typo must not launch a run with `/stpo` as its input.
48
+ - **Pipeline signals — `pause`, `resume`, `cancel`.** Signals travel _into_ a running pipeline, the opposite direction from interrupts, which a node raises and awaits. Acceptance is not application: backends observe signals cooperatively between steps, so the in-flight step always finishes first and the new `PipelineSignalService` reports `accepted` rather than claiming the run is paused, leaving the status poll to report what actually happened. Refusals ("the run already finished", "not paused", "already pending") come back as typed results rather than thrown errors, since they are outcomes to render. New `signals` endpoint block, with its own group-level `baseUrl`.
49
+ - **Starting a run without posting a message.** New `WorkflowLaunchService` and a `workflows.run` endpoint. Sending a message to start a run fabricates a user turn that is indistinguishable downstream from something the user actually typed; hosts that wire `onRunWorkflow` get a RUN button and a `/run` command that launch instead. `/run --key=value` passes named inputs. A rejected launch distinguishes bad inputs (the caller's to fix) from an invalid workflow (an authoring problem), surfacing the backend's own per-field locators.
50
+ - **Command autocomplete palette.** Typing `/` offers the commands available against the current configuration, reusing the editor console's listbox so both surfaces look and behave alike. Completes command _names_ only — argument values would mean guessing a workflow's declared launch inputs, which live server-side, and offering inputs the backend then rejects.
51
+ - **Optional session reset endpoint.** `playground.resetSession` plus `PlaygroundService.resetSession()`, for returning a stuck session to idle.
52
+ - **`behavior.chatAllowLayoutChanges` (default `true`).** When off, `AIChatPanel` skips layout commands rather than executing them. See the layout fix below; the default preserves existing behaviour.
53
+ - **`hideLabel` on `FormToggle`.** Keeps the state text as the switch's accessible name without rendering it. Defaults to `false`, so every other toggle is unchanged.
54
+
55
+ Commands are available **only where their endpoint is configured** — a host pointed at a backend without session reset gets no `/reset`, rather than a command that 404s. Commands bind to endpoint _keys_, never to paths or to any one backend's vocabulary, so this works against any API implementing the shape.
56
+
57
+ ### Fixed
58
+
59
+ - **The assistant re-arranged hand-made layouts unasked (#36).** Auto-beautify re-positions every node, so an unrequested `layout auto` / `layout beautify` destroyed a hand-crafted layout. The root cause was the prompt rather than the executor: the DSL prompt docs told the assistant to auto-arrange after building and to always end with `canvas fitview`. Both mandates are gone, layout commands are marked user-requested-only and must be emitted alone so they can be undone independently. Since the library cannot control how a remote backend renders those prompts, `chatAllowLayoutChanges` adds a local enforcement point.
60
+ - **Triple-quoted blocks swallowed every later command (#35).** The response _extractor_ only closed a `"""` block when a line was exactly `"""`; an assistant that put the closer at the end of a content line left the buffer open, collapsing 7 commands to 2 and consuming the closing fence and trailing prose. Both the extractor and the parser now track delimiter _parity_ (escaped `\"""` excluded), so a closer is valid inline or on its own line.
61
+ - **The assistant was never told what happened to its commands (#35).** `getHistory()` sent only the explanation, and approve/dismiss outcomes lived purely in UI state — which is what drove the duplicate-node loop on "try again". History now carries the raw response plus a per-command outcome report (APPLIED / FAILED / SKIPPED / DISMISSED / NOT APPLIED YET), read at send time so it is always current.
62
+ - **Node-level settings vanished for node types with no config schema (#34).** `ConfigForm` rendered its whole form inside one `{:else if configSchema}` branch, so a node whose type contributes no schema fell through to "No configuration options available" — taking the node-level settings the editor owns (port order and exposure) down with it. A reserved `ports` field is now composed into the node's effective schema, so a schema-less node with ports simply has a schema. No-op when a backend already serves a `ports` property, when there is no node, or when the node has no ports to configure. Nothing is persisted on panel open.
63
+ - **Port drags started a text selection in Safari (#37).** Dragging from a port handle text-selected content outside the canvas. xyflow sets `user-select: none`, but WebKit still _begins_ a selection drag from a mousedown on unselectable content, anchoring at the nearest selectable text; node and pane drags call `preventDefault()`, xyflow's `Handle` does not. A capture-phase `mousedown` on the canvas wrapper now suppresses the gesture for primary-button presses inside `.svelte-flow__handle` and re-applies the focus the default action would have moved.
64
+
65
+ ### Changed
66
+
67
+ - **`CommandExecutionStatus` gains `'skipped'`.** A widened union: consumers switching exhaustively on it will need to handle the new member. A skip is a non-failure, so the rest of a batch still applies and no retry feedback is generated.
68
+ - **Port rows in the ports widget are more compact.** The written "Exposed"/"Hidden" label next to each switch reserved a label column and let long port names widen the row. The switch alone now carries the state; a hidden row's name and type badge are dimmed to stay legible, and both ellipsize with `title` attributes preserving the full text.
69
+ - **`buildEndpointUrl` accepts a base-URL override**, so a group of endpoints can sit under a different prefix from the rest of the config. Additive — existing three-argument calls are unchanged.
70
+
71
+ ### Internal
72
+
73
+ - The range field's one-time step inference reads its initial value inside `untrack()`, making the read-once intent explicit and clearing a `state_referenced_locally` warning. No behaviour change.
74
+ - Restored the missing `## [2.0.0-beta.9]` heading below: that release's summary and its "Fixed" section had been absorbed into beta.10's section since the beta.10 release commit.
75
+
76
+ ## [2.0.0-beta.10] - 2026-07-22
77
+
78
+ Tenth 2.0 beta, published under the npm `beta` dist-tag (`npm install @flowdrop/flowdrop@beta`). `latest` remains 1.15.0 until 2.0.0 GA. This release reworks how node-config edits are committed and how the undo stack records state, fixing two editor bugs (a Safari save failure and a multi-step undo that reverted more than one edit) and the freeze that the prior on-blur commit was working around. It also re-establishes the editor font on the standalone `ConfigModal` export.
79
+
80
+ ### Fixed
81
+
82
+ - **Safari dropped config edits toggled with a checkbox or select (#38).** Node config committed only on the config form's `focusout`, but WebKit doesn't focus checkboxes/selects on click — so toggling one and clicking Save never fired `focusout` and the edit was lost. Node config now commits **live** per change (no focus dependency), making the bug structurally impossible. Workflow settings keep the blur-commit path but retain an immediate commit for discrete controls, so they stay correct on Safari too.
83
+ - **A single undo reverted more than one edit (#39).** The undo stack stored the _pre-change_ state of each mutation, so after two or more sequential edits a single undo skipped a step (reverting two edits at once) and redo could not reconstruct the intermediate state. The stack now stores **post-change** snapshots — the stack top is the current committed state — so one undo == one edit. `WorkflowStore` mutations (`addNode`/`removeNode`/`addEdge`/`removeEdge`/`updateNode`/`batchUpdate`/`swapNode`) push after mutating, and config-edit transactions commit their final state.
84
+ - **The editor no longer freezes while typing in a config field.** The old on-blur commit was itself a workaround for committing on every change deep-cloning the whole workflow onto the undo stack, pushing a per-keystroke undo entry, firing `onWorkflowChange`, and recomputing edge geometry — all per keystroke. A field-editing session now applies each change cheaply inside a lazily-opened history transaction and coalesces into a single undo step; the workflow event fires and edges refresh once per session, on finalize.
85
+ - **Standalone `ConfigModal` inherited the host page's font.** `ConfigModal` (exported via `@flowdrop/flowdrop/editor`) is mounted standalone by embedders on bare host pages, so its `font-family: inherit` text fell back to the host theme font (e.g. serif on Drupal) instead of the FlowDrop sans. It now declares its own `font-family` on the modal root, mirroring the `SurfaceOverlay` / `ConfigPanel` fix from beta.9.
86
+
87
+ ### Changed
88
+
89
+ - **History commits now require the final state, and undo/redo finalize any open edit first.** Hardening follow-up to the #39 fix: `commitTransaction(finalWorkflow)` is now required (the pre-change `?? transactionSnapshot` fallback that could silently reintroduce the off-by-one is gone). The service no longer guesses at the live state to auto-commit a dangling transaction inside `undo()`/`redo()`; instead the state owners finalize first (a `HistoryStore` before-navigate hook wired to `finalizeNodeConfig()`, and command-dispatch undo/redo), and if the service still finds an open transaction it abandons it with a warning rather than committing wrong state. New shared `clearTransaction()` internally.
90
+
10
91
  ## [2.0.0-beta.9] - 2026-07-12
11
92
 
12
93
  Ninth 2.0 beta, published under the npm `beta` dist-tag (`npm install @flowdrop/flowdrop@beta`). `latest` remains 1.15.0 until 2.0.0 GA. A follow-up fix to the relocatable surfaces shipped in beta.8: config surfaces hosted in the modal placement (and the config panel's pop-out) now keep the editor's font instead of falling back to the host page's default.
@@ -39,7 +39,7 @@ export function buildRetryFeedback(outcome) {
39
39
  const preview = pe.raw.includes('\n') ? `${firstLine} …` : firstLine;
40
40
  lines.push(` • ${preview}\n reason: ${pe.error}`);
41
41
  }
42
- lines.push('\nNote: multiline values must close with """ on its own line.');
42
+ lines.push('\nNote: a multiline value must be closed by a matching """ (on its own line or at the end of the last content line). Escape a literal triple-quote inside the value as \\""".');
43
43
  }
44
44
  if (rolledBack) {
45
45
  lines.push('\nPlease re-send the full corrected batch to achieve the original goal.');
@@ -17,3 +17,14 @@
17
17
  * @returns true if the command modifies workflow state, false if read-only
18
18
  */
19
19
  export declare function isMutatingCommand(commandType: string): boolean;
20
+ /**
21
+ * Determine whether a DSL command type re-arranges existing node positions.
22
+ *
23
+ * Used by the AI panel to honour the `chatAllowLayoutChanges` behaviour setting:
24
+ * when layout changes are disallowed, these commands are skipped instead of
25
+ * executed so a hand-crafted layout survives an assistant batch (issue #36).
26
+ *
27
+ * @param commandType - The command type string (e.g., "beautify_layout")
28
+ * @returns true if the command repositions existing nodes
29
+ */
30
+ export declare function isLayoutCommand(commandType: string): boolean;
@@ -28,3 +28,23 @@ const READ_ONLY_COMMANDS = new Set([
28
28
  export function isMutatingCommand(commandType) {
29
29
  return !READ_ONLY_COMMANDS.has(commandType);
30
30
  }
31
+ /**
32
+ * Commands that rewrite the position of *existing* nodes.
33
+ *
34
+ * Viewport commands (`canvas fitview`, zoom, pan) are deliberately absent —
35
+ * they only move the camera and leave the stored arrangement intact.
36
+ */
37
+ const LAYOUT_COMMANDS = new Set(['auto_layout', 'beautify_layout']);
38
+ /**
39
+ * Determine whether a DSL command type re-arranges existing node positions.
40
+ *
41
+ * Used by the AI panel to honour the `chatAllowLayoutChanges` behaviour setting:
42
+ * when layout changes are disallowed, these commands are skipped instead of
43
+ * executed so a hand-crafted layout survives an assistant batch (issue #36).
44
+ *
45
+ * @param commandType - The command type string (e.g., "beautify_layout")
46
+ * @returns true if the command repositions existing nodes
47
+ */
48
+ export function isLayoutCommand(commandType) {
49
+ return LAYOUT_COMMANDS.has(commandType);
50
+ }
@@ -0,0 +1,39 @@
1
+ /**
2
+ * Conversation history builder for the AI Assistant.
3
+ *
4
+ * The panel's chat log is tuned for humans: the assistant bubble shows only the
5
+ * explanation (the ```flowdrop block is lifted out into the command preview),
6
+ * and whether the user applied or dismissed that preview lives in UI state.
7
+ * Sending that log verbatim to the backend hides two things from the assistant
8
+ * on the next turn — the commands it emitted, and what became of them. It then
9
+ * has to guess whether its previous change landed, and re-emits `add …` for
10
+ * nodes that already exist (issue #35).
11
+ *
12
+ * This module rebuilds the log into API history: the assistant's *raw* response
13
+ * plus an explicit outcome report for every command it emitted.
14
+ *
15
+ * @module chat/historyBuilder
16
+ */
17
+ import type { ChatHistoryMessage, ChatMessageRole, CommandPreviewItem } from '../types/chat.js';
18
+ /** One entry of the panel's chat log, as far as history building cares. */
19
+ export interface ChatLogEntry {
20
+ role: ChatMessageRole;
21
+ /** What the bubble displays — explanation only for assistant messages. */
22
+ content: string;
23
+ /** The unmodified LLM response, when it differs from {@link content}. */
24
+ rawContent?: string;
25
+ /** Commands extracted from this response, with their live status. */
26
+ commandPreview?: CommandPreviewItem[];
27
+ /** Results of read-only commands auto-executed for this response. */
28
+ readOnlyResults?: string[];
29
+ /** Set when the user dismissed the preview instead of applying it. */
30
+ commandsDismissed?: boolean;
31
+ }
32
+ /**
33
+ * Convert the panel's chat log into the history sent to the chat endpoint.
34
+ *
35
+ * Assistant entries carry their raw response (so the assistant sees the DSL it
36
+ * emitted) followed by an outcome report for each command in it. User entries
37
+ * pass through unchanged.
38
+ */
39
+ export declare function buildApiHistory(log: ChatLogEntry[]): ChatHistoryMessage[];
@@ -0,0 +1,82 @@
1
+ /**
2
+ * Conversation history builder for the AI Assistant.
3
+ *
4
+ * The panel's chat log is tuned for humans: the assistant bubble shows only the
5
+ * explanation (the ```flowdrop block is lifted out into the command preview),
6
+ * and whether the user applied or dismissed that preview lives in UI state.
7
+ * Sending that log verbatim to the backend hides two things from the assistant
8
+ * on the next turn — the commands it emitted, and what became of them. It then
9
+ * has to guess whether its previous change landed, and re-emits `add …` for
10
+ * nodes that already exist (issue #35).
11
+ *
12
+ * This module rebuilds the log into API history: the assistant's *raw* response
13
+ * plus an explicit outcome report for every command it emitted.
14
+ *
15
+ * @module chat/historyBuilder
16
+ */
17
+ /** Longest command echo in an outcome line before it is elided. */
18
+ const MAX_COMMAND_ECHO = 160;
19
+ /** Collapse a (possibly multiline) command to one readable line. */
20
+ function echoCommand(raw) {
21
+ const flat = raw.replace(/\s+/g, ' ').trim();
22
+ return flat.length > MAX_COMMAND_ECHO ? `${flat.slice(0, MAX_COMMAND_ECHO)} …` : flat;
23
+ }
24
+ /** Describe what happened to a single previewed command. */
25
+ function describeOutcome(item, dismissed) {
26
+ const echo = echoCommand(item.raw);
27
+ const reason = item.result ? ` — ${item.result}` : '';
28
+ switch (item.status) {
29
+ case 'success':
30
+ return `APPLIED: ${echo}`;
31
+ case 'error':
32
+ return `FAILED, not applied: ${echo}${reason}`;
33
+ case 'skipped':
34
+ return `SKIPPED, not applied: ${echo}${reason}`;
35
+ // 'pending' / 'executing' — the user never resolved the preview, or is
36
+ // resolving it right now. Either way nothing is committed yet.
37
+ default:
38
+ return dismissed
39
+ ? `DISMISSED by the user, not applied: ${echo}`
40
+ : `NOT APPLIED YET (awaiting the user's approval): ${echo}`;
41
+ }
42
+ }
43
+ /**
44
+ * Build the outcome report appended to an assistant message in API history.
45
+ *
46
+ * Returns an empty string when the message emitted no commands.
47
+ */
48
+ function buildOutcomeReport(entry) {
49
+ const sections = [];
50
+ if (entry.commandPreview && entry.commandPreview.length > 0) {
51
+ const dismissed = entry.commandsDismissed === true;
52
+ sections.push([
53
+ '[command outcomes — authoritative. The workflow state in this request already',
54
+ 'includes every APPLIED command; re-sending one would duplicate it. Only commands',
55
+ 'marked not applied still need to be sent.]'
56
+ ].join('\n'));
57
+ for (const item of entry.commandPreview) {
58
+ sections.push(describeOutcome(item, dismissed));
59
+ }
60
+ }
61
+ if (entry.readOnlyResults && entry.readOnlyResults.length > 0) {
62
+ sections.push('[read-only command results]');
63
+ sections.push(...entry.readOnlyResults);
64
+ }
65
+ return sections.length > 0 ? `\n\n${sections.join('\n')}` : '';
66
+ }
67
+ /**
68
+ * Convert the panel's chat log into the history sent to the chat endpoint.
69
+ *
70
+ * Assistant entries carry their raw response (so the assistant sees the DSL it
71
+ * emitted) followed by an outcome report for each command in it. User entries
72
+ * pass through unchanged.
73
+ */
74
+ export function buildApiHistory(log) {
75
+ return log.map((entry) => {
76
+ if (entry.role !== 'assistant') {
77
+ return { role: entry.role, content: entry.content };
78
+ }
79
+ const base = entry.rawContent ?? entry.content;
80
+ return { role: entry.role, content: `${base}${buildOutcomeReport(entry)}` };
81
+ });
82
+ }
@@ -23,5 +23,6 @@
23
23
  export { default as AIChatPanel } from '../components/chat/AIChatPanel.svelte';
24
24
  export { default as CommandPreview } from '../components/chat/CommandPreview.svelte';
25
25
  export { extractCommands } from './responseParser.js';
26
- export { isMutatingCommand } from './commandClassifier.js';
26
+ export { isMutatingCommand, isLayoutCommand } from './commandClassifier.js';
27
+ export { buildApiHistory, type ChatLogEntry } from './historyBuilder.js';
27
28
  export type { ChatMessageRole, ChatHistoryMessage, ChatRequest, ChatResponse, ExtractedCommands, CommandExecutionStatus, CommandPreviewItem } from '../types/chat.js';
@@ -29,4 +29,5 @@ export { default as CommandPreview } from '../components/chat/CommandPreview.sve
29
29
  // Chat Utilities
30
30
  // ============================================================================
31
31
  export { extractCommands } from './responseParser.js';
32
- export { isMutatingCommand } from './commandClassifier.js';
32
+ export { isMutatingCommand, isLayoutCommand } from './commandClassifier.js';
33
+ export { buildApiHistory } from './historyBuilder.js';
@@ -7,6 +7,7 @@
7
7
  *
8
8
  * @module chat/responseParser
9
9
  */
10
+ import { countTripleQuotes } from '../commands/parser.js';
10
11
  /**
11
12
  * Extract DSL commands from an LLM response string.
12
13
  *
@@ -25,22 +26,25 @@ export function extractCommands(llmResponse) {
25
26
  let isFlowdropBlock = false;
26
27
  let currentExplanation = [];
27
28
  let multilineBuffer = null;
29
+ // Running count of unescaped """ delimiters seen since the buffer opened.
30
+ // The block is closed when the count is even again (issue #35).
31
+ let multilineDelimiters = 0;
28
32
  for (const line of lines) {
29
33
  const trimmed = line.trim();
30
34
  // Handle multiline buffer FIRST — prevents code fences inside """...""" from
31
35
  // closing the outer flowdrop block or being misinterpreted as control lines.
32
36
  if (multilineBuffer !== null) {
33
- // Closing """ must be a standalone line (exact match after trimming).
34
- // This prevents content lines that end with """ from prematurely closing
35
- // the block (e.g. `Use Python """docstrings"""` or JSON ending with """).
36
- if (trimmed === '"""') {
37
- multilineBuffer.push(line);
37
+ multilineBuffer.push(line); // preserve raw indentation inside value
38
+ multilineDelimiters += countTripleQuotes(trimmed);
39
+ // Delimiters balance out — the value ended on this line. Parity (rather
40
+ // than "the line is exactly \"\"\"") lets the closer sit at the end of a
41
+ // content line, which is how LLMs actually write it
42
+ // (`set n.1:t """line one\nline two"""`), while a content line carrying a
43
+ // balanced pair (`Use Python """docstrings"""`) keeps the block open.
44
+ if (multilineDelimiters % 2 === 0) {
38
45
  commands.push(multilineBuffer.join('\n'));
39
46
  multilineBuffer = null;
40
47
  }
41
- else {
42
- multilineBuffer.push(line); // preserve raw indentation inside value
43
- }
44
48
  continue;
45
49
  }
46
50
  // Check for code block fence opening/closing
@@ -68,12 +72,12 @@ export function extractCommands(llmResponse) {
68
72
  if (trimmed === '' || trimmed.startsWith('#') || trimmed.startsWith('//')) {
69
73
  continue;
70
74
  }
71
- // Detect opening triple-quote without a closing one on the same line —
75
+ // An odd number of unescaped """ leaves a value open at end of line —
72
76
  // start accumulating a multiline value block
73
- const tripleOpen = trimmed.indexOf('"""');
74
- if (tripleOpen !== -1 && trimmed.indexOf('"""', tripleOpen + 3) === -1) {
75
- // Opening triple-quote with no closing on this line — start buffer
77
+ const delimiters = countTripleQuotes(trimmed);
78
+ if (delimiters % 2 === 1) {
76
79
  multilineBuffer = [trimmed];
80
+ multilineDelimiters = delimiters;
77
81
  continue;
78
82
  }
79
83
  commands.push(trimmed);
@@ -7,6 +7,18 @@
7
7
  * @module commands/parser
8
8
  */
9
9
  import type { ParseResult } from './types.js';
10
+ /**
11
+ * Count the `"""` delimiters in a string, ignoring escaped ones.
12
+ *
13
+ * `\"""` is the escape for a literal triple-quote inside a value (unescaped
14
+ * when the value is parsed), so it is content, not a delimiter. Occurrences are
15
+ * counted non-overlapping, left to right — an odd total means a value was left
16
+ * open.
17
+ *
18
+ * Shared with the chat response parser, which uses the same parity rule to
19
+ * decide where a multiline value ends.
20
+ */
21
+ export declare function countTripleQuotes(input: string): number;
10
22
  /**
11
23
  * Parse a command string into a typed Command object.
12
24
  *
@@ -6,6 +6,33 @@
6
6
  *
7
7
  * @module commands/parser
8
8
  */
9
+ /**
10
+ * Count the `"""` delimiters in a string, ignoring escaped ones.
11
+ *
12
+ * `\"""` is the escape for a literal triple-quote inside a value (unescaped
13
+ * when the value is parsed), so it is content, not a delimiter. Occurrences are
14
+ * counted non-overlapping, left to right — an odd total means a value was left
15
+ * open.
16
+ *
17
+ * Shared with the chat response parser, which uses the same parity rule to
18
+ * decide where a multiline value ends.
19
+ */
20
+ export function countTripleQuotes(input) {
21
+ let count = 0;
22
+ let i = 0;
23
+ while (i <= input.length - 3) {
24
+ if (input.startsWith('"""', i)) {
25
+ if (i === 0 || input[i - 1] !== '\\') {
26
+ count++;
27
+ }
28
+ i += 3;
29
+ }
30
+ else {
31
+ i++;
32
+ }
33
+ }
34
+ return count;
35
+ }
9
36
  /**
10
37
  * Parse a coordinate pair like "200,300" or "-50, 100"
11
38
  */
@@ -260,14 +287,14 @@ export function parseCommand(input) {
260
287
  return { ok: false, error: 'Empty command', input };
261
288
  }
262
289
  // Detect an unclosed multiline """ block — common when a low-quality LLM
263
- // omits the closing """ on its own line. The opener pattern is `"""\n`
264
- // (triple-quote followed by a newline), and a well-formed value must end
265
- // with `"""`. If we see the opener but not the closer, surface a clear
266
- // error instead of falling through to a generic "Invalid syntax".
267
- if (trimmed.includes('"""\n') && !trimmed.endsWith('"""')) {
290
+ // omits the closing """. Delimiters come in pairs (escaped `\"""` excluded),
291
+ // so an odd count means a value was left open, whether it was opened on its
292
+ // own line or inline after the key. Surface a clear error instead of falling
293
+ // through to a generic "Invalid syntax".
294
+ if (countTripleQuotes(trimmed) % 2 === 1) {
268
295
  return {
269
296
  ok: false,
270
- error: 'Unclosed """ block — missing closing """ on its own line',
297
+ error: 'Unclosed """ block — no matching closing """',
271
298
  input
272
299
  };
273
300
  }
@@ -32,6 +32,8 @@ export function createStoreCommandContext(nodeTypes, onUIAction, instance) {
32
32
  removeEdge: (edgeId) => actions.removeEdge(edgeId),
33
33
  batchUpdate: (updates) => actions.batchUpdate(updates),
34
34
  undo: () => {
35
+ // Flush a pending edit session into a committed step before undoing it.
36
+ actions.finalizeNodeConfig();
35
37
  const previousState = history.undo();
36
38
  if (previousState) {
37
39
  actions.restoreFromHistory(previousState);
@@ -40,6 +42,7 @@ export function createStoreCommandContext(nodeTypes, onUIAction, instance) {
40
42
  return false;
41
43
  },
42
44
  redo: () => {
45
+ actions.finalizeNodeConfig();
43
46
  const nextState = history.redo();
44
47
  if (nextState) {
45
48
  actions.restoreFromHistory(nextState);
@@ -53,7 +56,14 @@ export function createStoreCommandContext(nodeTypes, onUIAction, instance) {
53
56
  history.startTransaction(currentWorkflow, description);
54
57
  }
55
58
  },
56
- commitTransaction: () => history.commitTransaction(),
59
+ // Commit the transaction's post-change (current) state so one undo reverts
60
+ // the whole batch and redo restores its result (issue #39).
61
+ commitTransaction: () => {
62
+ const currentWorkflow = readWorkflow();
63
+ if (currentWorkflow) {
64
+ history.commitTransaction(currentWorkflow);
65
+ }
66
+ },
57
67
  cancelTransaction: () => {
58
68
  const snapshot = history.cancelTransaction();
59
69
  if (snapshot) {
@@ -5,7 +5,7 @@
5
5
  -->
6
6
 
7
7
  <script lang="ts">
8
- import { onMount, tick } from 'svelte';
8
+ import { onMount, tick, untrack } from 'svelte';
9
9
  import MainLayout from './layouts/MainLayout.svelte';
10
10
  import WorkflowEditor from './WorkflowEditor.svelte';
11
11
  import NodeSidebar from './NodeSidebar.svelte';
@@ -732,7 +732,43 @@
732
732
  * All save logic (blur flush, metadata construction, API call, event hooks,
733
733
  * toast notifications) lives in globalSave.ts — the single source of truth.
734
734
  */
735
+ // --- Node config live-edit sessions --------------------------------------
736
+ // Config fields commit live (per change) into the store via
737
+ // fd.workflow.updateNodeConfig(), which coalesces a field-editing session
738
+ // into a single undo step and defers the external change event. We finalize
739
+ // that session — commit the undo step, fire the deferred event, and refresh
740
+ // edge geometry ONCE — on blur, panel close, node switch, and save. Edges are
741
+ // refreshed only here, never per keystroke (that per-change recompute, plus a
742
+ // full-workflow history clone per keystroke, was the original editor freeze).
743
+ let pendingConfigNodeId: string | null = null;
744
+
745
+ function flushNodeConfigEdit(): void {
746
+ const nodeId = pendingConfigNodeId;
747
+ pendingConfigNodeId = null;
748
+ fd.workflow.finalizeNodeConfig();
749
+ if (nodeId) {
750
+ // Handle geometry can only have changed via config (e.g. gateway
751
+ // branches); refresh once now that the session is done.
752
+ void workflowEditorRef?.refreshEdgePositions(nodeId);
753
+ }
754
+ }
755
+
756
+ // Finalize the previous field session when the open config node changes
757
+ // (switching nodes, or closing the panel). Tracks the node id reactively;
758
+ // the flush itself is untracked so it can't feed back into the effect.
759
+ let lastConfigNodeId: string | null = null;
760
+ $effect(() => {
761
+ const id = activeConfig?.kind === 'node' ? activeConfig.node.id : null;
762
+ if (id !== lastConfigNodeId) {
763
+ lastConfigNodeId = id;
764
+ untrack(() => flushNodeConfigEdit());
765
+ }
766
+ });
767
+
735
768
  async function saveWorkflow(): Promise<void> {
769
+ // Commit any in-flight config edit so the save and its history are
770
+ // consistent (the value itself is already live in the store).
771
+ flushNodeConfigEdit();
736
772
  await globalSaveWorkflow({
737
773
  eventHandlers: { onBeforeSave, onAfterSave, onSaveError, onApiError },
738
774
  features,
@@ -1101,26 +1137,28 @@
1101
1137
  <ConfigForm
1102
1138
  {authProvider}
1103
1139
  {node}
1140
+ commitMode="live"
1104
1141
  workflowId={fd.workflow.current?.id}
1105
1142
  workflowNodes={fd.workflow.current?.nodes}
1106
1143
  workflowEdges={fd.workflow.current?.edges}
1107
- onChange={async (updatedConfig) => {
1108
- // Sync config changes to workflow immediately on field blur
1109
- if (node.id) {
1110
- const updatedData = {
1111
- ...node.data,
1112
- config: updatedConfig
1113
- };
1114
- const nodeUpdates: Record<string, unknown> = { data: updatedData };
1115
-
1116
- fd.workflow.updateNode(node.id, nodeUpdates);
1117
-
1118
- // Reflect config changes immediately (needed for nodeType changes)
1119
- workflowEditorRef?.updateNodeData(node.id, updatedData);
1120
-
1121
- // Refresh edge positions in case config changes affect handles
1122
- await workflowEditorRef?.refreshEdgePositions(node.id);
1144
+ onChange={(updatedConfig, meta) => {
1145
+ if (!node.id) return;
1146
+ const updatedData = { ...node.data, config: updatedConfig };
1147
+
1148
+ // Blur / end-of-session: commit the coalesced undo step + fire the
1149
+ // change event once, and refresh edges once.
1150
+ if (meta?.commit) {
1151
+ pendingConfigNodeId = node.id;
1152
+ flushNodeConfigEdit();
1153
+ return;
1123
1154
  }
1155
+
1156
+ // Live edit (every change): update the store cheaply — no history clone,
1157
+ // no external event; both are deferred to the session flush above. Also
1158
+ // reflect the change on the canvas immediately (e.g. nodeType changes).
1159
+ pendingConfigNodeId = node.id;
1160
+ fd.workflow.updateNodeConfig(node.id, { data: updatedData }, { fieldKey: meta?.fieldKey });
1161
+ workflowEditorRef?.updateNodeData(node.id, updatedData);
1124
1162
  }}
1125
1163
  />
1126
1164
  {/snippet}
@@ -1130,6 +1168,7 @@
1130
1168
  {authProvider}
1131
1169
  schema={workflowConfigSchema}
1132
1170
  values={workflowConfigValues}
1171
+ commitMode="blur"
1133
1172
  onChange={(config) => {
1134
1173
  // Sync workflow settings changes immediately on field blur
1135
1174
  const wf = fd.workflow.current;