Skip to content

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

fix(chat): date proposal revisions by their draft and key cards by identity

M3gA-Minda45d245adb0e
diff --git a/app/src/components/chat/WorkflowProposalCard.test.tsx b/app/src/components/chat/WorkflowProposalCard.test.tsx
index 019035dfae..cd694d98b3 100644
--- a/app/src/components/chat/WorkflowProposalCard.test.tsx
+++ b/app/src/components/chat/WorkflowProposalCard.test.tsx
@@ -197,7 +197,7 @@ describe('WorkflowProposalCard', () => {
markWorkflowProposalSaved({ threadId: 't1', flowId: 'f1', name: 'Daily standup summary' })
);
expect(mockDispatch).toHaveBeenCalledWith(
- markWorkflowProposalCompleted({ threadId: 't1', flowId: 'f1' })
+ markWorkflowProposalCompleted({ threadId: 't1', flowId: 'f1', name: 'Daily standup summary' })
);
expect(mockNavigate).not.toHaveBeenCalled();
});
@@ -305,7 +305,7 @@ describe('WorkflowProposalCard', () => {
await waitFor(() => expect(screen.getByTestId('workflow-proposal-saved')).toBeInTheDocument());
expect(mockDispatch).toHaveBeenCalledTimes(2);
expect(mockDispatch).toHaveBeenCalledWith(
- markWorkflowProposalCompleted({ threadId: 't1', flowId: 'f1' })
+ markWorkflowProposalCompleted({ threadId: 't1', flowId: 'f1', name: 'Daily standup summary' })
);
});
@@ -342,7 +342,7 @@ describe('WorkflowProposalCard', () => {
// Redux-mirrored completion once the retry succeeds.
expect(mockDispatch).toHaveBeenCalledTimes(2);
expect(mockDispatch).toHaveBeenCalledWith(
- markWorkflowProposalCompleted({ threadId: 't1', flowId: 'f1' })
+ markWorkflowProposalCompleted({ threadId: 't1', flowId: 'f1', name: 'Daily standup summary' })
);
});
@@ -385,6 +385,16 @@ describe('WorkflowProposalCard', () => {
expect(mockDispatch).not.toHaveBeenCalled();
});
+ it('never writes a revision that carries no source version onto its flow', async () => {
+ render(<WorkflowProposalCard threadId="t1" proposal={proposal({ flowId: 'flow-1' })} />);
+ fireEvent.click(screen.getByText('chat.flowProposal.save'));
+ await waitFor(() =>
+ expect(screen.getByText(/chat\.flowProposal\.versionConflict/)).toBeInTheDocument()
+ );
+ expect(mockUpdateFlow).not.toHaveBeenCalled();
+ expect(mockCreateFlow).not.toHaveBeenCalled();
+ });
+
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'));
@@ -471,7 +481,7 @@ describe('WorkflowProposalCard pre-authorization', () => {
);
// Not completed yet — the decision is still pending.
expect(mockDispatch).not.toHaveBeenCalledWith(
- markWorkflowProposalCompleted({ threadId: 't1', flowId: 'f1' })
+ markWorkflowProposalCompleted({ threadId: 't1', flowId: 'f1', name: 'Daily standup summary' })
);
expect(mockDispatch).toHaveBeenCalledWith(
markWorkflowProposalSaved({ threadId: 't1', flowId: 'f1', name: 'Daily standup summary' })
@@ -492,7 +502,7 @@ describe('WorkflowProposalCard pre-authorization', () => {
await waitFor(() => expect(screen.getByTestId('workflow-proposal-saved')).toBeInTheDocument());
expect(mockPreauthorizeFlow).toHaveBeenCalledWith('f1', ['GMAIL_SEND_EMAIL']);
expect(mockDispatch).toHaveBeenCalledWith(
- markWorkflowProposalCompleted({ threadId: 't1', flowId: 'f1' })
+ markWorkflowProposalCompleted({ threadId: 't1', flowId: 'f1', name: 'Daily standup summary' })
);
// checkAfterSave path: the flow came back enabled from createFlow, so no
// redundant enable call fires on approve.
@@ -531,7 +541,7 @@ describe('WorkflowProposalCard pre-authorization', () => {
);
// No terminal completion — the proposal card stays for a later retry.
expect(mockDispatch).not.toHaveBeenCalledWith(
- markWorkflowProposalCompleted({ threadId: 't1', flowId: 'f1' })
+ markWorkflowProposalCompleted({ threadId: 't1', flowId: 'f1', name: 'Daily standup summary' })
);
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 94f70361d4..16712dc5d6 100644
--- a/app/src/components/chat/WorkflowProposalCard.tsx
+++ b/app/src/components/chat/WorkflowProposalCard.tsx
@@ -234,7 +234,14 @@ const WorkflowProposalCard: React.FC<Props> = ({ threadId, proposal, onSaved })
const markCompleted = (flowId: string) => {
setCompletedFlowId(flowId);
- dispatch(markWorkflowProposalCompleted({ threadId, flowId }));
+ dispatch(
+ markWorkflowProposalCompleted({
+ threadId,
+ flowId,
+ name: proposal.name,
+ sourceMessageId: proposal.sourceMessageId,
+ })
+ );
};
// Consolidated save+enable pre-authorization (Approve all / Deny), rendered
@@ -271,6 +278,15 @@ const WorkflowProposalCard: React.FC<Props> = ({ threadId, proposal, onSaved })
// what just happened in this attempt.
let flowId = savedFlowId;
let flowPersisted = flowId !== null;
+ // A revision without the version it was derived from (an older persisted
+ // proposal, or a flow edited after its draft was seeded) cannot be checked
+ // against newer edits, so it is never written onto the flow.
+ if (!flowId && proposal.flowId && !proposal.flowVersion) {
+ log('save: revision of %s carries no source version — refusing', proposal.flowId);
+ setErrorMsg(t('chat.flowProposal.versionConflict'));
+ setSaving(false);
+ return;
+ }
try {
if (!flowId) {
// A proposal that revises a saved flow (`flow_id` on its payload) is
diff --git a/app/src/features/conversations/Conversations.tsx b/app/src/features/conversations/Conversations.tsx
index b0bfae8896..4e4d0987a1 100644
--- a/app/src/features/conversations/Conversations.tsx
+++ b/app/src/features/conversations/Conversations.tsx
@@ -83,6 +83,7 @@ import {
type ProcessingTranscriptItem,
setToolTimelineForThread,
type ToolTimelineEntry,
+ workflowProposalKey,
} from '../../store/chatRuntimeSlice';
import { useAppDispatch, useAppSelector } from '../../store/hooks';
import { pendingFollowupAdded } from '../../store/queueSlice';
@@ -2050,11 +2051,12 @@ const Conversations = ({
path from proposal to saved automation via "Save & enable"
(`flows_create`), or the user can Dismiss it outright. */}
{selectedThreadId && pendingWorkflowProposal && (
- // Keyed by name so a second proposal in the same thread (before the
- // first is resolved) remounts the card and resets its local
- // saving/error state, matching the PlanReviewCard pattern above.
+ // Keyed by the proposal's identity (source message + name) so a
+ // second proposal in the same thread (before the first is resolved)
+ // remounts the card and resets its local saving/error state, matching
+ // the PlanReviewCard pattern above.
<WorkflowProposalCard
- key={pendingWorkflowProposal.name}
+ key={workflowProposalKey(pendingWorkflowProposal)}
threadId={selectedThreadId}
proposal={pendingWorkflowProposal}
/>
diff --git a/app/src/store/__tests__/chatRuntimeSlice.workflowProposal.test.ts b/app/src/store/__tests__/chatRuntimeSlice.workflowProposal.test.ts
index a5e9fb21c0..a275cdfeb5 100644
--- a/app/src/store/__tests__/chatRuntimeSlice.workflowProposal.test.ts
+++ b/app/src/store/__tests__/chatRuntimeSlice.workflowProposal.test.ts
@@ -1,6 +1,7 @@
import { describe, expect, it } from 'vitest';
import reducer, {
+ markWorkflowProposalCompleted,
markWorkflowProposalSaved,
setWorkflowProposalForThread,
type WorkflowProposal,
@@ -44,3 +45,18 @@ describe('markWorkflowProposalSaved', () => {
expect(state.pendingWorkflowProposalsByThread.t1?.savedFlowId).toBeUndefined();
});
});
+
+describe('markWorkflowProposalCompleted', () => {
+ it('ignores a late completion from a proposal that was replaced', () => {
+ const state = reducer(
+ withPending(proposal('Digest', 'm2')),
+ markWorkflowProposalCompleted({
+ threadId: 't1',
+ flowId: 'f1',
+ name: 'Digest',
+ sourceMessageId: 'm1',
+ })
+ );
+ expect(state.pendingWorkflowProposalsByThread.t1?.completedFlowId).toBeUndefined();
+ });
+});
diff --git a/app/src/store/chatRuntimeSlice.ts b/app/src/store/chatRuntimeSlice.ts
index c90ef84ed3..1db0df9475 100644
--- a/app/src/store/chatRuntimeSlice.ts
+++ b/app/src/store/chatRuntimeSlice.ts
@@ -833,6 +833,29 @@ export interface WorkflowProposal {
savedFlowId?: string;
}
+/**
+ * A proposal's identity across Redux updates and card remounts: its source
+ * message when it has one, and its name. Also the card's React key, so a
+ * replacement remounts the card and a late save/enable result from the
+ * replaced proposal is ignored instead of landing on the new one.
+ */
+export function workflowProposalKey(
+ proposal: Pick<WorkflowProposal, 'name' | 'sourceMessageId'>
+): string {
+ return `${proposal.sourceMessageId ?? ''}|${proposal.name}`;
+}
+
+/** Payload of the save/completion updates, naming the proposal they belong to. */
+interface WorkflowProposalSaveUpdate {
+ threadId: string;
+ flowId: string;
+ name: string;
+ sourceMessageId?: string;
+}
+
+const isSameProposal = (proposal: WorkflowProposal, update: WorkflowProposalSaveUpdate) =>
+ workflowProposalKey(proposal) === workflowProposalKey(update);
+
/**
* Lifecycle status of a single agent-generated artifact, as projected
* onto the chat runtime per thread.
@@ -2606,14 +2629,12 @@ const chatRuntimeSlice = createSlice({
* state survives a remount (thread switch, route change) while the
* proposal is still sitting in `pendingWorkflowProposalsByThread` — see
* `WorkflowProposal.completedFlowId`. No-op if the proposal was already
- * cleared (e.g. a race with `clearWorkflowProposalForThread`).
+ * cleared (e.g. a race with `clearWorkflowProposalForThread`) or replaced
+ * by another proposal (see `isSameProposal`).
*/
- markWorkflowProposalCompleted: (
- state,
- action: PayloadAction<{ threadId: string; flowId: string }>
- ) => {
+ markWorkflowProposalCompleted: (state, action: PayloadAction<WorkflowProposalSaveUpdate>) => {
const proposal = state.pendingWorkflowProposalsByThread[action.payload.threadId];
- if (proposal) {
+ if (proposal && isSameProposal(proposal, action.payload)) {
proposal.completedFlowId = action.payload.flowId;
}
},
@@ -2624,21 +2645,9 @@ const chatRuntimeSlice = createSlice({
* it while the save was in flight must not inherit its flow id. No-op if
* the proposal was cleared or replaced.
*/
- markWorkflowProposalSaved: (
- state,
- action: PayloadAction<{
- threadId: string;
- flowId: string;
- name: string;
- sourceMessageId?: string;
- }>
- ) => {
+ markWorkflowProposalSaved: (state, action: PayloadAction<WorkflowProposalSaveUpdate>) => {
const proposal = state.pendingWorkflowProposalsByThread[action.payload.threadId];
- if (
- proposal &&
- proposal.name === action.payload.name &&
- proposal.sourceMessageId === action.payload.sourceMessageId
- ) {
+ if (proposal && isSameProposal(proposal, action.payload)) {
proposal.savedFlowId = action.payload.flowId;
}
},
diff --git a/crates/openhuman-core/src/flows/ops/builder_gates.rs b/crates/openhuman-core/src/flows/ops/builder_gates.rs
index 7c361a59fa..37046b7754 100644
--- a/crates/openhuman-core/src/flows/ops/builder_gates.rs
+++ b/crates/openhuman-core/src/flows/ops/builder_gates.rs
@@ -214,28 +214,73 @@ pub(crate) async fn build_builder_proposal(
}
// Echo the persistence-state handles so the agent can iterate/persist
// against the right ids (the draft the edit lives on; the flow it targets).
+ if let Some(flow_id) = flow_id.as_deref() {
+ // The version this revision was derived from, so a save onto the flow
+ // can refuse to overwrite a newer edit (`flows_update`'s
+ // `expected_version`). Omitted when it cannot be established; the card
+ // then asks for a new revision instead of saving last-write-wins.
+ if let Some(version) = source_flow_version(config, flow_id, draft_id.as_deref()) {
+ payload["flow_version"] = json!(version);
+ }
+ }
if let Some(draft_id) = draft_id {
payload["draft_id"] = json!(draft_id);
}
if let Some(flow_id) = flow_id {
- // The version this revision was built against, so a save onto the
- // flow can refuse to overwrite a newer edit (`flows_update`'s
- // `expected_version`). Best-effort: without it the save is
- // last-write-wins, as before.
- match store::get_flow(config, &flow_id) {
- Ok(Some(flow)) => payload["flow_version"] = json!(flow.updated_at),
- Ok(None) => {
- tracing::debug!(target: "flows", %flow_id, "[flows] build_builder_proposal: target flow not found; no version")
- }
- Err(error) => {
- tracing::warn!(target: "flows", %flow_id, %error, "[flows] build_builder_proposal: could not read target flow version")
- }
- }
payload["flow_id"] = json!(flow_id);
}
Ok(payload)
}
+/// The version of `flow_id` a revision's graph was derived from.
+///
+/// A revision of a saved flow lives on a draft seeded from that flow, and the
+/// draft records no base version. The flow's current `updated_at` is the
+/// source version exactly when the flow has not changed since the draft was
+/// created; after a later edit it is not, and a version read now would let a
+/// stale graph pass `expected_version`. `None` when that cannot be shown.
+fn source_flow_version(config: &Config, flow_id: &str, draft_id: Option<&str>) -> Option<String> {
+ let flow = match store::get_flow(config, flow_id) {
+ Ok(Some(flow)) => flow,
+ Ok(None) => {
+ tracing::debug!(target: "flows", %flow_id, "[flows] source_flow_version: target flow not found");
+ return None;
+ }
+ Err(error) => {
+ tracing::warn!(target: "flows", %flow_id, %error, "[flows] source_flow_version: could not read target flow");
+ return None;
+ }
+ };
+ let Some(draft_id) = draft_id else {
+ tracing::debug!(target: "flows", %flow_id, "[flows] source_flow_version: no draft to date the revision");
+ return None;
+ };
+ let draft = match draft_store::get_draft(config, draft_id) {
+ Ok(Some(draft)) => draft,
+ Ok(None) => {
+ tracing::debug!(target: "flows", %draft_id, "[flows] source_flow_version: draft not found");
+ return None;
+ }
+ Err(error) => {
+ tracing::warn!(target: "flows", %draft_id, %error, "[flows] source_flow_version: could not read draft");
+ return None;
+ }
+ };
+ let flow_at = chrono::DateTime::parse_from_rfc3339(&flow.updated_at).ok()?;
+ let seeded_at = chrono::DateTime::parse_from_rfc3339(&draft.created_at).ok()?;
+ if flow_at <= seeded_at {
+ Some(flow.updated_at)
+ } else {
+ tracing::debug!(
+ target: "flows",
+ %flow_id,
+ %draft_id,
+ "[flows] source_flow_version: flow changed after the draft was seeded; no version"
+ );
+ None
+ }
+}
+
/// Decode the Copilot bus's portable graph payload and run the host-owned
/// proposal gates without exposing engine types through the callback adapter.
#[allow(clippy::too_many_arguments)]
diff --git a/crates/openhuman-core/src/flows/ops_agent_binding_tests.rs b/crates/openhuman-core/src/flows/ops_agent_binding_tests.rs
index 3e0b0d1931..b4e065524c 100644
--- a/crates/openhuman-core/src/flows/ops_agent_binding_tests.rs
+++ b/crates/openhuman-core/src/flows/ops_agent_binding_tests.rs
@@ -430,40 +430,95 @@ async fn agent_ref_gate_reads_the_registry_of_the_explicit_context() {
);
}
-#[tokio::test]
-async fn revision_proposal_carries_the_target_flow_version() {
- // A proposal that revises a saved flow carries that flow's version, so a
- // save onto it can refuse to overwrite a newer edit.
- let tmp = TempDir::new().unwrap();
- let config = test_config(&tmp);
- let g = graph(json!({
+fn tool_call_graph() -> Value {
+ graph(json!({
"nodes": [
{ "id": "t", "kind": "trigger", "name": "Manual" },
{ "id": "post", "kind": "tool_call", "name": "Post",
"config": { "slug": "oh:noop" } }
],
"edges": [ { "from_node": "t", "to_node": "post" } ]
- }));
- let flow = flows_create(&config, "Base".to_string(), g.clone(), false)
- .await
- .unwrap()
- .value;
+ }))
+}
- let payload = build_builder_proposal(
+async fn revision_payload(config: &Config, flow_id: &str, draft_id: Option<String>) -> Value {
+ build_builder_proposal(
&crate::core::runtime::DispatchCtx::ambient(),
- &config,
+ config,
"edit_workflow",
"Base",
- &g,
+ &tool_call_graph(),
false,
true,
None,
- None,
- Some(flow.id.clone()),
+ draft_id,
+ Some(flow_id.to_string()),
)
.await
- .expect("proposal must succeed for a tool_call-only graph");
+ .expect("proposal must succeed for a tool_call-only graph")
+}
+
+#[tokio::test]
+async fn revision_proposal_carries_the_version_its_draft_was_seeded_from() {
+ // The draft was seeded from the flow as it is now, so the flow's current
+ // version is the one the revision was derived from.
+ let tmp = TempDir::new().unwrap();
+ let config = test_config(&tmp);
+ let flow = flows_create(&config, "Base".to_string(), tool_call_graph(), false)
+ .await
+ .unwrap()
+ .value;
+ let draft = crate::flows::draft_store::create_draft(
+ &config,
+ Some(flow.id.clone()),
+ "Base".to_string(),
+ tool_call_graph(),
+ tinyflows_bus::catalog::DraftOrigin::Chat,
+ )
+ .unwrap();
+
+ let payload = revision_payload(&config, &flow.id, Some(draft.id)).await;
assert_eq!(payload["flow_id"], json!(flow.id));
assert_eq!(payload["flow_version"], json!(flow.updated_at));
}
+
+#[tokio::test]
+async fn revision_proposal_omits_the_version_after_the_flow_changed_under_its_draft() {
+ // An edit after the draft was seeded makes the flow's current version a
+ // later one than the revision was derived from; stamping it would let the
+ // stale graph pass `expected_version`.
+ let tmp = TempDir::new().unwrap();
+ let config = test_config(&tmp);
+ let flow = flows_create(&config, "Base".to_string(), tool_call_graph(), false)
+ .await
+ .unwrap()
+ .value;
+ let draft = crate::flows::draft_store::create_draft(
+ &config,
+ Some(flow.id.clone()),
+ "Base".to_string(),
+ tool_call_graph(),
+ tinyflows_bus::catalog::DraftOrigin::Chat,
+ )
+ .unwrap();
+ flows_update(
+ &config,
+ &flow.id,
+ Some("Edited".to_string()),
+ None,
+ None,
+ None,
+ )
+ .await
+ .unwrap();
+
+ let payload = revision_payload(&config, &flow.id, Some(draft.id)).await;
+
+ assert_eq!(payload["flow_id"], json!(flow.id));
+ assert!(payload.get("flow_version").is_none(), "{payload:?}");
+
+ // Without a draft to date the revision, no version is claimed either.
+ let undated = revision_payload(&config, &flow.id, None).await;
+ assert!(undated.get("flow_version").is_none(), "{undated:?}");
+}