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): make a model chosen at creation the session's model (#6786)
Wolf Mermelsteina7bf419881be
diff --git a/apps/web/src/features/block-agent/context/pending-session.ts b/apps/web/src/features/block-agent/context/pending-session.tsindex 897e2366ec..1dcaeea1d9 100644--- a/apps/web/src/features/block-agent/context/pending-session.ts+++ b/apps/web/src/features/block-agent/context/pending-session.ts@@ -52,11 +52,11 @@ export function isPlaceholderSessionId(id: string): boolean {export type StartPendingSessionOptions = {/** Persisted managed persona to run; omitted for Macro Coder. */botId?: string;- /** First prompt, delivered after any model override. */+ /** First prompt. */prompt?: string;/** Uploaded SFS files delivered with the first prompt. */attachments?: PromptAttachment[];- /** Optional model switch applied before the first prompt. */+ /** Model to run on instead of the persona's, set as the session is created. */modelOverride?: string;/*** Explicit GitHub repository for the managed Cursor session.@@ -85,6 +85,7 @@ export function startPendingSession(void agentHarnessServiceClient.create({...(options.botId ? { botId: options.botId } : {}),+ ...(options.modelOverride ? { model: options.modelOverride } : {}),...(options.repoUrl? { repoUrl: options.repoUrl, repoBranch: options.repoBranch }: {}),@@ -98,19 +99,6 @@ export function startPendingSession(return;}const id = result.value.session.id;- if (options.modelOverride) {- const changed = await agentHarnessServiceClient.control(id, {- type: 'setModel',- model: options.modelOverride,- });- if (changed.isErr()) {- setError(- changed.error.map((error) => error.message).join(' ') ||- 'The selected model could not be applied.'- );- return;- }- }const prompt = options.prompt?.trim() ?? '';if (prompt || options.attachments?.length) {const delivered = await agentHarnessServiceClient.control(id, {diff --git a/apps/web/src/features/block-agent/context/resolve-session-id.test.ts b/apps/web/src/features/block-agent/context/resolve-session-id.test.tsindex 6cd51efb2c..90405c892a 100644--- a/apps/web/src/features/block-agent/context/resolve-session-id.test.ts+++ b/apps/web/src/features/block-agent/context/resolve-session-id.test.ts@@ -93,7 +93,10 @@ describe('a placeholder', () => {});});- it('applies a model override before delivering the first prompt', async () => {+ // A model chosen before the session exists is what the session is created+ // on, not something switched afterwards: the first prompt is the only thing+ // sent, so it opens the session's first turn and the session gets a name.+ it('creates the session on the chosen model', async () => {create.control.mockResolvedValue({isErr: () => false,value: { actionId: 'action-1', status: 'accepted' },@@ -107,6 +110,7 @@ describe('a placeholder', () => {});expect(agentHarnessServiceClient.create).toHaveBeenLastCalledWith({botId: 'persona-1',+ model: 'model-2',repoUrl: 'https://github.com/macro-inc/macro',repoBranch: 'feature/home',});@@ -117,7 +121,6 @@ describe('a placeholder', () => {await flush();expect(create.control.mock.calls).toEqual([- ['session-10', { type: 'setModel', model: 'model-2' }],['session-10', { type: 'prompt', prompt: 'Fix the tests' }],]);expect(resolved.sessionId()).toBe('session-10');@@ -125,26 +128,6 @@ describe('a placeholder', () => {});});- it('shows a model failure without sending the prompt on the wrong model', async () => {- create.control.mockResolvedValue({- isErr: () => true,- error: [{ code: 'HTTP_ERROR', message: 'Model is unavailable.' }],- });- const placeholder = startPendingSession({- modelOverride: 'missing',- prompt: 'Hello',- });- await createRoot(async (dispose) => {- const resolved = resolveSessionId(() => placeholder);- create.resolve?.('session-model-error');- await flush();- expect(resolved.error()).toBe('Model is unavailable.');- expect(resolved.pending()).toBe(false);- expect(create.control).toHaveBeenCalledTimes(1);- dispose();- });- });-it('shows the first prompt failure', async () => {create.control.mockResolvedValue({isErr: () => true,diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/createAgentSessionRequest.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/createAgentSessionRequest.tsindex 0196a9cd34..ce5a3d7ab3 100644--- a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/createAgentSessionRequest.ts+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/createAgentSessionRequest.ts@@ -6,6 +6,7 @@*/import type { CreateAgentSessionRequestBotId } from './createAgentSessionRequestBotId';import type { CreateAgentSessionRequestInstructions } from './createAgentSessionRequestInstructions';+import type { CreateAgentSessionRequestModel } from './createAgentSessionRequestModel';import type { CreateAgentSessionRequestOwner } from './createAgentSessionRequestOwner';import type { CreateAgentSessionRequestPrompt } from './createAgentSessionRequestPrompt';import type { CreateAgentSessionRequestRepoBranch } from './createAgentSessionRequestRepoBranch';@@ -41,6 +42,14 @@ Recorded on the session whichever runtime serves it. Only thein-process one acts on them today; `agent_harness`'s `AgentKind`records what each of the others will need to. */instructions?: CreateAgentSessionRequestInstructions;+ /** Model the managed session runs on, overriding the persona's. Managed+sessions only: an external runtime picks its own.++The session's model from the moment it exists, which is what a caller+choosing one before the first prompt means. Selecting a model *during*+a session is a control action instead, and reads as one in its+transcript. */+ model?: CreateAgentSessionRequestModel;/** The user who owns the session. Ignored for user callers, who alwaysown their own sessions, and for harness callers, whose verified actinguser (owner or confirmed team member) owns the session instead;diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/createAgentSessionRequestModel.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/createAgentSessionRequestModel.tsnew file mode 100644index 0000000000..beb4f1b09e--- /dev/null+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/createAgentSessionRequestModel.ts@@ -0,0 +1,17 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * agent_harness_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Model the managed session runs on, overriding the persona's. Managed+sessions only: an external runtime picks its own.++The session's model from the moment it exists, which is what a caller+choosing one before the first prompt means. Selecting a model *during*+a session is a control action instead, and reads as one in its+transcript.+ */+export type CreateAgentSessionRequestModel = string | null;diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/index.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/index.tsindex 80ed85579d..6b219e48b7 100644--- a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/index.ts+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/index.ts@@ -89,6 +89,7 @@ export * from './controlStatusDto';export * from './createAgentSessionRequest';export * from './createAgentSessionRequestBotId';export * from './createAgentSessionRequestInstructions';+export * from './createAgentSessionRequestModel';export * from './createAgentSessionRequestOwner';export * from './createAgentSessionRequestPrompt';export * from './createAgentSessionRequestRepoBranch';diff --git a/apps/web/src/lib/service-clients/service-agent-harness/openapi.json b/apps/web/src/lib/service-clients/service-agent-harness/openapi.jsonindex fc949860f6..194a9da901 100644--- a/apps/web/src/lib/service-clients/service-agent-harness/openapi.json+++ b/apps/web/src/lib/service-clients/service-agent-harness/openapi.json@@ -2300,6 +2300,10 @@"type": ["string", "null"],"description": "Instructions the session's runtime works under, for its whole life.\n\nRecorded on the session whichever runtime serves it. Only the\nin-process one acts on them today; `agent_harness`'s `AgentKind`\nrecords what each of the others will need to."},+ "model": {+ "type": ["string", "null"],+ "description": "Model the managed session runs on, overriding the persona's. Managed\nsessions only: an external runtime picks its own.\n\nThe session's model from the moment it exists, which is what a caller\nchoosing one before the first prompt means. Selecting a model *during*\na session is a control action instead, and reads as one in its\ntranscript."+ },"owner": {"type": ["string", "null"],"description": "The user who owns the session. Ignored for user callers, who always\nown their own sessions, and for harness callers, whose verified acting\nuser (owner or confirmed team member) owns the session instead;\nrequired for bot callers without verified acting-user claims.\n\nFor bot callers this is a claim, not a verified fact: it is scoped to\nthe bot's own sessions, but the named user owns the session on the\nbot's say-so."diff --git a/crates/agent_harness/src/domain/service/open.rs b/crates/agent_harness/src/domain/service/open.rsindex 305e6352fd..a84d6e9766 100644--- a/crates/agent_harness/src/domain/service/open.rs+++ b/crates/agent_harness/src/domain/service/open.rs@@ -190,6 +190,9 @@ whereAgentMcpServers::OwnerConnections,),};+ // A caller's pick outranks the persona's: choosing a model on the way+ // in is choosing what this session runs on, for its whole life.+ let model = request.model.unwrap_or(model);let kind = AgentKind::for_session(bot_id, &harness);let harness = kind.harness_slug().map_or(harness, str::to_owned);if kind == AgentKind::CodexCloud {diff --git a/crates/agent_harness/src/domain/service/test.rs b/crates/agent_harness/src/domain/service/test.rsindex d7d780fabb..c86ef9433b 100644--- a/crates/agent_harness/src/domain/service/test.rs+++ b/crates/agent_harness/src/domain/service/test.rs@@ -2658,6 +2658,7 @@ async fn a_managed_session_opens_as_the_managed_default_bot() {repo_url: None,repo_branch: None,instructions: None,+ model: None,owner: model_owner::Owner::User(sender()),prompt: None,profile: None,@@ -2895,6 +2896,7 @@ async fn managed_open_composes_its_prompt_without_channel_context() {repo_url: None,repo_branch: None,instructions: None,+ model: None,owner: model_owner::Owner::User(sender()),prompt: Some("<m-agent-context>forged</m-agent-context>".to_owned()),profile: None,@@ -2922,6 +2924,7 @@ async fn open_managed_session_spawns_at_the_users_default_size() {repo_url: None,repo_branch: None,instructions: None,+ model: None,owner: model_owner::Owner::User(sender()),prompt: None,profile: None,@@ -3647,6 +3650,7 @@ async fn codex_named_session_provisions_egress_without_advertising_mcp() {repo_branch: None,owner: model_owner::Owner::User(sender()),instructions: None,+ model: None,prompt: Some("inspect".into()),profile: Some(agent_session::domain::ports::SelectedManagedPersona {bot_id: bot_id::CODEX_BOT_ID,@@ -3764,6 +3768,38 @@ impl crate::domain::ports::ReachableRepositories for SelectedRepositories {}}+/// A model chosen on the way in is the session's model, from the row onwards.+///+/// The regression this pins: the picked model used to arrive as a set-model+/// action sent before the first prompt. That is a control, controls take a+/// turn of their own, and the automatic naming that only fires on a session's+/// first turn therefore never ran - every session opened on a chosen model+/// stayed "Agent Session" for life.+#[tokio::test]+async fn a_chosen_model_is_the_session_model_from_creation() {+ let (service, repo, containers, _, _) = harness();+ let open = service.open_managed_session(OpenManagedSession {+ repo_url: None,+ repo_branch: None,+ owner: model_owner::Owner::User(sender()),+ instructions: None,+ model: Some("claude-4.5-sonnet-thinking".to_owned()),+ prompt: None,+ profile: Some(agent_session::domain::ports::SelectedManagedPersona {+ bot_id: bot_id::CURSOR_BOT_ID,+ profile: None,+ }),+ });+ let drive = async {+ let session = containers.first_spawned().await;+ let container = containers.container(session).unwrap();+ complete_session_handshake(&container).await;+ };+ let (opened, _) = tokio::join!(open, drive);+ let session = repo.get(opened.unwrap().id).await.unwrap();+ assert_eq!(session.model, "claude-4.5-sonnet-thinking");+}+/// The agents-view create path names the Cursor bot with no persisted/// profile. The deployment default harness is the sandboxed coder's/// `opencode`; Cursor sessions must not inherit it.@@ -3775,6 +3811,7 @@ async fn a_cursor_managed_session_is_always_stamped_cursor() {repo_branch: None,owner: model_owner::Owner::User(sender()),instructions: None,+ model: None,prompt: None,profile: Some(agent_session::domain::ports::SelectedManagedPersona {bot_id: bot_id::CURSOR_BOT_ID,@@ -3798,6 +3835,7 @@ fn explicit_cursor_request() -> OpenManagedSession {OpenManagedSession {owner: model_owner::Owner::User(sender()),instructions: None,+ model: None,prompt: None,repo_url: Some("https://github.com/macro-inc/macro".into()),repo_branch: Some(diff --git a/crates/agent_harness/src/outbound/cursor/manager.rs b/crates/agent_harness/src/outbound/cursor/manager.rsindex cf6f338db6..fdc3859f6d 100644--- a/crates/agent_harness/src/outbound/cursor/manager.rs+++ b/crates/agent_harness/src/outbound/cursor/manager.rs@@ -170,8 +170,6 @@ struct RestoredCursorSession {acp_session: SessionId,/// The Cursor agent, when one was ever minted.agent: Option<CursorAgentId>,- /// The model id the session last reported, from the projected column.- model_id: Option<String>,/// The last Cursor run whose output reached Macro's session log.last_run: Option<CursorRunId>,}@@ -413,9 +411,6 @@ where},));}- // The user's chosen model seeds the session as its default: a fresh- // session starts on it, and a resumed one still prefers whatever it- // was actually last using (carried in `restore.model_id`) over this.let chooser = HaikuRepositoryChooser::new(Arc::clone(&self.repositories),self.sessions.clone(),@@ -431,7 +426,12 @@ wherejournal,self.artifacts.clone(),)- .with_default_model(default_model_id),+ .with_default_model(default_model_id)+ // The session's own model outranks the account default: what its+ // owner picked for it when they opened it, what they switched it+ // to since, or - for a session that never picked - the slug this+ // harness seeded the record with, which resolves to no opinion.+ .with_host_model(Some(session.model.clone())),);if let Some(restored) = restore {service.restore_session_with_watermark(@@ -442,7 +442,6 @@ where// deployment default to fall back on, and a restored session// must land on the repository its agent was minted against.session.repo_url.as_deref().and_then(CursorRepoUrl::parse),- restored.model_id,restored.last_run,);}@@ -621,12 +620,6 @@ whereSome(RestoredCursorSession {acp_session: acp.clone(),agent,- // The projected model column. It round-trips a picked- // model back into the wrapper — and for a session that- // never picked, it still holds the deployment slug the- // harness seeded it with, which the wrapper resolves to- // "no opinion" rather than trusting.- model_id: Some(stored.model.clone()),last_run: external.and_then(|external| external.last_run_id).map(CursorRunId::new),diff --git a/crates/agent_harness/src/testing/helpers/containers.rs b/crates/agent_harness/src/testing/helpers/containers.rsindex 24804c16b3..b9449bba91 100644--- a/crates/agent_harness/src/testing/helpers/containers.rs+++ b/crates/agent_harness/src/testing/helpers/containers.rs@@ -204,6 +204,9 @@ pub struct MockContainerManager {resize_unsupported: Arc<AtomicBool>,resumes: Arc<AtomicUsize>,teardowns: Arc<AtomicUsize>,+ /// Signalled on every spawn, so a test waits for a sandbox instead of+ /// spinning on [`Self::spawned`].+ spawned_signal: Arc<tokio::sync::Notify>,}impl MockContainerManager {@@ -231,6 +234,20 @@ impl MockContainerManager {self.lock().len()}+ /// The first session a sandbox is booted for, awaited rather than polled.+ ///+ /// Returns at once when one has already been spawned, so a caller that+ /// arrives late still gets its session.+ pub async fn first_spawned(&self) -> AgentSessionId {+ loop {+ let waited = self.spawned_signal.notified();+ if let Some(session) = self.sessions().first().copied() {+ return session;+ }+ waited.await;+ }+ }+/// Answer every preflight with `blocker` from now on: the owner is not/// set up for this provider.pub fn block_with(&self, blocker: SessionBlocker) {@@ -323,6 +340,7 @@ impl ContainerManager for MockContainerManager {.push(command.size);let container = ContainerMock::default();self.lock().insert(command.session_id, container.clone());+ self.spawned_signal.notify_waiters();Ok(agent_session::domain::connection::RuntimeAttachment::solo(container,))diff --git a/crates/agent_session/src/domain/ports.rs b/crates/agent_session/src/domain/ports.rsindex c507550c99..a2506bcfa7 100644--- a/crates/agent_session/src/domain/ports.rs+++ b/crates/agent_session/src/domain/ports.rs@@ -234,6 +234,9 @@ pub struct OpenManagedSession {/// Ad-hoc instructions for the default managed persona. Ignored when a/// persisted persona profile is selected.pub instructions: Option<String>,+ /// Model to run on instead of the persona's own. The session's model from+ /// creation, so its runtime starts on it and nothing is sent to change it.+ pub model: Option<String>,}/// Opens sessions, however they are served. Implemented by the harness, whichdiff --git a/crates/agent_session/src/domain/service.rs b/crates/agent_session/src/domain/service.rsindex 1310d1f3c9..52e5065afc 100644--- a/crates/agent_session/src/domain/service.rs+++ b/crates/agent_session/src/domain/service.rs@@ -33,7 +33,7 @@ use agent_client_protocol::schema::v1::{RequestId, Response, SessionId, SetSessionConfigOptionResponse,};use agent_fold::domain::lifecycle::LifecycleFold;-use agent_fold::domain::model::TurnState;+use agent_fold::domain::model::{Author, FoldedMessage, MessagePart, TurnState};use agent_fold::domain::model_selection::model_selection;use agent_fold::domain::ports::FoldedMessageRepo;use agent_runtime_protocol::domain::action::{AgentAction, AgentActionId, AgentSetModelAction};@@ -937,8 +937,11 @@ wherelet AgentAction::Prompt(prompt) = action else {return None;};+ // Whether anyone has *spoken* here yet, rather than whether the log has+ // opened a turn: controls take turns of their own, so a session whose+ // model was set before its first prompt would otherwise never be named.folds- .next_turn_id(id)+ .messages(id).await.inspect_err(|error| {tracing::warn!(@@ -948,10 +951,21 @@ where);}).ok()- .filter(|turn| *turn == MessageId::first(AuthorKind::User).turn)+ .filter(|messages| !messages.iter().any(is_user_prompt)).map(|_| prompt.name_source().to_owned())}+/// A message a user wrote, as opposed to a control they issued.+fn is_user_prompt(message: &FoldedMessage) -> bool {+ matches!(message.author, Author::User { .. })+ && message.parts.iter().any(|part| {+ matches!(+ part,+ MessagePart::Text { .. } | MessagePart::Attachment { .. }+ )+ })+}+fn spawn_initial_agent_session_rename<R, Rt, Namer>(repo: R,realtime: Rt,diff --git a/crates/agent_session/src/domain/service/test.rs b/crates/agent_session/src/domain/service/test.rsindex 3aa6b0ef89..c4e51dfc1b 100644--- a/crates/agent_session/src/domain/service/test.rs+++ b/crates/agent_session/src/domain/service/test.rs@@ -166,6 +166,27 @@ async fn only_the_first_prompt_is_selected_for_automatic_naming() {Some("fix the flaky tests".to_owned()));+ // A control opens a turn of its own, so turn numbering cannot stand in for+ // "nobody has spoken yet" - a model picked before the first prompt used to+ // leave the session unnamed for life.+ repo.extend_log(vec![AgentSessionLog {+ agent_session_id: session,+ user_id: None,+ content: Message::ToRuntime(+ AgentAction::set_model("gpt-5.5")+ .to_runtime(+ &agent_client_protocol::schema::v1::SessionId::new("acp-1"),+ RequestId::Number(1),+ )+ .expect("a set-model frame builds"),+ ),+ }]);+ assert_eq!(+ initial_prompt_for_rename(&folds, session, &prompt).await,+ Some("fix the flaky tests".to_owned()),+ "a model chosen before the first prompt must not cost the session its name"+ );+repo.extend_log(parse_log_as(session, TURN));assert_eq!(initial_prompt_for_rename(&folds, session, &prompt).await,diff --git a/crates/agent_session/src/inbound/axum_router.rs b/crates/agent_session/src/inbound/axum_router.rsindex 576c49b708..e7371790c5 100644--- a/crates/agent_session/src/inbound/axum_router.rs+++ b/crates/agent_session/src/inbound/axum_router.rs@@ -1483,6 +1483,14 @@ pub struct CreateAgentSessionRequest {/// in-process one acts on them today; `agent_harness`'s `AgentKind`/// records what each of the others will need to.pub instructions: Option<String>,+ /// Model the managed session runs on, overriding the persona's. Managed+ /// sessions only: an external runtime picks its own.+ ///+ /// The session's model from the moment it exists, which is what a caller+ /// choosing one before the first prompt means. Selecting a model *during*+ /// a session is a control action instead, and reads as one in its+ /// transcript.+ pub model: Option<String>,}/// The triggering mention on a create request.@@ -1810,6 +1818,7 @@ pub async fn create_agent_session_handler<prompt: request.prompt,profile,instructions,+ model: request.model.filter(|model| !model.trim().is_empty()),}).await?;return Ok((@@ -1821,8 +1830,9 @@ pub async fn create_agent_session_handler<};// An external runtime sends its own first prompt through the control- // endpoint, so accepting one here would silently drop it.- if request.prompt.is_some() || request.repo_branch.is_some() {+ // endpoint, so accepting one here would silently drop it, and it runs on+ // whatever model its operator configured, which is not ours to set.+ if request.prompt.is_some() || request.repo_branch.is_some() || request.model.is_some() {return Err(CreateSessionApiError::MixedSessionShape);}let bot_id = resolve_bot(&caller.authorization, request.bot_id)?;diff --git a/crates/coding_agent_worker/src/dispatch.rs b/crates/coding_agent_worker/src/dispatch.rsindex f28c8033d9..e755aef630 100644--- a/crates/coding_agent_worker/src/dispatch.rs+++ b/crates/coding_agent_worker/src/dispatch.rs@@ -81,6 +81,9 @@ impl WorkExecutor for Dispatcher {// whatever the binary in its config was built with, so// there is nothing to state here.instructions: None,+ // Likewise the model: an external session runs on+ // whatever this runtime is configured with.+ model: None,};let created = match self.api.create_session(&request, &sender).await {Ok(created) => created,diff --git a/crates/cursor_cloud_agents/src/domain/service.rs b/crates/cursor_cloud_agents/src/domain/service.rsindex 8647a82d64..f752a4a397 100644--- a/crates/cursor_cloud_agents/src/domain/service.rs+++ b/crates/cursor_cloud_agents/src/domain/service.rs@@ -418,15 +418,6 @@ struct SessionState {struct Session {/// ACP working directory, used by the standalone repository chooser.cwd: PathBuf,- /// The model id this session was using before the process restarted, when- /// it was restored and had one. An id rather than a [`ModelChoice`]: only- /// the id is persisted, and its params must be re-resolved against the- /// live model table anyway, which can have drifted across the restart.- ///- /// May also be a value that was never a Cursor id at all — the harness- /// seeds its session records with a deployment slug like `claude` — so- /// resolution tolerates a miss instead of trusting this.- restored_model_id: Option<String>,/// Serializes turns against background foreign-run syncs, so a mirror of/// cursor.com activity never interleaves its frames with a live turn's./// A prompt waits on it; a sync skips its tick instead. Never held by@@ -451,6 +442,14 @@ pub struct CursorSessionService<Cursor, Notifier, Chooser, Store> {/// A model id this deployment pins, applied to every new session. `None`/// leaves the choice to Cursor's own default resolution.default_model_id: Option<String>,+ /// The model this one session runs on, from the host's own session record:+ /// what its owner picked for it, or the slug the host seeded it with.+ /// Outranks [`Self::default_model_id`], which is only what a session gets+ /// when nobody said otherwise.+ ///+ /// A whole service per session is how the hosted deployment serves them,+ /// so this sits beside the deployment default rather than on [`Session`].+ host_model_id: Option<String>,/// `GET /v1/models`, fetched once. The table is static for the life of a/// process and every `session/new` would otherwise re-fetch it.models: tokio::sync::Mutex<Option<Vec<CursorModel>>>,@@ -480,6 +479,7 @@ wheresessions: Mutex::new(HashMap::new()),next_session: Mutex::new(0),default_model_id: None,+ host_model_id: None,models: tokio::sync::Mutex::new(None),}}@@ -495,6 +495,20 @@ whereself}+ /// Pin the model this session runs on, by id, ahead of the deployment+ /// default.+ ///+ /// The host's session record, which holds the model its owner chose for+ /// this session - before it ever ran, or by selecting one mid-session -+ /// and otherwise whatever slug the host seeded the record with. Resolved+ /// like any other id, so a value that is not a Cursor model is no opinion+ /// and the deployment default still answers.+ #[must_use]+ pub fn with_host_model(mut self, model_id: Option<String>) -> Self {+ self.host_model_id = model_id;+ self+ }+/// Open a session.////// No repository is chosen here: a session's repository follows from what@@ -504,7 +518,6 @@ wherepub fn new_session(&self, cwd: &Path, mcp_servers: Vec<McpServer>) -> SessionId {let session = Arc::new(Session {cwd: cwd.to_path_buf(),- restored_model_id: None,turn_gate: Arc::new(tokio::sync::Mutex::new(())),state: Mutex::new(SessionState {mcp_servers,@@ -611,36 +624,40 @@ where{return Ok(Some(model));}- // The restored id outranks the deployment default: it is what this- // session was actually using before the restart, and the default is- // what a session gets when nobody ever said otherwise.- let fallback_id = session- .restored_model_id- .as_deref()- .or(self.default_model_id.as_deref());- let Some(fallback_id) = fallback_id else {- return Ok(None);- };- // A failure to *fetch* the model table degrades like a failed lookup- // in it: the fallback is a preference, and Cursor being unreachable- // for `GET /v1/models` must cost the preference, never the prompt —- // the run itself may well still work.- let choice = match self.resolve_model_id(fallback_id).await {- Ok(choice) => choice,- Err(error) => {- tracing::warn!(- fallback_id,- %error,- "could not resolve the fallback model; using Cursor's default"- );- None- }- };- let Some(choice) = choice else {- return Ok(None);- };- session.state.lock().expect("session state poisoned").model = Some(choice.clone());- Ok(Some(choice))+ // Session before deployment: the session's own id is what its owner+ // chose for it (or was using before a restart), and the default is+ // what a session gets when nobody ever said otherwise. Each is only a+ // preference, so one that resolves to nothing hands the question to+ // the next rather than answering it with silence.+ for fallback_id in [+ self.host_model_id.as_deref(),+ self.default_model_id.as_deref(),+ ]+ .into_iter()+ .flatten()+ {+ // A failure to *fetch* the model table degrades like a failed+ // lookup in it: the fallback is a preference, and Cursor being+ // unreachable for `GET /v1/models` must cost the preference, never+ // the prompt — the run itself may well still work.+ let choice = match self.resolve_model_id(fallback_id).await {+ Ok(choice) => choice,+ Err(error) => {+ tracing::warn!(+ fallback_id,+ %error,+ "could not resolve the fallback model; using Cursor's default"+ );+ None+ }+ };+ let Some(choice) = choice else {+ continue;+ };+ session.state.lock().expect("session state poisoned").model = Some(choice.clone());+ return Ok(Some(choice));+ }+ Ok(None)}/// The id resolved to a choice Cursor will accept, or `None` for an id@@ -1184,9 +1201,8 @@ whereid: SessionId,agent: Option<CursorAgentId>,repo: Option<RepoUrl>,- model_id: Option<String>,) {- self.restore_session_with_watermark(id, agent, repo, model_id, None);+ self.restore_session_with_watermark(id, agent, repo, None);}/// Restore a session together with its durable run-delivery checkpoint.@@ -1195,7 +1211,6 @@ whereid: SessionId,agent: Option<CursorAgentId>,repo: Option<RepoUrl>,- model_id: Option<String>,last_run: Option<CursorRunId>,) {// No MCP servers here on purpose: the host never had the truth to@@ -1203,7 +1218,6 @@ where// restates it on `session/load`, which is where it re-enters.let session = Arc::new(Session {cwd: PathBuf::new(),- restored_model_id: model_id,turn_gate: Arc::new(tokio::sync::Mutex::new(())),state: Mutex::new(SessionState {repo,diff --git a/crates/cursor_cloud_agents/src/domain/service/test.rs b/crates/cursor_cloud_agents/src/domain/service/test.rsindex bab0e5364a..1a9cb4551b 100644--- a/crates/cursor_cloud_agents/src/domain/service/test.rs+++ b/crates/cursor_cloud_agents/src/domain/service/test.rs@@ -858,7 +858,6 @@ async fn a_restored_session_prompts_its_existing_agent() {SessionId::new("cursor-acp-7"),Some(CursorAgentId::new("bc-restored")),None,- None,);crate::testing::script_legacy_history(&cursor);service@@ -896,7 +895,6 @@ async fn cancel_on_a_restored_session_finds_the_run_from_cursor() {SessionId::new("cursor-acp-7"),Some(CursorAgentId::new("bc-restored")),None,- None,);cursor.script_run_listings(vec![@@ -935,7 +933,6 @@ async fn cancel_on_a_restored_session_cancels_every_run_in_progress() {SessionId::new("cursor-acp-10"),Some(CursorAgentId::new("bc-restored")),None,- None,);cursor.script_run_listings(vec![@@ -982,7 +979,6 @@ async fn cancel_on_a_restored_session_with_no_run_going_is_a_no_op() {SessionId::new("cursor-acp-8"),Some(CursorAgentId::new("bc-restored")),None,- None,);cursor.script_run_listings(vec![RunListing {@@ -1006,7 +1002,6 @@ async fn new_sessions_never_collide_with_restored_ids() {SessionId::new("cursor-acp-1"),Some(CursorAgentId::new("bc-restored")),None,- None,);let fresh = service.new_session(Path::new(""), Vec::new());@@ -1022,7 +1017,7 @@ async fn new_sessions_never_collide_with_restored_ids() {#[tokio::test]async fn a_session_restored_without_an_agent_mints_one_on_the_next_prompt() {let (service, cursor, _notifier) = service(None);- service.restore_session(SessionId::new("cursor-acp-9"), None, None, None);+ service.restore_session(SessionId::new("cursor-acp-9"), None, None);service.replay_session(&SessionId::new("cursor-acp-9")).await@@ -1295,7 +1290,6 @@ async fn restore_recovers_runs_after_the_durable_watermark_once() {session.clone(),Some(CursorAgentId::new("bc-restored")),None,- None,Some(CursorRunId::new("run-delivered")),);// The initial load hydrates the run this session delivered before the@@ -1413,7 +1407,6 @@ async fn restore_without_a_watermark_hydrates_every_run_on_load() {Some(CursorAgentId::new("bc-restored")),None,None,- None,);cursor.script_run_listings(vec![RunListing {@@ -1476,7 +1469,6 @@ async fn restore_waits_for_session_load_before_recovering_runs() {session.clone(),Some(CursorAgentId::new("bc-restored")),None,- None,Some(CursorRunId::new("run-delivered")),);cursor.script_run_listings(vec![RunListing {@@ -1827,7 +1819,7 @@ async fn durable_multiturn_load_replays_full_history_and_supports_continuation()journal.clone(),NoArtifactStore,));- restored.restore_session(id.clone(), Some(CursorAgentId::new("bc-fake")), None, None);+ restored.restore_session(id.clone(), Some(CursorAgentId::new("bc-fake")), None);restored.replay_session(&id).await.unwrap().complete();let first = replayed.updates();let replay_without_users: Vec<_> = first@@ -2014,7 +2006,7 @@ async fn partial_capture_reconnect_matches_the_prefix_without_duplicate_content(async fn restored_agent_without_provider_history_cannot_commit_empty_replacement() {let (service, cursor, notifier) = service(None);let id = SessionId::new("restored");- service.restore_session(id.clone(), Some(CursorAgentId::new("agent")), None, None);+ service.restore_session(id.clone(), Some(CursorAgentId::new("agent")), None);cursor.script_run_listings(vec![]);assert!(service.replay_session(&id).await.is_err());@@ -2028,7 +2020,7 @@ async fn restored_agent_without_provider_history_cannot_commit_empty_replacementasync fn incomplete_legacy_hydration_emits_nothing_and_cannot_enable_sync() {let (service, cursor, notifier) = service(None);let id = SessionId::new("old");- service.restore_session(id.clone(), Some(CursorAgentId::new("agent")), None, None);+ service.restore_session(id.clone(), Some(CursorAgentId::new("agent")), None);cursor.script_run_listings(vec![RunListing {id: CursorRunId::new("run-old"),status: RunStatus::Finished,@@ -2273,7 +2265,6 @@ async fn capture_backlog_includes_the_run_at_the_delivered_watermark_after_restaid.clone(),Some(CursorAgentId::new("agent")),None,- None,Some(run.clone()),);service.replay_session(&id).await.unwrap().complete();diff --git a/crates/cursor_cloud_agents/src/domain/service/test/artifacts.rs b/crates/cursor_cloud_agents/src/domain/service/test/artifacts.rsindex 137bfe7bcc..37ec357192 100644--- a/crates/cursor_cloud_agents/src/domain/service/test/artifacts.rs+++ b/crates/cursor_cloud_agents/src/domain/service/test/artifacts.rs@@ -267,12 +267,7 @@ async fn a_reloaded_session_re_announces_the_same_artifacts() {harness.journal.clone(),FakeArtifactStore::new(),));- restored.restore_session(- session.clone(),- Some(CursorAgentId::new("bc-fake")),- None,- None,- );+ restored.restore_session(session.clone(), Some(CursorAgentId::new("bc-fake")), None);restored.replay_session(&session).awaitdiff --git a/crates/cursor_cloud_agents/src/domain/service/test/fold.rs b/crates/cursor_cloud_agents/src/domain/service/test/fold.rsindex cbaf1d57cb..c9e90df20a 100644--- a/crates/cursor_cloud_agents/src/domain/service/test/fold.rs+++ b/crates/cursor_cloud_agents/src/domain/service/test/fold.rs@@ -38,7 +38,7 @@ pub(super) async fn replay_with_runs(journal,crate::domain::ports::NoArtifactStore,));- service.restore_session(id.clone(), Some(CursorAgentId::new("agent")), None, None);+ service.restore_session(id.clone(), Some(CursorAgentId::new("agent")), None);let (agent, mut client) = Channel::duplex();let task = tokio::spawn(serve_transport(service.clone(), notifier, agent));let mut log = Vec::new();diff --git a/crates/cursor_cloud_agents/src/domain/service/test/working_branches.rs b/crates/cursor_cloud_agents/src/domain/service/test/working_branches.rsindex 880aef5eea..9b73eab98e 100644--- a/crates/cursor_cloud_agents/src/domain/service/test/working_branches.rs+++ b/crates/cursor_cloud_agents/src/domain/service/test/working_branches.rs@@ -90,7 +90,7 @@ async fn native_no_pr_branch_facts_survive_live_capture_and_durable_replay() {journal,NoArtifactStore,));- restored.restore_session(id.clone(), Some(CursorAgentId::new("bc-fake")), None, None);+ restored.restore_session(id.clone(), Some(CursorAgentId::new("bc-fake")), None);let before = cursor.calls();restored.replay_session(&id).await.unwrap().complete();assert_eq!(replayed.working_branches(), branches("cursor/renamed-work"));@@ -106,12 +106,7 @@ async fn native_no_pr_branch_facts_survive_live_capture_and_durable_replay() {async fn hydrated_no_pr_history_reports_latest_branch_for_every_repository() {let (service, cursor, notifier) = service(None);let id = SessionId::new("restored-cursor");- service.restore_session(- id.clone(),- Some(CursorAgentId::new("bc-restored")),- None,- None,- );+ service.restore_session(id.clone(), Some(CursorAgentId::new("bc-restored")), None);cursor.script_run_listings(vec![RunListing {id: CursorRunId::new("run-latest"),@@ -187,7 +182,7 @@ async fn replay_retains_only_latest_branch_across_repository_url_aliases() {journal,NoArtifactStore,);- restored.restore_session(id.clone(), Some(CursorAgentId::new("bc-fake")), None, None);+ restored.restore_session(id.clone(), Some(CursorAgentId::new("bc-fake")), None);restored.replay_session(&id).await.unwrap().complete();assert_eq!(replayed.working_branches(), branches("cursor/latest"));}diff --git a/crates/cursor_cloud_agents/src/inbound/acp/test.rs b/crates/cursor_cloud_agents/src/inbound/acp/test.rsindex 61b4f046c7..e4b1c34cd5 100644--- a/crates/cursor_cloud_agents/src/inbound/acp/test.rs+++ b/crates/cursor_cloud_agents/src/inbound/acp/test.rs@@ -127,6 +127,28 @@ fn serve_over_channel_with_default_model(cursor: FakeCursor,default_model: Option<&str>,configure: impl FnOnce(&Service),+) -> (Arc<Service>, TestClient) {+ serve_over_channel_with_models(cursor, default_model, None, configure)+}++/// [`serve_over_channel`], for a session whose host record names a model.+///+/// The other half of [`serve_over_channel_with_default_model`]: both are fixed+/// at construction, because the hosted deployment builds one service per+/// session and hands it both preferences there.+fn serve_over_channel_with_host_model(+ cursor: FakeCursor,+ host_model: Option<&str>,+ configure: impl FnOnce(&Service),+) -> (Arc<Service>, TestClient) {+ serve_over_channel_with_models(cursor, None, host_model, configure)+}++fn serve_over_channel_with_models(+ cursor: FakeCursor,+ default_model: Option<&str>,+ host_model: Option<&str>,+ configure: impl FnOnce(&Service),) -> (Arc<Service>, TestClient) {let notifier = AcpNotifier::new();let service = Arc::new(@@ -137,7 +159,8 @@ fn serve_over_channel_with_default_model(Arc::new(crate::outbound::memory_journal::MemoryJournal::default()),crate::domain::ports::NoArtifactStore,)- .with_default_model(default_model.map(str::to_owned)),+ .with_default_model(default_model.map(str::to_owned))+ .with_host_model(host_model.map(str::to_owned)),);configure(&service);let (agent_end, client_end) = Channel::duplex();@@ -692,7 +715,6 @@ async fn session_load_answers_for_restored_sessions_only() {SessionId::new("cursor-acp-3"),Some(crate::domain::model::CursorAgentId::new("bc-restored")),None,- None,);});@@ -834,7 +856,6 @@ async fn session_load_advertises_cursor_slash_commands() {SessionId::new("cursor-acp-3"),Some(crate::domain::model::CursorAgentId::new("bc-restored")),None,- None,);});@@ -1057,14 +1078,14 @@ async fn a_restored_session_keeps_its_model() {let cursor = FakeCursor::new();cursor.script_models(offered_models());crate::testing::script_legacy_history(&cursor);- let (service, mut client) = serve_over_channel(cursor.clone(), |service| {- service.restore_session(- SessionId::new("cursor-acp-3"),- Some(crate::domain::model::CursorAgentId::new("bc-restored")),- None,- Some("gpt-5.5".to_owned()),- );- });+ let (service, mut client) =+ serve_over_channel_with_host_model(cursor.clone(), Some("gpt-5.5"), |service| {+ service.restore_session(+ SessionId::new("cursor-acp-3"),+ Some(crate::domain::model::CursorAgentId::new("bc-restored")),+ None,+ );+ });// The picker is repopulated at load, current value included — this is the// other half of the regression, where the options came back empty.@@ -1123,14 +1144,14 @@ async fn a_restored_deployment_slug_falls_back_to_cursors_default() {let cursor = FakeCursor::new();cursor.script_models(offered_models());crate::testing::script_legacy_history(&cursor);- let (service, mut client) = serve_over_channel(cursor.clone(), |service| {- service.restore_session(- SessionId::new("cursor-acp-3"),- Some(crate::domain::model::CursorAgentId::new("bc-restored")),- None,- Some("claude".to_owned()),- );- });+ let (service, mut client) =+ serve_over_channel_with_host_model(cursor.clone(), Some("claude"), |service| {+ service.restore_session(+ SessionId::new("cursor-acp-3"),+ Some(crate::domain::model::CursorAgentId::new("bc-restored")),+ None,+ );+ });let loaded = client.call(@@ -1178,7 +1199,7 @@ async fn session_load_restores_the_clients_mcp_servers() {let cursor = FakeCursor::new();let (service, mut client) = serve_over_channel(cursor.clone(), |service| {// Restored with *no* agent: the session opened, never prompted, died.- service.restore_session(SessionId::new("cursor-acp-3"), None, None, None);+ service.restore_session(SessionId::new("cursor-acp-3"), None, None);});let loaded = client@@ -1336,7 +1357,6 @@ async fn load_queues_all_native_history_before_its_response_and_repeats_without_SessionId::new("restored"),Some(crate::domain::model::CursorAgentId::new("agent")),None,- None,);});let mut first = Vec::new();diff --git a/packages/sdk/generated/agent-harness/types.gen.ts b/packages/sdk/generated/agent-harness/types.gen.tsindex e7d9b20d3b..8ca9f087a7 100644--- a/packages/sdk/generated/agent-harness/types.gen.ts+++ b/packages/sdk/generated/agent-harness/types.gen.ts@@ -630,6 +630,16 @@ export type CreateAgentSessionRequest = {* records what each of the others will need to.*/instructions?: string | null;+ /**+ * Model the managed session runs on, overriding the persona's. Managed+ * sessions only: an external runtime picks its own.+ *+ * The session's model from the moment it exists, which is what a caller+ * choosing one before the first prompt means. Selecting a model *during*+ * a session is a control action instead, and reads as one in its+ * transcript.+ */+ model?: string | null;/*** The user who owns the session. Ignored for user callers, who always* own their own sessions, and for harness callers, whose verified actingdiff --git a/packages/sdk/specs/agent-harness.json b/packages/sdk/specs/agent-harness.jsonindex fc949860f6..194a9da901 100644--- a/packages/sdk/specs/agent-harness.json+++ b/packages/sdk/specs/agent-harness.json@@ -2300,6 +2300,10 @@"type": ["string", "null"],"description": "Instructions the session's runtime works under, for its whole life.\n\nRecorded on the session whichever runtime serves it. Only the\nin-process one acts on them today; `agent_harness`'s `AgentKind`\nrecords what each of the others will need to."},+ "model": {+ "type": ["string", "null"],+ "description": "Model the managed session runs on, overriding the persona's. Managed\nsessions only: an external runtime picks its own.\n\nThe session's model from the moment it exists, which is what a caller\nchoosing one before the first prompt means. Selecting a model *during*\na session is a control action instead, and reads as one in its\ntranscript."+ },"owner": {"type": ["string", "null"],"description": "The user who owns the session. Ignored for user callers, who always\nown their own sessions, and for harness callers, whose verified acting\nuser (owner or confirmed team member) owns the session instead;\nrequired for bot callers without verified acting-user claims.\n\nFor bot callers this is a claim, not a verified fact: it is scoped to\nthe bot's own sessions, but the named user owns the session on the\nbot's say-so."diff --git a/packages/sdk/src/entities/agent-sessions/agent-session.ts b/packages/sdk/src/entities/agent-sessions/agent-session.tsindex 48b50e68ba..140dcb26e9 100644--- a/packages/sdk/src/entities/agent-sessions/agent-session.ts+++ b/packages/sdk/src/entities/agent-sessions/agent-session.ts@@ -29,6 +29,11 @@ export type CreateManagedSessionOptions = {prompt?: string;/** Instructions the session's runtime works under, fixed for its life. */instructions?: string;+ /**+ * The model the session runs on, instead of its persona's. The session's+ * model from creation, read back as {@link AgentSession.model}.+ */+ model?: string;/*** The repository the session works on, as one of the URLs* {@link AgentSession.repositories} lists for the caller. Omitted, the@@ -59,6 +64,7 @@ export class AgentSession extends MacroEntity<AgentSessionResponse> {body: {prompt: opts?.prompt,instructions: opts?.instructions,+ model: opts?.model,repoUrl: opts?.repoUrl,repoBranch: opts?.repoBranch,},