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(agents): keep the model selector usable when a switch goes unconfirmed (#9310)
Wolf Mermelsteinf7bc0f5186c5
diff --git a/apps/web/src/features/block-agent/context/configure-session-model.ts b/apps/web/src/features/block-agent/context/configure-session-model.tsindex 307d92c081..c959ee6267 100644--- a/apps/web/src/features/block-agent/context/configure-session-model.ts+++ b/apps/web/src/features/block-agent/context/configure-session-model.ts@@ -49,7 +49,10 @@ export function sessionConfigReported(/** Validate against the model's confirmed runtime snapshot before setting effort. */export async function configureSessionModel(- session: Pick<AgentSession, 'issue' | 'snapshot' | 'subscribe'>,+ session: Pick<+ AgentSession,+ 'id' | 'issue' | 'snapshot' | 'subscribe' | 'refresh' | 'retract'+ >,model: string | undefined,effort?: EffortSelection) {diff --git a/apps/web/src/features/block-agent/context/confirm-session-control.test.ts b/apps/web/src/features/block-agent/context/confirm-session-control.test.tsindex 75c6c240e0..2a0c9b5377 100644--- a/apps/web/src/features/block-agent/context/confirm-session-control.test.ts+++ b/apps/web/src/features/block-agent/context/confirm-session-control.test.ts@@ -16,11 +16,25 @@ function session() {listener = callback;return unsubscribe;}),+ refresh: vi.fn(async () => {}),+ retract: vi.fn(),};return {value: value as unknown as AgentSession,issue: value.issue,+ refresh: value.refresh,+ retract: value.retract,unsubscribe,+ /** Settle the control in the snapshot without a fold event. */+ settleQuietly(kind: string) {+ snapshot.messages = [+ {+ requestId: 'action',+ pending: false,+ parts: [{ kind: 'control', outcome: { kind } }],+ },+ ];+ },outcome(kind: string, requestId = 'action') {snapshot.messages = [{@@ -73,15 +87,43 @@ describe('confirmed session controls', () => {await assertion;expect(test.unsubscribe).toHaveBeenCalledOnce();});- it('times out without treating silence as acceptance', async () => {+ it('times out without treating silence as acceptance, and takes the control back', async () => {vi.useFakeTimers();const test = session();const result = confirmSessionControl(test.value, action);const assertion = expect(result).rejects.toThrow('did not confirm');await vi.advanceTimersByTimeAsync(60_000);await assertion;+ expect(test.refresh).toHaveBeenCalledTimes(2);+ expect(test.retract).toHaveBeenCalledExactlyOnceWith('action');expect(test.unsubscribe).toHaveBeenCalledOnce();});+ it('gives up on time even when the final log read never answers', async () => {+ vi.useFakeTimers();+ const test = session();+ test.refresh.mockImplementation(() => new Promise(() => {}));+ const result = confirmSessionControl(test.value, action);+ const assertion = expect(result).rejects.toThrow('did not confirm');+ await vi.advanceTimersByTimeAsync(70_000);+ await assertion;+ expect(test.retract).toHaveBeenCalledExactlyOnceWith('action');+ });+ it('confirms from the refetched log when the live feed missed the answer', async () => {+ vi.useFakeTimers();+ const test = session();+ const done = vi.fn();+ test.refresh.mockImplementation(async () => test.settleQuietly('accepted'));+ const result = confirmSessionControl(test.value, action).then(done);+ await vi.advanceTimersByTimeAsync(9_999);+ expect(test.refresh).not.toHaveBeenCalled();+ expect(done).not.toHaveBeenCalled();+ await vi.advanceTimersByTimeAsync(1);+ await result;+ expect(done).toHaveBeenCalledOnce();+ expect(test.retract).not.toHaveBeenCalled();+ await vi.advanceTimersByTimeAsync(60_000);+ expect(test.refresh).toHaveBeenCalledOnce();+ });it('fails immediately on HTTP rejection', async () => {const test = session();test.issue.mockResolvedValue(err([{ message: 'disconnected' }]));diff --git a/apps/web/src/features/block-agent/context/confirm-session-control.ts b/apps/web/src/features/block-agent/context/confirm-session-control.tsindex e4ef850260..96c864df61 100644--- a/apps/web/src/features/block-agent/context/confirm-session-control.ts+++ b/apps/web/src/features/block-agent/context/confirm-session-control.ts@@ -1,22 +1,67 @@import type { AgentSession } from '@core/agent-session/AgentSession';import { fireAndForget } from '@core/util/fireAndForget';+import { type Span, Telemetry } from '@macro-inc/observability';import type { AgentAction } from '@service-agent-harness/generated/schemas';import { issueSessionAction } from '../queries/issue-session-action';-/** HTTP acceptance only queues a control. Wait for its correlated ACP outcome. */-export async function confirmSessionControl(- session: Pick<AgentSession, 'issue' | 'snapshot' | 'subscribe'>,+/** Unanswered this long, the log is read directly in case the live feed missed it. */+const REFRESH_AFTER_MS = 10_000;+const GIVE_UP_AFTER_MS = 60_000;+/** A final reread still out after this is abandoned so giving up cannot hang. */+const FINAL_REREAD_MAX_MS = 10_000;++/**+ * HTTP acceptance only queues a control. Wait for its correlated ACP outcome.+ *+ * The outcome reaches the fold through the live log feed, which can miss+ * rows while a sandbox wakes. Unanswered, the log is refetched once early and+ * again before giving up. A control the log still has not settled is+ * retracted when this gives up, so the selector shows the runtime's own model+ * and accepts another choice rather than holding the change in flight.+ */+export function confirmSessionControl(+ session: Pick<+ AgentSession,+ 'id' | 'issue' | 'snapshot' | 'subscribe' | 'refresh' | 'retract'+ >,action: AgentAction+): Promise<void> {+ return Telemetry.span('agent.session.confirm_control', async (span) => {+ span.setAttr('agent.session.id', session.id);+ span.setAttr('agent.control.type', action.type);+ try {+ await awaitConfirmation(session, action, span);+ } catch (error) {+ span.error(error);+ throw error;+ }+ });+}++async function awaitConfirmation(+ session: Pick<+ AgentSession,+ 'issue' | 'snapshot' | 'subscribe' | 'refresh' | 'retract'+ >,+ action: AgentAction,+ span: Span): Promise<void> {const result = await issueSessionAction(session, action);- if (result.isErr())+ if (result.isErr()) {+ span.setAttr('agent.control.outcome', 'refused');throw new Error(result.error.map((error) => error.message).join(' '));+ }const actionId = result.value.actionId;+ span.setAttr('agent.action.id', actionId);+ let refreshes = 0;+ let settledBy: 'feed' | 'refresh' = 'feed';await new Promise<void>((resolve, reject) => {let finished = false;const finish = (error?: Error) => {if (finished) return;finished = true;+ span.setAttr('agent.control.refreshes', refreshes);+ clearTimeout(refresh);clearTimeout(timeout);unsubscribe();if (error) reject(error);@@ -31,6 +76,8 @@ export async function confirmSessionControl(if (!message || message.pending) return;const part = message.parts.find((part) => part.kind === 'control');if (part?.kind !== 'control' || part.outcome.kind === 'pending') return;+ span.setAttr('agent.control.outcome', part.outcome.kind);+ span.setAttr('agent.control.settled_by', settledBy);finish(part.outcome.kind === 'rejected'? new Error(part.outcome.message)@@ -44,10 +91,38 @@ export async function confirmSessionControl();}};+ const reread = async () => {+ refreshes += 1;+ await session.refresh();+ settledBy = 'refresh';+ await inspect();+ settledBy = 'feed';+ };+ const giveUp = async () => {+ let bound: ReturnType<typeof setTimeout> | undefined;+ try {+ await Promise.race([+ reread(),+ new Promise<void>((resolve) => {+ bound = setTimeout(resolve, FINAL_REREAD_MAX_MS);+ }),+ ]);+ } finally {+ clearTimeout(bound);+ if (!finished) {+ session.retract(actionId);+ span.setAttr('agent.control.outcome', 'retracted');+ finish(new Error('The agent did not confirm the selected setting.'));+ }+ }+ };+ const refresh = setTimeout(+ () => fireAndForget(reread(), 'agent-session'),+ REFRESH_AFTER_MS+ );const timeout = setTimeout(- () =>- finish(new Error('The agent did not confirm the selected setting.')),- 60_000+ () => fireAndForget(giveUp(), 'agent-session'),+ GIVE_UP_AFTER_MS);const unsubscribe = session.subscribe(() =>fireAndForget(inspect(), 'agent-session')diff --git a/apps/web/src/features/block-agent/context/create-agent-session.ts b/apps/web/src/features/block-agent/context/create-agent-session.tsindex e8165583e3..dc877a236f 100644--- a/apps/web/src/features/block-agent/context/create-agent-session.ts+++ b/apps/web/src/features/block-agent/context/create-agent-session.ts@@ -381,10 +381,13 @@ export function createAgentSession(if (!current) throw new Error('The agent session is not ready.');await configureSessionModel({+ id: current.id,issue: (action) =>issueSessionAction(current, action, { userId: options.userId() }),snapshot: () => current.snapshot(),subscribe: (listener) => current.subscribe(listener),+ refresh: () => current.refresh(),+ retract: (actionId) => current.retract(actionId),},model,effortdiff --git a/apps/web/src/lib/core/agent-session/AgentSession.test.ts b/apps/web/src/lib/core/agent-session/AgentSession.test.tsindex 440124ed22..820df933bf 100644--- a/apps/web/src/lib/core/agent-session/AgentSession.test.ts+++ b/apps/web/src/lib/core/agent-session/AgentSession.test.ts@@ -716,6 +716,40 @@ describe('AgentSession', () => {live.release();});+ it('refreshes on request and resolves once the refetched log is folded', async () => {+ const live = AgentSession.acquire(SESSION);+ await live.load();+ const refetch = deferred<LogSnapshot>();+ logSource.fetched.mockReturnValueOnce(refetch.promise);+ const done = vi.fn();+ const refreshed = live.refresh().then(done);+ // A second request while the first is out rides the same run.+ const joined = live.refresh().then(done);+ await settle();+ expect(done).not.toHaveBeenCalled();+ logSource.fetched.mockResolvedValueOnce(logOf([row(1), row(2), row(3)]));+ refetch.resolve(logOf([row(1), row(2)]));+ await Promise.all([refreshed, joined]);+ expect(done).toHaveBeenCalledTimes(2);+ expect(inputs().at(-1)).toEqual({+ kind: 'snapshot',+ rows: [row(1), row(2), row(3)],+ });+ live.release();+ });++ it('resolves a refresh whose fetch fails, leaving the fold as it was', async () => {+ const live = AgentSession.acquire(SESSION);+ await live.load();+ const before = inputs();+ logSource.fetched.mockRejectedValueOnce(+ new logSource.Unavailable(SESSION, 'failed')+ );+ await live.refresh();+ expect(inputs()).toEqual(before);+ live.release();+ });+/** A fold whose turn state is `state` from the moment it loads. */const loadedWith = async (state: string) => {fold.readSession.mockResolvedValue({diff --git a/apps/web/src/lib/core/agent-session/AgentSession.ts b/apps/web/src/lib/core/agent-session/AgentSession.tsindex 1751f9f271..21616bd8f2 100644--- a/apps/web/src/lib/core/agent-session/AgentSession.ts+++ b/apps/web/src/lib/core/agent-session/AgentSession.ts@@ -241,7 +241,8 @@ export class AgentSession {private readonly unsubscribeSocket: () => void;private readonly unsubscribeUpdated: () => void;private readonly unsubscribeReconnected: () => void;- private syncing = false;+ /** The refetch in flight; it loops while another is requested. */+ private syncRun?: Promise<void>;private resyncRequested = false;private resyncRetry = 0;private resyncTimer?: ReturnType<typeof setTimeout>;@@ -825,20 +826,46 @@ export class AgentSession {});}+ /**+ * Refetch the log and fold it, resolving once a fetch that started after+ * this call has been folded. For a caller that has waited on a row the+ * live feed should have delivered: the log itself settles the question.+ * A failed fetch resolves too, leaving the fold as it was.+ */+ refresh(): Promise<void> {+ return this.resync();+ }+/*** A reopened socket is a new socket session: rows may have been missed* while it was down. Refetch, and let the machine reconcile the overlap* and settle any speculation the log confirmed meanwhile.*/- private async resync(retrying = false): Promise<void> {- if (this.closed) return;+ private resync(retrying = false): Promise<void> {+ if (this.closed) return Promise.resolve();if (!retrying) {clearTimeout(this.resyncTimer);this.resyncRetry = 0;}this.resyncRequested = true;- if (!this.ready || this.syncing) return;- this.syncing = true;+ // The run in flight fetches again before it ends.+ if (this.syncRun) return this.syncRun;+ if (!this.ready) return this.afterLoad();+ this.syncRun = this.runResync();+ return this.syncRun;+ }++ /** The load in flight starts a run after its snapshot; a failed one never does. */+ private async afterLoad(): Promise<void> {+ try {+ await this.loading;+ } catch {+ return;+ }+ await this.syncRun;+ }++ private async runResync(): Promise<void> {this.ready = false;let failed = false;try {@@ -863,9 +890,9 @@ export class AgentSession {// A snapshot may predate frames received during its fetch. Replay those// frames after it, retaining speculation and the fold's overlap deduping.await this.drainBuffered();- this.syncing = false;+ this.syncRun = undefined;if (!this.closed && this.resyncRequested) {- fireAndForget(this.resync(true), 'agent-session');+ await this.resync(true);} else if (!this.closed && failed) {const delay = RESYNC_RETRY_DELAYS_MS[this.resyncRetry++];if (delay !== undefined)diff --git a/crates/folds/agent_fold/src/domain/speculation/test.rs b/crates/folds/agent_fold/src/domain/speculation/test.rsindex a372ae69f6..00e373ad22 100644--- a/crates/folds/agent_fold/src/domain/speculation/test.rs+++ b/crates/folds/agent_fold/src/domain/speculation/test.rs@@ -862,3 +862,74 @@ fn permission_answers_speculate_once_and_promote_on_the_agents_request_id() {assert!(fold.metadata().pending_interactions.is_empty());assert_eq!(fold.metadata().turn, TurnState::Running);}++/// A model switch on a disconnected session: the harness wakes the runtime+/// (`initialize`, `session/load` and its replay) and only then logs the+/// change. The speculated control must promote and settle, or the composer+/// reads the switch as forever in flight.+#[test]+fn a_model_change_that_wakes_the_runtime_settles_after_the_load() {+ let mut fold = settled();+ let disconnected =+ parse_log(r#"{"direction":"to_server","content":{"type":"event","event":"disconnected"}}"#)+ .remove(0);+ fold.push(FoldInput::Confirmed(cursor(90), disconnected))+ .unwrap();++ let id = AgentActionId::mint();+ let change = AgentAction::set_model("gpt");+ fold.push(speculation(change.clone(), id)).unwrap();++ let options = |current: &str| {+ format!(+ r#"{{"configOptions":[{{"id":"model","name":"Model","type":"select","category":"model","currentValue":"{current}","options":[{{"name":"Claude","value":"claude"}},{{"name":"GPT","value":"gpt"}}]}}]}}"#+ )+ };+ let wake = [+ r#"{"direction":"to_runtime","content":{"type":"acp","jsonrpc":"2.0","id":"wake:0","method":"initialize","params":{"protocolVersion":1}}}"#.to_owned(),+ r#"{"direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","id":"wake:0","result":{"protocolVersion":1,"agentCapabilities":{"loadSession":true}}}}"#.to_owned(),+ r#"{"direction":"to_runtime","content":{"type":"acp","jsonrpc":"2.0","id":"wake:1","method":"session/load","params":{"sessionId":"s1","cwd":"/","mcpServers":[]}}}"#.to_owned(),+ r#"{"direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","method":"session/update","params":{"sessionId":"s1","update":{"sessionUpdate":"user_message_chunk","content":{"type":"text","text":"list the examples and write a file"}}}}}"#.to_owned(),+ r#"{"direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","method":"session/update","params":{"sessionId":"s1","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"Done."}}}}}"#.to_owned(),+ r#"{"direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","method":"_session/turn_complete","params":{"sessionId":"s1","outcome":{"kind":"finished"}}}}"#.to_owned(),+ format!(+ r#"{{"direction":"to_server","content":{{"type":"acp","jsonrpc":"2.0","id":"wake:1","result":{}}}}}"#,+ options("claude")+ ),+ ];+ for (index, line) in wake.iter().enumerate() {+ fold.push(FoldInput::Confirmed(+ cursor(100 + index),+ parse_log(line).remove(0),+ ))+ .unwrap();+ }+ fold.push(FoldInput::Confirmed(cursor(200), logged(&change, id)))+ .unwrap();+ let answer = format!(+ r#"{{"direction":"to_server","content":{{"type":"acp","jsonrpc":"2.0","id":"{}","result":{}}}}}"#,+ id.to_request_id(),+ options("gpt")+ );+ fold.push(FoldInput::Confirmed(+ cursor(201),+ parse_log(&answer).remove(0),+ ))+ .unwrap();++ assert_eq!(fold.pending().count(), 0);+ assert_eq!(fold.metadata().model.as_deref(), Some("gpt"));+ let control = fold+ .messages()+ .iter()+ .rev()+ .find_map(|message| match message.parts.first() {+ Some(MessagePart::Control {+ control: Control::SetModel { model },+ outcome,+ }) => Some((model.clone(), outcome.clone(), message.pending)),+ _ => None,+ })+ .expect("the model change is shown");+ assert_eq!(control, ("gpt".to_owned(), ControlOutcome::Accepted, false));+}diff --git a/docs/agent-guide/ai-chat.md b/docs/agent-guide/ai-chat.mdindex f8ca4c43df..ad79357f2e 100644--- a/docs/agent-guide/ai-chat.md+++ b/docs/agent-guide/ai-chat.md@@ -81,6 +81,12 @@ on the create (`prompt` + `promptActionId`) and no `/control` request follows;a persona, effort, or speed keeps the control request. Either way the promptshows as one bubble that the logged row confirms in place.+Switching a disconnected session's model wakes its runtime first; the+selector re-enables with the new model's options once the runtime answers. If+the live feed misses that answer, the client reads the log after 10 seconds,+and after a minute it takes back an unconfirmed change, so the selector shows+the runtime's model again and stays usable.+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("hi there", "thanks") gets that line as the whole reply, and the chosen model,