@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
@@ -18,6 +18,13 @@ import { logger } from '../utils/logger.js';
18
18
  * a complete copy of the workflow state. This trades memory for simplicity
19
19
  * and reliability.
20
20
  *
21
+ * Snapshot model: the undo stack holds *committed* states, and its **top is the
22
+ * current live state**. `initialize()` seeds it with the starting state, and each
23
+ * mutation pushes the state *after* the change. One `undo()` moves the top back by
24
+ * exactly one committed change, and `redo()` restores the state that was undone.
25
+ * (Callers must push the post-change state — pushing pre-change snapshots makes a
26
+ * single undo skip a step once there are ≥2 sequential edits; see issue #39.)
27
+ *
21
28
  * @example
22
29
  * ```typescript
23
30
  * const historyService = new HistoryService();
@@ -25,7 +32,7 @@ import { logger } from '../utils/logger.js';
25
32
  * // Initialize with current workflow
26
33
  * historyService.initialize(workflow);
27
34
  *
28
- * // Push state before making changes
35
+ * // Push state AFTER making changes (the new committed state)
29
36
  * historyService.push(workflow, { description: "Add node" });
30
37
  *
31
38
  * // Undo/Redo
@@ -82,12 +89,13 @@ export class HistoryService {
82
89
  this.notifyChange();
83
90
  }
84
91
  /**
85
- * Push the current state to history before making changes
92
+ * Push a new committed state to history
86
93
  *
87
- * Call this BEFORE modifying the workflow to capture the "before" state.
94
+ * Call this AFTER modifying the workflow, with the resulting ("after") state:
95
+ * the stack top is the current live state, so one undo == one committed change.
88
96
  * The redo stack is cleared when new changes are pushed.
89
97
  *
90
- * @param workflow - The current workflow state (before changes)
98
+ * @param workflow - The workflow state after the change
91
99
  * @param options - Options for this history entry
92
100
  */
93
101
  push(workflow, options = {}) {
@@ -109,6 +117,15 @@ export class HistoryService {
109
117
  * @returns The previous workflow state, or null if cannot undo
110
118
  */
111
119
  undo() {
120
+ // A transaction is the store's to finalize (it holds the live state), and it
121
+ // must do so BEFORE calling undo — the facade and command dispatch both
122
+ // finalize first, and the editor's blur commits earlier still. If one is
123
+ // still open here, the caller violated that contract; abandon it (rather than
124
+ // guess a snapshot to commit) so the flag can't wedge future pushes, and warn.
125
+ if (this.inTransaction) {
126
+ logger.warn('HistoryService: undo() called with an open transaction; finalize the edit session first. Abandoning it.');
127
+ this.clearTransaction();
128
+ }
112
129
  // Need at least 2 entries to undo (initial + 1 change)
113
130
  if (this.undoStack.length <= 1) {
114
131
  return null;
@@ -131,6 +148,13 @@ export class HistoryService {
131
148
  * @returns The next workflow state, or null if cannot redo
132
149
  */
133
150
  redo() {
151
+ // Same contract as undo(): the caller must finalize any open edit session
152
+ // first. A dangling transaction here is a caller bug — abandon it and warn
153
+ // rather than committing a state we don't have.
154
+ if (this.inTransaction) {
155
+ logger.warn('HistoryService: redo() called with an open transaction; finalize the edit session first. Abandoning it.');
156
+ this.clearTransaction();
157
+ }
134
158
  if (this.redoStack.length === 0) {
135
159
  return null;
136
160
  }
@@ -147,9 +171,13 @@ export class HistoryService {
147
171
  * Start a transaction for grouping multiple changes
148
172
  *
149
173
  * All changes made during a transaction are combined into a single undo entry.
150
- * Useful for operations like "delete node" which also removes connected edges.
174
+ * Useful for operations like "delete node" which also removes connected edges,
175
+ * or coalescing a burst of live config edits into one step. While open, `push()`
176
+ * is suppressed; `commitTransaction()` records a single post-change entry.
151
177
  *
152
- * @param workflow - The current workflow state (before changes)
178
+ * @param workflow - The current workflow state at transaction start. Retained so
179
+ * {@link cancelTransaction} can restore it; the committed entry is the *final*
180
+ * state passed to {@link commitTransaction}, not this snapshot.
153
181
  * @param description - Description for the combined change
154
182
  */
155
183
  startTransaction(workflow, description) {
@@ -164,19 +192,23 @@ export class HistoryService {
164
192
  /**
165
193
  * Commit the current transaction
166
194
  *
167
- * Pushes the state captured at transaction start to the history stack.
195
+ * Records the transaction's *post-change* state as a single history entry, so
196
+ * one undo reverts the whole grouped operation and redo restores its result.
197
+ *
198
+ * The final state is required: the transaction's owner (the store) holds the
199
+ * live workflow and must supply it. There is deliberately no "commit whatever
200
+ * you captured at start" fallback — that would silently record a pre-change
201
+ * snapshot and reintroduce the off-by-one this model exists to prevent (#39).
202
+ *
203
+ * @param finalWorkflow - The workflow state after the grouped change.
168
204
  */
169
- commitTransaction() {
205
+ commitTransaction(finalWorkflow) {
170
206
  if (!this.inTransaction || !this.transactionSnapshot) {
171
207
  logger.warn('HistoryService: No transaction in progress, ignoring commitTransaction');
172
208
  return;
173
209
  }
174
- // Push the snapshot captured at transaction start
175
- this.pushInternal(this.transactionSnapshot, this.transactionDescription ?? undefined);
176
- // Clear transaction state
177
- this.inTransaction = false;
178
- this.transactionSnapshot = null;
179
- this.transactionDescription = null;
210
+ this.pushInternal(finalWorkflow, this.transactionDescription ?? undefined);
211
+ this.clearTransaction();
180
212
  }
181
213
  /**
182
214
  * Cancel the current transaction without committing
@@ -187,10 +219,14 @@ export class HistoryService {
187
219
  */
188
220
  cancelTransaction() {
189
221
  const snapshot = this.transactionSnapshot;
222
+ this.clearTransaction();
223
+ return snapshot;
224
+ }
225
+ /** Reset the in-progress transaction bookkeeping. */
226
+ clearTransaction() {
190
227
  this.inTransaction = false;
191
228
  this.transactionSnapshot = null;
192
229
  this.transactionDescription = null;
193
- return snapshot;
194
230
  }
195
231
  /**
196
232
  * Clear all history
@@ -0,0 +1,97 @@
1
+ /**
2
+ * Pipeline Signal Service
3
+ *
4
+ * Operator signals *into* a running pipeline — pause, resume, cancel.
5
+ *
6
+ * The opposite direction from `interruptService`: an interrupt is raised by a
7
+ * node inside a run and awaits an answer, while a signal is raised by an
8
+ * external party and acts on a run that never asked.
9
+ *
10
+ * ## Why this returns a result instead of throwing
11
+ *
12
+ * Every refusal here is an ordinary, expected outcome the composer must render
13
+ * differently — a run that already finished, a duplicate signal, a resume with
14
+ * nothing to resume. Turning those into exceptions would force every caller to
15
+ * re-parse HTTP status codes out of message strings. Only genuine transport
16
+ * failures reject.
17
+ *
18
+ * ## Accepted is not applied
19
+ *
20
+ * A successful pause or cancel returns `accepted`, never `applied`. Backends
21
+ * are expected to observe signals cooperatively — the reference implementation
22
+ * polls between job steps, so the in-flight step always finishes first. Callers
23
+ * must render "pause requested", not "paused", and let a status poll confirm.
24
+ *
25
+ * @module services/pipelineSignalService
26
+ */
27
+ import type { EndpointConfig } from '../config/endpoints.js';
28
+ import type { AuthProvider } from '../types/auth.js';
29
+ /**
30
+ * Signals a pipeline can be sent.
31
+ *
32
+ * Open by design: this is the set the reference backend implements today, but
33
+ * the direction is a general concept and other backends may define more. Widen
34
+ * with care — the client must never offer a signal nothing implements.
35
+ */
36
+ export type SignalType = 'pause' | 'resume' | 'cancel' | (string & {});
37
+ /** Why a signal was refused. Maps onto distinct, user-visible explanations. */
38
+ export type SignalRefusal =
39
+ /** The run already finished — nothing left to signal. */
40
+ 'terminal'
41
+ /** A signal is already pending on this pipeline; the backend rejects a second. */
42
+ | 'duplicate'
43
+ /** Resume with no pause outstanding. */
44
+ | 'not-paused'
45
+ /** No such pipeline. */
46
+ | 'not-found'
47
+ /** Caller lacks permission for this pipeline. */
48
+ | 'forbidden'
49
+ /** Refused for a reason this client does not model. */
50
+ | 'rejected';
51
+ export type SignalResult =
52
+ /**
53
+ * The backend accepted the signal. It has *not* necessarily taken effect —
54
+ * see the module docblock.
55
+ */
56
+ {
57
+ status: 'accepted';
58
+ signal: SignalType;
59
+ pipelineId: string;
60
+ } | {
61
+ status: 'refused';
62
+ reason: SignalRefusal;
63
+ message: string;
64
+ } | {
65
+ status: 'unsupported';
66
+ };
67
+ /** Options accepted by every signal. */
68
+ export interface SendSignalOptions {
69
+ /**
70
+ * Free-text audit note recorded against the signal.
71
+ *
72
+ * Note this is an audit field, not an execution-control one. In the reference
73
+ * backend a pipeline's *paused reason* is a separate, enumerated concept that
74
+ * governs auto-resume, and an operator pause deliberately carries none — the
75
+ * absence is what keeps a human-initiated pause from resuming itself. Sending
76
+ * a note here must not populate that field.
77
+ */
78
+ reason?: string;
79
+ }
80
+ declare class PipelineSignalService {
81
+ #private;
82
+ /**
83
+ * True when this configuration exposes a signal plane at all.
84
+ *
85
+ * Callers gate on this rather than assuming: a backend without signals is a
86
+ * supported configuration, not an error.
87
+ */
88
+ isSupported(config: EndpointConfig | null): boolean;
89
+ /** Pause a running pipeline. */
90
+ pause(config: EndpointConfig | null, pipelineId: string, options?: SendSignalOptions, authProvider?: AuthProvider): Promise<SignalResult>;
91
+ /** Resume a paused pipeline. */
92
+ resume(config: EndpointConfig | null, pipelineId: string, options?: SendSignalOptions, authProvider?: AuthProvider): Promise<SignalResult>;
93
+ /** Cancel a running pipeline. Terminal and durable — it cannot be undone. */
94
+ cancel(config: EndpointConfig | null, pipelineId: string, options?: SendSignalOptions, authProvider?: AuthProvider): Promise<SignalResult>;
95
+ }
96
+ export declare const pipelineSignalService: PipelineSignalService;
97
+ export { PipelineSignalService };
@@ -0,0 +1,94 @@
1
+ /**
2
+ * Pipeline Signal Service
3
+ *
4
+ * Operator signals *into* a running pipeline — pause, resume, cancel.
5
+ *
6
+ * The opposite direction from `interruptService`: an interrupt is raised by a
7
+ * node inside a run and awaits an answer, while a signal is raised by an
8
+ * external party and acts on a run that never asked.
9
+ *
10
+ * ## Why this returns a result instead of throwing
11
+ *
12
+ * Every refusal here is an ordinary, expected outcome the composer must render
13
+ * differently — a run that already finished, a duplicate signal, a resume with
14
+ * nothing to resume. Turning those into exceptions would force every caller to
15
+ * re-parse HTTP status codes out of message strings. Only genuine transport
16
+ * failures reject.
17
+ *
18
+ * ## Accepted is not applied
19
+ *
20
+ * A successful pause or cancel returns `accepted`, never `applied`. Backends
21
+ * are expected to observe signals cooperatively — the reference implementation
22
+ * polls between job steps, so the in-flight step always finishes first. Callers
23
+ * must render "pause requested", not "paused", and let a status poll confirm.
24
+ *
25
+ * @module services/pipelineSignalService
26
+ */
27
+ import { buildEndpointUrl } from '../config/endpoints.js';
28
+ import { authenticatedFetch } from '../utils/fetchWithAuth.js';
29
+ import { logger } from '../utils/logger.js';
30
+ /** Map a refusal HTTP status + payload onto a modelled reason. */
31
+ function classifyRefusal(status, message) {
32
+ if (status === 404)
33
+ return 'not-found';
34
+ if (status === 403 || status === 401)
35
+ return 'forbidden';
36
+ if (status === 409) {
37
+ const text = message.toLowerCase();
38
+ if (text.includes('terminal'))
39
+ return 'terminal';
40
+ if (text.includes('already pending') || text.includes('already'))
41
+ return 'duplicate';
42
+ if (text.includes('no active pause') || text.includes('pause'))
43
+ return 'not-paused';
44
+ return 'rejected';
45
+ }
46
+ return 'rejected';
47
+ }
48
+ class PipelineSignalService {
49
+ /**
50
+ * True when this configuration exposes a signal plane at all.
51
+ *
52
+ * Callers gate on this rather than assuming: a backend without signals is a
53
+ * supported configuration, not an error.
54
+ */
55
+ isSupported(config) {
56
+ return config?.endpoints?.signals != null;
57
+ }
58
+ /** Pause a running pipeline. */
59
+ async pause(config, pipelineId, options = {}, authProvider) {
60
+ return this.#send(config, 'pause', pipelineId, options, authProvider);
61
+ }
62
+ /** Resume a paused pipeline. */
63
+ async resume(config, pipelineId, options = {}, authProvider) {
64
+ return this.#send(config, 'resume', pipelineId, options, authProvider);
65
+ }
66
+ /** Cancel a running pipeline. Terminal and durable — it cannot be undone. */
67
+ async cancel(config, pipelineId, options = {}, authProvider) {
68
+ return this.#send(config, 'cancel', pipelineId, options, authProvider);
69
+ }
70
+ async #send(config, signal, pipelineId, options, authProvider) {
71
+ const signals = config?.endpoints?.signals;
72
+ if (!config || !signals)
73
+ return { status: 'unsupported' };
74
+ const url = buildEndpointUrl(config, signals[signal], { pipelineId }, signals.baseUrl);
75
+ const response = await authenticatedFetch(url, {
76
+ method: 'POST',
77
+ headers: { 'Content-Type': 'application/json' },
78
+ body: JSON.stringify(options.reason ? { reason: options.reason } : {})
79
+ }, { config, endpointKey: 'signals', authProvider });
80
+ if (response.ok) {
81
+ return { status: 'accepted', signal, pipelineId };
82
+ }
83
+ const payload = (await response.json().catch(() => ({})));
84
+ const message = payload.error ?? payload.message ?? `HTTP ${response.status}: ${response.statusText}`;
85
+ logger.warn(`Pipeline signal "${signal}" refused for ${pipelineId}:`, message);
86
+ return {
87
+ status: 'refused',
88
+ reason: classifyRefusal(response.status, message),
89
+ message
90
+ };
91
+ }
92
+ }
93
+ export const pipelineSignalService = new PipelineSignalService();
94
+ export { PipelineSignalService };
@@ -123,6 +123,18 @@ export declare class PlaygroundService {
123
123
  * @param sessionId - The session UUID
124
124
  */
125
125
  stopExecution(endpointConfig: EndpointConfig | null, sessionId: string, authProvider?: AuthProvider): Promise<void>;
126
+ /**
127
+ * Reset a stuck session to idle, cancelling pending messages and clearing
128
+ * interrupt state.
129
+ *
130
+ * The endpoint is optional in {@link EndpointConfig} — a backend that cannot
131
+ * reset omits it. Callers should check availability first (the slash-command
132
+ * registry does); calling without a configured endpoint throws rather than
133
+ * silently hitting a wrong URL.
134
+ *
135
+ * @param sessionId - The session UUID
136
+ */
137
+ resetSession(endpointConfig: EndpointConfig | null, sessionId: string, authProvider?: AuthProvider): Promise<void>;
126
138
  /**
127
139
  * Start polling for new messages
128
140
  *
@@ -243,6 +243,28 @@ export class PlaygroundService {
243
243
  method: 'POST'
244
244
  }, authProvider);
245
245
  }
246
+ /**
247
+ * Reset a stuck session to idle, cancelling pending messages and clearing
248
+ * interrupt state.
249
+ *
250
+ * The endpoint is optional in {@link EndpointConfig} — a backend that cannot
251
+ * reset omits it. Callers should check availability first (the slash-command
252
+ * registry does); calling without a configured endpoint throws rather than
253
+ * silently hitting a wrong URL.
254
+ *
255
+ * @param sessionId - The session UUID
256
+ */
257
+ async resetSession(endpointConfig, sessionId, authProvider) {
258
+ const config = this.getConfig(endpointConfig);
259
+ const endpoint = config.endpoints.playground.resetSession;
260
+ if (!endpoint) {
261
+ throw new Error('Session reset is not supported by this backend');
262
+ }
263
+ const url = buildEndpointUrl(config, endpoint, { sessionId });
264
+ await this.request(config, url, {
265
+ method: 'POST'
266
+ }, authProvider);
267
+ }
246
268
  // =========================================================================
247
269
  // Polling
248
270
  // =========================================================================
@@ -0,0 +1,74 @@
1
+ /**
2
+ * Workflow Launch Service
3
+ *
4
+ * Starts a workflow run with named inputs — the explicit verb for "run this",
5
+ * as opposed to posting a chat message and relying on a run starting as a side
6
+ * effect.
7
+ *
8
+ * Why this matters beyond tidiness: launching by message fabricates a user turn
9
+ * that enters the conversation and is fed back as input on the next turn. A
10
+ * launch has no message, so nothing is fabricated.
11
+ *
12
+ * Like {@link pipelineSignalService}, this returns a typed result rather than
13
+ * throwing — invalid inputs and an invalid stored workflow are expected
14
+ * outcomes with distinct, per-field presentation, not exceptional ones.
15
+ *
16
+ * @module services/workflowLaunchService
17
+ */
18
+ import type { EndpointConfig } from '../config/endpoints.js';
19
+ import type { AuthProvider } from '../types/auth.js';
20
+ /** A single per-input validation failure reported by the backend. */
21
+ export interface LaunchInputError {
22
+ /** Machine-readable error code. */
23
+ code: string;
24
+ /** Human-readable explanation. */
25
+ message: string;
26
+ /** Which input the error belongs to, when the backend can attribute it. */
27
+ locator?: string;
28
+ }
29
+ export type LaunchResult =
30
+ /** The run was created. `status` is the backend's own lifecycle value. */
31
+ {
32
+ status: 'launched';
33
+ pipelineId: string;
34
+ runStatus?: string;
35
+ queued?: boolean;
36
+ }
37
+ /** Inputs were refused — unknown key, wrong type, missing required. */
38
+ | {
39
+ status: 'invalid-input';
40
+ message: string;
41
+ }
42
+ /**
43
+ * The *stored workflow* is structurally invalid, with per-error locators.
44
+ * Distinct from bad inputs: nothing the caller passed is at fault.
45
+ */
46
+ | {
47
+ status: 'invalid-workflow';
48
+ message: string;
49
+ errors: LaunchInputError[];
50
+ } | {
51
+ status: 'failed';
52
+ message: string;
53
+ } | {
54
+ status: 'unsupported';
55
+ };
56
+ export interface LaunchOptions {
57
+ /** Named inputs, resolved server-side against the workflow's declared manifest. */
58
+ inputs?: Record<string, unknown>;
59
+ /** Attribute the run to a session, so its messages land in that conversation. */
60
+ sessionId?: string;
61
+ }
62
+ declare class WorkflowLaunchService {
63
+ /** True when this configuration exposes an explicit launch verb. */
64
+ isSupported(config: EndpointConfig | null): boolean;
65
+ /**
66
+ * Launch a workflow run.
67
+ *
68
+ * An empty `inputs` is meaningful and supported — it means "run with no
69
+ * inputs", which is a legitimate thing to want and is why this verb exists.
70
+ */
71
+ launch(config: EndpointConfig | null, workflowId: string, options?: LaunchOptions, authProvider?: AuthProvider): Promise<LaunchResult>;
72
+ }
73
+ export declare const workflowLaunchService: WorkflowLaunchService;
74
+ export { WorkflowLaunchService };
@@ -0,0 +1,74 @@
1
+ /**
2
+ * Workflow Launch Service
3
+ *
4
+ * Starts a workflow run with named inputs — the explicit verb for "run this",
5
+ * as opposed to posting a chat message and relying on a run starting as a side
6
+ * effect.
7
+ *
8
+ * Why this matters beyond tidiness: launching by message fabricates a user turn
9
+ * that enters the conversation and is fed back as input on the next turn. A
10
+ * launch has no message, so nothing is fabricated.
11
+ *
12
+ * Like {@link pipelineSignalService}, this returns a typed result rather than
13
+ * throwing — invalid inputs and an invalid stored workflow are expected
14
+ * outcomes with distinct, per-field presentation, not exceptional ones.
15
+ *
16
+ * @module services/workflowLaunchService
17
+ */
18
+ import { buildEndpointUrl } from '../config/endpoints.js';
19
+ import { authenticatedFetch } from '../utils/fetchWithAuth.js';
20
+ import { logger } from '../utils/logger.js';
21
+ class WorkflowLaunchService {
22
+ /** True when this configuration exposes an explicit launch verb. */
23
+ isSupported(config) {
24
+ return config?.endpoints?.workflows?.run != null;
25
+ }
26
+ /**
27
+ * Launch a workflow run.
28
+ *
29
+ * An empty `inputs` is meaningful and supported — it means "run with no
30
+ * inputs", which is a legitimate thing to want and is why this verb exists.
31
+ */
32
+ async launch(config, workflowId, options = {}, authProvider) {
33
+ const endpoint = config?.endpoints?.workflows?.run;
34
+ if (!config || !endpoint)
35
+ return { status: 'unsupported' };
36
+ const url = buildEndpointUrl(config, endpoint, { workflowId });
37
+ const body = {};
38
+ if (options.inputs && Object.keys(options.inputs).length > 0)
39
+ body.inputs = options.inputs;
40
+ if (options.sessionId)
41
+ body.sessionId = options.sessionId;
42
+ const response = await authenticatedFetch(url, {
43
+ method: 'POST',
44
+ headers: { 'Content-Type': 'application/json' },
45
+ body: JSON.stringify(body)
46
+ }, { config, endpointKey: 'workflows', authProvider });
47
+ const payload = (await response.json().catch(() => ({})));
48
+ if (response.ok) {
49
+ const pipelineId = payload.data?.pipelineId;
50
+ if (!pipelineId) {
51
+ return { status: 'failed', message: 'Launch succeeded but returned no pipeline id' };
52
+ }
53
+ return {
54
+ status: 'launched',
55
+ pipelineId,
56
+ runStatus: payload.data?.status,
57
+ queued: payload.data?.queued
58
+ };
59
+ }
60
+ const message = payload.error ?? payload.message ?? `HTTP ${response.status}: ${response.statusText}`;
61
+ logger.warn(`Workflow launch refused for ${workflowId}:`, message);
62
+ // 422 carries per-error locators for a structurally invalid stored
63
+ // definition — a different problem from the caller passing bad inputs.
64
+ if (response.status === 422) {
65
+ return { status: 'invalid-workflow', message, errors: payload.details ?? [] };
66
+ }
67
+ if (response.status === 400) {
68
+ return { status: 'invalid-input', message };
69
+ }
70
+ return { status: 'failed', message };
71
+ }
72
+ }
73
+ export const workflowLaunchService = new WorkflowLaunchService();
74
+ export { WorkflowLaunchService };
@@ -24,7 +24,7 @@ export interface HistoryStoreActions {
24
24
  undo: () => boolean;
25
25
  redo: () => boolean;
26
26
  startTransaction: (workflow: Workflow, description?: string) => void;
27
- commitTransaction: () => void;
27
+ commitTransaction: (finalWorkflow: Workflow) => void;
28
28
  cancelTransaction: () => void;
29
29
  clear: (currentWorkflow?: Workflow) => void;
30
30
  canUndo: () => boolean;
@@ -71,6 +71,16 @@ export declare class HistoryStore {
71
71
  * Use this to update the workflow store or other state management.
72
72
  */
73
73
  setOnRestoreCallback(callback: ((workflow: Workflow) => void) | null): void;
74
+ /**
75
+ * Set the callback run just before every undo/redo.
76
+ *
77
+ * Use this to finalize an in-progress edit session (e.g. the workflow store's
78
+ * `finalizeNodeConfig`) so it is committed as one history step *before* being
79
+ * undone. The history service intentionally does not commit dangling
80
+ * transactions itself — it has no access to the live state — so this hook is
81
+ * how the owner of that state flushes it first.
82
+ */
83
+ setBeforeNavigateCallback(callback: (() => void) | null): void;
74
84
  /**
75
85
  * Release the history service subscription.
76
86
  * Called by the owning instance's destroy(); safe to call repeatedly.
@@ -106,8 +116,12 @@ export declare class HistoryStore {
106
116
  * All changes during a transaction are combined into a single undo entry.
107
117
  */
108
118
  startTransaction(workflow: Workflow, description?: string): void;
109
- /** Commit the current transaction. */
110
- commitTransaction(): void;
119
+ /**
120
+ * Commit the current transaction with its final (post-change) state.
121
+ *
122
+ * @param finalWorkflow - The workflow state after the grouped change.
123
+ */
124
+ commitTransaction(finalWorkflow: Workflow): void;
111
125
  /** Cancel the current transaction without committing. */
112
126
  cancelTransaction(): void;
113
127
  /**
@@ -34,6 +34,11 @@ export class HistoryStore {
34
34
  * Invoked when undo/redo operations return a workflow.
35
35
  */
36
36
  #onRestore = null;
37
+ /**
38
+ * Callback run immediately before an undo/redo, to flush any pending edit
39
+ * session into a committed history step (see {@link setBeforeNavigateCallback}).
40
+ */
41
+ #onBeforeNavigate = null;
37
42
  /** Unsubscribe handle for the service subscription. */
38
43
  #unsubscribe;
39
44
  /** The underlying (non-reactive) history service. */
@@ -102,6 +107,18 @@ export class HistoryStore {
102
107
  setOnRestoreCallback(callback) {
103
108
  this.#onRestore = callback;
104
109
  }
110
+ /**
111
+ * Set the callback run just before every undo/redo.
112
+ *
113
+ * Use this to finalize an in-progress edit session (e.g. the workflow store's
114
+ * `finalizeNodeConfig`) so it is committed as one history step *before* being
115
+ * undone. The history service intentionally does not commit dangling
116
+ * transactions itself — it has no access to the live state — so this hook is
117
+ * how the owner of that state flushes it first.
118
+ */
119
+ setBeforeNavigateCallback(callback) {
120
+ this.#onBeforeNavigate = callback;
121
+ }
105
122
  /**
106
123
  * Release the history service subscription.
107
124
  * Called by the owning instance's destroy(); safe to call repeatedly.
@@ -132,6 +149,9 @@ export class HistoryStore {
132
149
  * @returns true if undo was successful, false if at beginning of history
133
150
  */
134
151
  undo() {
152
+ // Flush any pending edit session into a committed step first, so undo reverts
153
+ // exactly that step rather than skipping over an uncommitted edit.
154
+ this.#onBeforeNavigate?.();
135
155
  const previousState = this.#service.undo();
136
156
  if (previousState && this.#onRestore) {
137
157
  this.#onRestore(previousState);
@@ -147,6 +167,9 @@ export class HistoryStore {
147
167
  * @returns true if redo was successful, false if at end of history
148
168
  */
149
169
  redo() {
170
+ // A pending edit session invalidates the redo stack (it is a new change), so
171
+ // finalize it first; redo then correctly reports nothing to redo.
172
+ this.#onBeforeNavigate?.();
150
173
  const nextState = this.#service.redo();
151
174
  if (nextState && this.#onRestore) {
152
175
  this.#onRestore(nextState);
@@ -162,9 +185,13 @@ export class HistoryStore {
162
185
  startTransaction(workflow, description) {
163
186
  this.#service.startTransaction(workflow, description);
164
187
  }
165
- /** Commit the current transaction. */
166
- commitTransaction() {
167
- this.#service.commitTransaction();
188
+ /**
189
+ * Commit the current transaction with its final (post-change) state.
190
+ *
191
+ * @param finalWorkflow - The workflow state after the grouped change.
192
+ */
193
+ commitTransaction(finalWorkflow) {
194
+ this.#service.commitTransaction(finalWorkflow);
168
195
  }
169
196
  /** Cancel the current transaction without committing. */
170
197
  cancelTransaction() {
@@ -55,10 +55,15 @@ export function createFlowDropInstance(options = {}) {
55
55
  // Default wiring: undo/redo restores into this instance's workflow store.
56
56
  // WorkflowEditor overrides this with a richer callback while mounted.
57
57
  historyBindings.setOnRestoreCallback((restored) => workflow.restoreFromHistory(restored));
58
+ // Before any undo/redo, flush a pending config-edit session into a committed
59
+ // step so it can be undone atomically (the history service won't commit a
60
+ // dangling transaction itself — it has no access to the live state).
61
+ historyBindings.setBeforeNavigateCallback(() => workflow.finalizeNodeConfig());
58
62
  const playground = new PlaygroundStore();
59
63
  const cleanups = [
60
64
  () => historyBindings.cleanup(),
61
65
  () => historyBindings.setOnRestoreCallback(null),
66
+ () => historyBindings.setBeforeNavigateCallback(null),
62
67
  () => workflow.setOnDirtyStateChange(null),
63
68
  () => workflow.setOnWorkflowChange(null),
64
69
  () => playground.dispose()