diff --git a/crates/fctl-client/src/api.rs b/crates/fctl-client/src/api.rs index 32342465..b022487d 100644 --- a/crates/fctl-client/src/api.rs +++ b/crates/fctl-client/src/api.rs @@ -2085,6 +2085,16 @@ impl Api { .await } + /// Names one of your Claude connections, or, with `None`, takes its + /// name away, so that it goes by its account or its kind. + pub async fn rename_claude(&self, id: &str, label: Option) -> Result { + self.patch( + &format!("/me/claude/{}", enc(id)), + &UpdateClaudeCredentialRequest { label: Some(label) }, + ) + .await + } + pub async fn start_claude_login(&self) -> Result { self.post("/me/claude/login", &serde_json::json!({})).await } diff --git a/crates/fctl-control/migrations/0081_claude_connection_names.sql b/crates/fctl-control/migrations/0081_claude_connection_names.sql new file mode 100644 index 00000000..95d37f32 --- /dev/null +++ b/crates/fctl-control/migrations/0081_claude_connection_names.sql @@ -0,0 +1,4 @@ +-- A Claude connection's label is the name its person gave it, which goes +-- before its account wherever it is named. Logins were labelled "Claude +-- login" by fctl itself, which would hide their account: they go without. +UPDATE claude_credentials SET label = NULL WHERE kind = 'oauth' AND label = 'Claude login'; diff --git a/crates/fctl-control/src/api/claude.rs b/crates/fctl-control/src/api/claude.rs index 3dcf595c..d423f73d 100644 --- a/crates/fctl-control/src/api/claude.rs +++ b/crates/fctl-control/src/api/claude.rs @@ -406,6 +406,57 @@ async fn stop_running(ctx: &Ctx, running: &[(&str, Option<&str>)]) { } } +/// `PATCH /api/v1/me/claude/{id}`: names one of the caller's connections, +/// or takes its name away. +pub async fn update(ctx: &mut Ctx, req: &mut Request, id: &str) -> AppResult { + let body: UpdateClaudeCredentialRequest = http::body(req).await?; + let user = ctx.user()?.clone(); + if let Some(label) = body.label { + let label = label + .as_deref() + .map(str::trim) + .filter(|l| !l.is_empty()) + .map(|l| fctl_domain::validate::name("label", l)) + .transpose()?; + #[derive(serde::Deserialize)] + struct Owned { + #[serde(deserialize_with = "crate::db::int_bool", default)] + provisioned: bool, + } + let owned: Option = q( + &ctx.db, + "SELECT provisioned FROM claude_credentials WHERE id = ? AND user_id = ?", + &[s(id), s(&user.id)], + )? + .first() + .await?; + let Some(owned) = owned else { + return Err(not_found("Credential")); + }; + // Its admins named it, read its name (`api::provision::read`) and + // name the next one: a name of the person's would reach them. + if owned.provisioned { + return Err(validation( + "label", + "Your admins set this token, and its name: they rename it", + )); + } + q( + &ctx.db, + "UPDATE claude_credentials SET label = ?, updated_at = ? WHERE id = ? AND user_id = ?", + &[os(label.as_deref()), n(ctx.now), s(id), s(&user.id)], + )? + .run() + .await?; + // Not the name: admins read the log, and never see it. + ctx.audit("claude.renamed", Some(id), None); + } + let user = auth::user_by_id(ctx, &user.id) + .await? + .ok_or_else(|| not_found("User"))?; + http::ok(&auth::me(ctx, &user).await?) +} + pub async fn set_default(ctx: &mut Ctx, id: &str) -> AppResult { let user = ctx.user()?.clone(); let owned: Option = q( diff --git a/crates/fctl-control/src/do_fleet.rs b/crates/fctl-control/src/do_fleet.rs index 96d479c1..284b042b 100644 --- a/crates/fctl-control/src/do_fleet.rs +++ b/crates/fctl-control/src/do_fleet.rs @@ -4456,12 +4456,11 @@ impl FleetObject { let email = bundle.account.as_ref().and_then(|a| a.email.clone()); crate::db::q( db, - "INSERT INTO claude_credentials (id, user_id, kind, label, secret_enc, scopes, account_email, subscription_type, rate_limit_tier, account, status, expires_at, created_at, updated_at) \ - VALUES (?, ?, 'oauth', ?, ?, ?, ?, ?, ?, ?, 'active', ?, ?, ?)", + "INSERT INTO claude_credentials (id, user_id, kind, secret_enc, scopes, account_email, subscription_type, rate_limit_tier, account, status, expires_at, created_at, updated_at) \ + VALUES (?, ?, 'oauth', ?, ?, ?, ?, ?, ?, 'active', ?, ?, ?)", &[ crate::db::s(id.as_str()), crate::db::s(user_id), - crate::db::s("Claude login"), crate::db::s(&sealed), crate::db::s(&bundle.scopes.join(" ")), crate::db::os(email.as_deref()), diff --git a/crates/fctl-control/src/lib.rs b/crates/fctl-control/src/lib.rs index 9a3e9179..a4816b53 100644 --- a/crates/fctl-control/src/lib.rs +++ b/crates/fctl-control/src/lib.rs @@ -721,6 +721,7 @@ async fn dispatch_rest( // Linear accounts (Get, ["me", "linear"]) => api::linear::mine(ctx).await, (Delete, ["me", "linear", organization]) => api::linear::unlink(ctx, organization).await, + (Patch, ["me", "claude", id]) => api::claude::update(ctx, req, id).await, (Delete, ["me", "claude", id]) => api::claude::remove(ctx, id).await, // Notifications (Get, ["me", "notifications"]) => api::notifications::get(ctx).await, diff --git a/crates/fctl-proto/src/api.rs b/crates/fctl-proto/src/api.rs index ad0795ed..8e8b2618 100644 --- a/crates/fctl-proto/src/api.rs +++ b/crates/fctl-proto/src/api.rs @@ -5495,6 +5495,9 @@ pub enum CredentialStatus { pub struct ClaudeCredentialInfo { pub id: CredentialId, pub kind: ClaudeCredentialKind, + /// The name its person gave it, which says what it is for ("Work + /// seat"): it goes before its account and its kind wherever it is + /// named. Absent until they name it. pub label: Option, pub account_email: Option, pub subscription_type: Option, @@ -5829,6 +5832,22 @@ pub struct AddClaudeTokenRequest { pub made_at: Option, } +/// `PATCH /api/v1/me/claude/{id}`: changes one of the caller's Claude +/// connections. +#[skip_serializing_none] +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS), ts(optional_fields))] +pub struct UpdateClaudeCredentialRequest { + /// Its name, which says what it is for ("Work seat"): `null` or `""` + /// for none, so that it goes by its account or its kind. Left out, it + /// stays. Its person sees it, never their workspaces' admins. A + /// connection an admin token set (`provisioned`) keeps the name its + /// admins gave it: renaming it is refused. + #[serde(default, with = "::serde_with::rust::double_option")] + #[cfg_attr(feature = "ts", ts(optional = nullable, as = "Option"))] + pub label: Option>, +} + /// `POST /api/v1/me/claude/on-runners`: connects the Claude token the /// caller keeps on their runners ([`ClaudeCredentialInfo::on_runners`]), /// which they never give to fctl, and makes it their default. Connecting it diff --git a/crates/fctl-proto/src/ts_export.rs b/crates/fctl-proto/src/ts_export.rs index d078ceb4..a34e3608 100644 --- a/crates/fctl-proto/src/ts_export.rs +++ b/crates/fctl-proto/src/ts_export.rs @@ -314,6 +314,7 @@ pub fn export_typescript(dir: &Path) -> Result<(), ExportError> { api::PlanLimit, api::AddClaudeTokenRequest, api::AddClaudeOnRunnersRequest, + api::UpdateClaudeCredentialRequest, api::ClaudeLoginJob, api::ClaudeLoginState, api::ClaudeLoginCodeRequest, diff --git a/crates/fctl/src/cmd/claude.rs b/crates/fctl/src/cmd/claude.rs index 10ec4046..3f3782cd 100644 --- a/crates/fctl/src/cmd/claude.rs +++ b/crates/fctl/src/cmd/claude.rs @@ -39,6 +39,29 @@ pub enum ClaudeCmd { /// the year from today and says it runs out around then. #[arg(long, value_name = "DAY", conflicts_with_all = ["login", "on_runners"], value_parser = super::claude_overview::made_at)] made_at: Option, + /// A name that says what it is for ("Work seat"), which you tell + /// your connections apart by here, in the web app and in each + /// workspace's choice of connection. `fctl claude rename` changes it. + #[arg(long, value_name = "NAME")] + name: Option, + }, + /// Name one of your connections, or take its name away, so that you + /// can tell them apart: the name goes before its account and its kind + /// wherever it is shown. Only you see it, never your workspaces' + /// admins. + #[command( + after_help = "Examples:\n fctl claude rename crd_01KF… \"Romanesco seat\"\n fctl claude rename ada@example.com Personal\n fctl claude rename Personal --clear" + )] + Rename { + /// The connection: its id (`fctl claude status` lists them), its + /// account, its name, or `on-runners`. + connection: String, + /// Its new name, at most 80 characters. + #[arg(required_unless_present = "clear", conflicts_with = "clear")] + name: Option, + /// Take its name away: it goes by its account, else its kind. + #[arg(long)] + clear: bool, }, /// Show connected subscriptions, when Claude last answered each, when a /// long-lived token runs out, and how much of each plan's limits is used. @@ -78,11 +101,12 @@ pub(crate) const ON_RUNNERS: &str = "on-runners"; pub(crate) const NO_CONNECTION: &str = "You have no Claude connection yet: connect one with `fctl claude connect`."; -/// How a connection reads in lists: its account, else its label, else its kind. +/// How a connection reads in lists: the name its person gave it, else its +/// account, else its kind. fn name(c: &ClaudeCredentialInfo) -> String { - c.account_email + c.label .clone() - .or_else(|| c.label.clone()) + .or_else(|| c.account_email.clone()) .unwrap_or_else(|| { if c.on_runners { "On your runners".into() @@ -121,13 +145,31 @@ fn about(c: &ClaudeCredentialInfo) -> String { about } -/// One of your connections that sessions can run on: the one whose id is -/// `which`, the one you keep on your runners for `on-runners`, else the -/// working one whose account or label it is. +/// One of your connections that sessions can run on: the one +/// [`find_connection`] finds, while it works. pub(crate) fn pick_connection<'a>( mine: &'a [ClaudeCredentialInfo], which: &str, now: i64, +) -> Result<&'a ClaudeCredentialInfo> { + let c = find_connection(mine, which, now)?; + if c.status != CredentialStatus::Active { + bail!( + "{} ({}) needs reconnecting, so sessions can't run on it: `fctl claude connect` adds a new connection", + name(c), + c.id + ); + } + Ok(c) +} + +/// One of your connections: the one whose id is `which`, the one you keep +/// on your runners for `on-runners`, else the one whose name or account it +/// is, the working one where several are. +fn find_connection<'a>( + mine: &'a [ClaudeCredentialInfo], + which: &str, + now: i64, ) -> Result<&'a ClaudeCredentialInfo> { let found = mine.iter().find(|c| c.id.as_str() == which).or_else(|| { (which == ON_RUNNERS) @@ -145,7 +187,7 @@ pub(crate) fn pick_connection<'a>( let named: Vec<&ClaudeCredentialInfo> = mine .iter() .filter(|c| { - [&c.account_email, &c.label] + [&c.label, &c.account_email] .into_iter() .flatten() .any(|n| n.eq_ignore_ascii_case(which)) @@ -158,7 +200,7 @@ pub(crate) fn pick_connection<'a>( .collect(); match (working.as_slice(), named.first().copied()) { ([c], _) => *c, - // It needs reconnecting, which is said below. + // It needs reconnecting, which pick_connection says. ([], Some(c)) => c, ([], None) if mine.is_empty() => bail!(NO_CONNECTION), ([], None) => bail!( @@ -179,13 +221,6 @@ pub(crate) fn pick_connection<'a>( } } }; - if c.status != CredentialStatus::Active { - bail!( - "{} ({}) needs reconnecting, so sessions can't run on it: `fctl claude connect` adds a new connection", - name(c), - c.id - ); - } Ok(c) } @@ -356,13 +391,19 @@ pub async fn run(server: Option<&str>, cmd: ClaudeCmd, json: bool) -> Result<()> }; for c in &me.claude { println!( - "{} {} · {}{}{}", + "{} {} · {}{}{}{}", if c.is_default { style::accent("●") } else { style::dim("○") }, - name(c), + style::terminal_safe(&name(c)), + // A named login says its account too. + c.label + .as_ref() + .and(c.account_email.as_ref()) + .map(|a| format!("{a} · ")) + .unwrap_or_default(), about(c), if c.status == CredentialStatus::Active { String::new() @@ -404,10 +445,49 @@ pub async fn run(server: Option<&str>, cmd: ClaudeCmd, json: bool) -> Result<()> ); Ok(()) } + ClaudeCmd::Rename { + connection, + name: new, + clear, + } => { + // A blank name (an unset variable, say) takes nothing away: + // only --clear does. + let label = if clear { + None + } else { + Some(checked_name(new.as_deref())?) + }; + let me = super::auth::account(&api).await?; + let c = find_connection(&me.claude, &connection, style::now_ms())?; + let me = api.rename_claude(c.id.as_str(), label).await?; + if json { + return style::print_json(&me); + } + if let Some(c) = me.claude.iter().find(|r| r.id == c.id) { + println!( + "{} {} {}", + style::accent("✓"), + if c.label.is_some() { + "Named it" + } else { + "It goes by its account or its kind again:" + }, + style::terminal_safe(&name(c)) + ); + } + Ok(()) + } + // Before anything connects, so that a name the control plane would + // refuse doesn't leave a connection behind an error. + ClaudeCmd::Connect { name: Some(n), .. } if checked_name(Some(&n)).is_err() => { + checked_name(Some(&n)).map(|_| ()) + } ClaudeCmd::Connect { - on_runners: true, .. + on_runners: true, + name: label, + .. } => { - let me = api.add_claude_on_runners(None).await?; + let me = api.add_claude_on_runners(label).await?; if json { return style::print_json(&me); } @@ -434,6 +514,7 @@ pub async fn run(server: Option<&str>, cmd: ClaudeCmd, json: bool) -> Result<()> token, login: false, made_at, + name: label, .. } => { // Before the token is asked for: a day it can't be is said now. @@ -456,7 +537,7 @@ pub async fn run(server: Option<&str>, cmd: ClaudeCmd, json: bool) -> Result<()> crate::prompt::read_secret("Paste the token (input hidden): ")? } }; - let me = api.add_claude_token(&token, None, made_at).await?; + let me = api.add_claude_token(&token, label, made_at).await?; if json { return style::print_json(&me); } @@ -494,7 +575,11 @@ pub async fn run(server: Option<&str>, cmd: ClaudeCmd, json: bool) -> Result<()> ); Ok(()) } - ClaudeCmd::Connect { login: true, .. } => { + ClaudeCmd::Connect { + login: true, + name: label, + .. + } => { let mut job = api.start_claude_login().await?; match &job.runner { Some(r) if r.yours => println!( @@ -536,7 +621,25 @@ pub async fn run(server: Option<&str>, cmd: ClaudeCmd, json: bool) -> Result<()> job = api.submit_claude_code(&job.id.0, &code).await?; continue; } - ClaudeLoginState::Succeeded { .. } => { + ClaudeLoginState::Succeeded { credential_id } => { + // A sign-in takes no name: the connection it made + // gets it once it's there. It's connected whatever + // the name does, so a failed rename only warns. + if let Some(label) = &label + && let Err(e) = api + .rename_claude( + credential_id.as_str(), + Some(label.trim().to_owned()), + ) + .await + { + eprintln!( + "{}", + style::amber(&format!( + "Connected, but not named: {e}. Name it with `fctl claude rename {credential_id} `." + )) + ); + } if json { return style::print_json(&job); } @@ -557,6 +660,16 @@ pub async fn run(server: Option<&str>, cmd: ClaudeCmd, json: bool) -> Result<()> } } +/// A connection's new name, as the control plane takes it: trimmed, not +/// blank, at most 80 characters. +fn checked_name(name: Option<&str>) -> Result { + let name = name.unwrap_or_default(); + if name.trim().is_empty() { + bail!("Give it a name, or take its name away with --clear"); + } + fctl_domain::validate::name("label", name).map_err(|e| anyhow::anyhow!(e.message)) +} + /// What `fctl claude connect --login` says of the runner its sign-in runs /// on, when it isn't one of the person's own: whose it is, and what its /// host could do with the login (docs/security.md). @@ -657,6 +770,44 @@ mod tests { Ok(()) } + #[test] + fn a_connection_goes_by_its_name_before_its_account() -> Result<()> { + let mut login = connection("crd_01ADA", "oauth", Some("ada@example.com"), "active", 0)?; + assert_eq!(name(&login), "ada@example.com"); + login.label = Some("Romanesco seat".into()); + assert_eq!(name(&login), "Romanesco seat"); + assert_eq!( + name(&connection("crd_01T", "setup_token", None, "active", 0)?), + "setup_token" + ); + // One that ended can still be renamed, but sessions can't take it. + let mut ended = connection("crd_01OLD", "setup_token", None, "invalid", 0)?; + ended.label = Some("Old seat".into()); + let mine = [login, ended]; + assert_eq!( + find_connection(&mine, "old seat", NOW) + .map(|c| c.id.to_string()) + .ok(), + Some("crd_01OLD".into()) + ); + assert!(picked(&mine, "old seat").is_err_and(|e| e.contains("needs reconnecting"))); + Ok(()) + } + + #[test] + fn a_blank_or_long_name_is_refused_before_anything_changes() { + assert_eq!( + checked_name(Some(" Romanesco seat ")).ok(), + Some("Romanesco seat".into()) + ); + assert!(checked_name(Some(" ")).is_err_and(|e| e.to_string().contains("--clear"))); + assert!(checked_name(None).is_err()); + assert!( + checked_name(Some(&"x".repeat(81))) + .is_err_and(|e| e.to_string() == "Use at most 80 characters") + ); + } + #[test] fn ultra_plans_are_named() -> Result<()> { let mut login = connection("crd_01ADA", "oauth", None, "active", 0)?; diff --git a/docs/api.md b/docs/api.md index c2680798..00b53336 100644 --- a/docs/api.md +++ b/docs/api.md @@ -615,7 +615,7 @@ state (`none`, `unused`, `works`, `ended`), when their long-lived token runs out (`runs_out_at`, `runs_out_estimated`), whether their sessions wait for a usage limit to reset (`paused_until`), and, as much as they see, the connection's kind, plan and last answer and the limit pauses of -7 and 30 days; never a token, its account or its label. They choose how +7 and 30 days; never a token, its account or a name its person gave it. They choose how much they see and how they hear by email (`claude_oversight`, `claude_limit_pauses`, `claude_admin_email` in `PATCH /api/v1/workspaces/{id}`), within what the instance's admins let them @@ -624,7 +624,11 @@ much they see and how they hear by email (`claude_oversight`, /api/v1/admin/claude` to them, and `claude_refusals`) ([Claude seats](organizations.md#claude-seats)). People connect a long-lived token with `POST /api/v1/me/claude/token`, `{"token", "label", -"made_at"}`. +"made_at"}`, and name a connection, or take its name away, with `PATCH +/api/v1/me/claude/{id}`, `{"label": "Romanesco seat"}` (`null` or `""` +for none, so that it goes by its account or its kind). A token an admin +token set keeps the name its admins gave it, which the admin API reads: +renaming it is refused. ## Sign-in rules diff --git a/docs/cli.md b/docs/cli.md index c71d6e7b..a4415110 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -323,7 +323,7 @@ fctl workspaces order side-project acme # yours in this order, in lists and t fctl workspaces join side-project # an invitation (or decline it) fctl workspaces leave side-project # your sessions there stop fctl workspaces claude crd_01… -w acme # your sessions there run on this Claude connection -fctl workspaces claude ada@acme.example -w acme # …named by its account or label +fctl workspaces claude "Romanesco seat" -w acme # …by its name or its account fctl workspaces claude on-runners -w acme # …on the token you keep on your runners fctl workspaces claude default -w acme # …or on your default one fctl workspaces own-runners on -w acme # your sessions there run only on runners you registered @@ -1160,6 +1160,9 @@ fctl claude connect --token sk-ant-oat01-… fctl claude connect --login # full sign-in, on one of your runners (Remote Control), until Claude ends it fctl claude connect --on-runners # run on the token your runners keep, which you never give to fctl fctl claude connect --made-at 2026-01-14 # …a token `claude setup-token` made that day: it runs out a year on +fctl claude connect --name "Romanesco seat" # …named for what it's for, to tell it from your others +fctl claude rename crd_01… "Romanesco seat" # name one (by its id, account or name): only you see it +fctl claude rename "Romanesco seat" --clear # …or take its name away: it goes by its account or kind again fctl claude status # your connections, their ids, when Claude last answered each, when a token runs out, how much of each plan is used, and which runners keep your token ``` diff --git a/docs/getting-started.md b/docs/getting-started.md index c8e6281e..35511de1 100644 --- a/docs/getting-started.md +++ b/docs/getting-started.md @@ -172,9 +172,12 @@ report it as they work, so it is as recent as your latest session. From 90 %; sessions pause when one is used up, until it resets. With more than one connection, say your own plan and a seat your company -pays for, choose which one each workspace's sessions run on in **Settings -→ Workspaces** (`fctl workspaces claude -w acme`, with the -name or id `fctl claude status` shows). +pays for, name each for what it's for: click its name in **Settings → +Claude** (`fctl claude rename "Romanesco seat"`). Then choose +which one each workspace's sessions run on in **Settings → Workspaces** +(`fctl workspaces claude -w acme`, with the name or id `fctl +claude status` shows). Settings → Claude lists under each connection the +workspaces whose sessions run on it. ## 5. Bring a machine online diff --git a/docs/llms.txt b/docs/llms.txt index f205754f..06933d90 100644 --- a/docs/llms.txt +++ b/docs/llms.txt @@ -112,10 +112,10 @@ queued → provisioning → preparing → running ⇄ idle → stopping → stop ## Claude credentials and usage - Each person connects their own subscription (Pro or Max) in Settings → Claude or with `fctl claude connect` (paste a `claude setup-token` token; lasts a year, so sessions run around the clock without a new sign-in, which is why Settings recommends it; no Remote Control or claude.ai connectors), `fctl claude connect --on-runners` after `fctl host claude set-token` on each of their runners (the same kind of token, which never reaches fctl; their sessions then run only on those runners), or `fctl claude connect --login` (full login through a host: one of theirs, or, when none is online, one that runs their sessions, which the app and CLI name first, since its host sees the login and could swap in a Claude account of its own; Remote Control and claude.ai connectors, but Claude ends it after a while and its sessions stop until they sign in again). -- A session runs on the connection of the person it runs for: who started it (or resumed or took it over last; a schedule's owner; review agents' operator; whoever delegated a Linear ticket; the access token's person). Changing a schedule, or how review agents review, runs it on the subscription of whoever changes it from then on: nobody changes what runs on someone else's subscription. A member chooses which connection each workspace's sessions use (`fctl workspaces claude -w `). +- A session runs on the connection of the person it runs for: who started it (or resumed or took it over last; a schedule's owner; review agents' operator; whoever delegated a Linear ticket; the access token's person). Changing a schedule, or how review agents review, runs it on the subscription of whoever changes it from then on: nobody changes what runs on someone else's subscription. A member chooses which connection each workspace's sessions use (`fctl workspaces claude -w `), and can name each for what it's for (Settings → Claude, `fctl claude rename "Romanesco seat"`, `fctl claude connect --name …`; API: `PATCH /api/v1/me/claude/{id}` with `{"label": …}`, `null` to take it away; a token an admin token set keeps its admins' name), which goes before its account and kind wherever it's shown; Settings → Claude lists the workspaces each one runs. - `fctl claude status` shows each connection's plan usage (five-hour window, week, per-model week) as sessions last reported it, and `ultra` for Claude's Ultra plan, which has no five-hour window; when Claude last answered it; and when a long-lived token runs out: a year after `claude setup-token` made it (`fctl claude connect --made-at 2026-11-20`; without it fctl counts the year from the connection and says "around"; connecting the same token again keeps its date). Sessions pause at a limit and resume when it resets. - **When a connection stops working.** Claude refuses a revoked or expired token in the sessions that run on it; once it did in as many sessions as the instance says (2 by default, `fctl admin set --claude-refusals`) since it last answered it, fctl marks it ended, as it marks a login Claude won't renew, and sessions run on the person's other connection if one works. fctl tells the person 30 and 7 days before a token runs out and as soon as one stops working: by email where the instance sends it, under the connection in Settings → Claude, and on the Agent Floor in its last week. Where Claude refused a session's connection ("Failed to authenticate. API Error: 401 …", or "Not logged in · Please run /login" from Claude Code without a credential it can use), the session's page says the login or token most likely expired: messages to it fail the same way, since they keep it on that connection, and `/login` doesn't work in a session. Connect Claude again (a new long-lived token, or sign in with Claude), then continue the session on the new connection: **Continue the session** on its page, or `fctl take-over SESSION` (`fctl resume SESSION` for a failed one). -- **What admins see** (Claude seats in organizations): a workspace's admins see on its People tab, and with `fctl workspaces members -w acme --claude [--problems] [--expiring 30d] [--json]`, each member's connection there: its state (none, unused, works, ended), plan, kind and who set it (an admin token), when Claude last answered it, when its token runs out, whether their sessions wait for a usage limit, and how often their sessions there paused on limits in 7 and 30 days; never a token, its account or its label. The instance's admins choose the most workspaces' admins may see (`fctl admin set --claude-oversight details|readiness|off --claude-limit-pauses on|off`) and whether they see everyone's themselves (`--claude-instance-view on`, then Admin → People and `fctl admin claude`); each workspace chooses within it and how its admins hear by email (`fctl workspaces set --claude-oversight … --claude-limit-pauses … --claude-admin-email weekly|each|off`, weekly by default). Members read what their admins see in the workspace's Settings → You. API: `GET /api/v1/workspaces/{id}/claude`, `GET /api/v1/admin/claude`. +- **What admins see** (Claude seats in organizations): a workspace's admins see on its People tab, and with `fctl workspaces members -w acme --claude [--problems] [--expiring 30d] [--json]`, each member's connection there: its state (none, unused, works, ended), plan, kind and who set it (an admin token), when Claude last answered it, when its token runs out, whether their sessions wait for a usage limit, and how often their sessions there paused on limits in 7 and 30 days; never a token, its account or a name its person gave it. The instance's admins choose the most workspaces' admins may see (`fctl admin set --claude-oversight details|readiness|off --claude-limit-pauses on|off`) and whether they see everyone's themselves (`--claude-instance-view on`, then Admin → People and `fctl admin claude`); each workspace chooses within it and how its admins hear by email (`fctl workspaces set --claude-oversight … --claude-limit-pauses … --claude-admin-email weekly|each|off`, weekly by default). Members read what their admins see in the workspace's Settings → You. API: `GET /api/v1/workspaces/{id}/claude`, `GET /api/v1/admin/claude`. - **Keeping the token out of sandboxes** (experimental, off by default): `fctl claude set --stand-in on` (Settings → Claude) gives Claude a stand-in that Anthropic refuses, and the host of the runner puts the person's token in as Claude's requests leave for `api.anthropic.com`, so agents can neither read the token nor send it anywhere. It applies to the sessions that start afterwards, to every connection of theirs; Remote Control and claude.ai connectors may not work with it. Turning it off may need confirming it's them. ## Driving fctl from an agent or a script diff --git a/web/src/components/claude/connect.tsx b/web/src/components/claude/connect.tsx index c12b6cdd..558ea44a 100644 --- a/web/src/components/claude/connect.tsx +++ b/web/src/components/claude/connect.tsx @@ -7,7 +7,17 @@ import { useMutation, useQuery } from "@tanstack/react-query"; import { ArrowUpRight, Check, Info, KeyRound, Minus, Radio } from "lucide-react"; import { type ReactNode, useEffect, useId, useRef, useState } from "react"; -import { Banner, Button, buttonClass, CodeBox, Input, SecretInput, Spinner, toast } from "@/components/ui"; +import { + Banner, + Button, + buttonClass, + CodeBox, + Field, + Input, + SecretInput, + Spinner, + toast, +} from "@/components/ui"; import type * as G from "@/gen"; import { api } from "@/lib/api"; import { cn } from "@/lib/cn"; @@ -80,7 +90,11 @@ export function ConnectClaude({ recommended facts={TOKEN_FACTS} > - c.on_runners)} onConnected={() => onWay(null)} /> + c.on_runners)} + others={!first} + onConnected={() => onWay(null)} + /> void }) { +function TokenFlow({ + onRunners, + others, + onConnected, +}: { + onRunners: boolean; + /** You have other connections: it can take a name that tells it apart. */ + others: boolean; + onConnected: () => void; +}) { const [place, setPlace] = useState("fctl"); const name = useId(); // You keep one on your runners already: what is left is giving fctl one. @@ -259,7 +282,7 @@ function TokenFlow({ onRunners, onConnected }: { onRunners: boolean; onConnected )} {/* Both stay, one hidden, so that a pasted token is still there after a look at the other. */} {!onRunners && (

{madeHint(made, madeAt, now)}

+ {others && ( + + {(id) => ( + // Enter here connects too. + setLabel(e.target.value)} + placeholder="Work seat" + maxLength={80} + autoComplete="off" + /> + )} + + )} {add.error && (

{add.error.message} diff --git a/web/src/components/claude/connection.test.tsx b/web/src/components/claude/connection.test.tsx new file mode 100644 index 00000000..3598e1e4 --- /dev/null +++ b/web/src/components/claude/connection.test.tsx @@ -0,0 +1,141 @@ +import { QueryClientProvider } from "@tanstack/react-query"; +import { act, type ReactNode } from "react"; +import { createRoot } from "react-dom/client"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import type * as G from "@/gen"; +import { keys, queryClient } from "@/lib/queries"; +import { ConnectionName, ConnectionWorkspaces } from "./connection"; + +const claudeRename = vi.fn((id: string, label: string | null) => + Promise.resolve({ claude: [{ ...seat, id, label: label ?? undefined }] } as G.Me), +); + +vi.mock("@/lib/api", () => ({ + api: new Proxy({}, { get: (_, k) => (k === "claudeRename" ? claudeRename : () => new Promise(() => {})) }), + ApiFailure: class extends Error {}, +})); +vi.mock("@tanstack/react-router", () => ({ + Link: ({ children, className }: { children: ReactNode; className?: string }) => ( + + {children} + + ), +})); + +(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; + +const roots: (() => void)[] = []; +afterEach(() => { + for (const unmount of roots.splice(0)) unmount(); + queryClient.clear(); + claudeRename.mockClear(); +}); + +const seat: G.ClaudeCredentialInfo = { + id: "crd_seat", + kind: "oauth", + account_email: "ada@romanesco.example", + remote_control: true, + status: "active", + is_default: false, + created_at: 0, +}; + +function render(node: ReactNode) { + const container = document.createElement("div"); + document.body.append(container); + const root = createRoot(container); + act(() => root.render({node})); + roots.push(() => { + act(() => root.unmount()); + container.remove(); + }); + return container; +} + +function type(input: HTMLInputElement | null, value: string) { + if (!input) throw new Error("no input"); + const set = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")?.set; + act(() => { + set?.call(input, value); + input.dispatchEvent(new Event("input", { bubbles: true })); + }); +} + +const flush = () => act(() => new Promise((r) => setTimeout(r, 0))); + +describe("naming a Claude connection", () => { + it("goes by its account until it's named, and invites a name where several need telling apart", () => { + const view = render(); + const button = view.querySelector("button"); + expect(button?.textContent).toBe("ada@romanesco.example: name it"); + expect(view.querySelector("svg")?.getAttribute("class")).toContain("opacity-100"); + }); + + it("renames in place on Enter, and the page takes the new name", async () => { + queryClient.setQueryData(keys.me, { claude: [seat] }); + const view = render(); + act(() => view.querySelector("button")?.click()); + const input = view.querySelector("input"); + expect(input?.placeholder).toBe("ada@romanesco.example"); + expect(view.textContent).toContain("Only you see it."); + type(input, " Romanesco seat "); + act(() => input?.form?.requestSubmit()); + await flush(); + expect(claudeRename).toHaveBeenCalledWith("crd_seat", "Romanesco seat"); + expect(queryClient.getQueryData(keys.me)?.claude[0]?.label).toBe("Romanesco seat"); + expect(view.querySelector("input")).toBeNull(); + }); + + it("takes the name away when emptied, and changes nothing on Escape", async () => { + const named = { ...seat, label: "Romanesco seat" }; + const view = render(); + act(() => view.querySelector("button")?.click()); + const input = view.querySelector("input"); + type(input, "Something else"); + act(() => { + input?.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", bubbles: true })); + }); + expect(claudeRename).not.toHaveBeenCalled(); + expect(view.querySelector("button")?.textContent).toBe("Romanesco seat: rename it"); + act(() => view.querySelector("button")?.click()); + type(view.querySelector("input"), ""); + act(() => view.querySelector("form")?.requestSubmit()); + await flush(); + expect(claudeRename).toHaveBeenCalledWith("crd_seat", null); + }); + it("leaves the name of a token its admins set to them", () => { + const view = render( + , + ); + expect(view.querySelector("button")).toBeNull(); + expect(view.textContent).toBe("Acme seat"); + }); +}); + +describe("the workspaces a Claude connection runs", () => { + const ws = (id: string, name: string, claude?: string) => + ({ id, name, slug: id, color: "blue", claude }) as G.Workspace; + const own = { ...seat, id: "crd_own", kind: "setup_token", is_default: true } as G.ClaudeCredentialInfo; + const old = { ...seat, id: "crd_old", status: "invalid" } as G.ClaudeCredentialInfo; + const me = { claude: [seat, own, old] } as G.Me; + const all = [ws("wsp_r", "Romanesco", "crd_seat"), ws("wsp_p", "Personal"), ws("wsp_s", "Shop", "crd_old")]; + + it("names the workspaces whose sessions run on it", () => { + expect(render().textContent).toBe( + // Each after its avatar's initial. + "Runs your sessions inRRomanescoChoose per workspace", + ); + expect(render().textContent).toBe( + "Runs your sessions inPPersonalSShopChoose per workspace", + ); + }); + + it("says where one that ended was chosen, and shows nothing where none runs on it", () => { + expect(render().textContent).toBe( + "Chosen inSShop· their sessions run on your default until you reconnect itChoose per workspace", + ); + const spare = { ...seat, id: "crd_spare" }; + expect(render().textContent).toBe(""); + }); +}); diff --git a/web/src/components/claude/connection.tsx b/web/src/components/claude/connection.tsx new file mode 100644 index 00000000..d9ccc658 --- /dev/null +++ b/web/src/components/claude/connection.tsx @@ -0,0 +1,175 @@ +// A Claude connection's row in Settings → Claude: its name, which its person changes in place, and +// the workspaces whose sessions run on it. + +import { useMutation } from "@tanstack/react-query"; +import { Link } from "@tanstack/react-router"; +import { Pencil } from "lucide-react"; +import { useEffect, useRef, useState } from "react"; +import { Input, toast } from "@/components/ui"; +import { WorkspaceAvatar } from "@/components/workspace/avatar"; +import type * as G from "@/gen"; +import { api } from "@/lib/api"; +import { claudeName, kindName, workspacesOn } from "@/lib/claude"; +import { cn } from "@/lib/cn"; +import { keys, queryClient } from "@/lib/queries"; + +/** What a connection goes by without a name of its own: its account, else its kind. */ +const unnamed = (c: G.ClaudeCredentialInfo) => c.account_email ?? kindName(c); + +/** + * A connection's name, which its person changes in place: Enter or leaving the field saves, Escape + * cancels, and an empty name takes it away, so that it goes by its account or its kind again. The + * pencil shows on hover and focus, and always on touch; where `invite` (more connections than one, + * and this one has no name of its own), it always shows, as naming is what tells them apart. A token + * an admin token set keeps the name its admins gave it, which they read: it doesn't rename here. + */ +export function ConnectionName({ + credential: c, + invite, + children, +}: { + credential: G.ClaudeCredentialInfo; + invite?: boolean; + /** What goes after the name, before the pencil, such as a tag. */ + children?: React.ReactNode; +}) { + const [editing, setEditing] = useState(false); + const [draft, setDraft] = useState(c.label ?? ""); + const input = useRef(null); + const rename = useMutation({ + mutationFn: (label: string | null) => api.claudeRename(c.id, label), + onSuccess: (m, label) => { + queryClient.setQueryData(keys.me, m); + setEditing(false); + // The pickers and the session pages name it too: say where it shows. + toast(label ? `Named it ${label}: your workspaces' pickers say so` : `It goes by ${unnamed(c)} again`); + }, + onError: (e) => toast(e.message, "error"), + }); + useEffect(() => { + if (editing) input.current?.select(); + }, [editing]); + const stop = () => { + setDraft(c.label ?? ""); + setEditing(false); + }; + const save = () => { + const next = draft.trim().replace(/\s+/g, " "); + if (next === (c.label ?? "")) stop(); + else rename.mutate(next || null); + }; + // Its admins named it, and read the name: it stays theirs to change. + if (c.provisioned) + return ( +

+ {claudeName(c)} + {children} +
+ ); + if (editing) + return ( + { + e.preventDefault(); + save(); + }} + > + setDraft(e.target.value)} + onBlur={save} + onKeyDown={(e) => { + if (e.key === "Escape") { + // The field's own, not the page's or a dialog's. + e.preventDefault(); + stop(); + } + }} + maxLength={80} + aria-label="The connection's name" + aria-describedby={`${c.id}-name-hint`} + className="h-8 max-w-xs" + disabled={rename.isPending} + /> +

+ Say what it's for, such as a team or a plan. Only you see it. Empty, it goes by {unnamed(c)}. +

+ + ); + return ( + + ); +} + +/** How many workspaces a row names before it counts the rest. */ +const SHOWN = 4; + +/** + * The workspaces whose sessions run on a connection, as small chips, or, for one that stopped + * working, those that chose it and run on another until it's reconnected. Nothing where none does. + */ +export function ConnectionWorkspaces({ + credential: c, + me, + workspaces, +}: { + credential: G.ClaudeCredentialInfo; + me: G.Me; + workspaces: readonly G.Workspace[]; +}) { + const { runs, waits } = workspacesOn(c, me, workspaces); + const shown = runs.length ? runs : waits; + if (!shown.length) return null; + const more = shown.length - SHOWN; + return ( +
+ + {runs.length ? "Runs your sessions in" : "Chosen in"} + + {shown.slice(0, SHOWN).map((w) => ( + + + {w.name} + + ))} + {more > 0 && and {more} more} + {!runs.length && · their sessions run on your default until you reconnect it} + {/* A link sits after the chips, so it doesn't look like one of them. */} + + Choose per workspace + +
+ ); +} diff --git a/web/src/components/session/claude-refused.tsx b/web/src/components/session/claude-refused.tsx index 45cbc6b3..0f2aa65f 100644 --- a/web/src/components/session/claude-refused.tsx +++ b/web/src/components/session/claude-refused.tsx @@ -11,6 +11,7 @@ import { createContext, type ReactNode, useContext, useId, useState } from "reac import { ConnectClaude, type Way } from "@/components/claude/connect"; import { Button, Dialog } from "@/components/ui"; import type * as G from "@/gen"; +import { claudeName, kindName, namedConnection } from "@/lib/claude"; import { runsOutWords } from "@/lib/claude-oversight"; import type { Fix, Refusal, RefusedKind } from "@/lib/claude-refused"; import { cn } from "@/lib/cn"; @@ -93,23 +94,14 @@ export function refusedText(fix: Fix, why: Refusal): string { return `${lead}${because} Messages to the agent fail the same way until the session moves to a connection that works.`; } -/** What kind of connection it is, as Settings → Claude names one without a name of its own. */ -const kindName = (c: G.ClaudeCredentialInfo) => - c.on_runners ? "Token on your runners" : c.kind === "oauth" ? "Claude login" : "Long-lived token"; - -/** A connection by what people know it as: its account, its label, else its kind. */ -function connectionName(c: G.ClaudeCredentialInfo): string { - return c.account_email ?? c.label ?? kindName(c); -} - /** * What else there is to know of a connection, beside its name: its kind when the name isn't it, * whether new sessions run on it, and when a token runs out. */ function connectionDetails(c: G.ClaudeCredentialInfo): string { - const named = !!(c.account_email ?? c.label); const facts = [ - named && kindName(c), + c.label && c.account_email, + namedConnection(c) && kindName(c), c.is_default && "used for new sessions", c.kind !== "oauth" && c.expires_at && runsOutWords(c.expires_at, c.expiry_estimated), ].filter((f): f is string => !!f); @@ -337,7 +329,7 @@ function ConnectionLine({ connection: c }: { connection: G.ClaudeCredentialInfo {c.on_runners ? : c.kind === "oauth" ? : } - {connectionName(c)} + {claudeName(c)} {details && {details}} diff --git a/web/src/gen/ClaudeCredentialInfo.ts b/web/src/gen/ClaudeCredentialInfo.ts index 2bf2cca5..db8c767c 100644 --- a/web/src/gen/ClaudeCredentialInfo.ts +++ b/web/src/gen/ClaudeCredentialInfo.ts @@ -4,7 +4,13 @@ import type { CredentialId } from "./CredentialId"; import type { CredentialStatus } from "./CredentialStatus"; import type { PlanLimit } from "./PlanLimit"; -export type ClaudeCredentialInfo = { id: CredentialId, kind: ClaudeCredentialKind, label?: string, account_email?: string, subscription_type?: string, +export type ClaudeCredentialInfo = { id: CredentialId, kind: ClaudeCredentialKind, +/** + * The name its person gave it, which says what it is for ("Work + * seat"): it goes before its account and its kind wherever it is + * named. Absent until they name it. + */ +label?: string, account_email?: string, subscription_type?: string, /** * The login's rate limit tier (`default_claude_max_20x` is Ultra, which * was Max 20x), from `claude auth login`. Absent for long-lived tokens diff --git a/web/src/gen/UpdateClaudeCredentialRequest.ts b/web/src/gen/UpdateClaudeCredentialRequest.ts new file mode 100644 index 00000000..c8a7e46b --- /dev/null +++ b/web/src/gen/UpdateClaudeCredentialRequest.ts @@ -0,0 +1,15 @@ +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. + +/** + * `PATCH /api/v1/me/claude/{id}`: changes one of the caller's Claude + * connections. + */ +export type UpdateClaudeCredentialRequest = { +/** + * Its name, which says what it is for ("Work seat"): `null` or `""` + * for none, so that it goes by its account or its kind. Left out, it + * stays. Its person sees it, never their workspaces' admins. A + * connection an admin token set (`provisioned`) keeps the name its + * admins gave it: renaming it is refused. + */ +label?: string | null, }; diff --git a/web/src/gen/index.ts b/web/src/gen/index.ts index 0b48d78b..2f41b668 100644 --- a/web/src/gen/index.ts +++ b/web/src/gen/index.ts @@ -512,6 +512,7 @@ export type { TwoFactor } from "./TwoFactor"; export type { TwoFactorChallenge } from "./TwoFactorChallenge"; export type { TwoFactorCodeRequest } from "./TwoFactorCodeRequest"; export type { UnheardEvent } from "./UnheardEvent"; +export type { UpdateClaudeCredentialRequest } from "./UpdateClaudeCredentialRequest"; export type { UpdateEmailRequest } from "./UpdateEmailRequest"; export type { UpdateEnrollmentTokenRequest } from "./UpdateEnrollmentTokenRequest"; export type { UpdateInstanceSettingsRequest } from "./UpdateInstanceSettingsRequest"; diff --git a/web/src/lib/api.ts b/web/src/lib/api.ts index 97e07206..fba27718 100644 --- a/web/src/lib/api.ts +++ b/web/src/lib/api.ts @@ -575,6 +575,9 @@ export const api = { request("POST", `/me/claude/login/${enc(id)}/code`, { code }), claudeDefault: (id: string) => request("POST", `/me/claude/${enc(id)}/default`, {}), claudeRemove: (id: string) => request("DELETE", `/me/claude/${enc(id)}`), + /** Names a connection; `null` takes its name away. */ + claudeRename: (id: string, label: string | null) => + request("PATCH", `/me/claude/${enc(id)}`, { label } satisfies G.UpdateClaudeCredentialRequest), runners: () => request("GET", "/runners"), createRunner: (b: G.CreateRunnerRequest) => request("POST", "/runners", b), diff --git a/web/src/lib/audit.ts b/web/src/lib/audit.ts index f94b2106..18728bda 100644 --- a/web/src/lib/audit.ts +++ b/web/src/lib/audit.ts @@ -519,6 +519,8 @@ function sentence(e: G.AuditEntry, names: AuditNames): AuditPart[] { return ["connected a Claude subscription"]; case "claude.removed": return ["removed a Claude connection"]; + case "claude.renamed": + return ["renamed a Claude connection"]; case "claude.token_set": return ["set the Claude token of ", user(t)]; case "claude.token_removed": diff --git a/web/src/lib/claude.test.ts b/web/src/lib/claude.test.ts index 06bfcfb6..bccdb708 100644 --- a/web/src/lib/claude.test.ts +++ b/web/src/lib/claude.test.ts @@ -1,6 +1,14 @@ import { describe, expect, it } from "vitest"; import type * as G from "@/gen"; -import { connectionIn, tokenOnRunnersIn, tokenRunnersIn, tokenState, yourRunnerTokens } from "./claude"; +import { + claudeName, + connectionIn, + tokenOnRunnersIn, + tokenRunnersIn, + tokenState, + workspacesOn, + yourRunnerTokens, +} from "./claude"; const cred = (c: Partial & { id: string }): G.ClaudeCredentialInfo => ({ kind: "setup_token", @@ -49,6 +57,40 @@ describe("connectionIn", () => { }); }); +describe("claudeName", () => { + it("goes by the name you gave it, else its account, else its kind", () => { + const login = cred({ id: "crd_1", kind: "oauth", account_email: "ada@example.com" }); + expect(claudeName(login)).toBe("ada@example.com"); + expect(claudeName({ ...login, label: "Romanesco seat" })).toBe("Romanesco seat"); + expect(claudeName(cred({ id: "crd_2" }))).toBe("Long-lived token"); + expect(claudeName(cred({ id: "crd_3", kind: "oauth" }))).toBe("Claude login"); + expect(claudeName(cred({ id: "crd_4", on_runners: true }))).toBe("Token on your runners"); + }); +}); + +describe("workspacesOn", () => { + const seat = cred({ id: "crd_seat", label: "Romanesco seat" }); + const own = cred({ id: "crd_own", is_default: true }); + const old = cred({ id: "crd_old", status: "invalid" }); + const romanesco = { id: "wsp_r", claude: "crd_seat" }; + const personal = { id: "wsp_p" }; + const shop = { id: "wsp_s", claude: "crd_old" }; + const all = [romanesco, personal, shop]; + const ids = (ws: { id: string }[]) => ws.map((w) => w.id); + + it("finds the workspaces that chose it, and those that fall back on the default", () => { + expect(ids(workspacesOn(seat, me([seat, own, old]), all).runs)).toEqual(["wsp_r"]); + // The shop chose one that ended: its sessions run on the default meanwhile. + expect(ids(workspacesOn(own, me([seat, own, old]), all).runs)).toEqual(["wsp_p", "wsp_s"]); + }); + + it("says which workspaces wait for one that ended", () => { + const on = workspacesOn(old, me([seat, own, old]), all); + expect(on.runs).toEqual([]); + expect(ids(on.waits)).toEqual(["wsp_s"]); + }); +}); + describe("where your runners stand with your token", () => { it("tells runners that keep it from those that could and those too old to", () => { expect(tokenState(runner({ id: "a", claude_token: { saved_at: 5 } }))).toBe("kept"); diff --git a/web/src/lib/claude.ts b/web/src/lib/claude.ts index a151f7d0..46a8cda1 100644 --- a/web/src/lib/claude.ts +++ b/web/src/lib/claude.ts @@ -19,6 +19,35 @@ export function connectionIn( return chosen ?? working.find((c) => c.is_default) ?? newest; } +/** What kind of connection it is, as one without a name of its own goes by. */ +export function kindName(c: Pick): string { + return c.on_runners ? "Token on your runners" : c.kind === "oauth" ? "Claude login" : "Long-lived token"; +} + +/** A connection as you know it: the name you gave it, else its account, else its kind. */ +export function claudeName(c: G.ClaudeCredentialInfo): string { + return c.label ?? c.account_email ?? kindName(c); +} + +/** Whether it goes by a name or an account, rather than by its kind. */ +export const namedConnection = (c: G.ClaudeCredentialInfo): boolean => !!(c.label ?? c.account_email); + +/** + * Where a connection serves: `runs`, the workspaces whose sessions run on it (those that chose it, + * and those that chose none while it is the one they fall back on); `waits`, those that chose it + * after it stopped working, whose sessions run on another until it's reconnected. + */ +export function workspacesOn>( + c: G.ClaudeCredentialInfo, + me: Pick | null | undefined, + workspaces: readonly W[], +): { runs: W[]; waits: W[] } { + return { + runs: workspaces.filter((w) => connectionIn(me, w)?.id === c.id), + waits: c.status === "active" ? [] : workspaces.filter((w) => w.claude === c.id), + }; +} + /** Whether your sessions in `w` run on the token you keep on your runners. */ export function tokenOnRunnersIn( me: Pick | null | undefined, diff --git a/web/src/lib/settings.ts b/web/src/lib/settings.ts index 531d99f6..ef8eca57 100644 --- a/web/src/lib/settings.ts +++ b/web/src/lib/settings.ts @@ -2,9 +2,9 @@ // each, which one an address opens, and what the list of them on a phone says about each. import type * as G from "@/gen"; +import { claudeName } from "./claude"; import { daysLeft, yourClaude } from "./claude-oversight"; import { FEW_RECOVERY_CODES } from "./two-factor"; -import { claudeName } from "./workspaces"; export const SETTINGS_TABS = [ "profile", diff --git a/web/src/lib/workspaces.test.ts b/web/src/lib/workspaces.test.ts index ff20d428..a64228c4 100644 --- a/web/src/lib/workspaces.test.ts +++ b/web/src/lib/workspaces.test.ts @@ -39,6 +39,37 @@ describe("claudeOptions", () => { expect(options[3]?.label).toBe("old@company.example (reconnect it)"); }); + it("names each by the name you gave it, with its account and kind under it", () => { + const named = cred({ id: "crd_named", label: "Romanesco seat", account_email: "ada@company.example" }); + const options = claudeOptions(me([named, { ...own, label: "Personal" }]), undefined, "Claude: "); + expect(options[0]?.label).toBe("Claude: your default (Personal)"); + expect(options[1]).toMatchObject({ + label: "Claude: Romanesco seat", + description: "ada@company.example · Claude login", + }); + }); + + it("tells unnamed tokens apart by when they were added", () => { + const a = cred({ + id: "crd_a", + kind: "setup_token", + remote_control: false, + created_at: Date.UTC(2026, 0, 5), + }); + const b = cred({ + id: "crd_b", + kind: "setup_token", + remote_control: false, + created_at: Date.UTC(2026, 5, 9), + }); + const options = claudeOptions(me([a, b]), undefined); + expect(options.map((o) => o.label)).toEqual(["Your default", "Long-lived token", "Long-lived token"]); + expect(options[1]?.description).toMatch(/^added /); + expect(options[1]?.description).not.toBe(options[2]?.description); + // Alone, it needs no date, and its name says the rest. + expect(claudeOptions(me([a]), undefined)[1]?.description).toBeUndefined(); + }); + it("names one that was removed instead of showing its id", () => { const options = claudeOptions(me([own]), "crd_gone", "Claude: "); expect(options.at(-1)).toMatchObject({ value: "crd_gone", label: "Claude: A connection you removed" }); diff --git a/web/src/lib/workspaces.ts b/web/src/lib/workspaces.ts index ab2e8b8e..74d8c3a2 100644 --- a/web/src/lib/workspaces.ts +++ b/web/src/lib/workspaces.ts @@ -5,6 +5,8 @@ import { useCallback, useEffect, useMemo, useRef, useSyncExternalStore } from "react"; import type * as G from "@/gen"; import { workspaces as workspacesApi } from "./api"; +import { claudeName, kindName, namedConnection } from "./claude"; +import { shortDay } from "./claude-oversight"; import { pending, withPendingProjects, withPendingWorkspaces } from "./order"; import { keys, queryClient, useMe, useWorkspaces } from "./queries"; import { planOf } from "./usage"; @@ -278,22 +280,43 @@ export function useFactorsWatch() { }, [factors]); } -/** How a Claude connection reads in lists: its account, else its label. */ -export const claudeName = (c: G.ClaudeCredentialInfo) => - c.account_email ?? c.label ?? (c.on_runners ? "Token on your runners" : "Claude"); +/** + * What a picker says under a working connection: its account where a name of yours stands for it, + * its kind where its name isn't that, and its plan; and when it was connected, where another goes by + * the same name. + */ +function aboutConnection( + c: G.ClaudeCredentialInfo, + all: readonly G.ClaudeCredentialInfo[], +): string | undefined { + if (c.on_runners) return "Kept on your runners: sessions run only on yours that keep it"; + const twin = all.some((o) => o.id !== c.id && o.status === "active" && claudeName(o) === claudeName(c)); + return ( + [ + c.label && c.account_email, + namedConnection(c) && kindName(c), + planOf(c), + twin && `added ${shortDay(c.created_at)}`, + ] + .filter((f): f is string => !!f) + .join(" · ") || undefined + ); +} /** * The Claude connections someone's sessions in a workspace can run on: * their default, then each working one, and the one chosen there even * when it stopped working, so the picker says so instead of showing an id. - * `prefix` goes before each label (in a row of other things). + * Each goes by its name ([`claudeName`]). `prefix` goes before each label + * (in a row of other things). */ export function claudeOptions( me: G.Me | null | undefined, current: string | undefined, prefix = "", ): { value: string; label: string; description?: string }[] { - const fallback = me?.claude.find((c) => c.is_default); + const mine = me?.claude ?? []; + const fallback = mine.find((c) => c.is_default); const options: { value: string; label: string; description?: string }[] = [ { value: "default", @@ -302,14 +325,12 @@ export function claudeOptions( description: "The one Settings → Claude marks as default", }, ]; - for (const c of me?.claude ?? []) { + for (const c of mine) { if (c.status === "active") options.push({ value: c.id, label: `${prefix}${claudeName(c)}`, - description: c.on_runners - ? "Kept on your runners: sessions run only on yours that keep it" - : (planOf(c) ?? c.kind), + description: aboutConnection(c, mine), }); else if (c.id === current) options.push({ diff --git a/web/src/routes/settings.test.tsx b/web/src/routes/settings.test.tsx index c9c3f687..b1c249e4 100644 --- a/web/src/routes/settings.test.tsx +++ b/web/src/routes/settings.test.tsx @@ -253,7 +253,7 @@ describe("your Claude connections, as they run out and end", () => { }), ]); expect(page.textContent).toMatch( - /Inference only · no Remote Control · Claude answered 2 hours ago · runs out around /, + /Personal.*Long-lived token · inference only · no Remote Control · Claude answered 2 hours ago · runs out around /, ); expect(page.textContent).not.toContain("Connect a new token"); }); @@ -279,7 +279,7 @@ describe("your Claude connections, as they run out and end", () => { it("sends people to their admins for the next token an admin token set", () => { const page = claudePage([token({ provisioned: true, expires_at: Date.now() + 5 * day })]); - expect(page.textContent).toContain("Set by your admins · inference only"); + expect(page.textContent).toContain("Long-lived token · set by your admins · inference only"); expect(page.textContent).toContain( "Your admins set this token, and set the next one: ask them if it doesn't come before then, or connect one of your own here.", ); diff --git a/web/src/routes/settings.tsx b/web/src/routes/settings.tsx index 4b7f25f9..f320bf53 100644 --- a/web/src/routes/settings.tsx +++ b/web/src/routes/settings.tsx @@ -34,6 +34,7 @@ import { } from "lucide-react"; import { type ReactNode, useEffect, useRef, useState } from "react"; import { CONNECT_ID, ConnectClaude, EndedLogin, EndedToken, type Way } from "@/components/claude/connect"; +import { ConnectionName, ConnectionWorkspaces } from "@/components/claude/connection"; import { OnRunnersDetails } from "@/components/claude/on-runners"; import { KeepTokenOut } from "@/components/claude/stand-in"; import { PasskeySettings } from "@/components/passkeys/settings"; @@ -73,7 +74,7 @@ import type * as G from "@/gen"; import { api, clickConfirmed, confirmFirst, emails, linearLinkUrl, workspaces as wsApi } from "@/lib/api"; import { forgetLog } from "@/lib/app-log"; import { avatarImage } from "@/lib/avatar-image"; -import { tokenOnRunnersIn } from "@/lib/claude"; +import { kindName, namedConnection, tokenOnRunnersIn } from "@/lib/claude"; import { fullDay, runsOutWords, SOON_DAYS, within } from "@/lib/claude-oversight"; import { cn } from "@/lib/cn"; import { withAlpha } from "@/lib/color"; @@ -815,6 +816,8 @@ function Workspaces({ me }: { me: G.Me }) { function Claude({ me }: { me: G.Me }) { // Which way to connect is open: the recommended one until you have a connection. const [way, setWay] = useState(() => (me.claude.length === 0 ? "token" : null)); + // Which of them runs your sessions where. + const workspaces = useWorkspaces(); const remove = useMutation({ mutationFn: (id: string) => api.claudeRemove(id), onSuccess: (m) => queryClient.setQueryData(keys.me, m), @@ -868,28 +871,17 @@ function Claude({ me }: { me: G.Me }) { )}
-
- {c.account_email ?? - c.label ?? - (c.on_runners - ? "Token on your runners" - : c.kind === "oauth" - ? "Claude login" - : "Long-lived token")} - {c.is_default && ( - - used for new sessions - - )} +
+ 1 && !c.label}> + {c.is_default && ( + + used for new sessions + + )} +
- {c.on_runners - ? "Kept on your runners · never given to fctl · no Remote Control" - : c.kind === "oauth" - ? "Full login · Remote Control" - : c.provisioned - ? "Set by your admins · inference only · no Remote Control" - : "Inference only · no Remote Control"} + {connectionKind(c)} {planOf(c) && ` · ${planOf(c)}`} {c.status === "invalid" && · needs reconnecting} {c.status !== "invalid" && c.answered_at @@ -913,6 +905,9 @@ function Claude({ me }: { me: G.Me }) {
+ {workspaces.data && ( + + )} {c.status === "invalid" && c.kind === "oauth" && !c.on_runners && ( )} @@ -945,6 +940,24 @@ function Claude({ me }: { me: G.Me }) { ); } +/** + * What kind of connection it is, first in its line of facts: its account where a name of yours goes + * before it, and its kind where its name isn't that. + */ +function connectionKind(c: G.ClaudeCredentialInfo): string { + const facts = c.on_runners + ? ["never given to fctl", "no Remote Control"] + : c.kind === "oauth" + ? ["Remote Control"] + : [c.provisioned && "set by your admins", "inference only", "no Remote Control"]; + // Without a name, the title is the kind, or the account a full login signed in with. + const head = namedConnection(c) + ? [c.label && c.account_email, kindName(c)] + : [c.on_runners ? "Kept on your runners" : c.kind === "oauth" ? "Full login" : undefined]; + const line = [...head, ...facts].filter((f): f is string => !!f).join(" · "); + return line.charAt(0).toUpperCase() + line.slice(1); +} + /** A long-lived token fctl keeps, which runs out a year after it was made: it has a date. */ const runsOut = (c: G.ClaudeCredentialInfo) => c.kind === "setup_token" && !c.on_runners && c.status === "active" && c.expires_at !== undefined;