diff --git a/Cargo.lock b/Cargo.lock index b9dca580..c2f6a82c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -394,7 +394,7 @@ dependencies = [ [[package]] name = "ccteam-cli" -version = "0.13.1" +version = "0.13.2" dependencies = [ "anyhow", "async-trait", @@ -427,7 +427,7 @@ dependencies = [ [[package]] name = "ccteam-core" -version = "0.13.1" +version = "0.13.2" dependencies = [ "anyhow", "async-trait", @@ -455,7 +455,7 @@ dependencies = [ [[package]] name = "ccteam-cost" -version = "0.13.1" +version = "0.13.2" dependencies = [ "chrono", "serde", @@ -468,7 +468,7 @@ dependencies = [ [[package]] name = "ccteam-flow" -version = "0.13.1" +version = "0.13.2" dependencies = [ "async-trait", "ccteam-harness", @@ -485,7 +485,7 @@ dependencies = [ [[package]] name = "ccteam-harness" -version = "0.13.1" +version = "0.13.2" dependencies = [ "anyhow", "async-trait", @@ -523,7 +523,7 @@ dependencies = [ [[package]] name = "ccteam-hooks" -version = "0.13.1" +version = "0.13.2" dependencies = [ "anyhow", "ccteam-core", @@ -538,7 +538,7 @@ dependencies = [ [[package]] name = "ccteam-im" -version = "0.13.1" +version = "0.13.2" dependencies = [ "anyhow", "async-trait", @@ -569,7 +569,7 @@ dependencies = [ [[package]] name = "ccteam-web" -version = "0.13.1" +version = "0.13.2" dependencies = [ "anyhow", "askama", diff --git a/Cargo.toml b/Cargo.toml index 5208e715..9cf4c00a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -18,7 +18,7 @@ members = [ ] [workspace.package] -version = "0.13.1" +version = "0.13.2" edition = "2021" rust-version = "1.85" license = "MIT" diff --git a/README.md b/README.md index 7610ccd4..d9cf2926 100644 --- a/README.md +++ b/README.md @@ -62,6 +62,7 @@ The installer runs the daemon; `ccteam status` reprints your link (`http:// - six formation playbooks (commander & crews, driver & advisor, cross review, bake-off, research triangulation, cost pyramid) that prefill the launcher with a vendor lineup +- optional Claude subscription selection through a preinstalled [cswap](https://github.com/realiti4/claude-swap): pick any local account — listed as `# ` with the 5h / 7d quota cswap reports — from the **Claude account** button beside the model selector; default login works without cswap, a session keeps its account across resumes, and the same button in a running session (IM: `/account`) shows its current account and switches it in place — the conversation continues on the new account through cswap's shared history - a chat per session with a compact title/model header and unified Files / Context toolbar, including a clock on the composer to queue delayed user turns above the input; a turn's folded activity row opens into its steps, and each step into its full thinking text or tool input and output - a context sidebar per session: session status, harness/model/host, delegation parent, cumulative cost and last activity, followed by the harness's own context accounting — detailed categories for Claude; window totals and last-request input/cache/output/reasoning usage for Codex — refreshed when a turn ends, with dated snapshots after release - a Team page: the live delegation topology — vendor, the model and reasoning effort each session is actually running, cost, every row a real link so a parent and its delegate open side by side — plus a division-of-labor charter (the per-project `routing.md` agents read via `status`) edited in place, and a Runs tab listing every ccteam Flow run with the sessions it hired diff --git a/crates/ccteam-cli/src/main.rs b/crates/ccteam-cli/src/main.rs index c8c69c17..ef3a294b 100644 --- a/crates/ccteam-cli/src/main.rs +++ b/crates/ccteam-cli/src/main.rs @@ -693,6 +693,16 @@ enum HookCommand { } fn main() -> Result<()> { + // cswap's PATH entry must remain a transparent stdio exec, including for + // auth probes. Intercept before clap, logging, runtime and global setup. + let relay_args: Vec = std::env::args_os().collect(); + if relay_args.get(1).is_some_and(|arg| arg == "internal") + && relay_args + .get(2) + .is_some_and(|arg| arg == "claude-account-launch") + { + return ccteam_harness::execution::claude_accounts::run_relay(&relay_args[3..]); + } // V0.8 W2a — rmux SDK daemon spawn protocol. BEFORE clap parses // argv, intercept the `--__internal-daemon ` form emitted // by `rmux_sdk::Rmux::connect_or_start` so the same ccteam binary diff --git a/crates/ccteam-cli/tests/cswap_accounts_test.rs b/crates/ccteam-cli/tests/cswap_accounts_test.rs new file mode 100644 index 00000000..e3b0962b --- /dev/null +++ b/crates/ccteam-cli/tests/cswap_accounts_test.rs @@ -0,0 +1,403 @@ +//! Real adapter + real ccteam relay, with deterministic offline vendor/CLI +//! peers. All environment mutation is in this isolated integration process. +#![cfg(unix)] + +use ccteam_harness::execution::claude_accounts::{account_id, ClaudeAccountBinding}; +use ccteam_harness::{ + AgentSpecBrief, ClaudeStreamJsonAdapter, HarnessAdapter, PermissionMode, SpawnCtx, ThreadEvent, + TurnInput, +}; +use futures::StreamExt; +use std::{os::unix::fs::PermissionsExt, path::Path, time::Duration}; + +const FAKE_CLAUDE: &str = r#"#!/usr/bin/python3 +import json, os, sys +from pathlib import Path +profile = Path(os.environ.get('CLAUDE_CONFIG_DIR', str(Path.home() / '.claude'))) +email = os.environ.get('CSWAP_FAKE_DEFAULT_EMAIL', 'two@example.test') if 'CLAUDE_CONFIG_DIR' not in os.environ else 'two@example.test' +if sys.argv[1:3] == ['auth', 'status']: + assert sys.stdin.read(1) == '', 'auth probe consumed stream-json input' + print(json.dumps({'loggedIn':True,'authMethod':'claude.ai','email':email,'orgId':''})) + sys.exit(0) +args = sys.argv[1:] +assert '--no-chrome' in args and '--input-format' in args +log = {'argv':args,'profile':str(profile),'pid':os.getpid(),'isatty':[sys.stdin.isatty(),sys.stdout.isatty(),sys.stderr.isatty()], 'api_key':os.environ.get('ANTHROPIC_API_KEY'), 'path':os.environ['PATH']} +Path(os.environ['CSWAP_FAKE_LOG']).write_text(json.dumps(log)) +def emit(obj): + print(json.dumps(obj), flush=True) +for line in sys.stdin: + request=json.loads(line) + if request['type']=='control_request': + emit({'type':'control_response','response':{'subtype':'success','request_id':request['request_id'],'response':{'commands':[],'models':[{'value':'fake-model'}]}}}) + elif request['type']=='user': + emit({'type':'assistant','message':{'id':'msg-test','role':'assistant','model':'fake-model','content':[{'type':'text','text':'account reply'}]}}) + emit({'type':'result','subtype':'success','is_error':False,'result':'account reply','usage':{'input_tokens':1,'output_tokens':1}}) +"#; + +const FAKE_CSWAP: &str = r#"#!/usr/bin/python3 +import json, os, shutil, subprocess, sys +from pathlib import Path +log=Path(os.environ['CSWAP_FAKE_CALLS']) +with log.open('a') as output: + output.write(json.dumps(sys.argv[1:])+'\n') +if sys.argv[1:]==['list','--json']: + print(json.dumps({'schemaVersion':1,'accounts':[{'number':2,'email':os.environ.get('CSWAP_FAKE_ACCOUNT_EMAIL','two@example.test'),'organizationUuid':'','alias':'work','active':os.environ.get('CSWAP_FAKE_ACTIVE')=='1'}]})) + sys.exit(0) +if sys.argv[1:]==['run','--help']: + print('--share-history --no-share-history --require-session') + sys.exit(0) +if sys.argv[1:]==['config','list','--json']: + print(json.dumps({'schemaVersion':1,'settings':[]})) + sys.exit(0) +assert sys.argv[1:3]==['run','2'] +assert '--share-history' in sys.argv and '--no-share-history' not in sys.argv +active=os.environ.get('CSWAP_FAKE_ACTIVE')=='1' +if active and '--require-session' in sys.argv: + sys.exit(4) +env=dict(os.environ) +if not active: + # Shared history links the profile's projects/ to ~/.claude/projects; + # a deferred share (profile busy) leaves the profile's own directory. + deferred=os.environ.get('CSWAP_FAKE_DEFER_SHARE')=='1' + profile=Path.home()/'cswap-profiles'/('two-private' if deferred else 'two') + profile.mkdir(parents=True,exist_ok=True) + shared=Path.home()/'.claude'/'projects' + shared.mkdir(parents=True,exist_ok=True) + projects=profile/'projects' + if deferred: + projects.mkdir(exist_ok=True) + elif not projects.is_symlink(): + projects.symlink_to(shared) + env['CLAUDE_CONFIG_DIR']=str(profile) + for key in ['ANTHROPIC_API_KEY','ANTHROPIC_AUTH_TOKEN','CLAUDE_CODE_OAUTH_TOKEN']: + env.pop(key,None) + subprocess.run([shutil.which('claude'),'auth','status','--json'],env=env,check=True,capture_output=True) +print('Launching account two@example.test', flush=True) +args=sys.argv[sys.argv.index('--')+1:] +os.execvpe('claude',['claude',*args],env) +"#; + +fn script(path: &Path, body: &str) { + std::fs::write(path, body).unwrap(); + std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o700)).unwrap(); +} + +fn ctx(root: &Path, sid: &str, binding: Option) -> SpawnCtx { + SpawnCtx { + claude_account: binding, + generation: 1, + slug: "probe".into(), + sid: sid.into(), + owner: "user:web-api".into(), + cwd: root.into(), + project_dir: root.into(), + extra_args: vec![], + model_id: None, + effort: None, + mode: None, + permission_mode: PermissionMode::Skip, + secret: String::new(), + remote: None, + } +} + +fn log(root: &Path) -> serde_json::Value { + serde_json::from_slice(&std::fs::read(root.join("argv.json")).unwrap()).unwrap() +} + +#[tokio::test] +async fn account_launches_preserve_protocol_profiles_and_default_optional_behavior() { + let real_cswap = std::env::var_os("CCTEAM_TEST_REAL_CSWAP_BIN"); + let real_claude = std::env::var_os("CCTEAM_TEST_REAL_CLAUDE_BIN"); + let tmp = tempfile::tempdir().unwrap(); + let root = tmp.path(); + let home = root.join("home"); + std::fs::create_dir_all(home.join(".claude")).unwrap(); + std::env::set_var("HOME", &home); + std::env::set_var("CCTEAM_HOME", home.join(".ccteam")); + std::env::set_var("CLAUDE_CONFIG_HOME", home.join(".claude")); + std::env::set_var("XDG_DATA_HOME", root.join("data")); + std::env::set_var("PATH", "/usr/bin:/bin"); + std::env::remove_var("CLAUDE_CONFIG_DIR"); + for key in [ + "ANTHROPIC_API_KEY", + "ANTHROPIC_AUTH_TOKEN", + "ANTHROPIC_BASE_URL", + "CLAUDE_CODE_USE_BEDROCK", + "CLAUDE_CODE_USE_VERTEX", + "CLAUDE_CODE_USE_FOUNDRY", + "CLAUDE_CODE_OAUTH_TOKEN", + ] { + std::env::remove_var(key); + } + std::env::set_var("CCTEAM_CSWAP_RELAY_BIN", env!("CARGO_BIN_EXE_ccteam")); + std::env::set_var("CCTEAM_STREAM_JSON_INIT_TIMEOUT_MS", "5000"); + std::env::set_var("CSWAP_FAKE_LOG", root.join("argv.json")); + std::env::set_var("CSWAP_FAKE_CALLS", root.join("cswap.jsonl")); + let claude = root.join("real-claude"); + let cswap = root.join("cswap"); + script(&claude, FAKE_CLAUDE); + script(&cswap, FAKE_CSWAP); + std::env::set_var("CCTEAM_CLAUDE_BIN", &claude); + std::env::set_var("CCTEAM_CSWAP_BIN", root.join("missing-cswap")); + let spec = AgentSpecBrief { + role: String::new(), + }; + + // No cswap is installed: the ordinary adapter still starts and resumes. + let adapter = ClaudeStreamJsonAdapter::new(); + let normal = adapter + .start_thread(&spec, &ctx(root, "s1", None)) + .await + .unwrap(); + assert!(!root.join("cswap.jsonl").exists()); + assert_eq!( + log(root)["profile"], + home.join(".claude").to_string_lossy().as_ref() + ); + adapter.close_thread(&normal).await.unwrap(); + + std::env::set_var("CCTEAM_CSWAP_BIN", &cswap); + std::env::set_var("ANTHROPIC_API_KEY", "sandbox-ambient-key-must-not-win"); + let requested = ClaudeAccountBinding::requested(account_id("two@example.test", "")).unwrap(); + let selected = adapter + .start_thread(&spec, &ctx(root, "s2", Some(requested.clone()))) + .await + .unwrap(); + let binding: ClaudeAccountBinding = + serde_json::from_value(selected.raw_extras["claude_account"].clone()).unwrap(); + assert!(!binding.default_login); + assert_eq!(binding.config_dir, Some(home.join("cswap-profiles/two"))); + assert_eq!( + log(root)["isatty"], + serde_json::json!([false, false, false]) + ); + assert!(log(root)["api_key"].is_null()); + assert_eq!(log(root)["path"], "/usr/bin:/bin"); + let body: serde_json::Value = + serde_json::from_slice(&std::fs::read(root.join(".ccteam/chat/s2/body.json")).unwrap()) + .unwrap(); + assert_eq!(log(root)["pid"], body["pid"]); + for _ in 0..2 { + let mut events = adapter.events(&selected); + adapter + .submit_turn(&selected, TurnInput::UserText("hello".into())) + .await + .unwrap(); + let completed = tokio::time::timeout(Duration::from_secs(3), async { + while let Some(event) = events.next().await { + if matches!(event, ThreadEvent::TurnCompleted { .. }) { + return true; + } + } + false + }) + .await + .unwrap(); + assert!( + completed, + "each request must complete on the same stream-json process" + ); + assert!(adapter.thread_is_live(&selected)); + } + adapter.close_thread(&selected).await.unwrap(); + + let transcript = ccteam_harness::execution::transcript_tail::anthropic_project_dir_in( + &binding.config_dir.as_ref().unwrap().join("projects"), + root, + ) + .join(format!("{}.jsonl", selected.identity)); + std::fs::create_dir_all(transcript.parent().unwrap()).unwrap(); + std::fs::write(&transcript, "{}\n").unwrap(); + let resumed = adapter + .start_thread(&spec, &ctx(root, "s2", Some(binding.clone()))) + .await + .unwrap(); + assert!(log(root)["argv"] + .as_array() + .unwrap() + .iter() + .any(|arg| arg == "--resume")); + assert_eq!( + log(root)["profile"], + binding + .config_dir + .as_ref() + .unwrap() + .to_string_lossy() + .as_ref() + ); + adapter.close_thread(&resumed).await.unwrap(); + + // #236 — cswap's shared history makes the sid portable across accounts: + // the same transcript resumes on the default login and back on slot 2. + let resumed_with = |root: &Path| { + log(root)["argv"] + .as_array() + .unwrap() + .windows(2) + .any(|pair| pair[0] == "--resume" && pair[1] == selected.identity.as_str()) + }; + let on_default = adapter + .start_thread(&spec, &ctx(root, "s2", None)) + .await + .unwrap(); + assert_eq!( + log(root)["profile"], + home.join(".claude").to_string_lossy().as_ref() + ); + assert!( + resumed_with(root), + "default login resumes the shared transcript" + ); + adapter.close_thread(&on_default).await.unwrap(); + let back = adapter + .start_thread(&spec, &ctx(root, "s2", Some(requested.clone()))) + .await + .unwrap(); + assert_eq!( + log(root)["profile"], + home.join("cswap-profiles/two").to_string_lossy().as_ref() + ); + assert!( + resumed_with(root), + "the account resumes the same transcript" + ); + adapter.close_thread(&back).await.unwrap(); + + // History cswap has not shared into the target profile yet must never + // start the conversation over: the launch fails before Claude runs. + std::env::set_var("CSWAP_FAKE_DEFER_SHARE", "1"); + let before = log(root); + let refused = adapter + .start_thread(&spec, &ctx(root, "s2", Some(requested.clone()))) + .await; + let reason = refused.expect_err("a hidden transcript must not start fresh"); + assert!( + reason + .to_string() + .contains("not visible in the selected account"), + "the refusal names its reason: {reason}" + ); + assert_eq!(log(root), before, "no Claude process may start fresh"); + std::env::remove_var("CSWAP_FAKE_DEFER_SHARE"); + + // A movable slot is not an account identity. Replacing slot 2 fails closed. + std::env::set_var("CSWAP_FAKE_ACCOUNT_EMAIL", "replacement@example.test"); + assert!(adapter + .start_thread(&spec, &ctx(root, "s2", Some(binding.clone()))) + .await + .is_err()); + std::env::remove_var("CSWAP_FAKE_ACCOUNT_EMAIL"); + + // An already isolated sid cannot move into the default profile on resume. + std::env::set_var("CSWAP_FAKE_ACTIVE", "1"); + assert!(adapter + .start_thread(&spec, &ctx(root, "s2", Some(binding))) + .await + .is_err()); + assert!(transcript.exists()); + + // A NEW selection may fall back to the active/default login (owner choice). + let fallback = adapter + .start_thread(&spec, &ctx(root, "s3", Some(requested.clone()))) + .await + .unwrap(); + let default_binding: ClaudeAccountBinding = + serde_json::from_value(fallback.raw_extras["claude_account"].clone()).unwrap(); + assert!(default_binding.default_login); + assert_eq!(default_binding.config_dir, Some(home.join(".claude"))); + assert!(log(root)["api_key"].is_null()); + adapter.close_thread(&fallback).await.unwrap(); + + // Auto has changed the default identity and cswap has been uninstalled: + // the fallback sid must still resume in the original default profile. + std::env::set_var("CSWAP_FAKE_DEFAULT_EMAIL", "auto-switched@example.test"); + std::env::set_var("CCTEAM_CSWAP_BIN", root.join("missing-cswap")); + let followed = adapter + .start_thread(&spec, &ctx(root, "s3", Some(default_binding))) + .await + .unwrap(); + assert_eq!( + log(root)["profile"], + home.join(".claude").to_string_lossy().as_ref() + ); + adapter.close_thread(&followed).await.unwrap(); + assert!(adapter + .start_thread(&spec, &ctx(root, "s4", Some(requested))) + .await + .is_err()); + + // Optional compatibility probe: a fresh sandbox store with a fake token; + // no real account or credentials are read or copied. + if let Some(real_cswap) = real_cswap { + std::env::remove_var("CSWAP_FAKE_ACTIVE"); + std::env::remove_var("ANTHROPIC_API_KEY"); + let guard = root.join("netguard"); + std::fs::create_dir_all(&guard).unwrap(); + std::fs::write(guard.join("sitecustomize.py"), "import socket\ndef deny(*args, **kwargs):\n raise RuntimeError('network disabled for isolated cswap probe')\nsocket.socket.connect=deny\nsocket.create_connection=deny\n").unwrap(); + std::env::set_var("PYTHONPATH", &guard); + let result = std::process::Command::new(&real_cswap) + .args([ + "add-token", + "sk-ant-oat01-SANDBOX-NOT-REAL", + "--email", + "two@example.test", + "--slot", + "2", + ]) + .output() + .unwrap(); + assert!( + result.status.success(), + "sandbox setup failed: {}", + String::from_utf8_lossy(&result.stderr) + ); + std::env::set_var("CCTEAM_CSWAP_BIN", real_cswap); + let selection = + ClaudeAccountBinding::requested(account_id("two@example.test", "")).unwrap(); + let real_launcher = adapter + .start_thread(&spec, &ctx(root, "s5", Some(selection.clone()))) + .await + .unwrap(); + assert_eq!( + real_launcher.raw_extras["claude_account"]["default_login"], + false + ); + assert_eq!( + log(root)["isatty"], + serde_json::json!([false, false, false]) + ); + adapter.close_thread(&real_launcher).await.unwrap(); + if let Some(real_claude) = real_claude { + // Real binaries, initialize only: no user turn or model inference. + std::env::set_var("CCTEAM_CLAUDE_BIN", real_claude); + std::env::set_var("CCTEAM_STREAM_JSON_INIT_TIMEOUT_MS", "30000"); + std::env::set_var("CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC", "1"); + std::env::set_var("DISABLE_TELEMETRY", "1"); + let real = adapter + .start_thread(&spec, &ctx(root, "s6", Some(selection))) + .await + .unwrap(); + assert!(adapter.thread_is_live(&real)); + assert_eq!(real.raw_extras["claude_account"]["default_login"], false); + let profile = std::path::PathBuf::from( + real.raw_extras["claude_account"]["config_dir"] + .as_str() + .unwrap(), + ); + let body: serde_json::Value = serde_json::from_slice( + &std::fs::read(root.join(".ccteam/chat/s6/body.json")).unwrap(), + ) + .unwrap(); + let pid = body["pid"].as_u64().unwrap(); + let pid_record = profile.join("sessions").join(format!("{pid}.json")); + eprintln!("real cswap + Claude stream-json initialize passed; native session PID record exists: {}", pid_record.exists()); + assert!( + pid_record.exists(), + "cswap must be able to discover and protect the headless Claude process" + ); + adapter.close_thread(&real).await.unwrap(); + } + } +} diff --git a/crates/ccteam-cli/tests/status_view_test.rs b/crates/ccteam-cli/tests/status_view_test.rs index 2e15550d..a96b7f4a 100644 --- a/crates/ccteam-cli/tests/status_view_test.rs +++ b/crates/ccteam-cli/tests/status_view_test.rs @@ -78,6 +78,7 @@ fn ephemeral_home(slug: &str) -> (tempfile::TempDir, PathBuf, PathBuf, String) { mode: ccteam_harness::PermissionMode| { let now = "2026-01-01T00:00:00Z".to_string(); let meta = ccteam_harness::SessionMeta { + claude_account: None, model_pinned_generation: None, mode: None, tool_face: None, diff --git a/crates/ccteam-core/tests/claude_bg_rmux_adapter_test.rs b/crates/ccteam-core/tests/claude_bg_rmux_adapter_test.rs index 2b2e8c22..4e489555 100644 --- a/crates/ccteam-core/tests/claude_bg_rmux_adapter_test.rs +++ b/crates/ccteam-core/tests/claude_bg_rmux_adapter_test.rs @@ -107,6 +107,7 @@ async fn via_mux_bg_spawn_routes_through_rmux_daemon() { role: "tester".into(), }; let ctx = SpawnCtx { + claude_account: None, generation: 0, mode: None, slug: "rmuxbg".into(), diff --git a/crates/ccteam-core/tests/codex_app_server_progress_bridge_test.rs b/crates/ccteam-core/tests/codex_app_server_progress_bridge_test.rs index 3882689c..9c20baf7 100644 --- a/crates/ccteam-core/tests/codex_app_server_progress_bridge_test.rs +++ b/crates/ccteam-core/tests/codex_app_server_progress_bridge_test.rs @@ -269,6 +269,7 @@ async fn end_to_end_turn_completed_writes_progress_jsonl_with_vendor_codex() { role: "codex-bot".into(), }; let ctx = SpawnCtx { + claude_account: None, generation: 0, mode: None, slug: "demo-codex".into(), diff --git a/crates/ccteam-core/tests/harness_trait_test.rs b/crates/ccteam-core/tests/harness_trait_test.rs index 3d04d889..400d1529 100644 --- a/crates/ccteam-core/tests/harness_trait_test.rs +++ b/crates/ccteam-core/tests/harness_trait_test.rs @@ -121,6 +121,7 @@ async fn claude_bg_start_thread_parses_backgrounded_marker() { role: "tester".into(), }; let ctx = SpawnCtx { + claude_account: None, generation: 0, mode: None, slug: "demo".into(), @@ -158,6 +159,7 @@ async fn claude_bg_start_thread_rejects_empty_role() { role: String::new(), }; let ctx = SpawnCtx { + claude_account: None, generation: 0, mode: None, slug: "demo".into(), @@ -281,6 +283,7 @@ async fn claude_bg_via_mux_spawns_ephemeral_session_and_close_reaps_it() { role: "tester".into(), }; let ctx = SpawnCtx { + claude_account: None, generation: 0, mode: None, slug: "muxbg".into(), @@ -468,6 +471,7 @@ mod codex_tmux { role: String::new(), }; let ctx = SpawnCtx { + claude_account: None, generation: 0, slug: "codextest".into(), sid: "codex-1".into(), diff --git a/crates/ccteam-harness/src/adapter.rs b/crates/ccteam-harness/src/adapter.rs index c834b73c..003a5b19 100644 --- a/crates/ccteam-harness/src/adapter.rs +++ b/crates/ccteam-harness/src/adapter.rs @@ -415,6 +415,9 @@ pub enum DetachOutcome { /// finished a turn (or several) while no daemon was reading it. #[derive(Debug, Clone)] pub struct UnobservedTurnCtx { + /// Explicit profile binding from the session ledger; never infer it from + /// an ambient home or a possibly unreadable metadata file during reads. + pub claude_account: Option, pub sid: String, pub slug: String, /// The session's working directory (the vendor transcript lives keyed by @@ -1164,6 +1167,8 @@ pub enum DirectiveOutcome { /// `thread/name/set`) answers [`TitleSync::Deferred`] when `thread` is `None`. #[derive(Debug, Clone)] pub struct SessionTitleTarget { + /// The session's ledger-owned profile, including stopped sessions. + pub claude_account: Option, /// ccteam session id (`s{n}`). pub sid: String, /// The vendor's own session id as recorded in `meta.json` (Claude session @@ -1563,6 +1568,25 @@ pub struct AccountUsage { pub model_windows: Vec, } +impl AccountUsage { + /// Whether this says anything about HEADROOM — at least one rate-limit + /// window (5-hour, weekly, credits, or a per-model bucket). The tier alone + /// is a label for a window, never a fact on its own. + /// + /// The one "is this an observation" rule: the adapter parse, the cache + /// recorder and the cache reader all answer with it, so an answer that + /// says nothing can neither be shown as a row nor overwrite one that did. + /// Which windows exist is the account's own business (a plan with no + /// 5-hour window still has a weekly one), so no particular window is + /// required. + pub fn has_window(&self) -> bool { + self.five_hour_pct.is_some() + || self.weekly_pct.is_some() + || self.credits_pct.is_some() + || !self.model_windows.is_empty() + } +} + /// One model's own weekly rate-limit window, as the vendor meters it. /// /// `model` is the vendor's own bucket name (claude: `opus` / `sonnet` — the @@ -1838,6 +1862,9 @@ pub struct ThreadErrorEvent { /// per-model cost accuracy). #[derive(Debug, Clone, Default)] pub struct SpawnCtx { + /// Optional Claude subscription binding. Only local stream-json supports + /// cswap; default spawns never probe or invoke it (issue #229). + pub claude_account: Option, pub slug: String, pub sid: String, /// Which THREAD of this sid is starting. A sid outlives any one thread — diff --git a/crates/ccteam-harness/src/execution/acp/mod.rs b/crates/ccteam-harness/src/execution/acp/mod.rs index 87583558..071e7597 100644 --- a/crates/ccteam-harness/src/execution/acp/mod.rs +++ b/crates/ccteam-harness/src/execution/acp/mod.rs @@ -14,9 +14,9 @@ pub mod turn_runner; pub use context_probe::{AcpContextProbe, KIMI_STATUS_PROBE}; pub use protocol::{ acp_model_picker_options, content_text, cost_from_usage_update, is_replay, is_turn_boundary, - known_efforts, pluck_model_info, pluck_session_id, split_trailing_effort, - stop_reason_from_prompt_result, usage_from_prompt_result, AcpModelOption, AcpStopReason, - AvailableCommand, ModelInfo, + known_efforts, pluck_model_info, pluck_session_id, record_fresh_default_model, + split_trailing_effort, stop_reason_from_prompt_result, usage_from_prompt_result, + AcpModelOption, AcpStopReason, AvailableCommand, ModelInfo, }; pub use translate::{ apply_notification, apply_notification_shared, fail_turn, finalize_from_prompt_result, diff --git a/crates/ccteam-harness/src/execution/acp/protocol.rs b/crates/ccteam-harness/src/execution/acp/protocol.rs index 1e9a36cc..361ee2cf 100644 --- a/crates/ccteam-harness/src/execution/acp/protocol.rs +++ b/crates/ccteam-harness/src/execution/acp/protocol.rs @@ -327,6 +327,19 @@ fn effort_config_entry(opts: &[Value]) -> Option<&Value> { }) } +/// A fresh `session/new` that ccteam asked for no model reports the vendor's +/// own default — record it so the picker's default row can name the id. +/// Resumed sessions and explicit picks never count. +pub fn record_fresh_default_model(vendor: &str, requested_model: Option<&str>, info: &ModelInfo) { + if requested_model + .map(str::trim) + .is_some_and(|m| !m.is_empty()) + { + return; + } + crate::model_catalog::record_vendor_default_model_best_effort(vendor, info.model.as_deref()); +} + /// Pull model info from a `session/new` / `session/load` / `session/resume` /// result — or from a `config_option_update` payload, which carries the same /// `configOptions[]` snapshot. diff --git a/crates/ccteam-harness/src/execution/claude_accounts.rs b/crates/ccteam-harness/src/execution/claude_accounts.rs new file mode 100644 index 00000000..ea38e716 --- /dev/null +++ b/crates/ccteam-harness/src/execution/claude_accounts.rs @@ -0,0 +1,913 @@ +//! Optional cswap launcher integration. Claude/cswap own credentials; this +//! module handles only account references, argv, and profile metadata (#229). + +use std::{ + collections::BTreeMap, + ffi::OsString, + path::{Path, PathBuf}, + time::Duration, +}; + +use anyhow::{bail, Context, Result}; +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; + +use super::{fs_atomic::atomic_write_durable, transcript_tail::anthropic_project_dir_in}; + +const RELAY_ENV: &str = "CCTEAM_CSWAP_LAUNCH"; +const REAL_BIN_ENV: &str = "CCTEAM_CSWAP_CLAUDE"; +const ORIGINAL_PATH_ENV: &str = "CCTEAM_CSWAP_PATH"; +const MAX_DISCOVERY_BYTES: usize = 1024 * 1024; + +/// Safe to return to any authenticated frontend. No credentials or profile paths. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct CswapAccount { + pub id: String, + pub slot: String, + /// cswap alias, else the email's local part. The domain never leaves + /// the daemon (owner 2026-11-08: number + name + quota only). + pub label: String, + pub active: bool, + /// Rolling 5-hour window, whole percent. Absent for plans without one + /// (Max) and whenever cswap has no reading. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub five_hour_pct: Option, + /// Weekly window, whole percent. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub seven_day_pct: Option, + /// cswap's `usageStatus` when it is not `ok` (e.g. `relogin_required`). + /// With percentages present they are cswap's last good reading. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub usage_status: Option, +} + +/// Private session metadata. `config_dir` is the literal path exported by +/// cswap (its spelling also selects the macOS Keychain service). +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct ClaudeAccountBinding { + pub id: String, + #[serde(default)] + pub slot: String, + #[serde(default)] + pub label: String, + #[serde(default)] + pub config_dir: Option, + #[serde(default)] + pub directory_identity: Option, + #[serde(default)] + pub default_login: bool, +} + +impl ClaudeAccountBinding { + pub fn requested(id: String) -> Result { + if id.len() != 64 || !id.bytes().all(|b| b.is_ascii_hexdigit()) { + bail!("invalid cswap account reference; choose an account from the account list"); + } + Ok(Self { + id, + slot: String::new(), + label: String::new(), + config_dir: None, + directory_identity: None, + default_login: false, + }) + } + + pub fn display(&self) -> CswapAccount { + CswapAccount { + id: self.id.clone(), + slot: self.slot.clone(), + label: self.label.clone(), + active: self.default_login, + five_hour_pct: None, + seven_day_pct: None, + usage_status: None, + } + } +} + +/// Whether a sid's Claude transcript stays readable after the session moves +/// to another account (#236). cswap's shared history links every profile's +/// `projects/` to `~/.claude/projects`; a transcript that exists only in one +/// account's private profile (written before sharing, or while cswap +/// deferred merging it) would be invisible elsewhere, and resuming there +/// would start the conversation over. +pub fn history_follows_switch(cwd: &Path, uuid: &str, from: Option<&ClaudeAccountBinding>) -> bool { + dirs::home_dir().is_some_and(|home| { + history_follows_switch_in(&home.join(".claude").join("projects"), cwd, uuid, from) + }) +} + +/// [`history_follows_switch`] against an explicit shared projects root. +pub fn history_follows_switch_in( + shared_projects: &Path, + cwd: &Path, + uuid: &str, + from: Option<&ClaudeAccountBinding>, +) -> bool { + let file = format!("{uuid}.jsonl"); + if anthropic_project_dir_in(shared_projects, cwd) + .join(&file) + .exists() + { + return true; + } + // Not shared: only safe when the current profile holds no history either. + from.and_then(|binding| binding.config_dir.as_ref()) + .is_none_or(|dir| { + !anthropic_project_dir_in(&dir.join("projects"), cwd) + .join(&file) + .exists() + }) +} + +/// `# ` — how an account reads on every surface (no email domain). +pub fn display_name(account: &CswapAccount) -> String { + format!("#{} {}", account.slot, account.label) +} + +pub fn account_id(email: &str, organization: &str) -> String { + let identity = serde_json::to_vec(&(email, organization)).expect("string pair serializes"); + format!("{:x}", Sha256::digest(identity)) +} + +pub fn parse_accounts(bytes: &[u8]) -> Result> { + if bytes.len() > MAX_DISCOVERY_BYTES { + bail!("cswap account list is too large"); + } + let value: serde_json::Value = + serde_json::from_slice(bytes).context("cswap did not return a JSON account list")?; + if value["schemaVersion"].as_u64() != Some(1) { + bail!("unsupported cswap account-list schema"); + } + let rows = value["accounts"] + .as_array() + .context("cswap account list is missing accounts")?; + let mut accounts = BTreeMap::new(); + for row in rows { + // API-key accounts have no subscription quota and run does not support them. + if row["usageStatus"].as_str() == Some("api_key") { + continue; + } + let email = row["email"] + .as_str() + .filter(|s| !s.is_empty()) + .context("cswap account has no identity")?; + let org = row["organizationUuid"].as_str().unwrap_or(""); + let slot = row["number"] + .as_u64() + .filter(|n| *n > 0) + .context("cswap account has no slot")? + .to_string(); + let label = row["alias"] + .as_str() + .map(str::trim) + .filter(|s| !s.is_empty()) + .unwrap_or_else(|| email.split_once('@').map_or(email, |(name, _)| name)) + .to_string(); + // Live reading first; cswap keeps the last good one when a fetch fails. + let usage = Some(&row["usage"]) + .filter(|u| u.is_object()) + .or_else(|| Some(&row["lastGoodUsage"]).filter(|u| u.is_object())); + let pct = |window: &str| { + usage + .and_then(|u| u[window]["pct"].as_f64()) + .filter(|p| p.is_finite()) + .map(|p| p.clamp(0.0, 999.0).round() as u16) + }; + let usage_status = row["usageStatus"] + .as_str() + .filter(|status| *status != "ok") + .map(str::to_string); + let id = account_id(email, org); + if accounts + .insert( + id.clone(), + CswapAccount { + id, + slot, + label, + active: row["active"].as_bool().unwrap_or(false), + five_hour_pct: pct("fiveHour"), + seven_day_pct: pct("sevenDay"), + usage_status, + }, + ) + .is_some() + { + bail!("cswap contains duplicate account identities; repair its account list first"); + } + } + let mut accounts: Vec<_> = accounts.into_values().collect(); + accounts.sort_by_key(|account| account.slot.parse::().unwrap_or(u64::MAX)); + Ok(accounts) +} + +pub fn cswap_bin() -> OsString { + std::env::var_os("CCTEAM_CSWAP_BIN").unwrap_or_else(|| "cswap".into()) +} + +/// Called only by optional discovery or an explicitly selected account. Never +/// part of daemon readiness or a normal/default Claude spawn. +pub async fn discover_accounts() -> Result> { + let help = cswap_output(&["run", "--help"], Duration::from_secs(5)).await?; + let help = String::from_utf8_lossy(&help); + if !help.contains("--share-history") || !help.contains("--require-session") { + bail!("this cswap version lacks shared-history or session options; upgrade cswap or use default login"); + } + // Newer cswap versions optionally infer setup-token quota using a tiny + // model request. Discovery must not create inference outside a session. + verify_cswap_settings( + &cswap_output(&["config", "list", "--json"], Duration::from_secs(5)).await?, + )?; + parse_accounts(&cswap_output(&["list", "--json"], Duration::from_secs(20)).await?) +} + +fn verify_cswap_settings(bytes: &[u8]) -> Result<()> { + let value: serde_json::Value = + serde_json::from_slice(bytes).context("cswap settings discovery returned invalid JSON")?; + if value["schemaVersion"].as_u64() != Some(1) { + bail!("unsupported cswap settings schema"); + } + let settings = value["settings"] + .as_array() + .context("cswap settings discovery has no settings")?; + for setting in settings { + if setting["key"].as_str() == Some("usage.headerProbe") + && setting["value"].as_bool() != Some(false) + { + bail!("disable cswap usage.headerProbe before account discovery: ccteam does not run quota inference probes"); + } + } + Ok(()) +} + +async fn cswap_output(args: &[&str], timeout: Duration) -> Result> { + let mut command = tokio::process::Command::new(cswap_bin()); + command + .args(args) + .env_remove("CLAUDE_CONFIG_DIR") + .kill_on_drop(true); + let output = tokio::time::timeout(timeout, command.output()) + .await + .context("cswap account discovery timed out; default login remains available")? + .context("cswap is not installed or cannot run; install cswap to select an account")?; + if !output.status.success() { + bail!("cswap account discovery failed; check cswap list in the daemon user's environment"); + } + Ok(output.stdout) +} + +/// Resolve what a person typed (`2`, `#2`, an alias / name, or a stable id) +/// to one listed account (#236, IM `/account`). A name matching several +/// accounts resolves to none: the slot number is the unambiguous handle. +pub fn find_account<'a>(accounts: &'a [CswapAccount], reference: &str) -> Option<&'a CswapAccount> { + let reference = reference.trim(); + let slot = reference.strip_prefix('#').unwrap_or(reference); + if let Some(account) = accounts + .iter() + .find(|account| account.slot == slot || account.id == reference) + { + return Some(account); + } + let mut named = accounts + .iter() + .filter(|account| account.label.eq_ignore_ascii_case(reference)); + match (named.next(), named.next()) { + (Some(account), None) => Some(account), + _ => None, + } +} + +/// Discovery is explicit and isolated from readiness/status. Coalesce open +/// picker requests and briefly cache failures as well as successful results. +/// One instance serves both web and IM (the daemon hands the gateway's to +/// the web state), so they share one cache. +#[derive(Default)] +pub struct CswapAccountService { + cache: tokio::sync::Mutex>, + /// Test seam: answer with these accounts instead of running cswap. + fixed: Option>, +} + +struct CachedAccounts { + captured: std::time::Instant, + result: std::result::Result, String>, +} + +impl CswapAccountService { + /// A service that lists `accounts` without running cswap (tests). + pub fn fixed(accounts: Vec) -> Self { + Self { + cache: Default::default(), + fixed: Some(accounts), + } + } + + pub async fn accounts(&self) -> Result> { + if let Some(accounts) = &self.fixed { + return Ok(accounts.clone()); + } + let mut cache = self.cache.lock().await; + if let Some(cached) = &*cache { + let ttl = if cached.result.is_ok() { 30 } else { 5 }; + if cached.captured.elapsed() < Duration::from_secs(ttl) { + return cached.result.clone().map_err(anyhow::Error::msg); + } + } + let result = discover_accounts() + .await + .map_err(|error| format!("{error:#}")); + *cache = Some(CachedAccounts { + captured: std::time::Instant::now(), + result: result.clone(), + }); + result.map_err(anyhow::Error::msg) + } +} + +/// The relay performs the final profile check and fresh/resume decision just +/// before exec. This avoids a second preparatory run and a credential race. +#[derive(Debug, Serialize, Deserialize)] +struct LaunchRequest { + binding: ClaudeAccountBinding, + uuid: String, + cwd: PathBuf, +} + +pub struct CswapLaunch { + pub argv: Vec, + pub env: Vec<(String, String)>, + directory: PathBuf, +} + +impl Drop for CswapLaunch { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.directory); + } +} + +impl CswapLaunch { + pub async fn prepare( + binding: &ClaudeAccountBinding, + argv: &[String], + env: &[(String, String)], + cwd: &Path, + chat_dir: &Path, + uuid: &str, + ) -> Result { + #[cfg(not(unix))] + bail!("cswap accounts currently require Linux, WSL or macOS"); + let mut binding = binding.clone(); + if !binding.default_login { + let account = discover_accounts() + .await? + .into_iter() + .find(|a| a.id == binding.id) + .context( + "selected cswap account no longer exists; choose an account for a new session", + )?; + binding.slot = account.slot; + binding.label = account.label; + } + let mut nonce = [0u8; 16]; + getrandom::getrandom(&mut nonce) + .map_err(|error| anyhow::anyhow!("cswap launch nonce: {error}"))?; + let nonce = format!("{:x}", Sha256::digest(nonce)); + let directory = chat_dir.join(format!("cswap-launch-{nonce}")); + let bin_dir = directory.join("bin"); + std::fs::create_dir_all(&bin_dir)?; + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(&directory, std::fs::Permissions::from_mode(0o700))?; + } + let mut launch = Self { + argv: Vec::new(), + env: env.to_vec(), + directory, + }; + let request = LaunchRequest { + binding: binding.clone(), + uuid: uuid.to_string(), + cwd: cwd.to_path_buf(), + }; + atomic_write_durable( + &launch.directory.join("request.json"), + &serde_json::to_vec(&request)?, + )?; + let relay = std::env::var_os("CCTEAM_CSWAP_RELAY_BIN") + .map(PathBuf::from) + .map(Ok) + .unwrap_or_else(std::env::current_exe)?; + let quoted = relay.to_string_lossy().replace('\'', "'\\''"); + let script = format!("#!/bin/sh\nexec '{quoted}' internal claude-account-launch \"$@\"\n"); + let entry = bin_dir.join("claude"); + std::fs::write(&entry, script)?; + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(&entry, std::fs::Permissions::from_mode(0o700))?; + } + let original_path = std::env::var_os("PATH").unwrap_or_default(); + let mut paths = vec![bin_dir]; + paths.extend(std::env::split_paths(&original_path)); + launch.env.extend([ + ( + "PATH".into(), + std::env::join_paths(paths)?.to_string_lossy().into_owned(), + ), + ( + ORIGINAL_PATH_ENV.into(), + original_path.to_string_lossy().into_owned(), + ), + ( + REAL_BIN_ENV.into(), + argv.first().context("missing Claude binary")?.clone(), + ), + ( + RELAY_ENV.into(), + launch.directory.to_string_lossy().into_owned(), + ), + ]); + // A prior default fallback stays a default-profile session that follows + // cswap auto; re-running its old slot would quietly pin it instead. + if binding.default_login { + launch.argv = vec![entry.to_string_lossy().into_owned()]; + } else { + // cswap's shared history (its default since 1.0) links every + // profile's `projects/` to `~/.claude/projects`, so a sid's + // transcript is readable from any account and the session can + // switch accounts by sid (#236). Credentials stay per profile. + // Explicit, so a user-wide `run.shareHistory false` cannot strand + // a switched session's history in one account. + launch.argv = vec![ + cswap_bin().to_string_lossy().into_owned(), + "run".into(), + binding.slot, + "--share-history".into(), + ]; + if binding.config_dir.is_some() { + launch.argv.push("--require-session".into()); + } + launch.argv.push("--".into()); + } + launch.argv.extend_from_slice(&argv[1..]); + Ok(launch) + } + + /// Why the relay refused this launch, if it did. + pub fn failure(&self) -> Option { + std::fs::read_to_string(self.directory.join(FAILURE_FILE)) + .ok() + .map(|reason| reason.trim().to_string()) + .filter(|reason| !reason.is_empty()) + } + + pub fn binding(&self) -> Result { + serde_json::from_slice(&std::fs::read(self.directory.join("binding.json"))?) + .context("cswap launch did not confirm its profile") + } +} + +/// Hidden CLI entry: do not initialize daemon state or consume stdin. cswap +/// may call `claude auth status` before it execs the actual stream-json child. +pub fn run_relay(args: &[OsString]) -> Result<()> { + let directory = + PathBuf::from(std::env::var_os(RELAY_ENV).context("cswap relay is not configured")?); + let result = relay(&directory, args); + // The daemon discards a launch's stderr (Claude's debug stream), so a + // refusal leaves its reason where the launch can read it back and say + // why the session did not start. Reasons never carry credentials. + if let Err(error) = &result { + let _ = std::fs::write(directory.join(FAILURE_FILE), format!("{error:#}")); + } + result +} + +const FAILURE_FILE: &str = "failure.txt"; + +fn relay(directory: &Path, args: &[OsString]) -> Result<()> { + let request: LaunchRequest = + serde_json::from_slice(&std::fs::read(directory.join("request.json"))?)?; + let real_bin = std::env::var_os(REAL_BIN_ENV).context("cswap relay has no Claude binary")?; + let mut command = std::process::Command::new(&real_bin); + command.env( + "PATH", + std::env::var_os(ORIGINAL_PATH_ENV).unwrap_or_default(), + ); + command + .env_remove(RELAY_ENV) + .env_remove(REAL_BIN_ENV) + .env_remove(ORIGINAL_PATH_ENV); + let is_stream_json = args.iter().any(|arg| arg == "--input-format"); + if !is_stream_json { + // The SDK initialize request can already be queued in inherited + // stdin while cswap probes auth. Probes must never consume it. + command.stdin(std::process::Stdio::null()); + return exec(command, args); + } + let config_dir = std::env::var_os("CLAUDE_CONFIG_DIR") + .map(PathBuf::from) + .or_else(|| dirs::home_dir().map(|home| home.join(".claude"))) + .context("Claude profile cannot be resolved")?; + let default_login = std::env::var_os("CLAUDE_CONFIG_DIR").is_none(); + verify_subscription_settings(&config_dir, &request.cwd)?; + let mut binding = request.binding; + #[cfg(unix)] + let directory_identity = { + use std::os::unix::fs::MetadataExt; + let metadata = + std::fs::metadata(&config_dir).context("selected Claude profile is unavailable")?; + format!("{}:{}", metadata.dev(), metadata.ino()) + }; + #[cfg(not(unix))] + let directory_identity = config_dir.canonicalize()?.to_string_lossy().into_owned(); + if binding + .config_dir + .as_ref() + .is_some_and(|expected| expected != &config_dir) + || (binding.config_dir.is_some() && binding.default_login != default_login) + { + bail!("cswap profile changed; this session cannot resume in another profile"); + } + if binding + .directory_identity + .as_ref() + .is_some_and(|expected| expected != &directory_identity) + { + bail!("cswap profile directory was replaced; refusing to resume in another profile"); + } + // A selected subscription must not be hijacked by ambient API credentials, + // including cswap's default-account fast path which retains the full env. + for key in [ + "ANTHROPIC_API_KEY", + "ANTHROPIC_AUTH_TOKEN", + "CLAUDE_CODE_OAUTH_TOKEN", + "CLAUDE_CODE_OAUTH_TOKEN_FILE_DESCRIPTOR", + "CLAUDE_CODE_API_KEY_FILE_DESCRIPTOR", + ] { + command.env_remove(key); + } + for key in [ + "ANTHROPIC_BASE_URL", + "CLAUDE_CODE_USE_BEDROCK", + "CLAUDE_CODE_USE_VERTEX", + "CLAUDE_CODE_USE_FOUNDRY", + ] { + if std::env::var_os(key) + .is_some_and(|value| override_is_active(key, &value.to_string_lossy())) + { + bail!("selected cswap subscription conflicts with {key}; remove the provider override first"); + } + } + let mut probe = std::process::Command::new(&real_bin); + probe.args(["auth", "status", "--json"]).env( + "PATH", + std::env::var_os(ORIGINAL_PATH_ENV).unwrap_or_default(), + ); + for (key, value) in command.get_envs() { + if let Some(value) = value { + probe.env(key, value); + } else { + probe.env_remove(key); + } + } + let status = bounded_auth_probe(probe)?; + let identity: serde_json::Value = serde_json::from_slice(&status.stdout) + .context("Claude auth status returned invalid JSON")?; + if !status.status.success() + || identity["loggedIn"].as_bool() != Some(true) + || identity["authMethod"].as_str() != Some("claude.ai") + { + bail!("selected Claude profile is not logged into a subscription; use cswap to repair the login"); + } + if !binding.default_login { + let email = identity["email"] + .as_str() + .context("Claude auth status has no account identity")?; + let org = identity["orgId"].as_str().unwrap_or(""); + if account_id(email, org) != binding.id { + bail!("cswap account identity changed; refusing to use another account"); + } + } + binding.config_dir = Some(config_dir.clone()); + binding.directory_identity = Some(directory_identity); + binding.default_login = default_login; + let transcript = anthropic_project_dir_in(&config_dir.join("projects"), &request.cwd) + .join(format!("{}.jsonl", request.uuid)); + let mut args = args.to_vec(); + let flag = args + .iter() + .position(|arg| arg == "--session-id" || arg == "--resume") + .context("cswap relay has no session UUID argument")?; + let has_transcript = transcript.exists(); + // The daemon asks for `--resume` only when it saw this sid's transcript. + // Not finding it in the profile cswap prepared (history sharing deferred + // while another Claude still used that profile's own history) must not + // silently start the conversation over (#236). + if args[flag] == "--resume" && !has_transcript { + bail!( + "this conversation's history is not visible in the selected account's profile yet \ + (cswap shares history once no other Claude uses that profile); the session and \ + its history were kept, retry later or switch back" + ); + } + args[flag] = if has_transcript { + "--resume" + } else { + "--session-id" + } + .into(); + atomic_write_durable( + &directory.join("binding.json"), + &serde_json::to_vec(&binding)?, + )?; + exec(command, &args) +} + +fn verify_subscription_settings(config_dir: &Path, cwd: &Path) -> Result<()> { + for path in [ + config_dir.join("settings.json"), + cwd.join(".claude/settings.json"), + cwd.join(".claude/settings.local.json"), + ] { + let body = match std::fs::read(&path) { + Ok(body) => body, + Err(error) if error.kind() == std::io::ErrorKind::NotFound => continue, + Err(_) => bail!("could not verify Claude settings for the selected subscription"), + }; + let settings: serde_json::Value = serde_json::from_slice(&body) + .context("selected subscription has invalid Claude settings")?; + if settings + .get("apiKeyHelper") + .is_some_and(|value| !value.is_null() && value.as_str() != Some("")) + { + bail!( + "selected subscription conflicts with apiKeyHelper; remove the auth helper first" + ); + } + if let Some(env) = settings["env"].as_object() { + for key in [ + "ANTHROPIC_API_KEY", + "ANTHROPIC_AUTH_TOKEN", + "ANTHROPIC_BASE_URL", + "CLAUDE_CODE_OAUTH_TOKEN", + "CLAUDE_CODE_OAUTH_TOKEN_FILE_DESCRIPTOR", + "CLAUDE_CODE_API_KEY_FILE_DESCRIPTOR", + "CLAUDE_CODE_USE_BEDROCK", + "CLAUDE_CODE_USE_VERTEX", + "CLAUDE_CODE_USE_FOUNDRY", + ] { + if env.get(key).is_some_and(|value| match value { + serde_json::Value::Null => false, + serde_json::Value::String(value) => override_is_active(key, value), + serde_json::Value::Bool(false) => !is_cloud_switch(key), + _ => true, + }) { + bail!("selected subscription conflicts with {key} in Claude settings"); + } + } + } + } + Ok(()) +} + +fn is_cloud_switch(key: &str) -> bool { + matches!( + key, + "CLAUDE_CODE_USE_BEDROCK" | "CLAUDE_CODE_USE_VERTEX" | "CLAUDE_CODE_USE_FOUNDRY" + ) +} + +fn override_is_active(key: &str, value: &str) -> bool { + // "0" disables a boolean cloud switch, but is a real stdin descriptor + // for FD authentication; an arbitrary URL/key is never a boolean flag. + !value.is_empty() && (!is_cloud_switch(key) || !matches!(value, "0" | "false")) +} + +fn bounded_auth_probe(mut command: std::process::Command) -> Result { + use std::io::Read; + command + .stdin(std::process::Stdio::null()) + .stdout(std::process::Stdio::piped()) + .stderr(std::process::Stdio::null()); + let mut child = command + .spawn() + .context("could not verify selected Claude login")?; + let deadline = std::time::Instant::now() + Duration::from_secs(10); + let status = loop { + if let Some(status) = child.try_wait()? { + break status; + } + if std::time::Instant::now() >= deadline { + let _ = child.kill(); + let _ = child.wait(); + bail!("Claude auth status timed out; the profile and its history were kept"); + } + std::thread::sleep(Duration::from_millis(10)); + }; + let mut stdout = Vec::new(); + child + .stdout + .take() + .context("missing auth status output")? + .take(64 * 1024) + .read_to_end(&mut stdout)?; + Ok(std::process::Output { + status, + stdout, + stderr: Vec::new(), + }) +} + +fn exec(mut command: std::process::Command, args: &[OsString]) -> Result<()> { + command.args(args); + #[cfg(unix)] + { + use std::os::unix::process::CommandExt; + Err(command.exec()).context("could not execute Claude") + } + #[cfg(not(unix))] + { + let status = command.status()?; + std::process::exit(status.code().unwrap_or(1)); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn account_references_are_identity_based_and_labels_drop_the_domain() { + let body = br#"{"schemaVersion":1,"accounts":[{"number":2,"email":"alice@example.test","organizationUuid":"org","alias":"work","active":false}]}"#; + let account = parse_accounts(body).unwrap().pop().unwrap(); + assert_eq!(account.id, account_id("alice@example.test", "org")); + assert_eq!(account.label, "work"); + assert!(!serde_json::to_string(&account) + .unwrap() + .contains("example.test")); + let unaliased = String::from_utf8(body.to_vec()) + .unwrap() + .replace(",\"alias\":\"work\"", ""); + assert_eq!( + parse_accounts(unaliased.as_bytes()).unwrap()[0].label, + "alice" + ); + let moved = String::from_utf8(body.to_vec()) + .unwrap() + .replace("\"number\":2", "\"number\":7"); + assert_eq!(parse_accounts(moved.as_bytes()).unwrap()[0].id, account.id); + assert_ne!(account.id, account_id("alice@example.test", "another-org")); + } + + #[test] + fn quota_windows_follow_the_plan_and_rows_sort_by_slot() { + let body = br#"{"schemaVersion":1,"accounts":[ + {"number":10,"email":"stale@x","usageStatus":"unavailable","usage":null,"lastGoodUsage":{"fiveHour":{"pct":40.4},"sevenDay":{"pct":60}}}, + {"number":5,"email":"sddenter@x","usageStatus":"ok","usage":{"sevenDay":{"pct":100.0}}}, + {"number":1,"email":"cloud@x","usageStatus":"ok","usage":{"fiveHour":{"pct":10.6},"sevenDay":{"pct":100}}}, + {"number":6,"email":"gone@x","usageStatus":"relogin_required","usage":null} + ]}"#; + let accounts = parse_accounts(body).unwrap(); + let slots: Vec<_> = accounts.iter().map(|a| a.slot.as_str()).collect(); + assert_eq!( + slots, + ["1", "5", "6", "10"], + "numeric slot order, not id order" + ); + let cloud = &accounts[0]; + assert_eq!( + (cloud.five_hour_pct, cloud.seven_day_pct), + (Some(11), Some(100)) + ); + assert_eq!(cloud.usage_status, None); + let max = &accounts[1]; + assert_eq!(max.label, "sddenter"); + assert_eq!( + (max.five_hour_pct, max.seven_day_pct), + (None, Some(100)), + "a plan without a 5h window reports only the weekly one" + ); + let gone = &accounts[2]; + assert_eq!((gone.five_hour_pct, gone.seven_day_pct), (None, None)); + assert_eq!(gone.usage_status.as_deref(), Some("relogin_required")); + let stale = &accounts[3]; + assert_eq!( + (stale.five_hour_pct, stale.seven_day_pct), + (Some(40), Some(60)) + ); + assert_eq!(stale.usage_status.as_deref(), Some("unavailable")); + let wire = serde_json::to_value(max).unwrap(); + assert!(wire.get("five_hour_pct").is_none()); + } + + #[test] + fn discovery_fails_closed_on_unknown_shapes_or_duplicate_identities() { + for body in [ + r#"{"schemaVersion":2,"accounts":[]}"#, + r#"{"schemaVersion":1}"#, + r#"{"schemaVersion":1,"accounts":[{"number":1,"email":"a@b"},{"number":2,"email":"a@b"}]}"#, + ] { + assert!(parse_accounts(body.as_bytes()).is_err()); + } + assert!(ClaudeAccountBinding::requested("2".into()).is_err()); + } + + #[test] + fn subscription_settings_cannot_override_authentication() { + let tmp = tempfile::tempdir().unwrap(); + let profile = tmp.path().join("profile"); + let project = tmp.path().join("project"); + std::fs::create_dir_all(&profile).unwrap(); + std::fs::create_dir_all(project.join(".claude")).unwrap(); + assert!(verify_subscription_settings(&profile, &project).is_ok()); + for body in [ + r#"{"apiKeyHelper":"return-a-key"}"#, + r#"{"env":{"ANTHROPIC_API_KEY":"must-not-win"}}"#, + r#"{"env":{"CLAUDE_CODE_USE_VERTEX":"1"}}"#, + r#"{"env":{"CLAUDE_CODE_OAUTH_TOKEN_FILE_DESCRIPTOR":"0"}}"#, + r#"{"env":{"ANTHROPIC_BASE_URL":"false"}}"#, + ] { + std::fs::write(profile.join("settings.json"), body).unwrap(); + assert!(verify_subscription_settings(&profile, &project).is_err()); + } + std::fs::write( + profile.join("settings.json"), + r#"{"env":{"CLAUDE_CODE_USE_VERTEX":"0"},"theme":"dark"}"#, + ) + .unwrap(); + assert!(verify_subscription_settings(&profile, &project).is_ok()); + } + + #[test] + fn typed_account_references_resolve_by_slot_name_or_id() { + let account = |slot: &str, label: &str| CswapAccount { + id: account_id(&format!("{label}@x"), ""), + slot: slot.into(), + label: label.into(), + active: false, + five_hour_pct: None, + seven_day_pct: None, + usage_status: None, + }; + let accounts = [ + account("1", "cloud"), + account("2", "Work"), + account("3", "work"), + ]; + assert_eq!(find_account(&accounts, "2").unwrap().slot, "2"); + assert_eq!(find_account(&accounts, " #1 ").unwrap().slot, "1"); + assert_eq!(find_account(&accounts, "CLOUD").unwrap().slot, "1"); + assert_eq!(find_account(&accounts, &accounts[2].id).unwrap().slot, "3"); + assert!( + find_account(&accounts, "work").is_none(), + "an ambiguous name picks nothing" + ); + assert!(find_account(&accounts, "9").is_none()); + } + + #[test] + fn history_follows_a_switch_only_from_shared_history() { + let tmp = tempfile::tempdir().unwrap(); + let cwd = tmp.path().join("project"); + let shared = tmp.path().join("home/.claude/projects"); + let private = tmp.path().join("cswap/sessions/3-a"); + let uuid = "11111111-2222-3333-4444-555555555555"; + let mut bound = ClaudeAccountBinding::requested("a".repeat(64)).unwrap(); + bound.config_dir = Some(private.clone()); + let write = |root: &Path| { + let dir = anthropic_project_dir_in(root, &cwd); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write(dir.join(format!("{uuid}.jsonl")), "{}\n").unwrap(); + }; + // No transcript anywhere yet: nothing to lose. + assert!(history_follows_switch_in(&shared, &cwd, uuid, Some(&bound))); + assert!(history_follows_switch_in(&shared, &cwd, uuid, None)); + // Only in the private profile: another account would start over. + write(&private.join("projects")); + assert!(!history_follows_switch_in( + &shared, + &cwd, + uuid, + Some(&bound) + )); + // Once cswap shares it, every account reads the same transcript. + write(&shared); + assert!(history_follows_switch_in(&shared, &cwd, uuid, Some(&bound))); + } + + #[test] + fn discovery_never_enables_vendor_quota_inference() { + assert!(verify_cswap_settings(br#"{"schemaVersion":1,"settings":[]}"#).is_ok()); + assert!(verify_cswap_settings( + br#"{"schemaVersion":1,"settings":[{"key":"usage.headerProbe","value":false}]}"# + ) + .is_ok()); + assert!(verify_cswap_settings( + br#"{"schemaVersion":1,"settings":[{"key":"usage.headerProbe","value":true}]}"# + ) + .is_err()); + } +} diff --git a/crates/ccteam-harness/src/execution/claude_stream_json/mod.rs b/crates/ccteam-harness/src/execution/claude_stream_json/mod.rs index 1d786e48..115da7d1 100644 --- a/crates/ccteam-harness/src/execution/claude_stream_json/mod.rs +++ b/crates/ccteam-harness/src/execution/claude_stream_json/mod.rs @@ -48,12 +48,15 @@ use futures::stream::BoxStream; use serde_json::json; use tokio::sync::{broadcast, mpsc}; +use crate::execution::claude_accounts::CswapLaunch; use crate::execution::claude_common; use crate::execution::progress_bridge::{ append_event, build_chat_session_reset_event_with_reason, progress_jsonl_from_env, }; use crate::execution::session_status::{read_status_file, write_context_file, write_status_file}; -use crate::execution::transcript_tail::anthropic_project_dir; +use crate::execution::transcript_tail::{ + anthropic_bound_project_dir, anthropic_project_dir, anthropic_project_dir_in, +}; use crate::{ AgentSpecBrief, AgentVendor, ChoiceOption, ChoicePrompt, DetachOutcome, DetachedActivity, Directive, DirectiveOutcome, ExecutionMode, HarnessAdapter, HarnessError, RecoveredTurn, @@ -417,6 +420,9 @@ fn spawn_status_tap( cells: StatusTapCells, project_dir: PathBuf, sid: String, + // Spawned with no model at all (no pick, no role `model:`): the first + // API-reported model is claude's own default for the picker's default row. + mut record_default_model: bool, ) -> tokio::task::JoinHandle<()> { let StatusTapCells { status, @@ -488,6 +494,14 @@ fn spawn_status_tap( if let Ok(mut s) = status.lock() { s.model = Some(preserve_1m_tag(s.model.as_deref(), m)); } + // First observation only: a later `/model` switch + // is the user's pick, not the default. + if std::mem::take(&mut record_default_model) { + crate::model_catalog::record_vendor_default_model_best_effort( + "claude", + Some(m), + ); + } } // v0.8.20 — ALSO refresh the live context window mid-turn // (throttled) so `/sessions` reflects a long working turn's @@ -1209,9 +1223,24 @@ async fn get_context_breakdown(transport: &StreamJsonTransport) -> Option Option { let body = transport - .request_control("get_usage", json!({}), Duration::from_secs(3)) + .request_control( + "get_usage", + json!({ "skip_behaviors": true }), + Duration::from_secs(3), + ) .await .ok()?; if body.subtype != "success" { @@ -1261,11 +1290,15 @@ fn parse_get_usage_response(resp: &serde_json::Value) -> Option Result<(Arc, protocol::SystemMsg), HarnessError> { match transport - .request_control("initialize", json!({}), init_timeout()) + .request_control("initialize", json!({}), timeout) .await { Ok(body) if body.subtype == "success" => Ok(( @@ -1881,7 +1922,22 @@ impl HarnessAdapter for ClaudeStreamJsonAdapter { // a local resume failure — same contract, just optimistic instead // of fs-checked (tech-design §4.4: satellite `--resume` is how a // remote rebuild continues context, PRD F3.4). - let resume = ctx.remote.is_some() || Self::session_jsonl_exists(&ctx.cwd, &uuid); + if ctx.claude_account.is_some() && ctx.remote.is_some() { + return Err(HarnessError::SpawnFailed( + "cswap accounts are not supported on remote projects".into(), + )); + } + let resume = ctx.remote.is_some() + || ctx + .claude_account + .as_ref() + .and_then(|account| account.config_dir.as_ref()) + .map(|dir| { + anthropic_project_dir_in(&dir.join("projects"), &ctx.cwd) + .join(format!("{uuid}.jsonl")) + .exists() + }) + .unwrap_or_else(|| Self::session_jsonl_exists(&ctx.cwd, &uuid)); // v0.8.24 C1 / v0.9.0 W3 — curated per-session MCP. `--mcp-config` // is a RELATIVE path (`.ccteam/chat//mcp.json`, cwd = project @@ -1930,6 +1986,7 @@ impl HarnessAdapter for ClaudeStreamJsonAdapter { // `ccteam-exec.v1` WS bridge — tech-design §0.4: execution location // is a transport parameter); everything after this `match` is // identical for both. + let mut effective_account = ctx.claude_account.clone(); let (transport, init) = if let Some(remote) = ctx.remote.as_ref() { let build_spec = |resume: bool| { Self::build_exec_spec(ctx, make_argv(resume), &env, ship_mcp, &mcp_relpath) @@ -1960,6 +2017,21 @@ impl HarnessAdapter for ClaudeStreamJsonAdapter { } } else { let body = Some((ctx.project_dir.as_path(), ctx.sid.as_str())); + let launch = match ctx.claude_account.as_ref() { + Some(account) => Some( + CswapLaunch::prepare( + account, + &make_argv(resume), + &env, + &ctx.cwd, + &crate::execution::turns_mirror::chat_dir(&ctx.project_dir, &ctx.sid), + &uuid, + ) + .await + .map_err(|error| HarnessError::SpawnFailed(format!("cswap: {error:#}")))?, + ), + None => None, + }; // `resume` here means the transcript `.jsonl` is on disk, and // claude refuses `--session-id ` for an existing transcript // ("Session ID … is already in use", exit 1): a fresh fallback on @@ -1967,9 +2039,17 @@ impl HarnessAdapter for ClaudeStreamJsonAdapter { // resume into a second, misleading failure. Surface the resume // failure itself. Nothing sticks: the transcript is untouched and // the next message tries `--resume` again (docs-local issue #211). - Self::spawn_and_init(&make_argv(resume), &env, &ctx.cwd, body) + let result = Self::spawn_and_init( + &launch.as_ref().map(|launch| launch.argv.clone()).unwrap_or_else(|| make_argv(resume)), + launch.as_ref().map(|launch| launch.env.as_slice()).unwrap_or(&env), &ctx.cwd, body) .await .map_err(|err| { + // A relay refusal (profile/identity drift, history not + // visible yet, auth override) is the real reason. + let err = match launch.as_ref().and_then(CswapLaunch::failure) { + Some(reason) => HarnessError::SpawnFailed(format!("cswap: {reason}")), + None => err, + }; if !resume { return err; } @@ -1983,7 +2063,19 @@ impl HarnessAdapter for ClaudeStreamJsonAdapter { "claude --resume {uuid} failed: {err}. The conversation is intact on \ disk; the next resume retries it" )) - })? + })?; + if let Some(launch) = launch { + match launch.binding() { + Ok(binding) => effective_account = Some(binding), + Err(error) => { + let _ = result.0.shutdown().await; + return Err(HarnessError::SpawnFailed(format!( + "cswap profile confirmation failed: {error:#}" + ))); + } + } + } + result }; let identity = SessionIdentity { @@ -2056,6 +2148,9 @@ impl HarnessAdapter for ClaudeStreamJsonAdapter { }, ctx.project_dir.clone(), ctx.sid.clone(), + ctx.model_id + .as_deref() + .is_none_or(|model| model.trim().is_empty()), )); // HITL: only a hitl session (`--permission-prompt-tool stdio`) ever // receives `can_use_tool` reverse RPCs. Spawn the dispatcher that @@ -2173,6 +2268,7 @@ impl HarnessAdapter for ClaudeStreamJsonAdapter { "role": spec.role, "project_dir": ctx.project_dir.to_string_lossy(), "cwd": ctx.cwd.to_string_lossy(), + "claude_account": effective_account, }), }) } @@ -2549,7 +2645,8 @@ impl HarnessAdapter for ClaudeStreamJsonAdapter { if ctx.vendor_uuid.is_empty() { return None; } - let path = anthropic_project_dir(&ctx.cwd)?.join(format!("{}.jsonl", ctx.vendor_uuid)); + let path = anthropic_bound_project_dir(&ctx.cwd, ctx.claude_account.as_ref())? + .join(format!("{}.jsonl", ctx.vendor_uuid)); let observed_until = ctx.observed_until; let last = ctx.last_observed_assistant.clone(); tokio::task::spawn_blocking(move || { @@ -2564,7 +2661,8 @@ impl HarnessAdapter for ClaudeStreamJsonAdapter { if ctx.vendor_uuid.is_empty() { return None; } - let path = anthropic_project_dir(&ctx.cwd)?.join(format!("{}.jsonl", ctx.vendor_uuid)); + let path = anthropic_bound_project_dir(&ctx.cwd, ctx.claude_account.as_ref())? + .join(format!("{}.jsonl", ctx.vendor_uuid)); tokio::task::spawn_blocking(move || recovery::activity(&path, std::time::SystemTime::now())) .await .ok() @@ -2853,9 +2951,17 @@ impl HarnessAdapter for ClaudeStreamJsonAdapter { // it belongs. if let Some(cwd) = h.raw_extras.get("cwd").and_then(|v| v.as_str()) { let (cwd, uuid) = (PathBuf::from(cwd), h.identity.clone()); - let gating = tokio::task::spawn_blocking(move || turn_gating::read(&cwd, &uuid)) - .await - .unwrap_or(None); + let config_dir = h + .raw_extras + .get("claude_account") + .and_then(|value| value.get("config_dir")) + .and_then(|value| value.as_str()) + .map(PathBuf::from); + let gating = tokio::task::spawn_blocking(move || { + turn_gating::read(&cwd, &uuid, config_dir.as_deref()) + }) + .await + .unwrap_or(None); status.goal = gating.as_ref().and_then(|gating| gating.goal.clone()); status.stop_hook_blocks = gating.map(|gating| gating.stop_hook_blocks); } @@ -3249,8 +3355,89 @@ mod deferred_queue_tests { #[cfg(test)] mod account_usage_tests { - use super::parse_get_usage_response; + use super::{get_account_usage, parse_get_usage_response, StreamJsonTransport}; use serde_json::json; + use std::time::Duration; + use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader}; + + /// The 2026-11-06 freeze. Without `skip_behaviors`, claude first scans the + /// account's local transcript history to build usage recommendations — + /// ~3.9s on a well-used host, past the 3s deadline — so every live read + /// AND every release-time capture came back `None` and the IM row showed + /// a days-old snapshot of a since-replaced account. The peer here answers + /// the way that claude did for an ask WITHOUT the flag (only after the + /// deadline), so leaving the flag out fails this test. + #[tokio::test] + async fn get_usage_skips_the_slow_behaviors_scan() { + let (client, mut peer) = tokio::io::duplex(64 * 1024); + let (client_read, client_write) = tokio::io::split(client); + let transport = StreamJsonTransport::spawn_from_io(client_read, client_write, None); + tokio::spawn(async move { + let (peer_read, mut peer_write) = tokio::io::split(&mut peer); + let mut line = String::new(); + BufReader::new(peer_read) + .read_line(&mut line) + .await + .unwrap(); + let request: serde_json::Value = serde_json::from_str(line.trim()).unwrap(); + assert_eq!(request["request"]["subtype"], "get_usage"); + if request["request"]["skip_behaviors"] != json!(true) { + tokio::time::sleep(Duration::from_secs(5)).await; + } + let reply = json!({ + "type": "control_response", + "response": { + "subtype": "success", + "request_id": request["request_id"], + "response": { + "subscription_type": "team", + "rate_limits": { + "five_hour": {"utilization": 34, "resets_at": "2026-11-06T13:50:00Z"}, + "seven_day": {"utilization": 35, "resets_at": "2026-11-10T13:00:00Z"} + } + } + } + }); + peer_write + .write_all(format!("{reply}\n").as_bytes()) + .await + .unwrap(); + peer_write.flush().await.unwrap(); + tokio::time::sleep(Duration::from_millis(200)).await; + }); + + let usage = tokio::time::timeout(Duration::from_secs(10), get_account_usage(&transport)) + .await + .expect("the ask is bounded by its own deadline") + .expect("answered inside the deadline"); + assert_eq!(usage.subscription.as_deref(), Some("team")); + assert_eq!(usage.five_hour_pct, Some(34)); + assert_eq!(usage.weekly_pct, Some(35)); + } + + /// A plan with NO 5-hour window (live shape, claude 2.1.318: `five_hour` + /// is `null`) is a complete observation: the weekly window and the tier, + /// and no 5-hour figure from anywhere. + #[test] + fn a_plan_without_a_five_hour_window_reports_only_its_weekly_one() { + let usage = parse_get_usage_response(&json!({ + "subscription_type": "max", + "rate_limits_available": true, + "rate_limits": { + "five_hour": null, + "seven_day": {"utilization": 20, "resets_at": "2026-11-09T18:59:59Z"}, + "limits": [ + {"kind": "weekly_all", "group": "weekly", "percent": 20, "severity": "normal"} + ] + } + })) + .expect("a weekly window alone is an observation"); + assert_eq!(usage.five_hour_pct, None); + assert_eq!(usage.five_hour_resets_at, None); + assert_eq!(usage.weekly_pct, Some(20)); + assert_eq!(usage.weekly_severity.as_deref(), Some("normal")); + assert_eq!(usage.subscription.as_deref(), Some("max")); + } /// The `get_usage` response for a Max account whose server DOES send the /// declared per-model array. Key set pinned against a live claude 2.1.245. @@ -3370,6 +3557,15 @@ mod account_usage_tests { fn refuses_to_invent_rows_from_an_empty_answer() { assert!(parse_get_usage_response(&json!({})).is_none()); assert!(parse_get_usage_response(&json!({"rate_limits": {}})).is_none()); + // The tier with no windows (claude could not reach its usage endpoint) + // says nothing about headroom: not an observation either, so it can + // never overwrite the last one that did. + assert!(parse_get_usage_response(&json!({ + "subscription_type": "team", + "rate_limits_available": false, + "rate_limits": null + })) + .is_none()); assert!(parse_get_usage_response(&json!({ "rate_limits": {"seven_day_opus": {}, "model_scoped": [{"utilization": 5.0}]} })) diff --git a/crates/ccteam-harness/src/execution/claude_stream_json/transport.rs b/crates/ccteam-harness/src/execution/claude_stream_json/transport.rs index 4747e672..2922e16a 100644 --- a/crates/ccteam-harness/src/execution/claude_stream_json/transport.rs +++ b/crates/ccteam-harness/src/execution/claude_stream_json/transport.rs @@ -115,6 +115,11 @@ impl StreamJsonTransport { .stdin(std::process::Stdio::piped()) .stdout(std::process::Stdio::piped()) .stderr(std::process::Stdio::piped()); + // Only account launches clear inherited profile selection. Normal + // Claude starts preserve the daemon user's existing environment. + if env.iter().any(|(key, _)| key == "CCTEAM_CSWAP_LAUNCH") { + cmd.env_remove("CLAUDE_CONFIG_DIR"); + } // The body leads its own process group, so ending it (a user stop, or // a detached body a queued turn is waiting on) can end the background // processes it started too — `session_body::terminate` signals the @@ -402,7 +407,7 @@ async fn run_reader( let parsed: Outbound = match serde_json::from_str(trimmed) { Ok(v) => v, Err(err) => { - tracing::warn!(error = %err, line = %trimmed, "stream-json: parse failure"); + tracing::warn!(error = %err, "stream-json: discarded non-protocol output"); continue; } }; diff --git a/crates/ccteam-harness/src/execution/claude_stream_json/turn_gating.rs b/crates/ccteam-harness/src/execution/claude_stream_json/turn_gating.rs index 4c10b595..a6e6c067 100644 --- a/crates/ccteam-harness/src/execution/claude_stream_json/turn_gating.rs +++ b/crates/ccteam-harness/src/execution/claude_stream_json/turn_gating.rs @@ -15,7 +15,7 @@ use std::path::Path; use std::sync::LazyLock; use crate::execution::journal::{FoldCache, LineFold}; -use crate::execution::transcript_tail::anthropic_project_dir; +use crate::execution::transcript_tail::{anthropic_project_dir, anthropic_project_dir_in}; /// The session's current `/goal` + recent Stop-hook refusals. Read together /// because they are one answer: a goal whose condition is not met yet is @@ -155,8 +155,12 @@ impl GatingScan { /// met}}` record on the user turn. `None` when the transcript is absent or /// unreadable, which is what makes "cannot tell" distinguishable from /// "nothing refused". -pub(super) fn read(cwd: &Path, uuid: &str) -> Option { - let path = anthropic_project_dir(cwd)?.join(format!("{uuid}.jsonl")); +pub(super) fn read(cwd: &Path, uuid: &str, config_dir: Option<&Path>) -> Option { + let directory = match config_dir { + Some(dir) => anthropic_project_dir_in(&dir.join("projects"), cwd), + None => anthropic_project_dir(cwd)?, + }; + let path = directory.join(format!("{uuid}.jsonl")); read_path(&path, chrono::Utc::now()) } diff --git a/crates/ccteam-harness/src/execution/codex_app_server.rs b/crates/ccteam-harness/src/execution/codex_app_server.rs index c840babf..0f4dda71 100644 --- a/crates/ccteam-harness/src/execution/codex_app_server.rs +++ b/crates/ccteam-harness/src/execution/codex_app_server.rs @@ -776,10 +776,17 @@ impl CodexAppServerAdapter { } // Account-scoped rate-limit snapshot (no thread_id) — // cache the latest so `account_usage()` reports THIS - // vendor's own 5h/weekly windows. + // vendor's own 5h/weekly windows. Codex pushes one + // snapshot per metered bucket (`limitId` `codex`, + // `premium` …) and a bucket the plan does not meter + // arrives with every window null; such a snapshot says + // nothing about headroom, so it must not displace one + // that did (it blanked the `/status` row). if notif.method == "account/rateLimits/updated" { if let Some(snap) = - pluck_val(¬if.params, "rate_limits", "rateLimits") + pluck_val(¬if.params, "rate_limits", "rateLimits").filter( + |snap| account_usage_from_codex_snapshot(snap).is_some(), + ) { *rate_limits.lock().await = Some(snap); } @@ -1865,19 +1872,31 @@ impl CodexAppServerAdapter { } /// Map a codex `account/rateLimits/updated` snapshot (the inner `rateLimits` -/// object) → the vendor-neutral [`crate::AccountUsage`]. Codex's `primary` -/// window is the 5-hour limit and `secondary` the weekly (per the codex -/// protocol `windowDurationMins` 300 / 10080), mirroring Claude's two windows. +/// object) → the vendor-neutral [`crate::AccountUsage`]. +/// +/// Each window is placed by its OWN declared length (`windowDurationMins`, +/// snake `window_minutes`), never by its position: `primary` is merely codex's +/// first-listed window. On a plan with a 5-hour limit it is that 300-minute +/// window with the weekly 10080 in `secondary`; on a plan WITHOUT one, the +/// weekly window is `primary` and `secondary` is null (observed live, +/// 2026-11-06) — read positionally, a 89%-used WEEK rendered as `5h 89%`. +/// A window shorter than a day fills the short (5h) slot, a day or longer the +/// weekly one; only a window that declares no length falls back to its +/// position (primary = short, secondary = weekly). +/// /// `resetsAt` is an absolute Unix epoch (seconds) → ISO-8601 for the renderer; /// `planType` → subscription tier; a non-null `rateLimitReachedType` ⇒ weekly /// ⚠. `credits_pct` stays `None` — codex's `credits` is a balance object, not a /// utilization %, so the `/status` line correctly omits 额度 for codex. -/// All-`None` ⇒ `None`. +/// No window ⇒ `None` ([`crate::AccountUsage::has_window`]). fn account_usage_from_codex_snapshot(snapshot: &Value) -> Option { // dual-key (camelCase wire / snake_case) numeric lookup within a window. + // Integer or float: the app-server wire sends `usedPercent: 89`, codex's + // core protocol `used_percent: 89.0` — an integer-only read dropped the + // latter as "no window". let win_i64 = |w: Option<&Value>, snake: &str, camel: &str| -> Option { w.and_then(|x| x.get(camel).or_else(|| x.get(snake))) - .and_then(|v| v.as_i64()) + .and_then(|v| v.as_i64().or_else(|| v.as_f64().map(|f| f.round() as i64))) }; let pct = |w: Option<&Value>| { win_i64(w, "used_percent", "usedPercent").map(|n| n.clamp(0, 100) as u8) @@ -1887,8 +1906,25 @@ fn account_usage_from_codex_snapshot(snapshot: &Value) -> Option::from_timestamp(secs, 0)) .map(|dt| dt.to_rfc3339()) }; - let primary = snapshot.get("primary"); - let secondary = snapshot.get("secondary"); + const DAY_MINS: i64 = 24 * 60; + // `Some(true)` = a short (sub-day) window, `Some(false)` = day-or-longer, + // `None` = no declared length (position decides). + let is_short = |w: &Value| { + win_i64(Some(w), "window_minutes", "windowDurationMins").map(|mins| mins < DAY_MINS) + }; + let present = |key: &str| snapshot.get(key).filter(|w| w.is_object()); + let (mut short, mut weekly) = (None, None); + for (window, positional_short) in [(present("primary"), true), (present("secondary"), false)] { + let Some(window) = window else { continue }; + let slot = if is_short(window).unwrap_or(positional_short) { + &mut short + } else { + &mut weekly + }; + // First window of a length wins; a second of the same length is not + // folded into it. + slot.get_or_insert(window); + } let weekly_severity = snapshot .get("rate_limit_reached_type") .or_else(|| snapshot.get("rateLimitReachedType")) @@ -1901,21 +1937,17 @@ fn account_usage_from_codex_snapshot(snapshot: &Value) -> Option Option, + requested_model: Option<&str>, ) -> Result<(String, ModelInfo), HarnessError> { let _init = transport .call( @@ -257,7 +258,9 @@ impl GrokAcpAdapter { let session_id = pluck_session_id(&new_result).ok_or_else(|| { HarnessError::SpawnFailed("grok session/new missing sessionId".into()) })?; - Ok((session_id, pluck_model_info(&new_result))) + let info = pluck_model_info(&new_result); + crate::execution::acp::record_fresh_default_model("grok", requested_model, &info); + Ok((session_id, info)) } async fn handshake_and_load( @@ -754,8 +757,13 @@ impl HarnessAdapter for GrokAcpAdapter { HarnessError::SpawnFailed(format!("spawn grok after load fail: {e}")) })?; let transport = Arc::new(transport); - let (sid, info) = - Self::handshake_and_new(&transport, &cwd, mcp_servers.clone()).await?; + let (sid, info) = Self::handshake_and_new( + &transport, + &cwd, + mcp_servers.clone(), + ctx.model_id.as_deref(), + ) + .await?; (transport, sid, info) } } @@ -774,8 +782,13 @@ impl HarnessAdapter for GrokAcpAdapter { .await .map_err(|e| HarnessError::SpawnFailed(format!("spawn grok agent stdio: {e}")))?; let transport = Arc::new(transport); - let (sid, info) = - Self::handshake_and_new(&transport, &cwd, mcp_servers.clone()).await?; + let (sid, info) = Self::handshake_and_new( + &transport, + &cwd, + mcp_servers.clone(), + ctx.model_id.as_deref(), + ) + .await?; (transport, sid, info) } }; diff --git a/crates/ccteam-harness/src/execution/kimi_acp/mod.rs b/crates/ccteam-harness/src/execution/kimi_acp/mod.rs index aff23277..26676520 100644 --- a/crates/ccteam-harness/src/execution/kimi_acp/mod.rs +++ b/crates/ccteam-harness/src/execution/kimi_acp/mod.rs @@ -210,6 +210,7 @@ impl KimiAcpAdapter { transport: &AcpTransport, cwd: &std::path::Path, mcp_servers: Vec, + requested_model: Option<&str>, ) -> Result<(String, ModelInfo), HarnessError> { Self::handshake_initialize(transport).await?; let new_result = transport @@ -226,7 +227,9 @@ impl KimiAcpAdapter { let session_id = pluck_session_id(&new_result).ok_or_else(|| { HarnessError::SpawnFailed("kimi session/new missing sessionId".into()) })?; - Ok((session_id, pluck_model_info(&new_result))) + let info = pluck_model_info(&new_result); + crate::execution::acp::record_fresh_default_model("kimi", requested_model, &info); + Ok((session_id, info)) } /// Prefer `session/resume` (no history replay). Fall back to @@ -610,8 +613,13 @@ impl HarnessAdapter for KimiAcpAdapter { HarnessError::SpawnFailed(format!("spawn kimi after resume fail: {e}")) })?; let transport = Arc::new(transport); - let (sid, info) = - Self::handshake_and_new(&transport, &cwd, mcp_servers.clone()).await?; + let (sid, info) = Self::handshake_and_new( + &transport, + &cwd, + mcp_servers.clone(), + ctx.model_id.as_deref(), + ) + .await?; (transport, sid, info) } } @@ -630,8 +638,13 @@ impl HarnessAdapter for KimiAcpAdapter { .await .map_err(|e| HarnessError::SpawnFailed(format!("spawn kimi acp: {e}")))?; let transport = Arc::new(transport); - let (sid, info) = - Self::handshake_and_new(&transport, &cwd, mcp_servers.clone()).await?; + let (sid, info) = Self::handshake_and_new( + &transport, + &cwd, + mcp_servers.clone(), + ctx.model_id.as_deref(), + ) + .await?; (transport, sid, info) } }; diff --git a/crates/ccteam-harness/src/execution/mod.rs b/crates/ccteam-harness/src/execution/mod.rs index 6c04b198..16d681ad 100644 --- a/crates/ccteam-harness/src/execution/mod.rs +++ b/crates/ccteam-harness/src/execution/mod.rs @@ -1,6 +1,7 @@ //! Execution support modules shared by concrete harness adapters. //! pub mod acp; +pub mod claude_accounts; pub mod claude_bg; pub mod claude_common; pub mod claude_stream_json; diff --git a/crates/ccteam-harness/src/execution/opencode_acp/mod.rs b/crates/ccteam-harness/src/execution/opencode_acp/mod.rs index c1896e13..f4d5e69d 100644 --- a/crates/ccteam-harness/src/execution/opencode_acp/mod.rs +++ b/crates/ccteam-harness/src/execution/opencode_acp/mod.rs @@ -138,6 +138,7 @@ impl OpencodeAcpAdapter { transport: &AcpTransport, cwd: &std::path::Path, mcp_servers: Vec, + requested_model: Option<&str>, ) -> Result<(String, ModelInfo), HarnessError> { Self::handshake_initialize(transport).await?; let new_result = transport @@ -154,7 +155,9 @@ impl OpencodeAcpAdapter { let session_id = pluck_session_id(&new_result).ok_or_else(|| { HarnessError::SpawnFailed("opencode session/new missing sessionId".into()) })?; - Ok((session_id, pluck_model_info(&new_result))) + let info = pluck_model_info(&new_result); + crate::execution::acp::record_fresh_default_model("opencode", requested_model, &info); + Ok((session_id, info)) } /// Prefer `session/resume` (no history replay). Fall back to `session/load` @@ -537,8 +540,13 @@ impl HarnessAdapter for OpencodeAcpAdapter { )) })?; let transport = Arc::new(transport); - let (sid, info) = - Self::handshake_and_new(&transport, &cwd, mcp_servers.clone()).await?; + let (sid, info) = Self::handshake_and_new( + &transport, + &cwd, + mcp_servers.clone(), + ctx.model_id.as_deref(), + ) + .await?; (transport, sid, info) } } @@ -557,8 +565,13 @@ impl HarnessAdapter for OpencodeAcpAdapter { .await .map_err(|e| HarnessError::SpawnFailed(format!("spawn opencode acp: {e}")))?; let transport = Arc::new(transport); - let (sid, info) = - Self::handshake_and_new(&transport, &cwd, mcp_servers.clone()).await?; + let (sid, info) = Self::handshake_and_new( + &transport, + &cwd, + mcp_servers.clone(), + ctx.model_id.as_deref(), + ) + .await?; (transport, sid, info) } }; diff --git a/crates/ccteam-harness/src/execution/pi_rpc/mod.rs b/crates/ccteam-harness/src/execution/pi_rpc/mod.rs index 3079ec02..d9b2a285 100644 --- a/crates/ccteam-harness/src/execution/pi_rpc/mod.rs +++ b/crates/ccteam-harness/src/execution/pi_rpc/mod.rs @@ -581,6 +581,14 @@ impl PiRpcAdapter { HarnessError::SpawnFailed("Pi get_state returned no absolute sessionFile".into()) })?; let effective_model = ready.state.model.as_ref().map(PiModel::canonical_id); + // Fresh session, nothing requested (no pick, sidecar or role model): + // what Pi chose is its own default. + if model.is_none() && expected_session_file.is_none() { + crate::model_catalog::record_vendor_default_model_best_effort( + "pi", + effective_model.as_deref(), + ); + } let effective_effort = Some(ready.state.thinking_level.clone()); let config = LiveConfig { role: role.role.clone(), diff --git a/crates/ccteam-harness/src/execution/session_meta.rs b/crates/ccteam-harness/src/execution/session_meta.rs index 1bf681a2..309a7e9e 100644 --- a/crates/ccteam-harness/src/execution/session_meta.rs +++ b/crates/ccteam-harness/src/execution/session_meta.rs @@ -149,6 +149,9 @@ impl ManagedBy { #[derive(Debug, Clone, Serialize, Deserialize)] pub struct SessionMeta { + /// Private cswap binding, including the actual profile selected at exec. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub claude_account: Option, pub sid: String, pub slug: String, pub vendor: AgentVendor, @@ -707,6 +710,7 @@ mod title_tests { fn blank_meta() -> SessionMeta { SessionMeta { + claude_account: None, model_pinned_generation: None, mode: None, tool_face: None, @@ -747,6 +751,7 @@ mod title_tests { fn rescans_see_every_rewrite_addition_and_removal() { let tmp = tempfile::TempDir::new().unwrap(); let meta = |sid: &str, title: &str| SessionMeta { + claude_account: None, sid: sid.into(), title: Some(title.into()), ..blank_meta() @@ -794,6 +799,7 @@ mod title_tests { for _ in 0..50 { let tmp = tempfile::TempDir::new().unwrap(); let meta = |title: &str| SessionMeta { + claude_account: None, title: Some(title.into()), ..blank_meta() }; @@ -818,6 +824,7 @@ mod title_tests { fn an_unchanged_stamp_on_a_fresh_file_is_not_trusted() { let tmp = tempfile::TempDir::new().unwrap(); let meta = |title: &str| SessionMeta { + claude_account: None, title: Some(title.into()), ..blank_meta() }; diff --git a/crates/ccteam-harness/src/execution/transcript_tail.rs b/crates/ccteam-harness/src/execution/transcript_tail.rs index 5860b8ca..37943340 100644 --- a/crates/ccteam-harness/src/execution/transcript_tail.rs +++ b/crates/ccteam-harness/src/execution/transcript_tail.rs @@ -181,6 +181,21 @@ pub fn anthropic_project_dir(cwd: &Path) -> Option { Some(resolve_project_dir_in(&base, cwd)) } +/// Resolve a managed sid's bound Claude profile for reads that outlive its +/// process (recovery, titles). A confirmed profile is read as recorded. A +/// binding no launch has confirmed yet (a new session, or one that just +/// switched accounts) reads cswap's shared history: switching is only allowed +/// once the transcript is there (#236). +pub fn anthropic_bound_project_dir( + cwd: &Path, + account: Option<&super::claude_accounts::ClaudeAccountBinding>, +) -> Option { + match account.and_then(|account| account.config_dir.as_ref()) { + Some(config_dir) => Some(anthropic_project_dir_in(&config_dir.join("projects"), cwd)), + None => anthropic_project_dir(cwd), + } +} + /// [`anthropic_project_dir`] against an explicitly supplied Claude projects /// root — the injection seam (same shape as [`discover_active_session_in`]) so /// tests never touch the real `~/.claude/projects/`. diff --git a/crates/ccteam-harness/src/execution/vendor_title.rs b/crates/ccteam-harness/src/execution/vendor_title.rs index 8eba87c6..2f9a92fa 100644 --- a/crates/ccteam-harness/src/execution/vendor_title.rs +++ b/crates/ccteam-harness/src/execution/vendor_title.rs @@ -71,6 +71,12 @@ fn resolve_claude_uuid(target: &SessionTitleTarget) -> Option { /// (stream-json and the frozen terminal protocol) — the title surface is a /// property of the vendor, not of the wire protocol. pub fn push_claude_custom_title(target: &SessionTitleTarget, title: &str) -> TitleSync { + if let Some(account) = &target.claude_account { + let Some(config_dir) = &account.config_dir else { + return TitleSync::Deferred("session profile has not been confirmed".into()); + }; + return push_claude_custom_title_in(&config_dir.join("projects"), target, title); + } let Some(home) = dirs::home_dir() else { return TitleSync::Deferred("no home dir to resolve ~/.claude/projects".into()); }; @@ -122,6 +128,7 @@ mod tests { fn target(project_dir: &Path, uuid: &str) -> SessionTitleTarget { SessionTitleTarget { + claude_account: None, sid: "s7".into(), vendor_uuid: uuid.into(), project_dir: project_dir.to_path_buf(), diff --git a/crates/ccteam-harness/src/model_catalog.rs b/crates/ccteam-harness/src/model_catalog.rs index b3de33e2..87423273 100644 --- a/crates/ccteam-harness/src/model_catalog.rs +++ b/crates/ccteam-harness/src/model_catalog.rs @@ -38,6 +38,12 @@ pub struct VendorModelCatalog { /// Vendor models, kept in vendor order. #[serde(default)] pub models: Vec, + /// The concrete model id this vendor runs when ccteam requests no model + /// (the picker's "default" row). Observed on a fresh session spawned + /// without an explicit model, or declared by the vendor (codex + /// `isDefault`). Advisory like the rest of this file. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub default_model: Option, } /// Per-vendor cache. Transparent serialization produces the owner-approved @@ -91,18 +97,63 @@ pub fn record_vendor_models_in( std::fs::create_dir_all(root) .with_context(|| format!("create ccteam root {}", root.display()))?; let mut catalog = load_model_catalog_in(root); + // A model-list refresh must not forget the separately observed default. + let default_model = catalog + .0 + .get(vendor) + .and_then(|entry| entry.default_model.clone()); catalog.0.insert( vendor.to_string(), VendorModelCatalog { observed_at: chrono::Utc::now().to_rfc3339(), source: source.to_string(), models, + default_model, }, ); let bytes = serde_json::to_vec_pretty(&catalog).context("serialize model catalog")?; atomic_write_durable(&model_catalog_path_in(root), &bytes) } +/// Record the concrete model a vendor ran when no model was requested. +/// Callers pass `None`/blank when they do not know (explicit model, resume), +/// which is a no-op so a later observation never erases a good one. +pub fn record_vendor_default_model_in( + root: &Path, + vendor: &str, + model: Option<&str>, +) -> Result<()> { + let vendor = vendor.trim(); + let Some(model) = model.map(str::trim).filter(|m| !m.is_empty()) else { + return Ok(()); + }; + if vendor.is_empty() { + return Ok(()); + } + let lock = CATALOG_WRITE_LOCK.get_or_init(|| Mutex::new(())); + let _guard = lock + .lock() + .map_err(|_| anyhow::anyhow!("model catalog write lock poisoned"))?; + let mut catalog = load_model_catalog_in(root); + let entry = catalog.0.entry(vendor.to_string()).or_default(); + if entry.default_model.as_deref() == Some(model) { + return Ok(()); + } + entry.default_model = Some(model.to_string()); + std::fs::create_dir_all(root) + .with_context(|| format!("create ccteam root {}", root.display()))?; + let bytes = serde_json::to_vec_pretty(&catalog).context("serialize model catalog")?; + atomic_write_durable(&model_catalog_path_in(root), &bytes) +} + +/// Environment-resolved twin of [`record_vendor_default_model_in`]; errors +/// are swallowed like every other catalog write. +pub fn record_vendor_default_model_best_effort(vendor: &str, model: Option<&str>) { + if let Some(root) = ccteam_root_from_env() { + let _ = record_vendor_default_model_in(&root, vendor, model); + } +} + /// Environment-resolved adapter seam. Every error is intentionally swallowed: /// catalog persistence is never part of the spawn/turn success contract. pub fn record_vendor_models_best_effort(vendor: &str, source: &str, models: Vec) { @@ -177,6 +228,24 @@ fn pinned_efforts(vendor: &str) -> Vec { mod tests { use super::*; + #[test] + fn the_observed_default_survives_model_refreshes_and_blank_reports() { + let tmp = tempfile::tempdir().unwrap(); + record_vendor_models_in(tmp.path(), "codex", "t", vec![model("a")]).unwrap(); + record_vendor_default_model_in(tmp.path(), "codex", Some("gpt-x")).unwrap(); + record_vendor_models_in(tmp.path(), "codex", "t", vec![model("b")]).unwrap(); + record_vendor_default_model_in(tmp.path(), "codex", None).unwrap(); + record_vendor_default_model_in(tmp.path(), "codex", Some(" ")).unwrap(); + let entry = load_model_catalog_in(tmp.path()).0.remove("codex").unwrap(); + assert_eq!(entry.default_model.as_deref(), Some("gpt-x")); + assert_eq!(entry.models, vec![model("b")]); + // A vendor seen only through its default still gets an entry. + record_vendor_default_model_in(tmp.path(), "grok", Some("grok-9")).unwrap(); + let grok = load_model_catalog_in(tmp.path()).0.remove("grok").unwrap(); + assert_eq!(grok.default_model.as_deref(), Some("grok-9")); + assert!(grok.models.is_empty()); + } + fn model(id: &str) -> CatalogModel { CatalogModel { id: id.to_string(), diff --git a/crates/ccteam-harness/src/usage_catalog.rs b/crates/ccteam-harness/src/usage_catalog.rs index 51b4e7ae..40b9dd35 100644 --- a/crates/ccteam-harness/src/usage_catalog.rs +++ b/crates/ccteam-harness/src/usage_catalog.rs @@ -76,8 +76,14 @@ pub fn load_usage_catalog_in(root: &Path) -> UsageCatalog { } /// Atomically replace one vendor's last-seen entry under an injected root. -/// An all-`None` capture is ignored so a vendor that momentarily answers with -/// nothing cannot erase a useful prior observation. +/// A capture with no window ([`AccountUsage::has_window`]) is ignored so a +/// vendor that momentarily answers with nothing — or with its tier alone — +/// cannot erase a useful prior observation. +/// +/// A real capture REPLACES the entry whole, never merges into it: after an +/// account switch the old account's windows must not survive under the new +/// account's answer (a plan without a 5-hour window must not inherit the last +/// account's 5-hour figure). pub fn record_vendor_usage_in( root: &Path, vendor: &str, @@ -85,7 +91,7 @@ pub fn record_vendor_usage_in( usage: &AccountUsage, ) -> Result<()> { let vendor = vendor.trim(); - if vendor.is_empty() || usage == &AccountUsage::default() { + if vendor.is_empty() || !usage.has_window() { return Ok(()); } let lock = USAGE_WRITE_LOCK.get_or_init(|| Mutex::new(())); @@ -173,12 +179,7 @@ pub fn last_known_entry_in( // A surviving subscription tier alone renders no row (it is a tail segment, // never a fact on its own), so say so here rather than hand back a usage // that formats to nothing. - let usage = &entry.usage; - let has_window = usage.five_hour_pct.is_some() - || usage.weekly_pct.is_some() - || usage.credits_pct.is_some() - || !usage.model_windows.is_empty(); - has_window.then_some(entry) + entry.usage.has_window().then_some(entry) } fn parse_rfc3339(raw: &str) -> Option> { @@ -379,6 +380,46 @@ mod tests { assert_eq!(got.model_windows[0].pct, Some(9)); } + /// The tier alone is no observation: recording it must not erase the + /// windows a previous answer carried. + #[test] + fn a_tier_only_capture_preserves_last_seen_entry() { + let root = tempfile::tempdir().unwrap(); + record_vendor_usage_in(root.path(), "claude", "status card", &usage()).unwrap(); + record_vendor_usage_in( + root.path(), + "claude", + "session release", + &AccountUsage { + subscription: Some("team".into()), + ..Default::default() + }, + ) + .unwrap(); + let kept = &load_usage_catalog_in(root.path()).0["claude"]; + assert_eq!(kept.source, "status card"); + assert_eq!(kept.usage.subscription.as_deref(), Some("max")); + } + + /// An account switch replaces the entry WHOLE: the new account's answer + /// carries no 5-hour window, so none may survive from the old account. + #[test] + fn a_new_capture_replaces_the_entry_rather_than_merging_into_it() { + let root = tempfile::tempdir().unwrap(); + record_vendor_usage_in(root.path(), "claude", "status card", &usage()).unwrap(); + let weekly_only = AccountUsage { + subscription: Some("team".into()), + weekly_pct: Some(35), + weekly_resets_at: Some("2026-09-03T00:00:00Z".into()), + ..Default::default() + }; + record_vendor_usage_in(root.path(), "claude", "status card", &weekly_only).unwrap(); + assert_eq!( + last_known_usage_in(root.path(), "claude", at("2026-08-31T09:00:00Z")), + Some(weekly_only) + ); + } + /// A vendor answering with nothing must not erase what it said before — /// same rule as an empty model capture. #[test] diff --git a/crates/ccteam-harness/tests/claude_agent_smoke_test.rs b/crates/ccteam-harness/tests/claude_agent_smoke_test.rs index fc97dd91..08b9c011 100644 --- a/crates/ccteam-harness/tests/claude_agent_smoke_test.rs +++ b/crates/ccteam-harness/tests/claude_agent_smoke_test.rs @@ -170,6 +170,7 @@ fn write_hook_logger(tmp: &Path) -> (std::path::PathBuf, std::path::PathBuf) { fn make_ctx(cwd: &Path) -> SpawnCtx { SpawnCtx { + claude_account: None, generation: 0, mode: None, slug: SLUG.to_string(), @@ -496,6 +497,7 @@ fn seed_hitl_persona(project_dir: &Path, victim: &Path) { fn make_ctx_hitl(cwd: &Path) -> SpawnCtx { SpawnCtx { + claude_account: None, generation: 0, mode: None, slug: HITL_SLUG.to_string(), @@ -635,6 +637,7 @@ async fn run_hitl_decision_turn(allow: bool, tag: &str) -> (bool, bool) { let adapter = ClaudeTuiAdapter::new(); let ctx = SpawnCtx { + claude_account: None, generation: 0, mode: None, slug: slug.clone(), diff --git a/crates/ccteam-harness/tests/claude_stream_json_remote_test.rs b/crates/ccteam-harness/tests/claude_stream_json_remote_test.rs index 047e601e..28ad72d9 100644 --- a/crates/ccteam-harness/tests/claude_stream_json_remote_test.rs +++ b/crates/ccteam-harness/tests/claude_stream_json_remote_test.rs @@ -102,7 +102,19 @@ while True: "session_id":sid}) "#; +/// Pin `HOME` + `CCTEAM_HOME` to one process-wide temp dir. The adapter +/// records the fake claude's `initialize.models` into the model catalog under +/// `ccteam_root_from_env()`; unpinned, `fake-model` landed in the developer's +/// real `~/.ccteam/model-catalog.json` (#235). +fn isolate_state_home() { + static STATE: std::sync::OnceLock = std::sync::OnceLock::new(); + let dir = STATE.get_or_init(|| tempfile::TempDir::new().unwrap()); + std::env::set_var("HOME", dir.path()); + std::env::set_var("CCTEAM_HOME", dir.path().join(".ccteam")); +} + fn write_fake(tmp: &Path) -> PathBuf { + isolate_state_home(); let p = tmp.join("fake-claude-sj-remote.py"); std::fs::write(&p, FAKE_PY).unwrap(); std::fs::set_permissions(&p, std::fs::Permissions::from_mode(0o755)).unwrap(); @@ -117,6 +129,7 @@ fn ctx_remote( target: RemoteExecTarget, ) -> SpawnCtx { SpawnCtx { + claude_account: None, generation: 0, mode: None, slug: slug.to_string(), diff --git a/crates/ccteam-harness/tests/claude_stream_json_test.rs b/crates/ccteam-harness/tests/claude_stream_json_test.rs index 08c7e2fb..03bafdf7 100644 --- a/crates/ccteam-harness/tests/claude_stream_json_test.rs +++ b/crates/ccteam-harness/tests/claude_stream_json_test.rs @@ -234,6 +234,7 @@ fn setup(tmp: &Path) -> PathBuf { fn ctx(tmp: &Path, slug: &str, sid: &str) -> SpawnCtx { SpawnCtx { + claude_account: None, generation: 0, mode: None, slug: slug.to_string(), @@ -578,6 +579,7 @@ async fn child_death_then_restart_recovers() { fn ctx_hitl(tmp: &Path, slug: &str, sid: &str) -> SpawnCtx { SpawnCtx { + claude_account: None, generation: 0, permission_mode: PermissionMode::Hitl, ..ctx(tmp, slug, sid) @@ -2601,6 +2603,7 @@ async fn recover_unobserved_turn_reads_the_vendor_transcript() { .with_timezone(&chrono::Utc); let recovered = adapter .recover_unobserved_turn(&UnobservedTurnCtx { + claude_account: None, sid: "s43".into(), slug: "proj".into(), cwd: tmp.path().to_path_buf(), @@ -2623,6 +2626,7 @@ async fn recover_unobserved_turn_reads_the_vendor_transcript() { .with_timezone(&chrono::Utc); assert!(adapter .recover_unobserved_turn(&UnobservedTurnCtx { + claude_account: None, sid: "s43".into(), slug: "proj".into(), cwd: tmp.path().to_path_buf(), diff --git a/crates/ccteam-harness/tests/claude_tui_env_test.rs b/crates/ccteam-harness/tests/claude_tui_env_test.rs index bf9d4edc..db8315e3 100644 --- a/crates/ccteam-harness/tests/claude_tui_env_test.rs +++ b/crates/ccteam-harness/tests/claude_tui_env_test.rs @@ -39,6 +39,7 @@ const F175_SID: &str = "s1"; fn make_ctx(slug: &str, tmp: &tempfile::TempDir) -> SpawnCtx { SpawnCtx { + claude_account: None, generation: 0, mode: None, slug: slug.to_string(), diff --git a/crates/ccteam-harness/tests/claude_tui_reattach_test.rs b/crates/ccteam-harness/tests/claude_tui_reattach_test.rs index 4f43840e..9258cfeb 100644 --- a/crates/ccteam-harness/tests/claude_tui_reattach_test.rs +++ b/crates/ccteam-harness/tests/claude_tui_reattach_test.rs @@ -54,6 +54,7 @@ fn fake_claude_script(tmp: &tempfile::TempDir) -> PathBuf { fn make_ctx(slug: &str, sid: &str, role: &str, tmp: &tempfile::TempDir) -> SpawnCtx { let _ = role; // role rides on AgentSpecBrief, not the pane identity. SpawnCtx { + claude_account: None, generation: 0, mode: None, slug: slug.to_string(), diff --git a/crates/ccteam-harness/tests/claude_tui_resume_test.rs b/crates/ccteam-harness/tests/claude_tui_resume_test.rs index 48cc0715..603880eb 100644 --- a/crates/ccteam-harness/tests/claude_tui_resume_test.rs +++ b/crates/ccteam-harness/tests/claude_tui_resume_test.rs @@ -147,6 +147,7 @@ fn make_ctx(slug: &str, tmp: &tempfile::TempDir) -> SpawnCtx { /// same-(project,role) sessions stay distinct). fn make_ctx_sid(slug: &str, sid: &str, tmp: &tempfile::TempDir) -> SpawnCtx { SpawnCtx { + claude_account: None, generation: 0, mode: None, slug: slug.to_string(), @@ -167,6 +168,7 @@ fn make_ctx_sid(slug: &str, sid: &str, tmp: &tempfile::TempDir) -> SpawnCtx { /// the hitl spawn drops the skip flag and carries `--permission-mode default`. fn make_ctx_hitl(slug: &str, tmp: &tempfile::TempDir) -> SpawnCtx { SpawnCtx { + claude_account: None, generation: 0, mode: None, slug: slug.to_string(), diff --git a/crates/ccteam-harness/tests/claude_tui_test.rs b/crates/ccteam-harness/tests/claude_tui_test.rs index 6384b167..9bf3e778 100644 --- a/crates/ccteam-harness/tests/claude_tui_test.rs +++ b/crates/ccteam-harness/tests/claude_tui_test.rs @@ -46,6 +46,7 @@ fn kill_session_quiet(name: &str) { async fn spawn_time_effort_is_refused_rather_than_ignored() { let tmp = tempfile::TempDir::new().unwrap(); let ctx = SpawnCtx { + claude_account: None, generation: 0, mode: None, slug: "tui-effort".into(), @@ -96,6 +97,7 @@ async fn start_thread_spawns_tmux_and_returns_handle() { let brief = AgentSpecBrief { role: role.clone() }; let ctx = SpawnCtx { + claude_account: None, generation: 0, mode: None, slug: slug.clone(), @@ -148,6 +150,7 @@ async fn submit_turn_sends_literal_text_to_tmux_pane() { let brief = AgentSpecBrief { role: role.clone() }; let ctx = SpawnCtx { + claude_account: None, generation: 0, mode: None, slug: slug.clone(), @@ -215,6 +218,7 @@ async fn submit_turn_artifact_uses_read_protocol() { let brief = AgentSpecBrief { role: role.clone() }; let ctx = SpawnCtx { + claude_account: None, generation: 0, mode: None, slug: slug.clone(), @@ -502,6 +506,7 @@ async fn claude_directive_bare_model_passes_through_to_native_picker() { role: "alice".to_string(), }; let ctx = SpawnCtx { + claude_account: None, generation: 0, mode: None, slug: slug.clone(), diff --git a/crates/ccteam-harness/tests/codex_app_server_test.rs b/crates/ccteam-harness/tests/codex_app_server_test.rs index 1d891b37..249dd281 100644 --- a/crates/ccteam-harness/tests/codex_app_server_test.rs +++ b/crates/ccteam-harness/tests/codex_app_server_test.rs @@ -64,6 +64,7 @@ async fn real_codex_app_server_start_thread_smoke() { role: "real-smoke".to_string(), }, &SpawnCtx { + claude_account: None, generation: 0, mode: None, slug: "real-codex-smoke".to_string(), @@ -130,6 +131,7 @@ async fn real_codex_reply_roundtrip_proves_model_output() { role: "real-reply".to_string(), }, &SpawnCtx { + claude_account: None, generation: 0, mode: None, slug: "real-codex-reply".to_string(), @@ -328,6 +330,7 @@ async fn raw_extras_transport_is_resolved_tag() { role: "demo".into(), }, &SpawnCtx { + claude_account: None, generation: 0, mode: None, slug: "test".into(), @@ -393,6 +396,7 @@ async fn spawn_time_model_and_effort_ride_the_first_turn_start() { role: "demo".into(), }, &SpawnCtx { + claude_account: None, generation: 0, mode: None, slug: "tuned".into(), @@ -473,6 +477,7 @@ async fn submit_turn_resumes_unloaded_thread_before_turn_start() { role: "demo".into(), }, &SpawnCtx { + claude_account: None, generation: 0, mode: None, slug: "ensure-loaded".into(), @@ -585,6 +590,7 @@ async fn ensure_loaded_resume_carries_the_per_thread_mcp_principal() { role: String::new(), }, &SpawnCtx { + claude_account: None, generation: 0, mode: None, slug: "excore".into(), @@ -670,6 +676,7 @@ async fn f10_real_codex_stdio_new_smoke() { role: "f10-stdio-smoke".to_string(), }, &SpawnCtx { + claude_account: None, generation: 0, mode: None, slug: "f10-stdio-smoke".to_string(), @@ -710,6 +717,20 @@ async fn f10_real_codex_stdio_new_smoke() { /// Spawn a scripted peer that accepts ONE connection and serves the /// supplied request → response map. Notifications can be pushed /// out-of-band via the returned channel. +/// Pin `HOME` + `CCTEAM_HOME` to one process-wide temp dir. Adapters record +/// vendor model catalogs (and the observed default model) under +/// `ccteam_root_from_env()`; unpinned, these fixtures were written into the +/// developer's real `~/.ccteam/model-catalog.json` and showed up as the +/// composer's model rows. +fn isolate_state_home() { + static STATE: std::sync::OnceLock = std::sync::OnceLock::new(); + let dir = STATE.get_or_init(|| tempfile::TempDir::new().unwrap()); + unsafe { + std::env::set_var("HOME", dir.path()); + std::env::set_var("CCTEAM_HOME", dir.path().join(".ccteam")); + } +} + async fn spawn_scripted_peer( sock: PathBuf, handler: impl Fn(&Value) -> Value + Send + 'static, @@ -717,6 +738,7 @@ async fn spawn_scripted_peer( tokio::task::JoinHandle<()>, tokio::sync::mpsc::Sender, ) { + isolate_state_home(); let listener = UnixListener::bind(&sock).unwrap(); let (notif_tx, mut notif_rx) = tokio::sync::mpsc::channel::(16); let task = tokio::spawn(async move { @@ -1016,6 +1038,7 @@ async fn adapter_returns_spawn_failed_when_socket_missing() { role: "demo".into(), }; let ctx = SpawnCtx { + claude_account: None, generation: 0, mode: None, slug: "test".into(), @@ -1096,6 +1119,7 @@ async fn adapter_sends_initialize_handshake_before_thread_start() { role: "demo".into(), }; let ctx = SpawnCtx { + claude_account: None, generation: 0, mode: None, slug: "test".into(), @@ -1200,6 +1224,7 @@ async fn adapter_start_thread_against_scripted_peer() { role: "demo".into(), }; let ctx = SpawnCtx { + claude_account: None, generation: 0, mode: None, slug: "test".into(), @@ -1272,6 +1297,7 @@ async fn adapter_maps_system_directives_to_command_rpcs() { role: "demo".into(), }; let ctx = SpawnCtx { + claude_account: None, generation: 0, mode: None, slug: "test".into(), @@ -1533,6 +1559,7 @@ async fn d2_start_in( role: "demo".into(), }, &SpawnCtx { + claude_account: None, generation, mode: None, slug: "test".into(), @@ -1712,6 +1739,7 @@ async fn set_session_title_pushes_thread_name_set() { let (adapter, h, seen, peer, sock) = d2_start("d2-title").await; let target = SessionTitleTarget { + claude_account: None, sid: "s42".into(), vendor_uuid: h.identity.clone(), project_dir: std::env::temp_dir(), @@ -1742,6 +1770,7 @@ async fn set_session_title_pushes_thread_name_set() { async fn set_session_title_without_a_live_thread_is_deferred() { let adapter = CodexAppServerAdapter::new(); let target = SessionTitleTarget { + claude_account: None, sid: "s43".into(), vendor_uuid: "tid-gone".into(), project_dir: std::env::temp_dir(), @@ -3862,6 +3891,7 @@ async fn start_thread_injects_per_thread_mcp_config_with_identity() { role: "reviewer".into(), }, &SpawnCtx { + claude_account: None, generation: 0, mode: None, slug: "demo".into(), @@ -3951,6 +3981,7 @@ async fn start_thread_resumes_persisted_vendor_uuid_after_restart() { // Simulate the "before the restart" state: a prior codex session whose // vendor_uuid is persisted in meta.json (what apply_new_session writes). let meta = ccteam_harness::SessionMeta { + claude_account: None, model_pinned_generation: None, mode: None, tool_face: None, @@ -3993,6 +4024,7 @@ async fn start_thread_resumes_persisted_vendor_uuid_after_restart() { role: "reviewer".into(), }, &SpawnCtx { + claude_account: None, generation: 0, mode: None, slug: "demo".into(), @@ -4057,6 +4089,7 @@ async fn start_thread_resumes_persisted_vendor_uuid_after_restart() { async fn start_thread_rejects_remote_ctx_readable() { let tmp = TempDir::new().unwrap(); let ctx = SpawnCtx { + claude_account: None, generation: 0, mode: None, slug: "demo".into(), @@ -4145,6 +4178,7 @@ impl Drop for FakeAppServerEnv { fn fake_spawn_ctx(tmp: &std::path::Path, sid: &str) -> SpawnCtx { SpawnCtx { + claude_account: None, generation: 0, mode: None, slug: "fake-codex".to_string(), diff --git a/crates/ccteam-harness/tests/dsh_acp_test.rs b/crates/ccteam-harness/tests/dsh_acp_test.rs index 963e1b37..be2f452b 100644 --- a/crates/ccteam-harness/tests/dsh_acp_test.rs +++ b/crates/ccteam-harness/tests/dsh_acp_test.rs @@ -242,6 +242,7 @@ fn adapter() -> DshAcpAdapter { fn spawn_ctx(tmp: &TempDir, sid: &str) -> SpawnCtx { SpawnCtx { + claude_account: None, generation: 0, mode: None, slug: "demo".into(), @@ -269,6 +270,7 @@ fn spawn_ctx_with_model(tmp: &TempDir, sid: &str) -> SpawnCtx { fn write_meta(project: &Path, sid: &str, vendor_uuid: &str) { let meta = SessionMeta { + claude_account: None, model_pinned_generation: None, mode: None, tool_face: None, diff --git a/crates/ccteam-harness/tests/grok_acp_test.rs b/crates/ccteam-harness/tests/grok_acp_test.rs index c5ad2394..247fb04f 100644 --- a/crates/ccteam-harness/tests/grok_acp_test.rs +++ b/crates/ccteam-harness/tests/grok_acp_test.rs @@ -66,6 +66,7 @@ fn clear_fake() { fn spawn_ctx(tmp: &TempDir, sid: &str) -> SpawnCtx { SpawnCtx { + claude_account: None, generation: 0, mode: None, slug: "demo".into(), @@ -547,6 +548,7 @@ async fn load_resume_filters_is_replay() { let sid = "s-resume"; // Seed meta as if a prior session existed with known ACP sessionId. let meta = SessionMeta { + claude_account: None, model_pinned_generation: None, mode: None, tool_face: None, @@ -812,6 +814,7 @@ async fn session_new_and_load_carry_mcp_servers() { } let ctx_with_secret = |sid: &str| SpawnCtx { + claude_account: None, generation: 0, mode: None, slug: "demo".into(), @@ -843,6 +846,7 @@ async fn session_new_and_load_carry_mcp_servers() { // Phase B — cold resume via session/load (meta carries the vendor_uuid). let sid_load = "s-load-mcp"; let meta = SessionMeta { + claude_account: None, model_pinned_generation: None, mode: None, tool_face: None, @@ -943,6 +947,7 @@ async fn session_new_offers_this_sessions_principal_verbatim() { role: String::new(), }, &SpawnCtx { + claude_account: None, generation: 0, mode: None, slug: "demo".into(), diff --git a/crates/ccteam-harness/tests/kimi_acp_test.rs b/crates/ccteam-harness/tests/kimi_acp_test.rs index 2aaed666..6bbd4d45 100644 --- a/crates/ccteam-harness/tests/kimi_acp_test.rs +++ b/crates/ccteam-harness/tests/kimi_acp_test.rs @@ -21,7 +21,22 @@ fn fake_bin() -> PathBuf { PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/kimi_acp/fake_kimi_acp.py") } +/// Pin `HOME` + `CCTEAM_HOME` to one process-wide temp dir. Adapters record +/// vendor model catalogs (and the observed default model) under +/// `ccteam_root_from_env()`; unpinned, these fixtures were written into the +/// developer's real `~/.ccteam/model-catalog.json` and showed up as the +/// composer's model rows. +fn isolate_state_home() { + static STATE: std::sync::OnceLock = std::sync::OnceLock::new(); + let dir = STATE.get_or_init(|| tempfile::TempDir::new().unwrap()); + unsafe { + std::env::set_var("HOME", dir.path()); + std::env::set_var("CCTEAM_HOME", dir.path().join(".ccteam")); + } +} + fn install_fake() { + isolate_state_home(); let bin = fake_bin(); assert!(bin.is_file(), "missing fake at {}", bin.display()); let wrapper = std::env::temp_dir().join(format!( @@ -54,6 +69,7 @@ fn clear_fake() { fn spawn_ctx(tmp: &TempDir, sid: &str) -> SpawnCtx { SpawnCtx { + claude_account: None, generation: 0, mode: None, slug: "demo".into(), @@ -321,6 +337,7 @@ async fn resume_prefers_session_resume_no_replay() { let project = tmp.path(); let sid = "s-resume"; let meta = SessionMeta { + claude_account: None, model_pinned_generation: None, mode: None, tool_face: None, @@ -417,6 +434,7 @@ async fn resume_carries_mcp_servers() { } let meta = SessionMeta { + claude_account: None, model_pinned_generation: None, mode: None, tool_face: None, @@ -453,6 +471,7 @@ async fn resume_carries_mcp_servers() { // A SpawnCtx WITH a secret → `acp_mcp_servers_http` yields a non-empty array. let ctx = SpawnCtx { + claude_account: None, generation: 0, mode: None, slug: "demo".into(), diff --git a/crates/ccteam-harness/tests/opencode_acp_test.rs b/crates/ccteam-harness/tests/opencode_acp_test.rs index 224bd764..d05796ba 100644 --- a/crates/ccteam-harness/tests/opencode_acp_test.rs +++ b/crates/ccteam-harness/tests/opencode_acp_test.rs @@ -24,7 +24,22 @@ fn fake_bin() -> PathBuf { .join("tests/fixtures/opencode_acp/fake_opencode_acp.py") } +/// Pin `HOME` + `CCTEAM_HOME` to one process-wide temp dir. Adapters record +/// vendor model catalogs (and the observed default model) under +/// `ccteam_root_from_env()`; unpinned, these fixtures were written into the +/// developer's real `~/.ccteam/model-catalog.json` and showed up as the +/// composer's model rows. +fn isolate_state_home() { + static STATE: std::sync::OnceLock = std::sync::OnceLock::new(); + let dir = STATE.get_or_init(|| tempfile::TempDir::new().unwrap()); + unsafe { + std::env::set_var("HOME", dir.path()); + std::env::set_var("CCTEAM_HOME", dir.path().join(".ccteam")); + } +} + fn install_fake() { + isolate_state_home(); let bin = fake_bin(); assert!(bin.is_file(), "missing fake at {}", bin.display()); let wrapper = std::env::temp_dir().join(format!( @@ -57,6 +72,7 @@ fn clear_fake() { fn spawn_ctx(tmp: &TempDir, sid: &str) -> SpawnCtx { SpawnCtx { + claude_account: None, generation: 0, mode: None, slug: "demo".into(), @@ -264,6 +280,7 @@ async fn resume_prefers_session_resume_no_replay() { let project = tmp.path(); let sid = "s-resume"; let meta = SessionMeta { + claude_account: None, model_pinned_generation: None, mode: None, tool_face: None, @@ -361,6 +378,7 @@ async fn resume_carries_mcp_servers() { } let meta = SessionMeta { + claude_account: None, model_pinned_generation: None, mode: None, tool_face: None, @@ -397,6 +415,7 @@ async fn resume_carries_mcp_servers() { // A SpawnCtx WITH a secret → `acp_mcp_servers_http` yields a non-empty array. let ctx = SpawnCtx { + claude_account: None, generation: 0, mode: None, slug: "demo".into(), diff --git a/crates/ccteam-harness/tests/pi_bridge_test.rs b/crates/ccteam-harness/tests/pi_bridge_test.rs index 98286763..21a53ccc 100644 --- a/crates/ccteam-harness/tests/pi_bridge_test.rs +++ b/crates/ccteam-harness/tests/pi_bridge_test.rs @@ -70,6 +70,7 @@ impl TestEnv { fn ctx(&self, permission_mode: PermissionMode) -> SpawnCtx { SpawnCtx { + claude_account: None, generation: 0, mode: None, slug: "pi-bridge".into(), diff --git a/crates/ccteam-harness/tests/pi_rpc_test.rs b/crates/ccteam-harness/tests/pi_rpc_test.rs index fe7944dc..b89247a3 100644 --- a/crates/ccteam-harness/tests/pi_rpc_test.rs +++ b/crates/ccteam-harness/tests/pi_rpc_test.rs @@ -85,6 +85,7 @@ impl PiTestEnv { fn ctx(&self, sid: &str) -> SpawnCtx { SpawnCtx { + claude_account: None, generation: 0, mode: None, slug: "pi-test".to_string(), diff --git a/crates/ccteam-harness/tests/session_meta_test.rs b/crates/ccteam-harness/tests/session_meta_test.rs index ec3d59cd..5af62f0f 100644 --- a/crates/ccteam-harness/tests/session_meta_test.rs +++ b/crates/ccteam-harness/tests/session_meta_test.rs @@ -15,6 +15,7 @@ use tempfile::TempDir; fn sample_meta(sid: &str, slug: &str, last_active: &str, uuid: &str) -> SessionMeta { SessionMeta { + claude_account: None, model_pinned_generation: None, mode: None, tool_face: None, diff --git a/crates/ccteam-im/src/daemon.rs b/crates/ccteam-im/src/daemon.rs index 7646ebb1..51af7a78 100644 --- a/crates/ccteam-im/src/daemon.rs +++ b/crates/ccteam-im/src/daemon.rs @@ -1739,7 +1739,12 @@ async fn route_inbound_message( // reason: it has to take the stopped child's delegation claim, and // a claim is never taken while the gateway lock is held (issue #197 // E). `handle_message_shared` is where the lock can be dropped. - if may_spawn || Gateway::inbound_needs_shared_entry(&clean_payload) { + // `/account` (#236) runs cswap and the account switch without the lock; + // a button standing for such a command takes the same entry. + if may_spawn + || Gateway::inbound_needs_shared_entry(&clean_payload) + || Gateway::selection_needs_shared_entry(msg.selection.as_ref()) + { let gateway = Arc::clone(gateway); let channel = Arc::clone(&channel); let msg = msg.clone(); @@ -1771,8 +1776,9 @@ async fn route_inbound_message( return; } - let replies = gateway - .lock() + // Instrumented: a long inline hold now logs `gateway mutex held too long` + // with this site (it was invisible during #234). + let replies = crate::latency::gateway_lock(gateway, "im.inline.handle") .await .handle_message( &msg.channel, diff --git a/crates/ccteam-im/src/external_nodes.rs b/crates/ccteam-im/src/external_nodes.rs index b8587ef3..46159b99 100644 --- a/crates/ccteam-im/src/external_nodes.rs +++ b/crates/ccteam-im/src/external_nodes.rs @@ -64,6 +64,7 @@ pub fn external_node_meta( AgentVendor::Claude | AgentVendor::Codex | AgentVendor::Pi => SessionProtocol::StreamJson, }; let mut meta = SessionMeta { + claude_account: None, model_pinned_generation: None, tool_face: None, managed_by: ManagedBy::External, diff --git a/crates/ccteam-im/src/gateway.rs b/crates/ccteam-im/src/gateway.rs index 39ac68e4..b452982b 100644 --- a/crates/ccteam-im/src/gateway.rs +++ b/crates/ccteam-im/src/gateway.rs @@ -64,6 +64,119 @@ pub struct RoleNotFound { pub role: String, } +/// The frozen terminal protocol and remote projects do not support cswap. +#[derive(Debug, thiserror::Error)] +#[error("cswap accounts require a local Claude stream-json session")] +pub struct CswapAccountUnsupported; + +/// Why a session's Claude account switch was refused (#236). None of these +/// touched the session: binding, process and history are as they were. +#[derive(Debug, thiserror::Error)] +pub enum ClaudeAccountSwitchError { + /// No session with this sid. + #[error("unknown session: {0}")] + UnknownSession(String), + /// Not a local Claude stream-json session. + #[error(transparent)] + Unsupported(#[from] CswapAccountUnsupported), + /// The process is doing something releasing it would cut short. + #[error("{0}")] + Busy(String), + /// Switching would lose the conversation or misdescribe the session. + #[error("{0}")] + Refused(String), + /// Bookkeeping failed (meta write, release). + #[error(transparent)] + Internal(#[from] anyhow::Error), +} + +/// A session's account after [`Gateway::switch_claude_account_shared`]. +#[derive(Debug, Clone)] +pub struct ClaudeAccountSwitch { + /// The new binding as any frontend may show it; `None` = default login. + pub claude_account: Option, + /// The binding actually changed (picking the current account is a no-op). + pub changed: bool, + /// A resident process was released; the next message resumes the sid. + pub released: bool, +} + +/// One deadline for every live account-usage ask in a single read (#234). A +/// live answer is an in-memory read on the vendor side (claude `get_usage` +/// with `skip_behaviors` answers in milliseconds); past this, the vendor's +/// last recorded observation answers instead. +const ACCOUNT_USAGE_DEADLINE: Duration = Duration::from_secs(1); + +/// How long a `/status` usage prefetch stays valid for the render that follows. +const STATUS_USAGE_PREFETCH_TTL: Duration = Duration::from_secs(10); + +/// The live sessions to ask for each vendor's account windows, captured +/// under the gateway lock (cheap handle clones) so that the asking itself +/// never holds it. #234: `/status` awaited every live session in turn under +/// the lock, 3 s each; once claude's answer slowed down, one card held the +/// whole daemon for up to a minute and stalled web, IM and MCP with it. +pub struct AccountUsageProbes { + root: Option, + by_vendor: Vec<(AgentVendor, Vec)>, +} + +/// One live session to ask: its adapter and thread, cloned out of the lock. +type UsageAsker = (Arc, ThreadHandle); + +impl AccountUsageProbes { + /// Ask every captured session at once, all against one deadline. Per + /// vendor the first answer in capture order wins (a `/status` card + /// captures its own focus first: across a login switch processes can + /// disagree on the account), and is recorded; a vendor nobody answered + /// for reads its last observation from + /// [`ccteam_harness::usage_catalog`], which drops each window at the + /// vendor's declared reset. A vendor with neither is absent — never an + /// "unknown" row to misread as plenty left. Keyed by vendor token. + pub async fn resolve(self) -> BTreeMap { + let deadline = tokio::time::Instant::now() + ACCOUNT_USAGE_DEADLINE; + let root = self.root; + let per_vendor = self.by_vendor.into_iter().map(|(vendor, askers)| { + let root = root.clone(); + async move { + let answers = futures::future::join_all(askers.iter().map(|(adapter, thread)| { + tokio::time::timeout_at(deadline, adapter.account_usage(thread)) + })) + .await; + let entry = match answers.into_iter().find_map(|answer| answer.ok().flatten()) { + Some(usage) => { + if let Some(root) = root.as_deref() { + ccteam_harness::usage_catalog::record_vendor_usage_best_effort( + root, + vendor_str(vendor), + "status card", + &usage, + ); + } + Some(VendorAccountUsage { + observed_at: chrono::Utc::now().to_rfc3339(), + source: "status card".to_string(), + usage, + }) + } + None => root.as_deref().and_then(|root| { + ccteam_harness::usage_catalog::last_known_entry_in( + root, + vendor_str(vendor), + chrono::Utc::now(), + ) + }), + }; + entry.map(|entry| (vendor_str(vendor).to_string(), entry)) + } + }); + futures::future::join_all(per_vendor) + .await + .into_iter() + .flatten() + .collect() + } +} + #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] struct ChatKey { channel: String, @@ -717,6 +830,9 @@ enum ReleaseReason { Capacity, /// Nobody spoke to it for its harness's `sessions.idle_release_secs`. Idle, + /// The user moved the session to another Claude account (#236); the next + /// message resumes the same sid under it. + AccountSwitch, } impl ReleaseReason { @@ -724,6 +840,7 @@ impl ReleaseReason { match self { ReleaseReason::Capacity => "capacity", ReleaseReason::Idle => "idle", + ReleaseReason::AccountSwitch => "account_switch", } } } @@ -928,6 +1045,9 @@ pub struct Gateway { /// no longer the chat's focus, which otherwise masquerade as the current /// session in the single IM stream (v0.8.10 routing-isolation fix). current_session: FocusRoutes, + /// `/status` usage asked for WITHOUT the gateway lock by the shared IM + /// entry, parked for the `handle_message` render that follows (#234). + status_usage_prefetch: BTreeMap)>, sessions: BTreeMap, /// Process-wide allocator for [`GatewaySession::generation`]. It is not a /// persisted identity; it only fences races within this daemon lifetime. @@ -1022,6 +1142,9 @@ pub struct Gateway { /// the inbound hot path (see [`SpawnClaims`]); deliberately its own lock, /// never held under the gateway's own mutex for longer than a map lookup. spawn_claims: Arc, + /// Optional cswap discovery (#236 IM `/account`), shared with the web + /// picker so both read one cache. + cswap_accounts: Arc, /// The `(sid, secret)` authority behind every managed session's tool face /// — see [`crate::principals`]. Separate from `sessions` because a /// principal has to work BEFORE its session is live (the vendor uses it @@ -2487,6 +2610,9 @@ pub struct SessionInventory { // `assert_eq!`/`==`, which only need `PartialEq`. #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct SessionView { + /// Display-only account facts; private profile paths stay in meta.json. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub claude_account: Option, /// Gateway session id (`s{n}`) — the network-API session namespace. pub sid: String, /// Project slug the session runs in. @@ -2750,6 +2876,8 @@ pub struct StartOutcome { /// exist so a caller can pick well; they are never a gate. #[derive(Debug, Clone, Default, PartialEq, Eq)] pub struct SpawnTuning { + /// Stable identity reference returned by optional cswap discovery. + pub claude_account: Option, /// Explicit model id; overrides the role's `model:` frontmatter. pub model: Option, /// Explicit reasoning-effort token (vendor-specific value set — the @@ -2765,6 +2893,7 @@ impl SpawnTuning { fn normalized(self) -> Self { let clean = |s: Option| s.map(|v| v.trim().to_string()).filter(|v| !v.is_empty()); Self { + claude_account: clean(self.claude_account), model: clean(self.model), effort: clean(self.effort), mode: clean(self.mode), @@ -3102,6 +3231,7 @@ struct RoutingState { /// stale session's `system:init` — while the on-demand resume path runs the /// same core under its already-held lock. One construction site, no drift. struct MetaRebuildPlan { + claude_account: Option, generation: u64, sid: String, slug: String, @@ -3154,6 +3284,7 @@ struct MetaRebuildPlan { /// construction site (`plan_new_session`), no drift between the inline and /// lock-dropping callers. struct NewSessionPlan { + claude_account: Option, generation: u64, id: String, /// Canonical resource owner used by session ACL and persisted meta. @@ -3214,6 +3345,7 @@ struct NewSessionPlan { /// marker from the OLD thread (`identity@started_at`); apply discards the /// freshly spawned thread if the session vanished or was replaced meanwhile. struct ResumeDeadPlan { + claude_account: Option, session_id: String, project: String, role: String, @@ -3422,6 +3554,12 @@ pub const GATEWAY_COMMANDS: &[GatewayCommandSpec] = &[ help: "switch the current session to a fresh agent role", in_menu: true, }, + GatewayCommandSpec { + name: "/account", + arg_hint: Some("[ | default]"), + help: "show or switch the current Claude session's account (cswap); bare = list", + in_menu: true, + }, GatewayCommandSpec { name: "/stop", arg_hint: Some(""), @@ -3533,7 +3671,7 @@ impl NextStep { fn command_next_step(cmd: &str) -> Option { Some(match cmd { - "/new" | "/use" | "/role" | "/interrupt" => NextStep::Session, + "/new" | "/use" | "/role" | "/interrupt" | "/account" => NextStep::Session, "/stop" | "/rename" | "/cd" | "/newproject" => NextStep::Sessions, "/status" => NextStep::SessionControls, "/help" => NextStep::Menu, @@ -3552,6 +3690,16 @@ fn button_action_command(action: &str) -> Option { "help" => "/help", "model" => "/model", "interrupt" => "/interrupt", + _ if action.starts_with("account:") => { + // `account:` / `account:default` — the `/account` picker. + let target = action.strip_prefix("account:")?; + if target != "default" + && (target.is_empty() || !target.chars().all(|c| c.is_ascii_digit())) + { + return None; + } + return Some(format!("/account {target}")); + } _ => { // `new-effort::[:]` — the effort leads // because it never contains a `:` while a model id may. @@ -3684,6 +3832,7 @@ impl Gateway { next_session_presets: BTreeMap::new(), current_project: FocusRoutes::new(FocusScope::Conversation), current_session: FocusRoutes::new(FocusScope::Thread), + status_usage_prefetch: BTreeMap::new(), sessions: BTreeMap::new(), next_session_generation: 0, rebuild_reservations: BTreeMap::new(), @@ -3710,6 +3859,7 @@ impl Gateway { progress_projection: None, im_reload_tx: None, spawn_claims: Arc::new(SpawnClaims::new()), + cswap_accounts: Default::default(), principals: Arc::new(crate::principals::SessionPrincipals::new()), remote_host_proxy: None, local_vendor_availability_override: None, @@ -3930,6 +4080,13 @@ impl Gateway { BodyGate::PostMortem(body) => Some(body), }; let (host, wire_slug) = self.ensure_session_host_binding(slug, &meta.host)?; + if meta.claude_account.is_some() + && (meta.vendor != AgentVendor::Claude + || meta.protocol != SessionProtocol::StreamJson + || host != ccteam_core::LOCAL_HOST) + { + return Err(CswapAccountUnsupported.into()); + } let role_detail = ensure_role_exists(&cwd, &meta.role).ok().flatten(); // Both tuning axes, one precedence — see `respawn_tuning`. let (model_id, effort) = respawn_tuning( @@ -3973,6 +4130,7 @@ impl Gateway { self.rebuild_reservations .insert(meta.sid.clone(), generation); Ok(MetaRebuildPlan { + claude_account: meta.claude_account.clone(), generation, sid: meta.sid.clone(), slug: slug.to_string(), @@ -4054,6 +4212,7 @@ impl Gateway { role: plan.role.clone(), }, &SpawnCtx { + claude_account: plan.claude_account.clone(), generation: plan.generation, slug: plan.slug.clone(), sid: plan.sid.clone(), @@ -5009,6 +5168,7 @@ impl Gateway { }; let activity = adapter .detached_activity(&UnobservedTurnCtx { + claude_account: meta.claude_account.clone(), sid: d.sid.clone(), slug: d.slug.clone(), cwd: d.cwd.clone(), @@ -5304,6 +5464,7 @@ impl Gateway { }; let recovered = adapter .recover_unobserved_turn(&UnobservedTurnCtx { + claude_account: meta.claude_account.clone(), sid: sid.to_string(), slug: slug.to_string(), cwd: cwd.to_path_buf(), @@ -5716,7 +5877,23 @@ impl Gateway { /// `&mut Gateway` (the claim is always taken before the gateway lock). /// The daemon asks this so a `/stop` never reaches the inline path. pub fn inbound_needs_shared_entry(text: &str) -> bool { - text.split_whitespace().next() == Some("/stop") + matches!(text.split_whitespace().next(), Some("/stop" | "/account")) + || Self::is_status_command(text) + } + + /// A button that stands for a command needing the shared entry (an + /// `act:` click on `/account ` or `/status`) enters through it too. + pub fn selection_needs_shared_entry(selection: Option<&ChoiceReply>) -> bool { + selection + .and_then(|reply| reply.data.strip_prefix("act:")) + .and_then(button_action_command) + .is_some_and(|command| Self::inbound_needs_shared_entry(&command)) + } + + /// `/status` — routed through the shared entry so its account-usage asks + /// run without the gateway lock (#234). + fn is_status_command(text: &str) -> bool { + text.split_whitespace().next() == Some("/status") } /// True when `text` is one of the gateway-owned slash commands. @@ -6026,6 +6203,31 @@ impl Gateway { selection: Option<&ChoiceReply>, ) -> Result> { let chat = ChatKey::new(channel, chat_id, user_id).with_thread(thread); + // A button standing for a shared-entry command runs exactly as if it + // had been typed — through this entry, not the inline one. + if let Some(command) = selection + .and_then(|reply| reply.data.strip_prefix("act:")) + .and_then(button_action_command) + .filter(|command| Self::inbound_needs_shared_entry(command)) + { + return Box::pin(Self::handle_message_shared( + gateway, + channel, + chat_id, + user_id, + thread, + message_id, + &command, + &[], + None, + )) + .await; + } + // `/account` lists accounts (cswap runs) and switches through the + // per-sid claim: both without the gateway lock (#236). + if let Some(result) = Self::handle_account_command_shared(&gateway, &chat, text).await { + return result; + } // `/stop` before anything else: it is the one gateway command that has // to take a per-child claim, which means it cannot run inside a // `&mut Gateway` (issue #197 E). Handled here, where the lock can be @@ -6033,6 +6235,21 @@ impl Gateway { if let Some(result) = Self::handle_stop_command_shared(&gateway, &chat, text).await { return result; } + // `/status` asks live sessions for their account windows — vendor + // I/O that must not run under the daemon-wide lock (#234). Ask here + // with the lock dropped and park the answer for the render below. + if Self::is_status_command(text) { + let probes = crate::latency::gateway_lock(&gateway, "im.status.probes") + .await + .status_usage_probes(&chat); + if let Some((vendor, probes)) = probes { + let usage = probes.resolve().await.remove(vendor_str(vendor)); + crate::latency::gateway_lock(&gateway, "im.status.prefetch") + .await + .status_usage_prefetch + .insert(chat.clone(), (Instant::now(), vendor, usage)); + } + } // Re-derive the "implicit spawn candidate" decision authoritatively // (the daemon's `inbound_may_spawn` call is only a hint to decide // inline-vs-background — this is the one that actually acts). Any @@ -6165,6 +6382,152 @@ impl Gateway { }) } + /// IM `/account [|default]` (#236): show the chat's current Claude + /// session's account and the cswap accounts it can switch to, or switch + /// it. Same rules as the web picker — the switch is + /// [`Self::switch_claude_account_shared`]. cswap discovery and the switch + /// both run without the gateway lock. `None` = not an `/account` message. + async fn handle_account_command_shared( + gateway: &Arc>, + chat: &ChatKey, + text: &str, + ) -> Option>> { + let mut parts = text.split_whitespace(); + if parts.next() != Some("/account") { + return None; + } + let reference = parts.next().map(str::to_string); + Some(Self::account_command(gateway, chat, reference.as_deref()).await) + } + + async fn account_command( + gateway: &Arc>, + chat: &ChatKey, + reference: Option<&str>, + ) -> Result> { + let planned = { + let g = crate::latency::gateway_lock(gateway, "im.account.plan").await; + g.current_session.get(chat).map(|sid| { + let meta = g + .session_catalog + .find_or_load(&sid, &g.projects) + .map(|entry| entry.meta); + ( + sid, + meta, + Arc::clone(&g.cswap_accounts), + g.channel_supports_buttons(&chat.channel), + ) + }) + }; + let Some((sid, meta, service, buttons)) = planned else { + return Ok(vec![ + "这里现在没有会话 —— 发条消息或 /new claude 开一个,再用 /account".to_string(), + ]); + }; + let Some(meta) = meta else { + return Ok(vec![format!("找不到会话 {sid} 的记录")]); + }; + let local = meta.host.trim().is_empty() || meta.host == ccteam_core::LOCAL_HOST; + if meta.vendor != AgentVendor::Claude + || meta.protocol != SessionProtocol::StreamJson + || !local + { + return Ok(vec![format!( + "会话 {sid} 不是本机 Claude stream-json 会话,不能用 cswap 账号" + )]); + } + let bound = meta + .claude_account + .as_ref() + .map(|binding| binding.display()); + + let Some(reference) = reference else { + let listed = service.accounts().await; + let text = render_account_list(&sid, bound.as_ref(), &listed, !buttons); + let accounts = listed.unwrap_or_default(); + if buttons && !accounts.is_empty() { + let current = bound.as_ref().filter(|b| !b.active).map(|b| b.id.as_str()); + let mark = |on: bool| if on { " ✓" } else { "" }; + let mut options = vec![action_option( + "account:default", + &format!("默认登录{}", mark(current.is_none())), + OptionWeight::Normal, + )]; + options.extend(accounts.iter().map(|account| { + action_option( + &format!("account:{}", account.slot), + &format!( + "{}{}", + ccteam_harness::execution::claude_accounts::display_name(account), + mark(current == Some(account.id.as_str())) + ), + OptionWeight::Normal, + ) + })); + crate::latency::gateway_lock(gateway, "im.account.picker") + .await + .emit_list_options(chat, text, options); + return Ok(Vec::new()); + } + return Ok(vec![text]); + }; + + let target = if matches!(reference, "default" | "默认" | "默认登录") { + None + } else { + let accounts = match service.accounts().await { + Ok(accounts) => accounts, + Err(error) => { + return Ok(vec![format!( + "cswap 不可用,没有切换:{error:#}\n回默认登录不需要 cswap:/account default" + )]) + } + }; + match ccteam_harness::execution::claude_accounts::find_account(&accounts, reference) { + Some(account) => Some(account.clone()), + None => { + return Ok(vec![format!( + "没有编号或名字为「{reference}」的账号 —— /account 看列表" + )]) + } + } + }; + let name = |account: Option<&ccteam_harness::execution::claude_accounts::CswapAccount>| { + account.map_or_else( + || "默认登录".to_string(), + ccteam_harness::execution::claude_accounts::display_name, + ) + }; + use ClaudeAccountSwitchError as SwitchError; + let reply = match Self::switch_claude_account_shared(gateway, &sid, target).await { + Ok(switch) if !switch.changed => { + format!( + "会话 {sid} 已经在用 {}", + name(switch.claude_account.as_ref()) + ) + } + Ok(switch) => format!( + "已把会话 {sid} 切到 {}{}", + name(switch.claude_account.as_ref()), + if switch.released { + ";当前进程已结束,下一条消息在同一会话里按新账号继续(提示缓存会重建)" + } else { + ",下一条消息起生效" + } + ), + Err( + error @ (SwitchError::Busy(_) + | SwitchError::Refused(_) + | SwitchError::Unsupported(_)), + ) => format!("没有切换:{error}"), + Err(SwitchError::UnknownSession(_)) => format!("找不到会话 {sid}"), + Err(SwitchError::Internal(error)) => return Err(error), + }; + let g = crate::latency::gateway_lock(gateway, "im.account.next_step").await; + Ok(g.reply_with_next_step(chat, reply, command_next_step("/account"))) + } + async fn handle_command(&mut self, chat: &ChatKey, text: &str) -> Result> { let trimmed = text.trim(); if !trimmed.starts_with('/') { @@ -6181,8 +6544,17 @@ impl Gateway { role, permission_mode, protocol, - tuning, + mut tuning, } = parse_new_command_args(&args)?; + if vendor == AgentVendor::Claude && tuning.claude_account.is_none() { + tuning.claude_account = self + .current_session + .get(chat) + .and_then(|sid| self.session_catalog.find_or_load(&sid, &self.projects)) + .and_then(|entry| entry.meta.claude_account) + .filter(|binding| !binding.default_login) + .map(|binding| binding.id); + } let project = self.require_current_project(chat)?; let handle = role.clone(); let outcome = self @@ -6284,6 +6656,11 @@ impl Gateway { ), })) } + "/account" => Ok(Some( + "/account must be routed through the shared entry point (cswap discovery and \ + the switch run without the gateway lock)" + .to_string(), + )), "/interrupt" => { // Interrupt the session's CURRENTLY-RUNNING turn WITHOUT // destroying it — the context survives, so the user can then @@ -6378,7 +6755,14 @@ impl Gateway { Ok(Some(text)) } } - "/status" => Ok(Some(self.render_status(chat).await)), + "/status" => { + let prefetched = self + .status_usage_prefetch + .remove(chat) + .filter(|(at, _, _)| at.elapsed() < STATUS_USAGE_PREFETCH_TTL) + .map(|(_, vendor, usage)| (vendor, usage)); + Ok(Some(self.render_status_with(chat, prefetched).await)) + } "/mcp" => self.rebuild_tool_surface(chat).await.map(Some), "/projects" => { // Button-capable channel (Telegram) → a text header + one inline @@ -7608,6 +7992,18 @@ impl Gateway { // v0.8.24 A-U3 — an explicit composer choice beats the role's // `model:` frontmatter; effort has no role-level default. let tuning = tuning.normalized(); + let claude_account = tuning + .claude_account + .map(|id| { + if vendor != AgentVendor::Claude + || protocol != SessionProtocol::StreamJson + || host != ccteam_core::LOCAL_HOST + { + return Err(CswapAccountUnsupported.into()); + } + ccteam_harness::execution::claude_accounts::ClaudeAccountBinding::requested(id) + }) + .transpose()?; let model_id = tuning.model.or_else(|| { // Pi owns a vendor-specific `pi.model` frontmatter key. Passing // the generic role model through SpawnCtx would make it look like @@ -7669,6 +8065,7 @@ impl Gateway { .tenant_project_owner(&project) .unwrap_or_else(|| canonical_owner(&reply_to)); Ok(NewSessionPlan { + claude_account, generation, id, owner, @@ -7768,6 +8165,7 @@ impl Gateway { role: plan.role.clone(), }, &SpawnCtx { + claude_account: plan.claude_account.clone(), generation: plan.generation, slug: plan.project.clone(), sid: plan.id.clone(), @@ -7810,6 +8208,12 @@ impl Gateway { } }); let mut meta = SessionMeta { + claude_account: thread + .raw_extras + .get("claude_account") + .filter(|value| !value.is_null()) + .and_then(|value| serde_json::from_value(value.clone()).ok()) + .or_else(|| plan.claude_account.clone()), model_pinned_generation: None, managed_by: Default::default(), stopped_at: None, @@ -7872,6 +8276,7 @@ impl Gateway { let meta = prepared_meta.unwrap_or_else(|| Self::meta_for_new_session(&plan, &thread, trigger)); let NewSessionPlan { + claude_account: _, generation, id, owner, @@ -8060,6 +8465,20 @@ impl Gateway { )); } }; + let claude_account = self + .session_catalog + .find_or_load(&sid, &self.projects) + .and_then(|entry| entry.meta.claude_account); + if claude_account.is_none() + && old_thread + .raw_extras + .get("claude_account") + .is_some_and(|value| !value.is_null()) + { + return Err(anyhow!( + "session account metadata is unavailable; the current process was kept" + )); + } // Tear down the old pane + its event pump before re-spawning so the // same-sid pane is recreated cleanly and no stale pump keeps draining // the retired transcript. @@ -8111,6 +8530,7 @@ impl Gateway { model_id.clone(), effort.clone(), mode.clone(), + claude_account, permission_mode, secret.clone(), &host, @@ -11122,6 +11542,11 @@ impl Gateway { let host = s.host.clone(); let permission_mode = s.permission_mode; let secret = s.secret.clone(); + let had_account = s + .thread + .raw_extras + .get("claude_account") + .is_some_and(|value| !value.is_null()); let fenced_generation = s.generation; // Sync a possibly-registered-after-start project from the config.yaml // SoT before the lookup (mirrors start_session / `/role`). @@ -11139,6 +11564,19 @@ impl Gateway { .find_or_load(session_id, &self.projects) .map(|entry| entry.meta); let mode = meta.as_ref().and_then(|m| m.mode.clone()); + let claude_account = meta.as_ref().and_then(|meta| meta.claude_account.clone()); + if had_account && claude_account.is_none() { + return Err(anyhow!( + "session account metadata is unavailable; refusing to resume with default login" + )); + } + if claude_account.is_some() + && (vendor != AgentVendor::Claude + || protocol != SessionProtocol::StreamJson + || host != ccteam_core::LOCAL_HOST) + { + return Err(CswapAccountUnsupported.into()); + } let (model_id, effort) = respawn_tuning( &cwd, session_id, @@ -11160,6 +11598,7 @@ impl Gateway { // apply installs this same value on the live entry (issue #14②). let generation = self.next_live_generation(); Ok(Some(ResumeDeadPlan { + claude_account, session_id: session_id.to_string(), project, role, @@ -11204,6 +11643,7 @@ impl Gateway { role: plan.role.clone(), }, &SpawnCtx { + claude_account: plan.claude_account.clone(), generation: plan.generation, slug: plan.project.clone(), sid: plan.session_id.clone(), @@ -11233,6 +11673,7 @@ impl Gateway { thread: ThreadHandle, ) -> Result<()> { let ResumeDeadPlan { + claude_account: _, session_id, project, role, @@ -11333,6 +11774,7 @@ impl Gateway { effort: Option, // Replayed from `meta.mode`, same contract. mode: Option, + claude_account: Option, permission_mode: PermissionMode, secret: String, host: &str, @@ -11364,6 +11806,7 @@ impl Gateway { role: role.to_string(), }, &SpawnCtx { + claude_account, generation, slug: slug.to_string(), sid: sid.to_string(), @@ -13243,7 +13686,14 @@ impl Gateway { /// released case stopped after the resume line, silently dropping the /// account-usage row and the `/sessions` + `/projects` footer. There is /// no second renderer any more.) - async fn render_status(&self, chat: &ChatKey) -> String { + /// The `/status` card. `prefetched` is the focus vendor's account usage + /// already asked outside the lock by the shared IM entry (#234); `None` + /// (or a prefetch for another vendor, the focus having moved) asks here. + async fn render_status_with( + &self, + chat: &ChatKey, + prefetched: Option<(AgentVendor, Option)>, + ) -> String { let mut memo = ProjectPrincipalMemo::new(); let visible: Vec<&GatewaySession> = self .sessions @@ -13293,7 +13743,38 @@ impl Gateway { }; } }; - self.status_card(chat, &focus, &visible).await.render() + self.status_card(chat, &focus, &visible, prefetched) + .await + .render() + } + + /// Who `/status` would ask for its focus vendor's account, focus first — + /// the same order [`Gateway::status_card`] uses. `None` when the chat has + /// no focus (that card shows no usage). Captured under the lock, resolved + /// without it by [`Gateway::handle_message_shared`]. + fn status_usage_probes(&self, chat: &ChatKey) -> Option<(AgentVendor, AccountUsageProbes)> { + let mut memo = ProjectPrincipalMemo::new(); + let visible: Vec<&GatewaySession> = self + .sessions + .values() + .filter(|s| self.chat_can_access_with(chat, s, &mut memo)) + .collect(); + let sid = self.current_session.get(chat)?; + if let Some(focus) = visible.iter().copied().find(|s| s.id == sid) { + let vendor = focus.vendor; + let askers: Vec<&GatewaySession> = std::iter::once(focus) + .chain(visible.iter().copied().filter(|s| s.id != focus.id)) + .collect(); + return Some(( + vendor, + self.account_usage_probes_from(Some(vendor), &askers), + )); + } + let (_, meta) = self.released_focus(chat, &sid, &mut memo)?; + Some(( + meta.vendor, + self.account_usage_probes_from(Some(meta.vendor), &visible), + )) } /// The `/status` focus when the chat's current sid is one ccteam holds no @@ -13316,98 +13797,45 @@ impl Gateway { .then_some((slug, meta)) } - /// The vendor account's rate-limit windows — the ONE way any surface asks - /// for them, and the reason a `/status` card no longer has to care whether - /// its session is resident. - /// - /// Usage is ACCOUNT-scoped but only READABLE through a live session, so it - /// used to exist only while some process happened to be resident: the card - /// went scavenging through whatever sessions were alive and simply showed - /// nothing when none were — which is exactly when the focused session has - /// been idle-released (2026-08-30 IM report: the `⚡ 用量` row vanished from - /// a released card, and after a daemon restart from every card). - /// - /// So the fact gets a home. Any live session of `vendor` is asked (they all - /// report the same account, so the first answer wins) and what it says is - /// recorded; when none answers, the vendor's last observation is read back - /// from [`ccteam_harness::usage_catalog`], which drops each window at the - /// vendor's own declared reset so nothing stale is ever presented as - /// current. Callers get one `Option` and never branch on residency. - /// - /// `sessions` is the caller's ACL-scoped set (unchanged from the live-only - /// read this replaces); the catalog is keyed by vendor alone, which is the - /// same host-agnostic scope that read already had. - async fn account_usage_for( - &self, - vendor: AgentVendor, - sessions: &[&GatewaySession], - ) -> Option { - self.account_usage_entry_for(vendor, sessions) - .await - .map(|entry| entry.usage) - } - - /// [`Gateway::account_usage_for`] plus the PROVENANCE of the answer (when - /// it was observed, and what observed it). + /// Capture who to ask for each vendor's account windows — every live + /// session, or only `vendor`'s. The ONE way any surface reads account + /// usage (IM `/status`, MCP `status{detail:"usage"}`, the hook phase, + /// `GET /api/v1/usage`): take this under the gateway lock, drop the lock, + /// then [`AccountUsageProbes::resolve`] (#234). /// - /// The IM card renders one line and has nowhere to put "as of when", but a - /// machine-readable surface must publish it: a scheduler deciding whom to - /// hire needs to know whether a 92% weekly window was read a minute ago or - /// is a cached snapshot from an hour ago. So this is the primitive and the - /// percentage-only accessor above is its projection — one live-ask path, - /// one cache path, one expiry rule, two shapes. - async fn account_usage_entry_for( - &self, - vendor: AgentVendor, - sessions: &[&GatewaySession], - ) -> Option { - for session in sessions.iter().filter(|s| s.adapter.vendor() == vendor) { - if let Some(usage) = session.adapter.account_usage(&session.thread).await { - self.record_account_usage(vendor, "status card", &usage); - return Some(VendorAccountUsage { - observed_at: chrono::Utc::now().to_rfc3339(), - source: "status card".to_string(), - usage, - }); - } - } - let root = self.state_root.as_deref()?; - ccteam_harness::usage_catalog::last_known_entry_in( - root, - vendor_str(vendor), - chrono::Utc::now(), - ) + /// Usage is ACCOUNT-scoped but only READABLE through a live session; the + /// resolver records each live answer and falls back to the last recorded + /// observation, so callers never branch on residency. Scope is the + /// DAEMON's own vendor accounts (every session of that vendor spends from + /// them), not any one caller's data. + pub fn account_usage_probes(&self, vendor: Option) -> AccountUsageProbes { + let live: Vec<&GatewaySession> = self.sessions.values().collect(); + self.account_usage_probes_from(vendor, &live) } - /// Every vendor whose ACCOUNT ccteam currently knows something about, - /// keyed by vendor token — the one read behind the MCP - /// `status{detail:"usage"}` body and `GET /api/v1/usage`. - /// - /// HONEST ABSENCE: a vendor with no live session and no unexpired - /// observation is simply not in the map. There is no "unknown" row to - /// misread as "plenty left", and no probing engine — the live half asks - /// adapters that already hold the answer in memory (never a turn), the - /// cached half reads [`ccteam_harness::usage_catalog`]. Nothing here polls - /// or schedules; the map is built when a caller asks for it. - /// - /// Scope is the DAEMON's own vendor accounts (every session of that vendor - /// spends from them), not any one caller's data — the same host-agnostic - /// scope the IM `/status` card has always shown. `vendor` narrows it to one. - pub async fn account_usage_snapshot( + /// [`Gateway::account_usage_probes`] over the caller's ACL-scoped, + /// caller-ordered `sessions` (the first answer per vendor wins). + fn account_usage_probes_from( &self, vendor: Option, - ) -> BTreeMap { - let live: Vec<&GatewaySession> = self.sessions.values().collect(); - let mut out = BTreeMap::new(); - for candidate in AgentVendor::ALL.iter().copied() { - if vendor.is_some_and(|want| want != candidate) { - continue; - } - if let Some(entry) = self.account_usage_entry_for(candidate, &live).await { - out.insert(vendor_str(candidate).to_string(), entry); - } + sessions: &[&GatewaySession], + ) -> AccountUsageProbes { + AccountUsageProbes { + root: self.state_root.clone(), + by_vendor: AgentVendor::ALL + .iter() + .copied() + .filter(|candidate| vendor.is_none_or(|want| want == *candidate)) + .map(|candidate| { + let askers = sessions + .iter() + .filter(|s| s.adapter.vendor() == candidate) + .map(|s| (Arc::clone(&s.adapter), s.thread.clone())) + .collect(); + (candidate, askers) + }) + .collect(), } - out } /// Persist one account-usage observation. Best-effort by construction: a @@ -13462,6 +13890,7 @@ impl Gateway { chat: &ChatKey, focus: &SessionRowSource<'_>, visible: &[&GatewaySession], + prefetched: Option<(AgentVendor, Option)>, ) -> StatusCard { let slug = focus.slug_of(&self.default_project).to_string(); let sid = focus.sid().to_string(); @@ -13486,7 +13915,29 @@ impl Gateway { } SessionRowSource::Released(..) => (StatusRunState::Released, Vec::new(), None), }; - let account = self.account_usage_for(vendor, visible).await; + // A resident focus is asked FIRST: the card describes the account THIS + // session spends from. Every live process of a vendor normally reports + // the same account, but not across a login switch — a process started + // before it can still be signed in as the old account — and `visible` + // has no stable order, so "first answer wins" over it alone could show + // either account and flip between them from one `/status` to the next. + let askers: Vec<&GatewaySession> = match focus { + SessionRowSource::Resident(s) => std::iter::once(*s) + .chain(visible.iter().copied().filter(|v| v.id != s.id)) + .collect(), + SessionRowSource::Released(..) => visible.to_vec(), + }; + // Asked outside the lock when the shared IM entry prefetched it; the + // inline path asks here, bounded by one deadline for all askers. + let account = match prefetched { + Some((asked, usage)) if asked == vendor => usage, + _ => self + .account_usage_probes_from(Some(vendor), &askers) + .resolve() + .await + .remove(vendor_str(vendor)), + } + .map(|entry| entry.usage); // The ledger half — title / turn / cost / tokens and the spawn-time // model + effort picks — lives in `meta.json` for both residencies: @@ -13569,7 +14020,12 @@ impl Gateway { .count(); let visible_projects = self.visible_project_slugs(chat).len(); + let claude_account = meta + .as_ref() + .and_then(|m| m.claude_account.as_ref()) + .map(|binding| binding.display()); StatusCard { + claude_account, title: meta.and_then(|m| m.title), // Project working-tree PATH — resolved from the loaded project map // (slug → dir) for both residencies; omitted if the project isn't @@ -13719,6 +14175,10 @@ impl Gateway { .map(|guard| guard.pending_for_sid(&s.id).is_some()) .unwrap_or(false); SessionView { + claude_account: meta + .as_ref() + .and_then(|meta| meta.claude_account.as_ref()) + .map(|account| account.display()), sid: s.id.clone(), project: s.project.clone(), role: s.role.clone(), @@ -14235,6 +14695,7 @@ impl Gateway { let now = chrono::Utc::now().to_rfc3339(); let owner_tag = canonical_owner(&caller).identity(); let mut meta = SessionMeta { + claude_account: None, model_pinned_generation: None, managed_by: Default::default(), stopped_at: None, @@ -14339,6 +14800,7 @@ impl Gateway { let sid = format!("s{}", guard.next_session); let now = chrono::Utc::now().to_rfc3339(); let mut meta = SessionMeta { + claude_account: None, model_pinned_generation: None, managed_by: Default::default(), stopped_at: None, @@ -14582,6 +15044,21 @@ impl Gateway { } } + /// The cswap discovery service; the web state shares it (one cache). + pub fn cswap_accounts( + &self, + ) -> Arc { + Arc::clone(&self.cswap_accounts) + } + + /// Replace the cswap discovery service (tests inject a fixed list). + pub fn set_cswap_accounts( + &mut self, + service: Arc, + ) { + self.cswap_accounts = service; + } + /// Handle to the `(sid, secret)` registry, so a front door can verify a /// principal WITHOUT taking this gateway's lock. That independence is /// load-bearing, not an optimization: a spawn path may hold the gateway @@ -15037,6 +15514,21 @@ impl Gateway { let Some((slug, adapter, thread)) = fenced else { return Ok(false); }; + Self::finish_release_shared(gateway, sid, slug, adapter, thread, reason).await?; + Ok(true) + } + + /// The part of a release after the session is fenced out of the live map: + /// every caller (both residency policies and an account switch) ends a + /// process the same way. + async fn finish_release_shared( + gateway: &Arc>, + sid: &str, + slug: String, + adapter: Arc, + thread: ThreadHandle, + reason: ReleaseReason, + ) -> Result<()> { // Last chance to read an ACCOUNT-scoped fact from this session: the // windows belong to the vendor account, not to the process, so they are // captured before the process that can report them goes away. Without @@ -15071,7 +15563,186 @@ impl Gateway { .await .emit_session_evicted(sid, &slug, reason); tracing::info!(sid, %slug, reason = reason.as_str(), "ccteam-im: released session"); - Ok(true) + Ok(()) + } + + /// Move a session to another cswap account, or back to the default login + /// (#236). Only the binding changes — the sid, its focus routes and its + /// history stay — and a resident process is released exactly like an + /// idle release, so the next message resumes the SAME sid under the new + /// account (the vendor prompt cache is rebuilt, as any account change + /// requires). A user-explicit command, never a daemon decision. + /// + /// Refused, with nothing changed, while the process is mid-turn, waiting + /// on the user or running background work, and whenever the transcript + /// would not be readable from the new account (history still private to + /// the current account's profile): resuming there would silently start + /// the conversation over. + pub async fn switch_claude_account_shared( + gateway: &Arc>, + sid: &str, + target: Option, + ) -> std::result::Result { + use ccteam_harness::execution::claude_accounts::{ + history_follows_switch, ClaudeAccountBinding, + }; + let next = match &target { + Some(account) => { + let mut binding = ClaudeAccountBinding::requested(account.id.clone()) + .map_err(|error| ClaudeAccountSwitchError::Refused(error.to_string()))?; + // Display only until the launch confirms the profile; the + // spawn re-resolves the slot from the identity. + binding.slot = account.slot.clone(); + binding.label = account.label.clone(); + Some(binding) + } + None => None, + }; + // The per-sid claim every lock-free resume takes (acquired before the + // gateway lock): a cold start planned from the OLD binding can neither + // overlap this switch nor land after it and overwrite it. + let claims = Arc::clone(&gateway.lock().await.spawn_claims); + let _claim = claims.lock_for_sid(sid).await; + + let (slug, cwd, meta, live) = { + let guard = gateway.lock().await; + let (slug, cwd, meta) = guard + .find_meta_for_sid(sid) + .map_err(|_| ClaudeAccountSwitchError::UnknownSession(sid.to_string()))?; + if meta.managed_by == ccteam_harness::execution::session_meta::ManagedBy::External { + return Err(ClaudeAccountSwitchError::Refused( + "this agent was started by hand; ccteam does not launch it".into(), + )); + } + let host = guard.ensure_session_host_binding(&slug, &meta.host)?.0; + if meta.vendor != AgentVendor::Claude + || meta.protocol != SessionProtocol::StreamJson + || host != ccteam_core::LOCAL_HOST + { + return Err(CswapAccountUnsupported.into()); + } + if guard.detached.contains_key(sid) { + return Err(ClaudeAccountSwitchError::Busy( + "this session's process from before the daemon restart is still running; \ + interrupt or stop it first" + .into(), + )); + } + let live = guard + .sessions + .get(sid) + .map(|s| (s.generation, Arc::clone(&s.adapter), s.thread.clone())); + (slug, cwd, meta, live) + }; + let current = meta.claude_account.clone(); + let unchanged = match (¤t, &next) { + (None, None) => true, + (Some(current), None) => current.default_login, + (Some(current), Some(next)) => !current.default_login && current.id == next.id, + (None, Some(_)) => false, + }; + if unchanged { + return Ok(ClaudeAccountSwitch { + claude_account: current.as_ref().map(ClaudeAccountBinding::display), + changed: false, + released: false, + }); + } + + // Slow checks without the gateway lock: an adapter round-trip and fs. + if let Some((_, adapter, thread)) = &live { + if adapter + .running_tasks(thread) + .await + .iter() + .any(|task| task.outlives_turn()) + { + return Err(ClaudeAccountSwitchError::Busy( + "background work is still running in this session; wait for it or stop it \ + first" + .into(), + )); + } + } + let uuid = if meta.vendor_uuid.is_empty() { + ccteam_harness::execution::claude_stream_json::spawn_spec::deterministic_session_uuid( + &slug, sid, + ) + } else { + meta.vendor_uuid.clone() + }; + let (history_cwd, from) = (cwd.clone(), current.clone()); + let portable = tokio::task::spawn_blocking(move || { + history_follows_switch(&history_cwd, &uuid, from.as_ref()) + }) + .await + .unwrap_or(false); + if !portable { + return Err(ClaudeAccountSwitchError::Refused( + "this conversation's history is still private to the current account's profile. \ + cswap moves it into the shared history the next time this session runs on that \ + account while no other Claude uses it; switch after that" + .into(), + )); + } + + let fenced = { + let mut guard = gateway.lock().await; + let generation = guard.sessions.get(sid).map(|s| s.generation); + if generation != live.as_ref().map(|(generation, ..)| *generation) { + return Err(ClaudeAccountSwitchError::Busy( + "the session just started or stopped; try again".into(), + )); + } + if let Some(session) = guard.sessions.get(sid) { + let in_flight = session + .turn_started_at + .lock() + .map(|started| started.is_some()) + .unwrap_or(true); + if in_flight { + return Err(ClaudeAccountSwitchError::Busy( + "a turn is running; wait for it to finish or interrupt it first".into(), + )); + } + } + if guard.pending.lock().await.pending_for_sid(sid).is_some() { + return Err(ClaudeAccountSwitchError::Busy( + "the session is waiting for your decision; answer it first".into(), + )); + } + // Re-read under the lock so a concurrent rename is not lost. + let mut meta = guard + .session_catalog + .find_or_load(sid, &guard.projects) + .map(|entry| entry.meta) + .ok_or_else(|| ClaudeAccountSwitchError::UnknownSession(sid.to_string()))?; + meta.claude_account = next.clone(); + guard.persist_session_meta(&cwd, &meta)?; + let fenced = generation.and_then(|generation| guard.fence_out_session(sid, generation)); + if fenced.is_none() { + guard.emit_session_account_changed(sid, &slug); + } + fenced + }; + let released = fenced.is_some(); + if let Some((slug, adapter, thread)) = fenced { + Self::finish_release_shared( + gateway, + sid, + slug, + adapter, + thread, + ReleaseReason::AccountSwitch, + ) + .await?; + } + tracing::info!(sid, %slug, released, "ccteam-im: switched Claude account"); + Ok(ClaudeAccountSwitch { + claude_account: next.as_ref().map(ClaudeAccountBinding::display), + changed: true, + released, + }) } /// How long a releasing session may take to report its account usage @@ -15611,6 +16282,23 @@ impl Gateway { tuning, )?; plan.remote = host_target.remote; + if plan.vendor == AgentVendor::Claude && plan.claude_account.is_none() { + if let Some(binding) = parent_sid + .as_ref() + .and_then(|sid| self.session_catalog.find_or_load(sid, &self.projects)) + .and_then(|entry| entry.meta.claude_account) + .filter(|account| !account.default_login) + { + if plan.protocol != SessionProtocol::StreamJson + || plan.host != ccteam_core::LOCAL_HOST + { + anyhow::bail!( + "inherited cswap account requires a local Claude stream-json session" + ); + } + plan.claude_account = Some(binding); + } + } plan.parent_sid = parent_sid.clone(); plan.spawned_by_role = spawned_by_role; plan.delegation_depth = child_depth; @@ -15780,6 +16468,23 @@ impl Gateway { tuning, )?; plan.remote = host_target.remote; + if plan.vendor == AgentVendor::Claude && plan.claude_account.is_none() { + if let Some(binding) = parent_sid + .as_ref() + .and_then(|sid| guard.session_catalog.find_or_load(sid, &guard.projects)) + .and_then(|entry| entry.meta.claude_account) + .filter(|account| !account.default_login) + { + if plan.protocol != SessionProtocol::StreamJson + || plan.host != ccteam_core::LOCAL_HOST + { + anyhow::bail!( + "inherited cswap account requires a local Claude stream-json session" + ); + } + plan.claude_account = Some(binding); + } + } plan.parent_sid = parent_sid.clone(); plan.spawned_by_role = spawned_by_role; plan.delegation_depth = child_depth; @@ -18875,6 +19580,7 @@ impl Gateway { self.persist_session_meta(&dir, &meta)?; let target = SessionTitleTarget { + claude_account: meta.claude_account.clone(), sid: sid.to_string(), vendor_uuid: meta.vendor_uuid.clone(), project_dir: dir, @@ -18904,6 +19610,29 @@ impl Gateway { /// twin is `meta.json` itself, already written by the caller). Same frame /// family as [`Self::emit_session_evicted`], so the SPA's existing /// `session_lifecycle` listener refreshes the rail with no client change. + /// Lifecycle twin of an account switch on a session with no resident + /// process (a released one emits `evicted` instead); refreshes the rail + /// and the session header like a rename. + fn emit_session_account_changed(&self, sid: &str, slug: &str) { + self.emit_user_signal(GatewayEvent { + interim: false, + id: format!("session-account-{sid}"), + channel: String::new(), + chat_id: String::new(), + thread_ts: None, + content: format!("session account changed: {sid}"), + kind: GatewayEventKind::SessionLifecycle { + state: "account_changed".to_string(), + reason: "user".to_string(), + }, + attachments: Vec::new(), + options: Vec::new(), + status: None, + sid: Some(sid.to_string()), + slug: Some(slug.to_string()), + }); + } + fn emit_session_renamed(&self, sid: &str, slug: &str) { self.emit_user_signal(GatewayEvent { interim: false, @@ -18959,6 +19688,9 @@ fn detached_body_view( ) -> SessionView { let m = |f: &dyn Fn(&SessionMeta) -> String| meta.map(f).unwrap_or_default(); SessionView { + claude_account: meta + .and_then(|meta| meta.claude_account.as_ref()) + .map(|account| account.display()), sid: d.sid.clone(), project: d.slug.clone(), role: m(&|m| m.role.clone()), @@ -19137,6 +19869,10 @@ fn released_session_view( current: &std::collections::HashSet, ) -> SessionView { SessionView { + claude_account: meta + .claude_account + .as_ref() + .map(|account| account.display()), sid: meta.sid.clone(), project: slug.to_string(), role: meta.role.clone(), @@ -19180,6 +19916,10 @@ fn external_node_view(meta: &SessionMeta) -> SessionView { .max(0) as u64 }); SessionView { + claude_account: meta + .claude_account + .as_ref() + .map(|account| account.display()), sid: meta.sid.clone(), project: meta.slug.clone(), role: String::new(), @@ -19275,6 +20015,92 @@ fn activity_marker(activity: &str) -> &'static str { /// leading `s` token counts as a TARGET only when a title follows it, so /// `/rename s3` still titles the current session `s3` rather than trying to /// rename `s3` to nothing. Pure — unit-tested directly. +/// The IM `/account` listing (#236): which account the session runs on — a +/// default-login session names the account that login is right now — then +/// every cswap account with its quota windows. `typed` adds the commands to +/// type; a button channel offers buttons instead. +fn render_account_list( + sid: &str, + bound: Option<&ccteam_harness::execution::claude_accounts::CswapAccount>, + listed: &Result>, + typed: bool, +) -> String { + use ccteam_harness::execution::claude_accounts::display_name; + let accounts = listed.as_ref().map(Vec::as_slice).unwrap_or_default(); + let pinned = bound.filter(|account| !account.active); + let current = match pinned { + Some(account) => display_name(account), + None => match accounts.iter().find(|account| account.active) { + Some(default) => format!("默认登录(此刻是 {},跟随 cswap auto)", display_name(default)), + None => "默认登录".to_string(), + }, + }; + let mut out = format!("👤 会话 {sid} · Claude 账号:{current}"); + match listed { + Err(error) => { + out.push_str(&format!("\ncswap 不可用:{error:#}")); + if pinned.is_some() && typed { + out.push_str("\n回默认登录:/account default"); + } + return out; + } + Ok(accounts) if accounts.is_empty() => { + out.push_str("\ncswap 里还没有账号"); + return out; + } + Ok(_) => {} + } + out.push_str("\n可切换的账号:"); + for account in accounts { + let mut line = format!("\n {}", display_name(account)); + let quota = account_quota_text(account); + if !quota.is_empty() { + line.push_str(&format!(" {quota}")); + } + if account.active { + line.push_str(" (当前默认)"); + } + if pinned.is_some_and(|bound| bound.id == account.id) { + line.push_str(" ✓"); + } + out.push_str(&line); + } + if typed { + out.push_str("\n切换:/account <编号> 回默认登录:/account default"); + } + out.push_str("\n切换会结束当前进程,下一条消息在同一会话里按新账号继续。"); + out +} + +/// `5h 11% · 7d 100%`, a plan without a 5h window shows only 7d, no reading +/// shows cswap's status (`需重新登录`); a non-ok status beside numbers marks +/// them as cswap's last good reading. +fn account_quota_text( + account: &ccteam_harness::execution::claude_accounts::CswapAccount, +) -> String { + let status = account.usage_status.as_deref().map(|status| match status { + "relogin_required" => "需重新登录", + "token_expired" => "令牌过期", + "no_credentials" => "无凭据", + "keychain_unavailable" => "钥匙串不可用", + "foreign_credential" => "凭据不符", + "unavailable" => "额度暂不可读", + other => other, + }); + let windows: Vec = [("5h", account.five_hour_pct), ("7d", account.seven_day_pct)] + .into_iter() + .filter_map(|(window, pct)| pct.map(|pct| format!("{window} {pct}%"))) + .collect(); + if windows.is_empty() { + return status.unwrap_or_default().to_string(); + } + let mut text = windows.join(" · "); + if status.is_some() { + text.push_str("(上次)"); + } + text +} + fn split_leading_sid(rest: &str) -> Option<(&str, &str)> { let (head, tail) = rest.split_once(char::is_whitespace)?; let looks_like_sid = head @@ -20762,6 +21588,9 @@ struct StatusCard { /// finish. `None` when the channel cannot report it. stop_hook_blocks: Option, account: Option, + /// The cswap account a Claude session is bound to (#236); `None` for an + /// unbound session (`/account` names what its default login is). + claude_account: Option, children: Vec, /// Descendants below the direct children, collapsed to a count. deeper_descendants: usize, @@ -20811,6 +21640,16 @@ impl StatusCard { if !self.role.is_empty() { identity.push_str(&format!(" · {}", self.role)); } + if let Some(account) = &self.claude_account { + if account.active { + identity.push_str(" · 👤 默认登录"); + } else { + identity.push_str(&format!( + " · 👤 {}", + ccteam_harness::execution::claude_accounts::display_name(account) + )); + } + } let mut out = format!("{head}\n📍 {second}\n {identity}"); // Project working-tree PATH — disambiguates an auto-appended slug @@ -21387,6 +22226,7 @@ fn parse_new_command_args(args: &[&str]) -> Result { "model" | "m" => tuning.model = Some(value.to_string()), "effort" | "e" => tuning.effort = Some(value.to_string()), "mode" => tuning.mode = Some(value.to_string()), + "claude_account" => tuning.claude_account = Some(value.to_string()), other => { return Err(anyhow!( "/new: unknown option `{other}=` (accepts model= / m=, effort= / e=, mode=)\nsyntax: {NEW_COMMAND_SYNTAX}" @@ -21579,6 +22419,7 @@ mod tests { assert_eq!( parsed.tuning, SpawnTuning { + claude_account: None, mode: None, model: Some("kimi-code/k3".to_string()), effort: Some("max".to_string()), @@ -22076,6 +22917,91 @@ mod tests { assert_eq!(fake.starts.load(Ordering::SeqCst), 2); } + /// #234 — `/status` asked every live session for account usage one after + /// another while holding the daemon-wide gateway lock (3 s each), so a + /// slow vendor answer held web, IM and MCP for up to a minute. The asks + /// now share one deadline and run concurrently, and the shared IM entry + /// runs them with the lock dropped. + #[tokio::test] + async fn status_usage_asks_run_concurrently_and_outside_the_gateway_lock() { + let tmp = tempfile::tempdir().unwrap(); + let alpha = tmp.path().join("alpha"); + std::fs::create_dir_all(&alpha).unwrap(); + let fake = Arc::new(FakeAdapter::default()); + let mut gateway = Gateway::new(fake.clone(), "alpha", alpha.clone()); + for _ in 0..3 { + gateway + .handle_text("mock", "chat-1", "alice", "/new claude") + .await + .unwrap(); + } + fake.set_account_usage_delay(std::time::Duration::from_millis(600)); + let gateway = Arc::new(tokio::sync::Mutex::new(gateway)); + + // Concurrent: the #234 shape — no session has an answer, so every one + // is asked. Three 600 ms asks finish together, not in 1.8 s. + let started = std::time::Instant::now(); + gateway + .lock() + .await + .handle_text("mock", "chat-1", "alice", "/status") + .await + .unwrap(); + assert!( + started.elapsed() < std::time::Duration::from_millis(1400), + "asks ran one after another: {:?}", + started.elapsed() + ); + fake.set_account_usage(Some(AccountUsage { + five_hour_pct: Some(7), + ..Default::default() + })) + .await; + + // Lock-free: while the shared entry is asking, the lock is free. + assert!(Gateway::inbound_needs_shared_entry("/status")); + let shared = Arc::clone(&gateway); + let status = tokio::spawn(async move { + Gateway::handle_message_shared( + shared, + "mock", + "chat-1", + "alice", + None, + "m-1", + "/status", + &[], + None, + ) + .await + }); + tokio::time::sleep(std::time::Duration::from_millis(200)).await; + let waited = std::time::Instant::now(); + drop(gateway.lock().await); + assert!( + waited.elapsed() < std::time::Duration::from_millis(250), + "the usage asks held the gateway lock for {:?}", + waited.elapsed() + ); + let replies = status.await.unwrap().unwrap(); + assert!(replies[0].contains("5h 7%"), "{replies:?}"); + + // Bounded: a stuck vendor costs one deadline, not 3 × its delay. + fake.set_account_usage_delay(std::time::Duration::from_secs(5)); + let started = std::time::Instant::now(); + gateway + .lock() + .await + .handle_text("mock", "chat-1", "alice", "/status") + .await + .unwrap(); + assert!( + started.elapsed() < ACCOUNT_USAGE_DEADLINE + std::time::Duration::from_millis(800), + "a stuck vendor was waited out: {:?}", + started.elapsed() + ); + } + /// `/status` on a focus that points at a released session must render the /// session — the SAME card as a resident one, with `💤 released` in place /// of the run state and the same footer — not "无当前会话". @@ -22264,6 +23190,87 @@ mod tests { ); } + /// 2026-11-06 IM report: after the host's claude login moved from a plan + /// with no 5-hour window (`max`) to one with it (`team`), the `⚡ 用量` row + /// kept showing the old account. Across a login switch two live processes + /// can be signed in as different accounts, so the card must report the + /// account its OWN session spends from — not whichever live session the + /// fleet happens to list first (`s1` here, always, in sid order). + #[tokio::test] + async fn status_reports_the_focused_sessions_own_account() { + let tmp = tempfile::tempdir().unwrap(); + let alpha = tmp.path().join("alpha"); + std::fs::create_dir_all(&alpha).unwrap(); + let fake = Arc::new(FakeAdapter::default()); + let mut gateway = Gateway::new(fake.clone(), "alpha", alpha.clone()); + gateway.enable_persistence(tmp.path()).unwrap(); + for _ in 0..2 { + gateway + .handle_text("mock", "chat-1", "alice", "/new claude") + .await + .unwrap(); + } + let now = chrono::Utc::now(); + let week = Some((now + chrono::Duration::days(3)).to_rfc3339()); + // s1 started before the switch: the old plan, no 5-hour window at all. + fake.set_thread_account_usage( + &gateway.sessions["s1"].thread.identity, + AccountUsage { + subscription: Some("max".into()), + weekly_pct: Some(20), + weekly_resets_at: week.clone(), + ..Default::default() + }, + ); + // s2 started after it: the new plan, with both windows. + fake.set_thread_account_usage( + &gateway.sessions["s2"].thread.identity, + AccountUsage { + subscription: Some("team".into()), + five_hour_pct: Some(34), + five_hour_resets_at: Some((now + chrono::Duration::hours(2)).to_rfc3339()), + weekly_pct: Some(35), + weekly_resets_at: week, + ..Default::default() + }, + ); + let usage_row = |card: &str| { + card.lines() + .find(|line| line.contains("⚡ 用量")) + .unwrap_or_default() + .trim() + .to_string() + }; + + // The focus is s2 (the last `/new`): its own account, both windows. + let card = gateway + .handle_text("mock", "chat-1", "alice", "/status") + .await + .unwrap() + .remove(0); + let row = usage_row(&card); + assert!( + row.starts_with("⚡ 用量: 5h 34% (→") && row.ends_with(" · team"), + "s2's card shows s2's account, not the first-listed s1's: {row}" + ); + + // Back on s1: its own plan — no 5-hour segment, nothing borrowed. + gateway + .handle_text("mock", "chat-1", "alice", "/use s1") + .await + .unwrap(); + let card = gateway + .handle_text("mock", "chat-1", "alice", "/status") + .await + .unwrap() + .remove(0); + let row = usage_row(&card); + assert!( + row.starts_with("⚡ 用量: 周 20% (→") && row.ends_with(" · max"), + "s1's card shows s1's account, with no 5h window: {row}" + ); + } + /// The card layout is one function of the facts: every optional block is /// keyed on its fact being present — never on residency — in this order. /// Locks the shape once so no state-specific twin can drift from it. @@ -22305,6 +23312,7 @@ mod tests { weekly_resets_at: Some("2026-09-03T00:00:00Z".into()), ..Default::default() }), + claude_account: None, children: vec![StatusChild { sid: "s8".into(), vendor: AgentVendor::Codex, @@ -22371,6 +23379,7 @@ mod tests { goal: None, stop_hook_blocks: None, account: None, + claude_account: None, children: Vec::new(), deeper_descendants: 0, same_project_others: 0, @@ -24338,6 +25347,531 @@ mod tests { ); } + #[tokio::test] + async fn cswap_role_switch_never_defaults_after_metadata_loss() { + for corrupt in [false, true] { + let tmp = tempfile::tempdir().unwrap(); + seed_role_with_model(tmp.path(), "reviewer", None); + let fake = Arc::new(FakeAdapter::new(AgentVendor::Claude)); + let mut gateway = Gateway::new(fake.clone(), "alpha", tmp.path()); + let id = ccteam_harness::execution::claude_accounts::account_id("two@example.test", ""); + let created = gateway + .create_session_api_tuned( + "alpha".into(), + String::new(), + AgentVendor::Claude, + PermissionMode::Skip, + SessionProtocol::StreamJson, + "web-api".into(), + SpawnTuning { + claude_account: Some(id.clone()), + ..Default::default() + }, + ) + .await + .unwrap(); + let mut binding = + ccteam_harness::execution::claude_accounts::ClaudeAccountBinding::requested(id) + .unwrap(); + binding.config_dir = Some(tmp.path().join("account-profile")); + gateway + .sessions + .get_mut(&created.sid) + .unwrap() + .thread + .raw_extras["claude_account"] = serde_json::to_value(binding).unwrap(); + let meta_path = ccteam_harness::execution::session_meta::session_meta_path( + tmp.path(), + &created.sid, + ); + if corrupt { + std::fs::write(&meta_path, "invalid-json").unwrap(); + } else { + std::fs::remove_file(&meta_path).unwrap(); + } + gateway.session_catalog = Default::default(); + let started = fake.starts.load(Ordering::SeqCst); + let result = gateway + .switch_current_role( + &ChatKey::new("web", "web-api", "web-api"), + "reviewer".into(), + ) + .await; + assert!( + result.is_err(), + "missing/corrupt account metadata must not trigger a default spawn" + ); + assert_eq!(fake.starts.load(Ordering::SeqCst), started); + assert!(gateway.sessions.contains_key(&created.sid)); + } + } + + fn cswap_account( + slot: &str, + label: &str, + ) -> ccteam_harness::execution::claude_accounts::CswapAccount { + ccteam_harness::execution::claude_accounts::CswapAccount { + id: ccteam_harness::execution::claude_accounts::account_id( + &format!("{label}@example.test"), + "", + ), + slot: slot.into(), + label: label.into(), + active: false, + five_hour_pct: None, + seven_day_pct: None, + usage_status: None, + } + } + + async fn account_session( + tmp: &std::path::Path, + vendor: AgentVendor, + account: Option, + ) -> (Arc, Arc>, String) { + let fake = Arc::new(FakeAdapter::new(AgentVendor::Claude)); + let mut gateway = Gateway::new(fake.clone(), "alpha", tmp); + let created = gateway + .create_session_api_tuned( + "alpha".into(), + String::new(), + vendor, + PermissionMode::Skip, + SessionProtocol::StreamJson, + "web-api".into(), + SpawnTuning { + claude_account: account, + ..Default::default() + }, + ) + .await + .unwrap(); + ( + fake, + Arc::new(tokio::sync::Mutex::new(gateway)), + created.sid, + ) + } + + async fn stored_account( + gateway: &Arc>, + sid: &str, + ) -> Option { + let guard = gateway.lock().await; + guard + .session_catalog + .find_or_load(sid, &guard.projects) + .unwrap() + .meta + .claude_account + } + + /// #236 — a switch rebinds the SAME sid and releases its process; the + /// next resume runs under the new account, and back to the default login. + #[tokio::test] + async fn claude_account_switch_rebinds_the_sid_and_resumes_under_it() { + let tmp = tempfile::tempdir().unwrap(); + let (one, two) = (cswap_account("1", "cloud"), cswap_account("2", "work")); + let (fake, gateway, sid) = + account_session(tmp.path(), AgentVendor::Claude, Some(one.id.clone())).await; + + let same = Gateway::switch_claude_account_shared(&gateway, &sid, Some(one.clone())) + .await + .unwrap(); + assert!( + !same.changed && !same.released, + "the current account is a no-op" + ); + assert!(gateway.lock().await.sessions.contains_key(&sid)); + + let switched = Gateway::switch_claude_account_shared(&gateway, &sid, Some(two.clone())) + .await + .unwrap(); + assert!(switched.changed && switched.released); + let shown = switched.claude_account.unwrap(); + assert_eq!((shown.slot.as_str(), shown.label.as_str()), ("2", "work")); + assert!( + !gateway.lock().await.sessions.contains_key(&sid), + "the process is released, the session is not" + ); + let stored = stored_account(&gateway, &sid).await.unwrap(); + assert_eq!(stored.id, two.id); + assert_eq!( + stored.config_dir, None, + "the next launch confirms the profile" + ); + + Gateway::resume_stopped_session_shared( + Arc::clone(&gateway), + &sid, + "user:web-api", + None, + GatewayDeadline::start(), + ) + .await + .unwrap(); + assert_eq!( + fake.spawn_accounts.lock().await.last().cloned(), + Some(Some(two.id.clone())), + "the same sid resumes under the new account" + ); + + let default = Gateway::switch_claude_account_shared(&gateway, &sid, None) + .await + .unwrap(); + assert!(default.changed && default.released && default.claude_account.is_none()); + assert_eq!(stored_account(&gateway, &sid).await, None); + // Not resident any more: a further switch only rebinds. + let again = Gateway::switch_claude_account_shared(&gateway, &sid, Some(one.clone())) + .await + .unwrap(); + assert!(again.changed && !again.released); + assert_eq!(stored_account(&gateway, &sid).await.unwrap().id, one.id); + } + + /// The fake vendor never ends a turn; end it as a real one would. + fn end_turn(gw: &Gateway, sid: &str) { + *gw.sessions[sid].turn_started_at.lock().unwrap() = None; + } + + async fn im_send( + gateway: &Arc>, + text: &str, + tap: Option<&str>, + ) -> Vec { + let selection = tap.map(|data| ChoiceReply { + data: data.to_string(), + }); + Gateway::handle_message_shared( + Arc::clone(gateway), + "telegram", + "chat-1", + "alice", + None, + "m-1", + text, + &[], + selection.as_ref(), + ) + .await + .unwrap() + } + + /// #236 IM `/account`: names the session's account (a default-login + /// session names the cswap account that login is right now), lists the + /// accounts with their quota, and switches by number, name or `default` + /// through the same door as the web picker. + #[tokio::test] + async fn im_account_command_lists_and_switches_the_current_session() { + let tmp = tempfile::tempdir().unwrap(); + let fake = Arc::new(FakeAdapter::new(AgentVendor::Claude)); + let mut gw = Gateway::new(fake.clone(), "alpha", tmp.path()); + let mut cloud = cswap_account("1", "cloud"); + cloud.active = true; + cloud.five_hour_pct = Some(11); + cloud.seven_day_pct = Some(100); + let mut work = cswap_account("2", "work"); + work.seven_day_pct = Some(40); + gw.set_cswap_accounts(Arc::new( + ccteam_harness::execution::claude_accounts::CswapAccountService::fixed(vec![ + cloud.clone(), + work.clone(), + ]), + )); + assert!( + im_send( + &Arc::new(tokio::sync::Mutex::new(Gateway::new( + fake.clone(), + "alpha", + tmp.path() + ))), + "/account", + None + ) + .await[0] + .contains("没有会话"), + "no session yet: say how to get one" + ); + gw.handle_text("telegram", "chat-1", "alice", "hello") + .await + .unwrap(); + let sid = gw + .current_session + .get(&ChatKey::new("telegram", "chat-1", "alice")) + .unwrap(); + end_turn(&gw, &sid); + let gateway = Arc::new(tokio::sync::Mutex::new(gw)); + + let listing = im_send(&gateway, "/account", None).await.join("\n"); + assert!( + listing.contains(&format!( + "会话 {sid} · Claude 账号:默认登录(此刻是 #1 cloud" + )), + "{listing}" + ); + assert!( + listing.contains("#1 cloud 5h 11% · 7d 100% (当前默认)"), + "{listing}" + ); + assert!(listing.contains("#2 work 7d 40%"), "{listing}"); + assert!(listing.contains("/account <编号>"), "{listing}"); + + let switched = im_send(&gateway, "/account 2", None).await.join("\n"); + assert!( + switched.contains(&format!("已把会话 {sid} 切到 #2 work")), + "{switched}" + ); + assert!( + switched.contains("下一条消息在同一会话里按新账号继续"), + "{switched}" + ); + assert_eq!(stored_account(&gateway, &sid).await.unwrap().id, work.id); + let listing = im_send(&gateway, "/account", None).await.join("\n"); + assert!(listing.contains("Claude 账号:#2 work"), "{listing}"); + assert!(listing.contains("#2 work 7d 40% ✓"), "{listing}"); + + let again = im_send(&gateway, "/account work", None).await.join("\n"); + assert!(again.contains("已经在用 #2 work"), "{again}"); + let unknown = im_send(&gateway, "/account 9", None).await.join("\n"); + assert!(unknown.contains("没有编号或名字为「9」的账号"), "{unknown}"); + + // The next message resumes the same sid under the new account. + im_send(&gateway, "continue", None).await; + end_turn(&*gateway.lock().await, &sid); + assert_eq!( + fake.spawn_accounts.lock().await.last().cloned(), + Some(Some(work.id.clone())) + ); + let status = im_send(&gateway, "/status", None).await.join("\n"); + assert!(status.contains("👤 #2 work"), "{status}"); + + let back = im_send(&gateway, "/account default", None).await.join("\n"); + assert!(back.contains("切到 默认登录"), "{back}"); + assert_eq!(stored_account(&gateway, &sid).await, None); + } + + /// #236 — on a button channel `/account` offers one button per account, + /// and a tap runs `/account ` through the shared entry. + #[tokio::test] + async fn im_account_buttons_switch_through_the_shared_entry() { + let tmp = tempfile::tempdir().unwrap(); + let fake = Arc::new(FakeAdapter::new(AgentVendor::Claude)); + let mut gw = Gateway::new(fake.clone(), "alpha", tmp.path()); + let work = cswap_account("2", "work"); + gw.set_cswap_accounts(Arc::new( + ccteam_harness::execution::claude_accounts::CswapAccountService::fixed(vec![ + cswap_account("1", "cloud"), + work.clone(), + ]), + )); + gw.bind_channel_buttons("telegram", true); + let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel::(); + gw.set_event_sink(tx); + gw.handle_text("telegram", "chat-1", "alice", "hello") + .await + .unwrap(); + let sid = gw + .current_session + .get(&ChatKey::new("telegram", "chat-1", "alice")) + .unwrap(); + end_turn(&gw, &sid); + let gateway = Arc::new(tokio::sync::Mutex::new(gw)); + while rx.try_recv().is_ok() {} + + assert!(im_send(&gateway, "/account", None).await.is_empty()); + let picker = std::iter::from_fn(|| rx.try_recv().ok()) + .find(|event| !event.options.is_empty()) + .expect("the listing carries buttons"); + let taps: Vec<_> = picker.options.iter().map(|o| o.data.as_str()).collect(); + assert_eq!( + taps, + ["act:account:default", "act:account:1", "act:account:2"] + ); + assert!( + picker.options[0].label.ends_with('✓'), + "default login is current" + ); + + assert!(Gateway::selection_needs_shared_entry(Some(&ChoiceReply { + data: "act:account:2".into() + }))); + // A button channel gets the receipt as a message with next-step buttons. + assert!(im_send(&gateway, "", Some("act:account:2")) + .await + .is_empty()); + let receipt = std::iter::from_fn(|| rx.try_recv().ok()) + .map(|event| event.content) + .find(|content| content.contains("切到")) + .expect("the switch receipt"); + assert!(receipt.contains("切到 #2 work"), "{receipt}"); + assert_eq!(stored_account(&gateway, &sid).await.unwrap().id, work.id); + assert_eq!(button_action_command("account:x"), None); + assert_eq!(button_action_command("account:2 3"), None); + } + + /// #236 — refusals leave the binding and the process exactly as they were. + #[tokio::test] + async fn claude_account_switch_refuses_without_touching_the_session() { + let tmp = tempfile::tempdir().unwrap(); + let two = cswap_account("2", "work"); + let (_fake, gateway, sid) = account_session(tmp.path(), AgentVendor::Claude, None).await; + + // Mid-turn: releasing would cut the turn short. + let started = { + let guard = gateway.lock().await; + let session = guard.sessions.get(&sid).unwrap(); + *session.turn_started_at.lock().unwrap() = Some(Instant::now()); + Arc::clone(&session.turn_started_at) + }; + let busy = Gateway::switch_claude_account_shared(&gateway, &sid, Some(two.clone())).await; + assert!( + matches!(busy, Err(ClaudeAccountSwitchError::Busy(_))), + "{busy:?}" + ); + *started.lock().unwrap() = None; + assert!(gateway.lock().await.sessions.contains_key(&sid)); + assert_eq!(stored_account(&gateway, &sid).await, None); + + // History only in the current account's private profile: another + // account would resume nothing and start the conversation over. + let mut private = + ccteam_harness::execution::claude_accounts::ClaudeAccountBinding::requested( + cswap_account("3", "solo").id, + ) + .unwrap(); + private.config_dir = Some(tmp.path().join("profile-3")); + let uuid = { + let guard = gateway.lock().await; + let mut meta = guard + .session_catalog + .find_or_load(&sid, &guard.projects) + .unwrap() + .meta; + meta.claude_account = Some(private.clone()); + guard.persist_session_meta(tmp.path(), &meta).unwrap(); + if meta.vendor_uuid.is_empty() { + ccteam_harness::execution::claude_stream_json::spawn_spec::deterministic_session_uuid( + "alpha", &sid, + ) + } else { + meta.vendor_uuid + } + }; + let transcript = ccteam_harness::execution::transcript_tail::anthropic_project_dir_in( + &tmp.path().join("profile-3/projects"), + tmp.path(), + ); + std::fs::create_dir_all(&transcript).unwrap(); + std::fs::write(transcript.join(format!("{uuid}.jsonl")), "{}\n").unwrap(); + let private_history = + Gateway::switch_claude_account_shared(&gateway, &sid, Some(two.clone())).await; + assert!( + matches!(private_history, Err(ClaudeAccountSwitchError::Refused(_))), + "{private_history:?}" + ); + assert_eq!(stored_account(&gateway, &sid).await, Some(private)); + assert!(gateway.lock().await.sessions.contains_key(&sid)); + + // Only a local Claude stream-json session runs through cswap. + let other = tempfile::tempdir().unwrap(); + let (_fake, codex, codex_sid) = + account_session(other.path(), AgentVendor::Codex, None).await; + let unsupported = + Gateway::switch_claude_account_shared(&codex, &codex_sid, Some(two)).await; + assert!( + matches!(unsupported, Err(ClaudeAccountSwitchError::Unsupported(_))), + "{unsupported:?}" + ); + assert!(matches!( + Gateway::switch_claude_account_shared(&codex, "s404", None).await, + Err(ClaudeAccountSwitchError::UnknownSession(_)) + )); + } + + #[tokio::test] + async fn cswap_selection_needs_no_grant_but_only_runs_local_stream_json() { + let tmp = tempfile::tempdir().unwrap(); + let fake = Arc::new(FakeAdapter::new(AgentVendor::Claude)); + let mut gateway = Gateway::new(fake, "alpha", tmp.path()); + let id = ccteam_harness::execution::claude_accounts::account_id("two@example.test", ""); + let tuning = SpawnTuning { + claude_account: Some(id.clone()), + ..Default::default() + }; + for (vendor, protocol) in [ + (AgentVendor::Codex, SessionProtocol::StreamJson), + (AgentVendor::Claude, SessionProtocol::Terminal), + ] { + let denied = gateway.plan_new_session( + ChatKey::new("web", "web-api", "web-api"), + "alpha".into(), + vendor, + String::new(), + String::new(), + PermissionMode::Skip, + protocol, + tuning.clone(), + ); + assert!(denied.err().unwrap().is::()); + } + assert_eq!( + gateway.next_session, 0, + "a rejected choice allocates no sid" + ); + // Owner decision 2026-11-06: no per-identity grant — a per-user web + // login (Tenant) uses any local account exactly like the admin. + let plan = gateway + .plan_new_session( + ChatKey::new("web", "tenant", "tenant"), + "alpha".into(), + AgentVendor::Claude, + String::new(), + String::new(), + PermissionMode::Skip, + SessionProtocol::StreamJson, + tuning, + ) + .unwrap(); + assert_eq!(plan.claude_account.as_ref().unwrap().id, id); + let mut binding = plan.claude_account.clone().unwrap(); + binding.config_dir = Some(tmp.path().join("private-account")); + binding.slot = "2".into(); + binding.label = "work".into(); + let thread = ThreadHandle { + vendor: AgentVendor::Claude, + mode: ccteam_harness::ExecutionMode::Chat, + identity: "vendor-id".into(), + started_at: chrono::Utc::now(), + raw_extras: serde_json::json!({"vendor_uuid":"vendor-id","claude_account":binding}), + }; + let meta = Gateway::meta_for_new_session(&plan, &thread, None); + assert_eq!( + meta.claude_account.as_ref().unwrap().config_dir, + Some(tmp.path().join("private-account")) + ); + ccteam_harness::execution::session_meta::write_session_meta(tmp.path(), &meta).unwrap(); + assert_eq!( + ccteam_harness::execution::transcript_tail::anthropic_bound_project_dir( + tmp.path(), + meta.claude_account.as_ref() + ), + Some( + ccteam_harness::execution::transcript_tail::anthropic_project_dir_in( + &tmp.path().join("private-account/projects"), + tmp.path() + ) + ) + ); + let public = + serde_json::to_string(&released_session_view(&meta, "alpha", &Default::default())) + .unwrap(); + assert!( + !public.contains("private-account"), + "private profile paths must not escape through session DTOs" + ); + assert!(!public.contains("config_dir")); + } + /// v0.8.24 A-U3 — an explicit `SpawnTuning` (composer model + effort) /// reaches the adapter's `SpawnCtx`, and the explicit model beats the /// role's `model:` frontmatter; without tuning the role default holds @@ -24359,6 +25893,7 @@ mod tests { SessionProtocol::StreamJson, "web-api".into(), SpawnTuning { + claude_account: None, mode: None, model: Some("future-model-from-vendor".into()), effort: Some("max".into()), @@ -24392,6 +25927,7 @@ mod tests { SessionProtocol::StreamJson, "web-api".into(), SpawnTuning { + claude_account: None, mode: None, model: Some(" ".into()), effort: Some("".into()), @@ -24433,6 +25969,7 @@ mod tests { SessionProtocol::StreamJson, "web-api".into(), SpawnTuning { + claude_account: None, mode: None, model: Some("opus".into()), effort: Some("xhigh".into()), @@ -24524,6 +26061,7 @@ mod tests { SessionProtocol::StreamJson, "web-api".into(), SpawnTuning { + claude_account: None, mode: None, model: Some("claude-sonnet-5".into()), effort: Some("xhigh".into()), @@ -24589,6 +26127,7 @@ mod tests { SessionProtocol::StreamJson, "web-api".into(), SpawnTuning { + claude_account: None, mode: None, model: None, effort: None, @@ -24659,6 +26198,7 @@ mod tests { SessionProtocol::StreamJson, "web-api".into(), SpawnTuning { + claude_account: None, mode: None, model: Some("opus".into()), effort: Some("xhigh".into()), @@ -24849,6 +26389,7 @@ mod tests { SessionProtocol::StreamJson, "web-api".into(), SpawnTuning { + claude_account: None, mode: None, model: Some("claude-sonnet-5".into()), effort: Some("xhigh".into()), @@ -25420,6 +26961,8 @@ mod tests { /// `SpawnCtx::generation` captured per start_thread, so a test can assert /// the thread was stamped with the generation the live map installs. spawn_generations: Arc>>, + /// #236 — the cswap account id (`None` = default login) per start_thread. + spawn_accounts: Arc>>>, /// #203 — when set, every `start_thread` reports this id as /// `raw_extras.vendor_uuid` (a vendor whose resume ladder fell back to /// a fresh thread). `None` = no vendor id (the default `{}` extras). @@ -25491,6 +27034,13 @@ mod tests { /// trait default). Account-scoped: every session sharing this fake /// answers with the same windows, exactly like one vendor account. account_usage: Arc>>, + /// Per-thread override of `account_usage`, keyed by thread identity: + /// one process still signed in as a DIFFERENT account than the rest + /// (a login switch it started before). + account_usage_by_thread: Arc>>, + /// How long each `account_usage` ask takes — a slow or stuck vendor + /// (#234). Zero = immediate. + account_usage_delay: Arc>, /// Monotone submission counter, so every accepted message gets its OWN /// execution-turn id. One id per THREAD was enough while nothing /// correlated a completion with the message that asked for it; a @@ -25570,6 +27120,7 @@ mod tests { spawn_secrets: Arc::new(Mutex::new(Vec::new())), spawn_tunings: Arc::new(Mutex::new(Vec::new())), spawn_generations: Arc::new(Mutex::new(Vec::new())), + spawn_accounts: Arc::new(Mutex::new(Vec::new())), next_vendor_uuid: Arc::new(std::sync::Mutex::new(None)), emit_turn_boundary: false, assistant_messages: 1, @@ -25587,6 +27138,8 @@ mod tests { panic_recover_for: Arc::default(), recovered_for: Arc::default(), account_usage: Arc::new(Mutex::new(None)), + account_usage_by_thread: Arc::default(), + account_usage_delay: Arc::default(), turn_seq: Arc::new(AtomicUsize::new(0)), turn_queues: Arc::new(std::sync::Mutex::new(std::collections::HashMap::new())), events_held: Arc::new(std::sync::atomic::AtomicBool::new(false)), @@ -25837,6 +27390,17 @@ mod tests { *self.account_usage.lock().await = usage; } + fn set_account_usage_delay(&self, delay: std::time::Duration) { + *self.account_usage_delay.lock().unwrap() = delay; + } + + fn set_thread_account_usage(&self, identity: &str, usage: AccountUsage) { + self.account_usage_by_thread + .lock() + .unwrap() + .insert(identity.to_string(), usage); + } + fn new_with_event_delay(vendor: AgentVendor, event_delay: std::time::Duration) -> Self { Self { event_delay, @@ -25936,6 +27500,11 @@ mod tests { .await .push((ctx.model_id.clone(), ctx.effort.clone())); self.spawn_generations.lock().await.push(ctx.generation); + self.spawn_accounts.lock().await.push( + ctx.claude_account + .as_ref() + .map(|account| account.id.clone()), + ); // A fresh/resumed child is alive. self.live.store(true, Ordering::SeqCst); let raw_extras = match self.next_vendor_uuid.lock().unwrap().as_deref() { @@ -26139,8 +27708,21 @@ mod tests { None } - async fn account_usage(&self, _h: &ThreadHandle) -> Option { - self.account_usage.lock().await.clone() + async fn account_usage(&self, h: &ThreadHandle) -> Option { + let delay = *self.account_usage_delay.lock().unwrap(); + if !delay.is_zero() { + tokio::time::sleep(delay).await; + } + let own = self + .account_usage_by_thread + .lock() + .unwrap() + .get(&h.identity) + .cloned(); + match own { + Some(usage) => Some(usage), + None => self.account_usage.lock().await.clone(), + } } async fn handle_directive( @@ -29451,7 +31033,7 @@ mod tests { gateway.chat_can_access(&tenant, gateway.sessions.get(&child).unwrap()), "a LIVE session in a tenant-owned project belongs to that tenant" ); - let status = gateway.render_status(&tenant).await; + let status = gateway.render_status_with(&tenant, None).await; assert!( status.contains(&format!("👥 直接子会话:\n · {child} · claude")), "the tenant's /status must list its project's delegated children: {status}" @@ -34165,6 +35747,7 @@ mod tests { // A stopped session s1 belongs to project alpha (meta.json on disk). let meta = SessionMeta { + claude_account: None, model_pinned_generation: None, mode: None, managed_by: Default::default(), @@ -34244,6 +35827,7 @@ mod tests { // A stopped session s1 (meta.json on disk, never spawned → not live). let meta = SessionMeta { + claude_account: None, model_pinned_generation: None, mode: None, managed_by: Default::default(), diff --git a/crates/ccteam-im/src/mcp/dispatch.rs b/crates/ccteam-im/src/mcp/dispatch.rs index 9af2d650..ffb91ad2 100644 --- a/crates/ccteam-im/src/mcp/dispatch.rs +++ b/crates/ccteam-im/src/mcp/dispatch.rs @@ -1628,7 +1628,7 @@ async fn execute_status( /// is the whole reason this tier exists. /// /// No probing engine and no polling: the map is -/// [`Gateway::account_usage_snapshot`](crate::gateway::Gateway::account_usage_snapshot), +/// [`Gateway::account_usage_probes`](crate::gateway::Gateway::account_usage_probes), /// which asks live same-vendor adapters for state they already hold (never a /// turn) and otherwise reads the recorded observation. A vendor nobody has /// heard from is absent rather than zeroed. @@ -1644,13 +1644,14 @@ async fn append_usage_sections( let Some(gateway) = gateway else { return; }; - // Both reads under one guard: the snapshot is async (it may ask a live - // adapter), the sid resolution is a cheap in-memory lookup. - let (usage, own_project_dir) = { + // Only cheap in-memory reads under the guard; the live adapter asks run + // after it is dropped (#234). + let (probes, own_project_dir) = { let gw = gateway.lock().await; let dir = caller_sid.and_then(|sid| gw.session_resolve_any(sid).map(|r| r.project_dir)); - (gw.account_usage_snapshot(None).await, dir) + (gw.account_usage_probes(None), dir) }; + let usage = probes.resolve().await; if let Some(sid) = caller_sid { let mut you = serde_json::Map::new(); you.insert("sid".into(), serde_json::json!(sid)); @@ -2114,6 +2115,7 @@ async fn run_session_tool( /// refused rather than silently ignored, because "my model setting did /// nothing" is a far worse bug report than "that parameter is not for this". const AGENT_SPAWN_ONLY_PARAMS: &[&str] = &[ + "claude_account", "vendor", "model", "effort", @@ -2390,10 +2392,8 @@ async fn pre_agent_policy_gate( }; // ---- Phase 2: the facts that cost something, for a real hook only ---- - let usage = { - let gw = gateway.lock().await; - gw.account_usage_snapshot(None).await - }; + let probes = gateway.lock().await.account_usage_probes(None); + let usage = probes.resolve().await; let usage = (!usage.is_empty()).then(|| { serde_json::Value::Object( usage @@ -2721,6 +2721,12 @@ async fn run_agent_spawn_at( .filter(|s| !s.is_empty()) .map(String::from); let tuning = crate::gateway::SpawnTuning { + claude_account: args + .get("claude_account") + .and_then(|value| value.as_str()) + .map(str::trim) + .filter(|value| !value.is_empty()) + .map(str::to_string), model, effort, mode, diff --git a/crates/ccteam-im/src/mcp/protocol.rs b/crates/ccteam-im/src/mcp/protocol.rs index a0f8d0fb..1f099679 100644 --- a/crates/ccteam-im/src/mcp/protocol.rs +++ b/crates/ccteam-im/src/mcp/protocol.rs @@ -302,9 +302,10 @@ pub fn session_tool_definitions() -> Vec { "description": "Harness for a new session (default claude)." }, "wait": { "type": "integer", "description": "Seconds to block inline, 0-240 (default 0 = async)." }, - "model": { "type": "string", "description": "Model id, passed to the vendor verbatim." }, - "effort": { "type": "string", "description": "Reasoning-effort token, passed verbatim to the vendor." }, - "role": { "type": "string", "description": "Work-role `.claude/agents/.md`; omit for roleless." }, + "model": { "type": "string", "description": "Vendor model id." }, + "effort": { "type": "string", "description": "Vendor effort token." }, + "claude_account": { "type": "string", "description": "Local cswap account id." }, + "role": { "type": "string", "description": "Project role; omit for roleless." }, "project": { "type": "string", "description": "Workspace slug. Required on an enrolled client's first call." }, "title": { "type": "string", "description": "Ledger label (<=80 chars); never sent to the agent." }, "notify": { @@ -934,6 +935,7 @@ mod tests { "wait", "model", "effort", + "claude_account", "role", "project", "title", diff --git a/crates/ccteam-im/src/mcp/vendor_panel.rs b/crates/ccteam-im/src/mcp/vendor_panel.rs index 07313465..14dc845b 100644 --- a/crates/ccteam-im/src/mcp/vendor_panel.rs +++ b/crates/ccteam-im/src/mcp/vendor_panel.rs @@ -1038,6 +1038,7 @@ mod tests { efforts: Vec::new(), }) .collect(), + default_model: None, }, )])); let hub = crate::hub::HubModelsState::Available(crate::hub::HubModelsSnapshot { diff --git a/crates/ccteam-im/src/usage_view.rs b/crates/ccteam-im/src/usage_view.rs index 584e1247..8503450b 100644 --- a/crates/ccteam-im/src/usage_view.rs +++ b/crates/ccteam-im/src/usage_view.rs @@ -1,7 +1,7 @@ //! One JSON shape for "where does this vendor account stand", shared by every //! machine-readable surface. //! -//! [`Gateway::account_usage_snapshot`](crate::gateway::Gateway::account_usage_snapshot) +//! [`Gateway::account_usage_probes`](crate::gateway::Gateway::account_usage_probes) //! answers WHAT is known; this module decides how that is spelled on the wire, //! once, for both readers of it — the MCP `status{detail:"usage"}` body an //! agent calls and the `GET /api/v1/usage` a script calls. Two spellings of one diff --git a/crates/ccteam-web/src/routes/agents.rs b/crates/ccteam-web/src/routes/agents.rs index a09816f0..ed072a00 100644 --- a/crates/ccteam-web/src/routes/agents.rs +++ b/crates/ccteam-web/src/routes/agents.rs @@ -12,7 +12,7 @@ //! under the same lock, awaited after it drops — the SAME statusline source //! `GET /sessions/{sid}/status` serves, via //! [`super::sessions_api::resolved_thread_status`] ⇒ `nodes[].model` + -//! `nodes[].effort`) ⋈ +//! `nodes[].effort` + `nodes[].context_pct`) ⋈ //! [`ccteam_im::gateway::Gateway::armed_delegation_watch_sids`] (a //! best-effort seed for `edges[].active`, corrected live by the SSE //! `dispatched`/`completed` frames — see `AgentsView`'s reducer). @@ -91,6 +91,15 @@ pub struct AgentNode { /// on idle nodes and on vendors/models with no effort axis. #[serde(skip_serializing_if = "Option::is_none")] pub effort: Option, + /// How full the session's context window is RIGHT NOW (0-100, rounded), + /// from the same live statusline join as `model` — the vendor's own + /// accounting (claude refreshes it mid-turn, so a long working turn's + /// growth shows up between turns too). Only a session ccteam holds a + /// process for has a live window, so every other node is `null`: no + /// per-node transcript read on a fleet-wide snapshot that is polled, and + /// no number older than "now" passed off as current. + #[serde(skip_serializing_if = "Option::is_none")] + pub context_pct: Option, pub host: String, /// What the session is DOING: `working` | `idle` | `stale` | `stuck`, or /// `detached` for a body that outlived the daemon. See the module doc. @@ -146,7 +155,7 @@ pub(crate) struct AgentsGraphQuery { } /// How long ONE live session gets to report its statusline before the graph -/// gives up on it and reports the node without `model`/`effort`. The snapshot +/// gives up on it and reports the node without `model`/`effort`/`context_pct`. The snapshot /// is a fleet overview, not a per-session probe: a node's model is a nicety, /// while a stalled response blocks the whole team view. Per-session (not /// global) so one slow vendor never costs the others their model. @@ -247,6 +256,10 @@ pub(crate) fn build_agents_graph( effort: live .and_then(|s| s.effort.clone()) .or_else(|| m.effort.clone()), + context_pct: live + .and_then(|s| s.context.as_ref()) + .and_then(|context| context.pct()) + .map(|pct| pct.round() as u64), host, status, residency, @@ -517,6 +530,7 @@ mod tests { depth: u32, ) { let mut m = ccteam_harness::SessionMeta { + claude_account: None, model_pinned_generation: None, mode: None, tool_face: None, @@ -630,6 +644,7 @@ mod tests { live.insert( "s1".to_string(), SessionView { + claude_account: None, driveable: true, detached: None, context_pct: None, @@ -694,10 +709,11 @@ mod tests { assert_eq!(graph.nodes[0].residency, "resident"); } - /// TEAM-4 — `nodes[].model` + `nodes[].effort` come from the caller's - /// post-lock statusline join (`live_status`), never from `meta.json`: the - /// live sid carries its reported model/effort, the idle sid stays honestly - /// `None`. + /// TEAM-4 — `nodes[].model` + `nodes[].effort` + `nodes[].context_pct` + /// come from the caller's post-lock statusline join (`live_status`), never + /// from `meta.json`: the live sid carries its reported model/effort and its + /// window occupancy (the vendor's own numbers, rounded), the idle sid stays + /// honestly `None`. #[test] fn build_agents_graph_joins_live_model_only_for_live_nodes() { let tmp = tempfile::TempDir::new().unwrap(); @@ -723,6 +739,7 @@ mod tests { live.insert( "s1".to_string(), SessionView { + claude_account: None, driveable: true, detached: None, context_pct: None, @@ -754,6 +771,11 @@ mod tests { ThreadStatus { model: Some("fable-5".to_string()), effort: Some("high".to_string()), + context: Some(ccteam_harness::ContextUsage::known( + 126_500, + 200_000, + ccteam_harness::ContextSource::Reported, + )), ..Default::default() }, )] @@ -771,12 +793,43 @@ mod tests { let by_sid = |sid: &str| graph.nodes.iter().find(|n| n.sid == sid).unwrap(); assert_eq!(by_sid("s1").model.as_deref(), Some("fable-5")); assert_eq!(by_sid("s1").effort.as_deref(), Some("high")); + assert_eq!(by_sid("s1").context_pct, Some(63), "126.5k / 200k, rounded"); assert_eq!( by_sid("s2").model, None, "a released node has nothing live to report" ); assert_eq!(by_sid("s2").effort, None); + assert_eq!(by_sid("s2").context_pct, None); + } + + /// A live session whose vendor knows the window but not its occupancy + /// (no turn reported yet) has no percentage — never a fabricated 0%. + #[test] + fn a_window_without_occupancy_reports_no_context_pct() { + let tmp = tempfile::TempDir::new().unwrap(); + let dir = tmp.path().join("demo"); + std::fs::create_dir_all(&dir).unwrap(); + meta(&dir, "s1", "", ccteam_harness::AgentVendor::Claude, None, 0); + let live_status: HashMap = [( + "s1".to_string(), + ThreadStatus { + context: Some(ccteam_harness::ContextUsage::window_only(200_000)), + ..Default::default() + }, + )] + .into_iter() + .collect(); + let graph = build_agents_graph( + |_| dir.clone(), + &["demo".to_string()], + &HashMap::new(), + &live_status, + &HashSet::new(), + &empty_projection(tmp.path()), + &HashMap::new(), + ); + assert_eq!(graph.nodes[0].context_pct, None); } #[test] diff --git a/crates/ccteam-web/src/routes/claude_accounts.rs b/crates/ccteam-web/src/routes/claude_accounts.rs new file mode 100644 index 00000000..c24bc3ab --- /dev/null +++ b/crates/ccteam-web/src/routes/claude_accounts.rs @@ -0,0 +1,29 @@ +//! Optional local cswap discovery. Every identity that can start a Claude +//! session may use any local account (owner decision 2026-11-06, #229): the +//! default login is already the box owner's subscription, so a per-account +//! grant would gate nothing the default path does not already expose. + +use crate::state::AppState; +use axum::{ + extract::State, + response::{IntoResponse, Response}, + Json, +}; + +#[utoipa::path( + get, path = "/api/v1/vendors/claude/accounts", tag = "sessions", + responses((status = 200, description = "Optional cswap availability and local subscription accounts", body = serde_json::Value)) +)] +pub(crate) async fn handle_claude_accounts(State(app): State) -> Response { + match app.cswap_accounts.accounts().await { + Ok(accounts) => { + Json(serde_json::json!({"available": true, "accounts": accounts})).into_response() + } + Err(error) => Json(serde_json::json!({ + "available": false, + "accounts": [], + "message": error.to_string(), + })) + .into_response(), + } +} diff --git a/crates/ccteam-web/src/routes/mod.rs b/crates/ccteam-web/src/routes/mod.rs index 0dfa649d..ca593a83 100644 --- a/crates/ccteam-web/src/routes/mod.rs +++ b/crates/ccteam-web/src/routes/mod.rs @@ -57,6 +57,7 @@ pub mod marketplace; // Spawn-tuning discovery (`GET /api/v1/models`): per-vendor observed model // ids + reasoning-effort ladders, so a caller of `POST .../sessions` can see // what `model` / `effort` a vendor takes. Advisory, never a spawn gate. +pub mod claude_accounts; pub mod models; // v0.8.7 W5 (Item E) — OpenAPI auto-docs. Aggregates every `/api/v1` // handler into one `OpenApiRouter` (single source with the route table) diff --git a/crates/ccteam-web/src/routes/models.rs b/crates/ccteam-web/src/routes/models.rs index dcd8d4f6..17a577bd 100644 --- a/crates/ccteam-web/src/routes/models.rs +++ b/crates/ccteam-web/src/routes/models.rs @@ -64,6 +64,9 @@ pub struct VendorModels { pub source: Option, /// Observed model ids; `[]` when never observed (NOT "has no models"). pub models: Vec, + /// The concrete id the vendor runs when no model is requested (what the + /// picker's default row stands for); `null` until observed. + pub default_model: Option, /// Reasoning-effort ladder offered for this vendor: vendor-declared when /// its handshake said so, else the CLI-verified fallback. Empty means /// ccteam knows of no effort axis for this vendor (OpenCode today). @@ -109,6 +112,7 @@ pub(crate) async fn handle_models(State(app): State) -> impl IntoRespo .collect() }) .unwrap_or_default(), + default_model: entry.and_then(|e| e.default_model.clone()), // Deliberately the harness helper rather than a local fold // over `entry.models`: the "vendor-declared, else pinned // fallback" precedence has ONE home, and a web-local copy diff --git a/crates/ccteam-web/src/routes/openapi.rs b/crates/ccteam-web/src/routes/openapi.rs index 2612bf31..b91d7919 100644 --- a/crates/ccteam-web/src/routes/openapi.rs +++ b/crates/ccteam-web/src/routes/openapi.rs @@ -156,6 +156,7 @@ fn build_api_v1() -> OpenApiRouter { // spawn-tuning discovery — the affordance side of `POST .../sessions` // taking `model` + `effort` (no project named, so no project ACL). .routes(routes!(super::models::handle_models)) + .routes(routes!(super::claude_accounts::handle_claude_accounts)) // v0.8.18 柱1 — host-keyed agent report (list / detail / register-mcp) .routes(routes!(super::hosts::handle_hosts)) .routes(routes!(super::hosts::handle_host_detail)) @@ -275,6 +276,8 @@ fn build_api_v1() -> OpenApiRouter { super::sessions_api::handle_session_history, super::sessions_api::handle_patch_session )) + // #236 — move a session to another cswap account / the default login. + .routes(routes!(super::sessions_api::handle_switch_claude_account)) .routes(routes!(super::sessions_api::handle_session_status)) .routes(routes!(super::sessions_api::handle_session_context)) .routes(routes!(super::sessions_api::handle_session_turn)) diff --git a/crates/ccteam-web/src/routes/sessions_api.rs b/crates/ccteam-web/src/routes/sessions_api.rs index a3656213..47347689 100644 --- a/crates/ccteam-web/src/routes/sessions_api.rs +++ b/crates/ccteam-web/src/routes/sessions_api.rs @@ -322,6 +322,10 @@ fn apply_progress_activity_status( /// Accepts form or JSON via [`FormOrJson`]. #[derive(Debug, Deserialize, ToSchema)] pub struct CreateSessionForm { + /// Optional stable cswap account id returned by GET /vendors/claude/accounts. + /// Only local Claude stream-json supports account selection. + #[serde(default)] + pub claude_account: Option, pub role: String, #[serde(default)] pub vendor: Option, @@ -384,6 +388,7 @@ fn spawn_tuning_from_form( mode: Option, ) -> ccteam_im::gateway::SpawnTuning { ccteam_im::gateway::SpawnTuning { + claude_account: None, model, effort, mode, @@ -466,12 +471,25 @@ pub(crate) async fn handle_create_session( }; // v0.8.24 A-U3 — explicit model/effort from the composer menu. - let tuning = spawn_tuning_from_form( + let mut tuning = spawn_tuning_from_form( vendor, form.model.clone(), form.effort.clone(), form.mode.clone(), ); + tuning.claude_account = form + .claude_account + .clone() + .filter(|value| !value.trim().is_empty()); + if tuning.claude_account.is_some() + && (vendor != AgentVendor::Claude || protocol != SessionProtocol::StreamJson) + { + return create_error( + StatusCode::UNPROCESSABLE_ENTITY, + "cswap accounts require local Claude stream-json".into(), + mode, + ); + } let created = ccteam_im::gateway::Gateway::create_session_api_tuned_shared( Arc::clone(gw), slug.clone(), @@ -486,6 +504,9 @@ pub(crate) async fn handle_create_session( .await; match created { Ok(created) => (StatusCode::CREATED, Json(json!({"sid": created.sid}))).into_response(), + Err(error) if error.is::() => { + create_error(StatusCode::UNPROCESSABLE_ENTITY, error.to_string(), mode) + } // v0.8.7 review-fix (R-M6) — distinguish a caller mistake (the named // role has no `.claude/agents/.md`) from a real internal failure // (adapter spawn / fs error). A bad role is a client error → 422 @@ -664,6 +685,97 @@ pub(crate) async fn handle_patch_session( } } +/// PUT body for `PUT /api/v1/sessions/{sid}/claude-account` (#236). +#[derive(Debug, Deserialize, utoipa::ToSchema)] +pub struct SwitchClaudeAccountRequest { + /// A stable account id from `GET /api/v1/vendors/claude/accounts`; + /// `null` returns the session to the default login. + #[serde(default)] + pub claude_account: Option, +} + +/// `PUT /api/v1/sessions/{sid}/claude-account` +/// +/// Move a local Claude stream-json session to another cswap account, or back +/// to the default login (#236). Only the session's account binding changes: +/// a resident process is released and the next message resumes the SAME sid +/// under the new account (cswap's shared history keeps the transcript +/// readable from every account). Picking the current account is a no-op. +/// +/// 200 `{sid, claude_account, changed, released}` (`claude_account: null` = +/// default login). 404 unknown/inaccessible session (`gate_sid`). 409 the +/// session is mid-turn, waiting on the user, running background work, or +/// still has a process from before a daemon restart. 422 not a local Claude +/// stream-json session, an account cswap does not list (or cswap is +/// unavailable), or history still private to the current account. 503 no +/// gateway. +#[utoipa::path( + put, + path = "/api/v1/sessions/{sid}/claude-account", + tag = "sessions", + params(("sid" = String, Path, description = "Gateway session id (`s{n}`)")), + request_body = SwitchClaudeAccountRequest, + responses( + (status = 200, description = "`{sid, claude_account, changed, released}`", body = serde_json::Value), + (status = 404, description = "Unknown session"), + (status = 409, description = "Busy: mid-turn, awaiting the user, background work or a pre-restart process"), + (status = 422, description = "Unsupported session, unlisted account / cswap unavailable, or history not shared yet"), + (status = 503, description = "No live gateway (standalone web)"), + ), +)] +pub(crate) async fn handle_switch_claude_account( + State(app): State, + Extension(identity): Extension, + Path(sid): Path, + Json(body): Json, +) -> Response { + use ccteam_im::gateway::ClaudeAccountSwitchError as SwitchError; + if let Some(deny) = gate_sid(&app, &identity, &sid).await { + return deny; + } + let Some(gw) = app.gateway.as_ref() else { + return no_gateway(); + }; + let refuse = |status: StatusCode, error: String| { + (status, Json(json!({ "error": error }))).into_response() + }; + let target = match body.claude_account.filter(|id| !id.trim().is_empty()) { + None => None, + // The id must be one cswap lists right now: that both validates it + // and supplies the `#slot name` the session shows until it resumes. + Some(id) => match app.cswap_accounts.accounts().await { + Ok(accounts) => match accounts.into_iter().find(|account| account.id == id) { + Some(account) => Some(account), + None => { + return refuse( + StatusCode::UNPROCESSABLE_ENTITY, + "cswap does not list this account; choose one from the account list".into(), + ) + } + }, + Err(error) => return refuse(StatusCode::UNPROCESSABLE_ENTITY, format!("{error:#}")), + }, + }; + match ccteam_im::gateway::Gateway::switch_claude_account_shared(gw, &sid, target).await { + Ok(switch) => Json(json!({ + "sid": sid, + "claude_account": switch.claude_account, + "changed": switch.changed, + "released": switch.released, + })) + .into_response(), + Err(SwitchError::UnknownSession(_)) => unknown_session(&sid), + Err(SwitchError::Busy(message)) => refuse(StatusCode::CONFLICT, message), + Err(error @ (SwitchError::Unsupported(_) | SwitchError::Refused(_))) => { + refuse(StatusCode::UNPROCESSABLE_ENTITY, error.to_string()) + } + Err(SwitchError::Internal(error)) => { + tracing::warn!(%sid, error = %format!("{error:#}"), "switch_claude_account failed"); + refuse(StatusCode::INTERNAL_SERVER_ERROR, format!("{error:#}")) + } + } +} + /// Serialize a [`SessionRename`] for the PATCH response. Split out so the /// wire shape — including the vendor-sync report the SPA renders — is /// unit-testable without a live gateway. @@ -2955,6 +3067,7 @@ mod tests { fn view(sid: &str) -> SessionView { SessionView { + claude_account: None, driveable: true, residency: "resident".to_string(), detached: None, @@ -3036,6 +3149,7 @@ mod tests { write_project_state(&paths, "demo"); let projection = test_projection(&paths); let mut views = vec![SessionView { + claude_account: None, driveable: true, residency: "resident".to_string(), detached: None, @@ -3090,6 +3204,7 @@ mod tests { let projection = test_projection(&paths); let mut views = vec![ SessionView { + claude_account: None, driveable: true, residency: "resident".to_string(), detached: None, @@ -3116,6 +3231,7 @@ mod tests { delegation_depth: 0, }, SessionView { + claude_account: None, driveable: true, residency: "resident".to_string(), detached: None, @@ -3177,6 +3293,7 @@ mod tests { write_project_state(&paths, "demo"); let projection = test_projection(&paths); let mut views = vec![SessionView { + claude_account: None, driveable: true, residency: "resident".to_string(), detached: None, @@ -3225,6 +3342,7 @@ mod tests { write_project_state(&paths, "demo"); let projection = test_projection(&paths); let mut views = vec![SessionView { + claude_account: None, driveable: true, residency: "resident".to_string(), detached: None, diff --git a/crates/ccteam-web/src/routes/status.rs b/crates/ccteam-web/src/routes/status.rs index 05c963fc..ffa269ea 100644 --- a/crates/ccteam-web/src/routes/status.rs +++ b/crates/ccteam-web/src/routes/status.rs @@ -659,6 +659,7 @@ mod tests { fn view(sid: &str, project: &str, vendor: &str) -> ccteam_im::gateway::SessionView { ccteam_im::gateway::SessionView { + claude_account: None, driveable: true, residency: "resident".to_string(), detached: None, diff --git a/crates/ccteam-web/src/routes/usage.rs b/crates/ccteam-web/src/routes/usage.rs index dc5e34b4..00350eb7 100644 --- a/crates/ccteam-web/src/routes/usage.rs +++ b/crates/ccteam-web/src/routes/usage.rs @@ -7,7 +7,7 @@ //! spelling, so a script and an agent can never be told different numbers. //! //! **Not a probe.** Nothing here polls, and nothing here logs into a vendor: -//! [`Gateway::account_usage_snapshot`](ccteam_im::gateway::Gateway::account_usage_snapshot) +//! [`Gateway::account_usage_probes`](ccteam_im::gateway::Gateway::account_usage_probes) //! asks live same-vendor adapters for state they already hold in memory (never //! a turn) and otherwise reads the recorded observation from //! [`ccteam_harness::usage_catalog`], which drops each window at the vendor's @@ -87,9 +87,13 @@ pub(crate) async fn handle_usage( let usage: Map = match app.gateway.as_ref() { Some(gw) => { - let guard = ccteam_im::latency::gateway_lock(gw, "web.usage").await; - guard - .account_usage_snapshot(filter) + // Capture under the lock, ask the live sessions after it is + // dropped (#234). + let probes = ccteam_im::latency::gateway_lock(gw, "web.usage") + .await + .account_usage_probes(filter); + probes + .resolve() .await .iter() .map(|(vendor, entry)| { diff --git a/crates/ccteam-web/src/state.rs b/crates/ccteam-web/src/state.rs index f2c3a608..148ad973 100644 --- a/crates/ccteam-web/src/state.rs +++ b/crates/ccteam-web/src/state.rs @@ -129,6 +129,7 @@ pub struct AppState { pub vendor_installs: Arc, /// VENDOR-QUOTA-1 — per-vendor quota probe service (HTTP + 5min cache). pub vendor_quotas: Arc, + pub cswap_accounts: Arc, /// Coalesces concurrent daemon-wide status aggregations. The completed /// result is never retained after its in-flight computation finishes. pub(crate) status_singleflight: crate::routes::status::StatusSingleflight, @@ -208,6 +209,9 @@ impl AppState { crate::routes::vendor_install::VendorInstallManager::default(), ), vendor_quotas: Arc::new(crate::routes::vendor_quota::VendorQuotaService::default()), + cswap_accounts: Arc::new( + ccteam_harness::execution::claude_accounts::CswapAccountService::default(), + ), status_singleflight: crate::routes::status::StatusSingleflight::default(), file_previews: Arc::new(crate::routes::files::PreviewRegistry::default()), } @@ -275,6 +279,8 @@ impl AppState { debug_assert!(Arc::ptr_eq(&self.progress_projection, &projection)); self.progress_projection = projection; } + // One cswap discovery cache for the web picker and IM `/account`. + self.cswap_accounts = guard.cswap_accounts(); } self.progress_projection.start_hydration(); self.session_principals = Some(Arc::clone(&principals)); diff --git a/crates/ccteam-web/tests/agents_test.rs b/crates/ccteam-web/tests/agents_test.rs index 0bd4dd5a..8f44c0a8 100644 --- a/crates/ccteam-web/tests/agents_test.rs +++ b/crates/ccteam-web/tests/agents_test.rs @@ -232,6 +232,7 @@ fn idle_meta( observed_model: Option<&str>, ) { let m = ccteam_harness::SessionMeta { + claude_account: None, model_pinned_generation: None, mode: None, tool_face: None, diff --git a/crates/ccteam-web/tests/claude_accounts_test.rs b/crates/ccteam-web/tests/claude_accounts_test.rs new file mode 100644 index 00000000..598064e8 --- /dev/null +++ b/crates/ccteam-web/tests/claude_accounts_test.rs @@ -0,0 +1,208 @@ +//! Discovery is open to every authenticated identity (owner decision +//! 2026-11-06, #229) yet still never leaks raw emails and runs the optional +//! tool once per cache window. This integration process owns its temporary +//! HOME and store. +#![cfg(unix)] + +use ccteam_core::{tenants::TenantRegistry, CcteamPaths}; +use ccteam_harness::{execution::claude_accounts::account_id, ClaudeStreamJsonAdapter}; +use ccteam_im::gateway::Gateway; +use ccteam_web::{router_with_state, AppState, AuthState}; +use std::{os::unix::fs::PermissionsExt, sync::Arc}; + +#[tokio::test] +async fn every_identity_discovers_every_local_account_without_a_grant() { + let tmp = tempfile::tempdir().unwrap(); + std::env::set_var("HOME", tmp.path().join("home")); + std::env::set_var("CCTEAM_HOME", tmp.path().join("state")); + let paths = CcteamPaths { + root: tmp.path().join("state"), + projects_root: tmp.path().join("projects"), + }; + std::fs::create_dir_all(paths.users_dir()).unwrap(); + let mut tenants = TenantRegistry::default(); + let alice = tenants.add("alice"); + let bob = tenants.add("bob"); + tenants.save(&paths.users_dir()).unwrap(); + let first = account_id("one@example.test", ""); + let second = account_id("two@example.test", ""); + let calls = tmp.path().join("calls"); + let cswap = tmp.path().join("cswap"); + std::fs::write(&cswap, format!("#!/bin/sh\necho x >> '{}'\nif [ \"$1\" = run ]; then echo '--share-history --no-share-history --require-session'; exit 0; fi\nif [ \"$1\" = config ]; then echo '{{\"schemaVersion\":1,\"settings\":[]}}'; exit 0; fi\nprintf '%s\\n' '{{\"schemaVersion\":1,\"accounts\":[{{\"number\":1,\"email\":\"one@example.test\"}},{{\"number\":2,\"email\":\"two@example.test\"}}]}}'\n", calls.display())).unwrap(); + std::fs::set_permissions(&cswap, std::fs::Permissions::from_mode(0o700)).unwrap(); + std::env::set_var("CCTEAM_CSWAP_BIN", &cswap); + let mut gateway = Gateway::new( + Arc::new(ClaudeStreamJsonAdapter::new()), + "project", + tmp.path(), + ); + gateway.enable_project_creation(paths.clone()); + let admin = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"; + let mut state = AppState::with_auth(paths.clone(), AuthState::enabled(admin.into())); + state.gateway = Some(Arc::new(tokio::sync::Mutex::new(gateway))); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = listener.local_addr().unwrap(); + tokio::spawn(async move { + axum::serve(listener, router_with_state(state)) + .await + .unwrap(); + }); + let client = reqwest::Client::builder().no_proxy().build().unwrap(); + let url = format!("http://{address}/api/v1/vendors/claude/accounts"); + + for token in [alice.web_token.clone(), bob.web_token.clone(), admin.into()] { + let listed: serde_json::Value = client + .get(&url) + .bearer_auth(format!("ccteam:{token}")) + .send() + .await + .unwrap() + .json() + .await + .unwrap(); + assert_eq!(listed["available"], true); + let ids: std::collections::BTreeSet<_> = listed["accounts"] + .as_array() + .unwrap() + .iter() + .map(|account| account["id"].as_str().unwrap().to_string()) + .collect(); + assert_eq!( + ids, + [first.clone(), second.clone()].into(), + "tenants and the admin see the same local accounts" + ); + assert!( + !listed.to_string().contains("example.test"), + "labels carry the local part only; the email domain never leaves the daemon" + ); + } + assert_eq!( + std::fs::read_to_string(&calls).unwrap().lines().count(), + 3, + "discovery is coalesced and cached across identities" + ); + let anonymous = client.get(&url).send().await.unwrap(); + assert_eq!( + anonymous.status().as_u16(), + 401, + "discovery still sits behind the web-token gate" + ); + + // #236 — switching a session's account. A released Claude session only + // rebinds (nothing spawns); its next message resumes under the account. + use ccteam_harness::execution::session_meta::{ + read_session_meta, write_session_meta, SessionMeta, SessionOrigin, + }; + use ccteam_harness::{AgentVendor, PermissionMode, SessionProtocol}; + let state = paths.project_state("project"); + std::fs::create_dir_all(state.parent().unwrap()).unwrap(); + ccteam_core::ProjectState::initial("project".into()) + .save(&state) + .unwrap(); + write_session_meta( + tmp.path(), + &SessionMeta { + claude_account: None, + model_pinned_generation: None, + mode: None, + tool_face: None, + managed_by: Default::default(), + stopped_at: None, + sid: "s7".into(), + slug: "project".into(), + vendor: AgentVendor::Claude, + protocol: SessionProtocol::StreamJson, + role: String::new(), + permission_mode: PermissionMode::Skip, + owner: "user:web-api".into(), + vendor_uuid: String::new(), + model: None, + observed_model: None, + effort: None, + host: "local".into(), + created_at: "2026-11-08T00:00:00Z".into(), + last_active: "2026-11-08T00:00:00Z".into(), + origin: SessionOrigin::Ccteam, + title: None, + title_source: None, + turn_count: 0, + cost_usd: None, + tokens_total: None, + role_sha: None, + skills_sha: None, + trigger: None, + parent_sid: None, + spawned_by_role: None, + delegation_depth: 0, + }, + ) + .unwrap(); + let switch = |sid: &str, account: serde_json::Value, token: Option<&str>| { + let request = client + .put(format!( + "http://{address}/api/v1/sessions/{sid}/claude-account" + )) + .json(&serde_json::json!({ "claude_account": account })); + match token { + Some(token) => request.bearer_auth(format!("ccteam:{token}")), + None => request, + } + .send() + }; + let status = |response: reqwest::Response| response.status().as_u16(); + assert_eq!( + status(switch("s7", serde_json::Value::Null, None).await.unwrap()), + 401 + ); + assert_eq!( + status( + switch("s404", serde_json::Value::Null, Some(admin)) + .await + .unwrap() + ), + 404 + ); + assert_eq!( + status( + switch("s7", "f".repeat(64).into(), Some(admin)) + .await + .unwrap() + ), + 422, + "only an account cswap lists can be chosen" + ); + let switched: serde_json::Value = switch("s7", second.clone().into(), Some(admin)) + .await + .unwrap() + .json() + .await + .unwrap(); + assert_eq!(switched["changed"], true); + assert_eq!( + switched["released"], false, + "a released session only rebinds" + ); + assert_eq!(switched["claude_account"]["slot"], "2"); + assert_eq!(switched["claude_account"]["label"], "two"); + let stored = read_session_meta(tmp.path(), "s7") + .unwrap() + .claude_account + .unwrap(); + assert_eq!( + (stored.id.as_str(), stored.config_dir), + (second.as_str(), None) + ); + let default: serde_json::Value = switch("s7", serde_json::Value::Null, Some(admin)) + .await + .unwrap() + .json() + .await + .unwrap(); + assert_eq!(default["changed"], true); + assert!(default["claude_account"].is_null()); + assert!(read_session_meta(tmp.path(), "s7") + .unwrap() + .claude_account + .is_none()); +} diff --git a/crates/ccteam-web/tests/openapi_test.rs b/crates/ccteam-web/tests/openapi_test.rs index 86884bb0..f935902a 100644 --- a/crates/ccteam-web/tests/openapi_test.rs +++ b/crates/ccteam-web/tests/openapi_test.rs @@ -71,6 +71,8 @@ fn expected_operations() -> BTreeSet<(&'static str, &'static str)> { ), // VENDOR-QUOTA-1 — vendor subscription-quota snapshot (admin). ("GET", "/api/v1/vendors/quota"), + // #229 — optional cswap discovery. + ("GET", "/api/v1/vendors/claude/accounts"), ("POST", "/api/v1/hosts/join-token"), ("GET", "/api/v1/hosts/join-token"), ("POST", "/api/v1/hosts/join"), @@ -155,6 +157,8 @@ fn expected_operations() -> BTreeSet<(&'static str, &'static str)> { ("GET", "/api/v1/sessions/{sid}"), // v0.8.22 P1 — session-title system: rename a session's title. ("PATCH", "/api/v1/sessions/{sid}"), + // #236 — switch the session's Claude account (cswap) / default login. + ("PUT", "/api/v1/sessions/{sid}/claude-account"), // live statusline (model + context-window usage) for the SPA top bar. ("GET", "/api/v1/sessions/{sid}/status"), // issue #21 — context composition for the session's context sidebar. diff --git a/crates/ccteam-web/tests/status_test.rs b/crates/ccteam-web/tests/status_test.rs index 02d5987f..c6b9b690 100644 --- a/crates/ccteam-web/tests/status_test.rs +++ b/crates/ccteam-web/tests/status_test.rs @@ -79,6 +79,7 @@ fn write_one_tracked_session(root: &std::path::Path) { ccteam_harness::write_session_meta( &project_dir, &ccteam_harness::SessionMeta { + claude_account: None, model_pinned_generation: None, mode: None, tool_face: None, diff --git a/crates/ccteam-web/web/src/components/ChatComposer.test.tsx b/crates/ccteam-web/web/src/components/ChatComposer.test.tsx index 59e7d4bc..cf598f37 100644 --- a/crates/ccteam-web/web/src/components/ChatComposer.test.tsx +++ b/crates/ccteam-web/web/src/components/ChatComposer.test.tsx @@ -174,36 +174,49 @@ describe("model button label", () => { />, ); - it("new-session draft: the vendor prefixes the default/picked model", () => { - expect(renderBtn()).toContain("claude · 默认"); - expect(renderBtn({ draft: { ...defaultDraft(), model: "opus" } })).toContain( - "claude · opus", - ); - expect( - renderBtn({ - draft: { ...defaultDraft(), vendor: "codex", model: "默认", protocol: "app-server" }, - }), - ).toContain("codex · 默认"); + const vendorBtn = (html: string) => + /data-testid="vendor-btn"[^>]*><\/span>([^<]*)<\/span>/.exec(html)?.[1]; + const modelBtn = (html: string) => /([^<]*)<\/span>/.exec(html)?.[1]; + + it("new-session draft: vendor and model are separate buttons; claude opens on opus · high", () => { + const html = renderBtn(); + expect(vendorBtn(html)).toBe("claude"); + expect(modelBtn(html)).toBe("opus"); + expect(html).toContain('high'); + const codex = renderBtn({ + draft: { ...defaultDraft(), vendor: "codex", model: "默认", effort: "", protocol: "app-server" }, + }); + expect(vendorBtn(codex)).toBe("codex"); + expect(modelBtn(codex)).toBe("默认"); }); - it("conversation: the live model rides after the vendor; an unreported model leaves the vendor alone", () => { - expect( - renderBtn({ - modelLabel: "gpt-5.5", - draft: { ...defaultDraft(), vendor: "codex", model: "", protocol: "app-server" }, - }), - ).toContain("codex · gpt-5.5"); - const html = renderBtn({ modelLabel: "" }); - expect(html).toContain("claude"); - expect(html).not.toContain("claude · "); + it("the vendor-default model names the concrete id the daemon observed", () => { + const html = renderBtn({ + catalog: { codex: { models: [], efforts: ["low", "high"], defaultModel: "gpt-5.5" } }, + draft: { ...defaultDraft(), vendor: "codex", model: "默认", effort: "", protocol: "app-server" }, + }); + expect(modelBtn(html)).toBe("gpt-5.5"); + // The default row in the menu reads the id too, tagged as the default. + expect(html).toContain('gpt-5.5默认'); + }); + + it("conversation: the live model fills the model button; an unreported model reads 默认", () => { + const html = renderBtn({ + modelLabel: "gpt-5.5", + draft: { ...defaultDraft(), vendor: "codex", model: "", protocol: "app-server" }, + }); + expect(vendorBtn(html)).toBe("codex"); + expect(modelBtn(html)).toBe("gpt-5.5"); + expect(modelBtn(renderBtn({ modelLabel: "" }))).toBe("默认"); }); - it("conversation: a live kimi session shows the same vendor · model · effort shape", () => { + it("conversation: a live kimi session shows vendor, model and effort", () => { const html = renderBtn({ modelLabel: "kimi-code/k3", - draft: { ...defaultDraft(), vendor: "kimi", model: "", protocol: "acp" }, + draft: { ...defaultDraft(), vendor: "kimi", model: "", effort: "", protocol: "acp" }, }); - expect(html).toContain("Kimi · kimi-code/k3"); + expect(vendorBtn(html)).toBe("Kimi"); + expect(modelBtn(html)).toBe("kimi-code/k3"); // Effort renders as the vendor's own token, never a translated word — // identical in zh and en. Nothing reported ⇒ `default`. expect(html).toContain('default'); @@ -282,7 +295,7 @@ describe("model menu (rows come from the vendor, never from a ccteam ladder)", ( it("a live catalog supersedes the static rows for models AND efforts", () => { const html = renderMenu({ - draft: { ...defaultDraft(), vendor: "kimi", protocol: "acp" }, + draft: { ...defaultDraft(), vendor: "kimi", model: "默认", effort: "", protocol: "acp" }, catalog: { kimi: { models: [{ id: "kimi-code/k3" }, { id: "kimi-code/k3-256k" }], @@ -292,7 +305,10 @@ describe("model menu (rows come from the vendor, never from a ccteam ladder)", ( }, }); expect(html).toContain("kimi-code/k3-256k"); - expect(html).toContain("openai/gpt-5.5"); + // The model menu is the selected vendor's only; other vendors live in + // the vendor menu, not as model rows. + expect(html).not.toContain("openai/gpt-5.5"); + expect(html).toContain('data-testid="vendor-menu"'); // The catalog said low|max — `high` (static) is gone. expect(html).toContain(">low<"); expect(html).not.toContain(">high<"); diff --git a/crates/ccteam-web/web/src/components/ChatComposer.tsx b/crates/ccteam-web/web/src/components/ChatComposer.tsx index 61f4dbbf..e55eddae 100644 --- a/crates/ccteam-web/web/src/components/ChatComposer.tsx +++ b/crates/ccteam-web/web/src/components/ChatComposer.tsx @@ -48,8 +48,11 @@ import type { VendorCatalog } from "../lib/modelsApi"; import { effortRowLabel, effortRowsFor, + MODEL_DEFAULT, + modelRowLabel, modelRowsFor, selectDraftModel, + switchDraftVendor, vendorSpec, visibleProtocols, VENDORS, @@ -337,6 +340,7 @@ export function ChatComposer({ allowedVendors, catalog: catalogOverride, topSlot, + accountSlot, sendTestId = "composer-send", uploadSlug, prefill, @@ -380,6 +384,9 @@ export function ChatComposer({ catalog?: VendorCatalog; /** Home's inline new-project row renders inside the composer card. */ topSlot?: React.ReactNode; + /** Claude account menu, beside the model menu: the account to start + * with (new session) or the one the session runs on, switchable (#236). */ + accountSlot?: React.ReactNode; sendTestId?: string; /** Project slug uploads + the skill picker target. Omit (e.g. while the * Home new-project row is open) to disable attaching with a hint. */ @@ -397,6 +404,7 @@ export function ChatComposer({ const catalog = catalogOverride ?? fetchedCatalog; const [text, setText] = useState(() => loadDraft(draftKey)); const [menuOpen, setMenuOpen] = useState(false); + const [vendorOpen, setVendorOpen] = useState(false); const [attachOpen, setAttachOpen] = useState(false); const [skillsOpen, setSkillsOpen] = useState(false); const [attachments, setAttachments] = useState([]); @@ -412,6 +420,7 @@ export function ChatComposer({ const composingRef = useRef(false); const taRef = useRef(null); const selRef = useRef(null); + const vendorRef = useRef(null); const attachRef = useRef(null); const fileRef = useRef(null); @@ -459,20 +468,23 @@ export function ChatComposer({ autoGrow(); }, [text, autoGrow]); - // Close either menu on any outside click. + // Close any menu on an outside click; a click inside one menu still closes + // its siblings (each menu button stops propagation, so they handle that). useEffect(() => { - if (!menuOpen && !attachOpen) return; + if (!menuOpen && !attachOpen && !vendorOpen) return; const close = (e: MouseEvent) => { const target = e.target instanceof Node ? e.target : null; if (target && selRef.current?.contains(target)) return; + if (target && vendorRef.current?.contains(target)) return; if (target && attachRef.current?.contains(target)) return; setMenuOpen(false); + setVendorOpen(false); setAttachOpen(false); setSkillsOpen(false); }; document.addEventListener("click", close); return () => document.removeEventListener("click", close); - }, [menuOpen, attachOpen]); + }, [menuOpen, attachOpen, vendorOpen]); // ---- attachments ----------------------------------------------------------- @@ -698,6 +710,19 @@ export function ChatComposer({ setMenuOpen(false); }; + const pickVendor = (vendor: VendorId) => { + setVendorOpen(false); + if (locked) { + toastBus.handler?.info( + lang === "en" + ? "The harness is fixed for this session — start a new session to change it." + : "本会话的 vendor 已固定 —— 新建会话可更换。", + ); + return; + } + onDraftChange(switchDraftVendor(draft, vendor)); + }; + /** `effort` is the vendor's own token, verbatim; `""` = vendor default. */ const pickEffort = (effort: string) => { if (locked) { @@ -719,9 +744,15 @@ export function ChatComposer({ }; const spec = vendorSpec(draft.vendor); - // Vendor is ALWAYS spelled out next to the model — a bare "默认"/"opus" - // plus a colored dot left the harness unreadable (owner feedback). - const modelText = modelLabel ?? draft.model; + // The vendor has its own button now; the model button names the model — + // for the vendor default, the concrete id the daemon observed (owner + // 2026-11-08), else 默认. A conversation shows what the session reports. + const modelText = modelLabel !== undefined + ? modelLabel || MODEL_DEFAULT + : modelRowLabel(draft.vendor, draft.model, catalog); + const vendorChoices = allowedVendors + ? VENDORS.filter((v) => allowedVendors.includes(v.id)) + : VENDORS; const effortText = effortRowLabel(effortLabel ?? draft.effort); const showStop = !!busy && !scheduleMode && !text.trim() && !!onStop; const protocols = visibleProtocols(draft.vendor); @@ -992,41 +1023,75 @@ export function ChatComposer({ {t("approve")}
-
+ {accountSlot} +
+ +
+ {vendorChoices.map((v) => ( + + ))} +
+
+
- {(allowedVendors - ? VENDORS.filter((v) => allowedVendors.includes(v.id)) - : VENDORS - ).map((v) => ( -
-
{v.label}
- {modelRowsFor(v.id, catalog).map((m) => ( - - ))} -
- ))} +
{`${t("model")}(${spec.label})`}
+ {modelRowsFor(draft.vendor, catalog).map((m) => { + const display = catalog?.[spec.id]?.models.find((entry) => entry.id === m)?.display_name; + return ( + + ); + })} {efforts.length > 1 ? ( <> {/* One interpolated string, not adjacent children: the diff --git a/crates/ccteam-web/web/src/components/CswapAccountPicker.test.tsx b/crates/ccteam-web/web/src/components/CswapAccountPicker.test.tsx new file mode 100644 index 00000000..8d617d06 --- /dev/null +++ b/crates/ccteam-web/web/src/components/CswapAccountPicker.test.tsx @@ -0,0 +1,151 @@ +// @vitest-environment jsdom +import { act } from "react"; +import { createRoot } from "react-dom/client"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import { CswapAccountPicker } from "./CswapAccountPicker"; +import { createSession, switchSessionClaudeAccount, type CswapAccount } from "../lib/sessionsApi"; + +afterEach(() => { vi.unstubAllGlobals(); }); + +async function mount(body: unknown, onChange: (value: string) => void = () => {}) { + vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true); + const fetcher = vi.fn().mockResolvedValue(new Response(JSON.stringify(body))); + vi.stubGlobal("fetch", fetcher); + const container = document.createElement("div"); + document.body.appendChild(container); + const root = createRoot(container); + await act(() => root.render()); + const button = container.querySelector("[data-testid=claude-account-btn]")!; + const menu = () => container.querySelector(".sel")!; + return { fetcher, container, root, button, menu }; +} + +describe("optional cswap account selection", () => { + it("does not discover on mount and keeps default login usable without cswap", async () => { + const { fetcher, container, root, button, menu } = await mount({ available: false, accounts: [] }); + expect(fetcher).not.toHaveBeenCalled(); + expect(button.textContent).toContain("默认登录"); + await act(() => button.click()); + expect(fetcher).toHaveBeenCalledOnce(); + expect(menu().classList.contains("open")).toBe(true); + const items = container.querySelectorAll("[role=menuitemradio]"); + expect(items).toHaveLength(1); + expect(items[0].getAttribute("aria-checked")).toBe("true"); + expect(container.textContent).toContain("继续使用默认登录"); + expect(container.textContent).toContain("重试"); + await act(() => root.unmount()); + container.remove(); + }); + + it("picks an account from its own menu and closes on outside press", async () => { + const onChange = vi.fn(); + const account = { id: "a".repeat(64), slot: "2", label: "work", active: false }; + const { container, root, button, menu } = await mount({ available: true, accounts: [account] }, onChange); + await act(() => button.click()); + const items = container.querySelectorAll("[role=menuitemradio]"); + expect(items[1].textContent).toContain("#2 work"); + await act(() => items[1].click()); + expect(onChange).toHaveBeenCalledWith(account.id); + expect(menu().classList.contains("open")).toBe(false); + await act(() => button.click()); + expect(menu().classList.contains("open")).toBe(true); + await act(() => { document.body.dispatchEvent(new Event("pointerdown", { bubbles: true })); }); + expect(menu().classList.contains("open")).toBe(false); + await act(() => root.unmount()); + container.remove(); + }); + + it("shows number, name and the quota windows the plan has, never an email domain", async () => { + const { container, root, button } = await mount({ available: true, accounts: [ + { id: "a".repeat(64), slot: "1", label: "cloud", active: false, five_hour_pct: 11, seven_day_pct: 100 }, + { id: "b".repeat(64), slot: "5", label: "sddenter", active: true, seven_day_pct: 100 }, + { id: "c".repeat(64), slot: "6", label: "sudongdong", active: false, usage_status: "relogin_required" }, + { id: "d".repeat(64), slot: "7", label: "stale", active: false, five_hour_pct: 3, seven_day_pct: 9, usage_status: "unavailable" }, + ] }); + await act(() => button.click()); + const rows = [...container.querySelectorAll("[role=menuitemradio]")].slice(1).map((row) => row.textContent); + expect(rows[0]).toBe("#1 cloud5h:11%7d:100%✓"); + expect(rows[1]).toBe("#5 sddenter7d:100%当前默认✓"); + expect(rows[2]).toBe("#6 sudongdong需重新登录✓"); + expect(rows[3]).toContain("7d:9%上次"); + expect(container.textContent).not.toContain("@"); + await act(() => root.unmount()); + container.remove(); + }); + + it("in a running session names the default login's account and switches in place (#236)", async () => { + vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true); + const cloud = { id: "a".repeat(64), slot: "1", label: "cloud", active: true }; + const work = { id: "b".repeat(64), slot: "2", label: "work", active: false }; + const fetcher = vi.fn().mockImplementation(() => + Promise.resolve(new Response(JSON.stringify({ available: true, accounts: [cloud, work] })))); + vi.stubGlobal("fetch", fetcher); + let attempt = 0; + const onChange = vi.fn(() => (attempt++ === 0 + ? Promise.reject(new Error("a turn is running; wait for it to finish or interrupt it first")) + : Promise.resolve())); + const container = document.createElement("div"); + document.body.appendChild(container); + const root = createRoot(container); + await act(() => root.render()); + expect(fetcher).toHaveBeenCalledOnce(); + const button = container.querySelector("[data-testid=claude-account-btn]")!; + expect(button.textContent).toBe("默认 · #1 cloud"); + await act(() => button.click()); + const menu = () => container.querySelector(".sel")!; + const rows = () => container.querySelectorAll("[role=menuitemradio]"); + expect(container.textContent).toContain("下一条消息在同一会话里按新账号继续"); + await act(() => rows()[2].click()); + expect(onChange).toHaveBeenLastCalledWith(work.id); + expect(menu().classList.contains("open")).toBe(true); + expect(container.querySelector(".account-note.err")?.textContent).toContain("a turn is running"); + await act(() => rows()[2].click()); + expect(menu().classList.contains("open")).toBe(false); + await act(() => root.unmount()); + container.remove(); + }); + + it("stays out of a session's way without cswap unless the session is bound", async () => { + vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true); + vi.stubGlobal("fetch", vi.fn().mockImplementation(() => + Promise.resolve(new Response(JSON.stringify({ available: false, accounts: [], message: "cswap is not installed" }))))); + const bound: CswapAccount = { id: "c".repeat(64), slot: "3", label: "solo", active: false }; + const container = document.createElement("div"); + document.body.appendChild(container); + const root = createRoot(container); + await act(() => root.render( {}} lang="zh" + session={{ sid: "s1", bound: null }} />)); + expect(container.querySelector("[data-testid=claude-account-btn]")).toBeNull(); + await act(() => root.render( {}} lang="zh" + session={{ sid: "s2", bound }} />)); + expect(container.querySelector("[data-testid=claude-account-btn]")?.textContent).toBe("#3 solo"); + await act(() => root.unmount()); + container.remove(); + }); + + it("asks the daemon to switch with the account id, or null for the default login", async () => { + const fetcher = vi.fn().mockImplementation(() => Promise.resolve(new Response( + JSON.stringify({ sid: "s1", claude_account: null, changed: true, released: true })))); + vi.stubGlobal("fetch", fetcher); + await switchSessionClaudeAccount("s1", "stable-account-id"); + await switchSessionClaudeAccount("s1", null); + expect(fetcher.mock.calls[0][0]).toBe("/api/v1/sessions/s1/claude-account"); + expect(fetcher.mock.calls[0][1].method).toBe("PUT"); + expect(JSON.parse(fetcher.mock.calls[0][1].body)).toEqual({ claude_account: "stable-account-id" }); + expect(JSON.parse(fetcher.mock.calls[1][1].body)).toEqual({ claude_account: null }); + fetcher.mockImplementation(() => Promise.resolve(new Response( + JSON.stringify({ error: "history is still private" }), + { status: 422, headers: { "content-type": "application/json" } }))); + await expect(switchSessionClaudeAccount("s1", null)).rejects.toThrow("history is still private"); + }); + + it("sends an explicit reference only when the caller selected an account", async () => { + const fetcher = vi.fn().mockImplementation(() => Promise.resolve(new Response('{"sid":"s1"}'))); + vi.stubGlobal("fetch", fetcher); + await createSession("project", { role: "", vendor: "claude" }); + expect(JSON.parse(fetcher.mock.calls[0][1].body)).not.toHaveProperty("claude_account"); + await createSession("project", { role: "", vendor: "claude", claude_account: "stable-account-id" }); + expect(JSON.parse(fetcher.mock.calls[1][1].body).claude_account).toBe("stable-account-id"); + }); +}); diff --git a/crates/ccteam-web/web/src/components/CswapAccountPicker.tsx b/crates/ccteam-web/web/src/components/CswapAccountPicker.tsx new file mode 100644 index 00000000..a62348cd --- /dev/null +++ b/crates/ccteam-web/web/src/components/CswapAccountPicker.tsx @@ -0,0 +1,173 @@ +import { useEffect, useRef, useState } from "react"; +import { CircleUserRound } from "lucide-react"; +import { accountName, getCswapAccounts, type CswapAccount, type CswapAccounts } from "../lib/sessionsApi"; +import type { Lang } from "../lib/i18n"; + +const STATUS: Record = { + relogin_required: ["需重新登录", "re-login needed"], + token_expired: ["令牌过期", "token expired"], + no_credentials: ["无凭据", "no credentials"], + keychain_unavailable: ["钥匙串不可用", "keychain unavailable"], + foreign_credential: ["凭据不符", "foreign credential"], + unavailable: ["额度暂不可读", "quota unavailable"], +}; + +/** 5h / 7d cells in fixed columns so rows line up; a plan without a 5h + * window (Max) leaves that cell empty. No reading → cswap's status. */ +function Quota({ account, en }: { account: CswapAccount; en: boolean }) { + const { five_hour_pct: fiveHour, seven_day_pct: sevenDay, usage_status: status } = account; + if (fiveHour == null && sevenDay == null) { + const text = status ? (STATUS[status]?.[en ? 1 : 0] ?? status) : ""; + return {text}; + } + // A non-ok status next to numbers means they are cswap's last good reading. + const stale = status ? + {en ? "last" : "上次"} + : null; + const cell = (key: string, pct: number | undefined, extra?: React.ReactNode) => + {pct == null ? null : <>{key}:{pct}%} + {extra} + ; + return <> + {cell("5h", fiveHour)} + {cell("7d", sevenDay, stale)} + ; +} + +/** Claude account menu, a sibling of the model menu. New session: picks the + * account to start with; optional cswap discovery runs only when the user + * first opens it. Running session (`session` set): names the account the + * session runs on — the default login by its current cswap account — and a + * pick switches the session (#236); it hides itself on a machine without + * cswap unless the session is bound to an account. */ +export function CswapAccountPicker({ value, onChange, lang, session }: { + value: string; + /** May return a promise (a session switch): the menu stays open showing + * the server's reason when it rejects. */ + onChange: (value: string) => void | Promise; + lang: Lang; + session?: { sid: string; bound: CswapAccount | null }; +}) { + const [open, setOpen] = useState(false); + const [accounts, setAccounts] = useState(null); + const [loading, setLoading] = useState(false); + const [error, setError] = useState(""); + const [switching, setSwitching] = useState(false); + const [switchError, setSwitchError] = useState(""); + const ref = useRef(null); + const en = lang === "en"; + const load = () => { + if (loading) return; + setLoading(true); + setError(""); + void getCswapAccounts().then(setAccounts).catch((error: unknown) => { + setError(error instanceof Error ? error.message : String(error)); + }).finally(() => setLoading(false)); + }; + // A running session names its account up front (one cached discovery per + // session opened, never a poll). Callers key the picker by sid, so a new + // session starts from fresh state. + const sid = session?.sid; + useEffect(() => { + if (!sid) return; + let alive = true; + void getCswapAccounts().then((found) => { + if (alive) setAccounts(found); + }).catch(() => {}); + return () => { alive = false; }; + }, [sid]); + // pointerdown, not click: the neighbouring model button stops its click + // from propagating, which would otherwise leave both menus open. + useEffect(() => { + if (!open) return; + const close = (event: PointerEvent) => { + if (event.target instanceof Node && ref.current?.contains(event.target)) return; + setOpen(false); + }; + document.addEventListener("pointerdown", close); + return () => document.removeEventListener("pointerdown", close); + }, [open]); + const pick = (id: string) => { + if (switching) return; + if (id === value) { + setOpen(false); + return; + } + setSwitchError(""); + const pending = onChange(id); + if (!pending) { + setOpen(false); + return; + } + setSwitching(true); + void pending.then(() => setOpen(false)).catch((error: unknown) => { + setSwitchError(error instanceof Error ? error.message : String(error)); + }).finally(() => setSwitching(false)); + }; + const title = en ? "Claude account" : "Claude 账号"; + const defaultAccount = accounts?.accounts.find((account) => account.active); + const selected = accounts?.accounts.find((account) => account.id === value) + ?? (session?.bound && session.bound.id === value ? session.bound : undefined); + const defaultLabel = defaultAccount + ? `${en ? "Default" : "默认"} · ${accountName(defaultAccount)}` + : (en ? "Default login" : "默认登录"); + const label = !value ? defaultLabel : selected ? accountName(selected) : "cswap"; + const unavailable = accounts?.available === false; + if (session && unavailable && !value) return null; + const guide = session + ? (en ? "Switching ends this session's process; your next message continues the same conversation on the new account (its prompt cache is rebuilt)." + : "切换会结束当前进程,下一条消息在同一会话里按新账号继续(提示缓存会重建)。") + : (en ? "Default login follows cswap auto; a chosen account stays on that account." : "默认登录会跟随 cswap auto 切换;指定账号固定使用该账号。"); + const status = switching ? (en ? "Switching…" : "切换中…") + : switchError ? switchError + : loading ? (en ? "Checking cswap…" : "检查 cswap…") + : error ? error + : unavailable + ? `${en ? "cswap unavailable; default login remains available." : "cswap 不可用,仍可继续使用默认登录。"} ${accounts.message ?? ""}` + : accounts?.accounts.length === 0 + ? (en ? "cswap has no accounts yet. You can still use default login." : "cswap 里还没有账号,仍可使用默认登录。") + : accounts ? guide : ""; + return ( +
+ +
+
{title}
+ + {accounts?.accounts.map((account) => )} + {status ?

{status}

: null} + {(error || unavailable) && !loading ? : null} +
+
+ ); +} diff --git a/crates/ccteam-web/web/src/components/Markdown.test.tsx b/crates/ccteam-web/web/src/components/Markdown.test.tsx new file mode 100644 index 00000000..901c8c39 --- /dev/null +++ b/crates/ccteam-web/web/src/components/Markdown.test.tsx @@ -0,0 +1,80 @@ +// @vitest-environment jsdom +import { act } from "react"; +import { createRoot, type Root } from "react-dom/client"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { Markdown } from "./Markdown"; + +let container: HTMLDivElement; +let root: Root; +beforeEach(() => { + vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true); + container = document.createElement("div"); + document.body.append(container); + root = createRoot(container); +}); +afterEach(async () => { + await act(() => root.unmount()); + container.remove(); + vi.restoreAllMocks(); + vi.unstubAllGlobals(); +}); + +describe("Markdown code copy", () => { + it("adds an accessible icon for each block and copies only its exact code", async () => { + const writeText = vi.fn().mockResolvedValue(undefined); + Object.defineProperty(navigator, "clipboard", { configurable: true, value: { writeText } }); + await act(() => root.render()); + const buttons = container.querySelectorAll("pre button"); + expect(buttons).toHaveLength(2); + expect(buttons[0].getAttribute("aria-label")).toBe("复制代码"); + expect(buttons[0].querySelector("svg")).not.toBeNull(); + await act(() => root.render()); + expect(container.querySelectorAll("pre button")).toHaveLength(2); + await act(() => buttons[0].click()); + expect(writeText).toHaveBeenCalledWith('const x = "";\n'); + expect(buttons[0].getAttribute("aria-label")).toBe("已复制"); + expect(buttons[1].getAttribute("aria-label")).toBe("复制代码"); + }); + + it("uses the shared fallback and reports a failed copy honestly", async () => { + Object.defineProperty(navigator, "clipboard", { configurable: true, value: undefined }); + const exec = vi.fn().mockReturnValue(false); + Object.defineProperty(document, "execCommand", { configurable: true, value: exec }); + await act(() => root.render()); + const button = container.querySelector("button")!; + await act(() => button.click()); + expect(exec).toHaveBeenCalledWith("copy"); + expect(button.getAttribute("aria-label")).toBe("复制失败,点击重试"); + }); +}); + +describe("Markdown file previews", () => { + it("replaces document hrefs with minted same-site previews while retaining ordinary links", async () => { + const resolve = vi.fn().mockResolvedValue("/api/v1/projects/team/files/preview/fresh/docs/issue.md"); + const origin = window.location.origin; + await act(() => root.render()); + expect(resolve).toHaveBeenCalledExactlyOnceWith({ path: "/repo/docs/issue.md" }); + const links = container.querySelectorAll("a"); + expect(links[0].getAttribute("href")).toBe("/api/v1/projects/team/files/preview/fresh/docs/issue.md"); + expect(links[0].target).toBe("_blank"); + expect(links[1].getAttribute("href")).toBe("https://other.example/a.md"); + expect(links[2].getAttribute("href")).toBe("/repo/README.md:12"); + }); + + it("renews normal, modified and middle-click previews after backend tickets are lost", async () => { + const resolve = vi.fn().mockResolvedValue("/api/v1/projects/team/files/preview/old/README.md"); + const replace = vi.fn(); + vi.spyOn(window, "open").mockReturnValue({ opener: null, location: { replace }, close: vi.fn() } as unknown as Window); + await act(() => root.render()); + resolve.mockResolvedValue("/api/v1/projects/team/files/preview/new/README.md"); + const link = container.querySelector("a")!; + for (const [type, init] of [["click", {}], ["click", { ctrlKey: true }], ["auxclick", { button: 1 }]] as const) { + await act(() => { link.dispatchEvent(new MouseEvent(type, { bubbles: true, cancelable: true, ...init })); }); + expect(resolve).toHaveBeenLastCalledWith({ path: "README.md" }, true); + expect(replace).toHaveBeenLastCalledWith("/api/v1/projects/team/files/preview/new/README.md"); + } + }); +}); diff --git a/crates/ccteam-web/web/src/components/Markdown.tsx b/crates/ccteam-web/web/src/components/Markdown.tsx index 9be564d8..8c0b4d29 100644 --- a/crates/ccteam-web/web/src/components/Markdown.tsx +++ b/crates/ccteam-web/web/src/components/Markdown.tsx @@ -4,69 +4,127 @@ // button is added to the DOM AFTER the sanitized innerHTML, so it never rides // through DOMPurify / can't be injected by message content). -import { useEffect, useMemo, useRef } from "react"; +import { useEffect, useMemo, useRef, type MouseEvent } from "react"; import { renderMarkdown } from "../lib/markdown"; -import { fileLinkTarget, type FileTarget } from "../lib/filesApi"; +import { fileLinkTarget, supportsFilePreview, type FileTarget } from "../lib/filesApi"; +import { copyText } from "../lib/clipboard"; + +// Static SVG only; never interpolate message content into button markup. +const COPY_ICON = ''; +const CHECK_ICON = ''; +const ERROR_ICON = ''; export function Markdown({ content, className, onFileOpen, + resolveFilePreview, }: { content: string; className?: string; onFileOpen?: (target: FileTarget) => void; + resolveFilePreview?: (target: FileTarget, renew?: boolean) => Promise; }) { const ref = useRef(null); + const previewLinks = useRef(new WeakMap()); + const ordinaryLinks = useRef(new WeakSet()); const html = useMemo(() => renderMarkdown(content), [content]); + // React otherwise reapplies a new innerHTML object on parent updates, + // removing the post-render controls without rerunning the html effect. + const markup = useMemo(() => ({ __html: html }), [html]); useEffect(() => { const root = ref.current; if (!root) return; + const timers = new Set(); + const buttons: HTMLButtonElement[] = []; root.querySelectorAll("pre").forEach((pre) => { if (pre.querySelector(".code-copy")) return; pre.classList.add("has-copy"); const btn = document.createElement("button"); btn.type = "button"; btn.className = "code-copy"; - btn.textContent = "复制"; - btn.addEventListener("click", () => { - const code = - pre.querySelector("code")?.textContent ?? pre.textContent ?? ""; - void navigator.clipboard?.writeText(code); - btn.textContent = "已复制"; - window.setTimeout(() => { - btn.textContent = "复制"; - }, 1200); + const label = (text: string, icon: string) => { + btn.setAttribute("aria-label", text); + btn.title = text; + btn.innerHTML = icon; + }; + label("复制代码", COPY_ICON); + btn.addEventListener("click", async () => { + const code = pre.querySelector("code")?.textContent ?? ""; + const copied = await copyText(code); + if (!root.contains(btn)) return; + label(copied ? "已复制" : "复制失败,点击重试", copied ? CHECK_ICON : ERROR_ICON); + const timer = window.setTimeout(() => { + label("复制代码", COPY_ICON); + timers.delete(timer); + }, 1600); + timers.add(timer); }); pre.appendChild(btn); + buttons.push(btn); }); + return () => { + timers.forEach(window.clearTimeout); + buttons.forEach((button) => button.remove()); + }; }, [html]); + useEffect(() => { + const root = ref.current; + if (!root || !resolveFilePreview) return; + let active = true; + root.querySelectorAll("a[href]").forEach((link) => { + const target = previewLinks.current.get(link) ?? fileLinkTarget(link.getAttribute("href") ?? "", window.location.origin); + if (!target || target.line || !supportsFilePreview(target.path)) return; + void resolveFilePreview(target).then((url) => { + if (!active) return; + if (!url) { ordinaryLinks.current.add(link); return; } + previewLinks.current.set(link, target); + link.setAttribute("href", url); + link.target = "_blank"; + link.rel = "noopener noreferrer"; + }).catch(() => { + // A failed preview keeps the ordinary file-workspace click path. + }); + }); + return () => { active = false; }; + }, [html, resolveFilePreview]); + + const openLink = (event: MouseEvent) => { + const link = (event.target as Element).closest("a[href]"); + if (!link || ordinaryLinks.current.has(link)) return; + const preview = previewLinks.current.get(link); + if (preview && resolveFilePreview) { + event.preventDefault(); + // Each activation mints a fresh capability: TTL and daemon restarts + // invalidate old tickets, including on modified and middle clicks. + const page = window.open("about:blank", "_blank"); + if (page) page.opener = null; + void resolveFilePreview(preview, true).then((url) => { + if (page && url) { + link.setAttribute("href", url); + page.location.replace(url); + } else { page?.close(); onFileOpen?.(preview); } + }).catch(() => { page?.close(); onFileOpen?.(preview); }); + return; + } + if (!onFileOpen || event.button !== 0 || event.ctrlKey || event.metaKey || event.shiftKey || event.altKey) return; + const target = fileLinkTarget(link.getAttribute("href") ?? "", window.location.origin); + if (target) { + event.preventDefault(); + onFileOpen(target); + } + }; + return (
{ - if ( - !onFileOpen || - event.ctrlKey || - event.metaKey || - event.shiftKey || - event.altKey - ) - return; - const link = (event.target as Element).closest("a[href]"); - const target = link - ? fileLinkTarget(link.getAttribute("href") ?? "") - : null; - if (target) { - event.preventDefault(); - onFileOpen(target); - } - }} + onClick={openLink} + onAuxClick={(event) => { if (event.button === 1) openLink(event); }} // html is renderMarkdown() output = marked + DOMPurify.sanitize. - dangerouslySetInnerHTML={{ __html: html }} + dangerouslySetInnerHTML={markup} /> ); } diff --git a/crates/ccteam-web/web/src/index.css b/crates/ccteam-web/web/src/index.css index ff728363..1948c97d 100644 --- a/crates/ccteam-web/web/src/index.css +++ b/crates/ccteam-web/web/src/index.css @@ -556,6 +556,38 @@ button { font-family: inherit; cursor: pointer; } } .model-btn:hover { background: var(--bg-soft); color: var(--text); } .model-btn .eff { color: var(--text-faint); } +.account-btn svg { width: 15px; height: 15px; flex: none; } +.account-btn .account-label { max-width: 10rem; overflow: hidden; text-overflow: ellipsis; } +.account-menu { width: max-content; max-width: min(420px, calc(100vw - 48px)); } +.account-menu .sel-item { white-space: nowrap; } +.account-menu .sel-item .label { min-width: 0; overflow: hidden; text-overflow: ellipsis; } +/* name | 5h | 7d | marker | ✓ — fixed quota columns so rows line up. */ +.account-menu .sel-item.account-row { + display: grid; grid-template-columns: minmax(6em, 1fr) 4.6em minmax(5.2em, auto) auto auto; + align-items: center; column-gap: 10px; +} +.account-row .quota { display: inline-flex; gap: 4px; color: var(--text-muted); font-size: 12.5px; font-variant-numeric: tabular-nums; } +.account-row .quota .v { min-width: 4ch; text-align: right; color: var(--text); } +.account-row .quota-status { grid-column: 2 / 4; color: var(--text-faint); font-size: 12px; } +.account-row .quota-stale { color: var(--text-faint); font-size: 11px; } +.account-row .sub, .account-row .check { margin-left: 0; padding-left: 0; } +.account-menu .account-note { margin: 4px 10px 6px; max-width: 18rem; font-size: 11.5px; line-height: 1.45; color: var(--text-muted); white-space: normal; } +.account-menu .account-note.err { color: var(--red-text); } +.account-menu .sel-item[disabled] { opacity: .55; cursor: progress; } +.account-menu .account-retry { color: #0E7490; } +html.dark .account-menu .account-retry { color: #67e8f9; } +/* Phones: the row must keep mic + send on screen, so labels yield first — + HITL and account go icon-only (state stays visible), effort hides, and the + model label ellipsizes. */ +@media (max-width: 600px) { + .account-btn .account-label, .hitl-btn span, .model-btn .eff { display: none; } + .hitl-btn { padding: 6px 8px; } + .composer-row .right, .composer-row .model-sel, .model-btn { min-width: 0; } + .model-btn .model-label { min-width: 0; overflow: hidden; text-overflow: ellipsis; } + /* The account button sits mid-row; anchor its menu to the row's right edge. */ + .composer-row .right { position: relative; } + .composer-row .account-sel { position: static; } +} .send-btn { width: 36px; height: 36px; border-radius: 50%; flex: none; @@ -1140,7 +1172,12 @@ html.dark .cockpit-markdown a { color: #67e8f9; } position: absolute; top: 0.3rem; right: 0.3rem; - padding: 0.15rem 0.45rem; + display: inline-flex; + align-items: center; + justify-content: center; + width: 1.75rem; + height: 1.75rem; + padding: 0.3rem; font-family: var(--font-sans); font-size: 0.65rem; line-height: 1.3; @@ -1149,11 +1186,8 @@ html.dark .cockpit-markdown a { color: #67e8f9; } border: 1px solid var(--border); border-radius: 0.3rem; cursor: pointer; - opacity: 0; - transition: opacity 0.12s; } -.cockpit-markdown pre.has-copy:hover .code-copy, -.cockpit-markdown .code-copy:focus-visible { opacity: 1; } +.cockpit-markdown pre.has-copy { padding-top: 2.2rem; } .cockpit-markdown .code-copy:hover { color: var(--text); } .cockpit-markdown hr { border: none; border-top: 1px solid var(--border-soft); margin: 0.75rem 0; } .cockpit-markdown .cockpit-table-wrap { @@ -1287,15 +1321,15 @@ select:focus-visible, @container query. `min-width: 0` keeps a wide tree from stretching the canvas and squeezing the panel. */ .agents-canvas { flex: 1; min-width: 0; overflow: auto; padding: 8px 20px; container-type: inline-size; container-name: agents-canvas; } -.agents-tree { min-width: 780px; display: flex; flex-direction: column; gap: 10px; padding-bottom: 12px; } +.agents-tree { min-width: 850px; display: flex; flex-direction: column; gap: 10px; padding-bottom: 12px; } .agents-tree-project { width: max-content; min-width: 100%; border: 1px solid var(--border-soft); border-radius: 10px; overflow: hidden; background: var(--bg-card); } .agents-tree-project-head { height: 26px; padding: 0 10px; display: flex; align-items: center; justify-content: space-between; gap: 12px; background: var(--bg-soft); border-bottom: 1px solid var(--border-soft); color: var(--text-faint); font-size: 11px; } .agents-tree-project-head .mono { color: var(--text-muted); font-weight: 600; } .agents-tree-project-name { display: inline-flex; align-items: center; gap: 4px; min-width: 0; margin-left: -6px; } .agents-tree-project-name .agents-tree-toggle:hover { background: var(--bg-card); } -.agents-tree-row { --tree-guide: var(--border); min-width: max-content; height: 28px; display: grid; grid-template-columns: auto 18px 34px 50px minmax(140px, 1fr) 150px 8px 90px 86px 38px auto; gap: 7px; align-items: center; padding: 0 10px 0 4px; border-bottom: 1px solid color-mix(in srgb, var(--border-soft) 65%, transparent); color: var(--text-muted); cursor: pointer; font-size: 12px; } +.agents-tree-row { --tree-guide: var(--border); min-width: max-content; height: 28px; display: grid; grid-template-columns: auto 18px 34px 50px minmax(140px, 1fr) 150px 64px 8px 90px 86px 38px auto; gap: 7px; align-items: center; padding: 0 10px 0 4px; border-bottom: 1px solid color-mix(in srgb, var(--border-soft) 65%, transparent); color: var(--text-muted); cursor: pointer; font-size: 12px; } /* Host badge column exists only when the graph spans >1 host. */ -.agents-tree.with-host .agents-tree-row { grid-template-columns: auto 18px 34px 50px minmax(140px, 1fr) 150px 90px 8px 90px 86px 38px auto; } +.agents-tree.with-host .agents-tree-row { grid-template-columns: auto 18px 34px 50px minmax(140px, 1fr) 150px 64px 90px 8px 90px 86px 38px auto; } /* Identity / metrics groups are pure layout handles: transparent here (the row is one flat grid line), real flex boxes in card mode below. */ .agents-tree-main, .agents-tree-meta { display: contents; } @@ -1319,6 +1353,9 @@ select:focus-visible, .agents-tree-model { color: var(--text-faint); font-size: 11px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } .agents-tree-active { white-space: nowrap; text-align: right; } .agents-tree-cost, .agents-tree-turns { color: var(--text-muted); text-align: right; font-variant-numeric: tabular-nums; } +/* Live context occupancy — same ⚠ threshold + accent as the chat footer's `ctx N%`. */ +.agents-tree-ctx { color: var(--text-faint); font-size: 11px; white-space: nowrap; text-align: right; font-variant-numeric: tabular-nums; } +.agents-tree-ctx.warn { color: var(--accent, #b45309); font-weight: 600; } .agents-tree-row .dot.busy { animation: agent-active-pulse 1.8s ease-in-out infinite; } @media (prefers-reduced-motion: reduce) { .agents-tree-row .dot.busy { animation: none; } @@ -1365,7 +1402,7 @@ select:focus-visible, } /* Card mode — the row stops being one wide table line and becomes two: [guide][toggle] vendor · sid · title …………………………… 打开 ↗ - [guide][toggle] claude-opus-5 · high · host ● 2分钟前 $0.42 12t + [guide][toggle] claude-opus-5 · high · ctx 63% · host ● 2分钟前 $0.42 12t The tree guide + toggle span both lines (so depth stays readable) and the metrics line starts under the title, not at the card edge. Nothing scrolls horizontally at any width. */ @@ -1394,7 +1431,7 @@ select:focus-visible, /* Title + model truncate rather than push the card wider than the canvas. */ .agents-tree-title { flex: 1 1 auto; min-width: 0; } .agents-tree-model { flex: 0 1 auto; min-width: 0; } - .agents-tree-active, .agents-tree-cost, .agents-tree-turns { text-align: left; } + .agents-tree-active, .agents-tree-cost, .agents-tree-turns, .agents-tree-ctx { text-align: left; } } /* v0.9.11 TEAM-2 — 拓扑|分工 tab seg + charter tab (roster cards + editor). */ .agents-seg { margin: 0 28px 8px; } diff --git a/crates/ccteam-web/web/src/lib/agentsApi.ts b/crates/ccteam-web/web/src/lib/agentsApi.ts index dea35ada..bedab751 100644 --- a/crates/ccteam-web/web/src/lib/agentsApi.ts +++ b/crates/ccteam-web/web/src/lib/agentsApi.ts @@ -16,6 +16,11 @@ export interface AgentNode { * (`low`/`medium`/`high`/`xhigh`/`max`); absent on idle nodes and on * vendors with no effort axis. */ effort?: string | null; + /** How full the context window is RIGHT NOW (0-100, rounded) — the same + * live statusline join as `model`. Only a session ccteam holds a process + * for has a live window; every other node omits it (never a stale or + * fabricated number). */ + context_pct?: number | null; host: string; /** What the session is DOING: `working` | `idle` | `stale` | `stuck`, or * `detached` for a body that outlived the daemon. */ diff --git a/crates/ccteam-web/web/src/lib/filesApi.test.ts b/crates/ccteam-web/web/src/lib/filesApi.test.ts index 5bac9368..08a7f97f 100644 --- a/crates/ccteam-web/web/src/lib/filesApi.test.ts +++ b/crates/ccteam-web/web/src/lib/filesApi.test.ts @@ -1,12 +1,22 @@ -import { describe, expect, it } from "vitest"; +import { afterEach, describe, expect, it, vi } from "vitest"; import { fileLinkTarget, + createFilePreviewResolver, openFileTab, projectRelativePath, supportsFilePreview, } from "./filesApi"; describe("project file navigation", () => { + it("recognizes file URLs on the current origin without hardcoding a host", () => { + for (const origin of ["https://console.example", "http://localhost:7331"]) { + expect(fileLinkTarget(`${origin}/repo/docs/issue.md`, origin)).toEqual({ + path: "/repo/docs/issue.md", + }); + expect(fileLinkTarget(`${origin}/api/v1/projects/a`, origin)).toBeNull(); + expect(fileLinkTarget("https://elsewhere.example/repo/issue.md", origin)).toBeNull(); + } + }); it("shares preview controls between HTML and Markdown documents", () => { for (const path of [ "README.md", @@ -73,3 +83,43 @@ describe("project file navigation", () => { expect(projectRelativePath("/repo", p)).toBeNull(); }); }); + +describe("chat document preview links", () => { + afterEach(() => { + vi.unstubAllGlobals(); + vi.useRealTimers(); + }); + + it("resolves project paths and shares fresh tickets, then renews expired ones", async () => { + vi.useFakeTimers(); + let minted = 0; + const fetcher = vi.fn(async (_url: string, init?: RequestInit) => + new Response(JSON.stringify(init?.method === "POST" + ? { url: `/api/v1/projects/team/files/preview/t${++minted}/docs/issue.md`, expires_in: 3600 } + : { root: "/repo", paths: [], git_status: {}, truncated: false })), + ); + vi.stubGlobal("fetch", fetcher); + const resolve = createFilePreviewResolver("team"); + const first = await Promise.all([ + resolve({ path: "/repo/docs/issue.md" }), + resolve({ path: "docs/issue.md" }), + ]); + expect(first).toEqual(Array(2).fill("/api/v1/projects/team/files/preview/t1/docs/issue.md")); + expect(fetcher).toHaveBeenCalledTimes(2); + expect(JSON.parse(fetcher.mock.calls[1][1]?.body as string)).toEqual({ path: "docs/issue.md" }); + vi.advanceTimersByTime(3600_000); + expect(await resolve({ path: "/repo/docs/issue.md" })).toContain("/preview/t2/"); + expect(await resolve({ path: "/repo/docs/issue.md" }, true)).toContain("/preview/t3/"); + }); + + it("does not mint previews for sources, line links or files outside the project", async () => { + const fetcher = vi.fn(async () => new Response(JSON.stringify({ root: "/repo" }))); + vi.stubGlobal("fetch", fetcher); + const resolve = createFilePreviewResolver("team"); + expect(await resolve({ path: "src/lib.rs" })).toBeNull(); + expect(await resolve({ path: "README.md", line: 10 })).toBeNull(); + expect(await resolve({ path: "/repository/issue.md" })).toBeNull(); + expect(await resolve({ path: "../issue.md" })).toBeNull(); + expect(fetcher).toHaveBeenCalledTimes(1); + }); +}); diff --git a/crates/ccteam-web/web/src/lib/filesApi.ts b/crates/ccteam-web/web/src/lib/filesApi.ts index b82af920..c4e565e5 100644 --- a/crates/ccteam-web/web/src/lib/filesApi.ts +++ b/crates/ccteam-web/web/src/lib/filesApi.ts @@ -59,7 +59,18 @@ export const mintFilePreview = ( /** Local Markdown references only; ordinary web/navigation links retain their * browser behavior. Project containment is checked again by the server. */ -export function fileLinkTarget(href: string): FileTarget | null { +export function fileLinkTarget(href: string, origin?: string): FileTarget | null { + // Replies may spell a local path as an absolute URL on this console. + // Compare origins, never a deployment hostname or a string prefix. + if (origin && /^(?:https?:)?\/\//i.test(href)) { + try { + const url = new URL(href, origin); + if (url.origin !== origin) return null; + href = `${url.pathname}${url.search}${url.hash}`; + } catch { + return null; + } + } if ( /^(?:https?|ftp|javascript|data|blob|mailto|tel|file):/i.test(href) || /^[a-z][a-z\d+.-]*:\/\//i.test(href) || @@ -91,6 +102,36 @@ export function fileLinkTarget(href: string): FileTarget | null { return { path, ...(line && line > 0 ? { line } : {}) }; } +/** One resolver per mounted conversation: share root discovery and preview + * requests across its messages, without caching capabilities across logins. */ +export function createFilePreviewResolver(slug: string) { + let root: Promise | undefined; + const previews = new Map }>(); + return async (target: FileTarget, renew = false): Promise => { + if (target.line || !supportsFilePreview(target.path)) return null; + root ??= getProjectFiles(slug).then((tree) => tree.root).catch((error: unknown) => { + root = undefined; + throw error; + }); + const path = projectRelativePath(await root, target.path); + if (!path) return null; + const cached = previews.get(path); + if (cached && (cached.expires === Infinity || (!renew && cached.expires > Date.now()))) return cached.url; + const entry = { + expires: Infinity, + url: mintFilePreview(slug, path).then((preview) => { + entry.expires = Date.now() + Math.max(0, preview.expires_in * 1000 - 5000); + return preview.url; + }).catch((error: unknown) => { + previews.delete(path); + throw error; + }), + }; + previews.set(path, entry); + return entry.url; + }; +} + export interface FileTab { path: string; pinned: boolean; diff --git a/crates/ccteam-web/web/src/lib/i18n.ts b/crates/ccteam-web/web/src/lib/i18n.ts index ea218f87..28b2d3cf 100644 --- a/crates/ccteam-web/web/src/lib/i18n.ts +++ b/crates/ccteam-web/web/src/lib/i18n.ts @@ -182,6 +182,9 @@ export const I18N: Record> = { busyLastEvent: "最近事件", stopTip: "停止(状态保留,可 resume)", renameTip: "重命名(双击标题也可以)", + accountDefaultLogin: "默认登录", + accountSwitched: "已切换到", + accountNextMessage: "下一条消息按新账号继续本会话", renameHint: "回车保存,Esc 取消", renameFailed: "重命名失败", newInWs: "在此工作区新建会话", @@ -392,6 +395,7 @@ export const I18N: Record> = { teamKpiCost: "累计成本", teamColTurns: "轮次", teamColModel: "模型 · effort", + teamColContext: "上下文(实时)", teamTabTopology: "拓扑", teamTabCharter: "分工", teamTabRuns: "编排", @@ -620,6 +624,9 @@ export const I18N: Record> = { busyLastEvent: "last event", stopTip: "Stop (state kept, resume anytime)", renameTip: "Rename (or double-click the title)", + accountDefaultLogin: "default login", + accountSwitched: "Switched to", + accountNextMessage: "your next message continues this session on it", renameHint: "Enter to save, Esc to cancel", renameFailed: "Rename failed", newInWs: "New session in this workspace", @@ -830,6 +837,7 @@ export const I18N: Record> = { teamKpiCost: "total cost", teamColTurns: "Turns", teamColModel: "Model · effort", + teamColContext: "Context (live)", teamTabTopology: "Topology", teamTabCharter: "Charter", teamTabRuns: "Runs", diff --git a/crates/ccteam-web/web/src/lib/modelsApi.ts b/crates/ccteam-web/web/src/lib/modelsApi.ts index 69d10b81..8c992216 100644 --- a/crates/ccteam-web/web/src/lib/modelsApi.ts +++ b/crates/ccteam-web/web/src/lib/modelsApi.ts @@ -43,6 +43,8 @@ export interface VendorModels { source?: string | null; models: VendorModelEntry[]; efforts: string[]; + /** Concrete id the vendor runs when no model is requested; null until seen. */ + default_model?: string | null; } export interface ModelsResponse { @@ -54,7 +56,15 @@ export interface ModelsResponse { * takes this structural view so it never imports a fetch module. A vendor * missing from the map (or with an empty list) means "nothing observed" and * the static registry answers instead. */ -export type VendorCatalog = Record; +export type VendorCatalog = Record< + string, + { + models: CatalogModelEntry[]; + efforts: string[]; + /** Concrete id behind the picker's default row, once the daemon saw it. */ + defaultModel?: string; + } +>; async function getJson(url: string): Promise { const res = await fetch(url, { @@ -122,6 +132,8 @@ export function indexCatalog(res: ModelsResponse | null | undefined): VendorCata if (!vendor) continue; const models = cleanModels(entry.models); catalog[vendor] = { models, efforts: cleanTokens(entry.efforts) }; + const fallback = typeof entry.default_model === "string" ? entry.default_model.trim() : ""; + if (fallback) catalog[vendor]!.defaultModel = fallback; } return catalog; } diff --git a/crates/ccteam-web/web/src/lib/sessionsApi.ts b/crates/ccteam-web/web/src/lib/sessionsApi.ts index c94b449a..3e135482 100644 --- a/crates/ccteam-web/web/src/lib/sessionsApi.ts +++ b/crates/ccteam-web/web/src/lib/sessionsApi.ts @@ -23,6 +23,7 @@ import { backgroundHeaders } from "./backgroundRequest"; * `crates/ccteam-im/src/gateway.rs::SessionView`). `sid` is the gateway * `s{n}` id; `permission_mode` is `"skip"` | `"hitl"` (W2). */ export interface SessionView { + claude_account?: CswapAccount | null; sid: string; project: string; role: string; @@ -467,6 +468,7 @@ export function resolveApproval( * server-side when omitted; pass `"hitl"` to opt the new session into W2 * IM-approval prompts for non-allowlist tool calls. */ export interface CreateSessionOpts { + claude_account?: string; role: string; vendor?: string; permission_mode?: "skip" | "hitl"; @@ -504,9 +506,72 @@ export function createSession( if (opts.model) body.model = opts.model; if (opts.effort) body.effort = opts.effort; if (opts.mode) body.mode = opts.mode; + if (opts.claude_account) body.claude_account = opts.claude_account; return postJson(sessionsUrl(slug), body); } +export interface CswapAccount { + id: string; + slot: string; + /** cswap alias, else the email's local part (never the domain). */ + label: string; + /** Discovery: currently the default login. Session: runs on the default + * login (picked while it was the default; follows cswap auto). */ + active: boolean; + /** Whole-percent quota windows; absent when the plan has none (Max has no + * 5h) or cswap has no reading. Discovery only. */ + five_hour_pct?: number; + seven_day_pct?: number; + /** cswap `usageStatus` when not `ok`; with percentages, they are its last good reading. */ + usage_status?: string; +} +export interface CswapAccounts { + available: boolean; + accounts: CswapAccount[]; + message?: string; +} +/** `# ` — how an account reads everywhere (no email domain). */ +export const accountName = (account: Pick) => + `#${account.slot} ${account.label}`; +export const getCswapAccounts = () => + getJson("/api/v1/vendors/claude/accounts"); + +/** `PUT /api/v1/sessions/{sid}/claude-account` (#236). */ +export interface ClaudeAccountSwitch { + sid: string; + /** The session's binding now; `null` = default login. */ + claude_account: CswapAccount | null; + /** False when the pick was the session's current account. */ + changed: boolean; + /** A resident process was released; the next message resumes the SAME + * session under the new account. */ + released: boolean; +} +/** Move a running/released Claude session to another cswap account, or back + * to the default login (`null`). 409 = busy (mid-turn, awaiting you, + * background work), 422 = not possible (history not shared yet, unlisted + * account, cswap unavailable) — both surface the server's message. */ +export async function switchSessionClaudeAccount( + sid: string, + account: string | null, +): Promise { + let res: Response; + try { + res = await fetch(`/api/v1/sessions/${encodeURIComponent(sid)}/claude-account`, { + method: "PUT", + credentials: "same-origin", + headers: { "Content-Type": "application/json", Accept: "application/json" }, + body: JSON.stringify({ claude_account: account }), + }); + } catch (e) { + throw new Error(`network: ${e instanceof Error ? e.message : "connection failed"}`); + } + if (res.status === 401) throw new Error("UNAUTHENTICATED"); + if (res.status === 404) throw new Error("NOT_FOUND"); + if (!res.ok) throw new Error(await errorMessage(res)); + return (await res.json()) as ClaudeAccountSwitch; +} + // ── v0.8.21 history / resume / external-import ─────────────────────────────── /** A stopped ccteam session from `GET .../sessions/history`. */ diff --git a/crates/ccteam-web/web/src/lib/statusLine.ts b/crates/ccteam-web/web/src/lib/statusLine.ts index 3c0e19bc..ca252a87 100644 --- a/crates/ccteam-web/web/src/lib/statusLine.ts +++ b/crates/ccteam-web/web/src/lib/statusLine.ts @@ -60,6 +60,10 @@ export function formatStatusLine(status: SessionStatus): string | null { return parts.length > 0 ? parts.join(" · ") : null; } +/** Context occupancy (%) at and above which a window is flagged `⚠` — one + * threshold for the chat bubble footer and the team topology's ctx cell. */ +export const CTX_WARN_PCT = 85; + export function formatTurnStatus(status?: TurnStatus): { text: string; warn: boolean } | null { if (!status) return null; // The metrics half of the bubble footer (`turn N · ctx N%`); SessionView @@ -68,8 +72,9 @@ export function formatTurnStatus(status?: TurnStatus): { text: string; warn: boo const parts: string[] = [`turn ${status.turn}`]; const pct = contextPct(status.context); const roundedPct = typeof pct === "number" && Number.isFinite(pct) ? Math.round(pct) : null; - if (roundedPct !== null) parts.push(`ctx ${roundedPct}%${roundedPct >= 85 ? "⚠" : ""}`); - return { text: parts.join(" · "), warn: roundedPct !== null && roundedPct >= 85 }; + const warn = roundedPct !== null && roundedPct >= CTX_WARN_PCT; + if (roundedPct !== null) parts.push(`ctx ${roundedPct}%${warn ? "⚠" : ""}`); + return { text: parts.join(" · "), warn }; } /** TurnStatus serializes ContextUsage's numerator/denominator; derive pct diff --git a/crates/ccteam-web/web/src/lib/vendors.test.ts b/crates/ccteam-web/web/src/lib/vendors.test.ts index edae3efb..d337608d 100644 --- a/crates/ccteam-web/web/src/lib/vendors.test.ts +++ b/crates/ccteam-web/web/src/lib/vendors.test.ts @@ -12,6 +12,7 @@ import { effortRowLabel, effortRowsFor, effortSwitchFor, + modelRowLabel, modelRowsFor, modelSwitchFor, normalizeDraft, @@ -258,7 +259,6 @@ describe("effortRowsFor (there is NO global effort ladder)", () => { describe("modelSwitchFor (create-form `model` field)", () => { it("is null for the vendor-default row, for every vendor", () => { - expect(modelSwitchFor(defaultDraft())).toBeNull(); for (const vendor of VENDORS) { expect(modelSwitchFor({ vendor: vendor.id, model: MODEL_DEFAULT }, CATALOG)).toBeNull(); expect(modelSwitchFor({ vendor: vendor.id, model: "" }, CATALOG)).toBeNull(); @@ -292,7 +292,6 @@ describe("effortSwitchFor (create-form `effort` field — pass-through, no remap for (const vendor of VENDORS) { expect(effortSwitchFor({ vendor: vendor.id, effort: "" }, CATALOG)).toBeNull(); } - expect(effortSwitchFor(defaultDraft())).toBeNull(); }); it("sends the vendor's own token verbatim for every vendor", () => { @@ -365,9 +364,25 @@ describe("draft transitions (catalog is advisory, vendor changes are explicit)", expect(Object.keys(next).sort()).toEqual(["effort", "hitl", "model", "protocol", "vendor"]); }); - it("defaultDraft is the vendor default on both axes", () => { - expect(defaultDraft().model).toBe(MODEL_DEFAULT); - expect(defaultDraft().effort).toBe(""); + it("a fresh draft opens on claude · opus · high and wires both (owner 2026-11-08)", () => { + const draft = defaultDraft(); + expect([draft.vendor, draft.model, draft.effort]).toEqual(["claude", "opus", "high"]); + expect(modelSwitchFor(draft)).toBe("opus"); + expect(effortSwitchFor(draft)).toBe("high"); + }); + + it("switching vendor lands on that vendor's starting pick", () => { + const codex = switchDraftVendor(defaultDraft(), "codex"); + expect([codex.model, codex.effort]).toEqual([MODEL_DEFAULT, ""]); + const back = switchDraftVendor(codex, "claude"); + expect([back.model, back.effort]).toEqual(["opus", "high"]); + }); + + it("the default row names the observed concrete id, else 默认", () => { + const catalog = { codex: { models: [], efforts: [], defaultModel: "gpt-5.5" } }; + expect(modelRowLabel("codex", MODEL_DEFAULT, catalog)).toBe("gpt-5.5"); + expect(modelRowLabel("grok", MODEL_DEFAULT, catalog)).toBe(MODEL_DEFAULT); + expect(modelRowLabel("codex", "o9", catalog)).toBe("o9"); }); }); diff --git a/crates/ccteam-web/web/src/lib/vendors.ts b/crates/ccteam-web/web/src/lib/vendors.ts index 6545abb7..efacf6ee 100644 --- a/crates/ccteam-web/web/src/lib/vendors.ts +++ b/crates/ccteam-web/web/src/lib/vendors.ts @@ -200,16 +200,31 @@ export interface ComposerDraft { hitl: boolean; } +/** What a fresh pick of `vendor` starts on. Owner 2026-11-08: Claude opens + * on `opus` at `high`; every other vendor on its own default (wire nothing). */ +export function vendorStartingTuning(vendor: string): Pick { + return vendorSpec(vendor).id === "claude" + ? { model: "opus", effort: "high" } + : { model: MODEL_DEFAULT, effort: "" }; +} + export function defaultDraft(): ComposerDraft { return { vendor: "claude", - model: MODEL_DEFAULT, - effort: "", + ...vendorStartingTuning("claude"), protocol: VENDORS[0]!.protocols[0]!.id, hitl: false, }; } +/** How a model row / the model button reads: the default row names the + * concrete id the daemon observed for this vendor (falls back to 默认 until + * one has been seen); every other row is the vendor's own id verbatim. */ +export function modelRowLabel(vendor: string, model: string, catalog?: VendorCatalog | null): string { + if (model !== MODEL_DEFAULT) return model; + return catalog?.[vendorSpec(vendor).id]?.defaultModel ?? MODEL_DEFAULT; +} + /** Resolve the draft's wire protocol; unknown/hidden ids fall back to the * vendor's first (stable) protocol. */ export function wireProtocol(draft: Pick): "stream-json" | "terminal" | "acp" { @@ -255,8 +270,7 @@ export function switchDraftVendor(draft: ComposerDraft, vendor: string): Compose if (draft.vendor === spec.id) return normalizeDraft(draft); return { vendor: spec.id, - model: MODEL_DEFAULT, - effort: "", + ...vendorStartingTuning(spec.id), protocol: spec.protocols[0]!.id, hitl: !!draft.hitl, }; diff --git a/crates/ccteam-web/web/src/pages/AgentsView.test.tsx b/crates/ccteam-web/web/src/pages/AgentsView.test.tsx index 7b148364..e6fa16ad 100644 --- a/crates/ccteam-web/web/src/pages/AgentsView.test.tsx +++ b/crates/ccteam-web/web/src/pages/AgentsView.test.tsx @@ -272,6 +272,28 @@ describe("AgentsTree (SSR-safe, fixture-driven)", () => { expect(html).toMatch(/agents-tree-model[^>]*>— { + const rows = [ + fixtureNode({ sid: "s0", context_pct: 63 }), + fixtureNode({ sid: "s1", context_pct: 85 }), + fixtureNode({ sid: "s2", context_pct: 0 }), + // Released: no live window — never a stale number. + fixtureNode({ sid: "s3", residency: "released" }), + ]; + const html = renderToString( + + {}} /> + , + ).replace(//g, ""); + expect(html).toMatch(/class="agents-tree-ctx mono"[^>]*data-testid="agents-tree-ctx-s0">ctx 63%]*data-testid="agents-tree-ctx-s1">ctx 85%⚠ctx 0%— { const html = renderToString( diff --git a/crates/ccteam-web/web/src/pages/AgentsView.tsx b/crates/ccteam-web/web/src/pages/AgentsView.tsx index d9b28d79..a306d8fb 100644 --- a/crates/ccteam-web/web/src/pages/AgentsView.tsx +++ b/crates/ccteam-web/web/src/pages/AgentsView.tsx @@ -6,8 +6,9 @@ // // - 拓扑 topology: a compact, collapsible delegation tree grouped by project, // designed to stay readable with 100+ sessions. Every row carries what its -// session is running right now (模型 · effort, off the graph's live statusline -// join) and links to the real chat route `/chat/s/` — right/middle-click +// session is running right now (模型 · effort, plus `ctx N%` — how full its +// context window is — all off the graph's live statusline join) and links to +// the real chat route `/chat/s/` — right/middle-click // open-in-new-tab works because these are real hyperlinks. Narrow canvases // fold each row into two wrapped lines (index.css @container agents-canvas). // - 分工 charter: per-project routing.md editor + vendor roster (CharterPanel @@ -66,6 +67,7 @@ import { type ActivityFold, } from "./chatTranscript"; import { vendorDotClass } from "../lib/vendors"; +import { CTX_WARN_PCT } from "../lib/statusLine"; import { makeT, tr, type Lang } from "../lib/i18n"; import { relativeTime } from "./railHelpers"; import { toastBus } from "../lib/toastBus"; @@ -107,6 +109,18 @@ function modelEffortLabel(node: AgentNode): string { return [node.model?.trim(), node.effort?.trim()].filter(Boolean).join(" · ") || "—"; } +/** The ctx cell — how full the session's context window is right now, off + * the same live statusline join as {@link modelEffortLabel}, in the chat + * footer's own words (`ctx 63%`, `⚠` from {@link CTX_WARN_PCT}). A node with + * no live window (released, or a vendor that reports none) is a dash, never + * a stale or invented number. */ +function contextCell(node: AgentNode): { text: string; warn: boolean } { + const pct = node.context_pct; + if (typeof pct !== "number" || !Number.isFinite(pct)) return { text: "—", warn: false }; + const warn = pct >= CTX_WARN_PCT; + return { text: `ctx ${Math.round(pct)}%${warn ? "⚠" : ""}`, warn }; +} + /** The cost cell: vendor-reported USD when priced, else the raw token ledger * (`1.2m tok`) — the honest magnitude for vendors with no USD price table — * else an em-dash. Never a fake `$0.00`. */ @@ -229,6 +243,7 @@ export function AgentsTree({ {project.rows.map(({ node: n, indent, hasChildren }) => { const isCollapsed = collapsed.has(n.sid); const isDelegating = delegating.has(n.sid); + const ctx = contextCell(n); return (
{modelEffortLabel(n)} + + {ctx.text} + {showHost ? {n.host} : null}