rustimal 0.7.0

A minimal, GPU-rendered terminal for Windows that runs Git Bash, with animated split panes and a glass look
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
//! 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. If no
//! T3 Code server is running, one is started out of sight (see [`server`]).

pub mod server;

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 stop         stop the server rustimal started in the background
    t3 COMMAND ...  anything else goes to T3 Code's own CLI

T3 Code doesn't have to be open: if no server is running, one is started out of sight.
It stops by itself when you open the T3 Code app, which takes over.

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 NO_SERVER: &str = "No running T3 Code server";
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())
}

/// Does this failure mean there is no server to ask, so far? With none at all the CLI
/// says so. While one is starting, the CLI may instead try the database itself, and find
/// it taken or busy.
fn no_server_yet(error: &str) -> bool {
    [NO_SERVER, "ServerOwns", "effect/sql", "SqlError"].iter().any(|sign| error.contains(sign))
}

/// Is this failure the running server's own answer, so that trying again is no use?
fn answered(error: &str) -> bool {
    error.contains(NO_PROJECT)
}

/// What the running server wrote about itself.
fn runtime_file() -> Result<PathBuf, String> {
    Ok(t3_home()?.join("userdata").join("server-runtime.json"))
}

/// 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| no_server_yet(e)) {
        // While a server is starting, the CLI can fail in other ways too (it may find the
        // database taken before the server has said it is there). So only an answer from
        // the server counts, and that answer is the list that was wanted.
        let mut last = String::new();
        result = server::ensure(|| {
            let again = list(dir);
            match &again {
                Err(e) if !answered(e) => {
                    last.clone_from(e);
                    None
                }
                _ => Some(again),
            }
        })
        .map_err(|why| format!("{why}\n{last}"))?;
    }
    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(e),
    }
}

/// 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 origin = std::fs::read_to_string(runtime_file()?)
        .ok()
        .and_then(|text| local_origin(&text))
        .ok_or("could not find the address of T3 Code's local server")?;
    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;
    }
    if args == ["stop"] {
        return match server::stop() {
            Ok(said) => {
                println!("{said}");
                0
            }
            Err(e) => {
                eprintln!("t3: {e}");
                1
            }
        };
    }
    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_the_servers_own_answer_ends_the_wait() {
        assert!(answered("No T3 Code project matches 'C:\\x'."));
        assert!(!answered("No running T3 Code server uses C:\\x. Start T3 Code, then retry."));
        assert!(!answered("ERROR: ServerOwnsDatabaseError: Another T3 Code process owns this folder"));
        for starting in [
            "No running T3 Code server uses C:\\x.",
            "[11:26:08] ERROR (#2): ServerOwnsDatabaseError: ...",
            "[11:27:44] ERROR (#2): effect/sql/SqlError: database is locked",
        ] {
            assert!(no_server_yet(starting), "{starting}");
        }
        assert!(!no_server_yet("No T3 Code project matches 'C:\\x'."));
        assert!(!no_server_yet("T3 Code's CLI isn't at C:\\x."), "no use starting anything");
    }

    #[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)");
    }
}