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

+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;