SLOPSHOPPER

Turbo-MOD

A side pane for Claude Code with collapsible widgets: files Claude wrote, terminal splits, the state of your git repos and a TODO list, in retro colors.

paneguardcommandtoastprocesstimer
v0.16.0Apache-2.0updated 2026-10-17michaelblaess/turbo-mod
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · turbo-mod
│ ┃ turbo-mod ✕ › fix the failing auth test and add an audit log call │ ┃ ♞ Turbo-MOD v0.16.0 · https://www.michaelbl… │ ┃ Theme ◂ standard ▸ · [EN] · https://github.c ⏺ Read(src/auth.ts) │ ┃ ⎿ Read 6 lines │ ┃ ╭──────────────────────────────────────────╮ ⏺ Update(src/auth.ts) │ ┃ │ Disclaimer │ ⎿ Added 2 lines, removed 1 line │ ┃ │ Turbo-MOD starts programs on your │ ⏺ Bash(bun test) │ ┃ │ machine, runs git fetch and git pull in │ ⎿ 3 pass, 1 fail │ ┃ │ your repos when you press the buttons, │ │ ┃ │ and can start a command you have set. │ ● Done. refresh now rejects expired claims and logs an audit event. │ ┃ │ You use the mod at your own risk and │ │ ┃ │ without warranty, see the license │ ✻ Worked for 42s · done 4:20 PM │ ┃ │ (Apache 2.0). │ │ ┃ │ [Understood] │ › /turbo │ ┃ ╰──────────────────────────────────────────╯ ⎿ turbo-mod: Turbo-MOD hidden. /turbo shows it again. │ ┃ ───────────────────────────────────────────… │ ┃ ▾ Files 1 file · 193 B │ ┃ 1 ~ file:///work/app/src/auth.ts │ ┃ file:///work/app/src │ ┃ 193 B · 10-09 08:52:20 │ ┃ [open] [path] [content] │ ┃ [clear list] │ ┃ ───────────────────────────────────────────… │ ┃ ▾ Terminal │ ┃ Ghostty found. It cannot be split from │ ┃ outside, start Claude in tmux inside it. ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Pane · turbo-mod
♞ Turbo-MOD v0.16.0 · https://www.michaelblaess.de · Open S… Theme ◂ standard ▸ · [EN] · https://github.com/michaelblaess ╭──────────────────────────────────────────────────────────╮ │ Disclaimer │ │ Turbo-MOD starts programs on your machine, runs git │ │ fetch and git pull in your repos when you press the │ │ buttons, and can start a command you have set. You use │ │ the mod at your own risk and without warranty, see the │ │ license (Apache 2.0). │ │ [Understood] │ ╰──────────────────────────────────────────────────────────╯ ─────────────────────────────────────────────────────── ▾ Files 1 file · 193 B 1 ~ file:///work/app/src/auth.ts file:///work/app/src 193 B · 10-09 08:52:20 [open] [path] [content] [clear list] ─────────────────────────────────────────────────────── ▾ Terminal Ghostty found. It cannot be split from outside, start Claude in tmux inside it. ─────────────────────────────────────────────────────── ▸ Repos ─────────────────────────────────────────────────────── ▸ TODO ─────────────────────────────────────────────────────── ▾ Claude · https://www.michaelblaess.de/helfer/claude-code.h Current session ██████████████████████████████████████████████ 31 % Context ██████████████████████████████████████████████ 49 % 97k of 200k · Cost $0.42 [refresh] 08:53 [/compact] [/clear]
README

turbo-mod

<img src="docs/flags/gb.svg" height="13" alt=""> <b>English</b> · <img src="docs/flags/de.svg" height="13" alt=""> <a href="README.de.md">Deutsch</a>


A side pane for Claude Code. It sits to the right of the conversation and shows what you otherwise keep asking for:

  • Files - every file Claude wrote in this session, with buttons to open or copy it
  • Terminal - split the window or open a new tab, in the folder you are working in
  • Repos - which of your git repos have uncommitted changes or unpushed commits, with a pull button next to each
  • Claude - how much of your limits is used, when they reset and how full the context is
  • New tickets - optional, off by default: new tickets from your ticket system. Needs a second program on your machine, for Jira that is jira-timesheet
  • TODO - a plain list for ideas and reminders. It is kept as a Markdown file on your machine

It comes with 41 retro color schemes, speaks English and German, and plays a small text effect in its title.

<img src="docs/screenshots/pane-lenseflare-en.png" width="520" alt="The Turbo-MOD pane with sample data, color scheme lenseflare">

The pictures show made-up sample data, switched on with /turbo demo.

Everything in square brackets is a button, and so are the single arrows and the cross.

turbo-mod is a mod: a Claude Code plugin that draws its own surface. The mod interface of Claude Code is early access and may change between releases. turbo-mod was built and tested with Claude Code 2.1.291.

What you need

  • Claude Code in a terminal. The install command below does not work in the desktop app.
  • git, for the Repos widget.
  • For the Terminal widget, the editor button and [>_]: Windows Terminal on Windows, or tmux or kitty on Linux and macOS. Without one of them the rest of the pane still works.

kitty: it only takes commands from outside with remote control switched on. Put these lines into ~/.config/kitty/kitty.conf and restart kitty, a reload is not enough for listen_on:

allow_remote_control socket-only
listen_on unix:@kitty-{kitty_pid}
enabled_layouts splits,stack

Without the layout splits kitty still opens the new window, but places it by its own layout and not in the direction of the arrow. Other terminals such as Ghostty or the Xfce terminal have no command to split a window from outside. Start Claude in tmux inside them.

Git Bash on Windows: start it as a profile inside Windows Terminal. In the standalone Git Bash window (mintty) Claude Code does not start interactively and ends with Input must be provided either through stdin or as a prompt argument. That is a limit of that window, not of the mod.

Install

  1. Start Claude Code in a terminal:
   claude
  1. Type this line at the prompt and press Enter:
   /plugin install turbo-mod --marketplace michaelblaess/turbo-mod
  1. Claude Code asks three things:
  2. Add marketplace? - answer y. This only tells Claude Code where to fetch the mod from.
  3. The scope - press Enter for user. The mod then loads in every session you start.
  4. The options (theme, repo folder, language and so on) - press Enter to keep the defaults. You can change all of them later inside the pane or with /turbo.

You then see Installed turbo-mod. Plugin is now active. and the pane appears on the right. No restart is needed.

The pane does not show up? It opens by itself only when the terminal is at least 144 columns wide. In a narrower window, type /turbo.

First steps

  • On the very first start the pane shows a short disclaimer in a frame. Click [Understood] once. Until then [pull], [fetch all] and the ticket command stay locked, everything else works. The answer is remembered on this machine.
  • Ask Claude to write a file. It shows up under Files, newest on top.
  • Click the arrow in front of a heading to fold a widget away.
  • Click the arrows next to Theme below the title to try the color schemes.
  • Click [EN] next to it to switch the pane to German, and again to switch back.
  • Open Repos and click [choose folder] to pick the folder your git repos live in. [add folder] adds a second one, for example one for work and one for your own projects.

The widgets

Files

Every file Claude wrote through Write, Edit or NotebookEdit, newest on top. Files a shell command created or changed in a git repo are listed as well:

  • a running number, in the order the files were first written
  • + for a new file, ~ for a changed one, - for a deleted one
  • a deleted file stays in the list, struck through. Only its [path] button remains.
  • the file name and its folder as links
  • size, time of the last write and how often it was written
  • a button with the name of your editor ([nvim] by default) that opens the file in a new split. The button only appears when the editor was found on your machine.
  • [open] opens the file with the default application of your system
  • [path] puts the path of the file on the clipboard, [content] its whole text. Handy for a draft you want to paste somewhere else.

When the list is longer than its room in the pane, a row with two arrows and the range (◂ 6-10 of 11 ▸) pages through it. After the last page the first one follows. A new write takes the list back to page one, because the file just written is on top.

Terminal

One row with the three splits, each an arrow in the direction the new pane opens, and one row with [New tab] and [Close last pane]. Everything starts in the working folder of the session. [Close last pane] asks once: the button turns into [Really close?] and only closes on a second click within five seconds. Under Windows Terminal the heading carries a link to a cheat sheet for its shortcuts.

Repos

The state of all git repos directly below one or more folders. Only repos that need attention are listed. Behind the name is what is open:

SignMeaning
~3three changed files git already knows
?1one new file git does not know yet
↑1one commit you have not pushed
↓2two commits you do not have yet (as of your last fetch)

The widget starts folded and reads when you open it, then every two minutes while it stays open.

  • [pull] next to a repo runs git pull --ff-only there, which fetches first. It only ever fast-forwards: no merge commit, no rebase. If that is not possible, git's reason is shown and nothing is changed. A pull only clears ↓. A repo with ~ or ? stays in the list afterwards, because your own changes are still there.
  • [>_] opens a terminal split in the folder of that repo.
  • [fetch all] runs git fetch in every repo and reads again. Use it to see which repos are behind, since reading alone never contacts a server.
  • [add folder] adds another folder, the × in front of a folder removes it from the list. With more than one folder, the repos are grouped by folder.
  • With a ticket address set, a ticket key in a branch name (ABC-123 in feature/ABC-123-fix) becomes a link to that ticket. Set it once with /turbo ticket https://jira.example.com/browse/{id}.

Claude

What Claude Code measures for the running session, drawn as bars like /usage does: each rate-limit window with the share used and the time it resets, then the context window with the cost so far. A bar is green, yellow from 80 % and red from 95 %.

The figures arrive after every answer and once a minute while the widget is open, [refresh] reads them right away. The pane never asks a server for them: Claude Code learns the limits from its last answer, so use in another session shows up only after the next answer in this one. The heading carries a link to a Claude Code cheat sheet.

Next to [refresh] are [/compact] and [/clear]. They do what the commands of the same name do: summarize the conversation to free context, or start a fresh one. Both change the conversation for good, so the button turns into [Really?] and only runs on a second click within five seconds.

New tickets (optional)

Needs a second program that is installed on your machine. The mod never talks to a ticket system itself and knows no credentials. For Jira that program is jira-timesheet, version 1.25.0 or newer. Without it, or a command of your own that does the same, the widget stays off.

With jira-timesheet installed and set up, switch the widget on:

/turbo feed jira-timesheet --new-tickets-json

If jira-timesheet is not on the PATH, give the full path. A path with blanks goes in double quotes. /turbo feed off switches the widget off again.

The mod runs the command when you open the widget, on [refresh] and every ten minutes while it is open, and lists what comes back: the ticket key as a link, the title behind it, eight tickets at most.

Another ticket system: any command works that prints one JSON object in this form. Name it with /turbo feed <command>. Only key is required per ticket, other fields are ignored:

{
  "since": "2026-10-07",
  "tickets": [{ "key": "ABC-123", "summary": "Counter overflows", "url": "https://jira.example.com/browse/ABC-123" }]
}

A message in that object is shown instead of the list, for example when the command could not reach the server.

TODO

A plain list for ideas and for things you do not want to forget.

  • + shows a text field. Enter saves the task, [cancel] drops it.
  • [ ] ticks a task off, done ones are struck through at the bottom.
  • A double click on the text brings it back into the field for editing.
  • ✕ removes the task after asking once.
  • [remove N done] clears everything that is ticked off, after asking once as well.
  • /turbo todo <text> adds a task without touching the pane.

While the list is empty the section stays collapsed. Its head shows the number of open tasks even then.

The pane cuts a long task with three dots, the text field holds the whole text. A done task can only be edited once its tick is removed. The cursor jumps into the text field by itself only while your prompt is empty.

The tasks are kept in a Markdown file on your machine, by default ~/.claude/turbo-mod-todo.md. You can edit it in any editor:

- [ ] Write the release notes
- [ ] Idea: a dark variant of the logo
- [x] Tidy up the old branches

Lines that are no task stay as they are. /turbo todo file <path> moves the list somewhere else. A folder inside a git repo is refused, so the tasks never end up in a history.

Commands

CommandWhat it does
/turboshow or hide the pane
/turbo theme <name>pick a color scheme, without a name you get the list
/turbo repos <path>add a repo folder on this machine, without a path: refresh
/turbo repos remove <path>remove a repo folder from the list
/turbo ticket <address>ticket address with {id}, without an address: show it
/turbo feed <command>switch on the widget New tickets, off switches it off
/turbo todo <text>add a task to the TODO list, without text: count the open ones
/turbo todo file <path>set the file of the TODO list, without path: show it
`/turbo lang <de\en>`language of the pane and of the answers
/turbo clearreset the list of files, numbering starts again at 1
/turbo effectswitch the title effect off or on
/turbo demoshow or hide made-up sample data, for a screenshot that shows nothing of your work

Everything you set this way is remembered per machine and survives a restart. The close mark of the pane or ctrl+x x hides it as well.

Color schemes

41 retro schemes, taken from textual-themes, for example brotkasten, boing, synthwave, lenseflare and christophorus. standard follows the theme you set in Claude Code.

Three of them:

<img src="docs/screenshots/pane-christophorus-en.png" width="24%" alt="The pane in the color scheme christophorus"> <img src="docs/screenshots/pane-brotkasten-en.png" width="24%" alt="The pane in the color scheme brotkasten"> <img src="docs/screenshots/pane-cupertino-en.png" width="24%" alt="The pane in the color scheme cupertino">

Settings

Under /config, or in ~/.claude/settings.json under pluginConfigs["turbo-mod"].options. A value set in the pane or with /turbo on a machine takes precedence there.

FieldDefaultMeaning
themestandardcolor scheme
reposRootemptyrepo folder, several separated by ;
languageenlanguage of the pane, en or de
ticketUrlemptyticket address with {id}
ticketFeedemptycommand for the widget New tickets
editornvimprogram behind the editor button, a name or a full path

Without a folder from the pane or from reposRoot, the environment variable TURBO_MOD_REPOS is used.

Update and uninstall

claude plugin update turbo-mod
claude plugin uninstall turbo-mod

After an update, type /reload-plugins in a running session.

What the mod runs, writes and sends

Turbo-MOD draws a pane and starts programs on your machine. It makes no network request of its own and sends nothing to a server of mine.

Programs it starts

  • git, read-only, for the repo list and the file list: status, rev-parse and diff. This runs on a timer and after every shell command of the session.
  • git fetch and git pull --ff-only, only when you press [fetch all] or [pull]. These two talk to your git remote.
  • Your terminal, for the split buttons: wt.exe on Windows Terminal, tmux, or kitty @. On Windows, [Close last pane] runs a short PowerShell script.
  • The editor you set, when you press the editor button of a file.
  • explorer.exe, open or xdg-open, when you open a file with its default application.
  • The clipboard: PowerShell Set-Clipboard on Windows, pbcopy on macOS, wl-copy or xclip on Linux.
  • A folder dialog when you pick a repo folder: PowerShell on Windows, osascript on macOS, zenity on Linux.
  • The command you set with /turbo feed, exactly as you typed it. The mod reads its output as JSON. Without that setting nothing runs. What this command does is up to you.

What it reads

  • The file paths from the tool calls of the session, to list the files Claude wrote.
  • Context size and plan limits as Claude Code reports them.
  • A few environment variables to find your terminal and home folder, such as WT_SESSION, TMUX, KITTY_WINDOW_ID and HOME.

What it writes

  • One file: the TODO list, by default ~/.claude/turbo-mod-todo.md.
  • Its settings, in the store Claude Code gives every mod.

Slash commands it runs

  • /compact and /clear, each only after you press its button twice within five seconds.

The links in the header point to this repo and to michaelblaess.de. Your terminal opens them when you click, the mod does not load them.

Limits

  • Files from a shell command (a redirect, a copy, a script) are found through git. After every command the mod asks for the state of the repo the session runs in, including a new commit. Outside a git repo, and in a repo other than the one of the session, it does not see them.
  • A file git ignores does not show up after a shell command.
  • A command that changes more than 25 files counts as a pull, a checkout or an install and is not listed.
  • A shell command that deletes a file is only noticed if the file was already in the list or the deletion was committed.
  • Whether a listed file still exists is checked every 15 seconds and after every shell command.
  • The desktop app gets no file: links, the path is shown as text there.
  • Windows Terminal has no command to close a pane and none to split to the left. The split to the left therefore splits to the right and swaps the two panes. [Close last pane] moves the focus to the pane that was active before and then sends Ctrl+Shift+W to the window in the foreground. If there is no other pane, that closes the tab Claude runs in.
  • Other terminals (WezTerm, GNOME Terminal, Ghostty) are not supported for splitting.
  • The folder dialog needs zenity on Linux, the clipboard buttons wl-copy or xclip.
  • [content] is meant for text files.
  • Windows Terminal opens links only with Ctrl held down. The buttons react to a plain click.
  • A button cannot take a color, it is drawn in the text color of your terminal. On light schemes the buttons therefore sit on a dark patch. With a light terminal and a dark scheme a button can be hard to read.
  • Reading the repos never contacts a server. "Ahead" and "behind" reflect your last fetch, only [pull] and [fetch all] talk to the server. Both wait at most a minute per repo.
  • At most 80 folders below each repo folder are read.

For developers

Clone the repo and load the mod from the folder. Claude Code watches the folder and reloads the mod when you save a file.

git clone https://github.com/michaelblaess/turbo-mod
claude --plugin-dir turbo-mod

To load it in every session, put the absolute path of the clone into the environment variable CLAUDE_CODE_PLUGIN_DIRS. A terminal that was already open keeps the old value, so restart it.

On load, Claude Code writes the types of the mod interface to .claude-plugin/types/ (ignored by git). With them in place:

npm install        # once: Biome and TypeScript, only for development
npm run check      # Biome, tsc, claude plugin validate, claude plugin test
npm run format     # let Biome fix formatting and what it can fix safely

Biome lints and formats hooks/ and types/, the generated hooks/palettes.ts is left out. package-lock.json is not committed, it depends on the registry of the machine.

Texts live in hooks/texts.ts, one block per language. The palettes in hooks/palettes.ts are a snapshot written by tools/snapshot_palettes.py. What is planned and what was decided is in PLAN.md (German).

License

Apache License 2.0 - (c) 2026 Michael Blaess

Source 12 files
hooks/register.tsx 1818 lines
1import type { EngineInterface, PluginOptions, Register } from 'claude-code'
2import { atom, read, update } from 'claude-code'
3
4import type { FeedState, FileEntry, HostInfo, RepoEntry, ReposState, TodoItem, TodoState, UsageState } from '../types'
5import { demoState } from './demo'
6import type { EffectName } from './effects'
7import { EFFECTS, effectFrame } from './effects'
8import { parseFeed } from './feed'
9import {
10  barCells,
11  dotsFor,
12  fileHref,
13  formatClock,
14  formatDay,
15  formatReset,
16  formatSize,
17  formatStamp,
18  formatTokens,
19  formatUsd,
20  shortenDir,
21  splitPath,
22  ticketHref,
23  ticketOf,
24  workingLabel,
25} from './format'
26import type { ChangeEntry } from './git'
27import {
28  CHANGES_ARGV,
29  diffArgv,
30  FETCH_ARGV,
31  isClean,
32  PULL_ARGV,
33  parseChanges,
34  parseDiff,
35  parseStatus,
36  pathKey,
37  repoCounts,
38  repoPath,
39  STATUS_ARGV,
40  sortRepos,
41  TOP_HEAD_ARGV,
42} from './git'
43import {
44  CHEAT_SHEET,
45  CLAUDE_SHEET,
46  copyFileArgv,
47  copyTextArgv,
48  detectHost,
49  isPath,
50  joinPath,
51  openDefaultArgv,
52  openEditorArgv,
53  pickFolderArgv,
54  splitCommand,
55  splitRoots,
56  terminalActions,
57  whereArgv,
58} from './platform'
59import type { Lang } from './texts'
60import { findLanguage, LANGUAGES, textsFor } from './texts'
61import { findTheme, lookFor, STANDARD, themeNames } from './theme'
62import { addTodo, changeTodo, clearDoneTodos, fitTodoText, parseTodos, sortTodos, todoPathIn } from './todo'
63
64// Must match the version in .claude-plugin/plugin.json
65const VERSION = '0.16.0'
66
67const PANE = 'turbo-mod'
68const PANE_TITLE = 'Turbo-MOD'
69const COMMAND = 'turbo'
70// U+265E is the knight from the chess symbols
71const TITLE = '♞ Turbo-MOD'
72const AUTHOR = '(c) 2026 Michael Blaess'
73const AUTHOR_URL = 'https://www.michaelblaess.de'
74const TAGLINE = ' · Open Source @ 16 MHz'
75const REPO_URL = 'https://github.com/michaelblaess/turbo-mod'
76// Share of the terminal width the pane gets (Claude 80 %, pane 20 %)
77const SHARE = 0.2
78const MIN_COLUMNS = 30
79const MAX_FILES = 200
80const MAX_REPOS = 80
81// Tools that write a file and carry its path in the call
82const WRITERS = ['Write', 'Edit', 'MultiEdit', 'NotebookEdit']
83// A shell changes files without naming them in the call, git tells afterwards which ones
84const SHELLS = ['Bash', 'PowerShell']
85// More files than this from one call is a pull, a checkout or an install, nothing to list
86const MAX_SHELL_FILES = 25
87// A repo with more changed files than this is not looked through after every call
88const MAX_SHELL_CANDIDATES = 400
89const FILES_EVERY_MS = 15000
90const TITLE_FRAMES = 14
91const TITLE_FRAME_MS = 70
92// One second of rest between two runs
93const TITLE_PAUSE_TICKS = Math.round(1000 / TITLE_FRAME_MS)
94const REPOS_EVERY_MS = 120000
95const PULSE_EVERY_MS = 350
96const USAGE_EVERY_MS = 60000
97// The feed asks a ticket system, so it runs rarely
98const FEED_EVERY_MS = 600000
99const FEED_TIMEOUT_MS = 30000
100const MAX_FEED_ROWS = 8
101const RUN_TIMEOUT_MS = 10000
102// Fetch and pull talk to a server
103const NET_TIMEOUT_MS = 60000
104const PICK_TIMEOUT_MS = 300000
105const ARMED_MS = 5000
106// The three splits share one row, each as an arrow in the direction the new pane opens
107const SPLIT_SYMBOLS: Record<string, string> = {
108  'split-left': '[←]',
109  'split-right': '[→]',
110  'split-down': '[↓]',
111}
112
113const NO_REPOS: ReposState = {
114  roots: [],
115  list: [],
116  checkedAt: 0,
117  isBusy: false,
118  isFetching: false,
119  pulling: '',
120  note: '',
121}
122const NO_HOST: HostInfo = { os: 'linux', terminal: 'none' }
123const NO_FEED: FeedState = { command: '', list: [], since: '', checkedAt: 0, isBusy: false, note: '' }
124const NO_USAGE: UsageState = { measuredAt: 0, tokens: 0, window: 0, limits: [], usd: -1 }
125const NO_TODO: TodoState = { path: '', list: [], editing: -2, checkedAt: 0, note: '' }
126const MAX_TODO_ROWS = 12
127// Key of the text field of the TODO list, there is never more than one
128const TODO_INPUT = 'todo:input'
129// A second press on the same text within this time counts as a double click
130const DOUBLE_PRESS_MS = 600
131
132const files = atom({ plugin: 'turbo-mod', key: 'files' } as const, [] as FileEntry[])
133// The repo overview starts collapsed so that git does not run unasked
134const collapsed = atom({ plugin: 'turbo-mod', key: 'collapsed' } as const, { repos: true } as Record<string, boolean>)
135const repos = atom({ plugin: 'turbo-mod', key: 'repos' } as const, NO_REPOS)
136const host = atom({ plugin: 'turbo-mod', key: 'host' } as const, NO_HOST)
137const theme = atom({ plugin: 'turbo-mod', key: 'theme' } as const, STANDARD)
138const title = atom({ plugin: 'turbo-mod', key: 'title' } as const, TITLE)
139const filePage = atom({ plugin: 'turbo-mod', key: 'filePage' } as const, 0)
140const pulse = atom({ plugin: 'turbo-mod', key: 'pulse' } as const, 0)
141const accepted = atom({ plugin: 'turbo-mod', key: 'accepted' } as const, false)
142const ready = atom({ plugin: 'turbo-mod', key: 'ready' } as const, false)
143const armed = atom({ plugin: 'turbo-mod', key: 'armed' } as const, '')
144const lang = atom({ plugin: 'turbo-mod', key: 'lang' } as const, '')
145const editorPath = atom({ plugin: 'turbo-mod', key: 'editorPath' } as const, '')
146const usage = atom({ plugin: 'turbo-mod', key: 'usage' } as const, NO_USAGE)
147const ticketUrl = atom({ plugin: 'turbo-mod', key: 'ticketUrl' } as const, '')
148const feed = atom({ plugin: 'turbo-mod', key: 'feed' } as const, NO_FEED)
149const todo = atom({ plugin: 'turbo-mod', key: 'todo' } as const, NO_TODO)
150
151// Applies per module load: after a reload the timers are gone and the start runs again
152let isStarted = false
153let isRestoring = false
154let isTitleLooping = true
155// The last press on the text of a task, for the double click that opens the field
156let lastTextPress = { key: '', at: 0 }
157// While sample data is shown, nothing real may be read or written into the pane
158let isDemo = false
159let beforeDemo:
160  | {
161      files: FileEntry[]
162      repos: ReposState
163      feed: FeedState
164      usage: UsageState
165      todo: TodoState
166      collapsed: Record<string, boolean>
167    }
168  | undefined
169// The language from the options, it applies until the start has read the remembered choice
170let optionLanguage: Lang = 'en'
171
172const languageNow = async ($: EngineInterface): Promise<Lang> => findLanguage(await read($, lang)) ?? optionLanguage
173
174const pathOf = (e: unknown): string | undefined => {
175  const input = e as { file_path?: unknown; notebook_path?: unknown }
176  const path = input.file_path ?? input.notebook_path
177
178  return typeof path === 'string' && path.length > 0 ? path : undefined
179}
180
181const wantedColumns = (terminalColumns: number): number => Math.max(MIN_COLUMNS, Math.round(terminalColumns * SHARE))
182
183const textOf = (value: unknown): string => (typeof value === 'string' ? value.trim() : '')
184
185const isPaneUp = async ($: EngineInterface): Promise<boolean> =>
186  (await $.ui.panes()).some(pane => pane.id === PANE && pane.isPlaced)
187
188type Reading = {
189  context: { tokens?: number; window: number; percent?: number }
190  rateLimits: readonly { kind: string; percentUsed: number; resetsAt?: string }[]
191  cost?: { usd: number }
192}
193
194/** Keeps what the host measured: context window, rate-limit windows and cost. */
195const keepUsage = async ($: EngineInterface, reading: Reading): Promise<void> => {
196  if (isDemo) return
197
198  const measuredAt = await $.clock.now()
199  const window = reading.context.window
200  // Some hosts report only the share, some only the tokens
201  const tokens = reading.context.tokens ?? Math.round(((reading.context.percent ?? 0) / 100) * window)
202  await update($, usage, () => ({
203    measuredAt,
204    tokens,
205    window,
206    limits: reading.rateLimits.map(one => ({
207      kind: one.kind,
208      percentUsed: one.percentUsed,
209      resetsAt: one.resetsAt ?? '',
210    })),
211    usd: reading.cost?.usd ?? -1,
212  }))
213}
214
215/** True once the notice of the first start is confirmed, otherwise says so in a toast. */
216const isAccepted = async ($: EngineInterface): Promise<boolean> => {
217  if ((await read($, accepted)) === true) return true
218  $.ui.toast(textsFor(await languageNow($)).acceptFirst)
219
220  return false
221}
222
223/** Runs the feed command and keeps the tickets it prints. */
224const refreshFeed = async ($: EngineInterface): Promise<void> => {
225  if (isDemo) return
226
227  const before = (await read($, feed)) ?? NO_FEED
228  const argv = splitCommand(before.command)
229  if (argv.length === 0 || before.isBusy) return
230  if (!(await isAccepted($))) return
231
232  await update($, feed, now => ({ ...now, isBusy: true }))
233  const result = await $.process.run(argv, { timeoutMs: FEED_TIMEOUT_MS }).catch(() => undefined)
234  const checkedAt = await $.clock.now()
235  // A feed may end with an error code and still say why in its JSON
236  const parsed = result === undefined ? { list: [], since: '', note: 'no-start' } : parseFeed(result.stdout)
237  await update($, feed, now => ({ ...now, ...parsed, checkedAt, isBusy: false }))
238}
239
240/** Sets the feed command for this machine. An empty command switches the widget off. */
241const setFeed = async ($: EngineInterface, command: string): Promise<void> => {
242  await update($, feed, () => ({ ...NO_FEED, command }))
243  await $.store.set('feedCommand', command)
244  if (command.length > 0) {
245    await update($, collapsed, now => ({ ...now, feed: false }))
246    await refreshFeed($)
247  }
248}
249
250/**
251 * Shows or hides sample data. What the pane showed before is kept and comes back, the
252 * figures of the session are read again right away.
253 */
254const toggleDemo = async ($: EngineInterface): Promise<boolean> => {
255  if (isDemo) {
256    isDemo = false
257    const kept = beforeDemo
258    beforeDemo = undefined
259    if (kept !== undefined) {
260      await update($, files, () => kept.files)
261      await update($, repos, () => kept.repos)
262      await update($, feed, () => kept.feed)
263      await update($, usage, () => kept.usage)
264      await update($, todo, () => kept.todo)
265      await update($, collapsed, () => kept.collapsed)
266    }
267    await readUsage($)
268
269    return false
270  }
271
272  beforeDemo = {
273    files: await read($, files),
274    repos: await read($, repos),
275    feed: (await read($, feed)) ?? NO_FEED,
276    usage: (await read($, usage)) ?? NO_USAGE,
277    todo: (await read($, todo)) ?? NO_TODO,
278    collapsed: await read($, collapsed),
279  }
280  const sample = demoState(await $.clock.now())
281  isDemo = true
282  await update($, files, () => sample.files)
283  await update($, repos, () => sample.repos)
284  await update($, feed, () => sample.feed)
285  await update($, usage, () => sample.usage)
286  await update($, todo, now => ({ ...NO_TODO, path: now.path, list: sample.todos, checkedAt: sample.usage.measuredAt }))
287  // Everything open, so one screenshot shows every widget
288  await update($, collapsed, () => ({
289    files: false,
290    terminal: false,
291    repos: false,
292    feed: false,
293    todo: false,
294    session: false,
295  }))
296
297  return true
298}
299
300/** Asks the host for its current figures. Costs no request, the host has them at hand. */
301const readUsage = async ($: EngineInterface): Promise<void> => {
302  const reading = await $.session.usage().catch(() => undefined)
303  if (reading !== undefined) await keepUsage($, reading).catch(() => undefined)
304}
305
306/**
307 * True on the second press of a button within a few seconds, the first press only arms it.
308 * For everything that cannot be undone.
309 */
310const isSecondPress = async ($: EngineInterface, key: string): Promise<boolean> => {
311  if ((await read($, armed)) === key) {
312    await update($, armed, () => '')
313
314    return true
315  }
316
317  await update($, armed, () => key)
318  $.clock.after(ARMED_MS, () => {
319    void update($, armed, now => (now === key ? '' : now))
320  })
321
322  return false
323}
324
325/** True if the folder of the file belongs to a git repo. The tasks must never end up in a history. */
326const isInRepo = async ($: EngineInterface, path: string): Promise<boolean> => {
327  const dir = splitPath(path).dir
328  if (dir.length === 0) return false
329
330  const answer = await $.process
331    .run(['git', '-C', dir, 'rev-parse', '--is-inside-work-tree'], { timeoutMs: RUN_TIMEOUT_MS })
332    .then(result => result.stdout)
333    .catch(() => '')
334
335  return answer.trim() === 'true'
336}
337
338/** The content of the list. A missing file is an empty list, `undefined` a file that cannot be read. */
339const loadTodoFile = async ($: EngineInterface, path: string): Promise<string | undefined> => {
340  if (!(await $.fs.exists(path).catch(() => false))) return ''
341
342  return $.fs
343    .read(path)
344    .then(content => (typeof content === 'string' ? content : undefined))
345    .catch(() => undefined)
346}
347
348/** Reads the TODO list from its file. */
349const readTodos = async ($: EngineInterface): Promise<void> => {
350  if (isDemo) return
351
352  const state = (await read($, todo)) ?? NO_TODO
353  if (state.path.length === 0 || state.note === 'in-repo') return
354
355  const content = await loadTodoFile($, state.path)
356  const checkedAt = await $.clock.now()
357  await update($, todo, now => ({
358    ...now,
359    list: content === undefined ? [] : parseTodos(content),
360    note: content === undefined ? 'unreadable' : '',
361    checkedAt,
362  }))
363}
364
365/** Reads the file, applies the change and writes it back. The file is read anew every time. */
366const writeTodos = async ($: EngineInterface, change: (content: string) => string): Promise<boolean> => {
367  if (isDemo) return false
368
369  const state = (await read($, todo)) ?? NO_TODO
370  if (state.path.length === 0 || state.note === 'in-repo') return false
371
372  const content = await loadTodoFile($, state.path)
373  if (content === undefined) {
374    await update($, todo, now => ({ ...now, note: 'unreadable' }))
375
376    return false
377  }
378
379  const next = change(content)
380  const isWritten =
381    next === content ||
382    (await $.fs
383      .write(state.path, next)
384      .then(() => true)
385      .catch(() => false))
386  if (!isWritten) await update($, todo, now => ({ ...now, note: 'unreadable' }))
387  else await readTodos($)
388
389  return isWritten
390}
391
392/** Sets the file of the TODO list for this machine. A folder inside a git repo is refused. */
393const setTodoPath = async ($: EngineInterface, path: string): Promise<boolean> => {
394  if (await isInRepo($, path)) return false
395
396  await $.store.set('todoPath', path)
397  await update($, todo, now => ({ ...now, path, note: '', editing: -2 }))
398  await update($, collapsed, now => ({ ...now, todo: false }))
399  await readTodos($)
400
401  return true
402}
403
404/** True on the second press on the same text in quick succession. The interface has no double click of its own. */
405const isDoublePress = async ($: EngineInterface, key: string): Promise<boolean> => {
406  const at = await $.clock.now()
407  const isDouble = lastTextPress.key === key && at - lastTextPress.at <= DOUBLE_PRESS_MS
408  lastTextPress = isDouble ? { key: '', at: 0 } : { key, at }
409
410  return isDouble
411}
412
413/** Shows the text field for a new task (-1) or for the task of a line, -2 hides it. */
414const editTodo = async ($: EngineInterface, line: number): Promise<void> => {
415  await update($, todo, now => ({ ...now, editing: line }))
416  if (line === -2) return
417
418  // A click on a button does not hand the keyboard to the pane, so the pane asks for it. The
419  // field is drawn with the next rendering, the focus waits for it and tries once more if refused.
420  await $.ui.open({ id: PANE, title: PANE_TITLE, focus: true }).catch(() => undefined)
421  const toField = () => $.ui.focus({ requestId: PANE, key: TODO_INPUT }).catch(() => ({ deny: 'failed' }))
422  const first = await toField()
423  if ('deny' in first) {
424    $.clock.after(60, () => {
425      void toField()
426    })
427  }
428}
429
430/** Enter in the text field: a new task without `item`, otherwise the new text of that task. */
431const saveTodo = async ($: EngineInterface, item: TodoItem | undefined, value: string): Promise<void> => {
432  await update($, todo, now => ({ ...now, editing: -2 }))
433  if (value.trim().length === 0) return
434
435  await writeTodos($, content =>
436    item === undefined ? addTodo(content, value) : changeTodo(content, item, now => ({ ...now, text: value })),
437  )
438}
439
440/** Compacts the conversation as /compact does, then reads the figures again. */
441const compactSession = async ($: EngineInterface): Promise<void> => {
442  const t = textsFor(await languageNow($))
443  const result = await $.session.compact().catch(() => undefined)
444  if (result === undefined) $.ui.toast(t.hostFailed('/compact'))
445  // The host says why it did not compact, for example when there is nothing to compact yet
446  else $.ui.toast(typeof result.skip === 'string' ? `/compact: ${result.skip}` : t.compacted)
447  await readUsage($)
448}
449
450/** Starts a fresh conversation as /clear does. */
451const clearSession = async ($: EngineInterface): Promise<void> => {
452  const result = await $.command.run({ command: 'clear' }).catch(() => undefined)
453  if (result === undefined) $.ui.toast(textsFor(await languageNow($)).hostFailed('/clear'))
454}
455
456/** Starts a program on the machine and shows a toast if that fails. True if it ran without complaint. */
457const run = async ($: EngineInterface, argv: readonly string[], what: string): Promise<boolean> => {
458  const result = await $.process.run(argv, { timeoutMs: RUN_TIMEOUT_MS }).catch(() => undefined)
459  if (result === undefined) {
460    $.ui.toast(textsFor(await languageNow($)).runFailed(what, argv[0] ?? ''))
461
462    return false
463  }
464
465  // explorer.exe returns 1 even on success, so only an error message counts
466  const complaint = result.stderr.trim().split('\n')[0] ?? ''
467  if (result.exitCode !== 0 && complaint.length > 0) {
468    $.ui.toast(`${what}: ${complaint}`)
469
470    return false
471  }
472
473  return true
474}
475
476/**
477 * Looks up the full path of the editor. A new pane inherits the environment of the terminal, where
478 * the editor's folder is sometimes missing from PATH even though Claude Code knows it.
479 */
480const findEditor = async ($: EngineInterface, hostInfo: HostInfo, editor: string): Promise<string> => {
481  if (isPath(editor)) {
482    const stat = await $.fs.stat(editor).catch(() => undefined)
483
484    return stat !== undefined && stat.kind === 'file' ? editor : ''
485  }
486
487  const found = await $.process.run(whereArgv(hostInfo, editor), { timeoutMs: RUN_TIMEOUT_MS }).catch(() => undefined)
488  if (found === undefined || found.exitCode !== 0) return ''
489
490  return (found.stdout.split('\n')[0] ?? '').trim()
491}
492
493/** The root folders of a state. A state kept from before 0.6.0 has one `root` and no `roots`. */
494const rootsOf = (state: ReposState): string[] => {
495  const old = (state as { root?: unknown }).root
496
497  return Array.isArray(state.roots) ? state.roots : typeof old === 'string' && old.length > 0 ? [old] : []
498}
499
500/** Reads the state of one repo from `git status`. */
501const readRepo = async ($: EngineInterface, root: string, dir: string, name: string): Promise<RepoEntry> => {
502  const status = await $.process.run(STATUS_ARGV, { cwd: dir, timeoutMs: RUN_TIMEOUT_MS }).catch(() => undefined)
503
504  return status === undefined || status.exitCode !== 0
505    ? { root, dir, name, branch: '?', ahead: 0, behind: 0, changed: 0, untracked: 0, isRead: false }
506    : parseStatus(name, status.stdout, root, dir)
507}
508
509/**
510 * Reads the state of all git repos under the root folders. Contacts no server, unless `isFetching`
511 * asks for a `git fetch` in every repo first.
512 */
513const refreshRepos = async ($: EngineInterface, isFetching = false): Promise<void> => {
514  if (isDemo) return
515
516  const before = await read($, repos)
517  const roots = rootsOf(before)
518  if (roots.length === 0 || before.isBusy) return
519  // Reading the local state is plain display, only the fetch talks to a server
520  if (isFetching && !(await isAccepted($))) return
521
522  await update($, repos, now => ({ ...now, isBusy: true, isFetching, note: '' }))
523  const list: RepoEntry[] = []
524  let unreadable = 0
525  for (const root of roots) {
526    const entries = await $.fs.list(root).catch(() => undefined)
527    if (entries === undefined) {
528      unreadable += 1
529      continue
530    }
531
532    for (const entry of entries.filter(one => one.kind === 'dir').slice(0, MAX_REPOS)) {
533      const dir = joinPath(root, entry.name)
534      // .git is a file in a worktree, otherwise a folder
535      const marker = await $.fs.stat(joinPath(dir, '.git')).catch(() => undefined)
536      if (marker === undefined || marker.kind === 'other') continue
537
538      // A failed fetch (no remote, no network) leaves the counters as they were
539      if (isFetching) await $.process.run(FETCH_ARGV, { cwd: dir, timeoutMs: NET_TIMEOUT_MS }).catch(() => undefined)
540      list.push(await readRepo($, root, dir, entry.name))
541    }
542  }
543
544  const checkedAt = await $.clock.now()
545  await update($, repos, now => ({
546    ...now,
547    isBusy: false,
548    isFetching: false,
549    list: sortRepos(list),
550    checkedAt,
551    note: unreadable === roots.length ? 'unreadable' : list.length === 0 ? 'empty' : '',
552  }))
553}
554
555/** Fetches one repo and pulls it fast-forward only, then reads its state again. */
556const pullRepo = async ($: EngineInterface, repo: RepoEntry): Promise<void> => {
557  if (isDemo) return
558
559  const before = await read($, repos)
560  if (before.isBusy || (before.pulling ?? '').length > 0) return
561  if (!(await isAccepted($))) return
562
563  await update($, repos, now => ({ ...now, pulling: repo.dir }))
564  const t = textsFor(await languageNow($))
565  const result = await $.process.run(PULL_ARGV, { cwd: repo.dir, timeoutMs: NET_TIMEOUT_MS }).catch(() => undefined)
566  if (result === undefined) {
567    $.ui.toast(t.runFailed(`${repo.name}: pull`, 'git'))
568  } else if (result.exitCode !== 0) {
569    // git says why: diverged branches, local changes in the way, no upstream
570    $.ui.toast(`${repo.name}: ${result.stderr.trim().split('\n')[0] ?? 'git pull'}`)
571  } else {
572    $.ui.toast(t.pulled(repo.name))
573  }
574
575  const after = await readRepo($, repo.root, repo.dir, repo.name)
576  await update($, repos, now => ({
577    ...now,
578    pulling: '',
579    list: sortRepos(now.list.map(one => (one.dir === repo.dir ? after : one))),
580  }))
581}
582
583/** Sets the repo folders for this machine, expands the widget and reads. */
584const setReposRoots = async ($: EngineInterface, roots: string[]): Promise<void> => {
585  await update($, repos, now => ({ ...now, roots, list: [], checkedAt: 0, note: '' }))
586  await $.store.set('reposRoots', roots)
587  await update($, collapsed, now => ({ ...now, repos: false }))
588  await refreshRepos($)
589}
590
591const addReposRoot = async ($: EngineInterface, root: string): Promise<void> => {
592  const roots = rootsOf(await read($, repos))
593  await setReposRoots($, roots.includes(root) ? roots : [...roots, root])
594}
595
596/** Shows the folder dialog and takes the choice as the repo folder. */
597const pickReposRoot = async ($: EngineInterface): Promise<void> => {
598  const t = textsFor(await languageNow($))
599  const argv = pickFolderArgv(await read($, host), t.pickTitle)
600  const result = await $.process.run(argv, { timeoutMs: PICK_TIMEOUT_MS }).catch(() => undefined)
601  if (result === undefined) {
602    $.ui.toast(t.pickFailed(argv[0] ?? ''))
603
604    return
605  }
606
607  // Cancelled means: nothing printed
608  const root = result.stdout.trim()
609  if (root.length > 0) await addReposRoot($, root)
610}
611
612/** Switches to the next or previous color scheme and remembers it for this machine. */
613const stepTheme = async ($: EngineInterface, step: number): Promise<void> => {
614  const names = themeNames()
615  const current = Math.max(0, names.indexOf(await read($, theme)))
616  const next = names[(current + step + names.length) % names.length] ?? STANDARD
617  await update($, theme, () => next)
618  await $.store.set('theme', next)
619}
620
621/** Changes the language and remembers it for this machine. */
622const setLanguage = async ($: EngineInterface, language: Lang): Promise<void> => {
623  await update($, lang, () => language)
624  await $.store.set('lang', language)
625}
626
627/** Switches to the next language. */
628const stepLanguage = async ($: EngineInterface): Promise<void> => {
629  const current = Math.max(0, LANGUAGES.indexOf(await languageNow($)))
630  await setLanguage($, LANGUAGES[(current + 1) % LANGUAGES.length] ?? 'en')
631}
632
633/**
634 * Runs the title through an effect at intervals: effect, one second of rest, next effect.
635 * While the pane is not visible, the loop rests.
636 */
637const startTitleLoop = ($: EngineInterface): void => {
638  let tick = 0
639  let seed = 1
640  let effect: EffectName = 'decrypt'
641  let isVisible = false
642  // Writes one frame after the other so that no late frame overtakes an earlier one
643  let queue: Promise<unknown> = Promise.resolve()
644  const show = (text: string): void => {
645    queue = queue.then(() => update($, title, () => text)).catch(() => undefined)
646  }
647
648  $.clock.every(TITLE_FRAME_MS, () => {
649    const position = tick % (TITLE_FRAMES + TITLE_PAUSE_TICKS)
650    tick += 1
651
652    if (position === 0) {
653      seed += 1
654      // Never the same effect twice in a row
655      const others = EFFECTS.filter(one => one !== effect)
656      effect = others[Math.floor(Math.random() * others.length)] ?? 'decrypt'
657      void isPaneUp($)
658        .then(isUp => {
659          isVisible = isUp
660        })
661        .catch(() => undefined)
662    }
663
664    if (!isTitleLooping || !isVisible || position > TITLE_FRAMES) return
665
666    show(position === TITLE_FRAMES ? TITLE : effectFrame(effect, TITLE, position, TITLE_FRAMES, seed))
667  })
668}
669
670/**
671 * Brings the session state back from the store, the options and the environment. Runs again
672 * whenever the host has dropped the state, which a /clear does without loading the mod anew.
673 */
674const restore = async ($: EngineInterface, options: PluginOptions): Promise<void> => {
675  // Each step may fail on its own, the rest of the start still runs
676  const stored = async (key: string): Promise<string> => textOf(await $.store.get(key).catch(() => undefined))
677  const language = findLanguage(await stored('lang')) ?? optionLanguage
678  await update($, lang, () => language)
679
680  await $.command
681    .register({
682      name: COMMAND,
683      description: textsFor(language).commandDescription,
684      argumentHint:
685        '[todo <text> | theme <name> | repos [remove] <path> | ticket <url> | feed <command> | lang <de|en> | clear | effect | demo]',
686    })
687    .catch(() => undefined)
688
689  const os = await $.env.get('OS').catch(() => undefined)
690  const wtSession = await $.env.get('WT_SESSION').catch(() => undefined)
691  const tmux = await $.env.get('TMUX').catch(() => undefined)
692  const kittyWindowId = await $.env.get('KITTY_WINDOW_ID').catch(() => undefined)
693  const kittyListenOn = await $.env.get('KITTY_LISTEN_ON').catch(() => undefined)
694  const termProgram = await $.env.get('TERM_PROGRAM').catch(() => undefined)
695  const uname =
696    (os ?? '').toLowerCase() === 'windows_nt'
697      ? undefined
698      : await $.process
699          .run(['uname', '-s'])
700          .then(result => result.stdout)
701          .catch(() => undefined)
702  const detected = detectHost({ os, wtSession, tmux, kittyWindowId, kittyListenOn, termProgram }, uname)
703  await update($, host, () => detected)
704
705  const found = await findEditor($, detected, textOf(options.editor) || 'nvim').catch(() => '')
706  await update($, editorPath, () => found)
707
708  // What /turbo has set on this machine takes precedence over the options and the environment
709  const chosen = findTheme(await stored('theme')) ?? findTheme(textOf(options.theme)) ?? STANDARD
710  await update($, theme, () => chosen)
711  const kept = await $.store.get('reposRoots').catch(() => undefined)
712  const roots = Array.isArray(kept)
713    ? kept.filter((one): one is string => typeof one === 'string' && one.length > 0)
714    : splitRoots(
715        // Before 0.6.0 there was one folder under the key reposRoot
716        (await stored('reposRoot')) ||
717          textOf(options.reposRoot) ||
718          textOf(await $.env.get('TURBO_MOD_REPOS').catch(() => undefined)),
719      )
720  await update($, repos, now => ({ ...now, roots, isBusy: false, isFetching: false, pulling: '' }))
721  const tickets = (await stored('ticketUrl')) || textOf(options.ticketUrl)
722  await update($, ticketUrl, () => tickets)
723  const feedCommand = (await stored('feedCommand')) || textOf(options.ticketFeed)
724  await update($, feed, now => ({ ...NO_FEED, ...now, command: feedCommand, isBusy: false }))
725  const home =
726    textOf(await $.env.get('USERPROFILE').catch(() => undefined)) ||
727    textOf(await $.env.get('HOME').catch(() => undefined))
728  const todoPath = (await stored('todoPath')) || (home.length > 0 ? todoPathIn(home) : '')
729  const isTracked = todoPath.length > 0 && (await isInRepo($, todoPath).catch(() => false))
730  await update($, todo, now => ({
731    ...NO_TODO,
732    list: now.list ?? [],
733    path: todoPath,
734    note: isTracked ? 'in-repo' : '',
735  }))
736  await readTodos($).catch(() => undefined)
737  // Only ever switches on: a click that came before the end of the start must not be undone
738  if ((await stored('accepted')) === 'yes') await update($, accepted, () => true)
739  await readUsage($)
740  isTitleLooping = (await stored('effect')) !== 'aus'
741  await update($, armed, () => '')
742  await update($, title, () => TITLE)
743  await update($, ready, () => true)
744}
745
746/** Looks at every listed file again: a deleted one is marked, a changed one gets its new size and time. */
747const checkFiles = async ($: EngineInterface): Promise<void> => {
748  const list = await read($, files)
749  if (isDemo || list.length === 0) return
750
751  const stats = await Promise.all(list.map(one => $.fs.stat(one.path).catch(() => undefined)))
752  const changed = new Map<string, FileEntry>()
753  list.forEach((one, index) => {
754    const stat = stats[index]
755    const wasGone = one.isGone === true
756    if (stat === undefined || stat.kind !== 'file') {
757      if (!wasGone) changed.set(one.path, { ...one, isGone: true })
758
759      return
760    }
761
762    if (wasGone || stat.size !== one.size || stat.mtimeMs !== one.mtimeMs) {
763      changed.set(one.path, { ...one, size: stat.size, mtimeMs: stat.mtimeMs, isGone: false })
764    }
765  })
766
767  if (changed.size > 0) await update($, files, now => now.map(one => changed.get(one.path) ?? one))
768}
769
770type RepoPoint = { top: string; head: string }
771
772/** Top folder and commit of the repo the session works in, undefined outside a repo. */
773const readTopHead = async ($: EngineInterface): Promise<RepoPoint | undefined> => {
774  const cwd = await $.session.cwd().catch(() => undefined)
775  if (cwd === undefined) return undefined
776
777  const result = await $.process.run(TOP_HEAD_ARGV, { cwd, timeoutMs: RUN_TIMEOUT_MS }).catch(() => undefined)
778  if (result === undefined || result.exitCode !== 0) return undefined
779
780  const [top = '', head = ''] = result.stdout.split('\n').map(line => line.trim())
781
782  return top.length > 0 && head.length > 0 ? { top, head } : undefined
783}
784
785/**
786 * Puts the files into the list that a shell command changed. A shell call names no file, so git is
787 * asked afterwards: what differs from the last commit, and what a new commit brought along.
788 * Only files written since the call started count. Outside a git repo nothing is found.
789 */
790const noteShellChanges = async (
791  $: EngineInterface,
792  before: RepoPoint | undefined,
793  startedAt: number,
794): Promise<void> => {
795  if (before === undefined) return
796
797  const options = { cwd: before.top, timeoutMs: RUN_TIMEOUT_MS }
798  const status = await $.process.run(CHANGES_ARGV, options).catch(() => undefined)
799  if (status === undefined || status.exitCode !== 0) return
800
801  const now = parseChanges(status.stdout)
802  // A chain that commits leaves a clean tree, its files are only in the new commit
803  const isMoved = now.head.length > 0 && now.head !== before.head
804  const diff = isMoved
805    ? await $.process.run(diffArgv(before.head, now.head), options).catch(() => undefined)
806    : undefined
807  const committed = diff === undefined || diff.exitCode !== 0 ? [] : parseDiff(diff.stdout)
808
809  // A deletion counts only from a commit: the status also lists what was deleted long before this call
810  const candidates = new Map<string, ChangeEntry>()
811  for (const one of committed) candidates.set(one.path, one)
812  for (const one of now.list.filter(each => !each.isGone)) candidates.set(one.path, one)
813  if (candidates.size === 0 || candidates.size > MAX_SHELL_CANDIDATES) return
814
815  // A file system with a coarse clock rounds the time down to the second
816  const since = Math.floor(startedAt / 1000) * 1000
817  const found = await Promise.all(
818    [...candidates.values()].map(async one => {
819      const path = repoPath(before.top, one.path)
820
821      return { one, path, stat: await $.fs.stat(path).catch(() => undefined) }
822    }),
823  )
824  const written = found.filter(each => each.stat?.kind === 'file' && each.stat.mtimeMs >= since)
825  const gone = found.filter(each => each.one.isGone && each.stat?.kind !== 'file')
826  if (written.length + gone.length === 0 || written.length + gone.length > MAX_SHELL_FILES) return
827
828  await update($, files, list => {
829    let next = list
830    const nextNo = (): number => next.reduce((highest, each) => Math.max(highest, each.no), 0) + 1
831
832    for (const { one, path, stat } of written) {
833      const key = pathKey(path)
834      const known = next.find(each => pathKey(each.path) === key)
835      const entry: FileEntry = {
836        path: known?.path ?? path,
837        size: stat?.size ?? 0,
838        mtimeMs: stat?.mtimeMs ?? startedAt,
839        isNew: known?.isNew ?? one.isNew,
840        writes: (known?.writes ?? 0) + 1,
841        no: known?.no ?? nextNo(),
842      }
843      next = [entry, ...next.filter(each => pathKey(each.path) !== key)]
844    }
845
846    for (const { path } of gone) {
847      const key = pathKey(path)
848      next = next.some(each => pathKey(each.path) === key)
849        ? next.map(each => (pathKey(each.path) === key ? { ...each, isGone: true } : each))
850        : [{ path, size: 0, mtimeMs: startedAt, isNew: false, writes: 1, no: nextNo(), isGone: true }, ...next]
851    }
852
853    return next.slice(0, MAX_FILES)
854  })
855  // What the shell wrote is on top, so the list goes back to the first page
856  if (written.length > 0) await update($, filePage, () => 0)
857}
858
859/** The timers of the mod. They survive a /clear, so they start once per module load. */
860const startTimers = ($: EngineInterface): void => {
861  startTitleLoop($)
862  // The dots behind a busy label move only while something is being read
863  $.clock.every(PULSE_EVERY_MS, () => {
864    void (async () => {
865      const repoState = await read($, repos)
866      const feedState = (await read($, feed)) ?? NO_FEED
867      const isWorking = repoState.isBusy || (repoState.pulling ?? '').length > 0 || feedState.isBusy
868      if (isWorking) await update($, pulse, now => (now + 1) % 3)
869    })().catch(() => undefined)
870  })
871  $.clock.every(FEED_EVERY_MS, () => {
872    void (async () => {
873      const isFolded = (await read($, collapsed)).feed ?? true
874      // Without the confirmation the timer stays quiet instead of raising a toast every time
875      const isConfirmed = (await read($, accepted)) === true
876      if (isConfirmed && !isFolded && (await isPaneUp($))) await refreshFeed($)
877    })().catch(() => undefined)
878  })
879  // The host reports after every answer. In between, a look once a minute keeps the reset times fresh.
880  $.clock.every(USAGE_EVERY_MS, () => {
881    void (async () => {
882      const isFolded = (await read($, collapsed)).session ?? false
883      if (!isFolded && (await isPaneUp($))) await readUsage($)
884    })().catch(() => undefined)
885  })
886  // A file deleted or changed outside the write tools shows up after a few seconds
887  $.clock.every(FILES_EVERY_MS, () => {
888    void (async () => {
889      const isFolded = (await read($, collapsed)).files ?? false
890      if (!isFolded && (await isPaneUp($))) await checkFiles($)
891    })().catch(() => undefined)
892  })
893  $.clock.every(REPOS_EVERY_MS, () => {
894    void (async () => {
895      const isFolded = (await read($, collapsed)).repos ?? false
896      if (!isFolded && (await isPaneUp($))) await refreshRepos($)
897    })().catch(() => undefined)
898  })
899}
900
901/**
902 * Runs on session.start and, because that does not fire after reloading the mod, resuming a
903 * session or a /clear, also on every render and before every command. Does nothing while the
904 * state is in place.
905 */
906const start = async ($: EngineInterface, options: PluginOptions): Promise<void> => {
907  if (isRestoring) return
908  if (isStarted && (await read($, ready)) === true) return
909
910  isRestoring = true
911  try {
912    await restore($, options)
913    if (!isStarted) {
914      isStarted = true
915      startTimers($)
916    }
917  } finally {
918    isRestoring = false
919  }
920}
921
922export const register: Register = (on, options) => {
923  optionLanguage = findLanguage(textOf(options.language)) ?? 'en'
924  const editorName = splitPath(textOf(options.editor) || 'nvim').name.replace(/\.exe$/i, '')
925
926  on('session.start', async ($, e, next) => {
927    await start($, options)
928    // Opened unasked, the pane only appears from 144 columns on, below that via /turbo
929    void $.ui.open({ id: PANE, title: PANE_TITLE })
930
931    return next(e)
932  })
933
934  on('command.run', { command: COMMAND }, async ($, e) => {
935    await start($, options)
936    const t = textsFor(await languageNow($))
937    const args = e.args.trim()
938    const verb = (args.split(/\s+/)[0] ?? '').toLowerCase()
939    const argument = args.slice(verb.length).trim()
940
941    if (verb === '') {
942      if (await isPaneUp($)) {
943        await $.ui.close({ id: PANE })
944
945        return { text: t.hidden }
946      }
947
948      await $.ui.open({ id: PANE, title: PANE_TITLE, columns: wantedColumns(e.presentation.columns) })
949
950      return { text: t.shown(VERSION) }
951    }
952
953    if (verb === 'demo') {
954      return { text: (await toggleDemo($)) ? t.demoOn : t.demoOff }
955    }
956
957    if (verb === 'leeren' || verb === 'clear') {
958      await update($, files, () => [])
959
960      return { text: t.cleared }
961    }
962
963    if (verb === 'effekt' || verb === 'effect') {
964      isTitleLooping = !isTitleLooping
965      await $.store.set('effect', isTitleLooping ? 'an' : 'aus')
966      await update($, title, () => TITLE)
967
968      return { text: isTitleLooping ? t.effectOn : t.effectOff }
969    }
970
971    if (verb === 'theme' || verb === 'farben' || verb === 'colors') {
972      if (argument.length === 0) return { text: t.themeList(themeNames().join(', ')) }
973
974      const found = findTheme(argument)
975      if (found === undefined) return { text: t.themeUnknown(argument) }
976
977      await update($, theme, () => found)
978      await $.store.set('theme', found)
979
980      return { text: t.themeSet(found) }
981    }
982
983    if (verb === 'sprache' || verb === 'lang' || verb === 'language') {
984      const found = findLanguage(argument)
985      if (found === undefined) return { text: t.languageUnknown(argument) }
986
987      await setLanguage($, found)
988
989      return { text: textsFor(found).languageSet }
990    }
991
992    if (verb === 'feed') {
993      if (argument.length === 0) {
994        const now = ((await read($, feed)) ?? NO_FEED).command
995
996        return { text: now.length > 0 ? t.feedSet(now) : t.feedNone }
997      }
998
999      if (argument === 'aus' || argument === 'off') {
1000        await setFeed($, '')
1001
1002        return { text: t.feedOff }
1003      }
1004
1005      await setFeed($, argument)
1006      const after = (await read($, feed)) ?? NO_FEED
1007      const note = t.feedNotes[after.note] ?? after.note
1008
1009      return { text: note.length > 0 ? note : t.feedSet(argument) }
1010    }
1011
1012    if (verb === 'ticket') {
1013      if (argument.length === 0) {
1014        const now = await read($, ticketUrl)
1015
1016        return { text: now.length > 0 ? t.ticketSet(now) : t.ticketNone }
1017      }
1018
1019      await update($, ticketUrl, () => argument)
1020      await $.store.set('ticketUrl', argument)
1021
1022      return { text: t.ticketSet(argument) }
1023    }
1024
1025    if (verb === 'todo') {
1026      const state = (await read($, todo)) ?? NO_TODO
1027      const file = /^(datei|file)(?:\s+(.+))?$/i.exec(argument)
1028      if (file !== null) {
1029        const path = (file[2] ?? '').trim()
1030        if (path.length === 0) return { text: t.todoFile(state.path) }
1031
1032        return { text: (await setTodoPath($, path)) ? t.todoFileSet(path) : t.todoInRepo(path) }
1033      }
1034
1035      if (isDemo) return { text: t.demoOn }
1036      if (state.note === 'in-repo') return { text: t.todoInRepo(state.path) }
1037
1038      await update($, collapsed, now => ({ ...now, todo: false }))
1039      if (argument.length === 0) {
1040        await readTodos($)
1041        const list = ((await read($, todo)) ?? NO_TODO).list
1042
1043        return { text: t.todoCount(list.filter(one => !one.isDone).length) }
1044      }
1045
1046      return {
1047        text: (await writeTodos($, content => addTodo(content, argument))) ? t.todoAdded(argument) : t.todoFailed,
1048      }
1049    }
1050
1051    if (verb === 'repos') {
1052      const roots = rootsOf(await read($, repos))
1053      const removal = /^(remove|entfernen)\s+(.+)$/i.exec(argument)
1054      if (removal !== null) {
1055        const root = (removal[2] ?? '').trim()
1056        if (!roots.includes(root)) return { text: t.rootUnknown(root) }
1057
1058        await setReposRoots(
1059          $,
1060          roots.filter(one => one !== root),
1061        )
1062
1063        return { text: t.rootRemoved(root) }
1064      }
1065
1066      if (argument.length === 0 && roots.length === 0) return { text: t.rootMissing }
1067
1068      if (argument.length > 0) await addReposRoot($, argument)
1069      else await refreshRepos($)
1070      const after = await read($, repos)
1071      const dirty = after.list.filter(one => !isClean(one)).length
1072
1073      return { text: t.notes[after.note] ?? t.reposResult(after.list.length, rootsOf(after).join(', '), dirty) }
1074    }
1075
1076    return { text: t.help }
1077  })
1078
1079  on('ui.focus', { component: 'Pane', requestId: PANE }, async ($, e, next) => {
1080    const result = await next(e)
1081    // The ring left the text field, by Esc or by a click elsewhere: the field closes unsaved
1082    if (e.element !== TODO_INPUT && ((await read($, todo)) ?? NO_TODO).editing !== -2) {
1083      await update($, todo, now => ({ ...now, editing: -2 }))
1084    }
1085
1086    return result
1087  })
1088
1089  on('session.measure', async ($, e, next) => {
1090    await keepUsage($, e).catch(() => undefined)
1091
1092    return next(e)
1093  })
1094
1095  on('tool.call', async ($, e, next) => {
1096    if (SHELLS.includes(String(e.tool)) && !isDemo) {
1097      const before = await readTopHead($)
1098      const startedAt = await $.clock.now()
1099      const ran = await next(e)
1100      if (ran.deny !== undefined) return ran
1101
1102      await noteShellChanges($, before, startedAt).catch(() => undefined)
1103      await checkFiles($).catch(() => undefined)
1104
1105      return ran
1106    }
1107
1108    const path = WRITERS.includes(String(e.tool)) ? pathOf(e) : undefined
1109    if (path === undefined || isDemo) return next(e)
1110
1111    // Check before writing whether the file already existed: new or changed
1112    const before = await $.fs.stat(path).catch(() => undefined)
1113    const ran = await next(e)
1114    if (ran.deny !== undefined || ran.isError === true) return ran
1115
1116    const after = await $.fs.stat(path).catch(() => undefined)
1117    if (after === undefined || after.kind !== 'file') return ran
1118
1119    await update($, files, list => {
1120      const known = list.find(one => one.path === path)
1121      const entry: FileEntry = {
1122        path,
1123        size: after.size,
1124        mtimeMs: after.mtimeMs,
1125        isNew: known !== undefined ? known.isNew : before === undefined || before.kind !== 'file',
1126        writes: (known?.writes ?? 0) + 1,
1127        no: known?.no ?? list.reduce((highest, one) => Math.max(highest, one.no), 0) + 1,
1128      }
1129
1130      return [entry, ...list.filter(one => one.path !== path)].slice(0, MAX_FILES)
1131    })
1132    // The written file is on top, so the list goes back to the first page
1133    await update($, filePage, () => 0)
1134
1135    return ran
1136  })
1137
1138  on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
1139    // Nothing may be written while rendering, so the start runs right after
1140    if (!isStarted || (await read($, ready)) !== true) {
1141      $.clock.after(1, () => {
1142        void start($, options).catch(() => undefined)
1143      })
1144    }
1145
1146    const elements = $.ui.resolve(e)
1147    const { Box, Text, Link, Button } = elements
1148    // The mobile app draws no text field, there a task comes in with /turbo todo
1149    const Input = 'Input' in elements ? elements.Input : undefined
1150    const list = await read($, files)
1151    const folded = await read($, collapsed)
1152    const repoState = await read($, repos)
1153    const hostInfo = await read($, host)
1154    const themeName = await read($, theme)
1155    const look = lookFor(themeName)
1156    const heading = await read($, title)
1157    const armedKey = await read($, armed)
1158    const isConfirmed = (await read($, accepted)) === true
1159    const language = await languageNow($)
1160    const t = textsFor(language)
1161    const editor = await read($, editorPath)
1162    const usageState = (await read($, usage)) ?? NO_USAGE
1163    const feedState = (await read($, feed)) ?? NO_FEED
1164    const todoState = (await read($, todo)) ?? NO_TODO
1165    const ticketPattern = (await read($, ticketUrl)) ?? ''
1166    const contextPercent = usageState.window > 0 ? Math.round((usageState.tokens / usageState.window) * 100) : 0
1167
1168    const columns = Math.max(16, e.props.bodyColumns)
1169    // The height of the pane body, in tests and on other surfaces the value is missing
1170    const bodyRows = e.props.scroll?.bodyRows
1171    const rows = bodyRows ?? e.viewport?.rows ?? 30
1172    // A prop with the value undefined counts as invalid, so it is left out entirely then
1173    const ink = look.text === undefined ? {} : { color: look.text }
1174    const ground = look.background === undefined ? {} : { backgroundColor: look.background }
1175    // Without a minimum height the area of the color scheme ends below the last line
1176    const tall = look.background === undefined || bodyRows === undefined ? {} : { minHeight: bodyRows }
1177    const chip = look.chip === undefined ? {} : { backgroundColor: look.chip }
1178    const isFolded = (id: string): boolean => folded[id] ?? false
1179    // The TODO list starts collapsed while it is empty, so it takes no room from the files
1180    const isTodoFolded = folded.todo ?? todoState.list.length === 0
1181    const foldedNow = (id: string): boolean => (id === 'todo' ? isTodoFolded : (folded[id] ?? id === 'feed'))
1182    const actions = terminalActions(hostInfo, '')
1183    const dirty = repoState.list.filter(one => !isClean(one))
1184    const total = list.reduce((sum, one) => sum + (one.isGone === true ? 0 : one.size), 0)
1185    const note = t.notes[repoState.note] ?? ''
1186
1187    // How many rows the other widgets need, the rest belongs to the files (four rows per file)
1188    const terminalRows = isFolded('terminal') ? 1 : 3
1189    const repoRoom = Math.max(3, Math.floor(rows / 4))
1190    const roots = rootsOf(repoState)
1191    const pulling = repoState.pulling ?? ''
1192    // One to three dots in a fixed width, so the button does not change its size
1193    const step = (await read($, pulse)) ?? 0
1194    const dots = dotsFor(step)
1195    const working = (label: string): string => workingLabel(label, step)
1196    const repoRows = isFolded('repos') ? 1 : 2 + 2 * roots.length + Math.min(dirty.length, repoRoom)
1197    const sessionRows = isFolded('session') ? 1 : 5 + 3 * usageState.limits.length
1198    // The feed widget exists only with a command and starts collapsed
1199    const isFeedOn = feedState.command.length > 0
1200    const isFeedFolded = folded.feed ?? true
hooks/demo.ts 95 lines
1// Invented data for screenshots - without $ and therefore directly testable.
2// Nothing here comes from a real machine: the paths, repos and tickets are made up.
3
4import type { FeedState, FileEntry, ReposState, TodoItem, UsageState } from '../types'
5
6const HOME = '/home/sam/projects'
7const MINUTE = 60000
8const HOUR = 60 * MINUTE
9
10export type DemoState = {
11  files: FileEntry[]
12  repos: ReposState
13  feed: FeedState
14  usage: UsageState
15  todos: TodoItem[]
16}
17
18/** Everything the pane shows, filled with made-up content around the moment `now`. */
19export const demoState = (now: number): DemoState => {
20  const file = (no: number, path: string, size: number, minutesAgo: number, isNew: boolean, writes = 1): FileEntry => ({
21    path: `${HOME}/${path}`,
22    size,
23    mtimeMs: now - minutesAgo * MINUTE,
24    isNew,
25    writes,
26    no,
27  })
28  const repo = (name: string, branch: string, changed: number, untracked: number, ahead: number, behind: number) => ({
29    root: HOME,
30    dir: `${HOME}/${name}`,
31    name,
32    branch,
33    ahead,
34    behind,
35    changed,
36    untracked,
37    isRead: true,
38  })
39  const ticket = (key: string, summary: string) => ({ key, summary, url: `https://tickets.example.com/browse/${key}` })
40
41  return {
42    files: [
43      file(4, 'shop/docs/release-notes.md', 2150, 1, true),
44      file(3, 'shop/src/cart/checkout.ts', 12595, 3, false, 3),
45      file(2, 'shop/src/cart/checkout.test.ts', 5420, 4, true),
46      file(1, 'shop/package.json', 1002, 9, false),
47    ],
48    repos: {
49      roots: [HOME],
50      list: [
51        repo('shop', 'feature/ABC-123-checkout', 3, 1, 1, 0),
52        repo('website', 'main', 0, 0, 0, 2),
53        repo('design-system', 'main', 0, 2, 0, 0),
54        repo('api', 'main', 0, 0, 0, 0),
55        repo('docs', 'main', 0, 0, 0, 0),
56        repo('infra', 'main', 0, 0, 0, 0),
57      ],
58      checkedAt: now,
59      isBusy: false,
60      isFetching: false,
61      pulling: '',
62      note: '',
63    },
64    feed: {
65      command: 'demo',
66      list: [
67        ticket('ABC-131', 'Checkout: total is wrong with two vouchers'),
68        ticket('ABC-130', 'Add dark mode to the order history'),
69        ticket('ABC-129', 'Search returns nothing for umlauts'),
70        ticket('ABC-128', 'Update the payment provider SDK'),
71      ],
72      since: new Date(now - 24 * HOUR).toISOString().slice(0, 10),
73      checkedAt: now,
74      isBusy: false,
75      note: '',
76    },
77    todos: [
78      { line: 0, text: 'Write the release notes', isDone: false },
79      { line: 1, text: 'Idea: a dark variant of the logo', isDone: false },
80      { line: 2, text: 'Tidy up the old branches', isDone: false },
81      { line: 3, text: 'Update the README screenshots', isDone: true },
82    ],
83    usage: {
84      measuredAt: now,
85      tokens: 42000,
86      window: 200000,
87      limits: [
88        { kind: 'five_hour', percentUsed: 48, resetsAt: new Date(now + 2 * HOUR + 20 * MINUTE).toISOString() },
89        { kind: 'seven_day', percentUsed: 10, resetsAt: new Date(now + 6 * 24 * HOUR).toISOString() },
90      ],
91      usd: 1.37,
92    },
93  }
94}
95
hooks/effects.ts 96 lines
1// Text effects for the title line - without $ and therefore directly testable.
2// Three effects from retro-text-effects.js are rebuilt here as small functions: decrypt,
3// wipe and errorcorrect. The library itself needs the DOM and requestAnimationFrame,
4// neither exists in a mod. Each function returns ONE frame, the host sets the pace.
5
6const GLYPHS = Array.from('#%&$@*+=<>/\\|[]{}0123456789')
7// U+2588, the full block as the cursor
8const CURSOR = '█'
9
10export const EFFECTS = ['decrypt', 'wipe', 'errorcorrect'] as const
11export type EffectName = (typeof EFFECTS)[number]
12
13/** Random numbers in [0, 1) from a seed (mulberry32): same seed, same sequence. */
14export const seeded = (seed: number): (() => number) => {
15  let state = seed >>> 0
16
17  return () => {
18    state = (state + 0x6d2b79f5) >>> 0
19    let value = state
20    value = Math.imul(value ^ (value >>> 15), value | 1)
21    value ^= value + Math.imul(value ^ (value >>> 7), value | 61)
22
23    return ((value ^ (value >>> 14)) >>> 0) / 4294967296
24  }
25}
26
27/**
28 * decrypt: the first characters are already in place, the rest flickers through random characters.
29 *
30 * @param text The finished text.
31 * @param frame Number of the frame, from 0.
32 * @param frames Number of frames, at `frame >= frames` the whole text is shown.
33 * @param random Random number in [0, 1), fixed in tests.
34 */
35export const decryptFrame = (text: string, frame: number, frames: number, random: () => number): string => {
36  const cells = Array.from(text)
37  if (frame >= frames || frames <= 0) return text
38
39  const settled = Math.floor((cells.length * Math.max(0, frame)) / frames)
40
41  return cells
42    .map((ch, i) => {
43      // Spaces stay in place so that the line does not jump
44      if (i < settled || ch === ' ') return ch
45
46      return GLYPHS[Math.floor(random() * GLYPHS.length) % GLYPHS.length]
47    })
48    .join('')
49}
50
51/** wipe: the text is written from the left, with a cursor running ahead of it. */
52export const wipeFrame = (text: string, frame: number, frames: number): string => {
53  const cells = Array.from(text)
54  if (frame >= frames || frames <= 0) return text
55
56  const written = Math.floor((cells.length * Math.max(0, frame)) / frames)
57
58  return cells.map((ch, i) => (i < written ? ch : i === written ? CURSOR : ' ')).join('')
59}
60
61/** errorcorrect: letters are swapped and move pair by pair to their place. */
62export const errorcorrectFrame = (text: string, frame: number, frames: number, seed: number): string => {
63  const cells = Array.from(text)
64  if (frame >= frames || frames <= 0) return text
65
66  // The pairs depend only on the seed, so that every frame of the same run knows the same pairs
67  const random = seeded(seed)
68  const places = cells.map((ch, i) => (ch === ' ' ? -1 : i)).filter(i => i >= 0)
69  for (let i = places.length - 1; i > 0; i -= 1) {
70    const j = Math.floor(random() * (i + 1))
71    const held = places[i] as number
72    places[i] = places[j] as number
73    places[j] = held
74  }
75
76  const pairs = Math.floor(places.length / 2)
77  const corrected = Math.floor((pairs * Math.max(0, frame)) / frames)
78  for (let pair = corrected; pair < pairs; pair += 1) {
79    const a = places[pair * 2] as number
80    const b = places[pair * 2 + 1] as number
81    const held = cells[a] as string
82    cells[a] = cells[b] as string
83    cells[b] = held
84  }
85
86  return cells.join('')
87}
88
89/** One frame of the named effect. The same seed gives the same result for the same frame. */
90export const effectFrame = (name: EffectName, text: string, frame: number, frames: number, seed: number): string => {
91  if (name === 'wipe') return wipeFrame(text, frame, frames)
92  if (name === 'errorcorrect') return errorcorrectFrame(text, frame, frames, seed)
93
94  return decryptFrame(text, frame, frames, seeded(seed * 31 + frame))
95}
96
hooks/feed.ts 30 lines
1// Reads what a ticket feed prints - without $ and therefore directly testable.
2// A feed is any command that prints one JSON object: { tickets: [{ key, summary, url }], since?, message? }.
3
4import type { FeedTicket } from '../types'
5
6export type FeedResult = { list: FeedTicket[]; since: string; note: string }
7
8const text = (value: unknown): string => (typeof value === 'string' ? value : '')
9
10/** Tickets, first day and a note from the output of a feed. Never throws: broken output becomes a note. */
11export const parseFeed = (stdout: string): FeedResult => {
12  let data: unknown
13  try {
14    data = JSON.parse(stdout)
15  } catch {
16    return { list: [], since: '', note: 'no-json' }
17  }
18
19  if (typeof data !== 'object' || data === null) return { list: [], since: '', note: 'no-json' }
20
21  const feed = data as { tickets?: unknown; since?: unknown; message?: unknown; error?: unknown }
22  const rows = Array.isArray(feed.tickets) ? feed.tickets : []
23  const list = rows
24    .filter((row): row is Record<string, unknown> => typeof row === 'object' && row !== null)
25    .map(row => ({ key: text(row.key), summary: text(row.summary), url: text(row.url) }))
26    .filter(row => row.key.length > 0)
27
28  return { list, since: text(feed.since), note: text(feed.message) || text(feed.error) }
29}
30
hooks/format.ts 114 lines
1// Pure helper functions for the display - without $ and therefore directly testable.
2
3const pad = (n: number): string => (n < 10 ? `0${n}` : `${n}`)
4
5/** Bytes as a size: 512 B, 12,3 KB, 4,0 MB. English with a dot instead of a comma. */
6export const formatSize = (bytes: number, lang = 'de'): string => {
7  if (bytes < 1024) return `${bytes} B`
8  const units = ['KB', 'MB', 'GB']
9  let value = bytes / 1024
10  let unit = 0
11  while (value >= 1024 && unit < units.length - 1) {
12    value /= 1024
13    unit += 1
14  }
15
16  return `${value.toFixed(1).replace('.', lang === 'en' ? '.' : ',')} ${units[unit]}`
17}
18
19/** Timestamp as dd.MM. HH:mm:ss, in English as MM-dd HH:mm:ss. */
20export const formatStamp = (mtimeMs: number, lang = 'de'): string => {
21  const d = new Date(mtimeMs)
22  const day =
23    lang === 'en' ? `${pad(d.getMonth() + 1)}-${pad(d.getDate())}` : `${pad(d.getDate())}.${pad(d.getMonth() + 1)}.`
24
25  return `${day} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`
26}
27
28/** Time of day as HH:mm. */
29export const formatClock = (ms: number): string => {
30  const d = new Date(ms)
31
32  return `${pad(d.getHours())}:${pad(d.getMinutes())}`
33}
34
35/** Splits a path into folder and file name, whether \ or /. */
36export const splitPath = (path: string): { dir: string; name: string } => {
37  const cut = Math.max(path.lastIndexOf('/'), path.lastIndexOf('\\'))
38
39  return cut < 0 ? { dir: '', name: path } : { dir: path.slice(0, cut), name: path.slice(cut + 1) }
40}
41
42/** file: URL for an absolute path, also for Windows drives. */
43export const fileHref = (path: string): string => {
44  const forward = path.replace(/\\/g, '/')
45  const encoded = forward
46    .split('/')
47    .map((part, i) => (i === 0 && /^[A-Za-z]:$/.test(part) ? part : encodeURIComponent(part)))
48    .join('/')
49
50  return encoded.startsWith('/') ? `file://${encoded}` : `file:///${encoded}`
51}
52
53/** Shortens the folder from the front so that the end (the telling part) stays. */
54export const shortenDir = (dir: string, room: number): string =>
55  dir.length <= room ? dir : `...${dir.slice(dir.length - Math.max(1, room - 3))}`
56
57/** Tokens in short form: 950, 84k, 1.2M. */
58export const formatTokens = (tokens: number): string =>
59  tokens >= 1000000
60    ? `${(tokens / 1000000).toFixed(1)}M`
61    : tokens >= 1000
62      ? `${Math.round(tokens / 1000)}k`
63      : String(Math.round(tokens))
64
65/** Time of a reset: HH:mm on the same day as `nowMs`, otherwise with the date in front. */
66export const formatReset = (iso: string, nowMs: number, lang = 'de'): string => {
67  const ms = Date.parse(iso)
68  if (Number.isNaN(ms)) return ''
69
70  const d = new Date(ms)
71  const now = new Date(nowMs)
72  const isSameDay =
73    d.getFullYear() === now.getFullYear() && d.getMonth() === now.getMonth() && d.getDate() === now.getDate()
74  if (isSameDay) return formatClock(ms)
75
76  const date =
77    lang === 'en' ? `${pad(d.getMonth() + 1)}-${pad(d.getDate())}` : `${pad(d.getDate())}.${pad(d.getMonth() + 1)}.`
78
79  return `${date} ${formatClock(ms)}`
80}
81
82/** US dollars: 3,21 $ in German, $3.21 in English. */
83export const formatUsd = (usd: number, lang = 'de'): string =>
84  lang === 'en' ? `$${usd.toFixed(2)}` : `${usd.toFixed(2).replace('.', ',')} $`
85
86/** The first ticket key in a branch name, for example ABC-123 in feature/ABC-123-fix. */
87export const ticketOf = (branch: string): string | undefined => /[A-Z][A-Z0-9]+-\d+/.exec(branch)?.[0]
88
89/** Address of a ticket: the key replaces {id}, without a placeholder it is appended. */
90export const ticketHref = (pattern: string, id: string): string =>
91  pattern.includes('{id}') ? pattern.replace('{id}', id) : `${pattern.replace(/\/+$/, '')}/${id}`
92
93/** How many of `width` cells of a bar are filled at `percent`. Anything above zero shows at least one. */
94export const barCells = (percent: number, width: number): number => {
95  const share = Math.min(100, Math.max(0, percent)) / 100
96
97  return share > 0 ? Math.max(1, Math.round(share * width)) : 0
98}
99
100/** An ISO date as dd.MM. or, in English, MM-dd. Empty for anything else. */
101export const formatDay = (iso: string, lang = 'de'): string => {
102  const match = /^(\d{4})-(\d\d)-(\d\d)/.exec(iso)
103  if (match === null) return ''
104
105  return lang === 'en' ? `${match[2]}-${match[3]}` : `${match[3]}.${match[2]}.`
106}
107
108/** One to three dots in a fixed width of three cells, so a label does not change its size. */
109export const dotsFor = (step: number): string => '.'.repeat((Math.max(0, Math.trunc(step)) % 3) + 1).padEnd(3)
110
111/** A busy label with moving dots in place of its own three: "reading ..." becomes "reading .  ". */
112export const workingLabel = (label: string, step: number): string =>
113  `${label.replace(/ ?\.{3}$/, '')} ${dotsFor(step)}`.trimStart()
114
hooks/git.ts 146 lines
1// Reads the output of `git status --porcelain=v2 --branch` - without $ and therefore directly testable.
2
3import type { RepoEntry } from '../types'
4
5export const STATUS_ARGV = ['git', 'status', '--porcelain=v2', '--branch'] as const
6export const FETCH_ARGV = ['git', 'fetch', '--quiet'] as const
7// Fast-forward only: a pull never creates a merge commit and never rewrites local work
8export const PULL_ARGV = ['git', 'pull', '--ff-only', '--quiet'] as const
9
10/** State of a repo from the status output: branch, ahead, behind, number of changes. */
11export const parseStatus = (name: string, stdout: string, root = '', dir = ''): RepoEntry => {
12  const entry: RepoEntry = { root, dir, name, branch: '?', ahead: 0, behind: 0, changed: 0, untracked: 0, isRead: true }
13
14  for (const line of stdout.split('\n')) {
15    if (line.startsWith('# branch.head ')) {
16      entry.branch = line.slice('# branch.head '.length).trim()
17      continue
18    }
19
20    if (line.startsWith('# branch.ab ')) {
21      const match = /\+(\d+) -(\d+)/.exec(line)
22      if (match !== null) {
23        entry.ahead = Number(match[1])
24        entry.behind = Number(match[2])
25      }
26      continue
27    }
28
29    // 1 = changed, 2 = renamed, u = conflict
30    if (/^[12u] /.test(line)) entry.changed += 1
31    // ? = a file git does not know yet
32    if (line.startsWith('? ')) entry.untracked += 1
33  }
34
35  return entry
36}
37
38/** True if there is nothing to do in the repo: nothing changed, nothing ahead, nothing behind. */
39export const isClean = (repo: RepoEntry): boolean =>
40  repo.isRead && repo.changed === 0 && (repo.untracked ?? 0) === 0 && repo.ahead === 0 && repo.behind === 0
41
42/** Repos that need attention first, within the groups by name. */
43export const sortRepos = (list: RepoEntry[]): RepoEntry[] =>
44  [...list].sort((a, b) => Number(isClean(a)) - Number(isClean(b)) || a.name.localeCompare(b.name))
45
46/** Short form of the counters for one line: "~3 ?1 ↑1 ↓2", empty for a clean repo. */
47export const repoCounts = (repo: RepoEntry): string =>
48  [
49    repo.changed > 0 ? `~${repo.changed}` : '',
50    (repo.untracked ?? 0) > 0 ? `?${repo.untracked}` : '',
51    repo.ahead > 0 ? `↑${repo.ahead}` : '',
52    repo.behind > 0 ? `↓${repo.behind}` : '',
53  ]
54    .filter(part => part.length > 0)
55    .join(' ')
56
57// One call for both: the top folder of the repo and the commit it stands on. Fails outside a repo.
58export const TOP_HEAD_ARGV = ['git', 'rev-parse', '--show-toplevel', 'HEAD'] as const
59// Every untracked file by name instead of one line per folder
60export const CHANGES_ARGV = ['git', 'status', '--porcelain=v2', '--branch', '--untracked-files=all'] as const
61
62/** A file a shell command touched, as git names it: relative to the top folder, forward slashes. */
63export type ChangeEntry = { path: string; isNew: boolean; isGone: boolean }
64
65/** Files changed between two commits, without rename detection: a rename is one gone and one new. */
66export const diffArgv = (before: string, after: string): string[] => [
67  'git',
68  'diff',
69  '--name-status',
70  '--no-renames',
71  before,
72  after,
73]
74
75// The part of a line behind its first `count` fields. Paths may contain spaces, fields may not.
76const afterFields = (line: string, count: number): string => {
77  let at = 0
78  for (let field = 0; field < count; field += 1) {
79    const space = line.indexOf(' ', at)
80    if (space < 0) return ''
81    at = space + 1
82  }
83
84  return line.slice(at)
85}
86
87// git quotes a path with special characters. Such a path is left out instead of guessed.
88const isPlain = (path: string): boolean => path.length > 0 && !path.startsWith('"')
89
90/** The commit and the changed files from `git status --porcelain=v2 --branch`. */
91export const parseChanges = (stdout: string): { head: string; list: ChangeEntry[] } => {
92  let head = ''
93  const list: ChangeEntry[] = []
94
95  for (const line of stdout.split('\n')) {
96    if (line.startsWith('# branch.oid ')) {
97      head = line.slice('# branch.oid '.length).trim()
98      continue
99    }
100
101    if (line.startsWith('? ')) {
102      const path = line.slice(2).trim()
103      if (isPlain(path)) list.push({ path, isNew: true, isGone: false })
104      continue
105    }
106
107    // 1 = changed (8 fields before the path), 2 = renamed (9, then a tab and the old path), u = conflict (10)
108    const fields = line.startsWith('1 ') ? 8 : line.startsWith('2 ') ? 9 : line.startsWith('u ') ? 10 : 0
109    if (fields === 0) continue
110
111    const path = (afterFields(line, fields).split('\t')[0] ?? '').trim()
112    // XY: X is the index, Y the working tree
113    const index = line.charAt(2)
114    const tree = line.charAt(3)
115    if (isPlain(path))
116      list.push({ path, isNew: index === 'A', isGone: tree === 'D' || (index === 'D' && tree === '.') })
117  }
118
119  return { head, list }
120}
121
122/** The files from `git diff --name-status --no-renames`. */
123export const parseDiff = (stdout: string): ChangeEntry[] => {
124  const list: ChangeEntry[] = []
125
126  for (const line of stdout.split('\n')) {
127    const [status = '', path = ''] = line.split('\t')
128    if (status.length === 0 || !isPlain(path.trim())) continue
129
130    list.push({ path: path.trim(), isNew: status.startsWith('A'), isGone: status.startsWith('D') })
131  }
132
133  return list
134}
135
136/** Absolute path of a file in a repo. On a Windows drive with backslashes, as the write tools name it. */
137export const repoPath = (top: string, relative: string): string => {
138  const joined = `${top.replace(/[\\/]+$/, '')}/${relative}`
139
140  return /^[A-Za-z]:[\\/]/.test(top) ? joined.replaceAll('/', '\\') : joined
141}
142
143/** Two spellings of one Windows path compare equal: slashes and case do not count there. */
144export const pathKey = (path: string): string =>
145  /^[A-Za-z]:[\\/]/.test(path) ? path.replaceAll('/', '\\').toLowerCase() : path
146
hooks/platform.ts 192 lines
1// Which commands the given operating system and terminal need - without $ and therefore directly testable.
2
3import type { HostInfo } from '../types'
4
5export type TerminalAction = {
6  /** Key of the command, also the key of its label in texts.ts. */
7  key: string
8  argv: string[]
9  /** True for commands that close something: the button then asks once. */
10  needsConfirm?: true
11}
12
13export const CHEAT_SHEET = 'https://www.michaelblaess.de/helfer/windows-terminal.html'
14
15/** Detects operating system and terminal from environment variables and the output of `uname -s`. */
16export const detectHost = (
17  env: {
18    os?: string
19    wtSession?: string
20    tmux?: string
21    kittyWindowId?: string
22    kittyListenOn?: string
23    termProgram?: string
24  },
25  uname?: string,
26): HostInfo => {
27  const isWindows = (env.os ?? '').toLowerCase() === 'windows_nt'
28  const os = isWindows ? 'windows' : (uname ?? '').trim().toLowerCase() === 'darwin' ? 'mac' : 'linux'
29  const isSet = (value?: string): boolean => value !== undefined && value.trim().length > 0
30  // tmux first: if it runs inside Windows Terminal (WSL), tmux splits the window
31  if (isSet(env.tmux)) return { os, terminal: 'tmux' }
32  if (isSet(env.wtSession)) return { os, terminal: 'wt' }
33  // kitty only takes commands from outside over its socket, the window alone is not enough
34  if (isSet(env.kittyWindowId)) {
35    return isSet(env.kittyListenOn) ? { os, terminal: 'kitty' } : { os, terminal: 'none', hint: 'kitty-remote-off' }
36  }
37  // Ghostty has no command that splits a window from outside
38  if ((env.termProgram ?? '').trim().toLowerCase() === 'ghostty') return { os, terminal: 'none', hint: 'ghostty' }
39
40  return { os, terminal: 'none' }
41}
42
43/** Command that opens a file or folder with the default application. */
44export const openDefaultArgv = (host: HostInfo, path: string): string[] => {
45  // explorer.exe only understands backslashes, in return it needs no shell and no quoting
46  if (host.os === 'windows') return ['explorer.exe', path.replace(/\//g, '\\')]
47
48  return host.os === 'mac' ? ['open', path] : ['xdg-open', path]
49}
50
51/** Command that opens the file in the editor in a new split, or undefined without a splittable terminal. */
52export const openEditorArgv = (host: HostInfo, editor: string, path: string, cwd: string): string[] | undefined => {
53  if (host.terminal === 'wt') return ['wt.exe', '-w', '0', 'split-pane', '-V', '-d', cwd, editor, path]
54  if (host.terminal === 'tmux') return ['tmux', 'split-window', '-h', '-c', cwd, editor, path]
55  if (host.terminal === 'kitty') return [...KITTY_LAUNCH, '--location=vsplit', '--cwd', cwd, editor, path]
56
57  return undefined
58}
59
60// Windows Terminal has no command for closing. So: focus the last active pane,
61// then send the key combination for "close pane" to the foreground window.
62const WT_CLOSE_LAST =
63  "wt.exe -w 0 move-focus previous; Start-Sleep -Milliseconds 400; (New-Object -ComObject WScript.Shell).SendKeys('^+w')"
64
65// kitty finds its socket through KITTY_LISTEN_ON. The directions only count in the layout "splits".
66const KITTY_LAUNCH = ['kitty', '@', 'launch']
67
68// kitty has no split to the left either: split right, the new window is the active one, move it left.
69// The folder travels as an argument and never as part of the script.
70const KITTY_SPLIT_LEFT = 'kitty @ launch --location=vsplit --cwd "$1" && kitty @ action move_window left'
71
72/** The window commands of the terminal, empty without a splittable terminal. */
73export const terminalActions = (host: HostInfo, cwd: string): TerminalAction[] => {
74  if (host.terminal === 'wt') {
75    const split = ['wt.exe', '-w', '0', 'split-pane']
76
77    return [
78      // A split to the left is missing on the command line: split right and swap the two panes
79      { key: 'split-left', argv: [...split, '-V', '-d', cwd, ';', 'swap-pane', 'left'] },
80      { key: 'split-right', argv: [...split, '-V', '-d', cwd] },
81      { key: 'split-down', argv: [...split, '-H', '-d', cwd] },
82      { key: 'new-tab', argv: ['wt.exe', '-w', '0', 'new-tab', '-d', cwd] },
83      { key: 'close-last', argv: ['powershell.exe', '-NoProfile', '-Command', WT_CLOSE_LAST], needsConfirm: true },
84    ]
85  }
86
87  if (host.terminal === 'tmux') {
88    return [
89      { key: 'split-left', argv: ['tmux', 'split-window', '-h', '-b', '-c', cwd] },
90      { key: 'split-right', argv: ['tmux', 'split-window', '-h', '-c', cwd] },
91      { key: 'split-down', argv: ['tmux', 'split-window', '-v', '-c', cwd] },
92      { key: 'new-tab', argv: ['tmux', 'new-window', '-c', cwd] },
93      // The active pane is Claude's own, so the last used other one
94      { key: 'close-last', argv: ['tmux', 'kill-pane', '-t', '{last}'], needsConfirm: true },
95    ]
96  }
97
98  if (host.terminal === 'kitty') {
99    return [
100      { key: 'split-left', argv: ['sh', '-c', KITTY_SPLIT_LEFT, 'sh', cwd] },
101      { key: 'split-right', argv: [...KITTY_LAUNCH, '--location=vsplit', '--cwd', cwd] },
102      { key: 'split-down', argv: [...KITTY_LAUNCH, '--location=hsplit', '--cwd', cwd] },
103      { key: 'new-tab', argv: [...KITTY_LAUNCH, '--type=tab', '--cwd', cwd] },
104      // recent:0 is the active window and with it Claude's own, recent:1 the one used before
105      { key: 'close-last', argv: ['kitty', '@', 'close-window', '--match', 'recent:1'], needsConfirm: true },
106    ]
107  }
108
109  return []
110}
111
112const windowsPicker = (title: string): string =>
113  [
114    '[Console]::OutputEncoding = [Text.Encoding]::UTF8',
115    'Add-Type -AssemblyName System.Windows.Forms',
116    '$dialog = New-Object System.Windows.Forms.FolderBrowserDialog',
117    `$dialog.Description = '${title}'`,
118    // Without a window in the foreground the dialog opens behind the terminal
119    '$owner = New-Object System.Windows.Forms.Form -Property @{ TopMost = $true }',
120    "if ($dialog.ShowDialog($owner) -eq 'OK') { [Console]::Out.Write($dialog.SelectedPath) }",
121  ].join('; ')
122
123/**
124 * Command that shows a folder dialog and prints the chosen path.
125 * The title ends up in a command text, so quotes in it are removed.
126 */
127export const pickFolderArgv = (host: HostInfo, title: string): string[] => {
128  const safe = title.replace(/['"`$]/g, '')
129  if (host.os === 'windows') return ['powershell.exe', '-NoProfile', '-STA', '-Command', windowsPicker(safe)]
130  if (host.os === 'mac') return ['osascript', '-e', `POSIX path of (choose folder with prompt "${safe}")`]
131
132  return ['zenity', '--file-selection', '--directory', `--title=${safe}`]
133}
134
135/**
136 * Command that prints the full path of a program. A new pane inherits the environment of the
137 * terminal and not that of Claude Code, so the bare name is not always enough there.
138 */
139export const whereArgv = (host: HostInfo, program: string): string[] =>
140  host.os === 'windows' ? ['where.exe', program] : ['which', program]
141
142/** Splits a list of folders written with ; or line breaks, without blanks and without duplicates. */
143export const splitRoots = (text: string): string[] => [
144  ...new Set(
145    text
146      .split(/[;\n]/)
147      .map(one => one.trim())
148      .filter(one => one.length > 0),
149  ),
150]
151
152/** True if the name is already a path and does not have to be looked up first. */
153export const isPath = (program: string): boolean => /[\\/]/.test(program)
154
155/** Appends a name to a folder, with the separator the folder itself uses. */
156export const joinPath = (dir: string, name: string): string => {
157  const separator = dir.includes('\\') ? '\\' : '/'
158
159  return dir.endsWith('/') || dir.endsWith('\\') ? `${dir}${name}` : `${dir}${separator}${name}`
160}
161
162export const CLAUDE_SHEET = 'https://www.michaelblaess.de/helfer/claude-code.html'
163
164// The text travels as an argument and never as part of the script, so nothing in it is run
165const POSIX_COPY = 'if command -v wl-copy >/dev/null 2>&1; then wl-copy; else xclip -selection clipboard; fi'
166
167const quoted = (text: string): string => `'${text.replace(/'/g, "''")}'`
168
169const powershell = (script: string): string[] => ['powershell.exe', '-NoProfile', '-NonInteractive', '-Command', script]
170
171/** Command that puts a text on the clipboard. */
172export const copyTextArgv = (host: HostInfo, text: string): string[] => {
173  if (host.os === 'windows') return powershell(`Set-Clipboard -Value ${quoted(text)}`)
174  if (host.os === 'mac') return ['sh', '-c', 'printf %s "$1" | pbcopy', 'sh', text]
175
176  return ['sh', '-c', `printf %s "$1" | { ${POSIX_COPY}; }`, 'sh', text]
177}
178
179/** Command that puts the content of a text file on the clipboard. */
180export const copyFileArgv = (host: HostInfo, path: string): string[] => {
181  if (host.os === 'windows') {
182    return powershell(`Get-Content -Raw -Encoding UTF8 -LiteralPath ${quoted(path)} | Set-Clipboard`)
183  }
184  if (host.os === 'mac') return ['sh', '-c', 'pbcopy < "$1"', 'sh', path]
185
186  return ['sh', '-c', `{ ${POSIX_COPY}; } < "$1"`, 'sh', path]
187}
188
189/** Splits a command line into program and arguments. Double quotes keep blanks together. */
190export const splitCommand = (line: string): string[] =>
191  (line.match(/"[^"]*"|\S+/g) ?? []).map(part => part.replace(/^"(.*)"$/, '$1'))
192
hooks/texts.ts 369 lines
1// All texts shown in the pane and in the answers of /turbo, per language - without $ and therefore directly testable.
2
3export const LANGUAGES = ['de', 'en'] as const
4export type Lang = (typeof LANGUAGES)[number]
5
6export type Texts = {
7  files: string
8  fileCount: (count: number) => string
9  nothingWritten: string
10  gone: string
11  more: (count: number) => string
12  range: (from: number, to: number, total: number) => string
13  clearList: string
14  open: string
15  terminal: string
16  noTerminal: string
17  terminalHints: Record<string, string>
18  sheet: string
19  confirmClose: string
20  confirmRun: string
21  compacted: string
22  hostFailed: (what: string) => string
23  /** Label per terminal command, keys as in platform.ts. */
24  actions: Record<string, string>
25  repos: string
26  reposCount: (dirty: number, total: number) => string
27  noFolder: string
28  pickFolder: string
29  addFolder: string
30  fetchAll: string
31  fetching: string
32  pull: string
33  pulled: (name: string) => string
34  rootRemoved: (root: string) => string
35  rootUnknown: (root: string) => string
36  session: string
37  context: string
38  of: string
39  resets: string
40  cost: string
41  /** Label per rate-limit window, keys as the host reports them. */
42  limits: Record<string, string>
43  noReading: string
44  copyPath: string
45  copyContent: string
46  copied: (what: string) => string
47  ticketSet: (url: string) => string
48  ticketNone: string
49  feed: string
50  feedCount: (count: number, since: string) => string
51  feedEmpty: string
52  feedSet: (command: string) => string
53  feedOff: string
54  demoOn: string
55  demoOff: string
56  feedNone: string
57  /** Notes of the feed, keys as in feed.ts and register.tsx. */
58  feedNotes: Record<string, string>
59  todo: string
60  todoOpen: (open: number) => string
61  todoCount: (open: number) => string
62  todoEmpty: string
63  todoPlaceholder: string
64  todoSave: string
65  todoCancel: string
66  todoTidy: (done: number) => string
67  todoAdded: (text: string) => string
68  todoFailed: string
69  todoFile: (path: string) => string
70  todoFileSet: (path: string) => string
71  todoInRepo: (path: string) => string
72  todoNotes: Record<string, string>
73  noticeTitle: string
74  notice: string
75  accept: string
76  acceptFirst: string
77  reread: string
78  reading: string
79  allClean: string
80  unreadable: string
81  /** Notes of the repo overview, keys as in ReposState.note. */
82  notes: Record<string, string>
83  /** Title of the folder dialog. No apostrophe, it sits inside a PowerShell string. */
84  pickTitle: string
85  colors: string
86  commandDescription: string
87  help: string
88  hidden: string
89  shown: (version: string) => string
90  cleared: string
91  effectOn: string
92  effectOff: string
93  themeList: (names: string) => string
94  themeUnknown: (name: string) => string
95  themeSet: (name: string) => string
96  rootMissing: string
97  reposResult: (total: number, root: string, dirty: number) => string
98  languageSet: string
99  languageUnknown: (name: string) => string
100  runFailed: (what: string, program: string) => string
101  pickFailed: (program: string) => string
102}
103
104const DE: Texts = {
105  files: 'Dateien',
106  fileCount: count => (count === 1 ? '1 Datei' : `${count} Dateien`),
107  nothingWritten: 'Noch nichts geschrieben. Hier erscheint jede Datei, die Claude anlegt oder ändert.',
108  gone: 'gelöscht',
109  more: count => `... und ${count} weitere`,
110  range: (from, to, total) => `${from}-${to} von ${total}`,
111  clearList: 'Liste leeren',
112  open: 'öffnen',
113  terminal: 'Terminal',
114  noTerminal: 'Kein teilbares Terminal erkannt. Unterstützt sind Windows Terminal, tmux und kitty.',
115  terminalHints: {
116    'kitty-remote-off':
117      'kitty erkannt, die Fernsteuerung ist aber aus. Setze allow_remote_control und listen_on in der kitty.conf und starte kitty neu.',
118    ghostty: 'Ghostty erkannt. Es lässt sich von außen nicht teilen, starte Claude darin in tmux.',
119  },
120  sheet: 'Spickzettel',
121  confirmClose: 'Wirklich schließen?',
122  confirmRun: 'Wirklich?',
123  compacted: 'Gespräch zusammengefasst.',
124  hostFailed: what => `${what} ließ sich von hier aus nicht starten. Tippe den Befehl in die Eingabe.`,
125  actions: {
126    'split-left': 'Split links',
127    'split-right': 'Split rechts',
128    'split-down': 'Split unten',
129    'new-tab': 'Neuer Tab',
130    'close-last': 'Letztes Pane schließen',
131  },
132  repos: 'Repos',
133  reposCount: (dirty, total) => `${dirty} von ${total} mit Änderungen`,
134  noFolder: 'Noch kein Ordner gesetzt.',
135  pickFolder: 'Ordner wählen',
136  addFolder: 'Ordner hinzufügen',
137  fetchAll: 'alle fetchen',
138  fetching: 'fetcht ...',
139  pull: 'pull',
140  pulled: name => `${name}: auf dem Stand des Servers.`,
141  rootRemoved: root => `Repo-Ordner entfernt: ${root}`,
142  rootUnknown: root => `Kein Repo-Ordner "${root}" gesetzt.`,
143  session: 'Claude',
144  context: 'Kontext',
145  of: 'von',
146  resets: 'Reset',
147  cost: 'Kosten',
148  limits: { five_hour: 'Aktuelle Sitzung', seven_day: 'Aktuelle Woche', spend_limit: 'Budget' },
149  noReading: 'Noch keine Werte. Sie kommen nach der ersten Antwort.',
150  copyPath: 'Pfad',
151  copyContent: 'Inhalt',
152  copied: what => `${what} liegt in der Zwischenablage.`,
153  ticketSet: url => `Ticket-Adresse: ${url}`,
154  ticketNone: 'Keine Ticket-Adresse gesetzt. Beispiel: /turbo ticket https://jira.example.com/browse/{id}',
155  feed: 'Neue Tickets',
156  feedCount: (count, since) => (since.length > 0 ? `${count} seit ${since}` : String(count)),
157  feedEmpty: 'Keine neuen Tickets.',
158  feedSet: command => `Neue Tickets kommen von: ${command}`,
159  feedOff: 'Neue Tickets abgeschaltet.',
160  demoOn: 'Beispieldaten eingeblendet, nichts davon ist echt. /turbo demo blendet sie wieder aus.',
161  demoOff: 'Beispieldaten ausgeblendet.',
162  feedNone: 'Kein Befehl gesetzt. /turbo feed <befehl> schaltet das Widget ein, /turbo feed aus schaltet es ab.',
163  feedNotes: {
164    'no-json': 'Der Befehl hat kein JSON ausgegeben.',
165    'no-start': 'Der Befehl ließ sich nicht starten oder hat nicht geantwortet.',
166  },
167  todo: 'TODO',
168  todoOpen: open => (open === 0 ? '' : `${open} offen`),
169  todoCount: open => (open === 1 ? '1 Aufgabe offen.' : `${open} Aufgaben offen.`),
170  todoEmpty: 'Noch keine Aufgaben.',
171  todoPlaceholder: 'Neue Aufgabe',
172  todoSave: 'speichern',
173  todoCancel: 'abbrechen',
174  todoTidy: done => `${done} erledigte entfernen`,
175  todoAdded: text => `Aufgabe angelegt: ${text}`,
176  todoFailed: 'Die Datei der TODO-Liste ließ sich nicht schreiben.',
177  todoFile: path => `Die TODO-Liste liegt in: ${path}`,
178  todoFileSet: path => `Die TODO-Liste liegt jetzt in: ${path}`,
179  todoInRepo: path =>
180    `${path} liegt in einem Git-Repo. Die TODO-Liste gehört nicht in eine Historie, /turbo todo datei <pfad> setzt einen anderen Ort.`,
181  todoNotes: {
182    'in-repo': 'Die Datei liegt in einem Git-Repo. /turbo todo datei <pfad> setzt einen anderen Ort.',
183    unreadable: 'Die Datei ließ sich nicht lesen oder schreiben.',
184  },
185  noticeTitle: 'Disclaimer',
186  notice:
187    'Turbo-MOD startet Programme auf Deinem Rechner, führt auf Knopfdruck git fetch und git pull in Deinen Repos aus und kann einen von Dir eingestellten Befehl starten. Du nutzt den Mod auf eigene Verantwortung und ohne Gewähr, siehe Lizenz (Apache 2.0).',
188  accept: 'Verstanden',
189  acceptFirst: 'Bitte zuerst den Hinweis oben im Pane bestätigen.',
190  reread: 'neu lesen',
191  reading: 'liest ...',
192  allClean: 'Alles sauber.',
193  unreadable: 'nicht lesbar',
194  notes: {
195    unreadable: 'Der Ordner ist nicht lesbar.',
196    empty: 'Keine Git-Repos in diesem Ordner.',
197  },
198  pickTitle: 'Ordner mit den Git-Repos',
199  colors: 'Theme',
200  commandDescription: 'Turbo-MOD: Pane ein- oder ausblenden, Farbschema, Sprache und Repo-Ordner setzen',
201  help: [
202    '/turbo                 Pane ein- oder ausblenden',
203    '/turbo todo <text>     Aufgabe anlegen, ohne Text: offene zählen',
204    '/turbo todo datei <pfad>  Datei der TODO-Liste setzen, ohne Pfad: anzeigen',
205    '/turbo theme <name>    Farbschema wählen, ohne Namen: Liste',
206    '/turbo repos <pfad>    Repo-Ordner hinzufügen, ohne Pfad: neu lesen',
207    '/turbo repos entfernen <pfad>  Repo-Ordner wieder entfernen',
208    '/turbo ticket <adresse>  Ticket-Adresse mit {id}, macht die Ticketnummer im Branch zum Link',
209    '/turbo feed <befehl>   Widget Neue Tickets: Befehl, der die Tickets als JSON ausgibt, "aus" schaltet ab',
210    '/turbo demo            Beispieldaten für ein Bildschirmfoto ein- oder ausblenden',
211    '/turbo sprache <de|en> Sprache des Panes',
212    '/turbo leeren          Liste der Dateien zurücksetzen',
213    '/turbo effekt          Titeleffekt aus- oder einschalten',
214  ].join('\n'),
215  hidden: 'Turbo-MOD ausgeblendet. /turbo blendet ihn wieder ein.',
216  shown: version => `Turbo-MOD ${version} eingeblendet.`,
217  cleared: 'Liste der Dateien geleert.',
218  effectOn: 'Titeleffekt läuft.',
219  effectOff: 'Titeleffekt aus.',
220  themeList: names => `Farbschemata: ${names}`,
221  themeUnknown: name => `Kein Farbschema "${name}". /turbo theme zeigt die Liste.`,
222  themeSet: name => `Farbschema: ${name}`,
223  rootMissing: 'Kein Repo-Ordner gesetzt. /turbo repos <pfad> fügt einen hinzu.',
224  reposResult: (total, root, dirty) => `${total} Repos unter ${root}, ${dirty} mit Änderungen.`,
225  languageSet: 'Sprache: Deutsch',
226  languageUnknown: name => `Keine Sprache "${name}". Es gibt de und en.`,
227  runFailed: (what, program) => `${what}: ${program} ließ sich nicht starten oder hat nicht geantwortet.`,
228  pickFailed: program =>
229    `Ordnerauswahl: ${program} ließ sich nicht starten. /turbo repos <pfad> setzt den Ordner von Hand.`,
230}
231
232const EN: Texts = {
233  files: 'Files',
234  fileCount: count => (count === 1 ? '1 file' : `${count} files`),
235  nothingWritten: 'Nothing written yet. Every file Claude creates or changes shows up here.',
236  gone: 'deleted',
237  more: count => `... and ${count} more`,
238  range: (from, to, total) => `${from}-${to} of ${total}`,
239  clearList: 'clear list',
240  open: 'open',
241  terminal: 'Terminal',
242  noTerminal: 'No splittable terminal found. Windows Terminal, tmux and kitty are supported.',
243  terminalHints: {
244    'kitty-remote-off':
245      'kitty found, but remote control is off. Set allow_remote_control and listen_on in kitty.conf and restart kitty.',
246    ghostty: 'Ghostty found. It cannot be split from outside, start Claude in tmux inside it.',
247  },
248  sheet: 'cheat sheet',
249  confirmClose: 'Really close?',
250  confirmRun: 'Really?',
251  compacted: 'Conversation compacted.',
252  hostFailed: what => `${what} could not be started from here. Type the command at the prompt.`,
253  actions: {
254    'split-left': 'Split left',
255    'split-right': 'Split right',
256    'split-down': 'Split down',
257    'new-tab': 'New tab',
258    'close-last': 'Close last pane',
259  },
260  repos: 'Repos',
261  reposCount: (dirty, total) => `${dirty} of ${total} with changes`,
262  noFolder: 'No folder set yet.',
263  pickFolder: 'choose folder',
264  addFolder: 'add folder',
265  fetchAll: 'fetch all',
266  fetching: 'fetching ...',
267  pull: 'pull',
268  pulled: name => `${name}: up to date with the server.`,
269  rootRemoved: root => `Repo folder removed: ${root}`,
270  rootUnknown: root => `No repo folder "${root}" set.`,
271  session: 'Claude',
272  context: 'Context',
273  of: 'of',
274  resets: 'Resets',
275  cost: 'Cost',
276  limits: { five_hour: 'Current session', seven_day: 'Current week', spend_limit: 'Budget' },
277  noReading: 'No figures yet. They arrive after the first answer.',
278  copyPath: 'path',
279  copyContent: 'content',
280  copied: what => `${what} is on the clipboard.`,
281  ticketSet: url => `Ticket address: ${url}`,
282  ticketNone: 'No ticket address set. Example: /turbo ticket https://jira.example.com/browse/{id}',
283  feed: 'New tickets',
284  feedCount: (count, since) => (since.length > 0 ? `${count} since ${since}` : String(count)),
285  feedEmpty: 'No new tickets.',
286  feedSet: command => `New tickets come from: ${command}`,
287  feedOff: 'New tickets switched off.',
288  demoOn: 'Sample data shown, none of it is real. /turbo demo hides it again.',
289  demoOff: 'Sample data hidden.',
290  feedNone: 'No command set. /turbo feed <command> switches the widget on, /turbo feed off switches it off.',
291  feedNotes: {
292    'no-json': 'The command did not print JSON.',
293    'no-start': 'The command could not be started or did not answer.',
294  },
295  todo: 'TODO',
296  todoOpen: open => (open === 0 ? '' : `${open} open`),
297  todoCount: open => (open === 1 ? '1 task open.' : `${open} tasks open.`),
298  todoEmpty: 'No tasks yet.',
299  todoPlaceholder: 'New task',
300  todoSave: 'save',
301  todoCancel: 'cancel',
302  todoTidy: done => `remove ${done} done`,
303  todoAdded: text => `Task added: ${text}`,
304  todoFailed: 'The file of the TODO list could not be written.',
305  todoFile: path => `The TODO list is kept in: ${path}`,
306  todoFileSet: path => `The TODO list is now kept in: ${path}`,
307  todoInRepo: path =>
308    `${path} lies inside a git repo. The TODO list does not belong in a history, /turbo todo file <path> sets another place.`,
309  todoNotes: {
310    'in-repo': 'The file lies inside a git repo. /turbo todo file <path> sets another place.',
311    unreadable: 'The file could not be read or written.',
312  },
313  noticeTitle: 'Disclaimer',
314  notice:
315    'Turbo-MOD starts programs on your machine, runs git fetch and git pull in your repos when you press the buttons, and can start a command you have set. You use the mod at your own risk and without warranty, see the license (Apache 2.0).',
316  accept: 'Understood',
317  acceptFirst: 'Please confirm the notice at the top of the pane first.',
318  reread: 'refresh',
319  reading: 'reading ...',
320  allClean: 'All clean.',
321  unreadable: 'unreadable',
322  notes: {
323    unreadable: 'The folder cannot be read.',
324    empty: 'No git repos in this folder.',
325  },
326  pickTitle: 'Folder with the git repos',
327  colors: 'Theme',
328  commandDescription: 'Turbo-MOD: show or hide the pane, set color scheme, language and repo folder',
329  help: [
330    '/turbo                  show or hide the pane',
331    '/turbo todo <text>      add a task, without text: count the open ones',
332    '/turbo todo file <path> set the file of the TODO list, without path: show it',
333    '/turbo theme <name>     pick a color scheme, without a name: the list',
334    '/turbo repos <path>     add a repo folder, without a path: refresh',
335    '/turbo repos remove <path>  remove a repo folder again',
336    '/turbo ticket <address>  ticket address with {id}, turns the ticket key in a branch into a link',
337    '/turbo feed <command>   widget New tickets: command that prints the tickets as JSON, "off" switches it off',
338    '/turbo demo             show or hide sample data for a screenshot',
339    '/turbo lang <de|en>     language of the pane',
340    '/turbo clear            reset the list of files',
341    '/turbo effect           switch the title effect off or on',
342  ].join('\n'),
343  hidden: 'Turbo-MOD hidden. /turbo shows it again.',
344  shown: version => `Turbo-MOD ${version} shown.`,
345  cleared: 'List of files cleared.',
346  effectOn: 'Title effect is running.',
347  effectOff: 'Title effect is off.',
348  themeList: names => `Color schemes: ${names}`,
349  themeUnknown: name => `No color scheme "${name}". /turbo theme shows the list.`,
350  themeSet: name => `Color scheme: ${name}`,
351  rootMissing: 'No repo folder set. /turbo repos <path> adds one.',
352  reposResult: (total, root, dirty) => `${total} repos under ${root}, ${dirty} with changes.`,
353  languageSet: 'Language: English',
354  languageUnknown: name => `No language "${name}". There are de and en.`,
355  runFailed: (what, program) => `${what}: ${program} could not be started or did not answer.`,
356  pickFailed: program => `Folder dialog: ${program} could not be started. /turbo repos <path> sets the folder by hand.`,
357}
358
359const ALL: Record<Lang, Texts> = { de: DE, en: EN }
360
361/** Finds a language by its code, ignoring case. */
362export const findLanguage = (name: string): Lang | undefined => {
363  const wanted = name.trim().toLowerCase()
364
365  return LANGUAGES.find(one => one === wanted)
366}
367
368export const textsFor = (lang: string): Texts => ALL[findLanguage(lang) ?? 'en']
369
hooks/theme.ts 63 lines
1// Translates a color scheme into the colors the pane needs - without $ and therefore directly testable.
2
3import { PALETTES } from './palettes'
4
5export const STANDARD = 'standard'
6
7export type Look = {
8  /** Title line. */
9  title: string
10  /** Header lines of the widgets. */
11  accent: string
12  /** Body text, undefined means: color of the terminal. */
13  text: string | undefined
14  ok: string
15  warn: string
16  bad: string
17  /** Area behind the pane, undefined means: background of the terminal. */
18  background: string | undefined
19  /**
20   * Area behind a button. A button takes no color, it draws in the text color
21   * of the terminal. On a light scheme that would be light on light, so there it gets
22   * the dark text color of the scheme as its ground.
23   */
24  chip: string | undefined
25}
26
27/** The colors of the host: they follow the theme set in Claude Code. */
28const HOST_LOOK: Look = {
29  title: 'claude',
30  accent: 'suggestion',
31  text: undefined,
32  ok: 'success',
33  warn: 'warning',
34  bad: 'error',
35  background: undefined,
36  chip: undefined,
37}
38
39export const themeNames = (): string[] => [STANDARD, ...PALETTES.map(palette => palette.name)]
40
41/** Finds a scheme by name, ignoring case. */
42export const findTheme = (name: string): string | undefined => {
43  const wanted = name.trim().toLowerCase()
44
45  return themeNames().find(one => one === wanted)
46}
47
48export const lookFor = (name: string): Look => {
49  const palette = PALETTES.find(one => one.name === name)
50  if (palette === undefined) return HOST_LOOK
51
52  return {
53    title: palette.primary,
54    accent: palette.accent,
55    text: palette.foreground,
56    ok: palette.success,
57    warn: palette.warning,
58    bad: palette.error,
59    background: palette.background,
60    chip: palette.dark ? undefined : palette.foreground,
61  }
62}
63
hooks/todo.ts 111 lines
1// The TODO list as a Markdown file - without $ and therefore directly testable.
2// One task per line: "- [ ] text". Every other line of the file stays as it is.
3
4import type { TodoItem } from '../types'
5
6/** Name of the list below the home folder. It lies outside every git repo on purpose. */
7export const TODO_FILE = '.claude/turbo-mod-todo.md'
8
9const ROW = /^\s*[-*]\s+\[( |x|X)\]\s+(.*)$/
10
11/** One line of text without line breaks and without spaces at the ends. */
12export const cleanTodoText = (text: string): string => text.replace(/\s+/g, ' ').trim()
13
14const parseRow = (row: string, line: number): TodoItem | undefined => {
15  const found = ROW.exec(row)
16  if (found === null) return undefined
17
18  const text = cleanTodoText(found[2] ?? '')
19  if (text.length === 0) return undefined
20
21  return { line, text, isDone: found[1] !== ' ' }
22}
23
24/** The text cut to the room it has, three dots mark the cut. A button does not shorten its label by itself. */
25export const fitTodoText = (text: string, room: number): string => {
26  const width = Math.max(4, room)
27
28  return text.length <= width ? text : `${text.slice(0, width - 3).trimEnd()}...`
29}
30
31/** Reads the tasks of the file in the order of their lines. Lines that are no task are skipped. */
32export const parseTodos = (content: string): TodoItem[] => {
33  const items: TodoItem[] = []
34  const rows = content.split(/\r?\n/)
35  for (let line = 0; line < rows.length; line += 1) {
36    const item = parseRow(rows[line] ?? '', line)
37    if (item !== undefined) items.push(item)
38  }
39
40  return items
41}
42
43/** A task as its line in the file. */
44export const formatTodo = (item: Pick<TodoItem, 'text' | 'isDone'>): string =>
45  `- [${item.isDone ? 'x' : ' '}] ${cleanTodoText(item.text)}`
46
47/** Open tasks first in the order of the file, the done ones below. */
48export const sortTodos = (items: readonly TodoItem[]): TodoItem[] =>
49  [...items].sort((a, b) => {
50    if (a.isDone !== b.isDone) return a.isDone ? 1 : -1
51
52    return a.line - b.line
53  })
54
55/** Appends a task. An empty text changes nothing. */
56export const addTodo = (content: string, text: string): string => {
57  const clean = cleanTodoText(text)
58  if (clean.length === 0) return content
59
60  const body = content.length === 0 || content.endsWith('\n') ? content : `${content}\n`
61
62  return `${body}${formatTodo({ text: clean, isDone: false })}\n`
63}
64
65// The file may have been edited by hand since the pane drew it. The task is therefore found by
66// its line and its text, and by its text alone if the line moved.
67const findRow = (rows: readonly string[], item: TodoItem): number => {
68  const atLine = parseRow(rows[item.line] ?? '', item.line)
69  if (atLine !== undefined && atLine.text === item.text) return item.line
70
71  return rows.findIndex((row, line) => parseRow(row, line)?.text === item.text)
72}
73
74/**
75 * Rewrites the line of one task, `undefined` removes it. A task that is no longer in the file
76 * changes nothing.
77 */
78export const changeTodo = (
79  content: string,
80  item: TodoItem,
81  change: (now: TodoItem) => Pick<TodoItem, 'text' | 'isDone'> | undefined,
82): string => {
83  const rows = content.split('\n')
84  const at = findRow(rows, item)
85  if (at < 0) return content
86
87  const now = parseRow(rows[at] ?? '', at)
88  if (now === undefined) return content
89
90  const next = change(now)
91  if (next === undefined) rows.splice(at, 1)
92  else if (cleanTodoText(next.text).length > 0) rows[at] = formatTodo(next)
93
94  return rows.join('\n')
95}
96
97/** Removes every task that is ticked off. */
98export const clearDoneTodos = (content: string): string =>
99  content
100    .split('\n')
101    .filter((row, line) => parseRow(row, line)?.isDone !== true)
102    .join('\n')
103
104/** Full path of the list below the home folder, with the slashes of that folder. */
105export const todoPathIn = (home: string): string => {
106  const base = home.replace(/[\\/]+$/, '')
107  const slash = base.includes('\\') ? '\\' : '/'
108
109  return `${base}${slash}${TODO_FILE.replace(/\//g, slash)}`
110}
111
hooks/palettes.ts 63 lines
1// Snapshot of textual-themes 0.15.2 (Apache-2.0, Michael Blaess).
2// Generated by tools/snapshot_palettes.py - do not edit by hand.
3
4export type Palette = {
5  name: string
6  title: string
7  dark: boolean
8  primary: string
9  secondary: string
10  accent: string
11  foreground: string
12  background: string
13  surface: string
14  panel: string
15  warning: string
16  error: string
17  success: string
18}
19
20export const PALETTES: readonly Palette[] = [
21  { name: 'brotkasten', title: 'Brotkasten', dark: true, primary: '#7C70DA', secondary: '#3A2B8A', accent: '#EDF171', foreground: '#D0CCFF', background: '#3A2B8A', surface: '#5446B8', panel: '#241870', warning: '#EDF171', error: '#C46C71', success: '#A9FF9F' },
22  { name: 'boing', title: 'Boing', dark: true, primary: '#FF8800', secondary: '#0055AA', accent: '#FF8800', foreground: '#FFFFFF', background: '#0055AA', surface: '#0066BB', panel: '#004499', warning: '#FFAA00', error: '#FF4444', success: '#44BB44' },
23  { name: 'gemstone', title: 'Gemstone', dark: false, primary: '#007700', secondary: '#555555', accent: '#009900', foreground: '#111111', background: '#E8E8E8', surface: '#F2F2F2', panel: '#DDDDDD', warning: '#AA8800', error: '#CC0000', success: '#007700' },
24  { name: 'classic-terminal', title: 'Classic Terminal', dark: true, primary: '#33FF33', secondary: '#2A7A2A', accent: '#88FF88', foreground: '#33FF33', background: '#0A0A0A', surface: '#162616', panel: '#0F1B0F', warning: '#FFAA00', error: '#FF4444', success: '#33FF33' },
25  { name: 'next', title: 'Next', dark: true, primary: '#9966CC', secondary: '#555555', accent: '#9966CC', foreground: '#E0E0E0', background: '#2A2A2A', surface: '#3A3A3A', panel: '#222222', warning: '#CC9933', error: '#CC4444', success: '#44AA44' },
26  { name: 'bebox', title: 'BeBox', dark: true, primary: '#FFD800', secondary: '#5F5F5F', accent: '#FFD800', foreground: '#E8E8E8', background: '#3A3A4A', surface: '#4A4A5A', panel: '#333344', warning: '#FF9900', error: '#DD3333', success: '#33BB33' },
27  { name: 'bunty', title: 'Bunty', dark: true, primary: '#DD4814', secondary: '#77216F', accent: '#E18B5C', foreground: '#F2EAEA', background: '#2C001E', surface: '#4A2540', panel: '#1F0014', warning: '#F99B11', error: '#DF382C', success: '#38B44A' },
28  { name: 'cupertino', title: 'Cupertino', dark: false, primary: '#007AFF', secondary: '#5856D6', accent: '#007AFF', foreground: '#1D1D1F', background: '#F5F5F7', surface: '#FFFFFF', panel: '#E8E8ED', warning: '#FF9500', error: '#FF3B30', success: '#34C759' },
29  { name: 'luna', title: 'Luna', dark: true, primary: '#0054E3', secondary: '#21A121', accent: '#0054E3', foreground: '#FFFFFF', background: '#003399', surface: '#0044AA', panel: '#002D8A', warning: '#FFCC00', error: '#E81123', success: '#21A121' },
30  { name: 'commandr', title: 'Commandr', dark: true, primary: '#FFFF55', secondary: '#55FFFF', accent: '#FFFF55', foreground: '#FFFFFF', background: '#0000AA', surface: '#1A1ACC', panel: '#000077', warning: '#FFAA00', error: '#FF5555', success: '#55FF55' },
31  { name: 'plan9', title: 'Plan 9', dark: false, primary: '#228844', secondary: '#4488AA', accent: '#228844', foreground: '#111111', background: '#FFFFEA', surface: '#EAFFFF', panel: '#D5E8D0', warning: '#BB8800', error: '#CC2222', success: '#228844' },
32  { name: 'motif', title: 'Motif', dark: true, primary: '#CC9966', secondary: '#5F7B8A', accent: '#CC9966', foreground: '#D8D0C8', background: '#3A4A5A', surface: '#455565', panel: '#303F4F', warning: '#CCAA44', error: '#CC5544', success: '#55AA66' },
33  { name: 'warp', title: 'Warp', dark: true, primary: '#00BBBB', secondary: '#3333AA', accent: '#00BBBB', foreground: '#D0D0D0', background: '#1A1A4E', surface: '#25255E', panel: '#141442', warning: '#DDAA22', error: '#DD4444', success: '#44BB66' },
34  { name: 'geeko', title: 'Geeko', dark: true, primary: '#73BA25', secondary: '#35B9AB', accent: '#73BA25', foreground: '#EEEEEE', background: '#173F0F', surface: '#1E4D15', panel: '#12330B', warning: '#F0A30A', error: '#DD3333', success: '#73BA25' },
35  { name: 'minty', title: 'Minty', dark: true, primary: '#8BB158', secondary: '#6DAB76', accent: '#8BB158', foreground: '#E8E8E8', background: '#2B2B2B', surface: '#363636', panel: '#232323', warning: '#E5A50A', error: '#CC3333', success: '#8BB158' },
36  { name: 'crimson', title: 'Crimson', dark: true, primary: '#CC0000', secondary: '#A30000', accent: '#EE0000', foreground: '#E0E0E0', background: '#1A0A0A', surface: '#2A1515', panel: '#140808', warning: '#EEA500', error: '#FF4444', success: '#44AA44' },
37  { name: 'razzy', title: 'Razzy', dark: true, primary: '#C51A4A', secondary: '#6CC24A', accent: '#C51A4A', foreground: '#EEEEEE', background: '#1E1E2E', surface: '#2A2A3A', panel: '#181828', warning: '#E5A50A', error: '#DD3333', success: '#6CC24A' },
38  { name: 'beastie', title: 'Beastie', dark: true, primary: '#AB2B28', secondary: '#5E8AAA', accent: '#AB2B28', foreground: '#D4D4D4', background: '#1C2028', surface: '#262A32', panel: '#161A20', warning: '#CC9933', error: '#DD4444', success: '#55AA66' },
39  { name: 'fifty-eight', title: 'Fifty-Eight', dark: true, primary: '#C9A96E', secondary: '#6A6A6A', accent: '#9E1B25', foreground: '#E8C985', background: '#100C08', surface: '#1E1914', panel: '#080605', warning: '#C9A048', error: '#B8252E', success: '#6A9A5A' },
40  { name: 'bluesy', title: 'Bluesy', dark: true, primary: '#D4AF37', secondary: '#1E4FA0', accent: '#F0C85A', foreground: '#F5D76E', background: '#081F54', surface: '#0E2E6E', panel: '#04133A', warning: '#E8A838', error: '#DD3344', success: '#48B870' },
41  { name: 'goldfinder', title: 'Goldfinder', dark: true, primary: '#E6B800', secondary: '#8A6E20', accent: '#FFD740', foreground: '#E8DFC0', background: '#080705', surface: '#18140A', panel: '#040302', warning: '#E8A838', error: '#CC4040', success: '#5AAA5A' },
42  { name: 'goldrunner', title: 'Goldrunner', dark: true, primary: '#C8A93A', secondary: '#C788CE', accent: '#E8C547', foreground: '#EEEECA', background: '#080520', surface: '#1A0F3D', panel: '#120A2E', warning: '#B06400', error: '#D6456A', success: '#5FA82E' },
43  { name: 'hercules', title: 'Hercules', dark: true, primary: '#FF9A2E', secondary: '#A85F12', accent: '#FFC470', foreground: '#F5A742', background: '#0B0A09', surface: '#1D1B19', panel: '#12110F', warning: '#FFC470', error: '#FF4A1F', success: '#F5A742' },
44  { name: 'hulkula', title: 'Hulkula', dark: true, primary: '#2BA841', secondary: '#BCC4CA', accent: '#4DC962', foreground: '#F0F2EE', background: '#083C14', surface: '#104B1B', panel: '#042608', warning: '#D4A040', error: '#CC2222', success: '#4DC962' },
45  { name: 'flughund', title: 'Flughund', dark: true, primary: '#244B85', secondary: '#BCC4CA', accent: '#3D6FB8', foreground: '#F0F2F5', background: '#060810', surface: '#0E1422', panel: '#030509', warning: '#D4A040', error: '#CC3030', success: '#50AA50' },
46  { name: 'classic-navy', title: 'Classic Navy', dark: true, primary: '#C0C5CC', secondary: '#1E4585', accent: '#9E3A42', foreground: '#EEF0F5', background: '#0C2B5C', surface: '#143465', panel: '#061A3A', warning: '#D4A040', error: '#B04048', success: '#50AA50' },
47  { name: 'brick', title: 'Brick', dark: false, primary: '#8E2A5E', secondary: '#5A4858', accent: '#D63B68', foreground: '#241F28', background: '#D4CEBC', surface: '#E2DCCA', panel: '#B2AC9A', warning: '#C85820', error: '#A0203A', success: '#4A7A3A' },
48  { name: 'clipper', title: 'Clipper', dark: false, primary: '#1A4FA0', secondary: '#C61F2C', accent: '#D4222F', foreground: '#1A1A1A', background: '#F6F3E8', surface: '#FCFAF0', panel: '#EBE6D4', warning: '#C88A20', error: '#C61F2C', success: '#2E8B3D' },
49  { name: 'synthwave', title: 'Synthwave', dark: true, primary: '#FF2E93', secondary: '#7B2D8E', accent: '#05D9E8', foreground: '#F5E9FF', background: '#1A0B3D', surface: '#261553', panel: '#0E0524', warning: '#FFD319', error: '#FF3860', success: '#39FF14' },
50  { name: 'miami', title: 'Miami', dark: true, primary: '#FF6FAB', secondary: '#1FB8BC', accent: '#FFA06A', foreground: '#FFE8E0', background: '#0B2F3F', surface: '#124050', panel: '#051825', warning: '#FFD76B', error: '#E63970', success: '#4ECDA8' },
51  { name: 'racing', title: 'Racing', dark: true, primary: '#1A5CC8', secondary: '#C0C6D0', accent: '#E42030', foreground: '#EEF0F5', background: '#14161E', surface: '#1F232E', panel: '#080A10', warning: '#E8A838', error: '#E42030', success: '#3AAA4A' },
52  { name: 'metropolis', title: 'Metropolis', dark: true, primary: '#E02030', secondary: '#1A5CC8', accent: '#FFD53B', foreground: '#F0F2F8', background: '#0A2A5E', surface: '#123876', panel: '#051838', warning: '#FFD53B', error: '#C80A18', success: '#3AAA4A' },
53  { name: 'spiderized', title: 'Spiderized', dark: true, primary: '#D71920', secondary: '#1F75FE', accent: '#1F75FE', foreground: '#FFFFFF', background: '#0E1A3A', surface: '#1A2C5F', panel: '#070D24', warning: '#FFA830', error: '#C80A18', success: '#4AA85A' },
54  { name: 'ascot', title: 'Ascot', dark: true, primary: '#F2C200', secondary: '#C0C5CC', accent: '#F2C200', foreground: '#F5EBD2', background: '#173E2D', surface: '#1F4E3A', panel: '#0E2C1E', warning: '#F2C200', error: '#C81E2A', success: '#2E7D52' },
55  { name: 'joker', title: 'Joker', dark: true, primary: '#7B3FB2', secondary: '#2FCC2F', accent: '#FFC72C', foreground: '#F5F0E5', background: '#0E0824', surface: '#1F0F3F', panel: '#2D1758', warning: '#FFC72C', error: '#DC4040', success: '#2FCC2F' },
56  { name: 'marley', title: 'Marley', dark: true, primary: '#078930', secondary: '#DA121A', accent: '#FCDD09', foreground: '#F5EFD8', background: '#0C0A06', surface: '#181818', panel: '#050505', warning: '#FCDD09', error: '#DA121A', success: '#078930' },
57  { name: 'lenseflare', title: 'Lenseflare', dark: true, primary: '#FF8C42', secondary: '#2BD0E0', accent: '#E5283A', foreground: '#F0E5D2', background: '#0A1226', surface: '#14213D', panel: '#060B18', warning: '#FFB838', error: '#E5283A', success: '#2BD0E0' },
58  { name: 'platoon', title: 'Platoon', dark: true, primary: '#9AA04A', secondary: '#6F8A3C', accent: '#C7B06A', foreground: '#E4E0CF', background: '#12130B', surface: '#22241A', panel: '#3A3D22', warning: '#E0B330', error: '#BF3B2A', success: '#6F9A4A' },
59  { name: 'corleone', title: 'Corleone', dark: true, primary: '#A88B52', secondary: '#4A4E58', accent: '#9A8147', foreground: '#C3C0B4', background: '#0B0C0E', surface: '#16181C', panel: '#1F2228', warning: '#B89043', error: '#8C2F2F', success: '#5E7355' },
60  { name: 'golden-brown', title: 'Golden Brown', dark: true, primary: '#A8843F', secondary: '#6E4E36', accent: '#C29A4E', foreground: '#D5C5A4', background: '#0F0B07', surface: '#1C1611', panel: '#2B2018', warning: '#BE8F39', error: '#9A2B2B', success: '#5F6B42' },
61  { name: 'christophorus', title: 'Christophorus', dark: true, primary: '#D4A15A', secondary: '#50698A', accent: '#E0B574', foreground: '#E6E9EE', background: '#102640', surface: '#132D4B', panel: '#1A3A5E', warning: '#E8B45A', error: '#FF6B8B', success: '#8FD16A' },
62]
63
types/index.d.ts 156 lines
1export type FileEntry = {
2  /** Absolute path, exactly as the tool received it. */
3  path: string
4  /** Bytes after the last write. */
5  size: number
6  /** Last change, milliseconds since 1970. */
7  mtimeMs: number
8  /** True if the file was newly created in this session. */
9  isNew: boolean
10  /** How often the file was written in this session. */
11  writes: number
12  /** Running number in order of the first write, from 1. Stays the same on later writes. */
13  no: number
14  /** True once the file no longer exists. The entry stays in the list, struck through. */
15  isGone?: boolean
16}
17
18export type HostInfo = {
19  /** Operating system, detected via `OS` and `uname -s`. */
20  os: 'windows' | 'mac' | 'linux'
21  /** Terminal that can be split from outside: Windows Terminal, tmux, kitty or none. */
22  terminal: 'wt' | 'tmux' | 'kitty' | 'none'
23  /** Why a terminal that was recognized still cannot be split, the key of its text in texts.ts. */
24  hint?: 'kitty-remote-off' | 'ghostty'
25}
26
27export type RepoEntry = {
28  /** Root folder the repo was found under. */
29  root: string
30  /** Full path of the repo. */
31  dir: string
32  /** Folder name under the root folder. */
33  name: string
34  /** Current branch, "(detached)" for a detached HEAD. */
35  branch: string
36  /** Commits ahead of the upstream, as of the last fetch. */
37  ahead: number
38  /** Commits behind the upstream, as of the last fetch. */
39  behind: number
40  /** Changed and staged entries of files git knows. */
41  changed: number
42  /** Files git does not know yet. */
43  untracked: number
44  /** False if `git status` failed for this repo. */
45  isRead: boolean
46}
47
48export type ReposState = {
49  /** Root folders of the repos, empty as long as none is set. */
50  roots: string[]
51  /** True while a run also fetches every repo from its server. */
52  isFetching: boolean
53  /** Full path of the repo that is being pulled right now, otherwise empty. */
54  pulling: string
55  list: RepoEntry[]
56  /** Time of the last run, 0 as long as none has run. */
57  checkedAt: number
58  isBusy: boolean
59  /** Key of a note for the display ("unreadable", "empty"), otherwise empty. */
60  note: string
61}
62
63export type FeedTicket = {
64  key: string
65  summary: string
66  /** Address of the ticket, empty if the feed gives none. */
67  url: string
68}
69
70export type FeedState = {
71  /** Command line that prints the tickets as JSON, empty turns the widget off. */
72  command: string
73  list: FeedTicket[]
74  /** First day the feed covers, ISO date, empty if the feed does not say. */
75  since: string
76  /** Time of the last run, 0 as long as none has run. */
77  checkedAt: number
78  isBusy: boolean
79  /** What the feed or the mod has to say about a failed run, otherwise empty. */
80  note: string
81}
82
83export type TodoItem = {
84  /** Line of the task in the file, from 0. */
85  line: number
86  text: string
87  isDone: boolean
88}
89
90export type TodoState = {
91  /** Full path of the Markdown file that holds the list, empty until the start has run. */
92  path: string
93  list: TodoItem[]
94  /** What the field in the pane edits: -2 nothing, -1 a new task, otherwise the line of a task. */
95  editing: number
96  /** Time of the last reading, 0 as long as none has run. */
97  checkedAt: number
98  /** Key of a note for the display ("in-repo", "unreadable"), otherwise empty. */
99  note: string
100}
101
102export type UsageLimit = {
103  /** Name of the window as the host reports it, for example "five_hour". */
104  kind: string
105  percentUsed: number
106  /** When the window resets, ISO 8601, empty if the host does not say. */
107  resetsAt: string
108}
109
110export type UsageState = {
111  /** Time of the reading, 0 as long as there is none. */
112  measuredAt: number
113  /** Tokens in the context window right now. */
114  tokens: number
115  /** Size of the context window of the model. */
116  window: number
117  limits: UsageLimit[]
118  /** Cost of the session in US dollars, -1 where the host keeps no ledger. */
119  usd: number
120}
121
122declare module 'claude-code' {
123  interface PluginState {
124    'turbo-mod': {
125      files: FileEntry[]
126      /** Page of the file list that is shown, from 0. A new write goes back to 0. */
127      filePage: number
128      /** Per widget: true means collapsed. */
129      collapsed: Record<string, boolean>
130      repos: ReposState
131      host: HostInfo
132      /** Name of the color scheme, "standard" follows the theme of Claude Code. */
133      theme: string
134      /** The title as it is currently drawn (runs through an effect at intervals). */
135      title: string
136      /** True once the state is restored. False again after the host dropped it, as on /clear. */
137      ready: boolean
138      /** True once the notice of the first start is confirmed on this machine. */
139      accepted: boolean
140      /** Step of the moving dots behind a busy label, 0 to 2. */
141      pulse: number
142      /** Key of the button currently waiting for the second confirmation, otherwise empty. */
143      armed: string
144      /** Language of the pane, "de" or "en". */
145      lang: string
146      /** Full path of the editor, empty if it was not found on this machine. */
147      editorPath: string
148      usage: UsageState
149      feed: FeedState
150      todo: TodoState
151      /** Address of a ticket with the placeholder {id}, empty if none is set. */
152      ticketUrl: string
153    }
154  }
155}
156