Skip to content

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

fix(flows): settle the proposal card when the agent saves it in chat

M3gA-Mind3cd6cef8a8a1
diff --git a/app/src/components/chat/WorkflowProposalCard.test.tsx b/app/src/components/chat/WorkflowProposalCard.test.tsx
index cd694d98b3..c76388068e 100644
--- a/app/src/components/chat/WorkflowProposalCard.test.tsx
+++ b/app/src/components/chat/WorkflowProposalCard.test.tsx
@@ -25,6 +25,8 @@ const {
mockPreauthorizeFlow,
mockDispatch,
mockNavigate,
+ mockGetThreadMessages,
+ mockUpdateMessage,
} = vi.hoisted(() => ({
mockCreateFlow: vi.fn(),
mockUpdateFlow: vi.fn(),
@@ -33,6 +35,14 @@ const {
mockPreauthorizeFlow: vi.fn(),
mockDispatch: vi.fn(),
mockNavigate: vi.fn(),
+ mockGetThreadMessages: vi.fn(),
+ mockUpdateMessage: vi.fn(),
+}));
+vi.mock('../../services/api/threadApi', () => ({
+ threadApi: {
+ getThreadMessages: (...args: unknown[]) => mockGetThreadMessages(...args),
+ updateMessage: (...args: unknown[]) => mockUpdateMessage(...args),
+ },
}));
vi.mock('../../services/api/flowsApi', () => ({
createFlow: (...args: unknown[]) => mockCreateFlow(...args),
@@ -83,6 +93,8 @@ describe('WorkflowProposalCard', () => {
.mockResolvedValue({ flow_id: 'f1', granted: [], already_trusted: [], gate_installed: true });
mockDispatch.mockReset();
mockNavigate.mockReset();
+ mockGetThreadMessages.mockReset().mockResolvedValue({ messages: [] });
+ mockUpdateMessage.mockReset().mockResolvedValue({});
});
it('renders the name, trigger, and steps with plain-language node-kind badges', () => {
@@ -395,6 +407,29 @@ describe('WorkflowProposalCard', () => {
expect(mockCreateFlow).not.toHaveBeenCalled();
});
+ it('enables the flow the agent already saved for this proposal instead of creating one', async () => {
+ // The user said "save it" in chat; the core recorded the agent's flow on
+ // the proposal's source message, which this card's state never saw.
+ mockGetThreadMessages.mockResolvedValueOnce({
+ messages: [
+ {
+ id: 'workflow-proposal:sub-1',
+ extraMetadata: { scope: 'workflow_proposal', saved_flow_id: 'agent-flow' },
+ },
+ ],
+ });
+ render(
+ <WorkflowProposalCard
+ threadId="t1"
+ proposal={proposal({ sourceMessageId: 'workflow-proposal:sub-1' })}
+ />
+ );
+ fireEvent.click(screen.getByText('chat.flowProposal.save'));
+ await waitFor(() => expect(mockSetFlowEnabled).toHaveBeenCalledWith('agent-flow', true));
+ expect(mockCreateFlow).not.toHaveBeenCalled();
+ expect(mockGetThreadMessages).toHaveBeenCalledWith('t1');
+ });
+
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'));
diff --git a/app/src/components/chat/WorkflowProposalCard.tsx b/app/src/components/chat/WorkflowProposalCard.tsx
index 16712dc5d6..4bd6e02177 100644
--- a/app/src/components/chat/WorkflowProposalCard.tsx
+++ b/app/src/components/chat/WorkflowProposalCard.tsx
@@ -232,6 +232,25 @@ const WorkflowProposalCard: React.FC<Props> = ({ threadId, proposal, onSaved })
.catch(e => log('markSaved message write failed (non-fatal): %o', e));
};
+ /**
+ * The flow already persisted for this proposal and recorded on its source
+ * message (`saved_flow_id`): by an earlier save from this card, or by the
+ * agent when the user asked for the save in chat. Read fresh before
+ * persisting, since an agent-side save never reaches this card's state.
+ * `null` when nothing is recorded or the read fails.
+ */
+ const recordedSavedFlowId = async (): Promise<string | null> => {
+ if (!proposal.sourceMessageId) return null;
+ try {
+ const { messages } = await threadApi.getThreadMessages(threadId);
+ const meta = messages.find(m => m.id === proposal.sourceMessageId)?.extraMetadata;
+ return typeof meta?.saved_flow_id === 'string' ? meta.saved_flow_id : null;
+ } catch (e) {
+ log('recordedSavedFlowId read failed (non-fatal): %o', e);
+ return null;
+ }
+ };
+
const markCompleted = (flowId: string) => {
setCompletedFlowId(flowId);
dispatch(
@@ -278,6 +297,15 @@ const WorkflowProposalCard: React.FC<Props> = ({ threadId, proposal, onSaved })
// what just happened in this attempt.
let flowId = savedFlowId;
let flowPersisted = flowId !== null;
+ if (!flowId) {
+ const recorded = await recordedSavedFlowId();
+ if (recorded) {
+ log('save: flow %s already saved for this proposal — resuming at enable', recorded);
+ flowId = recorded;
+ flowPersisted = true;
+ markSaved(recorded);
+ }
+ }
// 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.
diff --git a/crates/openhuman-core/src/agent/orchestration/tools/spawn_subagent_async_tests.rs b/crates/openhuman-core/src/agent/orchestration/tools/spawn_subagent_async_tests.rs
index 1b5caf485b..58c19d61d2 100644
--- a/crates/openhuman-core/src/agent/orchestration/tools/spawn_subagent_async_tests.rs
+++ b/crates/openhuman-core/src/agent/orchestration/tools/spawn_subagent_async_tests.rs
@@ -240,6 +240,92 @@ fn attach_workflow_proposal_persists_thread_message_and_extends_summary() {
assert_eq!(proposal_msg.extra_metadata["task_id"], "sub-task-1");
}
+/// A thread holding one delivered proposal (task `sub-propose`), named `name`.
+fn thread_with_delivered_proposal(name: &str) -> tempfile::TempDir {
+ use crate::threads::store::CreateConversationThread;
+ let temp = tempfile::tempdir().expect("tempdir");
+ conversations::ensure_thread(
+ &crate::core::runtime::DispatchCtx::ambient(),
+ temp.path().to_path_buf(),
+ CreateConversationThread {
+ id: "thread-parent".into(),
+ title: "Main chat".into(),
+ created_at: chrono::Utc::now().to_rfc3339(),
+ parent_thread_id: None,
+ labels: None,
+ personality_id: None,
+ working_dir: None,
+ },
+ )
+ .expect("thread created");
+ attach_workflow_proposal(
+ &crate::core::runtime::DispatchCtx::ambient(),
+ temp.path(),
+ Some("thread-parent"),
+ "sub-propose",
+ "workflow_builder",
+ &[TranscriptMessage::tool(format!(
+ r#"{{"type":"workflow_proposal","persisted":false,"name":"{name}","graph":{{"nodes":[],"edges":[]}}}}"#
+ ))],
+ "proposal".to_string(),
+ );
+ temp
+}
+
+fn delivered_proposal_metadata(temp: &tempfile::TempDir) -> serde_json::Value {
+ conversations::get_messages(
+ &crate::core::runtime::DispatchCtx::ambient(),
+ temp.path().to_path_buf(),
+ "thread-parent",
+ )
+ .expect("messages")
+ .into_iter()
+ .find(|m| m.id == "workflow-proposal:sub-propose")
+ .expect("proposal message")
+ .extra_metadata
+}
+
+#[test]
+fn an_agent_save_of_the_delivered_proposal_is_recorded_on_its_card() {
+ // The user said "save it" in chat: a later builder run created the flow.
+ // The proposal card must resume at that flow instead of creating another.
+ let temp = thread_with_delivered_proposal("Friday Inbox Wrap-up");
+ attach_workflow_proposal(
+ &crate::core::runtime::DispatchCtx::ambient(),
+ temp.path(),
+ Some("thread-parent"),
+ "sub-save",
+ "workflow_builder",
+ &[TranscriptMessage::tool(
+ r#"{"type":"workflow_created","flow_id":"flow-1","name":"Friday Inbox Wrap-up","enabled":false}"#,
+ )],
+ "saved".to_string(),
+ );
+ assert_eq!(
+ delivered_proposal_metadata(&temp)["saved_flow_id"],
+ "flow-1"
+ );
+}
+
+#[test]
+fn an_agent_save_of_another_workflow_leaves_the_proposal_alone() {
+ let temp = thread_with_delivered_proposal("Friday Inbox Wrap-up");
+ attach_workflow_proposal(
+ &crate::core::runtime::DispatchCtx::ambient(),
+ temp.path(),
+ Some("thread-parent"),
+ "sub-save",
+ "workflow_builder",
+ &[TranscriptMessage::tool(
+ r#"{"type":"workflow_saved","flow_id":"flow-9","name":"Something Else","enabled":true}"#,
+ )],
+ "saved".to_string(),
+ );
+ assert!(delivered_proposal_metadata(&temp)
+ .get("saved_flow_id")
+ .is_none());
+}
+
#[test]
fn attach_workflow_proposal_without_proposal_returns_summary_unchanged() {
let temp = tempfile::tempdir().expect("tempdir");
diff --git a/crates/openhuman-core/src/agent/orchestration/tools/spawn_subagent_surface.rs b/crates/openhuman-core/src/agent/orchestration/tools/spawn_subagent_surface.rs
index 105dfdc043..afe8c4184e 100644
--- a/crates/openhuman-core/src/agent/orchestration/tools/spawn_subagent_surface.rs
+++ b/crates/openhuman-core/src/agent/orchestration/tools/spawn_subagent_surface.rs
@@ -485,6 +485,129 @@ pub(crate) fn extract_workflow_proposal_from_history(
})
}
+/// Settle a finished child's workflow output in the parent thread: surface a
+/// proposal it produced (see [`persist_workflow_proposal`]), then record a flow
+/// it persisted onto the thread's live proposal (see
+/// [`record_agent_saved_workflow`]), in that order, so a save made in the same
+/// run settles the proposal the user is now looking at.
+fn attach_workflow_proposal(
+ ctx: &DispatchCtx,
+ workspace_dir: &std::path::Path,
+ parent_thread_id: Option<&str>,
+ task_id: &str,
+ agent_id: &str,
+ final_history: &[TranscriptMessage],
+ summary: String,
+) -> String {
+ let summary = persist_workflow_proposal(
+ ctx,
+ workspace_dir,
+ parent_thread_id,
+ task_id,
+ agent_id,
+ final_history,
+ summary,
+ );
+ if let Some(thread_id) = parent_thread_id {
+ record_agent_saved_workflow(ctx, workspace_dir, thread_id, task_id, final_history);
+ }
+ summary
+}
+
+/// The flow a finished child persisted from a proposal: the LAST
+/// `workflow_created` (`create_workflow`) or `workflow_saved` (`save_workflow`)
+/// tool result, as `(flow_id, name)`.
+pub(crate) fn extract_saved_workflow_from_history(
+ history: &[TranscriptMessage],
+) -> Option<(String, String)> {
+ history
+ .iter()
+ .rev()
+ .filter(|message| message.role == "tool")
+ .find_map(|message| {
+ let value: serde_json::Value = serde_json::from_str(message.content.trim()).ok()?;
+ let kind = value.get("type").and_then(|t| t.as_str())?;
+ if kind != "workflow_created" && kind != "workflow_saved" {
+ return None;
+ }
+ let flow_id = value.get("flow_id").and_then(|v| v.as_str())?;
+ let name = value.get("name").and_then(|v| v.as_str()).unwrap_or("");
+ Some((flow_id.to_string(), name.to_string()))
+ })
+}
+
+/// A flow the agent persisted from a delivered proposal (the user said "save
+/// it" in chat rather than clicking the card) is recorded on the thread's live
+/// proposal message as `saved_flow_id`, the same field the card writes. The
+/// card then resumes at the enable step for that flow instead of creating a
+/// second copy. Only the newest proposal message counts, and only while it is
+/// unsettled and has the saved flow's name, so an unrelated proposal is never
+/// claimed. Best-effort: a failure is logged and the delivery is unaffected.
+fn record_agent_saved_workflow(
+ ctx: &DispatchCtx,
+ workspace_dir: &std::path::Path,
+ thread_id: &str,
+ task_id: &str,
+ final_history: &[TranscriptMessage],
+) {
+ let Some((flow_id, name)) = extract_saved_workflow_from_history(final_history) else {
+ return;
+ };
+ let messages = match conversations::get_messages(ctx, workspace_dir.to_path_buf(), thread_id) {
+ Ok(messages) => messages,
+ Err(err) => {
+ log::warn!(
+ "[spawn_subagent] agent-saved workflow: could not read thread_id={thread_id} \
+ task_id={task_id} error={err}"
+ );
+ return;
+ }
+ };
+ let Some(proposal) = messages
+ .iter()
+ .rev()
+ .find(|m| m.extra_metadata["scope"] == "workflow_proposal")
+ else {
+ log::debug!(
+ "[spawn_subagent] agent-saved workflow: no proposal in thread_id={thread_id} \
+ task_id={task_id} flow_id={flow_id}"
+ );
+ return;
+ };
+ let meta = &proposal.extra_metadata;
+ let settled = meta["consumed"] == true || meta.get("saved_flow_id").is_some();
+ if settled || meta["proposal"]["name"] != name.as_str() {
+ log::debug!(
+ "[spawn_subagent] agent-saved workflow: newest proposal {} not claimed \
+ (settled={settled}) task_id={task_id} flow_id={flow_id}",
+ proposal.id
+ );
+ return;
+ }
+ let patch = conversations::ConversationMessagePatch {
+ merge_extra_metadata: Some(json!({ "saved_flow_id": flow_id })),
+ ..Default::default()
+ };
+ match conversations::update_message(
+ ctx,
+ workspace_dir.to_path_buf(),
+ thread_id,
+ &proposal.id,
+ patch,
+ ) {
+ Ok(_) => log::info!(
+ "[spawn_subagent] agent-saved workflow recorded on proposal {} \
+ flow_id={flow_id} task_id={task_id}",
+ proposal.id
+ ),
+ Err(err) => log::warn!(
+ "[spawn_subagent] agent-saved workflow: could not mark proposal {} \
+ flow_id={flow_id} task_id={task_id} error={err}",
+ proposal.id
+ ),
+ }
+}
+
/// Durably surface a workflow proposal found in a finished child's history:
/// persist it as a parent-thread conversation message (metadata carries the
/// full payload so the UI can rehydrate the proposal card after reload) and
@@ -492,7 +615,7 @@ pub(crate) fn extract_workflow_proposal_from_history(
/// follow-up turn presents it faithfully. Returns the (possibly extended)
/// summary; on any persistence error the summary still carries the envelope —
/// losing durability must not lose delivery.
-fn attach_workflow_proposal(
+fn persist_workflow_proposal(
ctx: &DispatchCtx,
workspace_dir: &std::path::Path,
parent_thread_id: Option<&str>,