Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
fix(agent-session): keep model-change work below the line (#8202)
Wolf Mermelsteindafeaefa33e8
diff --git a/apps/web/src/features/block-agent/state/live-turn.test.ts b/apps/web/src/features/block-agent/state/live-turn.test.tsindex 83fea8adb1..cc23340b17 100644--- a/apps/web/src/features/block-agent/state/live-turn.test.ts+++ b/apps/web/src/features/block-agent/state/live-turn.test.ts@@ -64,9 +64,17 @@ describe('liveTurnMessage', () => {).toBeUndefined();});- it('looks past a trailing control to the turn behind it', () => {- const tail = agent(0, null);- expect(liveTurnMessage([user(0), tail, control(1)], true)).toBe(tail);+ it('does not keep a turn live across a trailing model change', () => {+ expect(+ liveTurnMessage([user(0), agent(0, null), control(1)], true)+ ).toBeUndefined();+ });++ it('names the agent message that follows a model change', () => {+ const next = agent(2, null);+ expect(+ liveTurnMessage([user(0), agent(0, null), control(1), next], true)+ ).toBe(next);});it('is empty for an empty transcript', () => {diff --git a/apps/web/src/features/block-agent/state/live-turn.ts b/apps/web/src/features/block-agent/state/live-turn.tsindex 97631b8295..0f168c8666 100644--- a/apps/web/src/features/block-agent/state/live-turn.ts+++ b/apps/web/src/features/block-agent/state/live-turn.ts@@ -19,6 +19,16 @@import type { FoldedMessage } from '@service-agent-fold/generated/types';import { lastTurnMessage } from './control-message';+/** A model change is punctuation between turns, not beside one. */+function isTurnBoundary(message: FoldedMessage): boolean {+ const part = message.parts[0];+ return (+ message.parts.length === 1 &&+ part?.kind === 'control' &&+ part.control.kind === 'set_model'+ );+}+/** The agent message of the running turn, or nothing when no turn runs. */export function liveTurnMessage(messages: readonly FoldedMessage[],@@ -26,7 +36,15 @@ export function liveTurnMessage(): FoldedMessage | undefined {if (!working) return undefined;const last = lastTurnMessage(messages);- return last?.author.kind === 'agent' ? last : undefined;+ if (last?.author.kind !== 'agent') return undefined;+ // The fold leaves a superseded turn at `stop: null`. Looking past a+ // trailing model change would keep that turn shimmering above the line+ // while "Working" also sits below it.+ const index = messages.lastIndexOf(last);+ if (index >= 0 && messages.slice(index + 1).some(isTurnBoundary)) {+ return undefined;+ }+ return last;}/** Whether `message` is the live turn `live` names. */diff --git a/crates/folds/agent_fold/AGENTS.md b/crates/folds/agent_fold/AGENTS.mdindex 3ce65a595d..5fe1e4f4ce 100644--- a/crates/folds/agent_fold/AGENTS.md+++ b/crates/folds/agent_fold/AGENTS.md@@ -97,6 +97,10 @@ session projection carries that state to list rows without loading transcripts.returned as an error — `fold` must stay total (see `domain/fold.rs` docs).- `scripts/sanitize_recording.py` strips real-session fixtures before theyland under `fixtures/real/`; never commit an unsanitized recording.+- A user-issued `set_model` closes the open turn so later agent output gets+ a new turn id and sorts below the control line. A `set_model` with no+ `user_id` is the session applying its own model (create/resume) and draws+ no line. `set_config_option` (mode, effort) does not split a turn.## Relateddiff --git a/crates/folds/agent_fold/src/domain/fold/control.rs b/crates/folds/agent_fold/src/domain/fold/control.rsindex d833323471..d666c58cde 100644--- a/crates/folds/agent_fold/src/domain/fold/control.rs+++ b/crates/folds/agent_fold/src/domain/fold/control.rs@@ -57,12 +57,33 @@ impl FoldState {/// Emit a standalone control message. A request-backed control starts/// pending and is resolved by its response; one with no request to answer/// (a stop notification) is accepted outright.+ ///+ /// A model change is punctuation *between* turns. If one lands while a+ /// turn is open — the user switched models after sending, or a speculated+ /// prompt raced the selection — later agent output must not keep the open+ /// turn's id. The transcript sorts by turn, so that leftover id put every+ /// later chunk *above* the line.+ ///+ /// A set-model with no user is the session applying its own model+ /// (create, resume, reconnect). That is not a user action and must not+ /// draw a line, or a resumed transcript grows a "Model set to" under+ /// the history it just loaded.pub(super) fn record_control(&mut self,control: Control,request_id: Option<&RequestId>,user_id: Option<MacroUserIdStr<'static>>,) -> Option<Changed> {+ if matches!(control, Control::SetModel { .. }) && user_id.is_none() {+ return None;+ }+ if matches!(control, Control::SetModel { .. }) && self.turn.is_some() {+ // Nothing to stamp: the runtime has not ended the turn. Dropping+ // it is enough for the next agent part to open a new one after+ // this line. In-flight tool patches still find their parts by+ // session-wide tool id.+ let _ = self.close_turn(None);+ }let id = TurnId(self.turns_opened);self.turns_opened += 1;let message = self.messages.len();diff --git a/crates/folds/agent_fold/src/domain/test/fold.rs b/crates/folds/agent_fold/src/domain/test/fold.rsindex 7210f708a7..8e5ded4d0f 100644--- a/crates/folds/agent_fold/src/domain/test/fold.rs+++ b/crates/folds/agent_fold/src/domain/test/fold.rs@@ -228,6 +228,133 @@ fn folds_session_controls_as_typed_parts() {assert_eq!(messages[2].id, TurnId(2));}+/// A model change is punctuation between turns. If it is logged after the+/// prompt — the user switched models while waiting, or a startup selection+/// lands after a speculated prompt — later agent output must not keep the+/// prompt's turn id. The transcript sorts by turn, so that leftover id put+/// every later chunk above the "Model set to" line.+#[test]+fn a_model_change_puts_later_output_below_the_line() {+ let log = parse_log(concat!(+ r#"{"direction":"to_runtime","user_id":"macro|[email protected]","content":{"type":"acp","jsonrpc":"2.0","id":"p","method":"session/prompt","params":{"sessionId":"s","prompt":[{"type":"text","text":"look around"}]}}}"#,+ "\n",+ r#"{"direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","method":"session/update","params":{"sessionId":"s","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"Before the switch."}}}}}"#,+ "\n",+ r#"{"direction":"to_runtime","user_id":"macro|[email protected]","content":{"type":"acp","jsonrpc":"2.0","id":"m","method":"session/set_config_option","params":{"sessionId":"s","configId":"model","value":"opus"}}}"#,+ "\n",+ r#"{"direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","method":"session/update","params":{"sessionId":"s","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"After the switch."}}}}}"#,+ "\n",+ r#"{"direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","id":"p","result":{"stopReason":"end_turn"}}}"#,+ ));++ let messages = fold(log);+ assert_eq!(+ messages.len(),+ 4,+ "prompt, pre-change reply, model line, post-change reply"+ );+ assert_eq!(+ messages[0].parts.as_slice(),+ &[MessagePart::Text {+ text: "look around".to_owned()+ }]+ );+ assert_eq!(+ messages[1].parts.as_slice(),+ &[MessagePart::Text {+ text: "Before the switch.".to_owned()+ }]+ );+ assert_eq!(messages[1].author, Author::Agent);+ assert_eq!(messages[1].id, TurnId(0));+ assert_eq!(+ messages[2].parts.as_slice(),+ &[MessagePart::Control {+ control: Control::SetModel {+ model: "opus".to_owned()+ },+ outcome: ControlOutcome::Pending,+ }]+ );+ assert_eq!(+ messages[3].parts.as_slice(),+ &[MessagePart::Text {+ text: "After the switch.".to_owned()+ }]+ );+ assert_eq!(messages[3].author, Author::Agent);+ assert!(+ messages[3].id > messages[2].id,+ "post-change output sorts after the line, not with the prompt"+ );+ assert_eq!(messages[3].stop, Some(StopReason::EndTurn));+}++/// Same boundary when the model is chosen before the agent has spoken: the+/// reply must not inherit the prompt's turn and sort above the line.+#[test]+fn a_model_change_before_the_reply_keeps_the_reply_below_the_line() {+ let log = parse_log(concat!(+ r#"{"direction":"to_runtime","user_id":"macro|[email protected]","content":{"type":"acp","jsonrpc":"2.0","id":"p","method":"session/prompt","params":{"sessionId":"s","prompt":[{"type":"text","text":"look around"}]}}}"#,+ "\n",+ r#"{"direction":"to_runtime","user_id":"macro|[email protected]","content":{"type":"acp","jsonrpc":"2.0","id":"m","method":"session/set_config_option","params":{"sessionId":"s","configId":"model","value":"opus"}}}"#,+ "\n",+ r#"{"direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","method":"session/update","params":{"sessionId":"s","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"Working on opus."}}}}}"#,+ "\n",+ r#"{"direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","id":"p","result":{"stopReason":"end_turn"}}}"#,+ ));++ let messages = fold(log);+ assert_eq!(messages.len(), 3, "prompt, model line, reply");+ assert_eq!(+ messages[1].parts.as_slice(),+ &[MessagePart::Control {+ control: Control::SetModel {+ model: "opus".to_owned()+ },+ outcome: ControlOutcome::Pending,+ }]+ );+ assert_eq!(+ messages[2].parts.as_slice(),+ &[MessagePart::Text {+ text: "Working on opus.".to_owned()+ }]+ );+ assert_eq!(messages[2].author, Author::Agent);+ assert!(+ messages[2].id > messages[1].id,+ "the reply sorts after the model line"+ );+ assert_eq!(messages[2].stop, Some(StopReason::EndTurn));+}++/// Create, resume, and reconnect apply the session's model with no user on+/// the frame. That is not a switch the reader made, so it must not draw a+/// line under the history that just loaded.+#[test]+fn a_session_applied_model_does_not_draw_a_line() {+ let log = parse_log(concat!(+ r#"{"direction":"to_runtime","user_id":"macro|[email protected]","content":{"type":"acp","jsonrpc":"2.0","id":"p","method":"session/prompt","params":{"sessionId":"s","prompt":[{"type":"text","text":"look around"}]}}}"#,+ "\n",+ r#"{"direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","method":"session/update","params":{"sessionId":"s","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"Looking."}}}}}"#,+ "\n",+ r#"{"direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","id":"p","result":{"stopReason":"end_turn"}}}"#,+ "\n",+ r#"{"direction":"to_runtime","content":{"type":"acp","jsonrpc":"2.0","id":"m","method":"session/set_config_option","params":{"sessionId":"s","configId":"model","value":"opus"}}}"#,+ ));++ let messages = fold(log);+ assert_eq!(messages.len(), 2, "prompt and reply; no model line");+ assert!(+ messages+ .iter()+ .flat_map(|message| message.parts.iter())+ .all(|part| !matches!(part, MessagePart::Control { .. })),+ "a session-applied model is not a control line"+ );+}+/// `/compact` is a message to every harness: the transcript shows what the/// agent did, not what someone asked for. A compaction shows when the agent/// reports one, at the point in the turn it landed, which carries on after it@@ -376,7 +503,7 @@ fn a_stop_after_the_agent_speaks_stamps_the_message_it_has() {#[test]fn a_rejected_control_reports_the_runtime_error() {let log = parse_log(concat!(- r#"{"direction":"to_runtime","content":{"type":"acp","jsonrpc":"2.0","id":"01920000-0000-7000-8000-0000000000a1","method":"session/set_config_option","params":{"sessionId":"s","configId":"model","value":"claude-fable-5"}}}"#,+ r#"{"direction":"to_runtime","user_id":"macro|[email protected]","content":{"type":"acp","jsonrpc":"2.0","id":"01920000-0000-7000-8000-0000000000a1","method":"session/set_config_option","params":{"sessionId":"s","configId":"model","value":"claude-fable-5"}}}"#,"\n",r#"{"direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","id":"01920000-0000-7000-8000-0000000000a1","error":{"code":-32602,"message":"Invalid params: model not found: claude-fable-5"}}}"#,));@@ -402,7 +529,7 @@ fn a_rejected_control_reports_the_runtime_error() {#[test]fn an_accepted_control_resolves_and_the_same_frame_moves_the_metadata() {let log = parse_log(concat!(- r#"{"direction":"to_runtime","content":{"type":"acp","jsonrpc":"2.0","id":"01920000-0000-7000-8000-0000000000a1","method":"session/set_config_option","params":{"sessionId":"s","configId":"model","value":"opus"}}}"#,+ r#"{"direction":"to_runtime","user_id":"macro|[email protected]","content":{"type":"acp","jsonrpc":"2.0","id":"01920000-0000-7000-8000-0000000000a1","method":"session/set_config_option","params":{"sessionId":"s","configId":"model","value":"opus"}}}"#,"\n",r#"{"direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","id":"01920000-0000-7000-8000-0000000000a1","result":{"configOptions":[{"id":"model","name":"Model","type":"select","currentValue":"opus","options":[{"value":"opus","name":"Opus"}]}]}}}"#,));diff --git a/crates/folds/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@command_invocation.jsonl.snap b/crates/folds/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@command_invocation.jsonl.snapindex 161f599a6a..c544dfde28 100644--- a/crates/folds/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@command_invocation.jsonl.snap+++ b/crates/folds/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@command_invocation.jsonl.snap@@ -8,32 +8,6 @@ input_file: crates/folds/agent_fold/fixtures/real/command_invocation.jsonlid: TurnId(0,),- author: User {- user_id: None,- },- request_id: Some(- AgentActionId(- b544d9a7-b4f6-4452-b797-dc15b0ee442e,- ),- ),- parts: NonEmpty {- inner: [- Control {- control: SetModel {- model: "opus[1m]",- },- outcome: Accepted,- },- ],- },- stop: None,- pending: false,- posted_at: None,- },- FoldedMessage {- id: TurnId(- 1,- ),author: User {user_id: Some(macro|[email protected],@@ -57,7 +31,7 @@ input_file: crates/folds/agent_fold/fixtures/real/command_invocation.jsonl},FoldedMessage {id: TurnId(- 1,+ 0,),author: Agent,request_id: None,diff --git a/crates/folds/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@plan_todo.jsonl.snap b/crates/folds/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@plan_todo.jsonl.snapindex a2069f72c3..46d4145b35 100644--- a/crates/folds/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@plan_todo.jsonl.snap+++ b/crates/folds/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@plan_todo.jsonl.snap@@ -8,32 +8,6 @@ input_file: crates/folds/agent_fold/fixtures/real/plan_todo.jsonlid: TurnId(0,),- author: User {- user_id: None,- },- request_id: Some(- AgentActionId(- 826d1392-b8c8-4208-8f79-856aa3c17b0b,- ),- ),- parts: NonEmpty {- inner: [- Control {- control: SetModel {- model: "opus[1m]",- },- outcome: Accepted,- },- ],- },- stop: None,- pending: false,- posted_at: None,- },- FoldedMessage {- id: TurnId(- 1,- ),author: User {user_id: Some(macro|[email protected],@@ -57,7 +31,7 @@ input_file: crates/folds/agent_fold/fixtures/real/plan_todo.jsonl},FoldedMessage {id: TurnId(- 1,+ 0,),author: Agent,request_id: None,diff --git a/crates/folds/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@real_multi_turn.jsonl.snap b/crates/folds/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@real_multi_turn.jsonl.snapindex 1102c93bbe..c849c54ea0 100644--- a/crates/folds/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@real_multi_turn.jsonl.snap+++ b/crates/folds/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@real_multi_turn.jsonl.snap@@ -780,32 +780,6 @@ input_file: crates/folds/agent_fold/fixtures/real/real_multi_turn.jsonlauthor: User {user_id: None,},- request_id: Some(- AgentActionId(- 27e3ed1d-3814-4805-abd6-92bbc9bcf3cc,- ),- ),- parts: NonEmpty {- inner: [- Control {- control: SetModel {- model: "opus[1m]",- },- outcome: Accepted,- },- ],- },- stop: None,- pending: false,- posted_at: None,- },- FoldedMessage {- id: TurnId(- 4,- ),- author: User {- user_id: None,- },request_id: Some(AgentActionId(cfe33ce9-7db9-4865-9e67-dea14b35f54d,@@ -828,7 +802,7 @@ input_file: crates/folds/agent_fold/fixtures/real/real_multi_turn.jsonl},FoldedMessage {id: TurnId(- 5,+ 4,),author: User {user_id: Some(@@ -853,7 +827,7 @@ input_file: crates/folds/agent_fold/fixtures/real/real_multi_turn.jsonl},FoldedMessage {id: TurnId(- 5,+ 4,),author: Agent,request_id: None,diff --git a/crates/folds/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@resumed_no_prompt.jsonl.snap b/crates/folds/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@resumed_no_prompt.jsonl.snapindex c925b3bebc..4f2badaf0b 100644--- a/crates/folds/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@resumed_no_prompt.jsonl.snap+++ b/crates/folds/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@resumed_no_prompt.jsonl.snap@@ -3700,32 +3700,6 @@ input_file: crates/folds/agent_fold/fixtures/real/resumed_no_prompt.jsonlauthor: User {user_id: None,},- request_id: Some(- AgentActionId(- 482c3d39-c381-4809-874c-fe00bc757345,- ),- ),- parts: NonEmpty {- inner: [- Control {- control: SetModel {- model: "opus[1m]",- },- outcome: Accepted,- },- ],- },- stop: None,- pending: false,- posted_at: None,- },- FoldedMessage {- id: TurnId(- 8,- ),- author: User {- user_id: None,- },request_id: Some(AgentActionId(0937d42c-b2e1-49fe-bd3f-4914ae2075e2,diff --git a/crates/folds/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@subagent_claude_code.jsonl.snap b/crates/folds/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@subagent_claude_code.jsonl.snapindex d2e1b02aa5..f1d679a758 100644--- a/crates/folds/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@subagent_claude_code.jsonl.snap+++ b/crates/folds/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@subagent_claude_code.jsonl.snap@@ -8,32 +8,6 @@ input_file: crates/folds/agent_fold/fixtures/real/subagent_claude_code.jsonlid: TurnId(0,),- author: User {- user_id: None,- },- request_id: Some(- AgentActionId(- 56062802-48df-4dca-b98d-966c762ee74c,- ),- ),- parts: NonEmpty {- inner: [- Control {- control: SetModel {- model: "opus[1m]",- },- outcome: Accepted,- },- ],- },- stop: None,- pending: false,- posted_at: None,- },- FoldedMessage {- id: TurnId(- 1,- ),author: User {user_id: Some(macro|[email protected],@@ -57,7 +31,7 @@ input_file: crates/folds/agent_fold/fixtures/real/subagent_claude_code.jsonl},FoldedMessage {id: TurnId(- 1,+ 0,),author: Agent,request_id: None,diff --git a/crates/folds/agent_fold/src/testing.rs b/crates/folds/agent_fold/src/testing.rsindex ca1bd005fc..bfe4a478fb 100644--- a/crates/folds/agent_fold/src/testing.rs+++ b/crates/folds/agent_fold/src/testing.rs@@ -114,11 +114,22 @@ fn parse_line(session: AgentSessionId, line: &str) -> AgentSessionLog {));+ // Prompts keep the historic fixture user so existing assertions stay put.+ // Other user-originated frames (a model change) take `user_id` from the+ // line when the recording has one, so tests can tell them apart from a+ // session-applied set-model that has no user.+ let user_id = if is_prompt {+ Some(MacroUserIdStr::try_from_email("[email protected]").expect("test email parses"))+ } else {+ value+ .get("user_id")+ .and_then(|id| id.as_str())+ .and_then(|id| MacroUserIdStr::try_from(id.to_owned()).ok())+ };+AgentSessionLog {agent_session_id: session,- user_id: is_prompt.then(|| {- MacroUserIdStr::try_from_email("[email protected]").expect("test email parses")- }),+ user_id,content,logged_at: None,}diff --git a/docs/agent-guide/ai-chat.md b/docs/agent-guide/ai-chat.mdindex 0528ac690b..082cbb3164 100644--- a/docs/agent-guide/ai-chat.md+++ b/docs/agent-guide/ai-chat.md@@ -70,8 +70,12 @@ later chunks can arrive in batches. Reasoning or a tool row should not delay thefirst prose. Verify a second prompt and a reload preserve the complete answer.A model selected before the first prompt is part of the create request, and theruntime starts on it; no model change appears in the new session's transcript.-A selected effort is confirmed before the first prompt; settings the runtime-already reports do not need another control request.+Resuming or reconnecting a session also applies its saved model without a+line — that is not a switch the user made. A selected effort is confirmed+before the first prompt; settings the runtime already reports do not need+another control request.+A model the user picks mid-session is a line between turns. Work from before+the change stays above it; anything the agent says after appears below it.Macro's in-process agent opens each reply with a line from a fast model(`gpt-5.4-mini`), usually within half a second of Enter. Small talk