Rename to t3tui

The command, package, env vars (T3TUI_*), config folder, tmux session and
the session label it issues itself. An existing ~/.config/tui3 moves to
~/.config/t3tui on the first run.
This commit is contained in:
Callum Alpass committed 2026-11-03 01:12:17 +11:00
1 parent 673d314e46
commit 1cccff8031
30 files changed
+147 -138

No files matched your search

+13 -13
View File
@@ -1,23 +1,23 @@
# tui3
# t3tui
**A TUI for a GUI for TUIs.**
Claude Code and Codex run in a terminal. [T3 Code](https://github.com/pingdotgg/t3code) gives them a proper app, with your threads, worktrees, diffs and approvals in one window, which is a lot nicer than keeping track of a dozen terminal tabs. tui3 takes that app and puts it back in a terminal.
Claude Code and Codex run in a terminal. [T3 Code](https://github.com/pingdotgg/t3code) gives them a proper app, with your threads, worktrees, diffs and approvals in one window, which is a lot nicer than keeping track of a dozen terminal tabs. t3tui takes that app and puts it back in a terminal.
It works anywhere you can get a shell, so you can check on a run over SSH from a laptop or your phone, or from a server you were already logged into. `tui3 tmux --watch` mirrors each active thread into its own tmux window, which you can detach from and come back to later. Everything is on the keyboard (`j`/`k` between threads, `y` to approve, `D` for the diff, `ctrl+k` for the rest), and `tui3 list --json` gives scripts something to read. Since it talks to the same server as the app, you can start a run in one and carry on in the other without anything needing to sync.
It works anywhere you can get a shell, so you can check on a run over SSH from a laptop or your phone, or from a server you were already logged into. `t3tui tmux --watch` mirrors each active thread into its own tmux window, which you can detach from and come back to later. Everything is on the keyboard (`j`/`k` between threads, `y` to approve, `D` for the diff, `ctrl+k` for the rest), and `t3tui list --json` gives scripts something to read. Since it talks to the same server as the app, you can start a run in one and carry on in the other without anything needing to sync.
tui3 doesn't have to do much. T3 Code's server runs the agents and keeps track of sessions, worktrees, checkpoints, approvals, terminals and pull requests. tui3 connects to the server you already have running, speaks its WebSocket protocol, and applies updates with upstream's own types and reducers, so mostly it draws what T3 Code already knows and sends back what you type. That's why it was quick to build, and why it tends to stay in step with the app. Credit for the parts that work goes to T3 Code; anything that looks wrong is probably tui3's fault.
t3tui doesn't have to do much. T3 Code's server runs the agents and keeps track of sessions, worktrees, checkpoints, approvals, terminals and pull requests. t3tui connects to the server you already have running, speaks its WebSocket protocol, and applies updates with upstream's own types and reducers, so mostly it draws what T3 Code already knows and sends back what you type. That's why it was quick to build, and why it tends to stay in step with the app. Credit for the parts that work goes to T3 Code; anything that looks wrong is probably t3tui's fault.
Built with Bun and [OpenTUI](https://github.com/anomalyco/opentui) (React). tui3 is an unofficial project, not made by or affiliated with the T3 Code team.
Built with Bun and [OpenTUI](https://github.com/anomalyco/opentui) (React). t3tui is an unofficial project, not made by or affiliated with the T3 Code team.
## Install
You need [Bun](https://bun.sh) and a T3 Code server running on the same machine (or a token for a remote one; see [How it connects](#how-it-connects)).
```sh
git clone --recurse-submodules https://github.com/callumalpass/tui3.git && cd tui3
git clone --recurse-submodules https://github.com/callumalpass/t3tui.git && cd t3tui
bun install # also links the pinned T3 Code packages into node_modules and builds dist/
bun link # optional: puts `tui3` on your PATH
bun link # optional: puts `t3tui` on your PATH
```
After pulling changes, run `bun run build` (or `bun install`) to rebuild.
@@ -25,13 +25,13 @@ After pulling changes, run `bun run build` (or `bun install`) to rebuild.
## Use
```sh
tui3 # dashboard: threads on the left, the selected thread on the right
tui3 attach <thread> # one thread, full screen (id, short id from `tui3 list`, or title text)
tui3 list [--json] # print threads and exit
tui3 tmux [--watch] # mirror active threads into a tmux session, one window each
t3tui # dashboard: threads on the left, the selected thread on the right
t3tui attach <thread> # one thread, full screen (id, short id from `t3tui list`, or title text)
t3tui list [--json] # print threads and exit
t3tui tmux [--watch] # mirror active threads into a tmux session, one window each
```
The message box is always at the bottom. tui3 has two modes: **typing**, where keys go to the message box, and **navigation**, where single keys act. `esc` switches to navigation; `i`, `enter` or `tab` switch back.
The message box is always at the bottom. t3tui has two modes: **typing**, where keys go to the message box, and **navigation**, where single keys act. `esc` switches to navigation; `i`, `enter` or `tab` switch back.
The keys you'll use most:
@@ -57,7 +57,7 @@ See [docs/reference.md](docs/reference.md) for every key, the message box, diffs
## How it connects
tui3 finds the local T3 Code server from `~/.t3/userdata/server-runtime.json` (override with `TUI3_SERVER`). On first run it issues itself a session with `t3 auth session issue --label tui3`, scoped to what it needs, and stores it in `~/.config/tui3/credentials.json`. Revoke it any time with `t3 auth session revoke`. For a remote server, pass a token in `TUI3_TOKEN`.
t3tui finds the local T3 Code server from `~/.t3/userdata/server-runtime.json` (override with `T3TUI_SERVER`). On first run it issues itself a session with `t3 auth session issue --label t3tui`, scoped to what it needs, and stores it in `~/.config/t3tui/credentials.json`. Revoke it any time with `t3 auth session revoke`. For a remote server, pass a token in `T3TUI_TOKEN`.
The scopes, the protocol and how to update for a newer T3 Code are in [docs/development.md](docs/development.md).
+1 -1
View File
@@ -3,7 +3,7 @@
"configVersion": 1,
"workspaces": {
"": {
"name": "tui3",
"name": "t3tui",
"dependencies": {
"@opentui/core": "0.2.7",
"@opentui/react": "0.2.7",
+8 -8
View File
@@ -1,26 +1,26 @@
# Developing tui3
# Developing t3tui
## Running from source
`tui3` runs the bundle in `dist/`, which uses over 100 MB less memory than the sources. After pulling changes, run `bun run build` (or `bun install`) to rebuild it; `bun run dev` runs the sources directly.
`t3tui` runs the bundle in `dist/`, which uses over 100 MB less memory than the sources. After pulling changes, run `bun run build` (or `bun install`) to rebuild it; `bun run dev` runs the sources directly.
Set `TUI3_DEBUG=/path/to/log` to log thread subscriptions and snapshots.
Set `T3TUI_DEBUG=/path/to/log` to log thread subscriptions and snapshots.
## How it connects
- It finds the local server from `~/.t3/userdata/server-runtime.json` (override with `TUI3_SERVER`).
- On first run it mints its own bearer session with `t3 auth session issue --label tui3`, scoped to `orchestration:read`, `orchestration:operate` (attachments and automations ride on it), `filesystem:read` (diffs), `source-control:write` (git actions), `terminal:read` and `terminal:operate` (terminals, stopping servers), `diagnostics:read` (usage totals) and `providers:manage` (reset credits), and stores it in `~/.config/tui3/credentials.json` (mode 600). A stored credential missing any of these scopes is replaced with a new one. Revoke it any time with `t3 auth session revoke`. For a remote server, pass a token in `TUI3_TOKEN`.
- It finds the local server from `~/.t3/userdata/server-runtime.json` (override with `T3TUI_SERVER`).
- On first run it mints its own bearer session with `t3 auth session issue --label t3tui`, scoped to `orchestration:read`, `orchestration:operate` (attachments and automations ride on it), `filesystem:read` (diffs), `source-control:write` (git actions), `terminal:read` and `terminal:operate` (terminals, stopping servers), `diagnostics:read` (usage totals) and `providers:manage` (reset credits), and stores it in `~/.config/t3tui/credentials.json` (mode 600). A stored credential missing any of these scopes is replaced with a new one. Revoke it any time with `t3 auth session revoke`. For a remote server, pass a token in `T3TUI_TOKEN`.
- It speaks T3 Code's own WebSocket RPC protocol, typed by upstream's `@t3tools/contracts`, and applies thread updates with upstream's own reducers. Both come from `vendor/t3code`, a submodule pinned to the server version this was built against (`v0.1.6-nightly.20261030.3917`).
## Following the web app
tui3 aims to behave like T3 Code's web app: the same sidebar sections and status words, timeline, thread menu, palette scoring, alert rules, setting names and defaults (except the two alert settings), attachment limits, and editor fallback order. Where it can, it uses the web app's own code from `vendor/t3code` rather than reimplementing it. When a behaviour differs, that's either a gap (listed under "Not yet supported" in the README) or a terminal constraint, such as links showing as raw markdown in the message box instead of chips.
t3tui aims to behave like T3 Code's web app: the same sidebar sections and status words, timeline, thread menu, palette scoring, alert rules, setting names and defaults (except the two alert settings), attachment limits, and editor fallback order. Where it can, it uses the web app's own code from `vendor/t3code` rather than reimplementing it. When a behaviour differs, that's either a gap (listed under "Not yet supported" in the README) or a terminal constraint, such as links showing as raw markdown in the message box instead of chips.
Some gaps come from the pinned server rather than tui3: it doesn't publish update-available or shutting-down events, historical checkpoint diffs have no unchanged context, and the open-in-editor RPC has no line argument.
Some gaps come from the pinned server rather than t3tui: it doesn't publish update-available or shutting-down events, historical checkpoint diffs have no unchanged context, and the open-in-editor RPC has no line argument.
## Updating for a newer T3 Code
The protocol packages are private and change without notice, so tui3 tracks a pinned upstream tag:
The protocol packages are private and change without notice, so t3tui tracks a pinned upstream tag:
```sh
cd vendor/t3code && git fetch --depth 1 origin tag <tag> && git checkout <tag> && cd -
+10 -10
View File
@@ -1,6 +1,6 @@
# tui3 reference
# t3tui reference
Everything tui3 does, by area. Most of it is also in the command palette (`ctrl+k`), which lists every action and its key.
Everything t3tui does, by area. Most of it is also in the command palette (`ctrl+k`), which lists every action and its key.
- [Modes](#modes)
- [Keys](#keys)
@@ -18,7 +18,7 @@ Everything tui3 does, by area. Most of it is also in the command palette (`ctrl+
## Modes
The message box is always at the bottom. tui3 has two modes: **typing**, where keys go to the message box, and **navigation**, where single keys act. `esc` switches to navigation; `i`, `enter` or `tab` switch back. Drafts are kept per thread.
The message box is always at the bottom. t3tui has two modes: **typing**, where keys go to the message box, and **navigation**, where single keys act. `esc` switches to navigation; `i`, `enter` or `tab` switch back. Drafts are kept per thread.
## Keys
@@ -105,8 +105,8 @@ The layout follows T3 Code's web app, and much of it uses the web app's own code
- **Find in thread:** `f`, or `Find in thread` in the palette or thread menu, searches the whole conversation, counts matches, highlights them, and loads earlier history to reach the selected one. Matching Markdown shows as plain text while you search.
- **Archived threads:** `A` or `Show archived threads` opens the archive. Open a thread as usual; `Unarchive thread` in the palette restores it, and `Show active threads` returns to the live list.
- **Ordering:** `J` / `K` or `Move pinned thread down` / `up` in the palette reorder pinned threads. Active threads stay ordered by when they came back to you.
- **Read state:** opening a thread marks it read after a moment. Set `TUI3_NO_VISIT=1` to turn that off.
- **Bottom line:** server restarts, update results and migration events flash here, along with reconnect status. If the connection drops, tui3 reconnects and resubscribes on its own; press `r` to retry straight away.
- **Read state:** opening a thread marks it read after a moment. Set `T3TUI_NO_VISIT=1` to turn that off.
- **Bottom line:** server restarts, update results and migration events flash here, along with reconnect status. If the connection drops, t3tui reconnects and resubscribes on its own; press `r` to retry straight away.
## Mouse
@@ -149,7 +149,7 @@ Limits: GIF, JPEG, PNG and WebP images up to 10 MB each and 80 MB in all, other
## Terminals
`ctrl+j` attaches to the thread's terminal on the T3 server, the same one the app's terminal drawer shows. If the thread has none, it starts one in the thread's worktree or project folder; with several, you pick one or start another. tui3 hands the whole screen to the terminal; `ctrl+j` or `ctrl+]` comes back, and the terminal keeps running. Its size is shared, so attaching resizes it for anyone else watching.
`ctrl+j` attaches to the thread's terminal on the T3 server, the same one the app's terminal drawer shows. If the thread has none, it starts one in the thread's worktree or project folder; with several, you pick one or start another. t3tui hands the whole screen to the terminal; `ctrl+j` or `ctrl+]` comes back, and the terminal keeps running. Its size is shared, so attaching resizes it for anyone else watching.
`T` opens the terminal picker even with only one terminal. Choose `New terminal`, `Close terminal…` or `Clear terminal…`; typing `close` or `clear` finds each terminal's action directly. Closing ends the shell and deletes its history; clearing clears its scrollback. These are in the command palette too.
@@ -159,11 +159,11 @@ Limits: GIF, JPEG, PNG and WebP images up to 10 MB each and 80 MB in all, other
While a worktree is being prepared, its stage, progress and any failure show above the message box. `Cancel worktree setup…` in the palette asks first.
`E` opens the workspace in an editor on the server. In a single-file diff it opens that file; in a whole-tree diff it asks which file. It picks from the server's available editors in the app's fallback order (tui3 can't see which editor your browser last used), and it can't jump to a line.
`E` opens the workspace in an editor on the server. In a single-file diff it opens that file; in a whole-tree diff it asks which file. It picks from the server's available editors in the app's fallback order (t3tui can't see which editor your browser last used), and it can't jump to a line.
## Alerts
tui3 alerts when a thread you aren't watching finishes or needs you (approval, input, a request, a failure or a usage limit), on the same rules as T3 Code. Subagents don't alert. Depending on `notificationMode`:
t3tui alerts when a thread you aren't watching finishes or needs you (approval, input, a request, a failure or a usage limit), on the same rules as T3 Code. Subagents don't alert. Depending on `notificationMode`:
- **Bell:** the terminal bell.
- **Desktop notifications:** sent through the terminal (OSC 9, or OSC 99 in kitty), only when the terminal window isn't focused. Under tmux they need `set -g allow-passthrough on`.
@@ -172,7 +172,7 @@ While the terminal is focused, alerts for other threads also show on the bottom
## Settings
Open them from the command palette (`Settings`). `j`/`k` move, `enter` or a click changes one, and changes save to `~/.config/tui3/config.json`:
Open them from the command palette (`Settings`). `j`/`k` move, `enter` or a click changes one, and changes save to `~/.config/t3tui/config.json`:
| Setting | Choices | Default |
| --- | --- | --- |
@@ -184,6 +184,6 @@ Open them from the command palette (`Settings`). `j`/`k` move, `enter` or a clic
| `inAppNotificationsEnabled` | `true`, `false` | `true` |
| `theme` | `auto` (match the terminal), `dark`, `light`; applies from the next start | `auto` |
They have the same names as the app's settings. The app keeps its settings in the browser, so tui3 keeps its own, and turns the two alert settings on by default where the app leaves them off.
They have the same names as the app's settings. The app keeps its settings in the browser, so t3tui keeps its own, and turns the two alert settings on by default where the app leaves them off.
The same view shows the server settings that matter here (model and mode for new threads, auto-settle, rate-limited threads), read-only; change those in the app. Below them is usage: each provider's limit windows as room left, its banked reset credits, and the last 30 days' cost and tokens. When a window is 90% used or more, the top line says so. `Use reset credit: …` in the palette spends a banked credit, after asking.
+2 -2
View File
@@ -1,11 +1,11 @@
{
"name": "tui3",
"name": "t3tui",
"version": "0.0.1",
"private": true,
"license": "MIT",
"type": "module",
"bin": {
"tui3": "./dist/bin.js"
"t3tui": "./dist/bin.js"
},
"scripts": {
"dev": "bun run src/bin.ts",
+1 -1
View File
@@ -1,4 +1,4 @@
// Bundles tui3 into dist/. Running the TypeScript sources makes Bun compile and keep
// Bundles t3tui into dist/. Running the TypeScript sources makes Bun compile and keep
// hundreds of vendored modules at startup, which costs over 100 MB of memory.
import { rm } from "node:fs/promises";
import { join } from "node:path";
+6 -6
View File
@@ -50,7 +50,7 @@ const snapshot = {
schemaVersion: 1,
snapshotSequence: 0,
projects: [
project("project-tui3", "tui3", "/home/dev/projects/tui3"),
project("project-t3tui", "t3tui", "/home/dev/projects/t3tui"),
project("project-acme", "acme-api", "/home/dev/projects/acme-api"),
project("project-dotfiles", "dotfiles", "/home/dev/dotfiles"),
],
@@ -58,7 +58,7 @@ const snapshot = {
// The open thread: pinned, running, and waiting on a command approval.
thread({
id: OPEN_THREAD,
projectId: "project-tui3",
projectId: "project-t3tui",
title: "Bundle into dist/",
runtimeMode: "approval-required",
status: "running",
@@ -95,7 +95,7 @@ const snapshot = {
// Waiting for an answer.
thread({
id: "thread-resize",
projectId: "project-tui3",
projectId: "project-t3tui",
title: "Resize the thread list",
status: "running",
latestRunId: "run-resize",
@@ -136,7 +136,7 @@ const snapshot = {
// Idle and read.
thread({
id: "thread-tmux",
projectId: "project-tui3",
projectId: "project-t3tui",
title: "Add tmux mirror",
latestRunRequestedAt: ago(3 * HOUR + 10 * MIN),
latestRunStartedAt: ago(3 * HOUR + 10 * MIN),
@@ -263,7 +263,7 @@ const projection = {
thread: {
...v2Projection.thread,
id: OPEN_THREAD,
projectId: "project-tui3",
projectId: "project-t3tui",
title: "Bundle into dist/",
runtimeMode: "approval-required",
createdAt: ago(2 * DAY),
@@ -340,7 +340,7 @@ function standalonePage(fragment: string, pageBg: string): string {
<html lang="en">
<head>
<meta charset="utf-8">
<title>tui3 — demo screen</title>
<title>t3tui — demo screen</title>
<style>
body { margin: 0; padding: 24px; background: ${pageBg}; }
.tui { font-family: ui-monospace, "SF Mono", Menlo, Consolas, monospace; font-size: 13px; line-height: 1.3; margin: 0; padding: 12px 14px; border-radius: 8px; overflow-x: auto; }
+17 -15
View File
@@ -1,31 +1,33 @@
#!/usr/bin/env bun
import type { OrchestrationV2ShellSnapshot, ThreadId } from "@t3tools/contracts";
import { migrateConfigDir } from "./client/auth.ts";
import { T3Session } from "./client/session.ts";
import { findThread, lastActivity, relativeTime, rowTime, shortId, statusLabel, threadRows } from "./model/threads.ts";
const USAGE = `tui3: a terminal client for T3 Code
const USAGE = `t3tui: a terminal client for T3 Code
usage:
tui3 dashboard: every thread, live
tui3 attach <thread> one thread, full screen (id, short id from \`list\`, or title text)
tui3 list [--json] print threads and exit
tui3 tmux [--watch] [--session <name>]
mirror active threads into tmux windows (default session: tui3)
tui3 help
t3tui dashboard: every thread, live
t3tui attach <thread> one thread, full screen (id, short id from \`list\`, or title text)
t3tui list [--json] print threads and exit
t3tui tmux [--watch] [--session <name>]
mirror active threads into tmux windows (default session: t3tui)
t3tui help
env:
TUI3_SERVER server origin (default: the local server from ~/.t3)
TUI3_TOKEN bearer token for a remote server (local servers mint one via \`t3\`)`;
T3TUI_SERVER server origin (default: the local server from ~/.t3)
T3TUI_TOKEN bearer token for a remote server (local servers mint one via \`t3\`)`;
async function main(argv: string[]) {
migrateConfigDir();
const [command, ...rest] = argv;
switch (command) {
case undefined:
return runUi();
case "attach": {
const needle = rest.join(" ").trim();
if (!needle) return fail("usage: tui3 attach <thread>");
if (!needle) return fail("usage: t3tui attach <thread>");
return runUi(needle);
}
case "list":
@@ -79,9 +81,9 @@ async function list(json: boolean) {
async function tmuxCommand(args: string[]) {
const { syncTmux } = await import("./mux/tmux.ts");
const sessionFlag = args.indexOf("--session");
const name = sessionFlag >= 0 ? args[sessionFlag + 1] : "tui3";
if (!name) return fail("usage: tui3 tmux [--watch] [--session <name>]");
const options = { session: name, tui3: [process.execPath, import.meta.path] };
const name = sessionFlag >= 0 ? args[sessionFlag + 1] : "t3tui";
if (!name) return fail("usage: t3tui tmux [--watch] [--session <name>]");
const options = { session: name, t3tui: [process.execPath, import.meta.path] };
const { session, snapshot } = await connectedSession();
const { opened } = await syncTmux(snapshot, options);
console.log(`tmux session "${name}" is in sync (${opened} new window${opened === 1 ? "" : "s"}). Attach with: tmux attach -t ${name}`);
@@ -146,11 +148,11 @@ async function runUi(attachNeedle?: string) {
// The kitty keyboard protocol lets terminals that support it send shift+enter, for newlines.
const renderer = await createCliRenderer({ exitOnCtrlC: false, useMouse: true, useKittyKeyboard: {} });
// OpenTUI answers SIGHUP and SIGTERM by tearing the screen down without exiting, and the
// session's socket would keep a closed terminal's tui3 running for good.
// session's socket would keep a closed terminal's t3tui running for good.
renderer.once("destroy", () => {
void Promise.race([session.stop(), Bun.sleep(1000)]).finally(() => process.exit(0));
});
// Bun collects so lazily that a streaming thread takes tui3 past 500 MB of garbage. A full
// Bun collects so lazily that a streaming thread takes t3tui past 500 MB of garbage. A full
// collection pauses for up to ~150 ms, so it waits for a few seconds without keys or clicks.
let lastInput = Date.now();
process.stdin.on("data", () => {
+23 -16
View File
@@ -1,13 +1,14 @@
import { existsSync, renameSync } from "node:fs";
import { chmod, mkdir, readFile, writeFile } from "node:fs/promises";
import { homedir } from "node:os";
import { dirname, join } from "node:path";
/**
* Scopes tui3 asks for: read and operate threads (attachments and automations ride on
* Scopes t3tui asks for: read and operate threads (attachments and automations ride on
* operate), read diffs, run git actions (commit, push, open a PR), stop a thread's local
* servers, use its terminals, read usage totals, and spend reset credits.
*/
export const TUI3_SCOPES = ["orchestration:read", "orchestration:operate", "filesystem:read", "source-control:write", "terminal:read", "terminal:operate", "diagnostics:read", "providers:manage"] as const;
export const T3TUI_SCOPES = ["orchestration:read", "orchestration:operate", "filesystem:read", "source-control:write", "terminal:read", "terminal:operate", "diagnostics:read", "providers:manage"] as const;
export interface ServerTarget {
/** e.g. http://127.0.0.1:3773 */
@@ -25,19 +26,25 @@ export interface StoredCredential {
const t3Home = () => process.env.T3CODE_HOME ?? join(homedir(), ".t3");
export const configDir = () =>
join(process.env.XDG_CONFIG_HOME ?? join(homedir(), ".config"), "tui3");
join(process.env.XDG_CONFIG_HOME ?? join(homedir(), ".config"), "t3tui");
const credentialPath = () => join(configDir(), "credentials.json");
/** Moves settings and credentials from before the rename (~/.config/tui3) to the new folder, once. */
export function migrateConfigDir(): void {
const old = join(dirname(configDir()), "tui3");
if (!existsSync(configDir()) && existsSync(old)) renameSync(old, configDir());
}
/** Finds the local server from the runtime file T3 Code writes on startup. */
export async function resolveLocalServer(): Promise<ServerTarget> {
const override = process.env.TUI3_SERVER;
const override = process.env.T3TUI_SERVER;
if (override) return targetFromHttp(override);
const runtimePath = join(t3Home(), "userdata", "server-runtime.json");
let runtime: { origin?: string; port?: number };
try {
runtime = JSON.parse(await readFile(runtimePath, "utf8"));
} catch {
throw new Error(`No running T3 Code server found (${runtimePath} is missing). Start T3 Code, or set TUI3_SERVER.`);
throw new Error(`No running T3 Code server found (${runtimePath} is missing). Start T3 Code, or set T3TUI_SERVER.`);
}
const origin = runtime.origin ?? `http://127.0.0.1:${runtime.port ?? 3773}`;
return targetFromHttp(origin);
@@ -51,14 +58,14 @@ function targetFromHttp(httpBaseUrl: string): ServerTarget {
}
export async function readCredential(target: ServerTarget): Promise<StoredCredential | undefined> {
if (process.env.TUI3_TOKEN) {
return { httpBaseUrl: target.httpBaseUrl, bearerToken: process.env.TUI3_TOKEN, issuedAt: "" };
if (process.env.T3TUI_TOKEN) {
return { httpBaseUrl: target.httpBaseUrl, bearerToken: process.env.T3TUI_TOKEN, issuedAt: "" };
}
try {
const all: StoredCredential[] = JSON.parse(await readFile(credentialPath(), "utf8"));
const stored = all.find((c) => c.httpBaseUrl === target.httpBaseUrl);
// A credential from an older tui3 lacks newer scopes; issue a fresh one.
return stored && TUI3_SCOPES.every((scope) => stored.scopes?.includes(scope)) ? stored : undefined;
// A credential from an older t3tui lacks newer scopes; issue a fresh one.
return stored && T3TUI_SCOPES.every((scope) => stored.scopes?.includes(scope)) ? stored : undefined;
} catch {
return undefined;
}
@@ -78,12 +85,12 @@ async function writeCredential(credential: StoredCredential): Promise<void> {
/**
* Issues a scoped bearer session through the local `t3` CLI, which can mint one
* because it shares the server's data directory. Remote servers need TUI3_TOKEN.
* because it shares the server's data directory. Remote servers need T3TUI_TOKEN.
*/
export async function issueLocalCredential(target: ServerTarget): Promise<StoredCredential> {
const t3 = process.env.TUI3_T3_BIN ?? join(t3Home(), "bin", "t3");
const args = ["auth", "session", "issue", "--label", "tui3", "--token-only"];
for (const scope of TUI3_SCOPES) args.push("--scope", scope);
const t3 = process.env.T3TUI_T3_BIN ?? join(t3Home(), "bin", "t3");
const args = ["auth", "session", "issue", "--label", "t3tui", "--token-only"];
for (const scope of T3TUI_SCOPES) args.push("--scope", scope);
const proc = Bun.spawn([t3, ...args], { stdout: "pipe", stderr: "pipe" });
const [stdout, stderr, code] = await Promise.all([
new Response(proc.stdout).text(),
@@ -94,7 +101,7 @@ export async function issueLocalCredential(target: ServerTarget): Promise<Stored
if (code !== 0 || !token) {
throw new Error(`\`t3 auth session issue\` failed (exit ${code}): ${stderr.trim() || stdout.trim()}`);
}
const credential = { httpBaseUrl: target.httpBaseUrl, bearerToken: token, issuedAt: new Date().toISOString(), scopes: [...TUI3_SCOPES] };
const credential = { httpBaseUrl: target.httpBaseUrl, bearerToken: token, issuedAt: new Date().toISOString(), scopes: [...T3TUI_SCOPES] };
await writeCredential(credential);
return credential;
}
@@ -112,7 +119,7 @@ export async function resolveSocketUrl(
headers: { authorization: `Bearer ${credential.bearerToken}` },
});
if (response.status === 401 || response.status === 403) {
throw new UnauthorizedError(`T3 Code rejected tui3's token (${response.status}).`);
throw new UnauthorizedError(`T3 Code rejected t3tui's token (${response.status}).`);
}
if (!response.ok) {
throw new Error(`WebSocket ticket request failed: ${response.status} ${await response.text()}`);
@@ -121,7 +128,7 @@ export async function resolveSocketUrl(
const url = new URL("/ws", target.wsBaseUrl);
url.searchParams.set("wsTicket", ticket);
url.searchParams.set(protocol.param, String(protocol.version));
url.searchParams.set("clientSurface", "tui3");
url.searchParams.set("clientSurface", "t3tui");
url.searchParams.set("connectionMethod", "direct");
return url.toString();
}
+2 -2
View File
@@ -38,8 +38,8 @@ const socketUrlFor = async (target: ServerTarget) => {
try {
return { url: await resolveSocketUrl(target, existing, protocol), credential: existing };
} catch (error) {
// A revoked or expired token falls through to a fresh one; TUI3_TOKEN never does.
if (!(error instanceof UnauthorizedError) || process.env.TUI3_TOKEN) throw error;
// A revoked or expired token falls through to a fresh one; T3TUI_TOKEN never does.
if (!(error instanceof UnauthorizedError) || process.env.T3TUI_TOKEN) throw error;
}
}
const credential = await issueLocalCredential(target);
+4 -4
View File
@@ -159,8 +159,8 @@ const RECONNECT_DELAYS_MS = [500, 1_000, 2_000, 5_000, 10_000];
const NO_HISTORY: ThreadHistory = { cursor: null, hasMore: false, loading: false };
const debugPath = process.env.TUI3_DEBUG;
/** Appends to the file named by TUI3_DEBUG; the TUI owns stdout and stderr. */
const debugPath = process.env.T3TUI_DEBUG;
/** Appends to the file named by T3TUI_DEBUG; the TUI owns stdout and stderr. */
export function debugLog(message: string): void {
if (debugPath) appendFileSync(debugPath, `${new Date().toISOString()} ${message}\n`);
}
@@ -560,9 +560,9 @@ export class T3Session {
return this.dispatch({ type: "thread.user-input.dismiss", commandId: newCommandId(), threadId, requestId });
}
/** Moves the thread's read watermark, as opening it in the web app does. TUI3_NO_VISIT=1 peeks without it. */
/** Moves the thread's read watermark, as opening it in the web app does. T3TUI_NO_VISIT=1 peeks without it. */
visit(threadId: ThreadId): Promise<void> {
if (process.env.TUI3_NO_VISIT === "1") return Promise.resolve();
if (process.env.T3TUI_NO_VISIT === "1") return Promise.resolve();
return this.dispatch({ type: "thread.visit", commandId: newCommandId(), threadId, visitedAt: new Date().toISOString(), opened: true });
}
+12 -12
View File
@@ -4,10 +4,10 @@ import { join } from "node:path";
import { configDir } from "./client/auth.ts";
/**
* tui3's own preferences. The web app keeps these in each browser's storage, out of the
* server's reach, so tui3 keeps its own copy, under the web app's names and defaults.
* t3tui's own preferences. The web app keeps these in each browser's storage, out of the
* server's reach, so t3tui keeps its own copy, under the web app's names and defaults.
*/
export interface Tui3Config {
export interface T3tuiConfig {
/** What enter does while the agent is running; alt+enter does the other. */
readonly followUpBehavior: "steer" | "queue";
/** "ctrl-enter" makes enter a newline and ctrl+enter send (needs the kitty keyboard protocol). */
@@ -22,10 +22,10 @@ export interface Tui3Config {
readonly theme: "auto" | "dark" | "light";
}
export const DEFAULT_CONFIG: Tui3Config = { followUpBehavior: "steer", sendShortcut: "enter", timestampFormat: "locale", diffIgnoreWhitespace: true, notificationMode: "sound", inAppNotificationsEnabled: true, theme: "auto" };
export const DEFAULT_CONFIG: T3tuiConfig = { followUpBehavior: "steer", sendShortcut: "enter", timestampFormat: "locale", diffIgnoreWhitespace: true, notificationMode: "sound", inAppNotificationsEnabled: true, theme: "auto" };
/** Every setting with its choices in cycling order, for the settings view. */
export const CONFIG_CHOICES: { readonly [K in keyof Tui3Config]: readonly Tui3Config[K][] } = {
export const CONFIG_CHOICES: { readonly [K in keyof T3tuiConfig]: readonly T3tuiConfig[K][] } = {
followUpBehavior: ["steer", "queue"],
sendShortcut: ["enter", "ctrl-enter"],
timestampFormat: ["locale", "12-hour", "24-hour"],
@@ -38,7 +38,7 @@ export const CONFIG_CHOICES: { readonly [K in keyof Tui3Config]: readonly Tui3Co
export const configPath = () => join(configDir(), "config.json");
/** Reads the config, keeping defaults for anything missing or not one of the choices. */
export async function loadConfig(): Promise<Tui3Config> {
export async function loadConfig(): Promise<T3tuiConfig> {
let raw: unknown;
try {
raw = JSON.parse(await readFile(configPath(), "utf8"));
@@ -48,29 +48,29 @@ export async function loadConfig(): Promise<Tui3Config> {
return parseConfig(raw);
}
export function parseConfig(raw: unknown): Tui3Config {
export function parseConfig(raw: unknown): T3tuiConfig {
const record = raw && typeof raw === "object" ? (raw as Record<string, unknown>) : {};
const config: Record<string, unknown> = { ...DEFAULT_CONFIG };
for (const [key, choices] of Object.entries(CONFIG_CHOICES)) {
if ((choices as readonly unknown[]).includes(record[key])) config[key] = record[key];
}
return config as unknown as Tui3Config;
return config as unknown as T3tuiConfig;
}
export async function saveConfig(config: Tui3Config): Promise<void> {
export async function saveConfig(config: T3tuiConfig): Promise<void> {
await mkdir(configDir(), { recursive: true });
await writeFile(configPath(), `${JSON.stringify(config, null, 2)}\n`);
}
/** The next choice for one setting, wrapping around. */
export function cycleConfig<K extends keyof Tui3Config>(config: Tui3Config, key: K): Tui3Config {
const choices = CONFIG_CHOICES[key] as readonly Tui3Config[K][];
export function cycleConfig<K extends keyof T3tuiConfig>(config: T3tuiConfig, key: K): T3tuiConfig {
const choices = CONFIG_CHOICES[key] as readonly T3tuiConfig[K][];
const next = choices[(choices.indexOf(config[key]) + 1) % choices.length]!;
return { ...config, [key]: next };
}
/** A clock time ("HH:MM") in the chosen format, as the web app's timestamps. */
export function formatClock(timeOfDay: string, format: Tui3Config["timestampFormat"]): string {
export function formatClock(timeOfDay: string, format: T3tuiConfig["timestampFormat"]): string {
const [hours, minutes] = timeOfDay.split(":").map(Number);
if (hours === undefined || minutes === undefined || Number.isNaN(hours) || Number.isNaN(minutes)) return timeOfDay;
const date = new Date(2000, 0, 1, hours, minutes);
+1 -1
View File
@@ -25,7 +25,7 @@ const LOCAL_ENVIRONMENT = "local" as EnvironmentId;
* The web's ThreadNotificationCoordinator over the shell snapshot: attention (approval,
* question, guest request, failure, usage limit) alerts once per run and status;
* completion alerts after the Working shelf's grace, unless the run was stopped. Nothing
* alerts for state that was already there when tui3 connected.
* alerts for state that was already there when t3tui connected.
*/
export function createAlerts(onAlert: (alert: Alert) => void) {
let previous = new Map<ThreadId, Observed>();
+1 -1
View File
@@ -32,7 +32,7 @@ export interface ComposerItem {
const THREAD_LIMIT = 5;
export const PATH_SEARCH_LIMIT = 80;
/** The trigger the cursor sits in, or null. `/model` is a command here, as tui3 has no model-name search. */
/** The trigger the cursor sits in, or null. `/model` is a command here, as t3tui has no model-name search. */
export function composerTrigger(text: string, cursor: number): ComposerTrigger | null {
const trigger = detectComposerTrigger(text, cursor);
if (trigger?.kind === "slash-model") return { ...trigger, kind: "slash-command", query: "model" };
+3 -3
View File
@@ -13,7 +13,7 @@ import { formatWorkingDurationLabel } from "@t3tools/client-runtime/state/models
import { homedir } from "node:os";
import type { VcsState } from "../client/session.ts";
import { formatClock, type Tui3Config } from "../config.ts";
import { formatClock, type T3tuiConfig } from "../config.ts";
import { buildMenuItems, resolveQuickAction } from "../../vendor/t3code/apps/web/src/components/GitActionsControl.logic.ts";
import type { StatusTone } from "./threads.ts";
@@ -93,7 +93,7 @@ export interface DetailsInput {
readonly automations?: readonly ScheduledTask[];
readonly now?: number;
/** How automation times read; the system's locale by default. */
readonly timestampFormat?: Tui3Config["timestampFormat"];
readonly timestampFormat?: T3tuiConfig["timestampFormat"];
}
export interface PullRequestLine {
@@ -223,7 +223,7 @@ function gitActions(status: VcsStatusResult): NonNullable<ThreadDetails["git"]>
return { quick, hint: quick ? null : quickAction.hint ?? quickAction.label, menu };
}
function automationLine(task: ScheduledTask, now: number, timestampFormat: Tui3Config["timestampFormat"]): AutomationLine {
function automationLine(task: ScheduledTask, now: number, timestampFormat: T3tuiConfig["timestampFormat"]): AutomationLine {
const schedule =
task.schedule.type === "interval"
? `every ${formatWorkingDurationLabel(task.schedule.everyMs)}`
+6 -6
View File
@@ -1,16 +1,16 @@
import type { ServerConfig } from "@t3tools/contracts";
import { CONFIG_CHOICES, type Tui3Config } from "../config.ts";
import { CONFIG_CHOICES, type T3tuiConfig } from "../config.ts";
import { RUNTIME_MODE_LABELS } from "./details.ts";
export interface SettingRow {
readonly key: keyof Tui3Config;
readonly key: keyof T3tuiConfig;
readonly label: string;
readonly value: string;
readonly help: string;
}
const LABELS: { readonly [K in keyof Tui3Config]: { readonly label: string; readonly help: string; readonly values?: Partial<Record<string, string>> } } = {
const LABELS: { readonly [K in keyof T3tuiConfig]: { readonly label: string; readonly help: string; readonly values?: Partial<Record<string, string>> } } = {
followUpBehavior: { label: "While the agent runs, enter", help: "alt+enter does the other", values: { steer: "steers", queue: "queues" } },
sendShortcut: { label: "Send with", help: "ctrl+enter needs kitty keyboard support; alt+enter also sends", values: { enter: "enter", "ctrl-enter": "ctrl+enter (enter adds a line)" } },
timestampFormat: { label: "Times", help: "automation schedules", values: { locale: "system locale", "12-hour": "12-hour", "24-hour": "24-hour" } },
@@ -24,9 +24,9 @@ const LABELS: { readonly [K in keyof Tui3Config]: { readonly label: string; read
theme: { label: "Colours", help: "from the next start", values: { auto: "match the terminal", dark: "dark", light: "light" } },
};
/** tui3's own settings, in display order, each cycled with enter. */
export function settingRows(config: Tui3Config): SettingRow[] {
return (Object.keys(CONFIG_CHOICES) as (keyof Tui3Config)[]).map((key) => {
/** t3tui's own settings, in display order, each cycled with enter. */
export function settingRows(config: T3tuiConfig): SettingRow[] {
return (Object.keys(CONFIG_CHOICES) as (keyof T3tuiConfig)[]).map((key) => {
const meta = LABELS[key];
const raw = String(config[key]);
return { key, label: meta.label, value: meta.values?.[raw] ?? raw, help: meta.help };
+6 -6
View File
@@ -3,7 +3,7 @@ import { presentThreadShell, threadRuntimeCanArchive } from "@t3tools/client-run
import { canSnooze, effectiveSnoozed, pickSnoozePreset, resolveSnoozePresets, type SnoozePreset } from "@t3tools/client-runtime/state/thread-settled";
import { pinOrderKeyBetween } from "@t3tools/client-runtime/state/thread-sort";
import type { Tui3Config } from "../config.ts";
import type { T3tuiConfig } from "../config.ts";
import { buildThreadActionMenuItems, type ThreadActionMenuId } from "../../vendor/t3code/apps/web/src/components/threadActionMenu.logic.ts";
export type { ThreadActionMenuId };
@@ -18,8 +18,8 @@ export interface ThreadMenu {
readonly snoozePresets: readonly SnoozePreset[];
}
/** The web sidebar's thread menu (right-click), from the same builder, less what tui3 can't do. */
export function threadMenu(input: { readonly thread: OrchestrationV2ThreadShell; readonly config: ServerConfig | null; readonly timestampFormat: Tui3Config["timestampFormat"]; readonly now?: Date }): ThreadMenu {
/** The web sidebar's thread menu (right-click), from the same builder, less what t3tui can't do. */
export function threadMenu(input: { readonly thread: OrchestrationV2ThreadShell; readonly config: ServerConfig | null; readonly timestampFormat: T3tuiConfig["timestampFormat"]; readonly now?: Date }): ThreadMenu {
const { config } = input;
// The presented shell carries what the menu reads: pending requests, the runtime.
const thread = presentThreadShell(config?.environment.environmentId ?? LOCAL, input.thread);
@@ -44,18 +44,18 @@ export function threadMenu(input: { readonly thread: OrchestrationV2ThreadShell;
return { items: items.filter((item) => !UNSUPPORTED.has(item.id)), snoozePresets };
}
function snoozeMenu(config: ServerConfig | null, timestampFormat: Tui3Config["timestampFormat"], now: Date): readonly SnoozePreset[] {
function snoozeMenu(config: ServerConfig | null, timestampFormat: T3tuiConfig["timestampFormat"], now: Date): readonly SnoozePreset[] {
const presets = config?.settings.snoozePresets;
return resolveSnoozePresets(now, { ...(presets ? { presets } : {}), formatTime: (date) => formatTime(date, timestampFormat) });
}
/** A shown snooze choice, re-resolved now as the web does; undefined once its time has passed. */
export function pickSnooze(shown: readonly SnoozePreset[], id: string, config: ServerConfig | null, timestampFormat: Tui3Config["timestampFormat"]): SnoozePreset | undefined {
export function pickSnooze(shown: readonly SnoozePreset[], id: string, config: ServerConfig | null, timestampFormat: T3tuiConfig["timestampFormat"]): SnoozePreset | undefined {
const presets = config?.settings.snoozePresets;
return pickSnoozePreset({ shown, id, now: new Date(), ...(presets ? { presets } : {}), formatTime: (date) => formatTime(date, timestampFormat) });
}
function formatTime(date: Date, format: Tui3Config["timestampFormat"]): string {
function formatTime(date: Date, format: T3tuiConfig["timestampFormat"]): string {
return date.toLocaleTimeString(undefined, { hour: "numeric", minute: "2-digit", ...(format === "locale" ? {} : { hour12: format === "12-hour" }) });
}
+1 -1
View File
@@ -9,7 +9,7 @@ import {
import { derivePendingThreadRequests, type PendingThreadRequests } from "@t3tools/client-runtime/state/thread-requests";
import { deriveThreadCheckpointSummaries } from "@t3tools/client-runtime/state/thread-checkpoints";
// The web app's own timeline derivation: tui3 shows the same rows, folds and labels.
// The web app's own timeline derivation: t3tui shows the same rows, folds and labels.
import {
computeStableMessagesTimelineRows,
deriveMessagesTimelineRowsWithState,
+5 -5
View File
@@ -3,13 +3,13 @@ import type { OrchestrationV2ShellSnapshot } from "@t3tools/contracts";
import { needsAttention, threadRows, type ThreadRow } from "../model/threads.ts";
/** Window option that ties a tmux window to the thread it attaches to. */
const THREAD_OPTION = "@tui3_thread";
const THREAD_OPTION = "@t3tui_thread";
const TITLE_WIDTH = 24;
export interface TmuxSyncOptions {
readonly session: string;
/** Command that starts tui3, e.g. [bun, /path/to/bin.ts]. */
readonly tui3: readonly string[];
/** Command that starts t3tui, e.g. [bun, /path/to/bin.ts]. */
readonly t3tui: readonly string[];
}
async function tmux(args: readonly string[], allowFailure = false): Promise<string> {
@@ -35,7 +35,7 @@ export function windowName(row: ThreadRow): string {
export async function syncTmux(snapshot: OrchestrationV2ShellSnapshot, options: TmuxSyncOptions): Promise<{ readonly opened: number }> {
const { session } = options;
if (!(await sessionExists(session))) {
await tmux(["new-session", "-d", "-s", session, "-n", "dashboard", shellJoin(options.tui3)]);
await tmux(["new-session", "-d", "-s", session, "-n", "dashboard", shellJoin(options.t3tui)]);
}
const windows = new Map<string, string>();
for (const line of (await tmux(["list-windows", "-t", `=${session}`, "-F", `#{window_id}\t#{${THREAD_OPTION}}`])).split("\n")) {
@@ -50,7 +50,7 @@ export async function syncTmux(snapshot: OrchestrationV2ShellSnapshot, options:
for (const row of rows) {
if (windows.has(row.thread.id)) continue;
const windowId = (
await tmux(["new-window", "-d", "-P", "-F", "#{window_id}", "-t", `=${session}:`, "-n", windowName(row), shellJoin([...options.tui3, "attach", row.thread.id])])
await tmux(["new-window", "-d", "-P", "-F", "#{window_id}", "-t", `=${session}:`, "-n", windowName(row), shellJoin([...options.t3tui, "attach", row.thread.id])])
).trim();
await tmux(["set-option", "-w", "-t", windowId, THREAD_OPTION, row.thread.id]);
windows.set(row.thread.id, windowId);
+4 -4
View File
@@ -10,7 +10,7 @@ import type { ChatAttachment, OrchestrationMessageContext, OrchestrationV2Subage
import type { ServerConfigState, ShellState, T3Session, ThreadState } from "../client/session.ts";
import { createAlerts, type Alert } from "../model/alerts.ts";
import { modelSummary } from "../model/models.ts";
import { configPath, cycleConfig, saveConfig, type Tui3Config } from "../config.ts";
import { configPath, cycleConfig, saveConfig, type T3tuiConfig } from "../config.ts";
import { saveLayout, type Layout } from "../layout.ts";
import { RUNTIME_MODE_LABELS } from "../model/details.ts";
import { paletteEntries, paletteGroups, pickerGroups, type Picker, type PickerItem } from "../model/palette.ts";
@@ -98,7 +98,7 @@ const COMPOSER_KEYS = {
/** The composer's key while a new thread is being drafted. */
const DRAFT_KEY = "draft";
export function App(props: { readonly session: T3Session; readonly config: Tui3Config; readonly layout?: Layout; readonly attachThreadId?: ThreadId }) {
export function App(props: { readonly session: T3Session; readonly config: T3tuiConfig; readonly layout?: Layout; readonly attachThreadId?: ThreadId }) {
const { session, attachThreadId } = props;
const attached = attachThreadId !== undefined;
const renderer = useRenderer();
@@ -765,7 +765,7 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C
detailsKey,
parent && { keys: ["u"], run: () => openThread(parent.threadId), hint: "parent", command: { id: "parent", title: `Go to parent: ${parent.title}` } },
hinted(paletteKey, "commands"),
{ keys: ["q"], run: quit, hint: "quit", command: { id: "quit", title: "Quit tui3", keywords: ["exit"] } },
{ keys: ["q"], run: quit, hint: "quit", command: { id: "quit", title: "Quit t3tui", keywords: ["exit"] } },
panel.keys.toggle,
{ keys: ["e"], run: () => setExpandAll((value) => !value), command: { id: "expand", title: expandAll ? "Collapse work" : "Expand all work", keywords: ["fold", "tool calls"] } },
thread?.history.hasMore && { keys: ["o"], run: loadEarlier, command: { id: "earlier", title: "Load earlier turns", keywords: ["history", "older"] } },
@@ -1055,7 +1055,7 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C
{headerStatus ? <text fg={statusColor(headerStatus.tone)} wrapMode="none" flexShrink={0}>{` ${headerStatus.text}`}</text> : null}
</>
) : (
<text fg={colors.faint}>tui3</text>
<text fg={colors.faint}>t3tui</text>
)}
{shell.status.type !== "live" ? <text fg={colors.warn} wrapMode="none" onMouseDown={() => session.retryNow()}>{` ${status}`}</text> : null}
{usageInfo.note ? <text fg={colors.warn} wrapMode="none">{` ${usageInfo.note}`}</text> : null}
+2 -2
View File
@@ -2,7 +2,7 @@ import type { SettingRow } from "../model/settings.ts";
import { ClickRow } from "./Button.tsx";
import { colors } from "./theme.ts";
/** Settings in place of the conversation: tui3's own (cycled with enter or a click), then the server's, read-only. */
/** Settings in place of the conversation: t3tui's own (cycled with enter or a click), then the server's, read-only. */
export function SettingsView(props: {
readonly rows: readonly SettingRow[];
readonly server: readonly { label: string; value: string }[];
@@ -25,7 +25,7 @@ export function SettingsView(props: {
<text fg={colors.faint}>esc close</text>
</box>
<text fg={colors.text} marginTop={1}>
<strong>{`tui3 · ${props.path}`}</strong>
<strong>{`t3tui · ${props.path}`}</strong>
</text>
{props.rows.map((row, index) => {
const selected = index === props.selected;
+4 -4
View File
@@ -10,7 +10,7 @@ import { FindText } from "./FindText.tsx";
import { isLeftClick, isRightClick, useHover } from "./Button.tsx";
import { checkpointFileTotals, type ThreadCheckpointSummary } from "@t3tools/client-runtime/state/thread-checkpoints";
import { formatDuration } from "@t3tools/shared/orchestrationTiming";
import type { Tui3Config } from "../config.ts";
import type { T3tuiConfig } from "../config.ts";
import { CommandOutput } from "./CommandOutput.tsx";
import { BAR } from "./edges.ts";
@@ -52,7 +52,7 @@ export function ThreadView(props: {
readonly loading: boolean;
readonly error?: string | undefined;
readonly workspaceRoot: string | undefined;
readonly timestampFormat: Tui3Config["timestampFormat"];
readonly timestampFormat: T3tuiConfig["timestampFormat"];
readonly now: number;
readonly scrollRef: RefObject<ScrollBoxRenderable | null>;
/** For a subagent or fork: the thread it came from, shown as a link in the header. */
@@ -104,7 +104,7 @@ export function ThreadView(props: {
* landed, day-aware as the web's is. Parts a row doesn't carry are left out;
* only a finished turn's last reply (or its detached meta row) gets one.
*/
function assistantFooter(row: MessagesTimelineRow, timeline: Timeline, timestampFormat: Tui3Config["timestampFormat"], now: number): string {
function assistantFooter(row: MessagesTimelineRow, timeline: Timeline, timestampFormat: T3tuiConfig["timestampFormat"], now: number): string {
const message = row.kind === "assistant-meta" ? row.message : row.kind === "message" && row.showAssistantMeta ? row.message : null;
if (message?.role !== "assistant" || message.streaming) return "";
const meta = message.runId ? timeline.runMeta.get(message.runId) : undefined;
@@ -120,7 +120,7 @@ function assistantFooter(row: MessagesTimelineRow, timeline: Timeline, timestamp
}
/** The web's day-aware timestamp: a time today, "yesterday at …", then a short date. */
function dayAwareTime(iso: string, format: Tui3Config["timestampFormat"], now: number): string {
function dayAwareTime(iso: string, format: T3tuiConfig["timestampFormat"], now: number): string {
const date = new Date(iso);
if (Number.isNaN(date.getTime())) return "";
const time = date.toLocaleTimeString(undefined, { hour: "numeric", minute: "2-digit", ...(format === "locale" ? {} : { hour12: format === "12-hour" }) });
+1 -1
View File
@@ -10,7 +10,7 @@ import { join } from "node:path";
*/
export function editInEditor(renderer: CliRenderer, text: string): string | null {
const editor = process.env.VISUAL || process.env.EDITOR || "vi";
const dir = mkdtempSync(join(tmpdir(), "tui3-"));
const dir = mkdtempSync(join(tmpdir(), "t3tui-"));
const file = join(dir, "prompt.md");
writeFileSync(file, text);
renderer.suspend();
+3 -3
View File
@@ -6,7 +6,7 @@ import type { T3Session } from "../client/session.ts";
/** Ctrl+J (LF), Ctrl+] and Ctrl+J under the kitty keyboard protocol leave the terminal. */
const DETACH_KEYS = new Set(["\n", "\x1d", "\x1b[106;5u"]);
/** Modes a full-screen program may leave on; switched off before tui3 draws again. */
/** Modes a full-screen program may leave on; switched off before t3tui draws again. */
const RESET = "\x1b[0m\x1b[?25h\x1b[?1l\x1b[?2004l\x1b[?1000l\x1b[?1002l\x1b[?1003l\x1b[?1006l\x1b[?1049l";
export interface TerminalTarget {
@@ -30,7 +30,7 @@ export function attachTerminal(renderer: CliRenderer, session: T3Session, target
renderer.suspend();
stdout.write("\x1b[?1049h\x1b[H\x1b[2J");
stdout.write(`\x1b]2;tui3 · ${target.label} · ctrl+j to return\x07`);
stdout.write(`\x1b]2;t3tui · ${target.label} · ctrl+j to return\x07`);
stdin.setRawMode?.(true);
stdin.resume();
@@ -82,7 +82,7 @@ export function attachTerminal(renderer: CliRenderer, session: T3Session, target
stdin.off("data", onInput);
stdout.off("resize", onResize);
stdout.write(RESET);
stdout.write("\x1b]2;tui3\x07");
stdout.write("\x1b]2;t3tui\x07");
renderer.resume();
renderer.requestRender();
onDone(message);
+2 -2
View File
@@ -1,4 +1,4 @@
/** Escape sequences tui3 writes past the renderer: the bell, desktop notifications, the clipboard. */
/** Escape sequences t3tui writes past the renderer: the bell, desktop notifications, the clipboard. */
import type { CliRenderer } from "@opentui/core";
/** Inside tmux, escape sequences other than the bell need passthrough to reach the outer terminal. */
@@ -21,7 +21,7 @@ export function desktopNotify(title: string, body: string): void {
// biome-ignore lint/suspicious/noControlCharactersInRegex: the control characters are what is being stripped
const clean = (text: string) => text.replace(/[\x00-\x1f\x7f;]/g, " ").slice(0, 200);
const sequence = process.env.KITTY_WINDOW_ID
? `\x1b]99;i=tui3:d=0;${clean(title)}\x1b\\\x1b]99;i=tui3:p=body;${clean(body)}\x1b\\`
? `\x1b]99;i=t3tui:d=0;${clean(title)}\x1b\\\x1b]99;i=t3tui:p=body;${clean(body)}\x1b\\`
: `\x1b]9;${clean(title)}: ${clean(body)}\x07`;
process.stdout.write(passthrough(sequence));
}
+2 -2
View File
@@ -2,7 +2,7 @@ import type { DiscoveredLocalServer, OrchestrationProjectShell, OrchestrationV2S
import { useEffect, useMemo, useState } from "react";
import type { FeedState, T3Session, VcsState } from "../client/session.ts";
import type { Tui3Config } from "../config.ts";
import type { T3tuiConfig } from "../config.ts";
import { detailsActions, detailsCwd, threadDetails, type DetailsAction, type GitAction } from "../model/details.ts";
import { keys, type Binding } from "../model/keymap.ts";
import type { Automations } from "./useAutomations.ts";
@@ -27,7 +27,7 @@ export function useDetails(deps: {
readonly snapshot: OrchestrationV2ShellSnapshot | null;
readonly subagents: readonly OrchestrationV2Subagent[];
readonly now: number;
readonly config: Tui3Config;
readonly config: T3tuiConfig;
readonly diff: DiffState | null;
readonly setDiff: (update: DiffState | null | ((value: DiffState | null) => DiffState | null)) => void;
readonly automations: Automations;
+2 -2
View File
@@ -3,7 +3,7 @@ import { threadChipCopyTarget } from "@t3tools/client-runtime/thread-reference";
import type { ContextMenuItem, OrchestrationV2ShellSnapshot, OrchestrationV2ThreadShell, ServerConfig, ThreadId } from "@t3tools/contracts";
import type { T3Session } from "../client/session.ts";
import type { Tui3Config } from "../config.ts";
import type { T3tuiConfig } from "../config.ts";
import type { Binding } from "../model/keymap.ts";
import type { Picker, PickerItem } from "../model/palette.ts";
import { parseSnooze, pickSnooze, threadHasRuntime, threadMenu, topPinOrderKey, type ThreadActionMenuId } from "../model/threadMenu.ts";
@@ -18,7 +18,7 @@ export function useThreadMenu(deps: {
readonly renderer: CliRenderer;
readonly snapshot: OrchestrationV2ShellSnapshot | null;
readonly config: ServerConfig | null;
readonly timestampFormat: Tui3Config["timestampFormat"];
readonly timestampFormat: T3tuiConfig["timestampFormat"];
/** The open thread: the menu's key and palette command act on it. */
readonly thread: OrchestrationV2ThreadShell | undefined;
readonly openPicker: (picker: Picker) => void;
+3 -3
View File
@@ -6,7 +6,7 @@ import { createMockKeys, type KeyInput } from "@opentui/core/testing";
import type { OrchestrationV2ShellSnapshot, OrchestrationV2ThreadProjection, ThreadId } from "@t3tools/contracts";
import type { ConnectionStatus, T3Session } from "../../src/client/session.ts";
import { DEFAULT_CONFIG, type Tui3Config } from "../../src/config.ts";
import { DEFAULT_CONFIG, type T3tuiConfig } from "../../src/config.ts";
import type { Layout } from "../../src/layout.ts";
import { App } from "../../src/ui/App.tsx";
import { v2Projection, v2ShellSnapshot, v2ThreadId } from "../../vendor/t3code/packages/client-runtime/src/state/orchestrationV2TestFixtures.ts";
@@ -14,7 +14,7 @@ import { v2Projection, v2ShellSnapshot, v2ThreadId } from "../../vendor/t3code/p
export { v2Projection, v2ShellSnapshot, v2ThreadId };
// Settings and layout saves go to a scratch folder, never the real config.
process.env.XDG_CONFIG_HOME = mkdtempSync(join(tmpdir(), "tui3-test-"));
process.env.XDG_CONFIG_HOME = mkdtempSync(join(tmpdir(), "t3tui-test-"));
// Updates from the app's own timers land outside act(); the warnings say nothing useful here.
const consoleError = console.error;
@@ -76,7 +76,7 @@ export function fakeSession(
}
/** Renders the whole app against a fake session, with helpers to drive it by key and mouse. */
export async function renderApp(options: { readonly session?: ReturnType<typeof fakeSession>; readonly config?: Partial<Tui3Config>; readonly layout?: Layout; readonly width?: number; readonly height?: number } = {}) {
export async function renderApp(options: { readonly session?: ReturnType<typeof fakeSession>; readonly config?: Partial<T3tuiConfig>; readonly layout?: Layout; readonly width?: number; readonly height?: number } = {}) {
const fake = options.session ?? fakeSession();
const config = { ...DEFAULT_CONFIG, ...options.config };
const rig = await testRender(<App session={fake.session} config={config} {...(options.layout ? { layout: options.layout } : {})} />, { width: options.width ?? 140, height: options.height ?? 40 });
+1 -1
View File
@@ -6,7 +6,7 @@ import { automationTemplate, newAutomationTemplate, parseAutomation } from "../s
const projects = [
{ id: "p1", title: "tasknotes", workspaceRoot: "/repo/tasknotes" },
{ id: "p2", title: "tui3", workspaceRoot: "/repo/tui3" },
{ id: "p2", title: "t3tui", workspaceRoot: "/repo/t3tui" },
] as unknown as OrchestrationProjectShell[];
const task = (extra: Record<string, unknown> = {}) =>
+1 -1
View File
@@ -19,7 +19,7 @@ function capturingSession() {
const isCommand = Schema.is(OrchestrationV2Command);
const threadId = ThreadId.make("thread-1");
describe("commands tui3 dispatches", () => {
describe("commands t3tui dispatches", () => {
test("messages dispatch like the web composer: auto, steer or queue", async () => {
const { session, sent } = capturingSession();
await session.sendMessage(threadId, "hello");