Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

fix(chat): save each workflow proposal once, onto the flow it revises

M3gA-Mind783b2cf4492f
diff --git a/app/src/components/chat/WorkflowProposalCard.test.tsx b/app/src/components/chat/WorkflowProposalCard.test.tsx
index 0f7f536817..9f3405910b 100644
--- a/app/src/components/chat/WorkflowProposalCard.test.tsx
+++ b/app/src/components/chat/WorkflowProposalCard.test.tsx
@@ -1,7 +1,11 @@
import { fireEvent, render, screen, waitFor } from '@testing-library/react';
import { beforeEach, describe, expect, it, vi } from 'vitest';
-import { markWorkflowProposalCompleted, type WorkflowProposal } from '../../store/chatRuntimeSlice';
+import {
+ markWorkflowProposalCompleted,
+ markWorkflowProposalSaved,
+ type WorkflowProposal,
+} from '../../store/chatRuntimeSlice';
import WorkflowProposalCard from './WorkflowProposalCard';
// Echo i18n keys so we can assert on the stable key string.
@@ -184,7 +188,10 @@ describe('WorkflowProposalCard', () => {
// see `WorkflowProposal.completedFlowId`. It must not be the
// proposal-clearing dispatch, though — that only happens on "View
// workflow"/"Dismiss".
- expect(mockDispatch).toHaveBeenCalledTimes(1);
+ expect(mockDispatch).toHaveBeenCalledTimes(2);
+ expect(mockDispatch).toHaveBeenCalledWith(
+ markWorkflowProposalSaved({ threadId: 't1', flowId: 'f1' })
+ );
expect(mockDispatch).toHaveBeenCalledWith(
markWorkflowProposalCompleted({ threadId: 't1', flowId: 'f1' })
);
@@ -292,7 +299,7 @@ describe('WorkflowProposalCard', () => {
// dispatch is the Redux-mirrored completion (survives a remount), not a
// clear.
await waitFor(() => expect(screen.getByTestId('workflow-proposal-saved')).toBeInTheDocument());
- expect(mockDispatch).toHaveBeenCalledTimes(1);
+ expect(mockDispatch).toHaveBeenCalledTimes(2);
expect(mockDispatch).toHaveBeenCalledWith(
markWorkflowProposalCompleted({ threadId: 't1', flowId: 'f1' })
);
@@ -312,7 +319,12 @@ describe('WorkflowProposalCard', () => {
);
// The flow was already persisted — the card must not be cleared, and a
// retry must not re-create it (which would duplicate the flow).
- expect(mockDispatch).not.toHaveBeenCalled();
+ // It is recorded as saved (Redux + source message) so a remount or reload
+ // resumes at the enable step instead of creating the flow again.
+ expect(mockDispatch).toHaveBeenCalledTimes(1);
+ expect(mockDispatch).toHaveBeenCalledWith(
+ markWorkflowProposalSaved({ threadId: 't1', flowId: 'f1' })
+ );
mockSetFlowEnabled.mockResolvedValueOnce({ id: 'f1', enabled: true });
fireEvent.click(screen.getByText('chat.flowProposal.save'));
@@ -324,12 +336,40 @@ describe('WorkflowProposalCard', () => {
// Still not dispatched away — the retry lands on the same saved
// confirmation, not an immediate clear. The only dispatch is the
// Redux-mirrored completion once the retry succeeds.
- expect(mockDispatch).toHaveBeenCalledTimes(1);
+ expect(mockDispatch).toHaveBeenCalledTimes(2);
expect(mockDispatch).toHaveBeenCalledWith(
markWorkflowProposalCompleted({ threadId: 't1', flowId: 'f1' })
);
});
+ it('saves a revision onto the flow it targets instead of creating another', async () => {
+ mockUpdateFlow.mockResolvedValueOnce({
+ id: 'flow-1',
+ name: 'Daily standup summary',
+ enabled: true,
+ });
+ const p = proposal({ flowId: 'flow-1' });
+ render(<WorkflowProposalCard threadId="t1" proposal={p} />);
+ fireEvent.click(screen.getByText('chat.flowProposal.save'));
+ await waitFor(() =>
+ expect(mockUpdateFlow).toHaveBeenCalledWith('flow-1', {
+ name: p.name,
+ graph: p.graph,
+ requireApproval: p.requireApproval,
+ })
+ );
+ expect(mockCreateFlow).not.toHaveBeenCalled();
+ await waitFor(() => expect(screen.getByTestId('workflow-proposal-saved')).toBeInTheDocument());
+ });
+
+ it('resumes at the enable step for a proposal whose flow was already saved', async () => {
+ render(<WorkflowProposalCard threadId="t1" proposal={proposal({ savedFlowId: 'f1' })} />);
+ fireEvent.click(screen.getByText('chat.flowProposal.save'));
+ await waitFor(() => expect(mockSetFlowEnabled).toHaveBeenCalledWith('f1', true));
+ expect(mockCreateFlow).not.toHaveBeenCalled();
+ expect(mockUpdateFlow).not.toHaveBeenCalled();
+ });
+
it('opens the proposed graph in the canvas as an unsaved draft without persisting', () => {
const p = proposal();
render(<WorkflowProposalCard threadId="t1" proposal={p} />);
@@ -407,7 +447,12 @@ describe('WorkflowProposalCard pre-authorization', () => {
expect(screen.getByTestId('flow-preauthorization-card')).toBeInTheDocument()
);
// Not completed yet — the decision is still pending.
- expect(mockDispatch).not.toHaveBeenCalled();
+ expect(mockDispatch).not.toHaveBeenCalledWith(
+ markWorkflowProposalCompleted({ threadId: 't1', flowId: 'f1' })
+ );
+ expect(mockDispatch).toHaveBeenCalledWith(
+ markWorkflowProposalSaved({ threadId: 't1', flowId: 'f1' })
+ );
expect(screen.queryByTestId('workflow-proposal-saved')).not.toBeInTheDocument();
});
diff --git a/app/src/components/chat/WorkflowProposalCard.tsx b/app/src/components/chat/WorkflowProposalCard.tsx
index e2329a54a2..c08a5c7826 100644
--- a/app/src/components/chat/WorkflowProposalCard.tsx
+++ b/app/src/components/chat/WorkflowProposalCard.tsx
@@ -6,11 +6,12 @@ import { useFlowPreauthorization } from '../../hooks/useFlowPreauthorization';
import { FLOW_CANVAS_DRAFT_ROUTE, type FlowCanvasDraftState } from '../../lib/flows/canvasDraft';
import type { WorkflowGraph } from '../../lib/flows/types';
import { useT } from '../../lib/i18n/I18nContext';
-import { createFlow } from '../../services/api/flowsApi';
+import { createFlow, updateFlow } from '../../services/api/flowsApi';
import { threadApi } from '../../services/api/threadApi';
import {
clearWorkflowProposalForThread,
markWorkflowProposalCompleted,
+ markWorkflowProposalSaved,
type WorkflowProposal,
} from '../../store/chatRuntimeSlice';
import { useAppDispatch } from '../../store/hooks';
@@ -118,7 +119,13 @@ const WorkflowProposalCard: React.FC<Props> = ({ threadId, proposal, onSaved })
// (B29 Rule 1) and the follow-up `setFlowEnabled` call hasn't succeeded
// yet. Non-null means a retry of `save` should skip `createFlow` entirely
// and only retry the enable step.
- const [savedFlowId, setSavedFlowId] = useState<string | null>(null);
+ //
+ // Seeded from `proposal.savedFlowId` (Redux, or the source message's
+ // `saved_flow_id` after a reload) so a remount resumes the enable step
+ // instead of persisting the flow a second time.
+ const [savedFlowId, setSavedFlowId] = useState<string | null>(
+ () => proposal.savedFlowId ?? null
+ );
// Set once the flow is fully persisted AND enabled — the terminal success
// state. Non-null swaps the card's body from the editable proposal (name/
// trigger/steps/buttons) to a compact saved confirmation with a link into
@@ -202,6 +209,24 @@ const WorkflowProposalCard: React.FC<Props> = ({ threadId, proposal, onSaved })
* remount before the user clicks "View workflow" — see the
* `completedFlowId` state comment above).
*/
+ /**
+ * Record that the flow is persisted but not yet enabled, everywhere a
+ * remount or reload reads it back from: this render, Redux, and the source
+ * message (`saved_flow_id`, merged into its metadata). Fire-and-forget for
+ * the message write: a failed mark only risks a duplicate on a later reload.
+ */
+ const markSaved = (flowId: string) => {
+ setSavedFlowId(flowId);
+ dispatch(markWorkflowProposalSaved({ threadId, flowId }));
+ if (!proposal.sourceMessageId) return;
+ threadApi
+ .updateMessage(threadId, proposal.sourceMessageId, {
+ scope: 'workflow_proposal',
+ saved_flow_id: flowId,
+ })
+ .catch(e => log('markSaved message write failed (non-fatal): %o', e));
+ };
+
const markCompleted = (flowId: string) => {
setCompletedFlowId(flowId);
dispatch(markWorkflowProposalCompleted({ threadId, flowId }));
@@ -243,17 +268,25 @@ const WorkflowProposalCard: React.FC<Props> = ({ threadId, proposal, onSaved })
let flowPersisted = flowId !== null;
try {
if (!flowId) {
- const flow = await createFlow(proposal.name, proposal.graph, proposal.requireApproval);
+ // A proposal that revises a saved flow (`flow_id` on its payload) is
+ // written onto that flow; only a brand-new proposal creates one.
+ const flow = proposal.flowId
+ ? await updateFlow(proposal.flowId, {
+ name: proposal.name,
+ graph: proposal.graph,
+ requireApproval: proposal.requireApproval,
+ })
+ : await createFlow(proposal.name, proposal.graph, proposal.requireApproval);
flowId = flow.id;
flowPersisted = true;
// Persisted — record the id BEFORE any branch releases `saving`, so a
- // second click (e.g. while the pre-authorization card below is open)
- // can never reach `createFlow` again and duplicate the flow.
- setSavedFlowId(flow.id);
+ // second click (e.g. while the pre-authorization card below is open),
+ // a remount or a reload can never persist the flow again.
+ markSaved(flow.id);
if (flow.enabled) {
// Already live — surface the pre-authorization card when grants
// are missing; otherwise this is the terminal success state.
- log('save: createFlow returned enabled id=%s — running pre-auth check', flow.id);
+ log('save: flow persisted enabled id=%s — running pre-auth check', flow.id);
const cardShown = await preauth.checkAfterSave(flow.id, true);
setSaving(false);
if (!cardShown) {
@@ -266,7 +299,7 @@ const WorkflowProposalCard: React.FC<Props> = ({ threadId, proposal, onSaved })
// B29 Rule 1 saved this automatic-trigger flow disabled. This click
// is the user's own explicit "Save & enable" — not the copilot's
// silent autosave Rule 1 guards against — so arm it now.
- log('save: createFlow returned disabled (Rule 1) — arming explicitly id=%s', flow.id);
+ log('save: flow persisted disabled (Rule 1) — arming explicitly id=%s', flow.id);
}
// Enable through the pre-authorization check: enables directly when no
// grants are missing, otherwise the card renders below and the enable
diff --git a/app/src/lib/workflows/workflowProposal.test.ts b/app/src/lib/workflows/workflowProposal.test.ts
index af795f6d3e..6b2ccdf159 100644
--- a/app/src/lib/workflows/workflowProposal.test.ts
+++ b/app/src/lib/workflows/workflowProposal.test.ts
@@ -99,6 +99,18 @@ describe('maybeParseWorkflowProposalTool', () => {
});
});
+describe('coerceWorkflowProposal flow_id', () => {
+ it('keeps the flow a revision targets and omits it for a new proposal', () => {
+ const revision = parseWorkflowProposal(
+ JSON.stringify({ ...proposalPayload('Revised'), flow_id: 'flow-1', draft_id: 'draft-1' })
+ );
+ expect(revision?.flowId).toBe('flow-1');
+ expect(parseWorkflowProposal(JSON.stringify(proposalPayload('New')))).not.toHaveProperty(
+ 'flowId'
+ );
+ });
+});
+
describe('extractWorkflowProposalFromMessages', () => {
it('rehydrates the newest unconsumed proposal and tags its source message', () => {
const messages = [
@@ -111,18 +123,27 @@ describe('extractWorkflowProposalFromMessages', () => {
expect(proposal?.sourceMessageId).toBe('m3');
});
- it('skips consumed proposals so a saved/dismissed card does not resurrect', () => {
+ it('returns nothing once the newest proposal is consumed: older revisions are superseded', () => {
const messages = [
- message('m1', { scope: 'workflow_proposal', proposal: proposalPayload('Kept') }),
+ message('m1', { scope: 'workflow_proposal', proposal: proposalPayload('Superseded') }),
message('m2', {
scope: 'workflow_proposal',
proposal: proposalPayload('Already Saved'),
consumed: true,
}),
];
- const proposal = extractWorkflowProposalFromMessages(messages);
- expect(proposal?.name).toBe('Kept');
- expect(proposal?.sourceMessageId).toBe('m1');
+ expect(extractWorkflowProposalFromMessages(messages)).toBeNull();
+ });
+
+ it('carries the saved flow id so a reloaded card resumes at the enable step', () => {
+ const messages = [
+ message('m1', {
+ scope: 'workflow_proposal',
+ proposal: proposalPayload('Saved Not Enabled'),
+ saved_flow_id: 'flow-7',
+ }),
+ ];
+ expect(extractWorkflowProposalFromMessages(messages)?.savedFlowId).toBe('flow-7');
});
it('returns null when there is no proposal metadata or the payload is malformed', () => {
diff --git a/app/src/lib/workflows/workflowProposal.ts b/app/src/lib/workflows/workflowProposal.ts
index a17107f6a4..90366b66b8 100644
--- a/app/src/lib/workflows/workflowProposal.ts
+++ b/app/src/lib/workflows/workflowProposal.ts
@@ -45,6 +45,7 @@ export function coerceWorkflowProposal(parsed: unknown): WorkflowProposal | null
// here too — keeps the client's fallback in lockstep with the server's.
requireApproval: obj.require_approval !== false,
summary: { trigger: typeof summary.trigger === 'string' ? summary.trigger : '', steps },
+ ...(typeof obj.flow_id === 'string' && obj.flow_id ? { flowId: obj.flow_id } : {}),
};
}
@@ -68,23 +69,34 @@ export function maybeParseWorkflowProposalTool(
}
/**
- * Rehydrate the newest unconsumed workflow proposal from a thread's persisted
- * messages. The Rust core appends a message with
+ * Rehydrate a thread's live workflow proposal from its persisted messages. The
+ * Rust core appends a message with
* `extraMetadata: { scope: 'workflow_proposal', proposal, task_id, ... }`
* when an async `workflow_builder` run finishes; once the user saves or
* dismisses the card the message is marked `consumed: true` so it does not
* resurrect on the next load.
+ *
+ * Only the newest proposal message counts: a later proposal supersedes every
+ * earlier one, so an older unconsumed revision never comes back as a fresh,
+ * savable card (each such card used to create another copy of the flow).
+ * A `saved_flow_id` recorded on the message carries over, so a card whose
+ * flow was saved but not yet enabled resumes at the enable step.
*/
export function extractWorkflowProposalFromMessages(
messages: ThreadMessage[]
): WorkflowProposal | null {
for (let i = messages.length - 1; i >= 0; i--) {
const meta = messages[i].extraMetadata;
- if (!meta || meta.scope !== 'workflow_proposal' || meta.consumed === true) continue;
+ if (!meta || meta.scope !== 'workflow_proposal') continue;
+ if (meta.consumed === true) return null;
const proposal = coerceWorkflowProposal(meta.proposal);
- if (proposal) {
- return { ...proposal, sourceMessageId: messages[i].id };
- }
+ if (!proposal) return null;
+ const savedFlowId = typeof meta.saved_flow_id === 'string' ? meta.saved_flow_id : undefined;
+ return {
+ ...proposal,
+ sourceMessageId: messages[i].id,
+ ...(savedFlowId ? { savedFlowId } : {}),
+ };
}
return null;
}
diff --git a/app/src/store/chatRuntimeSlice.ts b/app/src/store/chatRuntimeSlice.ts
index 7b4c48fb41..8fb4c8401a 100644
--- a/app/src/store/chatRuntimeSlice.ts
+++ b/app/src/store/chatRuntimeSlice.ts
@@ -812,6 +812,19 @@ export interface WorkflowProposal {
* enable" click would call `createFlow` again and duplicate the flow.
*/
completedFlowId?: string;
+ /**
+ * The saved flow this proposal revises (`flow_id` on the proposal payload,
+ * set when the builder edited an existing flow). "Save & enable" writes onto
+ * this flow with `flows_update` instead of creating another one.
+ */
+ flowId?: string;
+ /**
+ * Id of the flow once "Save & enable" persisted it, before the enable step
+ * finished (pre-authorization pending, denied, or failed). Mirrored into
+ * Redux and onto the source message's `saved_flow_id` so a remount or reload
+ * resumes the enable step instead of creating the flow again.
+ */
+ savedFlowId?: string;
}
/**
@@ -2598,6 +2611,19 @@ const chatRuntimeSlice = createSlice({
proposal.completedFlowId = action.payload.flowId;
}
},
+ /**
+ * Record that a pending proposal's flow is persisted but not yet enabled
+ * (see `WorkflowProposal.savedFlowId`). No-op if the proposal was cleared.
+ */
+ markWorkflowProposalSaved: (
+ state,
+ action: PayloadAction<{ threadId: string; flowId: string }>
+ ) => {
+ const proposal = state.pendingWorkflowProposalsByThread[action.payload.threadId];
+ if (proposal) {
+ proposal.savedFlowId = action.payload.flowId;
+ }
+ },
/**
* Mark a producer-tool call as in-flight so the `ArtifactCard` can
* render a spinner before any ready/failed event arrives. Caller
@@ -3309,6 +3335,7 @@ export const {
setWorkflowProposalForThread,
clearWorkflowProposalForThread,
markWorkflowProposalCompleted,
+ markWorkflowProposalSaved,
upsertArtifactInProgressForThread,
upsertArtifactReadyForThread,
upsertArtifactFailedForThread,