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): enable hosted Claude browser sign-in (#6529)
Eric Hayes2e7cf53076b7
diff --git a/.sqlx/query-0c69d12ce11ea87b4856ccb20039ec6f045f2753d3c27a5243b5d7debc124a75.json b/.sqlx/query-0c69d12ce11ea87b4856ccb20039ec6f045f2753d3c27a5243b5d7debc124a75.jsonnew file mode 100644index 0000000000..f7978a9aaa--- /dev/null+++ b/.sqlx/query-0c69d12ce11ea87b4856ccb20039ec6f045f2753d3c27a5243b5d7debc124a75.json@@ -0,0 +1,16 @@+{+ "db_name": "PostgreSQL",+ "query": "INSERT INTO claude_oauth_grants (user_id, grant_ciphertext, kms_key_id, encryption_version) VALUES ($1, $2, $3, 2) ON CONFLICT (user_id) DO UPDATE SET grant_ciphertext = EXCLUDED.grant_ciphertext, kms_key_id = EXCLUDED.kms_key_id, encryption_version = 2, updated_at = now()",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Text",+ "Bytea",+ "Text"+ ]+ },+ "nullable": []+ },+ "hash": "0c69d12ce11ea87b4856ccb20039ec6f045f2753d3c27a5243b5d7debc124a75"+}diff --git a/apps/web/src/features/block-agent/component/compose-agent-session-options.ts b/apps/web/src/features/block-agent/component/compose-agent-session-options.tsindex 528611d730..808207a48c 100644--- a/apps/web/src/features/block-agent/component/compose-agent-session-options.ts+++ b/apps/web/src/features/block-agent/component/compose-agent-session-options.ts@@ -80,7 +80,7 @@ export function agentRuntimeDescription(if (persona.harness === 'codex-cloud')return 'Runs in your selected Codex cloud environment';if (persona.harness === 'claude-cloud') {- return 'Runs in Claude’s cloud using your subscription. Demo: text prompts, no Macro connectors';+ return 'Runs in Claude’s cloud using your subscription';}if (persona.harness === 'macrod') {return `Do work locally using ${persona.name}${ownerName ? ` owned by ${ownerName}` : ''}`;diff --git a/apps/web/src/features/claude-connection/components/connection-card.test.tsx b/apps/web/src/features/claude-connection/components/connection-card.test.tsxindex 0c591e62b5..2bce004fbd 100644--- a/apps/web/src/features/claude-connection/components/connection-card.test.tsx+++ b/apps/web/src/features/claude-connection/components/connection-card.test.tsx@@ -26,7 +26,7 @@ function props(): ConnectionCardProps {it('shows Claude before connection and explains restart behavior', () => {const value = props();render(() => <ConnectionCard {...value} />);- expect(screen.getByText('Claude Cloud (demo)')).toBeTruthy();+ expect(screen.getByText('Claude Cloud')).toBeTruthy();expect(screen.getByText(/Reconnect after a backend restart/)).toBeTruthy();fireEvent.click(screen.getByRole('button', { name: 'Connect Claude' }));expect(value.onBegin).toHaveBeenCalledOnce();@@ -61,7 +61,7 @@ it('shows disabled and failed states instead of silently disappearing', () => {/>));expect(- screen.getByText(/enabled only in the local demo backend/)+ screen.getByText(/sign-in is not configured on this deployment/)).toBeTruthy();expect(screen.queryByRole('button', { name: 'Connect Claude' })).toBeNull();cleanup();diff --git a/apps/web/src/features/claude-connection/components/connection-card.tsx b/apps/web/src/features/claude-connection/components/connection-card.tsxindex 58c11d5b75..ea9f19b80b 100644--- a/apps/web/src/features/claude-connection/components/connection-card.tsx+++ b/apps/web/src/features/claude-connection/components/connection-card.tsx@@ -26,7 +26,7 @@ export function ConnectionCard(props: ConnectionCardProps) {</div><div class="flex min-w-0 flex-1 flex-col gap-3"><div class="flex items-center gap-2">- <h2 class="text-sm font-medium text-ink">Claude Cloud (demo)</h2>+ <h2 class="text-sm font-medium text-ink">Claude Cloud</h2><Show when={props.status?.connected}><span class="text-xs text-success">Connected</span></Show>@@ -49,13 +49,13 @@ export function ConnectionCard(props: ConnectionCardProps) {when={props.status?.enabled}fallback={<p class="text-xs text-ink-muted">- Browser connection is enabled only in the local demo backend.+ Claude sign-in is not configured on this deployment.</p>}><p class="text-xs text-ink-muted">{props.status?.ephemeral- ? 'Local demo: credentials stay in server memory. Reconnect after a backend restart.'+ ? 'Credentials stay in server memory. Reconnect after a backend restart.': 'Your connection is saved securely and survives backend restarts.'}{' '}Macro never asks for your Claude password.</p>@@ -142,9 +142,9 @@ export function ConnectionCard(props: ConnectionCardProps) {</Show><Show when={props.status?.connected}><p class="text-xs text-ink-muted">- Ready. In Settings → Agents, choose Claude Cloud (demo) as the- agent’s harness. Disconnecting forgets Macro’s grant; it does not- revoke consent at Claude or stop an already-running cloud turn.+ Ready. In Settings → Agents, choose Claude Cloud as the agent’s+ harness. Disconnecting forgets Macro’s grant; it does not revoke+ consent at Claude or stop an already-running cloud turn.</p></Show><Show when={props.error}>diff --git a/apps/web/src/features/settings/Agents.test.tsx b/apps/web/src/features/settings/Agents.test.tsxindex a420849e4f..e3147c7543 100644--- a/apps/web/src/features/settings/Agents.test.tsx+++ b/apps/web/src/features/settings/Agents.test.tsx@@ -321,7 +321,7 @@ describe('Agents', () => {render(() => <Agents />);fireEvent.click(screen.getByRole('button', { name: 'Create agent' }));const option = screen.queryByRole('option', {- name: 'Claude Cloud (demo)',+ name: 'Claude Cloud',});expect(Boolean(option)).toBe(enabled);const targets = vi.mocked(useAgentModelsQueries).mock.lastCall?.[0]();diff --git a/apps/web/src/features/settings/Agents.tsx b/apps/web/src/features/settings/Agents.tsxindex 0d06fe57d6..8031cdff25 100644--- a/apps/web/src/features/settings/Agents.tsx+++ b/apps/web/src/features/settings/Agents.tsx@@ -130,7 +130,7 @@ export function Agents() {if (target.harness === 'claude-cloud') {return {id: 'claude-cloud',- name: 'Claude Cloud (demo)',+ name: 'Claude Cloud',kind: 'builtin',target,};@@ -392,7 +392,7 @@ function summarizeAgent(function harnessName(id: string): string {if (id === 'in-memory') return 'In-memory';if (id === 'cursor') return 'Cursor';- if (id === 'claude-cloud') return 'Claude Cloud (demo)';+ if (id === 'claude-cloud') return 'Claude Cloud';// Any other id is a registered macrod harness uuid; if it is not in the// connected list any more, the harness has been removed.return 'Disconnected harness';diff --git a/apps/web/src/features/settings/Harness.test.tsx b/apps/web/src/features/settings/Harness.test.tsxindex 26f7934a80..83c9b4de02 100644--- a/apps/web/src/features/settings/Harness.test.tsx+++ b/apps/web/src/features/settings/Harness.test.tsx@@ -323,7 +323,7 @@ describe('Harness', () => {expect(screen.getByRole('heading', { name: 'In-memory' })).toBeTruthy();expect(screen.getByRole('heading', { name: 'Cursor' })).toBeTruthy();- const claude = screen.getByRole('heading', { name: 'Claude Cloud (demo)' });+ const claude = screen.getByRole('heading', { name: 'Claude Cloud' });const cursor = screen.getByRole('heading', { name: 'Cursor' });expect(claude.compareDocumentPosition(cursor) & Node.DOCUMENT_POSITION_FOLLOWINGdiff --git a/crates/claude_cloud_agents/src/domain/auth.rs b/crates/claude_cloud_agents/src/domain/auth.rsindex c1c4b741e1..f6103d63b7 100644--- a/crates/claude_cloud_agents/src/domain/auth.rs+++ b/crates/claude_cloud_agents/src/domain/auth.rs@@ -1,22 +1,17 @@//! One-time, owner-bound browser consent. No provider tokens cross the inbound boundary.+use super::credentials::{ConnectionState, GrantTransaction};use super::model::{Credentials, Error, Secret};use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD};-use std::{- collections::HashMap,- sync::Arc,- time::{Duration, Instant},-};+use std::time::{Duration, SystemTime, UNIX_EPOCH};use subtle::ConstantTimeEq;-use tokio::sync::Mutex;const LOGIN_TTL: Duration = Duration::from_secs(600);-const MAX_ATTEMPTS: usize = 1024;/// Redacted, user-actionable connection errors.#[derive(Debug, thiserror::Error)]pub enum AuthError {- /// This deployment does not enable interactive demo connections.- #[error("Claude connection is available only in the local demo")]+ /// This deployment has no configured connection store.+ #[error("Claude connection is not configured on this deployment")]Disabled,/// Attempt expired, was canceled, replayed, or belongs to another user.#[error("Sign-in expired or was replaced. Start Connect Claude again.")]@@ -24,7 +19,7 @@ pub enum AuthError {/// Manual callback input must contain Claude's code and matching state.#[error("Paste the complete one-time code from Claude, including the # suffix.")]InvalidCode,- /// Global capacity or repeated starts are bounded.+ /// Repeated starts are bounded per owner.#[error("Please wait a moment before starting another sign-in.")]Busy,/// Provider or storage failures never include response bodies or secrets.@@ -67,6 +62,11 @@ pub trait OAuthProvider: Send + Sync + 'static {/// Owner-keyed credential storage capability.pub trait ConnectionStore: Send + Sync + 'static {+ /// Lock the owner's complete connection state across replicas.+ fn lock(+ &self,+ owner: &str,+ ) -> impl Future<Output = Result<Box<dyn GrantTransaction>, Error>> + Send;/// Query presence without returning secrets.fn connected(&self, owner: &str) -> impl Future<Output = bool> + Send;/// Save a grant for exactly the authenticated owner.@@ -96,19 +96,31 @@ pub trait ClaudeAuth: Send + Sync + 'static {fn disconnect(&self, owner: &str) -> impl Future<Output = Result<(), AuthError>> + Send;}-struct Attempt {- id: String,- state: String,- verifier: Option<Secret>,- started: Instant,+/// Encrypted pending consent. No verifier is returned to the browser.+#[derive(Clone, serde::Serialize, serde::Deserialize)]+pub struct Attempt {+ /// Opaque handle bound to the owner by storage.+ pub id: String,+ /// Expected OAuth state.+ pub state: String,+ /// Consumed durably before token exchange.+ pub verifier: Option<Secret>,+ /// Unix timestamp used across replicas and restarts.+ pub started: u64,}-/// Local-demo policy: bounded, expiring, one-use attempts, bound to authenticated users.+fn now() -> Result<u64, Error> {+ SystemTime::now()+ .duration_since(UNIX_EPOCH)+ .map(|time| time.as_secs())+ .map_err(|_| Error::Credentials)+}++/// Expiring, one-use browser consent bound to authenticated users.pub struct AuthService<P, S> {provider: P,store: Option<S>,ephemeral: bool,- attempts: Arc<Mutex<HashMap<String, Attempt>>>,}impl<P, S> AuthService<P, S> {@@ -118,7 +130,6 @@ impl<P, S> AuthService<P, S> {provider,store,ephemeral,- attempts: Arc::default(),}}}@@ -140,13 +151,14 @@ impl<P: OAuthProvider, S: ConnectionStore> ClaudeAuth for AuthService<P, S> {}async fn begin(&self, owner: &str) -> Result<Login, AuthError> {- self.store.as_ref().ok_or(AuthError::Disabled)?;- let mut attempts = self.attempts.lock().await;- attempts.retain(|_, attempt| attempt.started.elapsed() < LOGIN_TTL);- if attempts- .get(owner)- .is_some_and(|a| a.started.elapsed() < Duration::from_secs(2))- || (!attempts.contains_key(owner) && attempts.len() >= MAX_ATTEMPTS)+ let store = self.store.as_ref().ok_or(AuthError::Disabled)?;+ let mut transaction = store.lock(owner).await?;+ let started = now()?;+ if transaction+ .state()+ .attempt+ .as_ref()+ .is_some_and(|attempt| started.saturating_sub(attempt.started) < 2){return Err(AuthError::Busy);}@@ -154,15 +166,13 @@ impl<P: OAuthProvider, S: ConnectionStore> ClaudeAuth for AuthService<P, S> {let verifier = Secret::parse(random_secret())?;let attempt_id = random_secret();let authorization_url = self.provider.authorization_url(&state, &verifier);- attempts.insert(- owner.to_owned(),- Attempt {- id: attempt_id.clone(),- state,- verifier: Some(verifier),- started: Instant::now(),- },- );+ transaction.state().attempt = Some(Attempt {+ id: attempt_id.clone(),+ state,+ verifier: Some(verifier),+ started,+ });+ transaction.commit().await?;Ok(Login {attempt_id,authorization_url,@@ -190,39 +200,57 @@ impl<P: OAuthProvider, S: ConnectionStore> ClaudeAuth for AuthService<P, S> {return Err(AuthError::InvalidCode);}let verifier = {- let mut attempts = self.attempts.lock().await;- let attempt = attempts.get_mut(owner).ok_or(AuthError::InvalidAttempt)?;- if attempt.id != attempt_id || attempt.started.elapsed() >= LOGIN_TTL {+ let mut transaction = store.lock(owner).await?;+ let attempt = transaction+ .state()+ .attempt+ .as_mut()+ .ok_or(AuthError::InvalidAttempt)?;+ if attempt.id != attempt_id+ || now()?.saturating_sub(attempt.started) >= LOGIN_TTL.as_secs()+ {return Err(AuthError::InvalidAttempt);}if !bool::from(attempt.state.as_bytes().ct_eq(state.as_bytes())) {return Err(AuthError::InvalidCode);}// Taking the verifier consumes the attempt before making any network request.- attempt.verifier.take().ok_or(AuthError::InvalidAttempt)?+ let verifier = attempt.verifier.take().ok_or(AuthError::InvalidAttempt)?;+ transaction.commit().await?;+ verifier};let result = self.provider.exchange(Secret::parse(code.to_owned())?, state, verifier).await;- let mut attempts = self.attempts.lock().await;- if !attempts- .get(owner)- .is_some_and(|a| a.id == attempt_id && a.started.elapsed() < LOGIN_TTL)- {+ let mut transaction = store.lock(owner).await?;+ if !transaction.state().attempt.as_ref().is_some_and(|attempt| {+ attempt.id == attempt_id+ && now()+ .is_ok_and(|time| time.saturating_sub(attempt.started) < LOGIN_TTL.as_secs())+ }) {return Err(AuthError::InvalidAttempt);}- attempts.remove(owner);- // Serialize save against disconnect/restart of consent; late completion cannot reconnect.- store.save(owner, result?).await?;+ transaction.state().attempt = None;+ match result {+ Ok(grant) => {+ transaction.state().grant = Some(grant);+ transaction.state().refresh_id = None;+ transaction.commit().await?;+ }+ Err(error) => {+ transaction.commit().await?;+ return Err(error.into());+ }+ }Ok(())}async fn disconnect(&self, owner: &str) -> Result<(), AuthError> {let store = self.store.as_ref().ok_or(AuthError::Disabled)?;- let mut attempts = self.attempts.lock().await;- attempts.remove(owner);- store.remove(owner).await?;+ let mut transaction = store.lock(owner).await?;+ *transaction.state() = ConnectionState::default();+ transaction.commit().await?;Ok(())}}diff --git a/crates/claude_cloud_agents/src/domain/auth/test.rs b/crates/claude_cloud_agents/src/domain/auth/test.rsindex b809e20828..1e245ac79b 100644--- a/crates/claude_cloud_agents/src/domain/auth/test.rs+++ b/crates/claude_cloud_agents/src/domain/auth/test.rs@@ -1,19 +1,23 @@use super::*;use std::sync::atomic::{AtomicUsize, Ordering};+use super::super::credentials::{GrantRepository, test_support::MemoryRepository};+use std::sync::Arc;+#[derive(Clone, Default)]-struct Store(Arc<Mutex<HashMap<String, Credentials>>>);+struct Store(Arc<MemoryRepository>);impl ConnectionStore for Store {+ async fn lock(&self, owner: &str) -> Result<Box<dyn GrantTransaction>, Error> {+ self.0.lock(owner).await+ }async fn connected(&self, owner: &str) -> bool {- self.0.lock().await.contains_key(owner)+ self.0.get(owner).await.unwrap().is_some()}async fn save(&self, owner: &str, c: Credentials) -> Result<(), Error> {- self.0.lock().await.insert(owner.into(), c);- Ok(())+ self.0.put(owner, &c).await}async fn remove(&self, owner: &str) -> Result<(), Error> {- self.0.lock().await.remove(owner);- Ok(())+ self.0.delete(owner).await}}#[derive(Default)]@@ -94,13 +98,9 @@ async fn expiry_replacement_and_rate_limit() {let service = AuthService::new(Provider::default(), Some(Store::default()), true);let old = service.begin("alice").await.unwrap();assert!(matches!(service.begin("alice").await, Err(AuthError::Busy)));- service- .attempts- .lock()- .await- .get_mut("alice")- .unwrap()- .started -= LOGIN_TTL;+ let mut transaction = service.store.as_ref().unwrap().lock("alice").await.unwrap();+ transaction.state().attempt.as_mut().unwrap().started -= LOGIN_TTL.as_secs();+ transaction.commit().await.unwrap();assert!(matches!(service.complete("alice", &old.attempt_id, code(&old)).await,Err(AuthError::InvalidAttempt)@@ -185,3 +185,26 @@ async fn disconnect_during_exchange_cannot_reconnect() {));assert!(!service.status("alice").await.connected);}++#[tokio::test]+async fn consent_survives_replica_changes_and_restart() {+ let store = Store::default();+ let first = AuthService::new(Provider::default(), Some(store.clone()), false);+ let login = first.begin("alice").await.unwrap();+ drop(first);+ let second = AuthService::new(Provider::default(), Some(store.clone()), false);+ second+ .complete("alice", &login.attempt_id, code(&login))+ .await+ .unwrap();+ let third = AuthService::new(Provider::default(), Some(store), false);+ assert!(third.status("alice").await.connected);+ assert!(matches!(+ third+ .complete("alice", &login.attempt_id, code(&login))+ .await,+ Err(AuthError::InvalidAttempt)+ ));+ third.disconnect("alice").await.unwrap();+ assert!(!second.status("alice").await.connected);+}diff --git a/crates/claude_cloud_agents/src/domain/credentials.rs b/crates/claude_cloud_agents/src/domain/credentials.rsindex 3ff08342cd..928a5a6b49 100644--- a/crates/claude_cloud_agents/src/domain/credentials.rs+++ b/crates/claude_cloud_agents/src/domain/credentials.rs@@ -12,16 +12,53 @@ use tokio::sync::Mutex;#[cfg(test)]mod test;+#[cfg(test)]+pub(crate) mod test_support;++/// Encrypted connection state shared across service replicas.+#[derive(Clone, Default, serde::Serialize, serde::Deserialize)]+pub struct ConnectionState {+ /// The owner's subscription grant, if connected.+ pub grant: Option<Credentials>,+ /// Pending, owner-bound browser consent.+ pub attempt: Option<super::auth::Attempt>,+ /// A consumed refresh must never be retried after an uncertain exchange.+ pub refresh_id: Option<String>,+}-/// Persistence stores only the requested owner's grant.+/// Owner-scoped transaction. Dropping it rolls back uncommitted state.+#[async_trait::async_trait]+pub trait GrantTransaction: Send {+ /// Read or update the locked state.+ fn state(&mut self) -> &mut ConnectionState;+ /// Persist the state and release the owner lock.+ async fn commit(self: Box<Self>) -> Result<()>;+}++/// Persistence serializes connection changes across replicas.#[async_trait::async_trait]pub trait GrantRepository: Send + Sync {- /// Load one grant.- async fn get(&self, owner: &str) -> Result<Option<Credentials>>;- /// Persist one grant, including refresh-token rotation.- async fn put(&self, owner: &str, grant: &Credentials) -> Result<()>;- /// Forget one grant.- async fn delete(&self, owner: &str) -> Result<()>;+ /// Lock exactly one owner's state, including owners with no existing row.+ async fn lock(&self, owner: &str) -> Result<Box<dyn GrantTransaction>>;+ /// Load one grant without returning pending consent secrets.+ async fn get(&self, owner: &str) -> Result<Option<Credentials>> {+ Ok(self.lock(owner).await?.state().grant.clone())+ }+ /// Persist a new connection and invalidate pending consent or refresh.+ async fn put(&self, owner: &str, grant: &Credentials) -> Result<()> {+ let mut transaction = self.lock(owner).await?;+ *transaction.state() = ConnectionState {+ grant: Some(grant.clone()),+ ..Default::default()+ };+ transaction.commit().await+ }+ /// Forget this owner's connection and any pending consent.+ async fn delete(&self, owner: &str) -> Result<()> {+ let mut transaction = self.lock(owner).await?;+ *transaction.state() = ConnectionState::default();+ transaction.commit().await+ }}/// Provider refresh capability; never retries a token exchange automatically.@@ -31,14 +68,14 @@ pub trait RefreshGrant: Send + Sync {async fn refresh(&self, grant: &Credentials) -> Result<Credentials>;}-/// Single-replica demo service. Serializes refresh, connect, and disconnect.+/// Owner-scoped credential lifecycle with durable refresh consumption.#[derive(Clone)]pub struct AccountCredentials {repository: Arc<dyn GrantRepository>,refresher: Arc<dyn RefreshGrant>,// Keep rotated grants after a persistence failure so we never reuse an old// refresh token. The next operation retries persistence before using them.- pending: Arc<Mutex<BTreeMap<String, Credentials>>>,+ pending: Arc<Mutex<BTreeMap<String, (String, Credentials)>>>,}impl AccountCredentials {@@ -59,14 +96,25 @@ impl AccountCredentials {/// Resolve and persist a refresh before a provider operation.pub async fn resolve(&self, owner: &str) -> Result<Credentials> {let mut pending = self.pending.lock().await;- if let Some(grant) = pending.get(owner) {- self.repository.put(owner, grant).await?;- pending.remove(owner);+ let mut transaction = self.repository.lock(owner).await?;+ if let Some((id, grant)) = pending.remove(owner)+ && transaction.state().refresh_id.as_ref() == Some(&id)+ {+ transaction.state().grant = Some(grant.clone());+ transaction.state().refresh_id = None;+ if let Err(error) = transaction.commit().await {+ pending.insert(owner.to_owned(), (id, grant));+ return Err(error);+ }+ transaction = self.repository.lock(owner).await?;}- let grant = self- .repository- .get(owner)- .await?+ if transaction.state().refresh_id.is_some() {+ return Err(Error::Authorization);+ }+ let grant = transaction+ .state()+ .grant+ .clone().ok_or(Error::NotConnected)?;let now = SystemTime::now().duration_since(UNIX_EPOCH)@@ -75,15 +123,30 @@ impl AccountCredentials {if grant.expires_at > now + 120 {return Ok(grant);}+ // Persist consumption before the external mutation. A crashed process+ // cannot cause another replica to reuse a rotating refresh token.+ let id = uuid::Uuid::now_v7().to_string();+ transaction.state().refresh_id = Some(id.clone());+ transaction.commit().await?;let refreshed = self.refresher.refresh(&grant).await?;- pending.insert(owner.to_owned(), refreshed.clone());- self.repository.put(owner, &refreshed).await?;- pending.remove(owner);+ let mut transaction = self.repository.lock(owner).await?;+ if transaction.state().refresh_id.as_ref() != Some(&id) {+ return Err(Error::NotConnected);+ }+ transaction.state().grant = Some(refreshed.clone());+ transaction.state().refresh_id = None;+ if let Err(error) = transaction.commit().await {+ pending.insert(owner.to_owned(), (id, refreshed));+ return Err(error);+ }Ok(refreshed)}}impl ConnectionStore for AccountCredentials {+ async fn lock(&self, owner: &str) -> Result<Box<dyn GrantTransaction>> {+ self.repository.lock(owner).await+ }async fn connected(&self, owner: &str) -> bool {self.contains(owner).await}diff --git a/crates/claude_cloud_agents/src/domain/credentials/test.rs b/crates/claude_cloud_agents/src/domain/credentials/test.rsindex e000af1baf..0e4de77a15 100644--- a/crates/claude_cloud_agents/src/domain/credentials/test.rs+++ b/crates/claude_cloud_agents/src/domain/credentials/test.rs@@ -1,29 +1,8 @@+use super::test_support::MemoryRepository as Repo;use super::*;use crate::domain::model::Secret;-use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};+use std::sync::atomic::{AtomicUsize, Ordering};-#[derive(Default)]-struct Repo {- data: Mutex<BTreeMap<String, Credentials>>,- fail: AtomicBool,-}-#[async_trait::async_trait]-impl GrantRepository for Repo {- async fn get(&self, owner: &str) -> Result<Option<Credentials>> {- Ok(self.data.lock().await.get(owner).cloned())- }- async fn put(&self, owner: &str, grant: &Credentials) -> Result<()> {- if self.fail.load(Ordering::SeqCst) {- return Err(Error::Credentials);- }- self.data.lock().await.insert(owner.into(), grant.clone());- Ok(())- }- async fn delete(&self, owner: &str) -> Result<()> {- self.data.lock().await.remove(owner);- Ok(())- }-}#[derive(Default)]struct Refresh(AtomicUsize);#[async_trait::async_trait]@@ -58,11 +37,12 @@ async fn refresh_rotation_retries_persistence_without_reusing_old_token_and_discservice.resolve("bob").await,Err(Error::NotConnected)));- repo.fail.store(true, Ordering::SeqCst);+ repo.fail_commit.store(2, Ordering::SeqCst);assert!(service.resolve("alice").await.is_err());+ repo.fail_commit.store(1, Ordering::SeqCst);assert!(service.resolve("alice").await.is_err());assert_eq!(refresh.0.load(Ordering::SeqCst), 1);- repo.fail.store(false, Ordering::SeqCst);+ repo.fail_commit.store(0, Ordering::SeqCst);assert_eq!(service.resolve("alice")@@ -80,3 +60,38 @@ async fn refresh_rotation_retries_persistence_without_reusing_old_token_and_disc));assert_eq!(refresh.0.load(Ordering::SeqCst), 1);}++#[tokio::test]+async fn another_replica_cannot_reuse_refresh_or_resurrect_a_disconnected_grant() {+ let repo = Arc::new(Repo::default());+ let refresh = Arc::new(Refresh::default());+ let first = AccountCredentials::new(repo.clone(), refresh.clone());+ let second = AccountCredentials::new(repo.clone(), refresh.clone());+ first+ .save(+ "alice",+ Credentials {+ access_token: Secret::parse("access".into()).unwrap(),+ refresh_token: Some(Secret::parse("old".into()).unwrap()),+ expires_at: 0,+ organization_id: "org".into(),+ environment_id: "env_test".into(),+ },+ )+ .await+ .unwrap();+ repo.fail_commit.store(2, Ordering::SeqCst);+ assert!(first.resolve("alice").await.is_err());+ assert!(matches!(+ second.resolve("alice").await,+ Err(Error::Authorization)+ ));+ assert_eq!(refresh.0.load(Ordering::SeqCst), 1);+ second.remove("alice").await.unwrap();+ assert!(matches!(+ first.resolve("alice").await,+ Err(Error::NotConnected)+ ));+ assert!(!second.contains("alice").await);+ assert_eq!(refresh.0.load(Ordering::SeqCst), 1);+}diff --git a/crates/claude_cloud_agents/src/domain/credentials/test_support.rs b/crates/claude_cloud_agents/src/domain/credentials/test_support.rsnew file mode 100644index 0000000000..ae142e2ac4--- /dev/null+++ b/crates/claude_cloud_agents/src/domain/credentials/test_support.rs@@ -0,0 +1,47 @@+use super::*;+use std::sync::atomic::{AtomicUsize, Ordering};++#[derive(Default)]+pub(crate) struct MemoryRepository {+ pub data: Arc<Mutex<BTreeMap<String, ConnectionState>>>,+ /// A positive value fails that numbered future commit once.+ pub fail_commit: Arc<AtomicUsize>,+}+struct Transaction {+ data: tokio::sync::OwnedMutexGuard<BTreeMap<String, ConnectionState>>,+ owner: String,+ state: ConnectionState,+ fail: Arc<AtomicUsize>,+}+#[async_trait::async_trait]+impl GrantRepository for MemoryRepository {+ async fn lock(&self, owner: &str) -> Result<Box<dyn GrantTransaction>> {+ let data = self.data.clone().lock_owned().await;+ let state = data.get(owner).cloned().unwrap_or_default();+ Ok(Box::new(Transaction {+ data,+ owner: owner.to_owned(),+ state,+ fail: self.fail_commit.clone(),+ }))+ }+}+#[async_trait::async_trait]+impl GrantTransaction for Transaction {+ fn state(&mut self) -> &mut ConnectionState {+ &mut self.state+ }+ async fn commit(mut self: Box<Self>) -> Result<()> {+ if self+ .fail+ .fetch_update(Ordering::SeqCst, Ordering::SeqCst, |n| n.checked_sub(1))+ == Ok(1)+ {+ return Err(Error::Credentials);+ }+ let owner = self.owner.clone();+ let state = self.state.clone();+ self.data.insert(owner, state);+ Ok(())+ }+}diff --git a/crates/claude_cloud_agents/src/outbound/credentials.rs b/crates/claude_cloud_agents/src/outbound/credentials.rsindex 394ed615a8..eed530e47f 100644--- a/crates/claude_cloud_agents/src/outbound/credentials.rs+++ b/crates/claude_cloud_agents/src/outbound/credentials.rs@@ -1,7 +1,7 @@//! Legacy private-file and memory adapters for standalone smoke tests.pub use crate::domain::credentials::AccountCredentials;use crate::domain::{- credentials::{GrantRepository, RefreshGrant},+ credentials::{ConnectionState, GrantRepository, GrantTransaction, RefreshGrant},model::{Credentials, Error, Result, Secret},};use serde::{Deserialize, Serialize};@@ -22,10 +22,12 @@ pub type FileCredentials = AccountCredentials;#[derive(Default, Serialize, Deserialize)]struct FileData {users: BTreeMap<String, Credentials>,+ #[serde(default)]+ connections: BTreeMap<String, ConnectionState>,}struct FileRepository {path: Option<PathBuf>,- data: Mutex<FileData>,+ data: Arc<Mutex<FileData>>,}impl AccountCredentials {@@ -34,7 +36,7 @@ impl AccountCredentials {Ok(Self::new(Arc::new(FileRepository {path: None,- data: Mutex::default(),+ data: Arc::default(),}),Arc::new(ClaudeRefresh::new()?),))@@ -52,10 +54,16 @@ impl AccountCredentials {return Err(Error::Credentials);}let data: FileData = serde_json::from_slice(&bytes).map_err(|_| Error::Credentials)?;- for (owner, grant) in &data.users {+ for owner in data.users.keys().chain(data.connections.keys()) {if owner.trim() != owner || !owner.starts_with("macro|") || owner.contains('\0') {return Err(Error::Credentials);}+ }+ for grant in data.users.values().chain(+ data.connections+ .values()+ .filter_map(|state| state.grant.as_ref()),+ ) {uuid::Uuid::parse_str(&grant.organization_id).map_err(|_| Error::Credentials)?;if !grant.environment_id.starts_with("env_")|| !grant@@ -69,7 +77,7 @@ impl AccountCredentials {Ok(Self::new(Arc::new(FileRepository {path: Some(path),- data: Mutex::new(data),+ data: Arc::new(Mutex::new(data)),}),Arc::new(ClaudeRefresh::new()?),))@@ -77,8 +85,8 @@ impl AccountCredentials {}impl FileRepository {- async fn persist(&self, data: &FileData) -> Result<()> {- let Some(path) = &self.path else {+ async fn persist(path: &Option<PathBuf>, data: &FileData) -> Result<()> {+ let Some(path) = path else {return Ok(());};let bytes =@@ -98,33 +106,57 @@ impl FileRepository {.map_err(|_| Error::Credentials)}}+struct FileTransaction {+ data: tokio::sync::OwnedMutexGuard<FileData>,+ path: Option<PathBuf>,+ owner: String,+ state: ConnectionState,+}#[async_trait::async_trait]impl GrantRepository for FileRepository {- async fn get(&self, owner: &str) -> Result<Option<Credentials>> {- Ok(self.data.lock().await.users.get(owner).cloned())+ async fn lock(&self, owner: &str) -> Result<Box<dyn GrantTransaction>> {+ let data = self.data.clone().lock_owned().await;+ let state = data+ .connections+ .get(owner)+ .cloned()+ .unwrap_or_else(|| ConnectionState {+ grant: data.users.get(owner).cloned(),+ ..Default::default()+ });+ Ok(Box::new(FileTransaction {+ data,+ path: self.path.clone(),+ owner: owner.to_owned(),+ state,+ }))+ }+}+#[async_trait::async_trait]+impl GrantTransaction for FileTransaction {+ fn state(&mut self) -> &mut ConnectionState {+ &mut self.state}- async fn put(&self, owner: &str, grant: &Credentials) -> Result<()> {- let mut data = self.data.lock().await;- let previous = data.users.insert(owner.to_owned(), grant.clone());- if let Err(error) = self.persist(&data).await {+ async fn commit(self: Box<Self>) -> Result<()> {+ let Self {+ mut data,+ path,+ owner,+ state,+ } = *self;+ let previous = data.connections.insert(owner.clone(), state);+ let legacy = data.users.remove(&owner);+ if let Err(error) = FileRepository::persist(&path, &data).await {match previous {Some(value) => {- data.users.insert(owner.to_owned(), value);+ data.connections.insert(owner.clone(), value);}None => {- data.users.remove(owner);+ data.connections.remove(&owner);}}- return Err(error);- }- Ok(())- }- async fn delete(&self, owner: &str) -> Result<()> {- let mut data = self.data.lock().await;- let previous = data.users.remove(owner);- if let Err(error) = self.persist(&data).await {- if let Some(value) = previous {- data.users.insert(owner.to_owned(), value);+ if let Some(value) = legacy {+ data.users.insert(owner, value);}return Err(error);}diff --git a/crates/claude_cloud_agents/src/outbound/postgres.rs b/crates/claude_cloud_agents/src/outbound/postgres.rsindex ce91779adb..3ad9d66d83 100644--- a/crates/claude_cloud_agents/src/outbound/postgres.rs+++ b/crates/claude_cloud_agents/src/outbound/postgres.rs@@ -1,10 +1,10 @@-//! Encrypted owner-keyed Claude grants. No plaintext tokens are stored in SQL.+//! Encrypted owner-keyed connections with cross-replica transaction locks.use crate::domain::{- credentials::GrantRepository,- model::{Credentials, Error, Result},+ credentials::{ConnectionState, GrantRepository, GrantTransaction},+ model::{Error, Result},};use cursor_api_key::cipher::KmsCiphertexts;-use std::collections::HashMap;+use std::{collections::HashMap, sync::Arc};#[cfg(test)]mod test;@@ -12,62 +12,113 @@ mod test;/// PostgreSQL persistence with purpose- and owner-bound KMS ciphertext.pub struct PgClaudeGrants<K> {pool: sqlx::PgPool,- cipher: K,+ cipher: Arc<K>,}impl<K> PgClaudeGrants<K> {- /// Supply the existing local KMS transport at the composition root.+ /// Supply the deployment's KMS transport at the composition root.pub fn new(pool: sqlx::PgPool, cipher: K) -> Self {- Self { pool, cipher }+ Self {+ pool,+ cipher: Arc::new(cipher),+ }}}-fn context(owner: &str) -> HashMap<String, String> {+fn context(owner: &str, version: i16) -> HashMap<String, String> {HashMap::from([("purpose".into(), "claude-cloud-oauth".into()),("user_id".into(), owner.into()),- ("encryption_version".into(), "1".into()),+ ("encryption_version".into(), version.to_string()),])}+struct OwnerTransaction<K> {+ transaction: sqlx::Transaction<'static, sqlx::Postgres>,+ owner: String,+ state: ConnectionState,+ cipher: Arc<K>,+}#[async_trait::async_trait]-impl<K: KmsCiphertexts> GrantRepository for PgClaudeGrants<K> {- async fn get(&self, owner: &str) -> Result<Option<Credentials>> {+impl<K: KmsCiphertexts + 'static> GrantRepository for PgClaudeGrants<K> {+ async fn lock(&self, owner: &str) -> Result<Box<dyn GrantTransaction>> {+ let mut transaction = self.pool.begin().await.map_err(|_| Error::Credentials)?;+ // Transaction-scoped advisory locks also serialize absent/deleted rows.+ // The namespace prevents collisions with other services' owner locks.+ let lock_name = format!("claude-cloud-oauth:{owner}");+ sqlx::query!(+ "SELECT pg_advisory_xact_lock(hashtextextended($1, 0))",+ lock_name+ )+ .execute(&mut *transaction)+ .await+ .map_err(|_| Error::Credentials)?;let row = sqlx::query!("SELECT grant_ciphertext, kms_key_id, encryption_version FROM claude_oauth_grants WHERE user_id = $1", owner)- .fetch_optional(&self.pool).await.map_err(|_| Error::Credentials)?;- let Some(row) = row else {- return Ok(None);+ .fetch_optional(&mut *transaction).await.map_err(|_| Error::Credentials)?;+ let state = match row {+ None => ConnectionState::default(),+ Some(row) => {+ if !matches!(row.encryption_version, 1 | 2) {+ return Err(Error::Credentials);+ }+ let bytes = self+ .cipher+ .decrypt(+ &row.kms_key_id,+ &row.grant_ciphertext,+ context(owner, row.encryption_version),+ )+ .await+ .map_err(|_| Error::Credentials)?;+ if row.encryption_version == 1 {+ // Existing encrypted grants upgrade when next written.+ ConnectionState {+ grant: Some(+ serde_json::from_slice(&bytes).map_err(|_| Error::Credentials)?,+ ),+ ..Default::default()+ }+ } else {+ serde_json::from_slice(&bytes).map_err(|_| Error::Credentials)?+ }+ }};- if row.encryption_version != 1 {- return Err(Error::Credentials);- }- let bytes = self- .cipher- .decrypt(&row.kms_key_id, &row.grant_ciphertext, context(owner))- .await- .map_err(|_| Error::Credentials)?;- serde_json::from_slice(&bytes)- .map(Some)- .map_err(|_| Error::Credentials)+ Ok(Box::new(OwnerTransaction {+ transaction,+ owner: owner.to_owned(),+ state,+ cipher: self.cipher.clone(),+ }))}- async fn put(&self, owner: &str, grant: &Credentials) -> Result<()> {- let bytes =- zeroize::Zeroizing::new(serde_json::to_vec(grant).map_err(|_| Error::Credentials)?);- // Direct KMS encryption has a 4 KiB plaintext limit. Fail closed.- if bytes.len() > 4096 {- return Err(Error::Credentials);- }- let (ciphertext, key_id) = self- .cipher- .encrypt(context(owner), &bytes)- .await- .map_err(|_| Error::Credentials)?;- sqlx::query!("INSERT INTO claude_oauth_grants (user_id, grant_ciphertext, kms_key_id, encryption_version) VALUES ($1, $2, $3, 1) ON CONFLICT (user_id) DO UPDATE SET grant_ciphertext = EXCLUDED.grant_ciphertext, kms_key_id = EXCLUDED.kms_key_id, encryption_version = 1, updated_at = now()", owner, ciphertext, key_id)- .execute(&self.pool).await.map_err(|_| Error::Credentials)?;- Ok(())+}+#[async_trait::async_trait]+impl<K: KmsCiphertexts + 'static> GrantTransaction for OwnerTransaction<K> {+ fn state(&mut self) -> &mut ConnectionState {+ &mut self.state}- async fn delete(&self, owner: &str) -> Result<()> {- sqlx::query!("DELETE FROM claude_oauth_grants WHERE user_id = $1", owner)- .execute(&self.pool)- .await- .map_err(|_| Error::Credentials)?;- Ok(())+ async fn commit(self: Box<Self>) -> Result<()> {+ let Self {+ mut transaction,+ owner,+ state,+ cipher,+ } = *self;+ if state.grant.is_none() && state.attempt.is_none() {+ sqlx::query!("DELETE FROM claude_oauth_grants WHERE user_id = $1", owner)+ .execute(&mut *transaction)+ .await+ .map_err(|_| Error::Credentials)?;+ } else {+ let bytes = zeroize::Zeroizing::new(+ serde_json::to_vec(&state).map_err(|_| Error::Credentials)?,+ );+ if bytes.len() > 4096 {+ return Err(Error::Credentials);+ }+ let (ciphertext, key_id) = cipher+ .encrypt(context(&owner, 2), &bytes)+ .await+ .map_err(|_| Error::Credentials)?;+ sqlx::query!("INSERT INTO claude_oauth_grants (user_id, grant_ciphertext, kms_key_id, encryption_version) VALUES ($1, $2, $3, 2) ON CONFLICT (user_id) DO UPDATE SET grant_ciphertext = EXCLUDED.grant_ciphertext, kms_key_id = EXCLUDED.kms_key_id, encryption_version = 2, updated_at = now()", owner, ciphertext, key_id)+ .execute(&mut *transaction).await.map_err(|_| Error::Credentials)?;+ }+ transaction.commit().await.map_err(|_| Error::Credentials)}}diff --git a/crates/claude_cloud_agents/src/outbound/postgres/test.rs b/crates/claude_cloud_agents/src/outbound/postgres/test.rsindex c94b8d76a7..5f7265a768 100644--- a/crates/claude_cloud_agents/src/outbound/postgres/test.rs+++ b/crates/claude_cloud_agents/src/outbound/postgres/test.rs@@ -1,5 +1,5 @@use super::*;-use crate::domain::model::Secret;+use crate::domain::model::{Credentials, Secret};use cursor_api_key::cipher::KmsCiphertextsError;use macro_db_migrator::MACRO_DB_MIGRATIONS;use std::sync::{Arc, Mutex};@@ -95,8 +95,117 @@ async fn durable_encrypted_grants_are_owner_bound_replaceable_and_removable(pool);sqlx::query!("INSERT INTO claude_oauth_grants (user_id, grant_ciphertext, kms_key_id, encryption_version) SELECT 'bob', grant_ciphertext, kms_key_id, encryption_version FROM claude_oauth_grants WHERE user_id = 'alice'").execute(&pool).await.unwrap();assert!(matches!(store.get("bob").await, Err(Error::Credentials)));- restarted.delete("bob").await.unwrap();+ sqlx::query!("DELETE FROM claude_oauth_grants WHERE user_id = $1", "bob")+ .execute(&pool)+ .await+ .unwrap();assert!(store.get("alice").await.unwrap().is_some());restarted.delete("alice").await.unwrap();assert!(store.get("alice").await.unwrap().is_none());}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn pending_consent_is_encrypted_durable_and_locked_across_replicas(pool: sqlx::PgPool) {+ user(&pool, "alice").await;+ let kms = FakeKms::default();+ let first = Arc::new(PgClaudeGrants::new(pool.clone(), kms.clone()));+ let second = Arc::new(PgClaudeGrants::new(pool.clone(), kms));+ let mut transaction = first.lock("alice").await.unwrap();+ transaction.state().attempt = Some(crate::domain::auth::Attempt {+ id: "attempt".into(),+ state: "state".into(),+ verifier: Some(Secret::parse("private-verifier".into()).unwrap()),+ started: 1,+ });+ let waiting = {+ let second = second.clone();+ tokio::spawn(async move { second.lock("alice").await.unwrap() })+ };+ tokio::task::yield_now().await;+ assert!(!waiting.is_finished());+ transaction.commit().await.unwrap();+ let mut resumed = waiting.await.unwrap();+ assert_eq!(+ resumed+ .state()+ .attempt+ .as_ref()+ .unwrap()+ .verifier+ .as_ref()+ .unwrap()+ .expose(),+ "private-verifier"+ );+ resumed.state().attempt.as_mut().unwrap().verifier = None;+ resumed.commit().await.unwrap();+ drop(first);+ let mut restarted = second.lock("alice").await.unwrap();+ assert!(+ restarted+ .state()+ .attempt+ .as_ref()+ .unwrap()+ .verifier+ .is_none()+ );+ // An uncommitted replacement must not resurrect the consumed verifier.+ restarted.state().attempt = None;+ drop(restarted);+ assert!(+ second+ .lock("alice")+ .await+ .unwrap()+ .state()+ .attempt+ .is_some()+ );+ let ciphertext = sqlx::query_scalar!(+ "SELECT grant_ciphertext FROM claude_oauth_grants WHERE user_id = 'alice'"+ )+ .fetch_one(&pool)+ .await+ .unwrap();+ assert!(+ !ciphertext+ .windows(16)+ .any(|bytes| bytes == b"private-verifier")+ );+ second.delete("alice").await.unwrap();+ assert!(+ second+ .lock("alice")+ .await+ .unwrap()+ .state()+ .attempt+ .is_none()+ );+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn reads_legacy_grants_and_upgrades_on_write(pool: sqlx::PgPool) {+ user(&pool, "alice").await;+ let kms = FakeKms::default();+ let (ciphertext, key) = kms+ .encrypt(context("alice", 1), &serde_json::to_vec(&grant()).unwrap())+ .await+ .unwrap();+ sqlx::query!("INSERT INTO claude_oauth_grants (user_id, grant_ciphertext, kms_key_id, encryption_version) VALUES ($1, $2, $3, 1) ON CONFLICT (user_id) DO UPDATE SET grant_ciphertext = EXCLUDED.grant_ciphertext, kms_key_id = EXCLUDED.kms_key_id, encryption_version = 1, updated_at = now()", "alice", ciphertext, key).execute(&pool).await.unwrap();+ let repository = PgClaudeGrants::new(pool, kms);+ let mut transaction = repository.lock("alice").await.unwrap();+ assert_eq!(+ transaction+ .state()+ .grant+ .as_ref()+ .unwrap()+ .access_token+ .expose(),+ "test-access"+ );+ transaction.commit().await.unwrap();+ assert!(repository.get("alice").await.unwrap().is_some());+}diff --git a/docs/AGENT_GUIDE/navigation.md b/docs/AGENT_GUIDE/navigation.mdindex f0257a3233..e9d64743b9 100644--- a/docs/AGENT_GUIDE/navigation.md+++ b/docs/AGENT_GUIDE/navigation.md@@ -261,6 +261,11 @@ Settings → Harness, above Cursor, with theAnthropic logo. Settings → Agents selects an agent's harness but does not hostClaude's connection form. **Connect Claude** starts authorization and opens sign-inon the first click; a fallback link remains if the browser blocks the tab.+Approve on Claude's page, copy the complete `code#state`, then use **Finish+connecting**. Hosted and local deployments use the same flow. Grants and pending+sign-in attempts are encrypted in MacroDB and survive restarts or replica changes.+If the card says sign-in is not configured, the deployment is missing its Claude+OAuth KMS key; changing the frontend flag cannot fix that backend configuration.Claude's model picker uses provider-reported IDs,names, descriptions, and order. Settings discovers from recent account sessions;session catalogs update through replay, polling, and streaming. Before any catalogdiff --git a/docs/CLAUDE_CLOUD_DEMO.md b/docs/CLAUDE_CLOUD_DEMO.mdindex ed00202ded..020ad05fc9 100644--- a/docs/CLAUDE_CLOUD_DEMO.md+++ b/docs/CLAUDE_CLOUD_DEMO.md@@ -2,7 +2,7 @@`claude-cloud` runs Claude Code on Anthropic's cloud using **the session owner's subscription OAuth grant**. It does not use macrod, a local Claude process, or Macro's Anthropic API key. This uses an unofficial first-party protocol verified experimentally on September 15, 2026, not a supported third-party OAuth registration.-## Connect in the local UI (recommended)+## Connect in the browserThe frontend entry points require the PostHog flag **`claude-cloud`**. It isoff by default everywhere (including dev); for a local demo, set@@ -11,9 +11,9 @@ the connection card never mounts and agent settings neither offer Claude Cloudnor request its model catalog. This is a UI rollout flag, not a backendauthorization boundary or a kill switch for existing agents/sessions.-Rebuild the local backend from this workspace (`r` in the running `just run_local`-terminal) and refresh the browser. In **Settings → Harness**, the-**Claude Cloud (demo)** row has the Anthropic logo and appears above Cursor,+Deploy the backend and infrastructure from this workspace, or rebuild the local+backend (`r` in `just run_local`), then refresh the browser. In **Settings → Harness**, the+**Claude Cloud** row has the Anthropic logo and appears above Cursor,even before an account is connected. Connection setup is not in Settings → Agents:1. Click **Connect Claude** to open Claude sign-in in a new tab automatically.@@ -21,7 +21,7 @@ even before an account is connected. Connection setup is not in Settings → Age2. Sign in and approve on Claude's own page. Macro never asks for your password.3. Copy the entire one-time `code#state` displayed by Claude, paste it into Macro,and click **Finish connecting**.-4. Create/edit an agent and select **Claude Cloud (demo)** as its harness.+4. Create/edit an agent and select **Claude Cloud** as its harness.This is Claude Code's manual authorization-code + PKCE flow, not an RFC 8628device-code grant. The registered callback stays on Claude's site, so this works@@ -30,15 +30,19 @@ The Macro user comes from authenticated request identity, never an email field.Attempts expire after ten minutes, are one-use, and are canceled on disconnect.Starting again invalidates the prior attempt. A failed exchange requires starting again.-**No credential file, container mount, or credential environment variable is needed locally.**-With `ENVIRONMENT=local`, grants are stored in MacroDB's `claude_oauth_grants`-table. The serialized grant is KMS-encrypted, bound to its exact Macro owner and-the `claude-cloud-oauth` purpose. The local stack's existing Cursor KMS key is-reused with this separate encryption context; neither Cursor's configuration rows-nor macrod token hashes are reused. Grant updates include refresh-token rotation.-Reconnect once after upgrading from the old in-memory backend; subsequent-restarts/rebuilds retain the connection. Run one replica: refresh/connect/disconnect-are serialized in the domain service, not protected by a distributed lock.+**No credential file or mount is needed.** Every configured deployment stores+grants and pending PKCE attempts in MacroDB's `claude_oauth_grants` table. KMS+encryption binds state to its exact Macro owner and the `claude-cloud-oauth`+purpose. Hosted deployments use a dedicated key; the local stack uses its existing+Cursor KMS key with this separate context. PostgreSQL owner locks serialize+sign-in, disconnect, and credential changes across replicas. Starting on one+replica and finishing on another works, including after a restart. Existing+version-1 encrypted grants are read and upgraded on their next write.++A refresh is durably marked consumed before contacting Claude. A failed or+interrupted exchange requires reconnecting instead of reusing a possibly rotated+refresh token. A persistence retry in the same process may recover the refreshed+grant, but cannot overwrite a newer connection or undo a disconnect.Access/refresh tokens never reach frontend responses, query caches,local storage, or logs. The one-time code is briefly in the masked input and POST body,and is cleared on submission/cancel/expiry. Consent URLs are no-store responses.@@ -46,7 +50,7 @@ Local Macro login may be a different email from the Claude account you authorize**Disconnect Claude** forgets Macro's grant and pending attempt. It does not revokeconsent at Anthropic or stop a cloud turn already running; stop the turn first if-needed. Interactive onboarding is disabled outside `ENVIRONMENT=local`.+needed.## Legacy command-line provisioning (optional)@@ -64,21 +68,25 @@ The output defaults to `.claude-cloud/credentials.json` (gitignored). The parent## Enable the service-Local service startup always uses encrypted DB storage, ignoring the legacy file-path. Apply the MacroDB migration before rebuilding the service. Outside local,-`CLAUDE_CLOUD_CREDENTIALS_PATH` still enables the older private-file experiment;-empty leaves Claude disabled. Only that legacy mode needs a private directory-mount. Refresh atomically replaces the file, so mount the directory read/write,-not just the file. Run **one service replica**.+The service uses `CLAUDE_OAUTH_KMS_KEY_ID` from MacroConfig/Doppler or the ECS+container environment. `infra/stacks/agent-harness-service` provisions the dedicated+key and injects its ARN, with Encrypt/Decrypt permission restricted to the Claude+purpose and an owner encryption context. Deploy this infrastructure together with+the service. Without a configured key, connection status reports disabled with an+explicit setup message. There is no hosted/local auth behavior gate.-Production startup refuses a nonempty path. Before a hosted dev deployment, register the optional config key in the service's Doppler configuration and provision a private persistent volume; this change does not deploy or modify shared credentials. Local overrides use the normal MacroConfig environment loading.+LocalStack keeps the existing `alias/macro-local-cursor-api-key` default. The old+`CLAUDE_CLOUD_CREDENTIALS_PATH` service setting is removed; private files remain+supported only by standalone command-line probes.-The standalone frontend against the existing dev backend cannot exercise this new provider. Use a backend built from this workspace; see [running locally](RUNNING_LOCALLY.md).+Browser consent is authorization-code + PKCE with manual code entry. It does not+implement device-code polling. End-to-end provider verification requires approving+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 (demo)**. It is offered only when model discovery confirms that your Macro identity has a configured connection.+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.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.diff --git a/infra/stacks/agent-harness-service/agent_harness_service.ts b/infra/stacks/agent-harness-service/agent_harness_service.tsindex 84245853f8..086781b917 100644--- a/infra/stacks/agent-harness-service/agent_harness_service.ts+++ b/infra/stacks/agent-harness-service/agent_harness_service.ts@@ -197,6 +197,49 @@ export class AgentHarnessService extends pulumi.ComponentResource {{ parent: this });+ const claudeOauthKey = new aws.kms.Key(+ `${BASE_NAME}-claude-oauth-key`,+ {+ description:+ 'Encrypt per-user Claude OAuth grants and browser sign-in state',+ enableKeyRotation: true,+ deletionWindowInDays: 30,+ tags,+ },+ { parent: this }+ );+ new aws.kms.Alias(+ `${BASE_NAME}-claude-oauth-alias`,+ {+ name: `alias/agent-harness-service-claude-oauth-${stack}`,+ targetKeyId: claudeOauthKey.keyId,+ },+ { parent: this }+ );+ const claudeOauthPolicy = new aws.iam.RolePolicy(+ `${BASE_NAME}-claude-oauth-policy`,+ {+ role: this.role.name,+ policy: pulumi.jsonStringify({+ Version: '2012-10-17',+ Statement: [+ {+ Effect: 'Allow',+ Action: ['kms:Encrypt', 'kms:Decrypt'],+ Resource: claudeOauthKey.arn,+ Condition: {+ StringEquals: {+ 'kms:EncryptionContext:purpose': 'claude-cloud-oauth',+ },+ Null: { 'kms:EncryptionContext:user_id': 'false' },+ },+ },+ ],+ }),+ },+ { parent: this }+ );+// Producer/consumer access to the macro event Kafka cluster: the harness// consumes `macro.channels` and `macro.agent_sessions`, publishes agent// triggers, and publishes channel side effects.@@ -335,6 +378,7 @@ export class AgentHarnessService extends pulumi.ComponentResource {memory: 2048,environment: [...containerEnvVars,+ { name: 'CLAUDE_OAUTH_KMS_KEY_ID', value: claudeOauthKey.arn },{name: 'BASE_URL',value: this.domain,@@ -385,7 +429,11 @@ export class AgentHarnessService extends pulumi.ComponentResource {// ECS refuses a service whose target group is not yet associated// with a load balancer; it is the listener rule that creates that// association.- dependsOn: [gatewayTargetGroup.listener_rule, egress.listener_rule],+ dependsOn: [+ gatewayTargetGroup.listener_rule,+ egress.listener_rule,+ claudeOauthPolicy,+ ],});diff --git a/services/agent_harness_service/src/config.rs b/services/agent_harness_service/src/config.rsindex 4603ed5307..9102dffd5c 100644--- a/services/agent_harness_service/src/config.rs+++ b/services/agent_harness_service/src/config.rs@@ -36,6 +36,8 @@ macro_env_var::env_vars!();macro_env_var::maybe_env_vars!(+ /// KMS key for encrypted per-owner Claude OAuth connections.+ pub struct ClaudeOauthKmsKeyId;/// Dedicated KMS key for encrypted per-owner Codex OAuth state.pub struct CodexOauthKmsKeyId;);@@ -53,12 +55,8 @@ fn default_pipedream_environment() -> String {#[derive(macro_config::MacroConfig)]#[serde(rename_all = "SCREAMING_SNAKE_CASE")]pub struct Config {- /// Private owner-keyed OAuth file for the single-replica Claude demo.- /// Local browser connections always use encrypted MacroDB storage.- /// Empty disables Claude outside the local environment.- /// Nonempty is refused in production.- #[macro_config_default(String::new())]- pub claude_cloud_credentials_path: String,+ /// OAuth encryption key; deployments without a key do not advertise sign-in.+ pub claude_oauth_kms_key_id: ClaudeOauthKmsKeyId,/// The environment we are in.#[macro_config_default(Environment::new_or_prod())]pub environment: Environment,@@ -177,6 +175,26 @@ pub struct Config {}impl Config {+ /// Resolve the deployment-injected encryption key. Local stacks use their+ /// existing LocalStack key with a separate Claude encryption context.+ pub fn claude_oauth_kms_key_id(&self) -> Option<String> {+ self.claude_oauth_kms_key_id+ .value()+ .filter(|key| !key.trim().is_empty())+ .map(str::to_owned)+ .or_else(|| {+ ClaudeOauthKmsKeyId::new().and_then(|key| {+ key.value()+ .filter(|key| !key.trim().is_empty())+ .map(str::to_owned)+ })+ })+ .or_else(|| {+ matches!(self.environment, Environment::Local)+ .then(|| "alias/macro-local-cursor-api-key".to_owned())+ })+ }+/// Resolve the optional key from Doppler or the deployment-injected environment.pub fn codex_oauth_kms_key_id(&self) -> Option<String> {self.codex_oauth_kms_key_iddiff --git a/services/agent_harness_service/src/main.rs b/services/agent_harness_service/src/main.rsindex 0925f73bf7..ff5fa99a1b 100644--- a/services/agent_harness_service/src/main.rs+++ b/services/agent_harness_service/src/main.rs@@ -204,37 +204,21 @@ async fn run() -> anyhow::Result<()> {.await.context("failed to connect to macrodb")?;- // Local-only demo: reuse the local Cursor KMS key, but cryptographically- // separate Claude grants by purpose and owner. Never enables hosted writes.- let claude_credentials = if matches!(config.environment, Environment::Local) {- Some(- claude_cloud_agents::domain::credentials::AccountCredentials::new(- Arc::new(- claude_cloud_agents::outbound::postgres::PgClaudeGrants::new(- pool.clone(),- AwsKmsCiphertexts::new(- aws_sdk_kms::Client::new(&aws_config),- "alias/macro-local-cursor-api-key".into(),- ),- ),+ // The same encrypted connection store serves browser consent and runtime+ // credentials in every deployment. Only the KMS key configuration varies.+ let claude_refresh =+ Arc::new(claude_cloud_agents::outbound::credentials::ClaudeRefresh::new()?);+ let claude_credentials = config.claude_oauth_kms_key_id().map(|key| {+ claude_cloud_agents::domain::credentials::AccountCredentials::new(+ Arc::new(+ claude_cloud_agents::outbound::postgres::PgClaudeGrants::new(+ pool.clone(),+ AwsKmsCiphertexts::new(aws_sdk_kms::Client::new(&aws_config), key),),- Arc::new(claude_cloud_agents::outbound::credentials::ClaudeRefresh::new()?),),+ claude_refresh.clone(),)- } else if !config.claude_cloud_credentials_path.is_empty() {- anyhow::ensure!(- !matches!(config.environment, Environment::Production),- "Claude Cloud demo credentials are forbidden in production"- );- Some(- claude_cloud_agents::outbound::credentials::FileCredentials::open(- std::path::PathBuf::from(&config.claude_cloud_credentials_path),- )- .await?,- )- } else {- None- };+ });// Built before the sessions rather than beside the other channel plumbing// below: this service owns the live actors, so it is where a session's@@ -859,11 +843,7 @@ async fn run() -> anyhow::Result<()> {claude_cloud_agents::inbound::auth::ClaudeAuthState::new(Arc::new(claude_cloud_agents::domain::auth::AuthService::new(claude_cloud_agents::outbound::oauth::ClaudeOAuth::new()?,- if matches!(config.environment, Environment::Local) {- claude_credentials- } else {- None- },+ claude_credentials,false,)),MacroAuthorizationState::new(Arc::new(authorization_service.clone())),