use std::os::windows::process::CommandExt;
use std::path::{Path, PathBuf};
use std::process::Command;
use serde::Deserialize;
const USAGE: &str = "\
t3 - open the T3 Code conversation for a folder
USAGE (in a rustimal pane, where it opens in that pane):
t3 the latest conversation for this folder
t3 ./FOLDER ... for another folder (written as a path)
t3 -l list this folder's conversations
t3 2 open number 2 from that list
t3 COMMAND ... anything else goes to T3 Code's own CLI
Ctrl+Shift+T switches between T3 Code and the terminal.
From other shells, `rustimal --t3 [NUMBER | FOLDER]` opens the T3 Code desktop app.
";
const NO_PROJECT: &str = "No T3 Code project matches";
const CREATE_NO_WINDOW: u32 = 0x0800_0000;
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct Thread {
title: Option<String>,
link: String,
status: Option<String>,
updated_at: Option<String>,
#[serde(default)]
settled: bool,
#[serde(default)]
snoozed: bool,
parent_thread_id: Option<String>,
}
#[derive(Debug, PartialEq)]
enum Action {
Open(usize),
List,
}
fn parse_args(args: &[String]) -> Option<(Action, Option<&str>)> {
let (mut action, mut folder) = (None, None);
for a in args {
let next = match a.as_str() {
"-l" | "--list" => Some(Action::List),
s if !s.is_empty() && s.bytes().all(|b| b.is_ascii_digit()) => {
Some(Action::Open(s.parse().ok().filter(|&n| n > 0)?))
}
s if s.starts_with('-') => return None,
s => {
if folder.replace(s).is_some() {
return None;
}
None
}
};
if next.is_some() && std::mem::replace(&mut action, next).is_some() {
return None;
}
}
Some((action.unwrap_or(Action::Open(1)), folder))
}
fn ranked(json: &str) -> Result<Vec<Thread>, String> {
let mut threads: Vec<Thread> =
serde_json::from_str(json.trim()).map_err(|e| format!("could not read T3 Code's thread list: {e}"))?;
threads.retain(|t| t.parent_thread_id.is_none());
threads.sort_by(|a, b| {
(a.settled || a.snoozed).cmp(&(b.settled || b.snoozed)).then_with(|| b.updated_at.cmp(&a.updated_at))
});
Ok(threads)
}
fn app_link(web_link: &str) -> Option<String> {
let (_, ids) = web_link.split_once("/threads/")?;
let (env, thread) = ids.split_once('/')?;
let plain = |s: &str| !s.is_empty() && s.chars().all(|c| c.is_ascii_alphanumeric() || "-_.:".contains(c));
(plain(env) && plain(thread)).then(|| format!("t3code://threads/{env}/{thread}"))
}
fn main_checkout(dir: &Path) -> Option<PathBuf> {
let dot_git = dir.ancestors().map(|d| d.join(".git")).find(|p| p.exists())?;
let text = std::fs::read_to_string(dot_git).ok()?;
let git_dir = Path::new(text.trim().strip_prefix("gitdir:")?.trim());
let worktrees = git_dir.parent().filter(|p| p.ends_with(".git/worktrees"))?;
worktrees.parent()?.parent().map(Path::to_path_buf)
}
fn t3_home() -> Result<PathBuf, String> {
std::env::var_os("T3CODE_HOME")
.map(PathBuf::from)
.or_else(|| dirs::home_dir().map(|h| h.join(".t3")))
.ok_or_else(|| "could not find your home folder".to_string())
}
fn cli_path() -> Result<PathBuf, String> {
let cli = t3_home()?.join("bin").join("t3.cmd");
if cli.is_file() {
Ok(cli)
} else {
Err(format!("T3 Code's CLI isn't at {}. Install the T3 Code desktop app and open it once.", cli.display()))
}
}
fn cli(args: &[&std::ffi::OsStr]) -> Result<String, String> {
let out = Command::new(cli_path()?)
.args(args)
.creation_flags(CREATE_NO_WINDOW)
.output()
.map_err(|e| format!("could not run T3 Code's CLI: {e}"))?;
let stdout = String::from_utf8_lossy(&out.stdout).into_owned();
if out.status.success() {
return Ok(stdout);
}
let said = format!("{}\n{}", String::from_utf8_lossy(&out.stderr).trim(), stdout.trim());
Err(said.trim().to_string())
}
fn threads(dir: &Path) -> Result<Option<Vec<Thread>>, String> {
let list =
|d: &Path| cli(&["thread".as_ref(), "list".as_ref(), "--project".as_ref(), d.as_ref(), "--json".as_ref()]);
let mut result = list(dir);
if result.as_ref().is_err_and(|e| e.contains(NO_PROJECT))
&& let Some(main) = main_checkout(dir)
{
result = list(&main);
}
match result {
Ok(json) => ranked(&json).map(Some),
Err(e) if e.contains(NO_PROJECT) => Ok(None),
Err(e) => Err(format!("{e}\n(Is the T3 Code app open?)")),
}
}
fn local_origin(runtime: &str) -> Option<String> {
let value: serde_json::Value = serde_json::from_str(runtime).ok()?;
let origin = value.get("origin")?.as_str()?.trim_end_matches('/');
let port = ["http://127.0.0.1:", "http://localhost:"].iter().find_map(|p| origin.strip_prefix(p))?;
port.parse::<u16>().ok()?;
Some(origin.to_string())
}
fn web_page(origin: &str, web_link: &str) -> Option<String> {
let link = app_link(web_link)?;
Some(format!("{origin}/{}", link.strip_prefix("t3code://threads/")?))
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Page {
pub origin: String,
pub url: String,
}
pub fn page(dir: &Path, number: usize) -> Result<Page, String> {
let found = threads(dir)?;
let list = found.as_deref().unwrap_or_default();
let runtime = t3_home()?.join("userdata").join("server-runtime.json");
let origin = std::fs::read_to_string(runtime)
.ok()
.and_then(|text| local_origin(&text))
.ok_or("could not find T3 Code's local server. Is the T3 Code app open?")?;
let url = match list.get(number.saturating_sub(1)) {
Some(thread) => {
web_page(&origin, &thread.link).ok_or_else(|| format!("unexpected thread link: {}", thread.link))?
}
None if number <= 1 => format!("{origin}/"),
None => return Err(format!("there is no conversation {number}; `t3 -l` lists them")),
};
Ok(Page { origin, url })
}
fn describe(number: usize, t: &Thread) -> String {
let title: String = t.title.as_deref().unwrap_or("(untitled)").chars().filter(|c| !c.is_control()).collect();
let state = if t.settled {
"settled"
} else if t.snoozed {
"snoozed"
} else {
t.status.as_deref().unwrap_or("open")
};
format!("{number:>3} {title} ({state})")
}
fn switch(action: Action, dir: &Path) -> Result<(), String> {
let found = threads(dir)?;
let list = found.as_deref().unwrap_or_default();
match action {
Action::List if list.is_empty() => println!("No T3 Code conversations for {}", dir.display()),
Action::List => list.iter().enumerate().for_each(|(i, t)| println!("{}", describe(i + 1, t))),
Action::Open(1) if list.is_empty() => {
println!("No conversation here yet; opening {} in T3 Code", dir.display());
cli(&["app".as_ref(), dir.as_ref()])?;
}
Action::Open(n) => {
let thread = list.get(n - 1).ok_or_else(|| format!("there is no conversation {n}; `t3 -l` lists them"))?;
let link = app_link(&thread.link).ok_or_else(|| format!("unexpected thread link: {}", thread.link))?;
println!("{}", describe(n, thread).trim_start());
crate::links::shell_open(link.as_ref());
}
}
Ok(())
}
pub fn run(args: &[String]) -> i32 {
if args.iter().any(|a| a == "-h" || a == "--help") {
print!("{USAGE}");
return 0;
}
let Some((action, folder)) = parse_args(args) else {
eprint!("{USAGE}");
return 2;
};
let dir = match std::path::absolute(folder.unwrap_or(".")) {
Ok(d) if d.is_dir() => d,
_ => {
eprintln!("t3: {}: no such folder", folder.unwrap_or("."));
return 1;
}
};
match switch(action, &dir) {
Ok(()) => 0,
Err(e) => {
eprintln!("t3: {e}");
1
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn args(a: &[&str]) -> Vec<String> {
a.iter().map(|s| s.to_string()).collect()
}
#[test]
fn reads_the_arguments() {
assert_eq!(parse_args(&args(&[])), Some((Action::Open(1), None)));
assert_eq!(parse_args(&args(&["3"])), Some((Action::Open(3), None)));
assert_eq!(parse_args(&args(&["-l", "./src"])), Some((Action::List, Some("./src"))));
assert_eq!(parse_args(&args(&["0"])), None);
assert_eq!(parse_args(&args(&["-l", "2"])), None);
assert_eq!(parse_args(&args(&["./a", "./b"])), None);
assert_eq!(parse_args(&args(&["--nope"])), None);
}
#[test]
fn open_conversations_come_first_and_subagents_are_left_out() {
let json = r#"[
{"title":"settled, newest","link":"a","settled":true,"updatedAt":"2026-03-04T00:00:00.000Z"},
{"title":"older","link":"b","settled":false,"updatedAt":"2026-03-01T00:00:00.000Z"},
{"title":"subagent","link":"c","parentThreadId":"x","updatedAt":"2026-03-05T00:00:00.000Z"},
{"title":"snoozed","link":"d","snoozed":true,"updatedAt":"2026-03-03T00:00:00.000Z"},
{"title":"newer","link":"e","parentThreadId":null,"updatedAt":"2026-03-02T00:00:00.000Z"}
]"#;
let titles: Vec<_> = ranked(json).unwrap().into_iter().filter_map(|t| t.title).collect();
assert_eq!(titles, ["newer", "older", "settled, newest", "snoozed"]);
assert!(ranked("not json").is_err());
}
#[test]
fn web_links_become_app_links() {
assert_eq!(
app_link("https://app.t3.codes/threads/env-1/thread-2").as_deref(),
Some("t3code://threads/env-1/thread-2")
);
assert_eq!(app_link("https://app.t3.codes/threads/env/a&calc"), None);
assert_eq!(app_link("https://app.t3.codes/threads/env/a/b"), None);
assert_eq!(app_link("https://app.t3.codes/new"), None);
}
#[test]
fn only_a_server_on_this_computer_is_shown() {
let origin = |o: &str| local_origin(&format!(r#"{{"origin":"{o}"}}"#));
assert_eq!(origin("http://127.0.0.1:3773").as_deref(), Some("http://127.0.0.1:3773"));
assert_eq!(origin("http://localhost:80/").as_deref(), Some("http://localhost:80"));
assert_eq!(origin("http://127.0.0.1:80@example.com"), None);
assert_eq!(origin("http://127.0.0.1.example.com:80"), None);
assert_eq!(origin("https://example.com"), None);
assert_eq!(local_origin("{}"), None);
assert_eq!(
web_page("http://127.0.0.1:3773", "https://app.t3.codes/threads/e/t").as_deref(),
Some("http://127.0.0.1:3773/e/t")
);
}
#[test]
fn a_worktree_leads_to_its_main_checkout() {
let root = std::env::temp_dir().join(format!("rustimal-t3-test-{}", std::process::id()));
let (main, tree) = (root.join("main"), root.join("elsewhere"));
std::fs::create_dir_all(main.join(".git/worktrees/feature")).unwrap();
std::fs::create_dir_all(tree.join("src")).unwrap();
let git_dir = main.join(".git/worktrees/feature").to_string_lossy().replace('\\', "/");
std::fs::write(tree.join(".git"), format!("gitdir: {git_dir}\n")).unwrap();
let found = (main_checkout(&tree.join("src")), main_checkout(&main));
std::fs::remove_dir_all(&root).unwrap();
assert_eq!(found, (Some(main), None));
}
#[test]
fn titles_cannot_send_escape_codes() {
let t = &ranked(r#"[{"title":"a\u001b]2;b\u0007","link":"x","status":"running"}]"#).unwrap()[0];
assert_eq!(describe(1, t), " 1 a]2;b (running)");
}
}