Skip to content

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

fix(flows): settle proposals from this run only, and only by a later save

M3gA-Mindf879024773f4
diff --git a/app/src/components/chat/WorkflowProposalCard.test.tsx b/app/src/components/chat/WorkflowProposalCard.test.tsx
index c76388068e..d5c24af70e 100644
--- a/app/src/components/chat/WorkflowProposalCard.test.tsx
+++ b/app/src/components/chat/WorkflowProposalCard.test.tsx
@@ -430,6 +430,20 @@ describe('WorkflowProposalCard', () => {
expect(mockGetThreadMessages).toHaveBeenCalledWith('t1');
});
+ it('does not persist when it cannot check for an already-saved flow', async () => {
+ mockGetThreadMessages.mockRejectedValueOnce(new Error('core unavailable'));
+ render(
+ <WorkflowProposalCard
+ threadId="t1"
+ proposal={proposal({ sourceMessageId: 'workflow-proposal:sub-1' })}
+ />
+ );
+ fireEvent.click(screen.getByText('chat.flowProposal.save'));
+ await waitFor(() => expect(screen.getByText(/chat\.flowProposal\.error/)).toBeInTheDocument());
+ expect(mockCreateFlow).not.toHaveBeenCalled();
+ expect(mockUpdateFlow).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'));
diff --git a/app/src/components/chat/WorkflowProposalCard.tsx b/app/src/components/chat/WorkflowProposalCard.tsx
index 4bd6e02177..be2aeccec2 100644
--- a/app/src/components/chat/WorkflowProposalCard.tsx
+++ b/app/src/components/chat/WorkflowProposalCard.tsx
@@ -237,18 +237,14 @@ const WorkflowProposalCard: React.FC<Props> = ({ threadId, proposal, onSaved })
* 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.
+ * `null` when nothing is recorded; a failed read throws, because treating it
+ * as "nothing recorded" could create a second copy of a saved flow.
*/
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 { 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;
};
const markCompleted = (flowId: string) => {
@@ -298,7 +294,15 @@ const WorkflowProposalCard: React.FC<Props> = ({ threadId, proposal, onSaved })
let flowId = savedFlowId;
let flowPersisted = flowId !== null;
if (!flowId) {
- const recorded = await recordedSavedFlowId();
+ let recorded: string | null;
+ try {
+ recorded = await recordedSavedFlowId();
+ } catch (e) {
+ log('save: could not check for an already-saved flow — not persisting: %o', e);
+ setErrorMsg(t('chat.flowProposal.error'));
+ setSaving(false);
+ return;
+ }
if (recorded) {
log('save: flow %s already saved for this proposal — resuming at enable', recorded);
flowId = recorded;
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 58c19d61d2..47d7dae1fd 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
@@ -326,6 +326,74 @@ fn an_agent_save_of_another_workflow_leaves_the_proposal_alone() {
.is_none());
}
+#[test]
+fn a_save_followed_by_a_revision_does_not_settle_the_revision() {
+ // The run saved "Digest", then proposed a revised "Digest": the earlier
+ // save must not be recorded on the revision, or the card would enable the
+ // old flow and drop the revised graph.
+ let history = vec![
+ TranscriptMessage::tool(
+ r#"{"type":"workflow_saved","flow_id":"flow-old","name":"Digest","enabled":true}"#,
+ ),
+ TranscriptMessage::tool(
+ r#"{"type":"workflow_proposal","persisted":false,"name":"Digest","graph":{"nodes":[],"edges":[]}}"#,
+ ),
+ ];
+ assert!(extract_saved_workflow_from_history(&history).is_none());
+}
+
+#[test]
+fn a_reused_session_settles_the_delivered_proposal_without_duplicating_it() {
+ // Turn 1 delivered the proposal; the continuation (same task_key) only
+ // saved it. The runner returns the whole session history, turn 1 included.
+ let temp = thread_with_delivered_proposal("Friday Inbox Wrap-up");
+ let seed = vec![
+ TranscriptMessage::user("build it"),
+ TranscriptMessage::tool(
+ r#"{"type":"workflow_proposal","persisted":false,"name":"Friday Inbox Wrap-up","graph":{"nodes":[],"edges":[]}}"#,
+ ),
+ TranscriptMessage::user("save it"),
+ ];
+ let mut full = seed.clone();
+ full.push(TranscriptMessage::tool(
+ r#"{"type":"workflow_created","flow_id":"flow-1","name":"Friday Inbox Wrap-up","enabled":false}"#,
+ ));
+
+ let summary = attach_workflow_proposal(
+ &crate::core::runtime::DispatchCtx::ambient(),
+ temp.path(),
+ Some("thread-parent"),
+ "sub-save",
+ "workflow_builder",
+ this_run_history(&full, seed.len()),
+ "saved".to_string(),
+ );
+
+ // Turn 1's proposal is not re-delivered or re-persisted...
+ assert!(!summary.contains("[workflow_proposal]"));
+ let messages = conversations::get_messages(
+ &crate::core::runtime::DispatchCtx::ambient(),
+ temp.path().to_path_buf(),
+ "thread-parent",
+ )
+ .expect("messages");
+ assert!(!messages
+ .iter()
+ .any(|m| m.id == "workflow-proposal:sub-save"));
+ // ...and the save settles the proposal the card shows.
+ assert_eq!(
+ delivered_proposal_metadata(&temp)["saved_flow_id"],
+ "flow-1"
+ );
+}
+
+#[test]
+fn a_history_shorter_than_its_seed_is_used_whole() {
+ let history = vec![TranscriptMessage::user("compacted")];
+ assert_eq!(this_run_history(&history, 3).len(), 1);
+ assert!(this_run_history(&history, 1).is_empty());
+}
+
#[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_completion.rs b/crates/openhuman-core/src/agent/orchestration/tools/spawn_subagent_completion.rs
index 83237ffae0..155d594187 100644
--- a/crates/openhuman-core/src/agent/orchestration/tools/spawn_subagent_completion.rs
+++ b/crates/openhuman-core/src/agent/orchestration/tools/spawn_subagent_completion.rs
@@ -101,6 +101,7 @@ pub(super) fn make_completion(
background_store: Arc<dyn tinyagents_orchestration::subagent::SubagentSessionStore>,
background_subagent_session_id: String,
background_parent_thread_id: Option<String>,
+ seed_len: usize,
) -> impl Fn(
String,
Result<SubagentRunOutcome, String>,
@@ -182,7 +183,7 @@ pub(super) fn make_completion(
background_parent_thread_id.as_deref(),
&outcome.task_id,
&outcome.agent_id,
- &outcome.final_history,
+ this_run_history(&outcome.final_history, seed_len),
outcome.output.clone(),
);
completion_target
@@ -257,7 +258,7 @@ pub(super) fn make_completion(
background_parent_thread_id.as_deref(),
&outcome.task_id,
&outcome.agent_id,
- &outcome.final_history,
+ this_run_history(&outcome.final_history, seed_len),
framed,
);
completion_target
diff --git a/crates/openhuman-core/src/agent/orchestration/tools/spawn_subagent_host_impl.rs b/crates/openhuman-core/src/agent/orchestration/tools/spawn_subagent_host_impl.rs
index 5255203f89..d294a72c77 100644
--- a/crates/openhuman-core/src/agent/orchestration/tools/spawn_subagent_host_impl.rs
+++ b/crates/openhuman-core/src/agent/orchestration/tools/spawn_subagent_host_impl.rs
@@ -298,6 +298,7 @@ impl SpawnSubagentTool {
driver_store.clone(),
resumed_session.subagent_session_id.clone(),
parent_thread_id.clone(),
+ 0,
);
let options = SubagentRunOptions {
skill_filter_override: checkpoint.skill_filter_override,
@@ -652,6 +653,9 @@ impl SpawnSubagentTool {
let registration_parent_session = parent_session.clone();
let registration_agent_id = definition.id.clone();
let registration_task_id = task_id.clone();
+ // A reused session's run starts from its stored history; only what
+ // this run adds may be read for its proposals and saves.
+ let seed_len = initial_history.as_ref().map_or(0, Vec::len);
let completion = completion::make_completion(
completion_core,
completion_origin,
@@ -667,6 +671,7 @@ impl SpawnSubagentTool {
background_store,
background_subagent_session_id,
background_parent_thread_id,
+ seed_len,
);
let background_prompt = add_background_contract(&prompt);
let options = SubagentRunOptions {
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 afe8c4184e..a07c482562 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
@@ -514,26 +514,63 @@ fn attach_workflow_proposal(
summary
}
+/// The part of a finished child's history this run produced. A reused session
+/// starts from its stored history (`seed_len` messages, the follow-up prompt
+/// included) and returns it whole, so an earlier turn's proposal or save would
+/// otherwise be found again: re-persisted as a duplicate proposal message, or
+/// recorded against a later proposal. A history shorter than its seed (it was
+/// compacted) cannot be split and is used whole, as before.
+pub(crate) fn this_run_history(
+ history: &[TranscriptMessage],
+ seed_len: usize,
+) -> &[TranscriptMessage] {
+ match history.get(seed_len..) {
+ Some(run) => run,
+ None => {
+ log::debug!(
+ "[spawn_subagent] history ({} messages) shorter than its seed ({seed_len}); using it whole",
+ history.len()
+ );
+ history
+ }
+ }
+}
+
/// 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)`.
+/// tool result, as `(flow_id, name)`. `None` when the run produced a proposal
+/// after that save: the save then belongs to an earlier graph, not to the
+/// revision now in front of the user.
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()))
- })
+ let tool_payload = |message: &TranscriptMessage| -> Option<serde_json::Value> {
+ (message.role == "tool")
+ .then(|| serde_json::from_str(message.content.trim()).ok())
+ .flatten()
+ };
+ let kind_of = |value: &serde_json::Value| -> Option<String> {
+ value
+ .get("type")
+ .and_then(|t| t.as_str())
+ .map(str::to_string)
+ };
+ let (save_at, saved) = history.iter().enumerate().rev().find_map(|(at, message)| {
+ let value = tool_payload(message)?;
+ let kind = kind_of(&value)?;
+ (kind == "workflow_created" || kind == "workflow_saved").then_some((at, value))
+ })?;
+ let proposed_later = history[save_at + 1..].iter().any(|message| {
+ tool_payload(message)
+ .and_then(|value| kind_of(&value))
+ .is_some_and(|kind| kind == "workflow_proposal")
+ });
+ if proposed_later {
+ return None;
+ }
+ let flow_id = saved.get("flow_id").and_then(|v| v.as_str())?;
+ let name = saved.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