Skip to content

Reason Network: your team's coding agents, talking to each other. The engine behind `reason network`.

No restarts, a clean setup screen, shorter links, and agents can join for you

Lars Talianc542043e275f
diff --git a/Cargo.lock b/Cargo.lock
index ae1cadf..b6b2b50 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -3608,7 +3608,7 @@ dependencies = [
[[package]]
name = "tincan"
-version = "0.5.4"
+version = "0.6.0"
dependencies = [
"anyhow",
"blake3",
diff --git a/Cargo.toml b/Cargo.toml
index 812a4a9..d366da6 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "tincan"
-version = "0.5.4"
+version = "0.6.0"
edition = "2024"
description = "Team directory and message bus for coding agents across machines"
license = "MIT OR Apache-2.0"
diff --git a/README.md b/README.md
index 90b5b27..3cf9d89 100644
--- a/README.md
+++ b/README.md
@@ -28,15 +28,17 @@ a terminal, type their name, and they're in. The same link works for everyone an
the group chat and forget about it. `tincan link` shows it again; `tincan link --new` replaces it (removing
someone replaces it too).
-Agent sessions that were already open don't have tincan yet (agents load their tools at startup): reopen them
-(`claude --continue` keeps the conversation), then ask one: "who's on the team?" Plain `tincan` shows
+Then ask any of your agents: "who's on the team?" Claude Code sessions that were already open are on it right away
+(they take messages through their own socket and reply with the `tincan` CLI); other agents pick it up in new
+sessions. Plain `tincan` shows
who's around; `tincan setup` changes which agents are on tincan and how messages are handled.
There's no server and no host: every machine talks to the others directly, and any teammate's machine can let a
newcomer in, so someone just has to be online. Codex asks once to trust the new hooks: choose "Trust all and
continue". Gemini CLI only runs hooks and MCP servers in trusted folders.
-Agents (or scripts) can do it all without prompts: `tincan join <link> --as <name>`, `tincan init <team>`.
+Your agent can do it all for you, without prompts: the join page has a line to paste to it, which runs
+`curl … | sh -s -- <link> --as <name>`. Scripts can use `tincan join <link> --as <name>` and `tincan init <team>`.
On a Mac, tincan sits in the menu bar while it runs: two speech bubbles, filled while a teammate is connected,
with the number of messages waiting for you. Its menu lists each machine's sessions and what they're doing,
diff --git a/site/join/index.html b/site/join/index.html
index 0fa3cad..6ce56f8 100644
--- a/site/join/index.html
+++ b/site/join/index.html
@@ -50,8 +50,10 @@
</li>
<li>Type your name when it asks. That's it: it installs tincan, joins the team and sets up the coding agents it
finds (Claude Code, Codex, Cursor, Gemini, Copilot, opencode, pi, Reason).</li>
- <li>Agent sessions you already had open don't have tincan yet: reopen them (<code>claude --continue</code> keeps the conversation), then ask one: <em>"who's on the team?"</em></li>
+ <li>Ask any of your agents: <em>"who's on the team?"</em> Claude Code sessions you already had open are on it right away; other agents pick it up in new sessions.</li>
</ol>
+ <p class="muted" style="margin-bottom:6px">Or let your coding agent do it. Paste this to it:</p>
+ <div class="cmd"><pre id="agent"></pre><button id="copy-agent" type="button">Copy</button></div>
<div class="card">
<p class="muted">Your teammates will see your name, your machine, and what your agent sessions are working on
(repo, branch, busy or idle). Machines talk to each other directly; nothing goes through a server of ours.</p>
@@ -89,21 +91,27 @@
const cmd = `curl -fsSL ${installer} | sh -s -- ${ticket}`;
document.getElementById("team").textContent = name;
document.title = `Join ${name} on tincan`;
+ const agent = `Set up tincan for me, so my coding agents can talk to my team's. Ask me what name I want on the team, then run: ${cmd} --as <that name>`;
document.getElementById("cmd").textContent = cmd;
- const btn = document.getElementById("copy");
- btn.addEventListener("click", async () => {
- try {
- await navigator.clipboard.writeText(cmd);
- btn.textContent = "Copied";
- } catch (e) {
- const range = document.createRange();
- range.selectNodeContents(document.getElementById("cmd"));
- getSelection().removeAllRanges();
- getSelection().addRange(range);
- btn.textContent = "Press ⌘C";
- }
- setTimeout(() => (btn.textContent = "Copy"), 2000);
- });
+ document.getElementById("agent").textContent = agent;
+ const copyButton = (id, pre, text) => {
+ const btn = document.getElementById(id);
+ btn.addEventListener("click", async () => {
+ try {
+ await navigator.clipboard.writeText(text);
+ btn.textContent = "Copied";
+ } catch (e) {
+ const range = document.createRange();
+ range.selectNodeContents(document.getElementById(pre));
+ getSelection().removeAllRanges();
+ getSelection().addRange(range);
+ btn.textContent = "Press ⌘C";
+ }
+ setTimeout(() => (btn.textContent = "Copy"), 2000);
+ });
+ };
+ copyButton("copy", "cmd", cmd);
+ copyButton("copy-agent", "agent", agent);
document.getElementById("ok").hidden = false;
} else {
document.getElementById("bad").hidden = false;
diff --git a/src/claude.rs b/src/claude.rs
index 3aca641..e92f410 100644
--- a/src/claude.rs
+++ b/src/claude.rs
@@ -16,6 +16,8 @@ pub struct ClaudeSession {
pub status: Option<String>,
pub status_updated_at: Option<i64>,
pub started_at: Option<i64>,
+ /// Where the session takes messages from peers (what SendMessage uses).
+ pub messaging_socket_path: Option<String>,
}
pub fn scan() -> Vec<ClaudeSession> {
@@ -49,3 +51,28 @@ impl ClaudeSession {
self.name.as_deref().filter(|_| chosen)
}
}
+
+/// Whether tincan is one of Claude Code's MCP servers here (`tincan setup` chose Claude Code). Read once: the
+/// daemon restarts after setup.
+pub fn wired() -> bool {
+ static WIRED: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
+ *WIRED.get_or_init(|| {
+ let file = match std::env::var_os("CLAUDE_CONFIG_DIR") {
+ Some(dir) => std::path::PathBuf::from(dir).join(".claude.json"),
+ None => paths::user_home().join(".claude.json"),
+ };
+ std::fs::read(file)
+ .ok()
+ .and_then(|b| serde_json::from_slice::<serde_json::Value>(&b).ok())
+ .is_some_and(|v| v["mcpServers"]["tincan"].is_object())
+ })
+}
+
+/// The messaging socket of a live session, by its id or process.
+pub fn socket_for(session_id: Option<&str>, pid: Option<u32>) -> Option<std::path::PathBuf> {
+ scan()
+ .into_iter()
+ .find(|c| (session_id.is_some() && c.session_id.as_deref() == session_id) || (pid.is_some() && Some(c.pid) == pid))?
+ .messaging_socket_path
+ .map(Into::into)
+}
diff --git a/src/daemon/directory.rs b/src/daemon/directory.rs
index a5ec0d3..f056fa8 100644
--- a/src/daemon/directory.rs
+++ b/src/daemon/directory.rs
@@ -64,6 +64,36 @@ impl Daemon {
gits.insert(cwd, info);
}
+ // With Claude Code on tincan, every open Claude session is on it: sessions started before tincan was set
+ // up have no tincan tools, but take messages through their own socket and reply with the CLI.
+ if claude::wired() {
+ let now = util::now_ms();
+ for c in &claude {
+ let Some(id) = &c.session_id else { continue };
+ let key = format!("{}:{id}", agent::CLAUDE_CODE);
+ if !self.inner.lock().unwrap().live.contains_key(&key) {
+ let cwd = c.cwd.clone().unwrap_or_else(|| "/".into());
+ let git = gits.get(&cwd).cloned().unwrap_or_default();
+ let named = matches!(c.name_source.as_deref(), Some("user" | "peer" | "hook" | "auto"));
+ let reg = SessionReg {
+ key: key.clone(),
+ agent: agent::CLAUDE_CODE.into(),
+ cwd,
+ agent_session_id: Some(id.clone()),
+ pid: Some(c.pid),
+ tier: Tier::Push,
+ name: if named { c.label() } else { None },
+ };
+ if let Err(e) = self.register(None, reg, git) {
+ super::log(&format!("adding Claude session {id}: {e:#}"));
+ }
+ }
+ // Seen alive just now (it goes when its process does).
+ if let Some(l) = self.inner.lock().unwrap().live.get_mut(&key) {
+ l.last_hook = Some(now);
+ }
+ }
+ }
// A Claude Code session someone renamed goes by that name here too.
let renames: Vec<(String, String)> = {
let g = self.inner.lock().unwrap();
diff --git a/src/daemon/mail.rs b/src/daemon/mail.rs
index 13985ed..756ac74 100644
--- a/src/daemon/mail.rs
+++ b/src/daemon/mail.rs
@@ -5,7 +5,8 @@
//! show them a second time.
use super::{Daemon, Inner, directory::Target, log};
-use crate::{agent, config::Policy, proto::*, render, util};
+use crate::{
+ claude,agent, config::Policy, proto::*, render, util};
use anyhow::{Result, anyhow, bail};
use iroh::EndpointId;
use std::{
@@ -29,6 +30,8 @@ enum Channel {
ClaudeSocket(u64),
/// The agent's own CLI: `codex queue --thread <id> --message`, `reason session send <id> --message`.
Command(&'static str, Vec<String>),
+ /// Straight into a Claude Code session's messaging socket (one without tincan's tools: it replies with the CLI).
+ ClaudeDirect(std::path::PathBuf),
/// Hooks inject it at the next tool call or turn end.
Hook,
/// Only `check_inbox`.
@@ -187,11 +190,18 @@ impl Daemon {
(Tier::Push, _, Some(id)) if l.reg.agent == "reason" && has("reason") => {
Channel::Command("reason", vec!["session".into(), "send".into(), id.clone(), "--message".into()])
}
+ (Tier::Push, None, id) if l.reg.agent == agent::CLAUDE_CODE && !l.push_failed => {
+ match claude::socket_for(id.as_deref(), l.reg.pid) {
+ Some(path) => Channel::ClaudeDirect(path),
+ None => Channel::Pull,
+ }
+ }
_ if l.last_hook.is_some() => Channel::Hook,
_ => Channel::Pull,
};
let ids: Vec<String> = msgs.iter().map(|m| m.id.clone()).collect();
- let text = render::for_agent(&msgs, &self.person, Some(&l.reg.agent));
+ let cli = matches!(channel, Channel::ClaudeDirect(_));
+ let text = render::for_agent(&msgs, &self.person, Some(&l.reg.agent), cli);
let hook_note = if matches!(l.reg.agent.as_str(), "opencode" | "pi") {
"queued: delivered within seconds once the session is idle"
} else {
@@ -216,11 +226,38 @@ impl Daemon {
self.send_with(bin, args, key.to_string(), ids, text);
("pushed".into(), format!("queued into the {} session: it runs after the current turn, or now if idle", agent::label(bin)))
}
+ Channel::ClaudeDirect(path) => {
+ for id in &ids {
+ g.in_flight.insert(id.clone(), Instant::now());
+ }
+ self.post_direct(key.to_string(), path, ids, text);
+ ("pushed".into(), "delivered into the session: it reads it between tool calls, or wakes up if idle".into())
+ }
Channel::Hook => ("queued".into(), hook_note.into()),
Channel::Pull => ("queued".into(), "queued: this agent only sees it when it checks its inbox".into()),
}
}
+ /// Posts into a Claude Code session's messaging socket; read once it took it.
+ fn post_direct(self: &Arc<Self>, key: String, path: std::path::PathBuf, ids: Vec<String>, text: String) {
+ let this = self.clone();
+ tokio::spawn(async move {
+ let sock = agent::ClaudeSocket { path, token: None };
+ let res = tokio::task::spawn_blocking(move || agent::post_to_claude(&sock, &text)).await;
+ let mut g = this.inner.lock().unwrap();
+ for id in &ids {
+ g.in_flight.remove(id);
+ }
+ match res {
+ Ok(Ok(())) => {
+ let _ = g.store.mark_read(&ids, util::now_ms());
+ }
+ Ok(Err(e)) => log(&format!("delivering to Claude session {key}: {e}")),
+ Err(e) => log(&format!("delivering to Claude session {key}: {e}")),
+ }
+ });
+ }
+
/// Hands `text` to the agent's own CLI (`args` end with its message flag).
fn send_with(self: &Arc<Self>, bin: &'static str, args: Vec<String>, key: String, ids: Vec<String>, text: String) {
let this = self.clone();
@@ -361,7 +398,7 @@ impl Daemon {
messages
};
if !messages.is_empty() || tokio::time::Instant::now() >= deadline {
- let text = render::for_agent(&messages, &self.person, agent.as_deref());
+ let text = render::for_agent(&messages, &self.person, agent.as_deref(), false);
return Ok(Inbox { messages, text });
}
let _ = tokio::time::timeout_at(deadline, arrived).await;
diff --git a/src/daemon/sessions.rs b/src/daemon/sessions.rs
index 8a36cc0..ddb2f2a 100644
--- a/src/daemon/sessions.rs
+++ b/src/daemon/sessions.rs
@@ -207,7 +207,7 @@ impl Daemon {
};
// Not marked read here: the hook confirms with `Delivered` once it has printed them.
let ids: Vec<String> = msgs.iter().map(|m| m.id.clone()).collect();
- let text = (!msgs.is_empty()).then(|| render::for_agent(&msgs, &self.person, Some(&agent_kind)));
+ let text = (!msgs.is_empty()).then(|| render::for_agent(&msgs, &self.person, Some(&agent_kind), false));
Ok(HookReply { address: Some(address), text, ids })
}
diff --git a/src/daemon/teamops.rs b/src/daemon/teamops.rs
index 30950b8..2ca4df7 100644
--- a/src/daemon/teamops.rs
+++ b/src/daemon/teamops.rs
@@ -259,7 +259,7 @@ impl Daemon {
let online = |id: &EndpointId| self.net().is_some_and(|n| n.is_online(id));
let mut others: Vec<EndpointId> = team.active().map(|m| m.endpoint).filter(|e| *e != me).collect();
others.sort_by_key(|id| !online(id));
- let peers = std::iter::once(me).chain(others.into_iter().take(5)).collect();
+ let peers = std::iter::once(me).chain(others.into_iter().take(2)).collect();
let here = self.net().map(|n| n.addr());
Ticket {
team: team.id.clone(),
diff --git a/src/render.rs b/src/render.rs
index bbf626f..0ec6e66 100644
--- a/src/render.rs
+++ b/src/render.rs
@@ -195,8 +195,8 @@ pub fn send_result(r: &SendResult) -> String {
}
/// Messages framed for an agent's context: clearly peer input, with what it needs to reply. `agent` is the
-/// recipient's agent kind, if known.
-pub fn for_agent(msgs: &[Message], own_person: &str, agent: Option<&str>) -> String {
+/// recipient's agent kind, if known; `cli` when it has no tincan tools and replies with the CLI.
+pub fn for_agent(msgs: &[Message], own_person: &str, agent: Option<&str>, cli: bool) -> String {
let mut out = String::new();
for m in msgs {
let mut attrs = format!("from=\"{}\"", attr(&m.from));
@@ -219,9 +219,15 @@ pub fn for_agent(msgs: &[Message], own_person: &str, agent: Option<&str>) -> Str
} else {
format!("From {}, a teammate (human).", last.from)
};
+ let claude = agent == Some(crate::agent::CLAUDE_CODE);
let reply = match agent {
- // Reason's agent has no tincan tools, but its commands run on this computer.
- Some("reason") => format!("by running: tincan send {} --from {} \"<your reply>\"", last.from, last.to),
+ // No tincan tools (Reason's agent; a Claude session from before tincan), but commands run on this computer.
+ _ if cli || agent == Some("reason") => format!(
+ "by running: tincan send {} --from {} \"<your reply>\"{}",
+ last.from,
+ last.to,
+ if claude { " (Claude's SendMessage can't reach tincan addresses)." } else { "" }
+ ),
// Claude Code wraps pushed messages with "reply via SendMessage", which can't reach us.
Some(crate::agent::CLAUDE_CODE) => {
format!("with tincan's send_message to \"{}\" (Claude's SendMessage can't reach tincan addresses).", last.from)
@@ -309,7 +315,7 @@ mod tests {
wake: true,
sent_at: 0,
};
- let out = for_agent(&[m], "alex", None);
+ let out = for_agent(&[m], "alex", None, false);
assert_eq!(out.matches("</tincan-message>").count(), 1);
assert!(out.contains("repo=\"x&quot;&gt;&lt;evil&gt;\""));
}
diff --git a/src/setup.rs b/src/setup.rs
index 0cc184d..d222c07 100644
--- a/src/setup.rs
+++ b/src/setup.rs
@@ -158,12 +158,12 @@ fn changed(path: &Path, did: bool) -> String {
fn claude(exe: &Path, remove: bool, dry: bool) -> Result<Option<Report>> {
let Some(bin) = agent::find_bin("claude") else { return Ok(None) };
let mut r = Report { agent: "Claude Code", lines: Vec::new(), notes: Vec::new() };
- let get = Command::new(&bin).args(["mcp", "get", "tincan"]).output()?;
+ let get = Command::new(&bin).args(["mcp", "get", "tincan"]).stdin(std::process::Stdio::null()).output()?;
let existing = get.status.success();
let current = existing && String::from_utf8_lossy(&get.stdout).contains(&exe.display().to_string());
if remove || (existing && !current) {
if existing && !dry {
- Command::new(&bin).args(["mcp", "remove", "tincan", "--scope", "user"]).output()?;
+ Command::new(&bin).args(["mcp", "remove", "tincan", "--scope", "user"]).stdin(std::process::Stdio::null()).output()?;
}
if remove {
r.lines.push(if existing { "removed the tincan MCP server" } else { "nothing to remove" }.into());
@@ -178,13 +178,12 @@ fn claude(exe: &Path, remove: bool, dry: bool) -> Result<Option<Report>> {
.args(["mcp", "add", "--scope", "user", "tincan", "--"])
.arg(exe)
.arg("mcp")
- .output()?;
+ .stdin(std::process::Stdio::null()).output()?;
if !out.status.success() {
return Err(anyhow!("claude mcp add failed: {}", String::from_utf8_lossy(&out.stderr).trim()));
}
}
r.lines.push("added the tincan MCP server (user scope)".into());
- r.notes.push("Claude Code: new sessions get tincan; reopen running ones (`claude --continue` keeps the conversation).".into());
}
Ok(Some(r))
}
@@ -247,7 +246,7 @@ fn codex(exe: &Path, remove: bool, dry: bool) -> Result<Option<Report>> {
r.lines.push(changed(&hooks_path, did));
if did && !remove {
r.notes.push(
- "Codex: next time you start codex it asks about new hooks; choose \"Trust all and continue\" (or review them in /hooks). Until then Codex sessions only see messages when they check their inbox.".into(),
+ "Codex asks once to trust tincan's hooks: choose \"Trust all and continue\".".into(),
);
}
Ok(Some(r))
@@ -325,7 +324,7 @@ fn gemini(exe: &Path, remove: bool, dry: bool) -> Result<Option<Report>> {
let did = write_json(&path, &v, dry)?;
r.lines.push(changed(&path, did));
if did && !remove {
- r.notes.push("Gemini CLI: hooks and MCP servers only run in trusted folders (`/permissions trust` in a project).".into());
+ r.notes.push("Gemini CLI only runs tincan in trusted folders (`/permissions trust`).".into());
}
Ok(Some(r))
}
@@ -472,9 +471,9 @@ pub fn service_installed() -> bool {
pub fn start_service() -> bool {
let out = if cfg!(target_os = "macos") {
let uid = unsafe { libc::getuid() };
- Command::new("launchctl").args(["kickstart", &format!("gui/{uid}/{}", service_name())]).output()
+ Command::new("launchctl").args(["kickstart", &format!("gui/{uid}/{}", service_name())]).stdin(std::process::Stdio::null()).output()
} else {
- Command::new("systemctl").args(["--user", "start", &format!("{}.service", service_name())]).output()
+ Command::new("systemctl").args(["--user", "start", &format!("{}.service", service_name())]).stdin(std::process::Stdio::null()).output()
};
out.is_ok_and(|o| o.status.success())
}
@@ -501,7 +500,7 @@ async fn service(exe: &Path, remove: bool, dry: bool) -> Result<String> {
let target = format!("gui/{uid}/{}", service_name());
if remove {
if !dry {
- let _ = Command::new("launchctl").args(["bootout", &target]).output();
+ let _ = Command::new("launchctl").args(["bootout", &target]).stdin(std::process::Stdio::null()).output();
let _ = std::fs::remove_file(&path);
}
return Ok("removed the login service".into());
@@ -531,11 +530,11 @@ async fn service(exe: &Path, remove: bool, dry: bool) -> Result<String> {
xml(&service_path_env()),
);
let did = write_file(&path, &plist, dry)?;
- let loaded = Command::new("launchctl").args(["print", &target]).output().is_ok_and(|o| o.status.success());
+ let loaded = Command::new("launchctl").args(["print", &target]).stdin(std::process::Stdio::null()).output().is_ok_and(|o| o.status.success());
if !dry && (did || !loaded) {
- let _ = Command::new("launchctl").args(["bootout", &target]).output();
+ let _ = Command::new("launchctl").args(["bootout", &target]).stdin(std::process::Stdio::null()).output();
crate::stop_daemon().await;
- let out = Command::new("launchctl").args(["bootstrap", &format!("gui/{uid}")]).arg(&path).output()?;
+ let out = Command::new("launchctl").args(["bootstrap", &format!("gui/{uid}")]).arg(&path).stdin(std::process::Stdio::null()).output()?;
if !out.status.success() {
return Err(anyhow!("launchctl bootstrap: {}", String::from_utf8_lossy(&out.stderr).trim()));
}
@@ -544,7 +543,7 @@ async fn service(exe: &Path, remove: bool, dry: bool) -> Result<String> {
} else {
if remove {
if !dry {
- let _ = Command::new("systemctl").args(["--user", "disable", "--now", &format!("{}.service", service_name())]).output();
+ let _ = Command::new("systemctl").args(["--user", "disable", "--now", &format!("{}.service", service_name())]).stdin(std::process::Stdio::null()).output();
let _ = std::fs::remove_file(&path);
}
return Ok("removed the login service".into());
@@ -558,8 +557,8 @@ async fn service(exe: &Path, remove: bool, dry: bool) -> Result<String> {
let did = write_file(&path, &unit, dry)?;
if !dry {
crate::stop_daemon().await;
- Command::new("systemctl").args(["--user", "daemon-reload"]).output()?;
- let out = Command::new("systemctl").args(["--user", "enable", "--now", &format!("{}.service", service_name())]).output()?;
+ Command::new("systemctl").args(["--user", "daemon-reload"]).stdin(std::process::Stdio::null()).output()?;
+ let out = Command::new("systemctl").args(["--user", "enable", "--now", &format!("{}.service", service_name())]).stdin(std::process::Stdio::null()).output()?;
if !out.status.success() {
return Err(anyhow!("systemctl: {}", String::from_utf8_lossy(&out.stderr).trim()));
}
@@ -604,7 +603,7 @@ const AGENTS: [Agent; 8] = [
installed: || agent::find_bin("claude").is_some(),
wired: |_| {
agent::find_bin("claude")
- .is_some_and(|b| Command::new(b).args(["mcp", "get", "tincan"]).output().is_ok_and(|o| o.status.success()))
+ .is_some_and(|b| Command::new(b).args(["mcp", "get", "tincan"]).stdin(std::process::Stdio::null()).output().is_ok_and(|o| o.status.success()))
},
apply: claude,
},
@@ -687,6 +686,9 @@ pub fn detect(exe: &Path) -> Vec<Found> {
pub struct Applied {
pub lines: Vec<String>,
pub notes: Vec<String>,
+ /// The agents set up (or removed) without trouble, and whether the service is installed now.
+ pub agents: Vec<&'static str>,
+ pub service: Option<bool>,
}
/// Wires tincan into the `install` agents and out of the `remove` ones; installs (`Some(true)`) or removes
@@ -702,9 +704,13 @@ pub async fn apply(exe: &Path, install: &[&str], remove: &[&str], service: Optio
Ok(Some(r)) => {
out.lines.push(format!("{}: {}", r.agent, r.lines.join("; ")));
out.notes.extend(r.notes);
+ out.agents.push(a.name);
}
Ok(None) => {}
- Err(e) => out.lines.push(format!("{}: skipped ({e:#})", a.name)),
+ Err(e) => {
+ out.lines.push(format!("{}: skipped ({e:#})", a.name));
+ out.notes.push(format!("{} not set up: {e:#}", a.name));
+ }
}
}
if let Some(on) = service {
@@ -713,8 +719,14 @@ pub async fn apply(exe: &Path, install: &[&str], remove: &[&str], service: Optio
return out;
}
match self::service(exe, !on, dry).await {
- Ok(s) => out.lines.push(format!("service: {s}")),
- Err(e) => out.lines.push(format!("service: not installed ({e:#}); the daemon still starts on demand")),
+ Ok(s) => {
+ out.lines.push(format!("service: {s}"));
+ out.service = Some(on);
+ }
+ Err(e) => {
+ out.lines.push(format!("service: not installed ({e:#}); the daemon still starts on demand"));
+ out.notes.push(format!("Not running in the background ({e:#}); tincan starts when you use it."));
+ }
}
}
out
diff --git a/src/team.rs b/src/team.rs
index 81d40fe..1891bbe 100644
--- a/src/team.rs
+++ b/src/team.rs
@@ -386,6 +386,25 @@ pub struct Ticket {
}
const TICKET_PREFIX: &str = "tincan1";
+/// In place of a length: an n0 relay, given by its region (`use1-1` for `https://use1-1.relay.n0.iroh.link./`).
+const N0_RELAY: u8 = 0xFF;
+const N0_RELAY_SUFFIX: &str = ".relay.n0.iroh.link./";
+
+/// A length byte, then the text (cut to 250 bytes, so a length never reads as a marker).
+fn put_text(b: &mut Vec<u8>, text: &str) {
+ let mut n = text.len().min(250);
+ while !text.is_char_boundary(n) {
+ n -= 1;
+ }
+ b.push(n as u8);
+ b.extend(&text.as_bytes()[..n]);
+}
+
+fn n0_relay(url: &str) -> Option<&str> {
+ let host = url.strip_prefix("https://")?.trim_end_matches('/');
+ let region = host.strip_suffix(".relay.n0.iroh.link.").or_else(|| host.strip_suffix(".relay.n0.iroh.link"))?;
+ (!region.is_empty() && region.len() < 32 && region.bytes().all(|c| c.is_ascii_alphanumeric() || c == b'-')).then_some(region)
+}
impl Ticket {
/// `tincan1` + base64url of: team id (16 bytes), secret (16), name, team relay, first peer's relay hint (each
@@ -396,12 +415,19 @@ impl Ticket {
b.extend(HEXLOWER.decode(self.team.as_bytes()).expect("team ids are hex"));
b.extend(HEXLOWER.decode(self.secret.as_bytes()).expect("secrets are hex"));
let name: String = self.name.chars().take(60).collect();
- for field in [name.as_str(), self.relay.as_deref().unwrap_or(""), self.hint_relay.as_deref().unwrap_or("")] {
- let n = field.len().min(255);
- b.push(n as u8);
- b.extend(&field.as_bytes()[..n]);
+ put_text(&mut b, &name);
+ for relay in [&self.relay, &self.hint_relay] {
+ let relay = relay.as_deref().unwrap_or("");
+ match n0_relay(relay) {
+ // One of n0's relays: just its region, which keeps links short.
+ Some(region) => {
+ b.push(N0_RELAY);
+ put_text(&mut b, region);
+ }
+ None => put_text(&mut b, relay),
+ }
}
- let ips: Vec<&SocketAddr> = self.hint_ips.iter().take(4).collect();
+ let ips: Vec<&SocketAddr> = self.hint_ips.iter().take(2).collect();
b.push(ips.len() as u8);
for a in ips {
match a.ip() {
@@ -436,8 +462,12 @@ impl Ticket {
let team = HEXLOWER.encode(take(16)?);
let secret = HEXLOWER.encode(take(16)?);
let mut text = || -> Result<String> {
- let n = take(1)?[0] as usize;
- Ok(String::from_utf8_lossy(take(n)?).into_owned())
+ let n = take(1)?[0];
+ if n == N0_RELAY {
+ let n = take(1)?[0] as usize;
+ return Ok(format!("https://{}{N0_RELAY_SUFFIX}", String::from_utf8_lossy(take(n)?)));
+ }
+ Ok(String::from_utf8_lossy(take(n as usize)?).into_owned())
};
let name = text()?;
let relay = Some(text()?).filter(|r| !r.is_empty());
@@ -456,7 +486,8 @@ impl Ticket {
while let Ok(k) = take(32) {
peers.push(EndpointId::from_bytes(k.try_into().expect("32 bytes")).map_err(|_| damaged())?);
}
- if peers.is_empty() {
+ // A key cut short means the link was.
+ if peers.is_empty() || at != b.len() {
return Err(damaged());
}
Ok(Ticket { team, name, secret, relay, hint_relay, hint_ips, peers })
@@ -658,6 +689,35 @@ mod tests {
assert!(Ticket::decode("hello").is_err());
}
+ #[test]
+ fn links_name_n0_relays_by_region_and_old_links_still_work() {
+ let a = key();
+ let mut t = Ticket {
+ team: "00112233445566778899aabbccddeeff".into(),
+ name: "vibes".into(),
+ secret: random_secret(),
+ relay: None,
+ hint_relay: Some("https://use1-1.relay.n0.iroh.link./".into()),
+ hint_ips: vec![],
+ peers: vec![a.public()],
+ };
+ let short = t.encode();
+ assert_eq!(Ticket::decode(&short).unwrap(), t);
+ // The same link as 0.5 wrote it, with the relay spelled out.
+ let mut b = HEXLOWER.decode(t.team.as_bytes()).unwrap();
+ b.extend(HEXLOWER.decode(t.secret.as_bytes()).unwrap());
+ for f in ["vibes", "", "https://use1-1.relay.n0.iroh.link./"] {
+ put_text(&mut b, f);
+ }
+ b.push(0);
+ b.extend(a.public().as_bytes());
+ let old = format!("{TICKET_PREFIX}{}", BASE64URL_NOPAD.encode(&b));
+ assert!(short.len() + 30 < old.len(), "{} vs {}", short.len(), old.len());
+ assert_eq!(Ticket::decode(&old).unwrap(), t);
+ t.hint_relay = Some("https://relay.example.com/".into());
+ assert_eq!(Ticket::decode(&t.encode()).unwrap(), t);
+ }
+
#[test]
fn team_link_is_reusable_until_replaced() {
let (a, b, c, d) = (key(), key(), key(), key());
diff --git a/src/wizard.rs b/src/wizard.rs
index d9e8bff..c42dbed 100644
--- a/src/wizard.rs
+++ b/src/wizard.rs
@@ -110,14 +110,14 @@ pub async fn onboard(start: Option<bool>, team: Option<String>, invite: Option<S
if start {
let url = show_link(false).await?;
- outro("Agent sessions that were already open don't have tincan yet: reopen them (`claude --continue` keeps the conversation), then ask one: \"who's on the team?\"")?;
+ outro("Done. Ask any of your agents: \"who's on the team?\"")?;
// Outside the frame, so the terminal copies it whole.
println!("\n{url}\n");
} else {
if let Ok(t) = Link::new(None).call::<TeamInfo>(Request::Team).await {
note("Your team", render::team(&t).trim_end())?;
}
- outro("You're in. Agent sessions that were already open don't have tincan yet: reopen them (`claude --continue` keeps the conversation), then ask one: \"who's on the team?\"")?;
+ outro("You're in. Ask any of your agents: \"who's on the team?\"")?;
}
Ok(())
}
@@ -131,17 +131,28 @@ async fn set_up_agents_with_defaults() -> Result<()> {
sp.start("Setting up your agents...");
crate::stop_daemon().await;
let out = setup::apply(&exe, &ids, &[], Some(true), false).await;
- sp.stop(if found.is_empty() { "No coding agents found on this machine (yet)" } else { "Set up your agents" });
- for l in &out.lines {
- log::success(l)?;
+ sp.stop(match out.agents.as_slice() {
+ [] => "No coding agents found on this machine (yet)".to_string(),
+ names => format!("Set up {}", and_list(names)),
+ });
+ if out.service == Some(true) {
+ log::success("Runs in the background, from login")?;
}
for n in &out.notes {
log::warning(n)?;
}
- log::remark("Change any of this with `tincan setup`.")?;
Ok(())
}
+/// `a, b and c`.
+fn and_list(items: &[&str]) -> String {
+ match items {
+ [] => String::new(),
+ [one] => one.to_string(),
+ [rest @ .., last] => format!("{} and {last}", rest.join(", ")),
+ }
+}
+
/// Which agents are on tincan, the background service, and how teammates' messages are handled.
pub async fn agents_and_preferences() -> Result<()> {
let exe = setup::exe()?;
@@ -194,13 +205,8 @@ pub async fn agents_and_preferences() -> Result<()> {
pub async fn show_link(new: bool) -> Result<String> {
let l: LinkInfo = Link::new(None).call(Request::Link { new }).await?;
let copied = copy(&l.url);
- note(
- format!("Team link for {}", l.team),
- format!(
- "{}Send your friends the link below. It opens a page with one command: they\npaste it, type their name, and they're in. It keeps working for everyone\nuntil you run `tincan link --new`.",
- if copied { "It's on your clipboard. " } else { "" },
- ),
- )?;
+ let title = if copied { format!("Team link for {} (on your clipboard)", l.team) } else { format!("Team link for {}", l.team) };
+ note(title, "Send it to your friends: one paste and their name, and they're in.\nIt works for everyone until `tincan link --new`.")?;
Ok(l.url)
}
@@ -262,6 +268,6 @@ pub async fn invite() -> Result<()> {
pub async fn setup_agents() -> Result<()> {
intro(" tincan setup ")?;
agents_and_preferences().await?;
- outro("Agent sessions that were already open pick this up once you reopen them.")?;
+ outro("Done.")?;
Ok(())
}
diff --git a/tests/e2e/guided.py b/tests/e2e/guided.py
index 8cb62f2..0d8a0cb 100644
--- a/tests/e2e/guided.py
+++ b/tests/e2e/guided.py
@@ -78,7 +78,7 @@ try:
t.expect(r"Name your team")
t.send("the boys" + ENTER)
t.expect(r"Created team the boys\. You are alex on alex-box\.")
- t.expect(r"Codex: updated")
+ t.expect(r"Set up Codex")
t.expect(r"Team link for the boys")
m = t.expect(r"\n(https://\S+/join/#tincan1[A-Za-z0-9_-]+)\n")
link = m.group(1)
diff --git a/tests/e2e/hooks.py b/tests/e2e/hooks.py
index 5a09565..29c7201 100644
--- a/tests/e2e/hooks.py
+++ b/tests/e2e/hooks.py
@@ -2,13 +2,19 @@
cargo build && python3 tests/e2e/hooks.py
"""
-import json, os, subprocess, tempfile, time
+import json, os, socket, subprocess, tempfile, threading, time
ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
BIN = os.path.join(ROOT, "target", "debug", "tincan")
D = tempfile.mkdtemp(prefix="tincan-hooks-")
env = {k: v for k, v in os.environ.items() if not k.startswith("CLAUDE")}
env.update(TINCAN_HOME=os.path.join(D, "home"), TINCAN_NO_MDNS="1", TINCAN_NO_SERVICE="1", TINCAN_MACHINE="box")
+# A Claude Code setup of our own (never this machine's real sessions, which tincan could deliver into).
+CLAUDE = os.path.join(D, "claude")
+os.makedirs(os.path.join(CLAUDE, "sessions"))
+with open(os.path.join(CLAUDE, ".claude.json"), "w") as f:
+ json.dump({"mcpServers": {"tincan": {"type": "stdio", "command": BIN, "args": ["mcp"]}}}, f)
+env["CLAUDE_CONFIG_DIR"] = CLAUDE
results = []
@@ -146,6 +152,38 @@ run("send", "alex", "--from", "alex/fix-flaky-billing-reason", "found it: a time
out = run("inbox")
check("its reply comes from the Reason session", "── alex/fix-flaky-billing-reason" in out and "timezone bug" in out, out)
+# A Claude session that was open before tincan was set up: no restart needed. It's on the team at once, gets
+# messages through its own socket, and replies with the CLI.
+old_proj = os.path.join(D, "old-proj")
+os.makedirs(old_proj)
+sock_path = os.path.join(D, "cc.sock")
+got = []
+srv = socket.socket(socket.AF_UNIX)
+srv.bind(sock_path)
+srv.listen(4)
+def serve():
+ while True:
+ c, _ = srv.accept()
+ got.append(c.makefile().read())
+threading.Thread(target=serve, daemon=True).start()
+sleeper = subprocess.Popen(["sleep", "120"])
+with open(os.path.join(CLAUDE, "sessions", f"{sleeper.pid}.json"), "w") as f:
+ json.dump({"pid": sleeper.pid, "sessionId": "old-1", "cwd": old_proj, "name": "old-proj-1", "nameSource": "derived",
+ "status": "idle", "messagingSocketPath": sock_path}, f)
+time.sleep(3)
+out = run("who", "old-proj")
+check("an already-open Claude session is on the team, reachable right away", "old-proj-claude" in out and "push" in out, out)
+out = run("send", "old-proj-claude", "old session: can you hear me?")
+time.sleep(1.5)
+frame = "".join(got)
+check("…it's delivered straight into the session", "delivered into the session" in out and "can you hear me?" in frame, out + frame)
+check("…with how to reply using the CLI", "tincan send alex --from alex/old-proj-claude" in frame, frame)
+r = subprocess.run([BIN, "send", "alex", "loud and clear"], env=dict(env, CLAUDE_CODE_SESSION_ID="old-1", CLAUDECODE="1"),
+ capture_output=True, text=True, timeout=30)
+out = run("inbox")
+check("…and its reply (run from that session) comes from it", "── alex/old-proj-claude" in out and "loud and clear" in out, r.stdout + r.stderr + out)
+sleeper.kill()
+
# The daemon being down never breaks the agent.
run("stop")
bad = dict(env, TINCAN_HOME="/nonexistent/dir/that/cannot/exist")
diff --git a/tests/e2e/two_machines.py b/tests/e2e/two_machines.py
index f11d64b..a2fb9b8 100644
--- a/tests/e2e/two_machines.py
+++ b/tests/e2e/two_machines.py
@@ -29,6 +29,8 @@ def env(who, strip_claude=True):
for k in list(e):
if k.startswith("CLAUDE"):
del e[k]
+ # Never this machine's real Claude sessions: tincan could deliver into them.
+ e["CLAUDE_CONFIG_DIR"] = os.path.join(D, "claude-config")
return e