Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 8 additions & 3 deletions docs/remote.md
Original file line number Diff line number Diff line change
Expand Up @@ -176,7 +176,12 @@ read, so it is fetched whole (`cat` over `exec`) and read on the
desktop; only by the conversation id its hooks reported, since scanning
the box's conversations would mean fetching all of them:

- Claude: its JSONL under `~/.claude/projects/<cwd as a dir name>/`.
- Claude (and its clones): its JSONL under
`<config dir>/projects/<cwd as a dir name>/`, where the config dir is
the agent's `CLAUDE_CONFIG_DIR` from Settings (a clone with no env of
its own inherits its parent's), falling back to `~/.claude`. Server
tasks read the box's `~/.claude` only. Docker-sandboxed tasks are not
covered: their container writes under termic's `docker-agents` mount.
- Codex: its rollout under `~/.codex/sessions/YYYY/MM/DD/`. What Codex
adds to a prompt (`<environment_context>`, the AGENTS.md preamble) is
dropped; after 0.150 it no longer writes `user_message` events, so the
Expand All @@ -189,8 +194,8 @@ the box's conversations would mean fetching all of them:
The file is the one named by the session id the task's tab recorded
(agent_hooks.rs captures Codex's and agy's); without one, the newest
session started in the task's folder, which a task sharing the project
checkout cannot use, so it gets none. Account-relocated config dirs are
not followed yet: the default home dirs are read.
checkout cannot use, so it gets none. A named account's config dir is
not followed yet: the agent's own dir (above) is read.

**Copy and image paste cross machines.** An agent's copy (OSC 52, Claude's
"copied N chars") lands on the viewing computer's clipboard: the paired
Expand Down
133 changes: 125 additions & 8 deletions src-tauri/src/cli_server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -747,6 +747,13 @@ pub(crate) trait CliHost: Send + Sync {
fn stop_tab_ptys(&self, task_id: &str, tab_id: &str) -> u32;
/// The user's home directory (session transcripts live under it).
fn home_dir(&self) -> Option<PathBuf>;
/// The built-in a task's agent runs (a clone's base, else its id) and
/// the config dir its Settings env relocates it to
/// (`CLAUDE_CONFIG_DIR=...`, inherited by a clone that sets no env of
/// its own), from the task's own profile. None keeps the default.
fn agent_base_and_dir(&self, t: &Task) -> (String, Option<PathBuf>) {
(t.cli.clone(), None)
}
/// This app's LAN pairing node (docs/peers.md): the `peer` verbs and
/// `--peer` forwarding go through it. None in test hosts that do not
/// exercise pairing, and in an app with no data dir.
Expand Down Expand Up @@ -2727,7 +2734,8 @@ pub(crate) fn claude_transcript_file(host: &dyn CliHost, t: &Task) -> Result<(Pa
// Transcript layout is agent-specific; claude's JSONL is the one
// reader shipped (docs/plans/cli.md: the RESULT.md file drop stays
// the agent-agnostic floor).
if t.cli != "claude" {
let (base, config_dir) = host.agent_base_and_dir(t);
if base != "claude" {
return Err(err(
ErrorCode::Unsupported,
format!(
Expand All @@ -2741,18 +2749,29 @@ pub(crate) fn claude_transcript_file(host: &dyn CliHost, t: &Task) -> Result<(Pa
let Some(home) = home else {
return Err(err(ErrorCode::Internal, "no home directory".into()));
};
let dir = home.join(".claude").join("projects").join(claude_project_dir_name(&t.path));
// The agent's own config dir first (a clone, or `CLAUDE_CONFIG_DIR` in
// its Settings env, which is where it writes), then the default one,
// for sessions started before the variable was set. Server tasks keep
// the box's default: its agents' env is not known here. Docker tasks
// are not covered: their container writes under termic's
// docker-agents mount, which neither dir is.
let default_dir = home.join(".claude");
let dirs: Vec<PathBuf> = config_dir
.filter(|d| !fs.is_server() && *d != default_dir)
.into_iter()
.chain([default_dir])
.map(|d| d.join("projects").join(claude_project_dir_name(&t.path)))
.collect();
// A stored per-tab session id pins the transcript (repo-root tasks);
// otherwise the newest .jsonl of the task's cwd is the session
// `--continue` would resume (worktree tasks).
let pinned = t
let sid = t
.persisted_tabs
.iter()
.filter(|p| p.cli == "claude")
.filter(|p| p.cli == t.cli || p.cli == "claude")
.max_by_key(|p| p.is_default)
.and_then(|p| p.session_id.clone())
.map(|s| dir.join(format!("{s}.jsonl")))
.filter(|f| fs.is_file(f));
.and_then(|p| p.session_id.clone());
let pinned = sid.and_then(|s| dirs.iter().map(|d| d.join(format!("{s}.jsonl"))).find(|f| fs.is_file(f)));
// Main-checkout tasks SHARE their cwd with the user's own claude
// sessions and any sibling main-checkout task; newest-in-dir would
// happily serve someone else's conversation as this task's result.
Expand All @@ -2763,12 +2782,24 @@ pub(crate) fn claude_transcript_file(host: &dyn CliHost, t: &Task) -> Result<(Pa
"this task shares the project checkout, so its transcript cannot be identified. Use the file convention instead: prompt the agent to write RESULT.md, then read it from the task path.".into(),
));
}
let file = pinned.or_else(|| fs.newest_with_ext(&dir, "jsonl")).ok_or_else(|| {
let file = pinned.or_else(|| dirs.iter().find_map(|d| fs.newest_with_ext(d, "jsonl"))).ok_or_else(|| {
err(ErrorCode::NotFound, "no claude session transcript found for this task (has the agent replied yet?)".into())
})?;
Ok((file, fs))
}

/// `CliHost::agent_base_and_dir` over one profile's agents.
fn agent_base_and_dir_in(mut agents: Vec<crate::Agent>, agent_id: &str, home: &Path) -> (String, Option<PathBuf>) {
let base = crate::docker::base_agent_id(&agents, agent_id).to_string();
// A clone with no env of its own runs with its parent's.
if let Some(resolved) = crate::agent_dirs::resolve_agent(&agents, agent_id) {
if let Some(a) = agents.iter_mut().find(|a| a.id == agent_id) {
a.env = resolved.env;
}
}
(base, crate::agent_dirs::instance_config_dir(&agents, agent_id, home))
}

/// termic_remote::transcript::codex_rollout on a box: the rollout named for
/// the session, else the newest of the last 400 whose first line (its
/// `session_meta`) names the task's folder; its contents.
Expand Down Expand Up @@ -5076,6 +5107,13 @@ impl CliHost for TauriHost {
fn home_dir(&self) -> Option<PathBuf> {
dirs::home_dir()
}
fn agent_base_and_dir(&self, t: &Task) -> (String, Option<PathBuf>) {
let agents = crate::load_settings_in(&t.profile).agents;
let Some(home) = dirs::home_dir() else {
return (crate::docker::base_agent_id(&agents, &t.cli).to_string(), None);
};
agent_base_and_dir_in(agents, &t.cli, &home)
}
fn peers(&self) -> Option<Arc<crate::peers::Node>> {
crate::peers::node()
}
Expand Down Expand Up @@ -6928,6 +6966,8 @@ pub(crate) mod test_support {
pub(crate) resizes: Mutex<Vec<(String, u16, u16)>>,
/// Fake home dir for the transcript reader.
pub(crate) home: Option<PathBuf>,
/// agent id -> (base, relocated config dir), for `agent_base_and_dir`.
pub(crate) agent_dirs: HashMap<String, (String, Option<PathBuf>)>,
}

impl Default for StubHost {
Expand Down Expand Up @@ -6976,6 +7016,7 @@ pub(crate) mod test_support {
taps: Mutex::new(HashMap::new()),
resizes: Mutex::new(Vec::new()),
home: None,
agent_dirs: HashMap::new(),
}
}
}
Expand Down Expand Up @@ -7210,6 +7251,9 @@ pub(crate) mod test_support {
fn home_dir(&self) -> Option<PathBuf> {
self.home.clone()
}
fn agent_base_and_dir(&self, t: &Task) -> (String, Option<PathBuf>) {
self.agent_dirs.get(&t.cli).cloned().unwrap_or_else(|| (t.cli.clone(), None))
}
}

pub(crate) fn req(cmd: Command, token: Option<&str>) -> Request {
Expand Down Expand Up @@ -13025,6 +13069,79 @@ mod tests {
assert_eq!(err.code, ErrorCode::NotFound);
}

/// An agent whose Settings env sets `CLAUDE_CONFIG_DIR` (here a clone)
/// writes its transcripts there, not under `~/.claude`. Reading only the
/// default dir showed a phone an empty chat for every such task.
#[test]
fn a_relocated_claude_config_dir_is_where_the_chat_is_read() {
let home = tempfile::tempdir().unwrap();
let cfg = home.path().join("alt-claude");
let mut host = StubHost { home: Some(home.path().to_path_buf()), ..Default::default() };
host.tasks[2].cli = "claude-work".into();
host.agent_dirs.insert("claude-work".into(), ("claude".into(), Some(cfg.clone())));
let line = |text: &str| format!(r#"{{"type":"assistant","message":{{"content":[{{"type":"text","text":"{text}"}}]}}}}"#);
let relocated = cfg.join("projects").join(claude_project_dir_name("/tasks/web/solo"));
std::fs::create_dir_all(&relocated).unwrap();
std::fs::write(relocated.join("s1.jsonl"), line("from the relocated dir")).unwrap();
let (_, turns) = transcript_turns(&host, "solo").unwrap();
assert_eq!(turns.iter().map(|t| t.text.as_str()).collect::<Vec<_>>(), ["from the relocated dir"]);
// Nothing there yet: an older session under the default dir still shows.
std::fs::remove_file(relocated.join("s1.jsonl")).unwrap();
let fallback = home.path().join(".claude/projects").join(claude_project_dir_name("/tasks/web/solo"));
std::fs::create_dir_all(&fallback).unwrap();
std::fs::write(fallback.join("s0.jsonl"), line("from the default dir")).unwrap();
let (_, turns) = transcript_turns(&host, "solo").unwrap();
assert_eq!(turns.iter().map(|t| t.text.as_str()).collect::<Vec<_>>(), ["from the default dir"]);
}

/// A clone that sets no env of its own runs with its parent's
/// `CLAUDE_CONFIG_DIR`, so that is where its chat is; one with its own
/// keeps it; plain claude with none keeps the default dir.
#[test]
fn a_clone_reads_the_config_dir_it_inherits() {
let agent = |id: &str, extends: Option<&str>, env: &[(&str, &str)]| {
let mut a = crate::default_agents().into_iter().next().unwrap();
a.id = id.into();
a.extends = extends.map(Into::into);
a.env = env.iter().map(|(k, v)| (k.to_string(), v.to_string())).collect();
a
};
let home = Path::new("/Users/u");
let agents = vec![
agent("claude", None, &[("CLAUDE_CONFIG_DIR", "~/.alt-claude")]),
agent("c2", Some("claude"), &[]),
agent("c3", Some("claude"), &[("CLAUDE_CONFIG_DIR", "/Users/u/.c3")]),
];
let got = |id: &str| agent_base_and_dir_in(agents.clone(), id, home);
assert_eq!(got("c2"), ("claude".into(), Some(PathBuf::from("/Users/u/.alt-claude"))));
assert_eq!(got("c3"), ("claude".into(), Some(PathBuf::from("/Users/u/.c3"))));
let plain = vec![agent("claude", None, &[])];
assert_eq!(agent_base_and_dir_in(plain, "claude", home), ("claude".into(), Some(PathBuf::from("/Users/u/.claude"))));
}

/// A clone task on the shared checkout whose session id was recorded on
/// a plain `claude` tab still finds it, rather than reading as shared.
#[test]
fn a_clone_task_finds_the_session_pinned_on_a_claude_tab() {
let home = tempfile::tempdir().unwrap();
let mut host = StubHost { home: Some(home.path().to_path_buf()), ..Default::default() };
host.tasks[2].cli = "claude-work".into();
host.tasks[2].is_main_checkout = true;
host.agent_dirs.insert("claude-work".into(), ("claude".into(), None));
host.tasks[2].persisted_tabs = vec![crate::PersistedTab {
id: "tab1".into(),
cli: "claude".into(),
is_default: true,
session_id: Some("sess7".into()),
..Default::default()
}];
let dir = home.path().join(".claude/projects").join(claude_project_dir_name("/tasks/web/solo"));
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(dir.join("sess7.jsonl"), r#"{"type":"assistant","message":{"content":[{"type":"text","text":"pinned"}]}}"#).unwrap();
let (_, turns) = transcript_turns(&host, "solo").unwrap();
assert_eq!(turns.iter().map(|t| t.text.as_str()).collect::<Vec<_>>(), ["pinned"]);
}

/// A remote client's chat for a Codex task: the rollout named by the
/// session id its tab recorded, read into turns. A shared checkout
/// without that id is refused rather than guessed at.
Expand Down
19 changes: 17 additions & 2 deletions src-tauri/src/remote_server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
//! and one forwards the open terminal. Every wait is a blocking read, a
//! channel or the cache's condvar (CLAUDE.md: no sleep-polls).

use std::collections::HashMap;
use std::collections::{HashMap, HashSet};
use std::net::{IpAddr, TcpStream};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::mpsc;
Expand Down Expand Up @@ -787,6 +787,21 @@ fn state_loop(s: &Session) {
let state_of = |id: &str| -> String {
states.as_ref().and_then(|m| m.get(id)).map(|i| i.state.clone()).unwrap_or_else(|| "unknown".into())
};
// Tasks running a claude clone, whose chat is claude's. The other
// readers still match the agent id exactly, and a server task's
// reader only knows the box's default dir. Settings are read only
// when a task runs a non-built-in agent, once per profile.
let mut profile_agents: HashMap<crate::profiles::ProfileId, Vec<crate::Agent>> = HashMap::new();
let claude_clones: HashSet<&str> = live
.iter()
.filter(|t| !crate::docker::BASE_BUILTINS.contains(&t.cli.as_str()))
.filter(|t| !projects.iter().any(|p| p.id == t.project_id && p.server.is_some()))
.filter(|t| {
let agents = profile_agents.entry(t.profile.clone()).or_insert_with(|| crate::load_settings_in(&t.profile).agents);
crate::docker::base_agent_id(agents, &t.cli) == "claude"
})
.map(|t| t.id.as_str())
.collect();
let mut rows: Vec<TaskRow> = live
.iter()
.map(|t| {
Expand Down Expand Up @@ -892,7 +907,7 @@ fn state_loop(s: &Session) {
name: t.name.clone(),
project,
agent: t.cli.clone(),
chat: Some(crate::cli_server::chat_supported(&t.cli, on_server)),
chat: Some(crate::cli_server::chat_supported(if claude_clones.contains(t.id.as_str()) { "claude" } else { &t.cli }, on_server)),
branch: (!t.branch.is_empty()).then(|| t.branch.clone()),
since_ms: since,
activity,
Expand Down
Loading