rustimal 0.6.0

A minimal, GPU-rendered terminal for Windows that runs Git Bash, with animated split panes and a glass look
//! Which T3 Code conversation belongs to a folder.
//!
//! T3 Code's own CLI says which conversations a folder has. In a rustimal pane, `t3` shows
//! one in T3 Code's web UI, right in the pane (see `app::t3`). From other shells,
//! `rustimal --t3` opens it in the desktop app with a `t3code://threads/...` link.

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,
    /// Set on the conversations a conversation starts for itself (subagents).
    parent_thread_id: Option<String>,
}

#[derive(Debug, PartialEq)]
enum Action {
    /// Open the conversation with this number in the list, counted from 1.
    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))
}

/// The conversations worth jumping to, in the order `t3 -l` numbers them: the ones still
/// open before the settled and snoozed ones, newest first within each.
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());
    // The times are all ISO 8601 in UTC, so they sort as text.
    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)
}

/// The desktop app's link for a thread's web link (`https://.../threads/ENV/THREAD`). Only
/// plain ids are let through, since the result is handed to the Windows shell.
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}"))
}

/// For a folder in a linked Git worktree, the main checkout. T3 Code knows the project by
/// that folder, and a worktree can be anywhere on disk.
fn main_checkout(dir: &Path) -> Option<PathBuf> {
    let dot_git = dir.ancestors().map(|d| d.join(".git")).find(|p| p.exists())?;
    // A normal checkout has a .git folder; a worktree has a file pointing into the main one.
    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)
}

/// Where T3 Code keeps its data.
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())
}

/// The command T3 Code's desktop app writes for its bundled CLI.
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()))
    }
}

/// Run T3 Code's CLI. The error is whatever it printed.
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())
}

/// The folder's conversations, or `None` if T3 Code has no project for it.
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?)")),
    }
}

/// The address of the running server's web UI, from what the server writes about itself.
/// Only an address on this computer is accepted, since it is shown inside the terminal.
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())
}

/// The web UI's page for a thread's web link.
fn web_page(origin: &str, web_link: &str) -> Option<String> {
    let link = app_link(web_link)?;
    Some(format!("{origin}/{}", link.strip_prefix("t3code://threads/")?))
}

/// What a rustimal pane should show for a folder.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Page {
    /// The web UI's address, without a path.
    pub origin: String,
    pub url: String,
}

/// The page for conversation `number` (counted from 1, as `t3 -l` lists them) of a folder.
/// A folder with no conversation gets T3 Code's start page. This runs T3 Code's CLI, so
/// it takes about a second.
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 })
}

/// One line of `t3 -l`.
fn describe(number: usize, t: &Thread) -> String {
    // Titles are free text; keep them from sending escape codes to the terminal.
    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))),
        // Nothing to jump to yet: open the folder itself.
        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(())
}

/// `rustimal --t3 [-l | NUMBER] [FOLDER]`. Returns the exit code.
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)");
    }
}