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(claude-cloud): discover Fable through the models API (#6595)
Eric Hayes87484850c44b
diff --git a/apps/web/src/features/settings/Agents.test.tsx b/apps/web/src/features/settings/Agents.test.tsxindex e3147c7543..d08d06bffc 100644--- a/apps/web/src/features/settings/Agents.test.tsx+++ b/apps/web/src/features/settings/Agents.test.tsx@@ -438,6 +438,88 @@ describe('Agents', () => {});+ it('keeps a saved Claude harness selected while discovery loads and scopes Fable to it', async () => {+ agentMocks.query.data = [+ {+ bot: {+ id: 'agent-1',+ kind: 'owned',+ owner: { type: 'user', user_id: 'macro|[email protected]' },+ name: 'Bug fixer',+ handle: 'bug-fixer',+ has_agent: true,+ created_at: '2026-08-27T12:00:00Z',+ updated_at: '2026-08-27T12:00:00Z',+ },+ instructions: 'Fix the root cause.',+ harness: 'claude-cloud',+ default_model: 'claude-fable-5-1',+ channel_scope: 'all',+ channel_ids: [],+ },+ ];+ let resolveModels!: (models: LoadAgentModelsResponse) => void;+ const response = new Promise<LoadAgentModelsResponse>((resolve) => {+ resolveModels = resolve;+ });+ const client = new QueryClient({+ defaultOptions: { queries: { retry: false } },+ });+ vi.mocked(useAgentModelsQueries).mockImplementationOnce((targets) =>+ targets().map((target) =>+ useQuery(() => ({+ queryKey: ['pending-models', target.harness],+ queryFn: () =>+ target.harness === 'claude-cloud'+ ? response+ : Promise.resolve(modelMocks.queries['in-memory:'].data!),+ }))+ )+ );+ const view = render(() => (+ <QueryClientProvider client={client}>+ <Suspense fallback={<p>Settings suspended</p>}>+ <Agents />+ </Suspense>+ </QueryClientProvider>+ ));+ try {+ fireEvent.click(screen.getByRole('button', { name: 'Edit Bug fixer' }));+ const harness = screen.getByRole('combobox', { name: 'Harness' });+ expect(harness).toHaveProperty('value', 'claude-cloud');+ expect(screen.getByText('Loading models…')).toBeTruthy();+ resolveModels({+ status: 'available',+ currentModel: 'claude-fable-5-1',+ models: [{ id: 'claude-fable-5-1', name: 'Fable 5.1' }],+ });+ await waitFor(() =>+ expect(screen.getByRole('option', { name: 'Fable 5.1' })).toBeTruthy()+ );+ expect(harness).toHaveProperty('value', 'claude-cloud');+ fireEvent.change(harness, { target: { value: 'in-memory' } });+ await waitFor(() =>+ expect(+ screen.getByRole('combobox', { name: 'Default model' })+ ).toHaveProperty('value', Model.sonnet5)+ );+ expect(screen.queryByRole('option', { name: /Fable/i })).toBeNull();+ fireEvent.click(screen.getByRole('button', { name: 'Save changes' }));+ await waitFor(() =>+ expect(agentMocks.update).toHaveBeenCalledWith(+ expect.objectContaining({+ agentId: 'agent-1',+ harness: 'in-memory',+ defaultModel: Model.sonnet5,+ })+ )+ );+ } finally {+ view.unmount();+ client.clear();+ }+ });+it('lists the built-in global Macro agent as a team agent', () => {render(() => <Agents />);diff --git a/apps/web/src/features/settings/Agents.tsx b/apps/web/src/features/settings/Agents.tsxindex 8031cdff25..a93803872e 100644--- a/apps/web/src/features/settings/Agents.tsx+++ b/apps/web/src/features/settings/Agents.tsx@@ -875,6 +875,7 @@ function AgentDialog(props: {each={props.connectedHarnesses.filter((harness) =>harness.id !== 'claude-cloud' ||+ harness.id === harnessId() ||modelDataForHarness(harness.id)?.status ==='available')}diff --git a/crates/agent_harness/src/domain/claude.rs b/crates/agent_harness/src/domain/claude.rsindex c8bad2f54d..39d4844e9f 100644--- a/crates/agent_harness/src/domain/claude.rs+++ b/crates/agent_harness/src/domain/claude.rs@@ -83,6 +83,8 @@ impl<P: CloudProvider, Repo: AgentSessionRepo, External: ExternalSessionRepo>pub async fn attach(&self, id: AgentSessionId) -> Result<Arc<Session<P::Client>>> {let _creation = self.creation.lock().await;let row = AgentSessionRepo::get(&self.repo, id).await?;+ let model =+ claude_cloud_agents::domain::models::Model::parse(&row.model).map_err(cloud_error)?;let client = self.provider.connect(row.owner_id.as_ref())@@ -122,7 +124,7 @@ impl<P: CloudProvider, Repo: AgentSessionRepo, External: ExternalSessionRepo>).await?;let cloud_id = match client- .create(row.instructions.as_deref().unwrap_or_default())+ .create(row.instructions.as_deref().unwrap_or_default(), &model).await{Ok(id) => id,@@ -152,11 +154,7 @@ impl<P: CloudProvider, Repo: AgentSessionRepo, External: ExternalSessionRepo>cloud_id}};- Ok(Session::with_model(- client,- cloud_id,- claude_cloud_agents::domain::models::Model::parse(&row.model).map_err(cloud_error)?,- ))+ Ok(Session::with_model(client, cloud_id, model))}}diff --git a/crates/agent_harness/src/domain/claude/test.rs b/crates/agent_harness/src/domain/claude/test.rsindex 1fae9ad0e3..39d3080a2e 100644--- a/crates/agent_harness/src/domain/claude/test.rs+++ b/crates/agent_harness/src/domain/claude/test.rs@@ -14,6 +14,7 @@ use std::sync::Mutex;#[derive(Default)]struct Provider {calls: Arc<Mutex<Vec<(String, String)>>>,+ models: Arc<Mutex<Vec<String>>>,uncertain: bool,preparations: Arc<Mutex<Vec<(String, String)>>>,preparation_fails: bool,@@ -22,6 +23,7 @@ struct Provider {struct Client {owner: String,calls: Arc<Mutex<Vec<(String, String)>>>,+ models: Arc<Mutex<Vec<String>>>,uncertain: bool,preparations: Arc<Mutex<Vec<(String, String)>>>,preparation_fails: bool,@@ -32,6 +34,7 @@ impl CloudProvider for Provider {Ok(Client {owner: owner.into(),calls: self.calls.clone(),+ models: self.models.clone(),uncertain: self.uncertain,preparations: self.preparations.clone(),preparation_fails: self.preparation_fails,@@ -55,7 +58,9 @@ impl CloudLifecycle for Client {async fn create(&self,instructions: &str,+ model: &claude_cloud_agents::domain::models::Model,) -> claude_cloud_agents::domain::model::Result<SessionId> {+ self.models.lock().unwrap().push(model.id().to_owned());assert!(self.preparations.lock()@@ -77,7 +82,11 @@ impl CloudLifecycle for Client {}}impl Cloud for Client {- async fn recent_sessions(&self) -> claude_cloud_agents::domain::model::Result<Vec<SessionId>> {+ async fn models(+ &self,+ ) -> claude_cloud_agents::domain::model::Result<+ Vec<claude_cloud_agents::domain::models::ModelOption>,+ > {Ok(vec![])}async fn history(@@ -174,6 +183,7 @@ async fn distinct_agents_keep_their_owner_instructions_model_and_remote_session("Fix tests",).await;+ repo.set_model(first, "claude-fable-5-1").await.unwrap();let provider = Arc::new(Provider::default());let sessions = ClaudeSessions::new(provider.clone(),@@ -184,7 +194,11 @@ async fn distinct_agents_keep_their_owner_instructions_model_and_remote_session(let one = sessions.attach(first).await.unwrap();let two = sessions.attach(second).await.unwrap();assert_ne!(one.id(), two.id());- assert_eq!(one.model().await.id(), "claude-default");+ assert_eq!(one.model().await.id(), "claude-fable-5-1");+ assert_eq!(+ *provider.models.lock().unwrap(),+ vec!["claude-fable-5-1", "claude-default"]+ );assert_eq!(sessions.attach(first).await.unwrap().id(), one.id());assert_eq!(provider.preparations.lock().unwrap().len(), 2);assert_eq!(diff --git a/crates/agent_harness/src/domain/model_load/test.rs b/crates/agent_harness/src/domain/model_load/test.rsindex 2bd594eb50..88fc71a4ee 100644--- a/crates/agent_harness/src/domain/model_load/test.rs+++ b/crates/agent_harness/src/domain/model_load/test.rs@@ -90,6 +90,63 @@ impl CursorModelProbe for Probe {}}+impl ClaudeModelProbe for Probe {+ fn probe<'a>(+ &'a self,+ _caller: &'a MacroUserIdStr<'static>,+ ) -> std::pin::Pin<Box<dyn Future<Output = Result<RawModelProbe, ModelProbeError>> + Send + 'a>>+ {+ Box::pin(async move {+ self.calls.fetch_add(1, Ordering::Relaxed);+ (self.result)()+ })+ }+}++#[tokio::test]+async fn claude_models_are_never_returned_for_in_memory() {+ let claude = std::sync::Arc::new(Probe::new(|| {+ Ok(RawModelProbe::Options(vec![SessionConfigOption::select(+ "model",+ "Model",+ SessionConfigValueId::new("claude-fable-5-1"),+ vec![SessionConfigSelectOption::new(+ "claude-fable-5-1",+ "Fable 5.1",+ )],+ )]))+ }));+ let service = AgentModelsServiceImpl::new(+ Access(true),+ Probe::new(available),+ Probe::new(unsupported),+ Probe::new(unsupported),+ Duration::from_secs(1),+ )+ .with_claude(claude.clone());++ for (harness, expected) in [+ (ModelHarness::ClaudeCloud, "claude-fable-5-1"),+ (ModelHarness::InMemory, "fast"),+ ] {+ let result = service+ .load(+ caller(),+ LoadAgentModels {+ harness,+ harness_id: None,+ },+ )+ .await+ .unwrap();+ assert_eq!(result.status, AgentModelsStatus::Available);+ assert_eq!(result.models.len(), 1);+ assert_eq!(result.models[0].id, expected);+ }+ assert_eq!(claude.calls(), 1);+ assert_eq!(service.in_memory.calls(), 1);+}+impl MacrodModelProbe for Probe {async fn probe(&self, _harness: HarnessId) -> Result<RawModelProbe, ModelProbeError> {self.calls.fetch_add(1, Ordering::Relaxed);diff --git a/crates/claude_cloud_agents/examples/smoke.rs b/crates/claude_cloud_agents/examples/smoke.rsindex 77655c0cd5..a04c8d49f6 100644--- a/crates/claude_cloud_agents/examples/smoke.rs+++ b/crates/claude_cloud_agents/examples/smoke.rs@@ -5,7 +5,7 @@ use agent_runtime_protocol::domain::{};use clap::Parser;use claude_cloud_agents::{- domain::{model::SessionId, service::Session},+ domain::{model::SessionId, models, service::Session},inbound::acp,outbound::{credentials::FileCredentials, http::Client},};@@ -20,6 +20,12 @@ struct Args {/// Existing cloud conversation. Omitting this creates one new conversation.#[arg(long)]session: Option<String>,+ /// Discover choices without creating a session or spending inference.+ #[arg(long)]+ discover_only: bool,+ /// Select a discovered model before sending the smoke prompt.+ #[arg(long)]+ model: Option<String>,}fn send(channel: &ServerChannel, value: Value) {@@ -51,9 +57,22 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {let args = Args::parse();let credentials = FileCredentials::open(args.credentials).await?;let client = Client::new(credentials, args.owner).await?;+ if args.discover_only {+ for option in models::discover(&client).await?.options() {+ println!("{}: {}", option.model.id(), option.name);+ }+ return Ok(());+ }let id = match args.session {Some(id) => SessionId::parse(&id)?,- None => client.create("").await?,+ None => {+ client+ .create(+ "",+ &models::Model::parse(args.model.as_deref().unwrap_or("default"))?,+ )+ .await?+ }};println!("Testing Claude cloud session {}", id.as_str());let session = Session::new(client, id.clone());@@ -72,6 +91,17 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {loaded.get("result").is_some(),"history load failed: {loaded}");+ if let Some(model) = args.model {+ send(+ &channel,+ json!({"jsonrpc":"2.0","id":4,"method":"session/set_config_option","params":{"sessionId":id.as_str(),"configId":"model","value":model}}),+ );+ let selected = response(&mut channel, 4).await;+ assert!(+ selected.get("result").is_some(),+ "model selection failed: {selected}"+ );+ }send(&channel,json!({"jsonrpc":"2.0","id":3,"method":"session/prompt","params":{"sessionId":id.as_str(),"prompt":[{"type":"text","text":"Reply exactly MACRO_CLAUDE_HARNESS_OK. Do not use tools, read files, access the network, or modify anything."}]}}),diff --git a/crates/claude_cloud_agents/src/domain/models.rs b/crates/claude_cloud_agents/src/domain/models.rsindex 20d3ae66b1..890a53eea9 100644--- a/crates/claude_cloud_agents/src/domain/models.rs+++ b/crates/claude_cloud_agents/src/domain/models.rs@@ -38,7 +38,7 @@ impl Model {}}-/// One choice reported by the cloud worker.+/// One choice reported by the account catalog or cloud worker.#[derive(Clone, Debug, PartialEq, Eq)]pub struct ModelOption {/// Provider model ID, normalized only for default.@@ -55,7 +55,7 @@ pub enum Catalog {/// Bootstrap without claiming account-entitled models.#[default]Unknown,- /// Complete, ordered catalog from a successful initialization response.+ /// Ordered choices from the account catalog or successful initialization.Reported(Vec<ModelOption>),}impl Catalog {@@ -111,28 +111,42 @@ impl Catalog {}],}}- /// Reject choices absent from the latest provider catalog.+ /// Add account choices, preserving this session catalog's labels+ /// and order for duplicate IDs. Unknown catalogs do not manufacture defaults.+ pub fn supplemented_by(self, other: Self) -> Self {+ match (self, other) {+ (Self::Unknown, catalog) | (catalog, Self::Unknown) => catalog,+ (Self::Reported(mut options), Self::Reported(other)) => {+ let mut seen: std::collections::BTreeSet<_> = options+ .iter()+ .map(|option| option.model.id().to_owned())+ .collect();+ options.extend(+ other+ .into_iter()+ .filter(|option| seen.insert(option.model.id().to_owned())),+ );+ Self::Reported(options)+ }+ }+ }++ /// Reject choices absent from the provider-reported choices.pub fn contains(&self, model: &Model) -> bool {self.options().iter().any(|option| &option.model == model)}}-/// Discover without creating sessions or inference. The source is account-scoped;-/// catalogs are never cached across owners. This is a last-reported catalog,-/// not a fresh entitlement guarantee.+/// Discover from the account catalog without reading transcripts or starting a+/// worker. The provider still validates the selected model when a turn runs.pub async fn discover<C: Cloud>(cloud: &C) -> Result<Catalog> {- for id in cloud.recent_sessions().await?.into_iter().take(5) {- let history = match cloud.history(&id).await {- Ok(history) => history,- Err(Error::Http(404 | 410)) => continue,- Err(error) => return Err(error),- };- let catalog = Catalog::from_history(&history);- if matches!(catalog, Catalog::Reported(_)) {- return Ok(catalog);- }- }- Ok(Catalog::Unknown)+ let models = cloud.models().await?;+ let default = ModelOption {+ model: Model::default(),+ name: "Claude · subscription default".into(),+ description: Some("Let Claude choose the subscription's default model.".into()),+ };+ Ok(Catalog::Reported(vec![default]).supplemented_by(Catalog::Reported(models)))}#[cfg(test)]diff --git a/crates/claude_cloud_agents/src/domain/models/test.rs b/crates/claude_cloud_agents/src/domain/models/test.rsindex 55471f2c4a..af083e7503 100644--- a/crates/claude_cloud_agents/src/domain/models/test.rs+++ b/crates/claude_cloud_agents/src/domain/models/test.rs@@ -66,19 +66,18 @@ fn rejects_duplicate_aliases_malformed_catalogs_and_unsuccessful_responses() {#[derive(Clone)]struct AccountCloud {- histories: Vec<Vec<Event>>,- reads: std::sync::Arc<std::sync::atomic::AtomicUsize>,+ models: Vec<ModelOption>,+ fails: bool,}impl Cloud for AccountCloud {- async fn recent_sessions(&self) -> Result<Vec<super::super::model::SessionId>> {- (0..self.histories.len())- .map(|i| super::super::model::SessionId::parse(&format!("cse_{i}")))- .collect()+ async fn models(&self) -> Result<Vec<ModelOption>> {+ if self.fails {+ return Err(Error::Http(403));+ }+ Ok(self.models.clone())}- async fn history(&self, session: &super::super::model::SessionId) -> Result<Vec<Event>> {- self.reads.fetch_add(1, std::sync::atomic::Ordering::SeqCst);- let i: usize = session.as_str().trim_start_matches("cse_").parse().unwrap();- Ok(self.histories[i].clone())+ async fn history(&self, _: &super::super::model::SessionId) -> Result<Vec<Event>> {+ panic!("model discovery must not read any transcript")}async fn send(&self, _: &super::super::model::SessionId, _: serde_json::Value) -> Result<()> {panic!("discovery is read-only")@@ -100,32 +99,40 @@ impl Cloud for AccountCloud {}#[tokio::test]-async fn discovery_is_bounded_account_scoped_and_skips_uninitialized_sessions() {+async fn discovery_returns_account_models_without_any_sessions() {let first = AccountCloud {- histories: vec![- vec![],- vec![event(json!([{"value":"account-a","displayName":"A"}]))],- ],- reads: Default::default(),+ models: vec![ModelOption {+ model: Model::parse("claude-fable-5-1").unwrap(),+ name: "Claude Fable 5.1".into(),+ description: None,+ }],+ fails: false,};let second = AccountCloud {- histories: vec![vec![event(- json!([{"value":"account-b","displayName":"B"}]),- )]],- reads: Default::default(),+ models: vec![ModelOption {+ model: Model::parse("another-account-model").unwrap(),+ name: "Another account model".into(),+ description: None,+ }],+ fails: false,};- assert_eq!(- discover(&first).await.unwrap().options()[0].model.id(),- "account-a"- );- assert_eq!(- discover(&second).await.unwrap().options()[0].model.id(),- "account-b"- );- let empty = AccountCloud {- histories: vec![vec![]; 6],- reads: Default::default(),+ let fable = Model::parse("claude-fable-5-1").unwrap();+ let catalog = discover(&first).await.unwrap();+ assert!(catalog.contains(&Model::default()));+ assert!(catalog.contains(&fable));+ assert_eq!(catalog.options()[1].name, "Claude Fable 5.1");+ assert!(!discover(&second).await.unwrap().contains(&fable));+}++#[tokio::test]+async fn discovery_surfaces_errors_and_does_not_fall_back_to_history() {+ let mut cloud = AccountCloud {+ models: vec![],+ fails: true,};- assert_eq!(discover(&empty).await.unwrap(), Catalog::Unknown);- assert_eq!(empty.reads.load(std::sync::atomic::Ordering::SeqCst), 5);+ assert!(matches!(discover(&cloud).await, Err(Error::Http(403))));+ cloud.fails = false;+ let catalog = discover(&cloud).await.unwrap();+ assert_eq!(catalog.options().len(), 1);+ assert!(catalog.contains(&Model::default()));}diff --git a/crates/claude_cloud_agents/src/domain/ports.rs b/crates/claude_cloud_agents/src/domain/ports.rsindex bc93523680..af82730d10 100644--- a/crates/claude_cloud_agents/src/domain/ports.rs+++ b/crates/claude_cloud_agents/src/domain/ports.rs@@ -1,5 +1,6 @@//! Capabilities needed by the Claude session adapter.use super::model::{Event, Result, SessionId};+use super::models::{Model, ModelOption};use futures::Stream;use std::{future::Future, pin::Pin};@@ -19,8 +20,12 @@ pub trait CloudLifecycle: Cloud {/// Ensure the owner's selected environment allows this deployment's MCP host./// Must finish before creating a container, whose network policy is fixed.fn prepare_mcp_access(&self, host: &str) -> impl Future<Output = Result<()>> + Send;- /// Create a conversation with this agent's instructions.- fn create(&self, instructions: &str) -> impl Future<Output = Result<SessionId>> + Send;+ /// Create a conversation with this agent's instructions and starting model.+ fn create(+ &self,+ instructions: &str,+ model: &Model,+ ) -> impl Future<Output = Result<SessionId>> + Send;/// Archive the owner's conversation reversibly.fn archive(&self, session: &SessionId) -> impl Future<Output = Result<()>> + Send;}@@ -46,8 +51,9 @@ impl ToolPermissions for DenyToolPermissions {/// Account-scoped provider operations. Implementors must never choose another user's credential.pub trait Cloud: Clone + Send + Sync + 'static {- /// At most five recent sessions visible through this account's credential.- fn recent_sessions(&self) -> impl Future<Output = Result<Vec<SessionId>>> + Send;+ /// Complete model catalog fetched directly with this account's credential.+ /// Discovery must not read transcripts, create sessions, or spend inference.+ fn models(&self) -> impl Future<Output = Result<Vec<ModelOption>>> + Send;/// Submit one event. Mutations are not automatically retried.fn send(&self,diff --git a/crates/claude_cloud_agents/src/domain/service.rs b/crates/claude_cloud_agents/src/domain/service.rsindex 5e3939bacb..9a8a5de0f1 100644--- a/crates/claude_cloud_agents/src/domain/service.rs+++ b/crates/claude_cloud_agents/src/domain/service.rs@@ -21,6 +21,7 @@ pub struct Session<C> {translator: Mutex<Translator>,model: Mutex<Model>,catalog: Mutex<Catalog>,+ account_catalog: Mutex<Catalog>,mcp_servers: Mutex<Option<McpServers>>,}@@ -43,6 +44,7 @@ impl<C: Cloud> Session<C> {translator: Mutex::new(Translator::default()),model: Mutex::new(model),catalog: Mutex::new(Catalog::Unknown),+ account_catalog: Mutex::new(Catalog::Unknown),mcp_servers: Mutex::new(None),})}@@ -51,19 +53,21 @@ impl<C: Cloud> Session<C> {self.model.lock().await.clone()}- /// Current provider catalog, or the explicit default-only bootstrap state.+ /// Current session aliases supplemented by the direct account catalog.pub async fn catalog(&self) -> Catalog {- self.catalog.lock().await.clone()+ self.catalog+ .lock()+ .await+ .clone()+ .supplemented_by(self.account_catalog.lock().await.clone())}/// Read-only discovery; never starts a cloud worker merely to populate a picker.pub async fn refresh_catalog(&self) -> Result<()> {let history = self.cloud.history(&self.id).await?;- let mut catalog = Catalog::from_history(&history);- if matches!(catalog, Catalog::Unknown) {- catalog = super::models::discover(&self.cloud).await?;- }- *self.catalog.lock().await = catalog;+ let account = super::models::discover(&self.cloud).await?;+ *self.catalog.lock().await = Catalog::from_history(&history);+ *self.account_catalog.lock().await = account;Ok(())}@@ -76,7 +80,9 @@ impl<C: Cloud> Session<C> {let mut catalog = self.catalog.lock().await;if *catalog != next {emit(Update::Models {- catalog: next.clone(),+ catalog: next+ .clone()+ .supplemented_by(self.account_catalog.lock().await.clone()),current: self.model().await,})?;*catalog = next;@@ -134,9 +140,7 @@ impl<C: Cloud> Session<C> {}*self.cursor.lock().await = cursor;*self.translator.lock().await = translator;- if matches!(self.catalog().await, Catalog::Unknown) {- *self.catalog.lock().await = super::models::discover(&self.cloud).await?;- }+ *self.account_catalog.lock().await = super::models::discover(&self.cloud).await?;Ok(updates)}@@ -232,7 +236,10 @@ impl<C: Cloud> Session<C> {return Err(Error::Busy);}if !self.catalog().await.contains(&self.model().await) {- return Err(Error::ModelUnavailable);+ self.refresh_catalog().await?;+ if !self.catalog().await.contains(&self.model().await) {+ return Err(Error::ModelUnavailable);+ }}let mut translator = self.translator.lock().await;// Catch completed foreign turns even if a prompt beats the next poll.diff --git a/crates/claude_cloud_agents/src/domain/service/test.rs b/crates/claude_cloud_agents/src/domain/service/test.rsindex 77bbfc0a27..cf57ebe9a8 100644--- a/crates/claude_cloud_agents/src/domain/service/test.rs+++ b/crates/claude_cloud_agents/src/domain/service/test.rs@@ -10,7 +10,7 @@ struct ReconnectingCloud {history: Arc<Mutex<Vec<Event>>>,}impl Cloud for ReconnectingCloud {- async fn recent_sessions(&self) -> Result<Vec<SessionId>> {+ async fn models(&self) -> Result<Vec<crate::domain::models::ModelOption>> {Ok(Vec::new())}async fn send_batch(@@ -171,11 +171,13 @@ struct ModelCloud {sends: Arc<Mutex<Vec<serde_json::Value>>>,reject: Arc<std::sync::atomic::AtomicBool>,reject_model: Arc<std::sync::atomic::AtomicBool>,+ account_models: Arc<Mutex<Vec<crate::domain::models::ModelOption>>>,}impl Cloud for ModelCloud {- async fn recent_sessions(&self) -> Result<Vec<SessionId>> {- Ok(Vec::new())+ async fn models(&self) -> Result<Vec<crate::domain::models::ModelOption>> {+ Ok(self.account_models.lock().await.clone())}+async fn send(&self, _: &SessionId, payload: serde_json::Value) -> Result<()> {if self.reject.load(Ordering::SeqCst) {return Err(Error::Network);@@ -220,6 +222,65 @@ impl Cloud for ModelCloud {}}+#[tokio::test]+async fn account_fable_choice_survives_selection_load_poll_and_prompt() {+ let cloud = ModelCloud::default();+ *cloud.account_models.lock().await = vec![crate::domain::models::ModelOption {+ model: Model::parse("claude-fable-5-1").unwrap(),+ name: "Fable 5.1".into(),+ description: None,+ }];+ let fable = Model::parse("claude-fable-5-1").unwrap();+ let id = SessionId::parse("cse_test").unwrap();+ let session = Session::new(cloud.clone(), id.clone());+ session.set_model(fable.clone()).await.unwrap();+ assert_eq!(cloud.sends.lock().await[0]["request"]["model"], fable.id());+ assert!(matches!(+ session+ .set_model(Model::parse("not-reported").unwrap())+ .await,+ Err(Error::ModelUnavailable)+ ));++ let restored = Session::with_model(cloud.clone(), id, fable.clone());+ restored.load().await.unwrap();+ assert!(restored.catalog().await.contains(&fable));+ let changed = Event {+ kind: "client_event".into(),+ sequence: Some(1),+ data: json!({"payload":{"type":"control_response","response":{"subtype":"success","response":{"models":[+ {"value":"sonnet","displayName":"New Sonnet label"}+ ]}}}}),+ };+ restored+ .learn_catalog(&changed, |update| {+ let Update::Models { catalog, current } = update else {+ panic!("expected catalog")+ };+ assert!(catalog.contains(&fable));+ assert_eq!(current, fable);+ assert!(!catalog.contains(&Model::parse("opus").unwrap()));+ Ok(())+ })+ .await+ .unwrap();+ restored.prompt("hello".into(), |_| Ok(())).await.unwrap();+ assert_eq!(cloud.sends.lock().await[1]["request"]["model"], fable.id());++ // Claude still has final authority to reject an account-discovered choice.+ cloud.reject_model.store(true, Ordering::SeqCst);+ let restored = Session::with_model(cloud.clone(), SessionId::parse("cse_test").unwrap(), fable);+ restored.load().await.unwrap();+ assert!(matches!(+ restored.prompt("hello".into(), |_| Ok(())).await,+ Err(Error::ModelUnavailable)+ ));+ assert_eq!(+ cloud.sends.lock().await.last().unwrap()["request"]["subtype"],+ "interrupt"+ );+}+#[tokio::test]async fn idle_model_preference_does_not_wait_for_worker_and_failed_sends_preserve_it() {let cloud = ModelCloud::default();diff --git a/crates/claude_cloud_agents/src/inbound/acp/test.rs b/crates/claude_cloud_agents/src/inbound/acp/test.rsindex 1178703290..07f0970619 100644--- a/crates/claude_cloud_agents/src/inbound/acp/test.rs+++ b/crates/claude_cloud_agents/src/inbound/acp/test.rs@@ -11,7 +11,7 @@ struct FakeCloud {history: Arc<tokio::sync::Mutex<Vec<Event>>>,}impl Cloud for FakeCloud {- async fn recent_sessions(&self) -> Result<Vec<SessionId>> {+ async fn models(&self) -> Result<Vec<crate::domain::models::ModelOption>> {Ok(Vec::new())}async fn send_batch(&self, session: &SessionId, payloads: Vec<Value>) -> Result<()> {diff --git a/crates/claude_cloud_agents/src/inbound/acp/test/mcp.rs b/crates/claude_cloud_agents/src/inbound/acp/test/mcp.rsindex 0f4951c316..bc9e044635 100644--- a/crates/claude_cloud_agents/src/inbound/acp/test/mcp.rs+++ b/crates/claude_cloud_agents/src/inbound/acp/test/mcp.rs@@ -32,7 +32,7 @@ impl McpCloud {}}impl Cloud for McpCloud {- async fn recent_sessions(&self) -> Result<Vec<SessionId>> {+ async fn models(&self) -> Result<Vec<crate::domain::models::ModelOption>> {Ok(vec![])}async fn history(&self, _: &SessionId) -> Result<Vec<Event>> {diff --git a/crates/claude_cloud_agents/src/outbound/http.rs b/crates/claude_cloud_agents/src/outbound/http.rsindex b260cfdab8..c79ff3dd01 100644--- a/crates/claude_cloud_agents/src/outbound/http.rs+++ b/crates/claude_cloud_agents/src/outbound/http.rs@@ -3,6 +3,7 @@ use crate::domain::{credentials::AccountCredentials,environment::gateway_network_patch,model::{Error, Event, Result, SessionId},+ models::{Model, ModelOption},ports::{Cloud, CloudLifecycle, CloudProvider, Events},};use futures::StreamExt;@@ -11,6 +12,8 @@ use std::collections::VecDeque;const API: &str = "https://api.anthropic.com";const BETA: &str = "ccr-byoc-2025-07-29";+const MODEL_PAGE_SIZE: usize = 1000;+const MODEL_PAGE_LIMIT: u8 = 10;/// HTTP client pinned to one Macro account and the official Anthropic origin.#[derive(Clone)]@@ -98,9 +101,12 @@ impl Client {}/// Create only in the explicitly selected, active Anthropic cloud environment.- pub async fn create(&self, instructions: &str) -> Result<SessionId> {+ pub async fn create(&self, instructions: &str, model: &Model) -> Result<SessionId> {let environment = self.selected_environment().await?;let mut config = json!({"sources": [], "outcomes": []});+ if let Some(model) = model.provider_value() {+ config["model"] = json!(model);+ }if !instructions.is_empty() {config["append_system_prompt"] = json!(instructions);}@@ -170,8 +176,8 @@ impl CloudLifecycle for Client {Ok(())}- async fn create(&self, instructions: &str) -> Result<SessionId> {- Client::create(self, instructions).await+ async fn create(&self, instructions: &str, model: &Model) -> Result<SessionId> {+ Client::create(self, instructions, model).await}async fn archive(&self, session: &SessionId) -> Result<()> {@@ -180,20 +186,40 @@ impl CloudLifecycle for Client {}impl Cloud for Client {- async fn recent_sessions(&self) -> Result<Vec<SessionId>> {- let response: Value = self- .request("/v1/code/sessions?limit=5", None)- .await?- .json()+ async fn models(&self) -> Result<Vec<ModelOption>> {+ let credentials = self.credentials.resolve(&self.owner).await?;+ let mut models = Vec::new();+ let mut seen = std::collections::BTreeSet::new();+ let mut after = None;+ for _ in 0..MODEL_PAGE_LIMIT {+ let response = models_request(+ &self.http,+ credentials.access_token.expose(),+ &credentials.organization_id,+ after.as_ref(),+ )+ .send().await- .map_err(|_| Error::Protocol)?;- response["data"]- .as_array()- .ok_or(Error::Protocol)?- .iter()- .take(5)- .map(|row| SessionId::parse(row["id"].as_str().ok_or(Error::Protocol)?))- .collect()+ .map_err(|_| Error::Network)?;+ let page = checked(response)?+ .json()+ .await+ .map_err(|_| Error::Protocol)?;+ let (options, next) = model_page(page)?;+ for option in options {+ if !seen.insert(option.model.id().to_owned()) {+ return Err(Error::Protocol);+ }+ models.push(option);+ }+ match next {+ None => return Ok(models),+ Some(next) if after.as_ref() != Some(&next) => after = Some(next),+ Some(_) => return Err(Error::Protocol),+ }+ }+ // Never advertise a silently truncated catalog.+ Err(Error::Protocol)}async fn send_batch(&self, session: &SessionId, payloads: Vec<Value>) -> Result<()> {self.request(@@ -335,6 +361,60 @@ impl Cloud for Client {}}+// The code-session beta is not accepted by the standard models endpoint.+fn models_request(+ http: &reqwest::Client,+ token: &str,+ organization: &str,+ after: Option<&Model>,+) -> reqwest::RequestBuilder {+ let request = http+ .get(format!("{API}/v1/models"))+ .bearer_auth(token)+ .header("anthropic-version", "2023-06-01")+ .header("x-organization-uuid", organization)+ .query(&[("limit", MODEL_PAGE_SIZE)])+ .timeout(std::time::Duration::from_secs(30));+ match after {+ Some(model) => request.query(&[("after_id", model.id())]),+ None => request,+ }+}++fn model_page(response: Value) -> Result<(Vec<ModelOption>, Option<Model>)> {+ let rows = response["data"].as_array().ok_or(Error::Protocol)?;+ if rows.len() > MODEL_PAGE_SIZE {+ return Err(Error::Protocol);+ }+ let options = rows+ .iter()+ .map(|row| {+ let model = Model::parse(row["id"].as_str().ok_or(Error::Protocol)?)+ .map_err(|_| Error::Protocol)?;+ let name = row["display_name"].as_str().ok_or(Error::Protocol)?;+ if name.trim().is_empty() || name.len() > 512 {+ return Err(Error::Protocol);+ }+ Ok(ModelOption {+ model,+ name: name.into(),+ description: None,+ })+ })+ .collect::<Result<Vec<_>>>()?;+ let next = match response["has_more"].as_bool().ok_or(Error::Protocol)? {+ false => None,+ true => {+ let last = options.last().ok_or(Error::Protocol)?;+ if response["last_id"].as_str() != Some(last.model.id()) {+ return Err(Error::Protocol);+ }+ Some(last.model.clone())+ }+ };+ Ok((options, next))+}+fn checked(response: reqwest::Response) -> Result<reqwest::Response> {match response.status().as_u16() {200..=299 => Ok(response),diff --git a/crates/claude_cloud_agents/src/outbound/http/test.rs b/crates/claude_cloud_agents/src/outbound/http/test.rsindex 2d68b5dfa2..803e7a98f1 100644--- a/crates/claude_cloud_agents/src/outbound/http/test.rs+++ b/crates/claude_cloud_agents/src/outbound/http/test.rs@@ -1,5 +1,70 @@use super::*;+#[test]+fn direct_models_request_uses_oauth_and_pagination_without_session_beta() {+ let after = Model::parse("claude-fable-5-1").unwrap();+ let request = models_request(+ &reqwest::Client::new(),+ "test-token",+ "test-org",+ Some(&after),+ )+ .build()+ .unwrap();+ assert_eq!(request.method(), reqwest::Method::GET);+ assert_eq!(request.url().origin().ascii_serialization(), API);+ assert_eq!(request.url().path(), "/v1/models");+ assert_eq!(+ request.url().query_pairs().collect::<Vec<_>>(),+ vec![+ ("limit".into(), "1000".into()),+ ("after_id".into(), after.id().into())+ ]+ );+ assert_eq!(request.headers()["authorization"], "Bearer test-token");+ assert_eq!(request.headers()["x-organization-uuid"], "test-org");+ assert_eq!(request.headers()["anthropic-version"], "2023-06-01");+ assert!(!request.headers().contains_key("anthropic-beta"));+ assert!(request.body().is_none());+}++#[test]+fn direct_catalog_preserves_api_ids_names_order_and_next_cursor() {+ let (models, next) = model_page(json!({+ "data": [+ {"id":"claude-fable-5-1","display_name":"Claude Fable 5.1"},+ {"id":"brand-new-model","display_name":"New model"}+ ],+ "has_more":true,+ "last_id":"brand-new-model"+ }))+ .unwrap();+ assert_eq!(models[0].model.id(), "claude-fable-5-1");+ assert_eq!(models[0].name, "Claude Fable 5.1");+ assert_eq!(models[1].model.id(), "brand-new-model");+ assert_eq!(next.unwrap().id(), "brand-new-model");+ let (models, next) = model_page(json!({"data":[],"has_more":false})).unwrap();+ assert!(models.is_empty());+ assert!(next.is_none());+}++#[test]+fn malformed_catalogs_and_broken_pagination_fail_instead_of_truncating() {+ for response in [+ json!({}),+ json!({"data":[],"has_more":true,"last_id":"missing"}),+ json!({"data":[{"id":"model","display_name":"Model"}],"has_more":true}),+ json!({"data":[{"id":"model","display_name":"Model"}],"has_more":true,"last_id":"different"}),+ json!({"data":[{"id":"../model","display_name":"Model"}],"has_more":false}),+ json!({"data":[{"id":"model","display_name":" "}],"has_more":false}),+ json!({"data":[{"id":"model"}],"has_more":false}),+ json!({"data":[],"has_more":"false"}),+ json!({"data":vec![json!({"id":"model","display_name":"Model"}); MODEL_PAGE_SIZE + 1],"has_more":false}),+ ] {+ assert!(matches!(model_page(response), Err(Error::Protocol)));+ }+}+#[test]fn model_and_prompt_are_serialized_in_one_ordered_batch() {let batch = event_batch(vec![diff --git a/docs/CLAUDE_CLOUD_DEMO.md b/docs/CLAUDE_CLOUD_DEMO.mdindex c3271aa51a..882b56230c 100644--- a/docs/CLAUDE_CLOUD_DEMO.md+++ b/docs/CLAUDE_CLOUD_DEMO.md@@ -86,8 +86,8 @@ Claude's consent page and completing the one-time code exchange.## Use in Macro1. Connect through the Claude row in Settings → Harness, then create or edit a private agent in Settings → Agents.-2. Select **Claude Cloud**. It is offered only when model discovery confirms that your Macro identity has a configured connection.-3. Choose from Claude's reported model catalog. Settings reads up to five recent sessions through your connected account and uses the first available initialization catalog; an existing session uses its own latest catalog. IDs, names, descriptions, and ordering come from Claude, not a fixed list. With no catalog yet, only **Claude · subscription default** is offered, with an explanatory description. The first prompt requests initialization alongside the model and user message, and the picker updates when Claude reports its catalog. Subsequent catalogs replace old choices during polling and streaming without resetting your saved preference. This is last-reported availability, not a fresh entitlement guarantee. Selection saves the next-turn preference after event submission; it does not wait for an idle worker. Each prompt repeats that preference immediately before the user message in one ordered batch, including after a Macro restart. A worker rejection surfaces an error and requests interruption; this cannot guarantee zero inference before the rejection arrives.+2. Select **Claude Cloud**. It is offered for new selections only when model discovery confirms that your Macro identity has a configured connection. When editing a saved Claude agent, the harness stays visibly selected while discovery loads or fails. Models belong to the selected harness: Fable is available through Claude Cloud only, and switching to In-memory replaces the catalog and model preference with that harness's choices.+3. Choose from Claude's model catalog. Settings calls `GET /v1/models` with your connected account's OAuth credential, without the code-session beta header (which this endpoint rejects). Discovery follows pagination and fails visibly on provider errors or an incomplete catalog; it never scans recent sessions, reads transcripts, creates a worker, or spends inference. IDs, names, and ordering come from the API, with **Claude · subscription default** retained as the provider's reset choice. Fable can appear even when you have no previous sessions. New conversations pass the selected model in Claude's creation configuration. Existing conversations retain aliases reported by their own worker alongside the direct account catalog. The first prompt requests initialization alongside the model and user message, and subsequent worker catalogs replace that session's aliases without removing account-listed choices or resetting your saved preference. The Models API is not a guarantee that every cloud worker accepts every listed model: Claude validates the request when the worker runs. Selection saves the next-turn preference after event submission; it does not wait for an idle worker. Each prompt repeats that preference immediately before the user message in one ordered batch, including after a Macro restart. A worker rejection surfaces an error and requests interruption; this cannot guarantee zero inference before the rejection arrives.4. Start a session with that agent or mention it in a channel. Prompts, follow-ups, text streaming, tool cards, cancellation, and transcript load use Macro's existing session interface.5. In the session header, use **Open in Claude** (the external-link icon; in the toolbar overflow on narrow screens). Existing demo sessions get the link too.6. Send a message on that Claude page. While the Macro runtime connection is live,@@ -129,7 +129,7 @@ The cloud worker must be able to reach the configured egress URL.## Demo boundary- Text prompts only; attachments and repository selection are not forwarded yet. Macro and configured Pipedream MCP servers use the shared session egress path. Built-in cloud tools retain provider policy; explicit permission requests are delegated to the Macro host.-- Model discovery is read-only and bounded to five recent account sessions. No catalog is shared across credential owners. New/removed model IDs require no code change; choices absent from the current catalog are rejected. Provider errors stay visible rather than silently substituting a fixed list. No local filesystem. Agent instructions are forwarded as `append_system_prompt`.+- Model discovery reads the account-scoped Models API with a bound of ten pages of 1,000 models each; exceeding that bound fails instead of returning a partial catalog. No catalog is shared across credential owners. New/removed API model IDs require no code change; existing sessions can also select their own worker-reported aliases. Provider errors stay visible rather than silently substituting a fixed list. No local filesystem. Agent instructions are forwarded as `append_system_prompt`.- Access tokens refresh shortly before expiry; rotated refresh tokens are encrypted and saved before provider use. If saving fails, the process retains the rotated grant and retries persistence rather than reusing the old refresh token. A revoked grant produces a reconnect error. No API-key fallback or quota bypass.- Prompt sends and session creation are not blindly retried. A durable `claude-cloud-create-pending` mapping prevents duplicate creation after an uncertain request or crash. An operator must inspect the Claude account before clearing a stuck intent.- SSE reconnect is bounded and resumes durable sequence numbers. Durable assistant text reconciles with already-delivered ephemeral text; an inconsistent/truncated replay fails visibly. Session/load recovers the durable transcript. A result ends a turn, not the conversation.@@ -195,6 +195,8 @@ cargo run -p claude_cloud_agents --example smoke -- \--session cse_existing_session```+Use `--discover-only` to print API-discovered model IDs and names without creating a session or sending a prompt. Add `--model <advertised-id>` to verify selecting that model before the smoke prompt.+Omitting `--session` creates a new cloud conversation. Do not automatically rerun a failed create; inspect the account first. The runner prints only the session identity and outcome, not tokens or private transcript contents.## MCP gateway networking