diff --git a/README.md b/README.md index 02f7a51..ad9dd58 100644 --- a/README.md +++ b/README.md @@ -1,18 +1,26 @@ # tui3 -A terminal client for [T3 Code](https://github.com/pingdotgg/t3code). It connects to the T3 Code server you already run, shows every thread live, and lets you read, message, approve and stop them without the GUI. +**A TUI for a GUI for TUIs.** -Built with Bun and [OpenTUI](https://github.com/anomalyco/opentui) (React). +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. + +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. + +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. + +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. ## 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 && cd tui3 +git clone --recurse-submodules https://github.com/callumalpass/tui3.git && cd tui3 bun install # also links the pinned T3 Code packages into node_modules and builds dist/ bun link # optional: puts `tui3` on your PATH ``` -`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. +After pulling changes, run `bun run build` (or `bun install`) to rebuild. ## Use @@ -23,182 +31,40 @@ tui3 list [--json] # print threads and exit tui3 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. Drafts are kept per thread. +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. -Any mode: +The keys you'll use most: | Key | Action | | --- | --- | -| `ctrl+k` | command palette: every action below, plus thread search | -| `ctrl+j` | attach to the thread's terminal (see below) | -| `ctrl+n` / `ctrl+p` (or `alt+↓`/`alt+↑`) | next / previous thread | -| `pgup`/`pgdn`, `ctrl+u`/`ctrl+d` | scroll the conversation | +| `ctrl+k` | command palette: every action, with its key, plus thread search | +| `ctrl+n` / `ctrl+p` | next / previous thread (`j`/`k` in navigation) | +| `enter` | send; while the agent runs, steer it mid-run | +| `alt+enter` | queue the message for after the run | +| `y` / `Y` / `n` | approve / always allow this session / decline | +| `S` | stop the thread | +| `D` | view the latest turn's changes | +| `P` | view the thread's pull request | +| `c` | new thread | +| `m` | model, reasoning and access mode | +| `.` | thread actions: pin, snooze, rename, archive… | +| `ctrl+j` | attach to the thread's terminal on the server | | `ctrl+c` | quit | -Typing: `enter` sends. While the agent is running, `enter` steers it (the message reaches it mid-run) and `alt+enter` queues the message for after the run, as in T3 Code. With an approval pending, a typed message declines it with your feedback. `shift+enter` adds a newline (it needs a terminal with the kitty keyboard protocol); so does ending the line with `\` and pressing `enter`. The box grows up to 8 lines. With the box empty after an interrupted run (or one a usage limit stopped), `enter` continues where it left off, as T3's resume button does, and releases messages held in the queue. `ctrl+g` opens the message in `$VISUAL` or `$EDITOR` (falling back to `vi`); save and quit to bring it back. +In the message box, `/`, `$`, `@` and `#` suggest commands, skills, files and threads, and pull requests. Most things also work with the mouse. -As in T3 Code's message box, typing a trigger opens a list of suggestions above the box: - -| Trigger | Suggests | Inserts | -| --- | --- | --- | -| `/` | `/model`, then the provider's commands (only at the start of the message) and skills | `/command`, or `$skill` for a skill; `/model` opens the model picker | -| `$` | the provider's skills | `$skill` | -| `@` | threads, then files and folders in the thread's worktree or project | a markdown link to the file, or a link to the thread (sent along with the message, as T3 does) | -| `#` | pull requests in the thread's repository (by number, or by words in the title) | a link to the pull request (sent along with the message, as T3 does) | - -`↑`/`↓` or `ctrl+n`/`ctrl+p` move, `tab` or `enter` chooses, a click chooses, and `esc` closes the list. Links show as raw markdown in the box; T3 shows them as chips. - -Navigation: - -| Key | Action | -| --- | --- | -| `j`/`k`, arrows | next / previous thread (scroll, in `attach`) | -| `c` | new thread (see below) | -| `a` | attach a file to the next message (see below) | -| `.` | thread actions (see below); a right-click on a thread opens them too | -| `m` | model, options (reasoning, fast mode…) and access mode | -| `T` | terminals: attach, new, close or clear | -| `b` | branches and worktrees: switch, create, pull or remove | -| `E` | open the workspace (or diff file) in the server's editor | -| `y` / `Y` / `n` | approve / always allow this session / decline the pending approval | -| `1`–`9` | pick an option when the agent asks a question (also in an empty message box) | -| `x` | dismiss the agent's question, or decline its secret request | -| `enter` | with a secret request pending: type or paste the secret into a masked field (it never goes through the message box); `enter` saves it, `esc` cancels | -| `Q` | go through queued messages: `j`/`k` move, `enter` sends one now (starts a turn, or steers it into the running one), `e` edits it in the message box (`enter` saves, `esc` cancels), `x` removes it. `alt+↑` in the message box edits the last one | -| `e` | expand all folded turns, work groups and command output | -| `[` / `]` | select the previous / next turn; `esc` clears the selection | -| `D` | view changes from the selected turn, or the latest turn with changes | -| `R` | rewind to before the selected prompt, after confirmation | -| `o` | load earlier turns | -| `f` | find in the open thread; `enter` / `shift+enter` or `ctrl+n` / `ctrl+p` move between matches, `esc` closes | -| `A` | show archived threads / return to active threads | -| `J` / `K` | move the selected pinned thread down / up | -| `d` | show or hide thread details | -| `P` | show the thread's linked pull request (see below) | -| `l` / `→` | move into the details panel: `j`/`k` choose, `enter` opens, `t` turns an automation on or off, `esc` comes back | -| `u` | go to the parent thread (from a fork or subagent) | -| `:` | command palette | -| `z` | show the Settled and Snoozed sections; `Show more settled threads` in the palette loads older rows | -| `/` | filter threads by title or project (the box opens at the top of the thread list) | -| `S` | stop the thread | -| `g` / `G` | top / bottom of the conversation | -| `esc` / `q` | close the diff or cancel a new thread; otherwise `q` quits | - -The layout follows T3 Code's web app, and much of it uses the web app's own code (vendored from upstream): - -- **Sidebar:** the same sections (Pinned, Active, Working, then Snoozed and Settled folded to a count) and the same status words: `Working 2m`, `Waiting`, `Approval`, `Input`, `Request`, `Limited`, `Failed`, `Done`. Threads that need you are bold. -- **Turns:** `[`/`]` select a turn and mark its prompt. `R` or `Revert to this turn` asks `Edit from here?`, then rewinds chat and returns the prompt to the composer, keeping file changes. `Revert files too` in the palette also restores files, including your own edits. Stop a running turn first. Rewinding messages with attachments still needs the web app. -- **Command output:** expand work with `e` / `Expand all work`, or click a command. Output streams while its expanded row is in view; collapsing it, scrolling away or opening another thread stops the subscription. -- **Conversation:** built by the web app's timeline logic. Each finished turn's work folds into one line (`Worked for 3m 12s`), your messages are right-aligned, and a running turn shows its live step and `Working for 12s`. -- **Thread details:** a column beside the conversation with the workspace, model and mode, the branch with ahead/behind and its pull request, uncommitted changes per file, lineage (forks and subagents), background work and the goal. It opens by itself on terminals 160 columns or wider; on narrow ones `d` shows it in place of the conversation. -- **Diffs:** pick `View diff` or a file under Changes to see uncommitted changes as unified diffs in place of the conversation. `D` (or `View changes from this turn`) reviews a turn's checkpoint; `View all changes in this thread` reviews the whole thread. `j`/`k` scroll, `[`/`]` choose a file, and `esc` closes. In uncommitted diffs, `x` or `enter` shows the whole file, including unchanged context; press it again to collapse. Historical checkpoint context is unavailable, as in the web app. -- **Git:** the branch section offers the web app's quick action (`Commit & push`, `Push`, `Create PR`…) and its menu. Every action asks first, says when you are on the default branch, and takes an optional commit message (blank lets T3 write one). Progress shows on the bottom line. -- **Pull requests:** `P` shows a linked pull request in place of the conversation (with several, you pick one): its state, author and branches, description, checks, reviews, recent comments and the review guide when one was written. `j`/`k` scroll, `o` opens it in the browser, `r` refreshes it from the host, and `esc` closes it. From there, `c` comments and `R` reviews (approve / request changes / comment) in `$EDITOR`, `a` offers the host's actions (merge, close, ready…) behind a confirmation, `w` watches or stops watching, and `u` unlinks it. `Link pull request to thread` in the palette links one by URL or number, and `New thread from pull request…` checks one out into a draft in the project folder or a dedicated worktree. -- **Servers and automations:** local dev servers the thread started (stop one from the panel) and T3's scheduled tasks with their schedule and next run (run now, or turn on and off). Automations are made and changed from the palette: `New automation` and `Edit automation: …` open the web form's fields in `$EDITOR` (title, schedule, project, workspace, model, mode, prompt); save and quit to save. `Delete automation: …` asks first. Webhook signatures and filters are kept as they are; change those in the app. -- **Subagents:** subagent work in the conversation and the lineage rows in details are links; `enter` or a click opens the child thread, and `u` goes back. Idle subagents, which the thread list leaves out, are fetched from the server when you open one (on servers that serve them). A running subagent the web could stop gets a "Stop subagent" command in the palette. -- **Command palette:** `ctrl+k`, as in the web app. It searches commands and threads with T3's own scoring, then lists full-text hits with snippets under `In messages`; start with `>` for commands only. Message search needs a word of at least three letters. -- **Find in thread:** `f` or `Find in thread` in the palette or thread menu searches the whole conversation, counts matches, highlights matching text and loads earlier history to reveal the selected match. Matching Markdown is shown as highlighted plain text while finding. -- **Archived threads:** `A` or `Show archived threads` in the palette opens the archive. Open a thread normally; `Unarchive thread` in the palette restores it. `Show active threads` returns to the live list. -- **Ordering:** `J` / `K` or `Move pinned thread down` / `Move pinned thread up` in the palette reorder pinned threads. Active threads stay ordered by return time, as in T3 Code's Working shelf. -- **Mouse:** - - **Select and copy:** drag across any text to select it; it's copied when you let go (through the terminal with OSC 52, and the desktop clipboard locally). A key press clears the highlight. Your terminal's own selection still works with shift held. - - **Buttons:** approvals, questions (click an option), secret requests, confirmations, queued messages (click one for send now / edit / remove), attached files (✕ removes one) and the PR view have buttons, each with its key beside it. Every hint along the bottom that names one key is clickable, and so is `commands` at the top. - - **Conversation:** a click on a prompt selects that turn, as `[`/`]` do; a click on a folded turn or work group opens just that one; a click on a command shows its output; "Load earlier turns" loads them. In a diff, a click on a file selects it and a second click shows its whole file. In the PR view, the URL opens in the browser. - - **Right-click menus:** on a thread (its actions), a prompt (copy, view its changes, revert), a reply (copy), a command (copy the command or its output) and the PR view (its actions). - - **Panes:** clicking the conversation takes the keys out of the message box or details; clicking the message box types. The wheel scrolls the conversation, the thread list (without moving the selection) and the palette. Drag the thread list's right border to resize it; right-click the border to reset it. -- Threads open scrolled to the bottom. -- **Read state:** opening a thread marks it read after a moment, as the web app does. Set `TUI3_NO_VISIT=1` to turn that off. - -## Thread actions - -`.`, `Thread actions…` in the palette, or a right-click on a thread in the list opens T3 Code's thread menu, built by the web app's own code: - -- New thread on the thread's branch (in its worktree, if it has one) -- Pin or unpin, settle or un-settle, snooze (T3's presets or a custom time) or wake -- Rename, regenerate the title, mark unread -- Auto-settle on or off for the thread (on servers that support turning it off) -- Copy the workspace path, branch, thread link or thread ID -- Archive or delete - -Submenus open as their own list, and typing finds their items from the top (`thread id` finds `Copy › Thread ID`). A custom snooze takes a duration (`45m`, `3h`, `2d`, `1w`) or a time of day (`17:30`). Delete asks first, as the app does by default; it doesn't offer to remove the thread's worktree, which the app does. Copying goes through the terminal (OSC 52, so it works over SSH), and through `wl-copy`, `xclip` or `pbcopy` on a local desktop. The app's project settings and guest sharing aren't here. - -## New threads - -`c` (or `New thread` in the palette) opens a draft in the current thread's project, with the defaults T3 Code would use: the server's default model and mode for new threads, and the project folder or a new worktree as the project settings say. In the draft, `p` picks the project, `m` the model and mode, and `w` switches between the project folder and a new worktree off the default branch. Write the first message and send it: that starts the thread, which T3 then titles. `esc` cancels. - -## Attachments - -`a` in navigation (or `Attach file…` in the palette) prompts for a path: `~` expands, and a relative path is taken from the thread's worktree or project folder. `Paste image from clipboard` in the palette takes a clipboard image instead (`wl-paste`, `xclip`, or `pngpaste` on macOS). Files upload at once, as in the web composer, and their names show above the message box until the next message sends them; `Remove attachment: …` in the palette takes one back and deletes the unsent upload. The web composer's limits apply: GIF, JPEG, PNG and WebP images up to 10 MB each and 80 MB in all, other files up to the server's limit (50 MB at most), 100 attachments per message. A message can be attachments alone. - -## Model, options and mode - -`m` (or a click on the model under the message box) opens a picker with the access mode, the model's options as the server describes them (reasoning effort, fast mode and whatever else the provider offers), and every model from the providers that are enabled and available. As in the web app: - -- A new model or option applies from the next message you send; the line under the box shows `· next message` until then. -- The access mode changes at once. -- Once a thread has run, it stays on its provider; you can still change models within it. - -## 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. The terminal keeps running after you detach. The terminal's 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` also finds each terminal's action directly. Closing ends the shell and deletes its history; clearing clears its scrollback. These actions are also in the command palette. - -## Workspace - -`b` opens the web app's ref selector: local and remote refs, existing worktrees, `Create and switch ref…`, and `Pull`. Selecting a ref reuses its worktree if it has one; selecting the default branch returns to the project folder. `Create worktree…` asks for a new branch name and moves this thread there. `Remove worktree…` asks first, detaches this thread's provider session and removes the worktree only if no other thread uses it and Git permits it (no forced deletion). Moving folders detaches the provider session, as in the web app. - -Worktree preparation shows its current stage, percentage and detail above the message box, including failures. `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 uses the web app's fallback order among the server's available editors: the browser's last-used editor preference isn't shared with tui3. The pinned RPC has no line argument. - -Server ready/restart, update outcomes and legacy-thread migration events flash on the bottom line. This server version doesn't publish update-available or shutting-down lifecycle events; connection loss uses the existing reconnect status. - -## Alerts - -tui3 alerts when a thread you aren't watching finishes or needs you (approval, input, a request, a failure or a usage limit), using T3 Code's own rules for when to alert. 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`. - -While the terminal is focused, alerts for other threads also show on the bottom line (`inAppNotificationsEnabled`). - -## 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`: - -| Setting | Choices | Default | -| --- | --- | --- | -| `followUpBehavior` | `steer` or `queue`: what `enter` does while the agent runs (`alt+enter` does the other) | `steer` | -| `sendShortcut` | `enter`, or `ctrl-enter` (then `enter` adds a line; needs the kitty keyboard protocol, and `alt+enter` also sends) | `enter` | -| `timestampFormat` | `locale`, `12-hour`, `24-hour` | `locale` | -| `diffIgnoreWhitespace` | `true`, `false` | `true` | -| `notificationMode` | `off`, `sound` (bell), `notifications` (desktop), `notifications-and-sound` | `sound` | -| `inAppNotificationsEnabled` | `true`, `false` | `true` | - -These use the web app's names, and its defaults except for the two alert settings, which the web app leaves off. The web app keeps them in each browser, so tui3 can't read yours and keeps its own. The same view shows the server's 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. Spend a banked credit from the palette (`Use reset credit: …`); it asks first, as the app does. - -Long threads load as a bounded window of recent turns; press `o` for older ones. If the connection drops, tui3 reconnects with backoff and resubscribes. +See [docs/reference.md](docs/reference.md) for every key, the message box, diffs, git, terminals, worktrees, alerts and settings. ## 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). Revoke it any time with `t3 auth session revoke`. A stored credential missing any of these scopes is replaced with a new one. For a remote server, pass a token in `TUI3_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`). +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`. -Set `TUI3_DEBUG=/path/to/log` to log thread subscriptions and snapshots. - -## Updating for a newer T3 Code - -The protocol packages are private and change without notice, so tui3 tracks a pinned upstream tag: - -```sh -cd vendor/t3code && git fetch --depth 1 origin tag && git checkout && cd - -bun install && bun run typecheck && bun test -``` - -Type errors after a bump point at the protocol changes to adapt to. +The scopes, the protocol and how to update for a newer T3 Code are in [docs/development.md](docs/development.md). ## Not yet supported -Plan follow-ups, forking threads, and reviewing or commenting on diffs. Use the T3 Code app for those. +Plan follow-ups, forking threads, reviewing or commenting on diffs, rewinding messages with attachments, project settings and guest sharing. Use the T3 Code app for those. + +## Licence + +[MIT](LICENSE). T3 Code, pulled in as a submodule under `vendor/t3code`, is also MIT. diff --git a/docs/development.md b/docs/development.md new file mode 100644 index 0000000..8f3a2db --- /dev/null +++ b/docs/development.md @@ -0,0 +1,30 @@ +# Developing tui3 + +## 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. + +Set `TUI3_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 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. + +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. + +## Updating for a newer T3 Code + +The protocol packages are private and change without notice, so tui3 tracks a pinned upstream tag: + +```sh +cd vendor/t3code && git fetch --depth 1 origin tag && git checkout && cd - +bun install && bun run typecheck && bun test +``` + +Type errors after a bump point at the protocol changes to adapt to. diff --git a/docs/reference.md b/docs/reference.md new file mode 100644 index 0000000..57a774e --- /dev/null +++ b/docs/reference.md @@ -0,0 +1,189 @@ +# tui3 reference + +Everything tui3 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) +- [The message box](#the-message-box) +- [The screen](#the-screen) +- [Mouse](#mouse) +- [Thread actions](#thread-actions) +- [New threads](#new-threads) +- [Attachments](#attachments) +- [Model, options and mode](#model-options-and-mode) +- [Terminals](#terminals) +- [Workspace](#workspace) +- [Alerts](#alerts) +- [Settings](#settings) + +## 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. + +## Keys + +Any mode: + +| Key | Action | +| --- | --- | +| `ctrl+k` | command palette: every action below, plus thread search | +| `ctrl+j` | attach to the thread's terminal (see [Terminals](#terminals)) | +| `ctrl+n` / `ctrl+p` (or `alt+↓`/`alt+↑`) | next / previous thread | +| `pgup`/`pgdn`, `ctrl+u`/`ctrl+d` | scroll the conversation (`ctrl+u`/`ctrl+d` only in navigation; while typing they edit the text) | +| `ctrl+c` | quit | + +Navigation: + +| Key | Action | +| --- | --- | +| `j`/`k`, arrows | next / previous thread (scroll, in `attach`) | +| `c` | new thread (see [New threads](#new-threads)) | +| `a` | attach a file to the next message (see [Attachments](#attachments)) | +| `.` | thread actions (see [Thread actions](#thread-actions)); a right-click on a thread opens them too | +| `m` | model, options (reasoning, fast mode…) and access mode | +| `T` | terminals: attach, new, close or clear | +| `b` | branches and worktrees: switch, create, pull or remove | +| `E` | open the workspace (or diff file) in the server's editor | +| `y` / `Y` / `n` | approve / always allow this session / decline the pending approval | +| `1`–`9` | pick an option when the agent asks a question (also in an empty message box) | +| `x` | dismiss the agent's question, or decline its secret request | +| `enter` | with a secret request pending: type or paste the secret into a masked field (it never goes through the message box); `enter` saves it, `esc` cancels | +| `Q` | go through queued messages: `j`/`k` move, `enter` sends one now (starts a turn, or steers it into the running one), `e` edits it in the message box (`enter` saves, `esc` cancels), `x` removes it. `alt+↑` in the message box edits the last one | +| `e` | expand all folded turns, work groups and command output | +| `[` / `]` | select the previous / next turn; `esc` clears the selection | +| `D` | view changes from the selected turn, or the latest turn with changes | +| `R` | rewind to before the selected prompt, after confirmation | +| `o` | load earlier turns | +| `f` | find in the open thread; `enter` / `shift+enter` or `ctrl+n` / `ctrl+p` move between matches, `esc` closes | +| `A` | show archived threads / return to active threads | +| `J` / `K` | move the selected pinned thread down / up | +| `d` | show or hide thread details | +| `P` | show the thread's linked pull request | +| `l` / `→` | move into the details panel: `j`/`k` choose, `enter` opens, `t` turns an automation on or off, `esc` comes back | +| `u` | go to the parent thread (from a fork or subagent) | +| `:` | command palette | +| `z` | show the Settled and Snoozed sections; `Show more settled threads` in the palette loads older rows | +| `/` | filter threads by title or project (the box opens at the top of the thread list) | +| `S` | stop the thread | +| `g` / `G` | top / bottom of the conversation | +| `esc` / `q` | close the diff or cancel a new thread; otherwise `q` quits | + +## The message box + +`enter` sends. While the agent is running, `enter` steers it (the message reaches it mid-run) and `alt+enter` queues the message for after the run; the `followUpBehavior` setting swaps the two. With an approval pending, a typed message declines it with your feedback. + +`shift+enter` adds a newline (it needs a terminal with the kitty keyboard protocol); so does ending the line with `\` and pressing `enter`. The box grows up to 8 lines. `ctrl+g` opens the message in `$VISUAL` or `$EDITOR` (falling back to `vi`); save and quit to bring it back. + +With the box empty after an interrupted run (or one a usage limit stopped), `enter` continues where it left off and releases messages held in the queue. + +Typing a trigger opens a list of suggestions above the box: + +| Trigger | Suggests | Inserts | +| --- | --- | --- | +| `/` | `/model`, then the provider's commands (only at the start of the message) and skills | `/command`, or `$skill` for a skill; `/model` opens the model picker | +| `$` | the provider's skills | `$skill` | +| `@` | threads, then files and folders in the thread's worktree or project | a markdown link to the file, or a link to the thread (sent along with the message) | +| `#` | pull requests in the thread's repository (by number, or by words in the title) | a link to the pull request (sent along with the message) | + +`↑`/`↓` or `ctrl+n`/`ctrl+p` move, `tab`, `enter` or a click chooses, and `esc` closes the list. Links show as raw markdown in the box. + +## The screen + +The layout follows T3 Code's web app, and much of it uses the web app's own code. + +- **Sidebar:** the same sections as the app (Pinned, Active, Working, then Snoozed and Settled folded to a count) and the same status words: `Working 2m`, `Waiting`, `Approval`, `Input`, `Request`, `Limited`, `Failed`, `Done`. Threads that need you are bold. +- **Conversation:** each finished turn's work folds into one line (`Worked for 3m 12s`), your messages sit in a raised block with a bar down the left, and a running turn shows its live step and `Working for 12s`. Threads open scrolled to the bottom. Long threads load as a window of recent turns; press `o` for older ones. +- **Turns:** `[`/`]` select a turn and mark its prompt. `R` or `Revert to this turn` asks `Edit from here?`, then rewinds the chat and returns the prompt to the message box, keeping file changes. `Revert files too` in the palette also restores files, including your own edits. Stop a running turn first. Rewinding messages with attachments still needs the app. +- **Command output:** expand work with `e` / `Expand all work`, or click a command. Output streams while its expanded row is in view; collapsing it, scrolling away or opening another thread stops it. +- **Thread details:** a column beside the conversation with the workspace, model and mode, the branch with ahead/behind and its pull request, uncommitted changes per file, lineage (forks and subagents), background work and the goal. It opens by itself on terminals 160 columns or wider; on narrow ones `d` shows it in place of the conversation. +- **Diffs:** pick `View diff` or a file under Changes to see uncommitted changes as unified diffs in place of the conversation. `D` (or `View changes from this turn`) reviews a turn's checkpoint; `View all changes in this thread` reviews the whole thread. `j`/`k` scroll, `[`/`]` choose a file, and `esc` closes. In uncommitted diffs, `x` or `enter` shows the whole file, including unchanged lines; press it again to collapse. Diffs of past checkpoints show only the changed lines. +- **Git:** the branch section offers the quick action (`Commit & push`, `Push`, `Create PR`…) and a menu of the rest. Every action asks first, says when you are on the default branch, and takes an optional commit message (leave it blank and T3 writes one). Progress shows on the bottom line. +- **Pull requests:** `P` shows a linked pull request in place of the conversation (with several, you pick one): its state, author and branches, description, checks, reviews, recent comments and the review guide when one was written. `j`/`k` scroll, `o` opens it in the browser, `r` refreshes it, and `esc` closes it. From there, `c` comments and `R` reviews (approve / request changes / comment) in `$EDITOR`, `a` offers the host's actions (merge, close, ready…) behind a confirmation, `w` watches or stops watching, and `u` unlinks it. `Link pull request to thread` in the palette links one by URL or number, and `New thread from pull request…` checks one out into a draft in the project folder or its own worktree. +- **Servers and automations:** local dev servers the thread started (stop one from the panel) and T3's scheduled tasks with their schedule and next run (run now, or turn on and off). `New automation` and `Edit automation: …` in the palette open the automation's fields in `$EDITOR` (title, schedule, project, workspace, model, mode, prompt); save and quit to save. `Delete automation: …` asks first. Webhook signatures and filters are left as they are; change those in the app. +- **Subagents:** subagent work in the conversation and the lineage rows in details are links; `enter` or a click opens the child thread, and `u` goes back. Idle subagents, which the thread list leaves out, are fetched when you open one. A running subagent gets a `Stop subagent` command in the palette. +- **Command palette:** `ctrl+k` searches commands and threads, then lists full-text hits with snippets under `In messages`; start with `>` for commands only. Message search needs a word of at least three letters. +- **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. + +## Mouse + +- **Select and copy:** drag across any text to select it; it's copied when you let go (through the terminal with OSC 52, and the desktop clipboard locally). A key press clears the highlight. Your terminal's own selection still works with shift held. +- **Buttons:** approvals, questions (click an option), secret requests, confirmations, queued messages (click one to send it now, edit or remove it), attached files (✕ removes one) and the PR view have buttons, each with its key beside it. Every hint along the bottom that names one key is clickable, and so is `commands` at the top. +- **Conversation:** a click on a prompt selects that turn, as `[`/`]` do; a click on a folded turn or work group opens just that one; a click on a command shows its output; "Load earlier turns" loads them. In a diff, a click on a file selects it and a second click shows the whole file. In the PR view, the URL opens in the browser. +- **Right-click menus:** on a thread (its actions), a prompt (copy, view its changes, revert), a reply (copy), a command (copy the command or its output) and the PR view (its actions). +- **Panes:** clicking the conversation takes the keys out of the message box or details; clicking the message box types. The wheel scrolls the conversation, the thread list (without moving the selection) and the palette. Drag the thread list's right edge to resize it; right-click the edge to reset it. + +## Thread actions + +`.`, `Thread actions…` in the palette, or a right-click on a thread opens the thread menu: + +- New thread on the thread's branch (in its worktree, if it has one) +- Pin or unpin, settle or un-settle, snooze (T3's presets or a custom time) or wake +- Rename, regenerate the title, mark unread +- Auto-settle on or off for the thread (on servers that support turning it off) +- Copy the workspace path, branch, thread link or thread ID +- Archive or delete + +Submenus open as their own list, and typing finds their items from the top (`thread id` finds `Copy › Thread ID`). A custom snooze takes a duration (`45m`, `3h`, `2d`, `1w`) or a time of day (`17:30`). Delete asks first; it leaves the thread's worktree alone, so remove that from the app or with `b`. Copying goes through the terminal (OSC 52, so it works over SSH), and through `wl-copy`, `xclip` or `pbcopy` on a local desktop. Project settings and guest sharing are only in the app. + +## New threads + +`c` (or `New thread` in the palette) opens a draft in the current thread's project, with the server's defaults: its model and mode for new threads, and the project folder or a new worktree as the project settings say. In the draft, `p` picks the project, `m` the model and mode, and `w` switches between the project folder and a new worktree off the default branch. Send the first message to start the thread; T3 titles it. `esc` cancels. + +## Attachments + +`a` in navigation (or `Attach file…` in the palette) prompts for a path: `~` expands, and a relative path is taken from the thread's worktree or project folder. `Paste image from clipboard` in the palette takes a clipboard image instead (`wl-paste`, `xclip`, or `pngpaste` on macOS). Files upload at once, and their names show above the message box until the next message sends them; `Remove attachment: …` in the palette takes one back. A message can be attachments alone. + +Limits: GIF, JPEG, PNG and WebP images up to 10 MB each and 80 MB in all, other files up to the server's limit (50 MB at most), and 100 attachments per message. + +## Model, options and mode + +`m` (or a click on the model under the message box) opens a picker with the access mode, the model's options as the server describes them (reasoning effort, fast mode and whatever else the provider offers), and every model from the providers that are enabled and available. + +- A new model or option applies from the next message you send; the line under the box shows `· next message` until then. +- The access mode changes at once. +- Once a thread has run, it stays on its provider; you can still change models within it. + +## 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. + +`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. + +## Workspace + +`b` opens the branch picker: local and remote refs, existing worktrees, `Create and switch ref…`, and `Pull`. Selecting a ref reuses its worktree if it has one; selecting the default branch returns to the project folder. `Create worktree…` asks for a new branch name and moves this thread there. `Remove worktree…` asks first, then removes the worktree only if no other thread uses it and Git allows it (it never forces). Moving the thread to another folder detaches its provider session. + +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. + +## 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`: + +- **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`. + +While the terminal is focused, alerts for other threads also show on the bottom line (`inAppNotificationsEnabled`). + +## 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`: + +| Setting | Choices | Default | +| --- | --- | --- | +| `followUpBehavior` | `steer` or `queue`: what `enter` does while the agent runs (`alt+enter` does the other) | `steer` | +| `sendShortcut` | `enter`, or `ctrl-enter` (then `enter` adds a line; needs the kitty keyboard protocol, and `alt+enter` also sends) | `enter` | +| `timestampFormat` | `locale`, `12-hour`, `24-hour` | `locale` | +| `diffIgnoreWhitespace` | `true`, `false` | `true` | +| `notificationMode` | `off`, `sound` (bell), `notifications` (desktop), `notifications-and-sound` | `sound` | +| `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. + +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. diff --git a/scripts/demo-capture.tsx b/scripts/demo-capture.tsx new file mode 100644 index 0000000..ee8c1fa --- /dev/null +++ b/scripts/demo-capture.tsx @@ -0,0 +1,394 @@ +/** + * Renders the whole app against invented demo data (the interaction-test + * harness's fake session) and writes the settled frame as an HTML fragment + * for the landing page: dark, dark in a standalone page, and light. + * + * Run with `bun run scripts/demo-capture.tsx`. + */ +import { mkdir, writeFile } from "node:fs/promises"; +import { join } from "node:path"; + +import { type CapturedFrame, type RGBA, TextAttributes } from "@opentui/core"; +import type { OrchestrationV2ShellSnapshot, OrchestrationV2ThreadProjection } from "@t3tools/contracts"; +import * as DateTime from "effect/DateTime"; +import { applyTheme, colors } from "../src/ui/theme.ts"; +import { fakeSession, renderApp } from "../test/app/harness.tsx"; +import { v2Project, v2Projection, v2ThreadShell } from "../vendor/t3code/packages/client-runtime/src/state/orchestrationV2TestFixtures.ts"; + +/** Where the HTML goes: DEMO_OUT, or dist/demo. */ +const OUT_DIR = process.env.DEMO_OUT ?? join(import.meta.dir, "../dist/demo"); + +const NOW = Date.now(); +const MIN = 60_000; +const HOUR = 60 * MIN; +const DAY = 24 * HOUR; +/** A DateTime `ms` before the capture, so every relative time reads naturally. */ +const ago = (ms: number) => DateTime.makeUnsafe(NOW - ms); + +// --- The demo shell: 3 projects, 8 threads --------------------------------- + +const project = (id: string, title: string, workspaceRoot: string) => ({ ...v2Project, id, title, workspaceRoot }); + +const OPEN_THREAD = "thread-bundle"; +const APPROVAL_ID = "approval-1"; + +const thread = (extra: Record) => ({ + ...v2ThreadShell, + status: "completed", + activeRunId: null, + latestRunId: "run-1", + latestRunRequestedAt: ago(3 * HOUR), + latestRunStartedAt: ago(3 * HOUR), + latestRunCompletedAt: ago(3 * HOUR), + pendingRuntimeRequest: null, + pinnedAt: null, + lastVisitedAt: ago(2 * HOUR), + ...extra, +}); + +const snapshot = { + schemaVersion: 1, + snapshotSequence: 0, + projects: [ + project("project-tui3", "tui3", "/home/dev/projects/tui3"), + project("project-acme", "acme-api", "/home/dev/projects/acme-api"), + project("project-dotfiles", "dotfiles", "/home/dev/dotfiles"), + ], + threads: [ + // The open thread: pinned, running, and waiting on a command approval. + thread({ + id: OPEN_THREAD, + projectId: "project-tui3", + title: "Bundle into dist/", + runtimeMode: "approval-required", + status: "running", + latestRunId: "run-2", + activeRunId: "run-2", + latestRunRequestedAt: ago(3 * MIN), + latestRunStartedAt: ago(3 * MIN), + latestRunCompletedAt: null, + activityRunStartedAt: ago(3 * MIN), + pendingRuntimeRequest: { id: APPROVAL_ID, kind: "command", createdAt: ago(40_000) }, + latestUserMessageAt: ago(3 * MIN), + pinnedAt: ago(2 * DAY), + pinOrderKey: "a", + createdAt: ago(2 * DAY), + updatedAt: ago(40_000), + }), + // Working, six minutes in. + thread({ + id: "thread-flaky", + projectId: "project-acme", + title: "Fix flaky auth test", + modelSelection: { instanceId: "claude", model: "claude-sonnet-5" }, + status: "running", + latestRunId: "run-flaky", + activeRunId: "run-flaky", + latestRunRequestedAt: ago(6 * MIN), + latestRunStartedAt: ago(6 * MIN), + latestRunCompletedAt: null, + activityRunStartedAt: ago(6 * MIN), + latestUserMessageAt: ago(6 * MIN), + createdAt: ago(5 * HOUR), + updatedAt: ago(20_000), + }), + // Waiting for an answer. + thread({ + id: "thread-resize", + projectId: "project-tui3", + title: "Resize the thread list", + status: "running", + latestRunId: "run-resize", + activeRunId: "run-resize", + latestRunRequestedAt: ago(12 * MIN), + latestRunStartedAt: ago(12 * MIN), + latestRunCompletedAt: null, + pendingRuntimeRequest: { id: "question-1", kind: "user_input", createdAt: ago(9 * MIN) }, + latestUserMessageAt: ago(12 * MIN), + createdAt: ago(DAY), + updatedAt: ago(9 * MIN), + }), + // Finished while you were looking elsewhere. + thread({ + id: "thread-rate-limit", + projectId: "project-acme", + title: "Add rate-limit headers", + latestRunRequestedAt: ago(40 * MIN), + latestRunStartedAt: ago(40 * MIN), + latestRunCompletedAt: ago(18 * MIN), + latestUserMessageAt: ago(40 * MIN), + lastVisitedAt: ago(2 * HOUR), + createdAt: ago(DAY), + updatedAt: ago(18 * MIN), + }), + thread({ + id: "thread-sighup", + projectId: "project-dotfiles", + title: "Exit on SIGHUP", + latestRunRequestedAt: ago(HOUR), + latestRunStartedAt: ago(HOUR), + latestRunCompletedAt: ago(47 * MIN), + latestUserMessageAt: ago(HOUR), + lastVisitedAt: ago(3 * HOUR), + createdAt: ago(2 * DAY), + updatedAt: ago(47 * MIN), + }), + // Idle and read. + thread({ + id: "thread-tmux", + projectId: "project-tui3", + title: "Add tmux mirror", + latestRunRequestedAt: ago(3 * HOUR + 10 * MIN), + latestRunStartedAt: ago(3 * HOUR + 10 * MIN), + latestRunCompletedAt: ago(3 * HOUR), + latestUserMessageAt: ago(3 * HOUR + 10 * MIN), + lastVisitedAt: ago(2 * HOUR + 50 * MIN), + createdAt: ago(3 * DAY), + updatedAt: ago(3 * HOUR), + }), + thread({ + id: "thread-aliases", + projectId: "project-dotfiles", + title: "Tidy shell aliases", + latestRunRequestedAt: ago(3 * DAY), + latestRunStartedAt: ago(3 * DAY), + latestRunCompletedAt: ago(3 * DAY), + latestUserMessageAt: ago(3 * DAY), + lastVisitedAt: ago(3 * DAY - HOUR), + createdAt: ago(6 * DAY), + updatedAt: ago(3 * DAY), + }), + // Put away: the Settled section folds to a count at the bottom of the list. + thread({ + id: "thread-deps", + projectId: "project-acme", + title: "Bump dependencies", + settledOverride: "settled", + settledAt: ago(DAY), + latestRunRequestedAt: ago(2 * DAY), + latestRunStartedAt: ago(2 * DAY), + latestRunCompletedAt: ago(2 * DAY), + latestUserMessageAt: ago(2 * DAY), + lastVisitedAt: ago(DAY), + createdAt: ago(4 * DAY), + updatedAt: ago(DAY), + }), + ], + archivedThreads: [], +} as unknown as OrchestrationV2ShellSnapshot; + +// --- The open thread's conversation ----------------------------------------- + +const USER_1 = "Bundle the CLI into dist/ so it can run without the repo checkout. Keep the vendor link step on postinstall."; +const ASSISTANT_1 = [ + "Done — the bundle step is **self-contained** now:", + "", + "- `scripts/build.ts` bundles `src/bin.ts` into `dist/`", + "- the vendor symlink is created on `postinstall`", + "- `bun run build` passes typecheck and the test suite", + "", + "Say the word and I'll cut a clean rebuild.", +].join("\n"); +const USER_2 = "Now rebuild dist/ from scratch and check the bundled binary starts."; + +const run = (id: string, ordinal: number, userMessageId: string, status: string, requestedMsAgo: number, completedMsAgo: number | null) => ({ + id, + threadId: OPEN_THREAD, + ordinal, + providerInstanceId: "codex", + modelSelection: { instanceId: "codex", model: "gpt-5.4" }, + providerThreadId: null, + userMessageId, + rootNodeId: null, + activeAttemptId: null, + status, + requestedAt: ago(requestedMsAgo), + startedAt: ago(requestedMsAgo), + completedAt: completedMsAgo === null ? null : ago(completedMsAgo), + checkpointId: null, + contextHandoffId: null, +}); + +let ordinal = 0; +const item = (runId: string, startMsAgo: number, work: Record, status = "completed", spanMs = 5_000) => ({ + id: `item-${ordinal}`, + threadId: OPEN_THREAD, + runId, + nodeId: null, + providerThreadId: null, + providerTurnId: null, + nativeItemRef: null, + parentItemId: null, + ordinal: ordinal++, + status, + title: null, + startedAt: ago(startMsAgo), + completedAt: status === "completed" ? ago(startMsAgo - spanMs) : null, + updatedAt: status === "completed" ? ago(startMsAgo - spanMs) : ago(startMsAgo), + ...work, +}); + +const turnItems = [ + item("run-1", 26 * MIN, { type: "user_message", createdBy: "user", creationSource: "web", messageId: "msg-user-1", inputIntent: "turn_start", text: USER_1, attachments: [] }, "completed", 0), + item("run-1", 25 * MIN + 50_000, { type: "reasoning", text: "The build needs to inline the vendored packages and keep the symlink step for local development.", streaming: false }), + item("run-1", 25 * MIN + 20_000, { type: "file_search", pattern: "Bun.build", results: [{ fileName: "scripts/build.ts" }, { fileName: "package.json" }] }), + item("run-1", 24 * MIN + 40_000, { type: "file_change", fileName: "scripts/build.ts", additions: 42, deletions: 6 }), + item("run-1", 24 * MIN, { type: "command_execution", input: "bun run typecheck", output: "tsc --noEmit\n(no errors)", exitCode: 0 }, "completed", 20_000), + item("run-1", 23 * MIN + 20_000, { type: "command_execution", input: "bun test", output: "128 pass\n0 fail\n412 expect() calls", exitCode: 0 }, "completed", 30_000), + // 3m 12s after the first user message: the turn folds to "Worked for 3m 12s". + item("run-1", 22 * MIN + 48_000, { type: "assistant_message", messageId: "msg-assistant-1", text: ASSISTANT_1, streaming: false }, "completed", 0), + item("run-2", 3 * MIN, { type: "user_message", createdBy: "user", creationSource: "web", messageId: "msg-user-2", inputIntent: "turn_start", text: USER_2, attachments: [] }, "completed", 0), + item("run-2", 2 * MIN + 50_000, { type: "reasoning", text: "A clean rebuild means removing dist/ first, then re-running the bundle and smoke-testing the binary.", streaming: false }), + item("run-2", 2 * MIN + 30_000, { type: "command_execution", input: "git status --porcelain", output: " M scripts/build.ts\n M package.json", exitCode: 0 }, "completed", 3_000), + item("run-2", 40_000, { type: "approval_request", requestId: APPROVAL_ID, requestKind: "command", prompt: "rm -rf dist && bun run scripts/build.ts", reason: "Deletes dist/ and rebuilds it from a clean tree." }, "waiting", 0), +]; + +const message = (id: string, runId: string, role: string, text: string, atMsAgo: number) => ({ + createdBy: "user", + creationSource: "web", + id, + threadId: OPEN_THREAD, + runId, + nodeId: null, + role, + text, + attachments: [], + streaming: false, + createdAt: ago(atMsAgo), + updatedAt: ago(atMsAgo), +}); + +const projection = { + ...v2Projection, + thread: { + ...v2Projection.thread, + id: OPEN_THREAD, + projectId: "project-tui3", + title: "Bundle into dist/", + runtimeMode: "approval-required", + createdAt: ago(2 * DAY), + updatedAt: ago(40_000), + }, + runs: [run("run-1", 1, "msg-user-1", "completed", 26 * MIN, 22 * MIN + 48_000), run("run-2", 2, "msg-user-2", "running", 3 * MIN, null)], + runtimeRequests: [ + { id: APPROVAL_ID, nodeId: "node-1", providerTurnId: null, nativeRequestRef: null, kind: "command", status: "pending", responseCapability: { type: "live", providerSessionId: "session-1" }, createdAt: ago(40_000), resolvedAt: null }, + ], + messages: [ + message("msg-user-1", "run-1", "user", USER_1, 26 * MIN), + message("msg-assistant-1", "run-1", "assistant", ASSISTANT_1, 22 * MIN + 48_000), + message("msg-user-2", "run-2", "user", USER_2, 3 * MIN), + ], + turnItems, + visibleTurnItems: turnItems.map((entry, position) => ({ position, visibility: "local", sourceThreadId: OPEN_THREAD, sourceItemId: entry.id, item: entry })), + updatedAt: ago(40_000), +} as unknown as OrchestrationV2ThreadProjection; + +// --- Captured frame -> HTML --------------------------------------------------- + +function hex(color: RGBA): string { + const [r, g, b] = color.toInts(); + return `#${[r, g, b].map((value) => Math.max(0, Math.min(255, value)).toString(16).padStart(2, "0")).join("")}`; +} + +function escapeHtml(text: string): string { + return text.replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">").replaceAll('"', """); +} + +interface StyledSpan { + readonly text: string; + readonly style: string; +} + +/** One frame as a `
`, one line per row, styled spans merged. */
+function frameToHtml(frame: CapturedFrame, baseBg: string): string {
+  const lines = frame.lines.map((line) => {
+    const styled: StyledSpan[] = [];
+    for (const span of line.spans) {
+      if (!span.text) continue;
+      const attrs = span.attributes & 0xff;
+      const inverse = (attrs & TextAttributes.INVERSE) !== 0;
+      const fg = hex(inverse ? span.bg : span.fg);
+      const bg = hex(inverse ? span.fg : span.bg);
+      const declarations = [`color:${fg}`];
+      if (bg !== baseBg) declarations.push(`background:${bg}`);
+      if ((attrs & TextAttributes.BOLD) !== 0) declarations.push("font-weight:bold");
+      if ((attrs & TextAttributes.ITALIC) !== 0) declarations.push("font-style:italic");
+      const decorations = [
+        (attrs & TextAttributes.UNDERLINE) !== 0 ? "underline" : "",
+        (attrs & TextAttributes.STRIKETHROUGH) !== 0 ? "line-through" : "",
+      ].filter(Boolean);
+      if (decorations.length > 0) declarations.push(`text-decoration:${decorations.join(" ")}`);
+      if ((attrs & TextAttributes.DIM) !== 0) declarations.push("opacity:.65");
+      const style = declarations.join(";");
+      const last = styled.at(-1);
+      if (last && last.style === style) styled[styled.length - 1] = { text: last.text + span.text, style };
+      else styled.push({ text: span.text, style });
+    }
+    // Trailing blank spans in the base colour add nothing over the pre's background.
+    while (styled.length > 0) {
+      const last = styled.at(-1)!;
+      if (last.text.trim() !== "" || last.style.includes("background:")) break;
+      styled.pop();
+    }
+    return styled.map((span) => `${escapeHtml(span.text)}`).join("");
+  });
+  return `
${lines.join("\n")}\n
\n`; +} + +function standalonePage(fragment: string, pageBg: string): string { + return ` + + + +tui3 — demo screen + + + +${fragment} + +`; +} + +// --- Render both themes --------------------------------------------------------- + +async function capture(mode: "dark" | "light"): Promise<{ frame: CapturedFrame; chars: string; baseBg: string }> { + applyTheme(mode); + const app = await renderApp({ + session: fakeSession({ snapshot, projection }), + width: 140, + height: 34, + }); + try { + // A running run ticks a spinner and a duration, so settle() gives up after + // its retries; one more short wait lands on whatever frame is current. + await app.settle(120); + await app.renderOnce(); + return { frame: app.captureSpans(), chars: app.frame(), baseBg: colors.bg }; + } finally { + app.destroy(); + } +} + +await mkdir(OUT_DIR, { recursive: true }); + +const dark = await capture("dark"); +console.log(dark.chars); +const darkFragment = frameToHtml(dark.frame, dark.baseBg); +await writeFile(join(OUT_DIR, "demo-screen.html"), darkFragment); +await writeFile(join(OUT_DIR, "demo-screen-page.html"), standalonePage(darkFragment, "#161616")); + +const light = await capture("light"); +const lightFragment = frameToHtml(light.frame, light.baseBg); +await writeFile(join(OUT_DIR, "demo-screen-light.html"), lightFragment); +await writeFile(join(OUT_DIR, "demo-screen-light-page.html"), standalonePage(lightFragment, "#e8e8e8")); + +console.log(`wrote ${join(OUT_DIR, "demo-screen.html")}`); +console.log(`wrote ${join(OUT_DIR, "demo-screen-page.html")}`); +console.log(`wrote ${join(OUT_DIR, "demo-screen-light.html")}`); +process.exit(0);