One mod for Claude Code, Windows and CJK first: pasted-image and text previews in any terminal, themed replies with CJK-correct tables and charts, long edit…

<img src="docs/banner.svg" alt="tessera: one Claude Code mod for every terminal" width="100%">
<a href="https://github.com/OG-Matcha/tessera/actions/workflows/ci.yml"><img src="https://github.com/OG-Matcha/tessera/actions/workflows/ci.yml/badge.svg" alt="CI"></a> <a href="https://github.com/OG-Matcha/tessera/releases"><img src="https://img.shields.io/github/v/release/OG-Matcha/tessera?color=89b4fa" alt="Release"></a> <a href="LICENSE"><img src="https://img.shields.io/github/license/OG-Matcha/tessera?color=a6e3a1" alt="MIT license"></a> <img src="https://img.shields.io/badge/Claude_Code-%E2%89%A52.1.292-cba6f7" alt="Claude Code 2.1.292 or later"> <img src="https://img.shields.io/badge/Windows%20%C2%B7%20macOS%20%C2%B7%20Linux-tested-94e2d5" alt="Windows, macOS and Linux">
<img src="docs/demo.gif" alt="tessera in Claude Code: a pasted 30-line log previewed above the prompt, a reply with a CJK-aligned table, the Traditional Chinese guard refusing a Simplified write, then a 32-line edit folded to its first changes" width="760">
English · <a href="README.zh-TW.md">繁體中文</a>
tessera is a Claude Code mod that makes the terminal show what Claude Code hides and stops the mistakes that cost work: pasted images and text you can actually see, replies drawn with CJK-correct tables and diagrams, and guards for long multi-agent runs. One install, every feature switchable, nothing running that you turned off.
| Problem | Where it is reported | tessera |
|---|---|---|
A pasted image shows as [Image #1] in most terminals | Thumbnails above the prompt: real pixels in kitty and Ghostty, cell art everywhere else | |
Pasted text collapses to [Pasted text #1 +40 lines] before you send it | #23134 | Its first lines shown above the prompt |
Korean, Chinese or Japanese written as \uXXXX comes out as wrong characters | #83033 | Such tool calls are refused before they write; in code, where an escape can be meant, reminded once |
An edit to a Big5, Shift-JIS or GBK file rewrites it with � where its text was | #7134 | A reminder once before the edit, saying whether the file is UTF-16 or a legacy code page (Big5, Shift-JIS, GBK, EUC-KR) |
| A command Claude moved to the background hangs, and nothing says so until you ask | A row above the prompt after ten quiet minutes, with a button that asks Claude to look | |
| Claude answers a Chinese question in English because the pasted log was English | Replies follow the language of your own words | |
| Claude writes Simplified characters or zh-CN terms into a Traditional Chinese project | The write is refused once, with the zh-TW forms | |
A new session or /clear loses track of what was left to do | The unfinished tasks are offered back above the prompt | |
| A long edit fills the screen with its diff | The first lines of what was removed and added, the counts, and an expand button | |
| The Read tool does not say which file it read | #21151 | Tool rows name the file |
| Copying from the terminal brings indentation and trailing spaces | #18170 | Copy buttons and /tessera copy copy clean text |
claude plugin marketplace add OG-Matcha/tessera
claude plugin install tessera@og-matcha --scope user
Start a new session, then run /tessera setup to pick the features you want.
To get new releases automatically, open /plugin, go to Marketplaces, choose og-matcha and select Enable auto-update. Claude Code leaves auto-update off for marketplaces other than Anthropic's own; tessera reminds you of it once, above the prompt, with a button that opens /plugin. Without it, update by hand:
claude plugin marketplace update og-matcha
claude plugin update tessera@og-matcha
Installed before 0.8.0 as tessera@tessera? The marketplace was renamed from tessera to og-matcha, so that another plugin named tessera can be added beside it, and the old install no longer updates. Move it once:
claude plugin uninstall tessera@tessera
claude plugin marketplace remove tessera
claude plugin marketplace add OG-Matcha/tessera
claude plugin install tessera@og-matcha --scope user
Claude Code keeps a plugin's option values with its install ID, so pick yours again with /tessera setup or /plugin configure tessera@og-matcha.
[!IMPORTANT] tessera includes the reply rendering of prismantis and the paste preview idea of cc-mod-image-view. Uninstall those two first; two mods drawing the same part of the screen fight over it.
To give every contributor of one repository tessera, put these two keys in the repository's .claude/settings.json. Claude Code registers the marketplace once a contributor trusts the folder, and because tessera's marketplace lists it by a relative path, it loads from the marketplace copy from the next session on, with no install step:
{
"extraKnownMarketplaces": {
"og-matcha": { "source": { "source": "github", "repo": "OG-Matcha/tessera" } }
},
"enabledPlugins": { "tessera@og-matcha": true }
}
Option values can go beside them, under pluginConfigs, so the team shares one setup:
{
"pluginConfigs": { "tessera@og-matcha": { "options": { "guardGlossary": true, "language": "zh-TW" } } }
}
For a whole organization, the same extraKnownMarketplaces and enabledPlugins keys go into managed settings, with "autoUpdate": true on the marketplace entry if you want releases to reach every machine. Two things to know before you do:
allowManagedModsOnly refuses every mod installed from GitHub, tessera included. To run it as the organization's own, copy a release of this repository to an administrator-only directory on each machine and register that directory as the marketplace ("source": { "source": "directory", "path": "/opt/claude-plugins/tessera" }); tessera's marketplace lists it by a relative path, which is what makes it count as yours.PreToolUse hook in managed settings.Before rolling it out, claude plugin validate . in a checkout lists every event tessera handles and every file, process, environment and settings call it makes, which SECURITY.md explains line by line.
| Feature | Default | What it does |
|---|---|---|
| Themed replies | on | Tables, headings, highlighted code, mermaid diagrams and charts, tool rows, copy buttons; 16 themes |
| Fold long diffs | on | An Edit or Write diff over 12 lines shows up to 8 lines (the first of what was removed and of what was added), the counts, and expand; ctrl+o and --verbose show it whole. diffLines sets how many lines; 0 folds every edit to one line: its tool row carries the counts (+73 -19) and expand, and nothing is drawn below it. The files a shell command changed (Claude Code 2.1.296 on) fold the same way under the command's output, one row per file. Display only: what Claude reads is unchanged |
| Paste previews | on | Image thumbnails and collapsed pasted text above the prompt (the text is read from the clipboard and shown only when it matches the paste's line count); "original" opens the full image in an Orca tab, a VS Code tab or your system viewer |
| Reply in my language | on | When your own words are Chinese, Japanese or Korean, Claude replies in that language; pasted code, logs and quotes do not count |
| Carry over tasks | on | A new session, or the conversation after /clear, offers the tasks the last one in this repository left open: continue puts them in the prompt box, dismiss forgets them. It turns on Claude's task tools for the session (CLAUDE_CODE_ENABLE_TODO_TOOLS), which Claude Code leaves off for Claude 5.x, unless you set that variable yourself; Claude may then keep a task list on screen (Ctrl+T hides it) |
| CJK escape guard | on | Refuses Korean, Chinese or Japanese written as \uXXXX escapes in prose files and prompts; in code, where an escape can be meant, reminds once |
| Stash before discarding | off | When a discard the tree guard reminded about (git reset --hard, git checkout -- <paths>, git restore) is sent again, the tracked changes it throws away go into git stash first (stash@{0}), so git stash pop brings them back, or git checkout stash@{0} -- <file> for a discard of some files (pop refuses while the other changes are still in the tree); a toast says so. This writes into the repository's .git. git clean gets no snapshot, since a stash holds no untracked files |
| Database guard | on | Reminds once before a command that throws a database or its volumes away: prisma migrate reset, supabase db reset, rails db:drop, artisan migrate:fresh, docker compose down -v, docker volume rm, dropdb and their kin; sent again, it runs |
| Encoding guard | on | Before an edit to an existing file (up to 1 MiB) that is not UTF-8 (Big5, Shift-JIS, GBK, EUC-KR, UTF-16), reminds once that Claude Code reads and writes files as UTF-8 and would rewrite its text as � (#7134); sent again, the edit goes through and the file is not checked again that session |
| Session guard | on | Before Claude edits a file that another Claude Code session on this machine edited in the last 30 minutes, reminds once that the other session may still be working in it, so Claude reads it again first or asks you; sent again, the edit goes through. Only sessions with tessera count: edits in your editor are not seen |
| Traditional Chinese guard | auto | While you write Traditional Chinese, reminds once before Simplified characters or zh-CN terms go into a file and names the zh-TW forms (这→這, 服務器→伺服器); zh-CN files, files already in Simplified, terms the file already uses and Japanese lines are left alone |
A prompt Claude writes for another agent or tool draws as a card with a token estimate and a copy button.
On by default and quiet until they matter.
| Feature | Default | What it does |
|---|---|---|
| Watch background work | on | When a command Claude runs in the background writes nothing for ten minutes (backgroundQuietMinutes), one row above the prompt says so, however many are quiet: ask Claude fills the prompt box with a request to check them, ignore drops the row, and so does the next message you send; a task that ends takes itself off it. A hung command otherwise reports nothing until you ask |
| Cache clock | on | When the prompt cache is about to go cold (ten minutes left; cacheClockMinutes moves it, 60 keeps the row up from the end of every turn), one dim row above the prompt counts the minutes down and says what the next message re-caches once it is cold; while a turn runs it says nothing. An hour on a subscription, five minutes on an API key, told apart by the rate-limit windows |
| Python in UTF-8 | on | On Windows, sets PYTHONUTF8=1 for the session, so the Python that Claude runs reads and writes UTF-8 instead of the system code page, where CJK text fails with UnicodeEncodeError or prints as ?; nothing is set when you set the variable yourself, and nothing happens elsewhere |
| Tree guard | on | Refuses a recursive delete of the root, a drive, your home directory, or the session's directory or one above it, recursive deletes through links, and links to node_modules; reminds once before a force push to main or master, and before git reset --hard, git checkout -- <paths>, git restore or git clean -f throws away uncommitted work, naming the files; while agents run, refuses tree rewrites and git add -A in the main tree |
| Prompt log | on | /tessera log opens a pane beside the fullscreen transcript that lists every prompt you sent in this session, newest first: what you typed, slash commands, pastes (their text, not the placeholder) and prompts sent through Remote Control, each with its time and the first line of the reply in a preview. Enter scrolls the transcript back to it and lights the row for a second; f puts it back in the prompt, the way to reuse one the screen no longer keeps; each keeps its first 10,000 characters, as many as Claude Code's prompt box takes. A green dot marks the prompts on screen now. Kept in memory only, never written to disk; /clear empties it, and a restart or --resume starts it empty |
| Mask secrets | on | API keys, tokens, private keys, URL passwords and values given to a secret-sounding name (API_KEY=, "password":) in a tool's result show as •••••••• to Claude, in the transcript and on screen, by pattern, with a note that tells Claude so; code (process.env.KEY, ${TOKEN}), placeholders and an error result are left alone. A safety net, not a scanner: a shape it does not know goes through, and a line Claude never saw whole it cannot edit, so that one is yours |
| Heredoc guard | on | Reminds once before a Bash heredoc with an unquoted delimiter (<<EOF) whose body the shell would change: ${x}, $(cmd) and backticks expanded, \\ turned into \; sent again, it runs |
| Model per agent | auto | An agent with no model gets haiku, sonnet, opus or fable picked from its task by a short Haiku call, with a toast naming it; choose asks Claude to name one instead. A Workflow script without models is reminded once to name one per agent(); with choose or a fixed model it is refused until it does |
Off by default, for particular workflows. Turn them on in /tessera setup.
| Feature | Default | What it does |
|---|---|---|
| Glossary guard | off | When the repository's CLAUDE.md has a table with Use and Avoid columns, reminds once before a write brings in an avoided wording and names the term to use; does nothing without such a table |
| Workflows quote you | off | A Workflow script must carry your own words, so its agents keep your standing instruction |
| Client feedback inbox | off | Pasted chat logs (22:55 Name message) become numbered items; a complaint like a fixed item is flagged as a likely regression |
| Command | Does |
|---|---|
/tessera setup | Switch features on and off |
/tessera log | Find a prompt you sent in this session and jump back to it (Tab or j k to select, Enter to jump, f to put it back in the prompt) |
/tessera peek <file> | Preview Markdown, CSV, JSON, docx, xlsx or pptx in the terminal |
/tessera copy · copy code · copy prompt | Copy the last reply, its last code block, or its prompt card |
/tessera inbox · inbox fixed 3 5 | List the feedback inbox, mark items fixed at the current commit |
/tessera theme <name> | Switch theme |
/tessera demo | Show every element tessera draws |
/tessera record · record off | Record mode, for a screen that is recorded, streamed or shared: in what tessera draws (replies, your prompts, tool rows, folded diffs, paste previews, the prompt log), API keys and tokens (sk-ant-, ghp_, AKIA, JWTs and their kin), Bearer headers, passwords in URLs and in PASSWORD= lines, emails and phone numbers show as ••••; a status line under the prompt says so. What Claude Code draws itself (tool results, permission dialogs, the prompt box, the full transcript under ctrl+o) is not masked. Screen only: the transcript, what Claude reads and /tessera copy are unchanged, and copy buttons copy what is shown |
| Terminal | Image previews | "original" opens in |
|---|---|---|
| kitty, Ghostty | real pixels | system viewer |
| Windows Terminal, iTerm2, Apple Terminal, SSH | cell art | system viewer (explorer, open, xdg-open) |
| Orca | cell art | an Orca browser tab |
| VS Code, Cursor | cell art | a VS Code tab |
| inside tmux or screen | cell art | as above |
| WSL | cell art | Windows viewer through \\wsl.localhost |
If detection is wrong, set imageMode to pixels or cells in /config. Orca can draw kitty graphics but not yet the Unicode placeholders Claude Code uses (stablyai/orca#23615).
A mod's hooks run in every kind of session that loads the plugin; what it draws appears only where Claude Code draws mods. The table is Claude Code's; this is what it means for tessera:
| Where you run Claude Code | Guards, options, carry-over, background watch | Previews, themed replies, folded diffs, the bands above the prompt |
|---|---|---|
| A terminal, including an editor's integrated terminal and the JetBrains plugin | yes | yes; this is where tessera is tested |
| The Code tab of the Desktop app | yes | themed replies and folded diffs, drawn with the Desktop app's own elements; the previews and the bands above the prompt are terminal-only; nothing there is tested |
| A WSL session in the Desktop app | no, plugins are not available there | no |
| The VS Code extension's chat panel | yes | no, nothing a mod draws appears there |
claude -p and the Agent SDK | yes | no |
| Remote Control from claude.ai or the phone | yes, in the session on your machine | in the terminal on your machine |
| A cloud session | only when the plugin reaches that session | no |
No network requests of its own: the one model call, a short Haiku classification per Agent call that names no model (agentModel: auto, the default), goes through your Claude Code session. It reads your Claude Code settings (the language setting and whether tessera's marketplace auto-updates), Claude Code's paste cache, Workflow scripts when one starts, files you peek, the repository's CLAUDE.md for a glossary table, a file Claude is about to write Simplified characters, zh-CN terms or avoided glossary wordings into, the bytes of a file Claude is about to edit, to tell its encoding, and once at start Claude Code's own list of running sessions, to tell whether the session that left tasks open is still running; it runs git rev-parse, on Windows a junction listing before a recursive delete, git status, git diff or git clean -n before a git command that discards changes, with stash-before-discard on git stash create and git stash store before an answered discard runs, a clipboard read once per collapsed text paste, and your platform's viewer when you ask for an original; while a command Claude moved to the background runs, it reads the size of that command's output file once a minute; while carry-over is on it sets CLAUDE_CODE_ENABLE_TODO_TOOLS=1 for the session, and on Windows PYTHONUTF8=1 while Python in UTF-8 is on, each unless you set it yourself, and writes nothing to your settings. Details in SECURITY.md.
Does it slow Claude Code down? A feature that is off registers no hooks and no timers. Paste previews check the prompt box four times a second while on.
Does it add tokens? Little, and only where it says. Measured on Claude Code 2.1.294 against a first request of about 55,000 tokens:
| Feature | Adds | When |
|---|---|---|
Diagram hint (themed replies, diagramHints) | about 300 tokens | once per context, again after a compaction |
| Reply in my language | about 70–100 tokens | once per context, again when your language changes or Claude's last reply drifted |
| Guards | the refusal's reason, a short paragraph | only when a call is refused |
| Model per agent | one separate Haiku call with the agent's task (its first 2,000 characters) | each Agent call without a model; nothing in your conversation |
| Carry over tasks | no measurable change: Claude Code loads the task tools on demand | |
| Watch background work | nothing, until you press ask Claude and send the prompt it fills in | |
| Client feedback inbox | a note naming the filed items | when you paste a chat log |
| Themed replies, paste previews, fold long diffs | nothing: display only |
Each one can be switched off in /tessera setup or /config.
Why not just install prismantis and cc-mod-image-view? You can, if you use macOS or Linux and a kitty-graphics terminal. tessera exists for everything else: Windows, CJK, terminals without image protocols, and long agent runs.
Reply rendering is adapted from prismantis by Nahum Litvin; the paste-cache lookup follows cc-mod-image-view by gggodlin, itself from claude-image-view by Jarrod Watts; PNG and zip inflation use fflate. All MIT; see NOTICE.
Issues and pull requests are welcome in English or Chinese. Read CONTRIBUTING.md first; the code of conduct applies. Questions go to Discussions (SUPPORT.md); every release is listed in CHANGELOG.md.
hooks/register.tsx 905 lines1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, MatchedHook, On, Register, RenderElement, Timer } from 'claude-code'
3
4import type { CarryOver, LoggedPrompt, PromptLogView, Quiet, UpdateOffer } from '../types'
5import type { Env } from './platform'
6import { platformOf } from './platform'
7import type { InboxItem } from './inbox'
8import { intake, intakeNote, listText, markFixed, parseChat } from './inbox'
9
10import { parse } from './markdown'
11import { boxArt, mermaidFit, unpad } from './mermaid'
12import type { CopyKind, Drawn } from './render'
13import { breakUnits, remember, renderBlocks, renderExpandedShell, renderFoldedDiff, renderShellEdits, renderToolGroup, renderToolRow, renderTurnDuration, renderUserPrompt, shortPath } from './render'
14import { helpText, rtlShowcaseText, showcaseText } from './help'
15import { helpTextZh, showcaseTextZh } from './help-zh'
16import type { CarryStore, TaskLog } from './carry'
17import { REPOSITORIES_KEPT, carriedFrom, endSession, recordSession, restoredTasks, staleCarryKeys } from './carry'
18import { pickLang } from './i18n'
19import { session, t } from './session'
20import { isAbsolute } from './guard'
21import { configureGuards, guardAgent, guardToolCall, guardWorkflow } from './guard-hooks'
22import { configurePastes, pasteBand, startPastes } from './paste-hooks'
23import { background, configureBackgroundWatch, forgetStopped, quietBand, watchShell } from './background-hooks'
24import { cacheBand, configureCacheClock, forgetCache, warmCache } from './cache-hooks'
25import { PANE_COLUMNS, configurePromptLog, logArrows, logClosed, logCommand, logFocus, logPane, logPrompt, logReply, logScreen } from './prompt-log-hooks'
26import { isOwn, isRealRow, withRows } from './prompt-log'
27import { notifiedTask } from './background'
28import { EDITS, asEditLog, rekeyed } from './edits'
29import { FEATURES } from './features'
30import type { Folded } from './fold'
31import { editCounts, foldPatch, hunkCounts, patchOf, shellEdits } from './fold'
32import { mask, maskValues } from './mask'
33import { MARKETPLACE, marketplaceRenamed, marketplaceWithoutUpdates } from './update'
34import { peek } from './peek'
35import type { Voice } from './voice'
36import { replyNote, voiceOf } from './voice'
37import { PRESET_NAMES } from './presets'
38import type { Style } from './theme'
39import { resolveStyle } from './theme'
40import type { Terminal } from './rtl'
41import { TERMINALS, hasRtl } from './rtl'
42
43const carryOver = atom({ plugin: 'tessera', key: 'carryOver' } as const, null as CarryOver | null)
44// The marketplace named in the one-time offer to turn on auto-update, while it shows.
45const updateOffer = atom({ plugin: 'tessera', key: 'updateOffer' } as const, null as UpdateOffer | null)
46const quietTasks = atom({ plugin: 'tessera', key: 'quietTasks' } as const, [] as Quiet[])
47// Edit results the person unfolded.
48const unfoldedDiffs = atom({ plugin: 'tessera', key: 'unfoldedDiffs' } as const, [] as string[])
49const CARRY_SHOWN = 5
50// False while no setting or locale chose Chinese, so a prompt written in Chinese may still switch to it.
51let langSettled = false
52// Notes stay in the transcript once sent, so each goes once per context: again only after a compaction drops it.
53let hintSent = false
54let notedVoice: Voice | undefined
55let matchReplyLanguage = true
56// Renders cannot ask the engine, so tool rows read the session's working directory from here.
57let workDir: string | undefined
58
59
60// Every variable the platform decisions read, each named literally so the engine can list them, read
61// at once: each is a round trip to the engine.
62async function readEnv($: EngineInterface): Promise<Env> {
63 const [OS, TEMP, HOME, USERPROFILE, CLAUDE_CODE_TMPDIR, CLAUDE_CONFIG_DIR, CLAUDE_CODE_FORCE_TERMINAL_IMAGES, TERM, TERM_PROGRAM, KITTY_WINDOW_ID, TMUX, STY, WSL_DISTRO_NAME] = await Promise.all([
64 $.env.get('OS'),
65 $.env.get('TEMP'),
66 $.env.get('HOME'),
67 $.env.get('USERPROFILE'),
68 $.env.get('CLAUDE_CODE_TMPDIR'),
69 $.env.get('CLAUDE_CONFIG_DIR'),
70 $.env.get('CLAUDE_CODE_FORCE_TERMINAL_IMAGES'),
71 $.env.get('TERM'),
72 $.env.get('TERM_PROGRAM'),
73 $.env.get('KITTY_WINDOW_ID'),
74 $.env.get('TMUX'),
75 $.env.get('STY'),
76 $.env.get('WSL_DISTRO_NAME'),
77 ])
78 return { OS, TEMP, HOME, USERPROFILE, CLAUDE_CODE_TMPDIR, CLAUDE_CONFIG_DIR, CLAUDE_CODE_FORCE_TERMINAL_IMAGES, TERM, TERM_PROGRAM, KITTY_WINDOW_ID, TMUX, STY, WSL_DISTRO_NAME }
79}
80
81// The sessions Claude Code's registry lists as running: <config dir>/sessions/<pid>.json, each naming its
82// sessionId, written at start and swept when the session exits. Undefined when it cannot be read, and the
83// carry-over then falls back to the ended mark and the stale limit.
84async function liveSessions($: EngineInterface): Promise<Set<string> | undefined> {
85 const home = session.env.HOME ?? session.env.USERPROFILE
86 const dir = session.env.CLAUDE_CONFIG_DIR ?? (home === undefined ? undefined : `${home}/.claude`)
87 if (dir === undefined) return undefined
88 const entries = await $.fs.list(`${dir.replace(/\\/g, '/')}/sessions`).catch(() => undefined)
89 if (entries === undefined) return undefined
90 const ids = new Set<string>()
91 for (const entry of entries) {
92 if (entry.kind !== 'file' || !entry.name.endsWith('.json')) continue
93 const text = await $.fs.read(`${dir.replace(/\\/g, '/')}/sessions/${entry.name}`).catch(() => undefined)
94 try {
95 const id = (JSON.parse(String(text)) as { sessionId?: unknown }).sessionId
96 if (typeof id === 'string') ids.add(id)
97 } catch {
98 /* a file mid-write names nobody */
99 }
100 }
101 return ids
102}
103
104// The reply note sits far back in a long context and stops holding; a last reply in another language
105// than the person's gets the note sent again.
106async function replyDrifted($: EngineInterface, wanted: Voice): Promise<boolean> {
107 const messages = await $.session.messages().catch(() => [])
108 const last = messages.findLast(m => m.role === 'assistant')
109 const spoken = last === undefined ? undefined : voiceOf(last.text)
110 return spoken !== undefined && spoken !== wanted
111}
112
113// Carry-over: what this session's task lists leave open is kept per repository, and the next session
114// there offers it back above the prompt.
115let carryOn = true
116let pythonUtf8 = true
117let backgroundOn = true
118const taskLog: TaskLog = { tasks: new Map(), todos: [] }
119
120// Looked up per call, since the session's directory can change, and the last value kept for session.end,
121// which runs under one short bound that the repository lookup (a git call) overran on a busy machine.
122let carryKeyKnown: string | undefined
123async function carryKey($: EngineInterface): Promise<string> {
124 carryKeyKnown = `carry:${(await $.session.repo())?.root ?? (await $.session.cwd())}`
125 return carryKeyKnown
126}
127
128// The ended conversation's records under the new conversation's id: the files it edited, so they are not
129// another session's to the fresh one, and the variables tessera set for it, so the fresh one still owns them.
130async function rekeyRecords($: EngineInterface, from: string, to: string) {
131 const edits = rekeyed(asEditLog(await $.store.get(EDITS).catch(() => undefined)), from, to)
132 if (edits !== undefined) await $.store.set(EDITS, edits).catch(() => undefined)
133 const vars = await $.store.get('setVars').catch(() => undefined)
134 if (vars !== null && typeof vars === 'object' && from in vars) {
135 const { [from]: own, ...rest } = vars as Record<string, unknown>
136 await $.store.set('setVars', { ...rest, [to]: own }).catch(() => undefined)
137 }
138}
139
140// The newest entries of a store record keyed by session id.
141const newest = (record: Record<string, unknown>, n: number) => Object.fromEntries(Object.entries(record).slice(-n))
142
143async function readCarry($: EngineInterface, key: string): Promise<CarryStore> {
144 const stored = await $.store.get(key).catch(() => undefined)
145 return stored !== null && typeof stored === 'object' ? (stored as CarryStore) : {}
146}
147
148async function saveTasks($: EngineInterface) {
149 const key = await carryKey($)
150 await $.store.set(key, recordSession(await readCarry($, key), await $.session.id(), await $.clock.now(), taskLog)).catch(() => undefined)
151}
152
153async function settleCarry($: EngineInterface, from: string, fill: string | undefined) {
154 if (fill !== undefined) await $.prompt.fill({ text: fill })
155 const key = await carryKey($)
156 const { [from]: _dropped, ...rest } = await readCarry($, key)
157 await $.store.set(key, rest).catch(() => undefined)
158 await update($, carryOver, () => null)
159}
160
161const offeredKey = (offer: UpdateOffer) => (offer.reason === 'moved' ? 'moveOffered' : 'updateOffered')
162
163async function settleUpdate($: EngineInterface, offer: UpdateOffer, fill: string | undefined) {
164 if (fill !== undefined) await $.prompt.fill({ text: fill })
165 await $.store.set(offeredKey(offer), true).catch(() => undefined)
166 await update($, updateOffer, () => null)
167}
168
169function registerUpdateOffer(on: On) {
170 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
171 const offer = await read($, updateOffer)
172 if (e.surface !== 'terminal' || e.props.hasSurvey || offer === null) return next(e)
173 const { Box, Text, Button } = $.ui.resolve(e)
174 const below = await next(e)
175 const s = t()
176 const moved = offer.reason === 'moved'
177 const copyCommands = (press: { surface?: string }) =>
178 $.ui.copy({ text: s.movedCommands(offer.market), surface: press.surface as never })
179 .then(r => $.ui.toast(r.isCopied ? s.copied : `${s.copyFailed}: ${r.reason}`))
180 .then(() => settleUpdate($, offer, undefined))
181 return (
182 <Box flexDirection="column">
183 <Box flexDirection="column" borderStyle="round" borderDimColor paddingX={1}>
184 <Box flexDirection="row" gap={2}>
185 <Text bold>{moved ? s.movedTitle(MARKETPLACE, offer.market) : s.updateTitle}</Text>
186 {moved ? <Button key="update-copy" label={s.movedCopy} onPress={copyCommands} /> : <Button key="update-open" label={s.updateOpen} onPress={() => settleUpdate($, offer, '/plugin')} />}
187 <Button key="update-later" label={s.updateLater} onPress={() => settleUpdate($, offer, undefined)} />
188 </Box>
189 <Text dimColor>{moved ? s.movedSteps : s.updateSteps(offer.market)}</Text>
190 </Box>
191 {below}
192 </Box>
193 )
194 })
195}
196
197function registerCarryOver(on: On) {
198 on('tool.call', { tool: 'TaskCreate' }, async ($, e, next) => {
199 const out = await next(e)
200 const task = (out.result as { task?: { id: string; subject: string } } | undefined)?.task
201 if (e.agentId !== undefined || task === undefined) return out
202 taskLog.tasks.set(task.id, { subject: task.subject, status: 'pending' })
203 await saveTasks($)
204 return out
205 })
206 on('tool.call', { tool: 'TaskUpdate' }, async ($, e, next) => {
207 const out = await next(e)
208 const task = taskLog.tasks.get(e.taskId)
209 if (e.agentId !== undefined || task === undefined || out.deny !== undefined) return out
210 if (e.status === 'deleted') taskLog.tasks.delete(e.taskId)
211 else taskLog.tasks.set(e.taskId, { subject: e.subject ?? task.subject, status: e.status ?? task.status })
212 await saveTasks($)
213 return out
214 })
215 on('tool.call', { tool: 'TodoWrite' }, async ($, e, next) => {
216 const out = await next(e)
217 if (e.agentId !== undefined || out.deny !== undefined) return out
218 taskLog.todos = e.todos.map(t => ({ content: t.content, status: t.status }))
219 await saveTasks($)
220 return out
221 })
222 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
223 const offer = await read($, carryOver)
224 if (e.surface !== 'terminal' || e.props.hasSurvey || offer === null) return next(e)
225 const { Box, Text, Button } = $.ui.resolve(e)
226 const width = Math.max(20, (e.viewport?.columns ?? 80) - 6)
227 const below = await next(e)
228 return (
229 <Box flexDirection="column">
230 <Box flexDirection="column" borderStyle="round" borderDimColor paddingX={1}>
231 <Box flexDirection="row" gap={2}>
232 <Text bold>{t().carryTitle(offer.items.length)}</Text>
233 <Button key="carry-continue" label={t().carryContinue} onPress={() => settleCarry($, offer.from, t().carryPrompt(offer.items))} />
234 <Button key="carry-dismiss" label={t().carryDismiss} onPress={() => settleCarry($, offer.from, undefined)} />
235 </Box>
236 {offer.items.slice(0, CARRY_SHOWN).map((item, i) => (
237 <Text key={`carry-${i}`} wrap="truncate-end">{`· ${[...item].slice(0, width).join('')}`}</Text>
238 ))}
239 {offer.items.length > CARRY_SHOWN && <Text dimColor>…</Text>}
240 </Box>
241 {below}
242 </Box>
243 )
244 })
245}
246
247// The optional client-feedback inbox: pasted chat logs become numbered items per repository, kept across sessions.
248let inboxOn = false
249
250async function inboxKey($: EngineInterface): Promise<string> {
251 return `inbox:${(await $.session.repo())?.root ?? (await $.session.cwd())}`
252}
253
254const registerInboxTool = ($: EngineInterface) =>
255 $.tool
256 .register({
257 name: 'inbox_fixed',
258 description: "Mark client-feedback inbox items as fixed once a commit fixes them, so a later complaint like them is flagged as a regression. Pass the item numbers from tessera's inbox note and the commit hash.",
259 inputSchema: { type: 'object', properties: { ids: { type: 'array', items: { type: 'number' } }, commit: { type: 'string' } }, required: ['ids', 'commit'] },
260 })
261 .catch(() => undefined)
262
263async function readInbox($: EngineInterface, key: string): Promise<InboxItem[]> {
264 const stored = await $.store.get(key).catch(() => undefined)
265 return Array.isArray(stored) ? (stored as InboxItem[]) : []
266}
267
268async function fileFeedback($: EngineInterface, text: string): Promise<string | undefined> {
269 const lines = parseChat(text)
270 if (lines.length === 0) return undefined
271 const key = await inboxKey($)
272 const result = intake(await readInbox($, key), lines)
273 if (result.added.length === 0) return undefined
274 await $.store.set(key, result.items)
275 $.ui.toast(t().inboxFiled(result.added.length, result.regressions.map(r => r.like.id)))
276 return intakeNote(result)
277}
278
279async function markInbox($: EngineInterface, ids: number[], commit: string): Promise<string> {
280 const key = await inboxKey($)
281 await $.store.set(key, markFixed(await readInbox($, key), ids, commit))
282 return t().inboxMarked(ids, commit)
283}
284
285const SETUP_PANE = 'tessera-setup'
286
287// /tessera setup: one row per feature; a press writes its option, which reloads tessera with it.
288// One settings write per option, each with its key written out: a reader of the module (the directory's
289// validation among them) takes a settings write only with a literal key.
290function setOption($: EngineInterface, key: string, to: string | boolean) {
291 switch (key) {
292 case 'enabled': return $.config.set({ key: 'tessera.enabled', value: to })
293 case 'foldDiffs': return $.config.set({ key: 'tessera.foldDiffs', value: to })
294 case 'pastePreview': return $.config.set({ key: 'tessera.pastePreview', value: to })
295 case 'replyLanguage': return $.config.set({ key: 'tessera.replyLanguage', value: to })
296 case 'carryOver': return $.config.set({ key: 'tessera.carryOver', value: to })
297 case 'backgroundWatch': return $.config.set({ key: 'tessera.backgroundWatch', value: to })
298 case 'pythonUtf8': return $.config.set({ key: 'tessera.pythonUtf8', value: to })
299 case 'guardGit': return $.config.set({ key: 'tessera.guardGit', value: to })
300 case 'stashBeforeDiscard': return $.config.set({ key: 'tessera.stashBeforeDiscard', value: to })
301 case 'guardData': return $.config.set({ key: 'tessera.guardData', value: to })
302 case 'guardCjkEscapes': return $.config.set({ key: 'tessera.guardCjkEscapes', value: to })
303 case 'guardEncoding': return $.config.set({ key: 'tessera.guardEncoding', value: to })
304 case 'guardSessions': return $.config.set({ key: 'tessera.guardSessions', value: to })
305 case 'guardSimplified': return $.config.set({ key: 'tessera.guardSimplified', value: to })
306 case 'guardHeredoc': return $.config.set({ key: 'tessera.guardHeredoc', value: to })
307 case 'guardGlossary': return $.config.set({ key: 'tessera.guardGlossary', value: to })
308 case 'maskSecrets': return $.config.set({ key: 'tessera.maskSecrets', value: to })
309 case 'cacheClock': return $.config.set({ key: 'tessera.cacheClock', value: to })
310 case 'agentModel': return $.config.set({ key: 'tessera.agentModel', value: to })
311 case 'requireUserQuote': return $.config.set({ key: 'tessera.requireUserQuote', value: to })
312 case 'feedbackInbox': return $.config.set({ key: 'tessera.feedbackInbox', value: to })
313 case 'promptLog': return $.config.set({ key: 'tessera.promptLog', value: to })
314 default: return undefined
315 }
316}
317
318function registerSetup(on: On, options: Record<string, unknown>) {
319 on('ui.render', { component: 'Pane', requestId: SETUP_PANE }, async ($, e) => {
320 const { Box, Text, Button } = $.ui.resolve(e)
321 const s = t()
322 return (
323 <Box flexDirection="column">
324 <Box flexDirection="row" justifyContent="space-between">
325 <Text bold>{s.setupTitle}</Text>
326 <Button key="close" label={s.closePane} onPress={() => $.ui.close({ id: SETUP_PANE })} />
327 </Box>
328 {FEATURES.map(feature => {
329 const isOn = feature.isOn(options[feature.key])
330 return (
331 <Box key={feature.key} flexDirection="column" marginTop={1}>
332 <Button
333 key={`toggle-${feature.key}`}
334 label={`${isOn ? '☑' : '☐'} ${feature.name[session.lang]}`}
335 onPress={() => setOption($, feature.key, isOn ? feature.off : feature.on)}
336 />
337 {/* The pane's width is not known here, so the text wraps by its own pieces, between CJK characters too. */}
338 <Box flexDirection="row" flexWrap="wrap" paddingLeft={3}>
339 {breakUnits(feature.about[session.lang]).map((unit, i) => <Text key={`a${i}`} dimColor>{unit}</Text>)}
340 </Box>
341 </Box>
342 )
343 })}
344 </Box>
345 )
346 })
347}
348
349const HINT = [
350 'Replies in this session are drawn by the tessera mod, which runs inside Claude Code and is not a command or tool to call: when the user asks to show something with tessera, write it as markdown in the reply.',
351 'Markdown tables, GitHub alerts (> [!WARNING], > [!NOTE]), fenced code with a language tag, and ```mermaid blocks render as colored terminal graphics:',
352 'flowcharts, sequence diagrams and xychart-beta bar or line charts.',
353 'When a reply carries a numeric series or a flow that is easier to see than read, add one small diagram or chart with short labels.',
354 'Skip diagrams for simple answers.',
355 'When you write a prompt meant for another AI agent or tool, put the whole prompt in one ```prompt fenced block: it draws as a card with a copy button.',
356 'Put any command or snippet the user may run or copy in a fenced block with a language tag, never inline code: fenced blocks get a copy button, inline code does not.',
357].join(' ')
358
359const detectTerminal = async ($: EngineInterface): Promise<Terminal | null> => {
360 const program = await $.env.get('TERM_PROGRAM')
361 const term = await $.env.get('TERM')
362 if ((await $.env.get('KITTY_WINDOW_ID')) || term === 'xterm-kitty') return 'kitty'
363 if (program === 'Apple_Terminal') return 'apple-terminal'
364 if (program === 'WarpTerminal') return 'warp'
365 if (program === 'ghostty') return 'ghostty'
366 if (program === 'WezTerm') return 'wezterm'
367 if (program === 'vscode') return 'vscode'
368 if (program === 'iTerm.app') return 'iterm'
369 if (term === 'alacritty' || (await $.env.get('ALACRITTY_WINDOW_ID'))) return 'alacritty'
370 if (await $.env.get('WT_SESSION')) return 'windows-terminal'
371 if (await $.env.get('VTE_VERSION')) return 'gnome'
372 if (await $.env.get('KONSOLE_VERSION')) return 'konsole'
373 return null
374}
375
376const applyRtl = async ($: EngineInterface, style: Style): Promise<void> => {
377 if (style.rtl !== 'auto') return
378 const terminal = await detectTerminal($)
379 style.reorder = terminal !== null
380 if (terminal) style.shape = TERMINALS[terminal]
381}
382
383const expandedCalls = new Set<string>()
384// True while the transcript draws every row in full (ctrl+o, --verbose), which tool rows and folded diffs
385// leave to the engine. A user message says which view is drawing: every transcript has one, drawn first.
386let transcriptExpanded = false
387
388// Text as record mode shows it: keys, emails and phone numbers masked while /tessera record is on.
389const shown = (text: string): string => (session.recording ? mask(text) : text)
390const shownRow = <T extends { input: unknown; output?: unknown }>(row: T): T => (session.recording ? { ...row, input: maskValues(row.input), output: maskValues(row.output) } : row)
391
392const drawMarkdown =($: EngineInterface, el: ReturnType<EngineInterface['ui']['resolve']>, style: Style, blocks: ReturnType<typeof parse>, columns: number, reply?: string): RenderElement[] => {
393 const { Button } = el
394 const copy = (text: string | (() => string), key: string, kind: CopyKind | 'reply' = 'block') =>
395 style.copyButtons ? (
396 <Button
397 key={key}
398 variant="primary"
399 label={t().copyLabels[kind]}
400 onPress={press => {
401 $.ui.copy({ text: typeof text === 'function' ? text() : text, surface: press.surface })
402 .then(r => $.ui.toast(r.isCopied ? t().copied : `${t().copyFailed}: ${r.reason}`))
403 .catch(() => $.ui.toast(t().copyFailed))
404 }}
405 />
406 ) : null
407 const drawn: Drawn = new Map()
408 if (style.mermaid) {
409 for (const [i, block] of blocks.entries()) {
410 if (block.kind !== 'code' || block.lang.toLowerCase() !== 'mermaid') continue
411 const art = mermaidFit(block.lines.join('\n'), style.mermaidAscii, columns)
412 if (art !== null) drawn.set(i, { element: boxArt(el, style, art, `b${i}`), art: unpad(art) })
413 }
414 }
415 const elements = renderBlocks(el, style, blocks, columns, drawn, copy)
416 const button = reply === undefined ? null : copy(reply, 'reply', 'reply')
417 return button ? [...elements, <el.Box key="reply" alignSelf="flex-end">{button}</el.Box>] : elements
418}
419
420// The prompt log's work that needs $ and runs inside this module's own hooks: past an import, $ is
421// followed only into the hooks `on` registers, so these live here and the log's own hooks in
422// prompt-log-hooks.tsx. The state they touch is declared here too, as a reader of the module lists it
423// per file; prompt-log-hooks.tsx declares the same keys.
424const promptLog = atom({ plugin: 'tessera', key: 'promptLog' } as const, [] as LoggedPrompt[])
425const promptLogView = atom({ plugin: 'tessera', key: 'promptLogView' } as const, { selected: null } as PromptLogView)
426
427async function keepPromptRows($: EngineInterface) {
428 if (logScreen.seenRows.size > 0) await update($, promptLog, log => withRows(log, logScreen.seenRows.values()))
429}
430
431async function openPromptLog($: EngineInterface) {
432 await keepPromptRows($)
433 const log = await read($, promptLog)
434 const newest = log.at(-1)
435 if (newest !== undefined) await update($, promptLogView, v => (log.some(p => p.n === v.selected) ? v : { selected: newest.n }))
436 await $.ui.open({ id: 'tessera-log', title: t().logTitle(log.length), focus: true, closeOnEscape: true, columns: PANE_COLUMNS })
437}
438
439// A /clear or /resume starts another conversation in this terminal: its prompts are another log.
440async function clearPromptLog($: EngineInterface) {
441 logScreen.seenRows.clear()
442 logScreen.onScreen.clear()
443 logScreen.flashed = null
444 await update($, promptLog, () => [])
445 await update($, promptLogView, () => ({ selected: null }))
446}
447
448function noteScreen($: EngineInterface, id: string, screen: unknown) {
449 if (screen === undefined) return
450 const shown = screen !== null
451 if (logScreen.onScreen.has(id) === shown) return
452 if (shown) logScreen.onScreen.add(id)
453 else logScreen.onScreen.delete(id)
454 if (logScreen.paneShown) $.ui.invalidate('ui.render')
455}
456
457type UserRow = Parameters<MatchedHook<'ui.render', { component: 'UserMessage' }>>[1]
458type CommandRow = Parameters<MatchedHook<'ui.render', { component: 'CommandOutput' }>>[1]
459
460// A transcript row of the person's prompt, seen as it draws; a drawing cannot write state.
461function notePromptRow($: EngineInterface, e: UserRow) {
462 const id = e.requestId
463 if (!isRealRow(id) || !isOwn(e.props.origin.kind)) return
464 if (!logScreen.seenRows.has(id)) logScreen.seenRows.set(id, { id, kind: 'prompt', text: e.props.text })
465 noteScreen($, id, e.props.onScreen)
466}
467
468function noteCommandRow($: EngineInterface, e: CommandRow) {
469 const id = e.requestId
470 if (!isRealRow(id) || e.props.isErrored) return
471 if (!logScreen.seenRows.has(id)) logScreen.seenRows.set(id, { id, kind: 'command', command: e.props.command, args: e.props.args })
472 noteScreen($, id, e.props.onScreen)
473}
474
475// The row a jump landed on, lit for a moment in the theme's rule color; every other row as drawn.
476let rowFlashColor = 'gray'
477function flashRow($: EngineInterface, e: UserRow | CommandRow, drawn: RenderElement): RenderElement {
478 if (logScreen.flashed !== e.requestId) return drawn
479 const { Box } = $.ui.resolve(e)
480 return <Box backgroundColor={rowFlashColor}>{drawn}</Box>
481}
482
483export const register: Register = (on, options) => {
484 const isDrawing = options.enabled !== false
485 const promptLogOn = options.promptLog !== false
486 pythonUtf8 = options.pythonUtf8 !== false
487 const style = resolveStyle(options)
488
489 session.lang = pickLang(options.language, [])
490 langSettled = options.language === 'en' || options.language === 'zh-TW'
491 matchReplyLanguage = options.replyLanguage !== 'off'
492 session.voice = undefined
493 hintSent = false
494 notedVoice = undefined
495
496 on('session.start', async ($, e, next) => {
497 // Claude 5.x gets no task tools unless asked, and carry-over has nothing to keep without them; a
498 // value the person set, on or off, stands.
499 // Everything read before the session starts is read at once: each read is a round trip to the engine.
500 const [todoTools, pyUtf8, readsEnv, settings, userSettings, wroteLang, lcAll, langVar, setupSeen, sessionCwd, setVars, sessionId] = await Promise.all([
501 $.env.get('CLAUDE_CODE_ENABLE_TODO_TOOLS'),
502 $.env.get('PYTHONUTF8'),
503 readEnv($),
504 $.settings.read({}).catch(() => ({}) as Record<string, unknown>),
505 // The marketplace names go into commands shown to the person, so only what they wrote themselves is
506 // read for them: their own settings file and the --settings they launched with, not a repository's.
507 Promise.all([$.settings.read({ source: 'user' }), $.settings.read({ source: 'flag' })])
508 .then(([user, flag]) => ({ extraKnownMarketplaces: { ...(user.extraKnownMarketplaces as object | undefined), ...(flag.extraKnownMarketplaces as object | undefined) } }) as Record<string, unknown>)
509 .catch(() => ({}) as Record<string, unknown>),
510 $.store.get('wroteLang').catch(() => undefined),
511 $.env.get('LC_ALL'),
512 $.env.get('LANG'),
513 $.store.get('setupSeen').catch(() => true),
514 $.session.cwd().catch(() => undefined),
515 $.store.get('setVars').catch(() => undefined),
516 $.session.id().catch(() => undefined),
517 ])
518 workDir = sessionCwd
519 // Variables tessera set are noted under the session's id, so after a reload a value it set is known as
520 // its own and unset when the option is off, while a value found in a new process is the person's: an
521 // environment does not outlive its process, so nothing tessera set in an earlier session is there.
522 // One entry per session, so two sessions at once do not overwrite each other's note.
523 const record = setVars !== null && typeof setVars === 'object' ? (setVars as Record<string, unknown>) : {}
524 const own = sessionId === undefined ? undefined : record[sessionId]
525 const noted = Array.isArray(own) ? own.filter((v): v is string => typeof v === 'string') : []
526 const wanted = [
527 ...(carryOn && (todoTools === undefined || (todoTools === '1' && noted.includes('CLAUDE_CODE_ENABLE_TODO_TOOLS'))) ? ['CLAUDE_CODE_ENABLE_TODO_TOOLS'] : []),
528 // Python on Windows reads and writes the system code page by default (until 3.15), where CJK fails.
529 ...(pythonUtf8 && platformOf(readsEnv) === 'windows' && (pyUtf8 === undefined || (pyUtf8 === '1' && noted.includes('PYTHONUTF8'))) ? ['PYTHONUTF8'] : []),
530 ]
531 if (wanted.includes('CLAUDE_CODE_ENABLE_TODO_TOOLS') && todoTools === undefined) await $.env.set('CLAUDE_CODE_ENABLE_TODO_TOOLS', '1').catch(() => undefined)
532 if (wanted.includes('PYTHONUTF8') && pyUtf8 === undefined) await $.env.set('PYTHONUTF8', '1').catch(() => undefined)
533 if (!wanted.includes('CLAUDE_CODE_ENABLE_TODO_TOOLS') && todoTools === '1' && noted.includes('CLAUDE_CODE_ENABLE_TODO_TOOLS')) await $.env.set('CLAUDE_CODE_ENABLE_TODO_TOOLS', undefined).catch(() => undefined)
534 if (!wanted.includes('PYTHONUTF8') && pyUtf8 === '1' && noted.includes('PYTHONUTF8')) await $.env.set('PYTHONUTF8', undefined).catch(() => undefined)
535 if (sessionId !== undefined && wanted.join() !== noted.join()) await $.store.set('setVars', newest({ ...record, [sessionId]: wanted }, 8)).catch(() => undefined)
536 session.env = readsEnv
537 const hints = [
538 typeof settings.language === 'string' ? settings.language : undefined,
539 // The language the person wrote in last time, ahead of a system locale that may not be theirs.
540 typeof wroteLang === 'string' ? wroteLang : undefined,
541 lcAll,
542 langVar,
543 Intl.DateTimeFormat().resolvedOptions().locale,
544 ]
545 session.lang = pickLang(options.language, hints)
546 langSettled = options.language === 'en' || options.language === 'zh-TW' || session.lang === 'zh-TW'
547 const returning = setupSeen === true
548 if (!returning) {
549 await $.store.set('setupSeen', true).catch(() => undefined)
550 $.ui.toast(t().setupHint)
551 }
552 if (isDrawing) await applyRtl($, style)
553 const started = await next(e)
554 // Only the newest repositories' records stay; one key per repository, read whole at every access.
555 const pruneCarry = async (own: string) => {
556 const keys = (await $.store.keys().catch(() => [] as string[])).filter(k => k.startsWith('carry:'))
557 if (keys.length <= REPOSITORIES_KEPT) return
558 const records = Object.fromEntries(await Promise.all(keys.map(async k => [k, await readCarry($, k)] as const)))
559 for (const stale of staleCarryKeys(records, own)) await $.store.delete(stale).catch(() => undefined)
560 }
561 const carry = async () => {
562 const [key, sessionId, now] = await Promise.all([carryKey($), $.session.id(), $.clock.now()])
563 await pruneCarry(key)
564 let store = await readCarry($, key)
565 // A session resumed with --resume is running again: its record is no longer another terminal's leftovers.
566 if (store[sessionId]?.ended === true) {
567 const { ended: _dropped, ...live } = store[sessionId]!
568 store = { ...store, [sessionId]: { ...live, at: now } }
569 await $.store.set(key, store).catch(() => undefined)
570 }
571 // A reload starts the module over within the same session: pick its task list back up.
572 if (taskLog.tasks.size === 0) taskLog.tasks = restoredTasks(store, sessionId)
573 const offer = e.isInteractive ? carriedFrom(store, sessionId, now, await liveSessions($)) : undefined
574 if (offer !== undefined) await update($, carryOver, () => offer)
575 }
576 // Asked once, from the second session on, so the first one only shows the setup hint. An install
577 // under the marketplace's old name gets no updates at all, so that comes before auto-update.
578 const moved = marketplaceRenamed(userSettings)
579 const market = marketplaceWithoutUpdates(userSettings)
580 const offer: UpdateOffer | undefined = moved !== undefined ? { reason: 'moved', market: moved } : market !== undefined ? { reason: 'auto-update', market } : undefined
581 const offerUpdate = async () => {
582 if (e.isInteractive && returning && offer !== undefined && (await $.store.get(offeredKey(offer)).catch(() => true)) !== true)
583 await update($, updateOffer, () => offer)
584 }
585 // What follows the start is independent, so it runs at once too.
586 await Promise.all([
587 carryOn ? carry() : undefined,
588 offerUpdate(),
589 $.command
590 .register({ name: 'tessera', description: t().commandDescription, argumentHint: '[setup | log | peek <file> | inbox [fixed <n…>] | theme <name> | copy [code|prompt] | demo]' })
591 .catch(() => undefined),
592 inboxOn ? registerInboxTool($) : undefined,
593 ])
594 return started
595 })
596
597 // Every hook of the feature modules is registered here: `on` stays in this file, where a reader of the
598 // module (the directory's validation among them) can follow each registration to its hook.
599 const imagesOn = options.pastePreview !== false
600 if (imagesOn) {
601 configurePastes(options)
602 on('session.start', { surface: 'terminal' }, startPastes)
603 on('ui.render', { component: 'AbovePrompt' }, pasteBand)
604 }
605 backgroundOn = options.backgroundWatch !== false
606 if (backgroundOn) {
607 configureBackgroundWatch(options)
608 on('tool.call', { tool: 'Bash' }, watchShell)
609 // PowerShell exists only in the Windows build's tool table.
610 on('tool.call', { tool: 'PowerShell' as 'Bash' }, watchShell)
611 on('tool.call', { tool: 'TaskStop' as 'Bash' }, forgetStopped)
612 on('ui.render', { component: 'AbovePrompt' }, quietBand)
613 }
614 if (options.cacheClock !== false) {
615 configureCacheClock(options)
616 on('turn.complete', warmCache)
617 on('turn.start', forgetCache)
618 on('ui.render', { component: 'AbovePrompt' }, cacheBand)
619 }
620 if (options.guardGit !== false || options.guardCjkEscapes !== false || options.guardEncoding !== false || options.guardData !== false || options.guardSessions !== false || options.guardSimplified !== 'off' || options.guardHeredoc !== false || options.guardGlossary === true || options.agentModel !== 'off' || options.requireUserQuote === true || options.maskSecrets !== false) {
621 configureGuards(options)
622 on('tool.call', guardToolCall).catch((_, e, next) => next(e))
623 on('tool.call', { tool: 'Agent' }, guardAgent)
624 on('tool.call', { tool: 'Workflow' }, guardWorkflow).catch((_, e, next) => next(e))
625 }
626 registerSetup(on, options)
627 if (promptLogOn) {
628 configurePromptLog(style.theme)
629 rowFlashColor = style.theme.rule ?? 'gray'
630 // Each with a matcher: the module's own prompt.submit and the cache clock's turn.complete are unmatched.
631 on('prompt.submit', { origin: { kind: /^(composer|bridge)$/ } }, logPrompt)
632 on('turn.complete', { reason: 'answer' }, logReply)
633 on('command.run', logCommand)
634 on('ui.render', { component: 'Pane', requestId: 'tessera-log' }, logPane)
635 on('ui.focus', { component: 'Pane', requestId: 'tessera-log' }, logFocus)
636 on('ui.scroll', { component: 'Pane', requestId: 'tessera-log' }, logArrows)
637 on('ui.close', { id: 'tessera-log' }, logClosed)
638 }
639 carryOn = options.carryOver !== false
640 if (carryOn) registerCarryOver(on)
641 // The module's one session.end, whatever is on. A /clear, or a /resume typed in the session, ends the
642 // conversation and starts another in this terminal with no session.start between: the task list and the
643 // watched tasks start empty, and once the new id is in place the ended conversation's records are
644 // re-keyed to it, and what a cleared one left open is offered like a new session's. The store write
645 // comes first: the whole chain runs under one short bound.
646 on('session.end', async ($, e, next) => {
647 const key = carryOn ? (carryKeyKnown ?? (await carryKey($))) : undefined
648 const store = key === undefined ? undefined : endSession(await readCarry($, key), e.sessionId, await $.clock.now())
649 if (key !== undefined && store !== undefined) await $.store.set(key, store).catch(() => undefined)
650 if (e.reason !== 'clear' && e.reason !== 'resume') return next(e)
651 if (promptLogOn) await clearPromptLog($)
652 taskLog.tasks.clear()
653 taskLog.todos = []
654 background.watched.clear()
655 const open = e.reason === 'clear' ? (store?.[e.sessionId]?.open ?? []) : []
656 // The session's state is reset once session.end is done, so the records move and the offer is written
657 // when the fresh conversation's id is in place.
658 let tries = 0
659 const wait: Timer = $.clock.every(100, async () => {
660 if (++tries > 50) return wait.cancel()
661 const fresh = await $.session.id()
662 if (fresh === e.sessionId) return
663 wait.cancel()
664 await rekeyRecords($, e.sessionId, fresh)
665 if (open.length > 0) await update($, carryOver, () => ({ from: e.sessionId, items: open }))
666 })
667 return next(e)
668 })
669 registerUpdateOffer(on)
670 inboxOn = options.feedbackInbox === true
671 const parsed = new Map<string, ReturnType<typeof parse>>()
672 const parseCached = (text: string, cache = parsed, limit?: number) => remember(cache, text, () => parse(text, { numbers: style.highlightNumbers, paths: style.highlightPaths }), limit)
673
674 on('tool.call', { tool: 'mcp__tessera__inbox_fixed' }, async ($, e) => {
675 const input = e as unknown as { ids?: unknown; commit?: unknown }
676 const ids = Array.isArray(input.ids) ? input.ids.filter((n): n is number => typeof n === 'number') : []
677 const text = await markInbox($, ids, typeof input.commit === 'string' ? input.commit : '')
678 // An MCP tool's result is its text (or a content list), not a whole CallToolResult.
679 return { result: text } as never
680 })
681
682 on('session.compact', async (_, e, next) => {
683 const done = await next(e)
684 hintSent = false
685 notedVoice = undefined
686 return done
687 })
688
689 on('prompt.submit', async ($, e, next) => {
690 const own = e.origin.kind === 'composer' || e.origin.kind === 'bridge'
691 // A background task's own notification says it ended, however it ended.
692 const ended = backgroundOn && e.origin.kind === 'task-notification' ? notifiedTask(e.text) : undefined
693 if (ended !== undefined) {
694 background.watched.delete(ended)
695 if ((await read($, quietTasks)).some(q => q.id === ended)) await update($, quietTasks, list => list.filter(q => q.id !== ended))
696 }
697 const context = [...(e.context ?? [])]
698 if (own) {
699 if (carryOn && (await read($, carryOver)) !== null) await update($, carryOver, () => null)
700 if (backgroundOn && (await read($, quietTasks)).length > 0) await update($, quietTasks, () => [])
701 session.voice = voiceOf(e.text) ?? session.voice
702 if (!langSettled && (session.voice === 'zh-Hant' || session.voice === 'zh-Hans')) {
703 session.lang = 'zh-TW'
704 langSettled = true
705 await $.store.set('wroteLang', 'zh-TW').catch(() => undefined)
706 }
707 if (matchReplyLanguage && session.voice !== undefined && session.voice !== 'en' && (session.voice !== notedVoice || (await replyDrifted($, session.voice)))) context.push(replyNote(session.voice))
708 if (session.voice !== undefined) notedVoice = session.voice
709 }
710 if (isDrawing) {
711 await applyRtl($, style)
712 if (style.diagramHints && own && !hintSent) {
713 context.push(HINT)
714 hintSent = true
715 }
716 }
717 if (inboxOn && own) {
718 const note = await fileFeedback($, e.text)
719 if (note !== undefined) context.push(note)
720 }
721 return context.length === (e.context ?? []).length ? next(e) : next({ ...e, context })
722 })
723
724 on('command.run', { command: 'tessera' }, async ($, e) => {
725 const [sub, name, ...rest] = e.args.trim().split(/\s+/)
726 if (sub === 'peek') {
727 const target = [name, ...rest].filter(Boolean).join(' ').replace(/^@/, '').replace(/^["']|["']$/g, '')
728 if (target === '') return { text: t().peekUsage }
729 const path = isAbsolute(target) ? target : `${await $.session.cwd()}/${target}`
730 const file = await $.fs.read(path, { as: 'bytes' }).catch(() => undefined)
731 if (file === undefined) return { text: t().peekUnreadable(target) }
732 const summary = peek(path, Uint8Array.fromBase64(file.base64))
733 return { text: summary === null ? t().peekUnknown(target) : `### ${target.replace(/^.*[\\/]/, '')}\n\n${summary}` }
734 }
735 if (sub === 'setup') {
736 await $.store.set('setupSeen', true).catch(() => undefined)
737 await $.ui.open({ id: SETUP_PANE, title: 'tessera' })
738 return { text: t().setupOpened }
739 }
740 if (sub === 'inbox') {
741 if (!inboxOn) return { text: t().inboxOff }
742 if (name === 'fixed') {
743 const ids = rest.map(Number).filter(n => Number.isInteger(n) && n > 0)
744 const head = await $.process.run(['git', '-C', await $.session.cwd(), 'rev-parse', '--short', 'HEAD'], { timeoutMs: 5_000 }).catch(() => undefined)
745 return { text: await markInbox($, ids, head?.exitCode === 0 ? head.stdout.trim() : 'manual') }
746 }
747 return { text: listText(await readInbox($, await inboxKey($)), t().inboxEmpty, t().inboxHeaders) }
748 }
749 if (sub === 'log') {
750 if (!promptLogOn) return { text: t().logOff }
751 await openPromptLog($)
752 return { text: t().logOpened }
753 }
754 if (!isDrawing) return { text: t().drawingOff }
755
756 if (sub === 'record') {
757 session.recording = name === 'on' ? true : name === 'off' ? false : !session.recording
758 $.ui.status(session.recording ? t().recordStatus : undefined)
759 // What is already on screen is drawn again, masked or unmasked.
760 $.ui.invalidate('ui.render')
761 return { text: session.recording ? t().recordOn : t().recordOff }
762 }
763 if (sub === 'demo') return { text: session.lang === 'zh-TW' ? showcaseTextZh(PRESET_NAMES) : showcaseText(PRESET_NAMES) }
764 if (sub === 'copy') {
765 const reply = (await $.session.messages()).findLast(m => m.role === 'assistant' && m.text.trim())
766 if (!reply) return { text: t().nothingToCopy }
767 const wanted = name === 'code' || name === 'prompt' ? name : undefined
768 const code = wanted === undefined ? undefined : parseCached(reply.text).findLast(b => b.kind === 'code' && (wanted === 'code' || b.lang === 'prompt'))
769 if (wanted !== undefined && code?.kind !== 'code') return { text: wanted === 'prompt' ? t().noPromptBlock : t().noCodeBlock }
770 const result = await $.ui.copy({ text: code?.kind === 'code' ? code.lines.join('\n') : reply.text })
771 const done = wanted === 'prompt' ? t().copiedPrompt : code ? t().copiedCode : t().copiedReply
772 return { text: result.isCopied ? done : `${t().copyFailed}: ${result.reason}` }
773 }
774 if (sub === 'demo-rtl') {
775 await applyRtl($, style)
776 return { text: rtlShowcaseText() }
777 }
778 if (sub !== 'theme' || !name) return { text: session.lang === 'zh-TW' ? helpTextZh(PRESET_NAMES) : helpText(PRESET_NAMES) }
779 if (!(PRESET_NAMES as readonly string[]).includes(name)) return { text: t().unknownTheme(name, PRESET_NAMES.join(', ')) }
780 const result = await $.config.set({ key: 'tessera.theme', value: name })
781 return { text: result.deny ? `${t().themeFailed}: ${result.deny}` : t().themeSet(name) }
782 })
783
784 // How many lines a folded diff shows; 0 is the counts alone, for every edit. With tool rows drawn here too,
785 // 0 puts the counts and the expand button on the edit's own row and its result block draws nothing.
786 const diffLines = Number.isFinite(Number(options.diffLines)) && options.diffLines !== '' ? Math.min(40, Math.max(0, Math.round(Number(options.diffLines)))) : 8
787 const oneLineEdits = options.foldDiffs !== false && diffLines === 0 && isDrawing && options.toolRows !== false
788 const isEdit = (tool: string) => /^(Edit|MultiEdit|Write)$/.test(tool)
789 if (options.foldDiffs !== false) {
790 on('ui.render', { component: 'ToolResult' }, async ($, e, next) => {
791 const { tool, tool_use_id: id, output, isErrored } = e.props
792 if (transcriptExpanded || isErrored || expandedCalls.has(id)) return next(e)
793 const unfolded = async () => (await read($, unfoldedDiffs)).includes(id)
794 const maskLines = (folded: Folded) => (session.recording ? { ...folded, shown: folded.shown.map(line => ({ ...line, text: mask(line.text) })) } : folded)
795 if (tool === 'Bash' || tool === 'PowerShell') {
796 // The files the command changed, which the engine draws whole under the output: folded like edits,
797 // over the engine's own drawing of the output alone. Short changes stay the engine's, as an edit's do.
798 const files = shellEdits(output).map(file => ({ ...file, folded: foldPatch(file.hunks, diffLines) }))
799 if (!files.some(file => file.folded !== undefined) || (await unfolded())) return next(e)
800 const { bashEditDiff: _dropped, ...rest } = output as Record<string, unknown>
801 const base = await next({ ...e, props: { ...e.props, output: rest } })
802 const verbs = t().toolWords.verbs
803 const rows = files.map(file => ({
804 verb: file.deleted ? t().toolWords.deleted : (file.created ? verbs['Write'] : verbs['Edit']) ?? tool,
805 path: shortPath(file.filePath, workDir),
806 folded: maskLines(file.folded ?? { shown: [], hidden: 0, ...hunkCounts(file.hunks) }),
807 }))
808 const hidden = rows.reduce((n, row) => n + row.folded.hidden, 0)
809 return renderShellEdits($.ui.resolve(e), style, base, rows, { hidden: t().diffHidden(hidden), expand: t().diffExpand }, () => update($, unfoldedDiffs, ids => [...ids, id]))
810 }
811 if (!isEdit(tool)) return next(e)
812 if (oneLineEdits) {
813 // The edit's row carries the counts and the button; nothing to draw here until it is unfolded.
814 if (editCounts(output) === undefined || (await unfolded())) return next(e)
815 const { Box } = $.ui.resolve(e)
816 return <Box />
817 }
818 const folded = foldPatch(patchOf(output), diffLines)
819 if (folded === undefined || (await unfolded())) return next(e)
820 const labels = { summary: t().diffSummary(folded.added, folded.removed), hidden: t().diffHidden(folded.hidden), expand: t().diffExpand }
821 return renderFoldedDiff($.ui.resolve(e), style, maskLines(folded), labels, () => update($, unfoldedDiffs, ids => [...ids, id]))
822 })
823 }
824
825 on('ui.render', { component: 'UserMessage' }, async ($, e, next) => {
826 const kind = e.props.origin.kind
827 const own = kind === 'composer' || kind === 'bridge' || (kind === 'unclassified' && !e.props.from && !e.props.task)
828 // Only the person's own prompts tell whether the transcript is the ctrl+o or --verbose one: a row under
829 // a speaker label (a teammate's, a task's, a hook's summary) is `isExpanded` whenever its body fits, and
830 // taking that for the whole view handed every tool row and diff back to the engine. A toggle changes
831 // no tool row's props, so the engine would keep their drawings: they are redrawn here.
832 if (own && e.props.isExpanded !== transcriptExpanded) {
833 transcriptExpanded = e.props.isExpanded
834 $.ui.invalidate('ui.render')
835 }
836 if (promptLogOn) notePromptRow($, e)
837 const drawn = !isDrawing || style.promptStyle === 'off' || !own ? await next(e) : renderUserPrompt($.ui.resolve(e), style, shown(e.props.text), Math.max(20, (e.viewport?.columns ?? 100) - 4))
838 return promptLogOn ? flashRow($, e, drawn) : drawn
839 })
840
841 // A command's row tells the log where the command drew; with drawing on, the row's own hook below does.
842 if (promptLogOn && !isDrawing) {
843 on('ui.render', { component: 'CommandOutput' }, async ($, e, next) => {
844 noteCommandRow($, e)
845 return flashRow($, e, await next(e))
846 })
847 }
848
849 if (!isDrawing) return
850
851 if (options.toolRows !== false) {
852 on('ui.render', { component: 'ToolGroup' }, ($, e, next) => {
853 if (e.props.isExpanded) {
854 for (const call of e.props.calls) if (call.tool_use_id) expandedCalls.add(call.tool_use_id)
855 return next(e)
856 }
857 return renderToolGroup($.ui.resolve(e), style, e.props.calls.map(shownRow), e.props.isActive, e.viewport?.columns, workDir, t().toolWords)
858 })
859 on('ui.render', { component: 'ToolUse' }, async ($, e, next) => {
860 const id = e.props.tool_use_id
861 if (transcriptExpanded || expandedCalls.has(id)) return e.props.tool === 'Bash' || e.props.tool === 'PowerShell' ? renderExpandedShell($.ui.resolve(e), style, shownRow(e.props)) : next(e)
862 const counts = oneLineEdits && !e.props.isErrored && isEdit(e.props.tool) ? editCounts(e.props.output) : undefined
863 const unfolded = counts !== undefined && (await read($, unfoldedDiffs)).includes(id)
864 const fold = counts === undefined ? undefined : { ...counts, expand: unfolded ? undefined : { label: t().diffExpand, onPress: () => update($, unfoldedDiffs, ids => [...ids, id]) } }
865 return renderToolRow($.ui.resolve(e), style, shownRow(e.props), e.viewport?.columns, workDir, t().toolWords, fold)
866 })
867 }
868
869 on('ui.render', { component: 'TurnDuration' }, ($, e) => renderTurnDuration($.ui.resolve(e), style, e.props.word, e.props.durationMs))
870
871
872 on('ui.render', { component: 'CommandOutput' }, async ($, e, next) => {
873 if (promptLogOn) noteCommandRow($, e)
874 // An answer to a plugin's own command arrives as "<plugin>: <text>", which breaks a table or heading on
875 // its first line; the echoed command above already says whose it is.
876 const text = shown(e.props.command === 'tessera' ? e.props.text.replace(/^tessera: /, '') : e.props.text)
877 const blocks = e.props.isErrored ? [] : parseCached(text)
878 const el = $.ui.resolve(e)
879 const columns = Math.max(20, (e.viewport?.columns ?? 100) - 4)
880 const drawn = blocks.length === 0 ? await next(e) : <el.Box flexDirection="column" rowGap={1} {...(style.reorder && hasRtl(text) ? { width: '100%' } : {})}>{drawMarkdown($, el, style, blocks, columns)}</el.Box>
881 return promptLogOn ? flashRow($, e, drawn) : drawn
882 })
883
884 on('ui.render', { component: 'AssistantMessage' }, ($, e, next) => {
885 const text = shown(e.props.text)
886 const blocks = parseCached(text)
887 if (blocks.length === 0) return next(e)
888 const el = $.ui.resolve(e)
889 const { Box, Text } = el
890 const columns = Math.max(20, (e.viewport?.columns ?? 100) - 4)
891 const narration = style.toolStyle === 'tree-bold' && blocks.length === 1 && blocks[0]!.kind === 'paragraph'
892 return (
893 <Box flexDirection="row">
894 <Box width={2} flexShrink={0}>
895 <Text color={style.theme.accent}>{e.props.isFirstOfReply ? '●' : ' '}</Text>
896 </Box>
897 <Box flexDirection="column" rowGap={1} flexGrow={1}>
898 {drawMarkdown($, el, narration ? { ...style, narration } : style, blocks, columns, blocks.length > 1 || hasRtl(text) ? text : undefined)}
899 </Box>
900 </Box>
901 )
902 })
903
904}
905hooks/platform.ts 65 lines1export type Env = Record<string, string | undefined>
2
3type Platform = 'windows' | 'wsl' | 'mac' | 'linux'
4
5export function platformOf(env: Env): Platform {
6 if (env.OS === 'Windows_NT') return 'windows'
7 if (env.WSL_DISTRO_NAME !== undefined) return 'wsl'
8 if (env.HOME?.startsWith('/Users/')) return 'mac'
9 return 'linux'
10}
11
12// Where Claude Code caches pastes: %TEMP%\claude on Windows, /tmp/claude-<uid> elsewhere ({uid} is filled in by the caller).
13export function pasteRoot(env: Env): string {
14 if (env.CLAUDE_CODE_TMPDIR) return env.CLAUDE_CODE_TMPDIR.replace(/\\/g, '/')
15 if (platformOf(env) === 'windows' && env.TEMP) return `${env.TEMP.replace(/\\/g, '/')}/claude`
16 return '/tmp/claude-{uid}'
17}
18
19// Whether Claude Code's Image element will show real pixels: kitty graphics outside a multiplexer, or forced on.
20export function drawsPixels(mode: string, env: Env): boolean {
21 if (mode === 'pixels') return true
22 if (mode === 'cells') return false
23 if (env.CLAUDE_CODE_FORCE_TERMINAL_IMAGES === '1') return true
24 if (env.TMUX !== undefined || env.STY !== undefined) return false
25 return env.TERM === 'xterm-kitty' || env.TERM === 'xterm-ghostty' || env.TERM_PROGRAM === 'ghostty' || env.KITTY_WINDOW_ID !== undefined
26}
27
28const fileUrl = (path: string) => `file:///${encodeURI(path.replace(/\\/g, '/').replace(/^\//, ''))}`
29
30export function openers(env: Env, path: string): string[][] {
31 const host: string[][] = []
32 if (env.TERM_PROGRAM === 'Orca') host.push(['orca', 'tab', 'create', '--url', fileUrl(path)])
33 if (env.TERM_PROGRAM === 'vscode') host.push(platformOf(env) === 'windows' ? ['cmd', '/c', 'code', '--reuse-window', path] : ['code', '--reuse-window', path])
34 return [...host, opener(env, path)]
35}
36
37// Commands that print the clipboard as UTF-8, tried in order. PowerShell is told to, since it otherwise
38// prints in the console code page and turns CJK text into question marks.
39export function clipboardReaders(env: Env): string[][] {
40 const powershell = '[Console]::OutputEncoding = [Text.Encoding]::UTF8; Get-Clipboard -Raw'
41 switch (platformOf(env)) {
42 case 'windows':
43 return [['powershell', '-NoProfile', '-NonInteractive', '-Command', powershell]]
44 case 'wsl':
45 return [['powershell.exe', '-NoProfile', '-NonInteractive', '-Command', powershell]]
46 case 'mac':
47 return [['pbpaste']]
48 case 'linux':
49 return [['wl-paste', '--no-newline'], ['xclip', '-selection', 'clipboard', '-o'], ['xsel', '--clipboard', '--output']]
50 }
51}
52
53function opener(env: Env, path: string): string[] {
54 switch (platformOf(env)) {
55 case 'windows':
56 return ['explorer.exe', path.replace(/\//g, '\\')]
57 case 'wsl':
58 return ['explorer.exe', `\\\\wsl.localhost\\${env.WSL_DISTRO_NAME}${path.replace(/\//g, '\\')}`]
59 case 'mac':
60 return ['open', path]
61 case 'linux':
62 return ['xdg-open', path]
63 }
64}
65hooks/inbox.ts 77 lines1type ChatLine = { at: string; who: string; text: string }
2
3export type InboxItem = ChatLine & { id: number; status: 'open' | 'fixed'; fixedBy?: string; reopenedFrom?: number }
4
5// "22:55 Amy 首頁按鈕沒反應", "[09:01] 王小明:表單送不出去", "14:03:12 Amy: login fails"
6const LINE = /^\s*\[?(\d{1,2}:\d{2})(?::\d{2})?\]?\s+([^\s::\]]{1,20})(?:\s*[::]\s*|\s+)(\S.{2,})$/
7
8// A paste counts as a chat log only when at least two of its lines look like timestamped messages.
9export function parseChat(text: string): ChatLine[] {
10 const lines = text.split(/\r?\n/).flatMap(l => {
11 const m = LINE.exec(l)
12 return m ? [{ at: m[1] ?? '', who: m[2] ?? '', text: (m[3] ?? '').trim() }] : []
13 })
14 return lines.length >= 2 ? lines : []
15}
16
17const grams = (s: string) => {
18 const chars = [...s.toLowerCase().replace(/[\s\p{P}\p{S}]+/gu, '')]
19 const out = new Set<string>()
20 for (let i = 0; i + 1 < chars.length; i++) out.add(`${chars[i]}${chars[i + 1]}`)
21 return out
22}
23
24// Dice coefficient over character bigrams, which treats Chinese and English text alike.
25export function similarity(a: string, b: string): number {
26 const x = grams(a)
27 const y = grams(b)
28 if (x.size === 0 || y.size === 0) return 0
29 let both = 0
30 for (const g of x) if (y.has(g)) both++
31 return (2 * both) / (x.size + y.size)
32}
33
34const SIMILAR = 0.55
35
36type Intake = { items: InboxItem[]; added: InboxItem[]; regressions: { item: InboxItem; like: InboxItem }[] }
37
38export function intake(items: InboxItem[], lines: ChatLine[]): Intake {
39 const next = [...items]
40 const added: InboxItem[] = []
41 const regressions: Intake['regressions'] = []
42 let id = items.reduce((m, i) => Math.max(m, i.id), 0)
43 for (const line of lines) {
44 if (next.some(i => i.status === 'open' && i.text === line.text)) continue
45 const like = next
46 .filter(i => i.status === 'fixed')
47 .map(i => ({ i, score: similarity(i.text, line.text) }))
48 .filter(c => c.score >= SIMILAR)
49 .sort((a, b) => b.score - a.score)[0]?.i
50 const item: InboxItem = { ...line, id: ++id, status: 'open', ...(like ? { reopenedFrom: like.id } : {}) }
51 next.push(item)
52 added.push(item)
53 if (like) regressions.push({ item, like })
54 }
55 return { items: next, added, regressions }
56}
57
58export function markFixed(items: InboxItem[], ids: number[], commit: string): InboxItem[] {
59 return items.map(i => (ids.includes(i.id) ? { ...i, status: 'fixed' as const, fixedBy: commit } : i))
60}
61
62const clip = (s: string, n: number) => ([...s].length > n ? `${[...s].slice(0, n - 1).join('')}…` : s)
63
64export function intakeNote(result: Intake): string {
65 const lines = [`tessera feedback inbox: filed ${result.added.map(i => `#${i.id}`).join(', ')} from the pasted chat log.`]
66 for (const { item, like } of result.regressions)
67 lines.push(`#${item.id} ("${clip(item.text, 40)}") resembles #${like.id} ("${clip(like.text, 40)}"), marked fixed in ${like.fixedBy ?? 'an earlier change'}: check whether that fix regressed before fixing it again.`)
68 lines.push('When you fix items, call the tessera inbox_fixed tool with their numbers and the commit.')
69 return lines.join('\n')
70}
71
72export function listText(items: InboxItem[], empty: string, headers: readonly string[]): string {
73 if (items.length === 0) return empty
74 const mark = (i: InboxItem) => (i.status === 'fixed' ? `✓ ${i.fixedBy ?? ''}`.trim() : i.reopenedFrom ? `↺ #${i.reopenedFrom}` : '…')
75 return [`| ${headers.join(' | ')} |`, '|---|---|---|---|---|', ...items.slice(-40).map(i => `| ${i.id} | ${i.at} | ${i.who} | ${clip(i.text, 48).replace(/\|/g, '\\|')} | ${mark(i)} |`)].join('\n')
76}
77hooks/markdown.ts 223 lines1export type Inline =
2 | { kind: 'text'; text: string }
3 | { kind: 'strong'; children: Inline[] }
4 | { kind: 'emphasis'; children: Inline[] }
5 | { kind: 'strike'; children: Inline[] }
6 | { kind: 'code'; text: string }
7 | { kind: 'link'; text: string; href: string }
8 | { kind: 'number'; text: string }
9 | { kind: 'path'; text: string }
10 | { kind: 'dim'; text: string }
11
12export type Block = { raw: string } & (
13 | { kind: 'heading'; level: number; inline: Inline[] }
14 | { kind: 'paragraph'; inline: Inline[] }
15 | { kind: 'list'; ordered: boolean; items: { marker: string; depth: number; task?: boolean; inline: Inline[] }[] }
16 | { kind: 'code'; lang: string; lines: string[] }
17 | { kind: 'quote'; inline: Inline[] }
18 | { kind: 'alert'; level: AlertLevel; inline: Inline[] }
19 | { kind: 'rule' }
20 | { kind: 'table'; header: Inline[][]; align: ('left' | 'right' | 'center')[]; rows: Inline[][][] }
21)
22
23type Draft = Block extends infer B ? (B extends unknown ? Omit<B, 'raw'> : never) : never
24
25export type AlertLevel = 'note' | 'tip' | 'important' | 'warning' | 'caution'
26const ALERT = /^\[!(note|tip|important|warning|caution)\]\s*(.*)$/i
27
28// A line break inside a paragraph reads as a space, except between Chinese or Japanese characters, which
29// take none: a reply wrapped by hand would otherwise show a space at each of its line ends.
30const CJK_END = /[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana} -〿-]\s*$/u
31const CJK_START = /^\s*[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana} -〿-]/u
32const joinLines = (lines: readonly string[]): string =>
33 lines.reduce((text, line, i) => (i === 0 ? line : CJK_END.test(text) && CJK_START.test(line) ? text.trimEnd() + line.trimStart() : `${text} ${line}`), '')
34
35export type Highlight = { numbers: boolean; paths: boolean }
36
37const MAX_INLINE = 4000
38const TABLE_SEP = /^\s*\|?\s*:?-{2,}:?\s*(\|\s*:?-{2,}:?\s*)*\|?\s*$/
39const LIST_ITEM = /^(\s*)([-*+]|\d+[.)])\s+(.*)$/
40const FENCE = /^\s*(`{3,}|~{3,})\s*([\w+-]*)/
41
42const splitRow = (line: string): string[] => {
43 const trimmed = line.trim().replace(/^\|/, '').replace(/(?<!\\)\|$/, '')
44 const cells: string[] = []
45 let cell = ''
46 for (let i = 0; i < trimmed.length; i++) {
47 const ch = trimmed[i]
48 if (ch === '\\' && trimmed[i + 1] === '|') {
49 cell += '|'
50 i++
51 } else if (ch === '|') {
52 cells.push(cell.trim())
53 cell = ''
54 } else {
55 cell += ch
56 }
57 }
58 cells.push(cell.trim())
59 return cells
60}
61
62// A bare URL ends before CJK text and punctuation (U+3000-303F and the full-width punctuation, not the
63// full-width letters and digits), which follow a link with no space in CJK prose, except CJK right
64// after / = # % - _ or ·, where it is a path or query (zh.wikipedia.org/wiki/中文, …/中文-文件). A CJK
65// character right after a Latin letter or digit (wiki/C語言) ends the link: that is also how a link
66// before 就知道 ends, and the two cannot be told apart.
67const CJK_LETTERS = '\\p{Script=Han}\\p{Script=Hiragana}\\p{Script=Katakana}\\p{Script=Hangul}'
68const CJK_PUNCT = ' -〿-/:-@[-`{-'
69const URL = `https?:\\/\\/(?:[^\\s<>()${CJK_LETTERS}${CJK_PUNCT}]|(?<=[/=#%_·-])[${CJK_LETTERS}]+)*(?:[^\\s<>().,;:!?'"${CJK_LETTERS}${CJK_PUNCT}]|(?<=[/=#%_·-])[${CJK_LETTERS}]+)`
70const INLINE = new RegExp(`(\`+)(?!\`)(.+?)(?<!\`)\\1(?!\`)|\\[([^\\]]+)\\]\\(([^)\\s]+)\\)|\\*\\*([^*]+?)\\*\\*|__([^_]+?)__|~~([^~]+?)~~|(?<![\\w*])\\*([^*\\s][^*]*?)\\*(?!\\w)|(?<![\\w_])_([^_\\s][^_]*?)_(?!\\w)|(${URL})`, 'gu')
71const NUMBER = /(?<![\w.#/-])(v?\d+(?:[.,:]\d+)*(?:%|ms|s|m|h|d|Gi|Mi|GB|MB|KB|x)?)(?![\w/])/g
72const PATH = /(?<![\w/.:])((?:~|\.{1,2})?\/[\w.@+-]+(?:\/[\w.@+-]*)*)/g
73
74const decorate = (text: string, hl: Highlight): Inline[] => {
75 if (!hl.numbers && !hl.paths) return [{ kind: 'text', text }]
76 const marks: { start: number; end: number; kind: 'number' | 'path' }[] = []
77 if (hl.paths) for (const m of text.matchAll(PATH)) marks.push({ start: m.index, end: m.index + m[0].length, kind: 'path' })
78 if (hl.numbers) {
79 for (const m of text.matchAll(NUMBER)) {
80 const start = m.index
81 if (!marks.some(p => start < p.end && start + m[0].length > p.start)) {
82 marks.push({ start, end: start + m[0].length, kind: 'number' })
83 }
84 }
85 }
86 marks.sort((a, b) => a.start - b.start)
87 const out: Inline[] = []
88 let at = 0
89 for (const m of marks) {
90 if (m.start > at) out.push({ kind: 'text', text: text.slice(at, m.start) })
91 out.push({ kind: m.kind, text: text.slice(m.start, m.end) })
92 at = m.end
93 }
94 if (at < text.length) out.push({ kind: 'text', text: text.slice(at) })
95 return out
96}
97
98export const parseInline = (text: string, hl: Highlight): Inline[] => {
99 if (text.length > MAX_INLINE) return [{ kind: 'text', text }]
100 const out: Inline[] = []
101 let at = 0
102 for (const m of text.matchAll(INLINE)) {
103 if (m.index > at) out.push(...decorate(text.slice(at, m.index), hl))
104 if (m[2] !== undefined) out.push({ kind: 'code', text: m[2] })
105 else if (m[3] !== undefined) out.push({ kind: 'link', text: m[3], href: m[4] ?? "" })
106 else if (m[5] !== undefined || m[6] !== undefined) out.push({ kind: 'strong', children: parseInline(m[5] ?? m[6] ?? "", hl) })
107 else if (m[7] !== undefined) out.push({ kind: 'strike', children: parseInline(m[7], hl) })
108 else if (m[8] !== undefined || m[9] !== undefined) out.push({ kind: 'emphasis', children: parseInline(m[8] ?? m[9] ?? "", hl) })
109 else if (m[10] !== undefined) out.push({ kind: 'link', text: m[10], href: m[10] })
110 at = m.index + m[0].length
111 }
112 if (at < text.length) out.push(...decorate(text.slice(at), hl))
113 return out
114}
115
116export const inlineText = (inline: Inline[]): string =>
117 inline.map(n => ('children' in n ? inlineText(n.children) : n.text)).join('')
118
119export const parse = (source: string, hl: Highlight): Block[] => {
120 const lines = source.replace(/\r\n?/g, '\n').split('\n')
121 const at = (n: number) => lines[n] ?? ''
122 const blocks: Block[] = []
123 const add = (block: Draft, from: number, to: number) => blocks.push({ ...block, raw: lines.slice(from, to).join('\n') } as Block)
124 let paraStart = 0
125 let para: string[] = []
126
127 const flush = (end: number) => {
128 if (para.length) add({ kind: 'paragraph', inline: parseInline(joinLines(para), hl) }, paraStart, end)
129 para = []
130 }
131
132 for (let i = 0; i < lines.length; i++) {
133 const line = at(i)
134 const fence = FENCE.exec(line)
135 if (fence) {
136 flush(i)
137 const start = i
138 const run = fence[1] ?? '```'
139 const closer = new RegExp(`^\\s*\\${run[0]}{${run.length},}\\s*$`)
140 const body: string[] = []
141 i++
142 while (i < lines.length && !closer.test(at(i))) body.push(at(i++))
143 add({ kind: 'code', lang: fence[2] ?? '', lines: body }, start, i + 1)
144 continue
145 }
146 if (line.trim() === '') {
147 flush(i)
148 continue
149 }
150 const heading = /^(#{1,6})\s+(.*?)\s*#*\s*$/.exec(line)
151 if (heading) {
152 flush(i)
153 add({ kind: 'heading', level: (heading[1] ?? '#').length, inline: parseInline(heading[2] ?? '', hl) }, i, i + 1)
154 continue
155 }
156 if (/^\s*([-*_])(\s*\1){2,}\s*$/.test(line)) {
157 flush(i)
158 add({ kind: 'rule' }, i, i + 1)
159 continue
160 }
161 if (line.includes('|') && i + 1 < lines.length && TABLE_SEP.test(at(i + 1))) {
162 flush(i)
163 const start = i
164 const header = splitRow(line)
165 const align = splitRow(at(i + 1)).map(c =>
166 c.startsWith(':') && c.endsWith(':') ? 'center' : c.endsWith(':') ? 'right' : 'left',
167 )
168 i += 2
169 const rows: Inline[][][] = []
170 while (i < lines.length && at(i).includes('|') && at(i).trim() !== '') {
171 const cells = splitRow(at(i++))
172 rows.push(header.map((_, c) => parseInline(cells[c] ?? '', hl)))
173 }
174 add({ kind: 'table', header: header.map(c => parseInline(c, { numbers: false, paths: false })), align, rows }, start, i)
175 i--
176 continue
177 }
178 if (/^\s*>/.test(line)) {
179 flush(i)
180 const start = i
181 const body: string[] = []
182 while (i < lines.length && /^\s*>/.test(at(i))) body.push(at(i++).replace(/^\s*>\s?/, ''))
183 const alert = ALERT.exec(body[0] ?? '')
184 if (alert) add({ kind: 'alert', level: alert[1]!.toLowerCase() as AlertLevel, inline: parseInline(joinLines([alert[2]!, ...body.slice(1)]).trim(), hl) }, start, i)
185 else add({ kind: 'quote', inline: parseInline(joinLines(body), hl) }, start, i)
186 i--
187 continue
188 }
189 const item = LIST_ITEM.exec(line)
190 if (item) {
191 flush(i)
192 const start = i
193 const ordered = /\d/.test(item[2] ?? '')
194 const items: { marker: string; depth: number; task?: boolean; inline: Inline[] }[] = []
195 const contentIndent: number[] = []
196 while (i < lines.length) {
197 const it = LIST_ITEM.exec(at(i))
198 if (it) {
199 contentIndent.push((it[1] ?? '').replace(/\t/g, ' ').length + (it[2] ?? '').length + 1)
200 const task = /^\[([ xX])\]\s+(.*)$/.exec(it[3] ?? '')
201 items.push({ marker: it[2] ?? '-', depth: Math.floor((it[1] ?? '').replace(/\t/g, ' ').length / 2), ...(task ? { task: task[1] !== ' ' } : {}), inline: parseInline(task ? task[2]! : it[3] ?? '', hl) })
202 } else if (/^\s{2,}\S/.test(at(i)) && items.length) {
203 const indent = (at(i).match(/^\s*/)?.[0] ?? '').replace(/\t/g, ' ').length
204 let owner = items.length - 1
205 while (owner > 0 && contentIndent[owner]! > indent) owner--
206 const target = items[owner]!
207 target.inline = [...target.inline, { kind: 'text', text: ' ' }, ...parseInline(at(i).trim(), hl)]
208 } else {
209 break
210 }
211 i++
212 }
213 add({ kind: 'list', ordered, items }, start, i)
214 i--
215 continue
216 }
217 if (!para.length) paraStart = i
218 para.push(line.trim())
219 }
220 flush(lines.length)
221 return blocks
222}
223hooks/mermaid.tsx 160 lines1import type { ElementTable, RenderElement } from 'claude-code'
2
3import { remember, width } from './render'
4import type { Style } from './theme'
5import { renderMermaidAscii, setChartSize } from './vendor/mermaid-text.js'
6
7const MAX_LINES = 80
8
9// The diagram library sizes boxes by UTF-16 length, so a wide character one unit long gets a
10// private-use pad after it while laying out; the pads come out when the art is drawn or copied.
11const PAD = String.fromCharCode(0xe000)
12const padWide = (s: string) => [...s].map(c => c + PAD.repeat(Math.max(0, width(c) - c.length))).join('')
13export const unpad = (s: string) => s.replaceAll(PAD, '')
14const textCache = new Map<string, string | null>()
15
16export const chartSize = (columns: number, source = '') => {
17 const labels = (/^\s*x-axis\b[^[\n]*\[([^\]\n]*)\]/m.exec(source)?.[1] ?? '').split(',').map(s => s.trim().replace(/^"|"$/g, ''))
18 const fit = labels.length * (Math.max(...labels.map(width)) + 2)
19 const w = Math.max(24, Math.min(60, Math.max(Math.floor(columns / 6), fit), columns - 12))
20 return { width: w, height: Math.max(8, Math.min(20, Math.round(w * 0.3))) }
21}
22
23const unquoteCategories = (source: string) =>
24 source.replace(/^(\s*x-axis\b[^[\n]*\[)([^\]\n]*)\]/m, (_, head: string, items: string) => `${head}${items.replace(/"([^"]*)"/g, (_q, s: string) => s.replaceAll(',', ' '))}]`)
25
26const labelBars = (art: string, source: string): string => {
27 const series = source.match(/^\s*(bar|line)\b.*$/gm) ?? []
28 const values = /^\s*bar\b[^[\n]*\[([^\]\n]*)\]/m.exec(source)?.[1]?.split(',').map(v => v.trim())
29 if (series.length !== 1 || !values || /^\s*xychart(-beta)?\s+horizontal/m.test(source)) return art
30 const grid = art.split('\n').map(l => [...l])
31 const axis = grid.findLastIndex(row => row.includes('┬'))
32 const ticks = grid[axis]?.flatMap((ch, x) => (ch === '┬' ? [x] : [])) ?? []
33 if (ticks.length !== values.length) return art
34 ticks.forEach((x, k) => {
35 const top = grid.findIndex(row => row[x] === '█')
36 const y = top === -1 ? axis - 1 : top - 1
37 const text = [...values[k]!]
38 const from = x - Math.floor((text.length - 1) / 2)
39 const row = grid[y]
40 if (!row || y < 0) return
41 while (row.length < from + text.length) row.push(' ')
42 if (!text.every((_, i) => /[ ·]/.test(row[from + i] ?? ' '))) return
43 text.forEach((ch, i) => (row[from + i] = ch))
44 })
45 return grid.map(row => row.join('').trimEnd()).join('\n')
46}
47
48export const mermaidText =(source: string, ascii: boolean, columns: number): string | null => {
49 if (source.length > 8000 || source.split('\n').length > MAX_LINES) return null
50 const isChart = /^\s*xychart/.test(source)
51 const size = chartSize(columns, isChart ? source : '')
52 const key = `${ascii}:${isChart ? size.width : 0}:${source}`
53 return remember(textCache, key, () => {
54 try {
55 if (isChart) setChartSize(size.width, size.height)
56 const art = renderMermaidAscii(unquoteCategories(padWide(source).replace(/^(\s*%%[^\n]*\n)+/, '')).replace(/(-->|-\.->|==>|---|-\.-|===)[ \t]+\|/g, '$1|'), { useAscii: ascii, colorMode: 'none', paddingX: 3, paddingY: 1 }).replace(/[ \t]+$/gm, '').trimEnd().replace(/▶/g, '►').replace(/◀/g, '◄')
57 return isChart ? labelBars(art, source) : art.split('\n').filter(l => !/^[\s│|]*$/.test(l)).join('\n')
58 } catch {
59 return null
60 }
61 })
62}
63
64// A diagram wider than the terminal is drawn as code. A flowchart laid out left to right grows by a box
65// per node, so one that does not fit is laid out top down and tried again before giving up.
66const fits = (art: string, columns: number) => unpad(art).split('\n').every(l => width(l) <= columns - 2)
67const turnedDown = (source: string): string | undefined => {
68 const down = source.replace(/^(\s*(?:graph|flowchart)\s+)(?:LR|RL)\b/m, '$1TD')
69 return down === source ? undefined : down
70}
71
72export const mermaidFit = (source: string, ascii: boolean, columns: number): string | null => {
73 const art = mermaidText(source, ascii, columns)
74 if (art !== null && fits(art, columns)) return art
75 const down = turnedDown(source)
76 const again = down === undefined ? null : mermaidText(down, ascii, columns)
77 return again !== null && fits(again, columns) ? again : null
78}
79
80const LINE = /[─-╿◇]/
81const ARROW = /[►◄▲▼]/
82
83const paint = (art: string, style: Style): (string | undefined)[][] => {
84 const t = style.theme
85 const grid = art.split('\n').map(l => [...l])
86 const cell = (r: number, c: number) => grid[r]?.[c] ?? ''
87 const color: (string | undefined)[][] = grid.map(row => row.map(() => undefined))
88 const palette = [...new Set([t.link, t.number, t.heading, t.emphasis, t.path, t.codeFlag, t.accent])].filter((c): c is string => c !== undefined)
89 const next = (i: number) => palette[i % palette.length]
90 const labels = new Map<string, string | undefined>()
91
92 const rects: { r: number; c: number; r2: number; c2: number }[] = []
93 for (let r = 0; r < grid.length; r++) {
94 for (let c = 0; c < (grid[r]?.length ?? 0); c++) {
95 if (!/[┌╭(]/.test(cell(r, c))) continue
96 let c2 = c + 1
97 while (/[─┬┴┼▲▼]/.test(cell(r, c2))) c2++
98 if (!/[┐╮)]/.test(cell(r, c2)) || c2 === c + 1) continue
99 let r2 = r + 1
100 while (/[│├┤┼►◄]/.test(cell(r2, c))) r2++
101 if (!/[└╰(]/.test(cell(r2, c)) || !/[┘╯)]/.test(cell(r2, c2))) continue
102 rects.push({ r, c, r2, c2 })
103 }
104 }
105 const inside = (a: (typeof rects)[number], b: (typeof rects)[number]) => a !== b && b.r > a.r && b.r2 < a.r2 && b.c > a.c && b.c2 < a.c2
106 for (const box of rects.filter(a => !rects.some(b => inside(a, b)))) {
107 const { r, c, r2, c2 } = box
108 const label = grid.slice(r + 1, r2).map(row => row.slice(c + 1, c2).join('')).join(' ').trim()
109 if (!labels.has(label)) labels.set(label, next(labels.size))
110 const hue = labels.get(label)
111 for (let y = r; y <= r2; y++) for (let x = c; x <= c2; x++) if (cell(y, x).trim()) color[y]![x] = hue
112 }
113
114 const bars = [...new Set(grid.flatMap(row => row.flatMap((ch, c) => (ch === '█' && row[c - 1] !== '█' ? [c] : []))))].sort((a, b) => a - b)
115 const ticks = grid.findLast(row => row.includes('┬'))?.filter(ch => ch === '┬').length ?? 0
116 const tops = bars.map(x => grid.findIndex(row => row[x] === '█'))
117 const single = bars.length > 1 && bars.length <= ticks
118 const barColor = (i: number) => (single ? (tops[i] === Math.min(...tops) ? t.emphasis ?? t.accent : t.quote) : next(i))
119 grid.forEach((row, r) =>
120 row.forEach((ch, c) => {
121 if (color[r]![c] !== undefined) return
122 if (ch === '█') {
123 let start = c
124 while (row[start - 1] === '█') start--
125 color[r]![c] = barColor(bars.indexOf(start))
126 } else if (ch === '·') color[r]![c] = t.rule
127 else if (ARROW.test(ch)) color[r]![c] = t.accent
128 else if (LINE.test(ch)) color[r]![c] = t.diagram
129 else if (/^\d+[┤┼]/.test(row.slice(c).join(''))) color[r]![c] = t.number
130 else color[r]![c] = t.diagramText
131 }),
132 )
133 return color
134}
135
136const painted = new WeakMap<Style, Map<string, (string | undefined)[][]>>()
137
138export const boxArt = ({ Box, Text }: ElementTable, style: Style, art: string, key: string): RenderElement => {
139 const cache = painted.get(style) ?? new Map<string, (string | undefined)[][]>()
140 painted.set(style, cache)
141 const colors = remember(cache, art, () => paint(art, style))
142 return (
143 <Box key={key} flexDirection="column" paddingLeft={2}>
144 {art.split('\n').map((line, i) => {
145 const chars = [...line]
146 const parts: RenderElement[] = []
147 let at = 0
148 while (at < chars.length) {
149 const hue = colors[i]?.[at]
150 let end = at + 1
151 while (end < chars.length && colors[i]?.[end] === hue) end++
152 parts.push(<Text key={`t${parts.length}`} color={hue}>{unpad(chars.slice(at, end).join(''))}</Text>)
153 at = end
154 }
155 return <Text key={`${key}.${i}`}>{parts.length ? parts : ' '}</Text>
156 })}
157 </Box>
158 )
159}
160hooks/render.tsx 918 lines1import type { ElementTable, RenderElement } from 'claude-code'
2
3import type { DiffLine, Folded } from './fold'
4import type { ToolKind, ToolWords } from './i18n'
5import { STRINGS } from './i18n'
6import type { Block, Inline } from './markdown'
7import { inlineText } from './markdown'
8import { commentTail, commentVisual, flow, hasRtl } from './rtl'
9import type { Style, Theme } from './theme'
10import type { PrismToken } from './vendor/prism.js'
11import { languages, tokenize } from './vendor/prism.js'
12
13const WIDE = /[\u1100-\u115F\u2E80-\uA4CF\uAC00-\uD7A3\uF900-\uFAFF\uFE30-\uFE4F\uFF00-\uFF60\uFFE0-\uFFE6\u{20000}-\u{3FFFD}]|\p{Extended_Pictographic}/u
14const segmenter = typeof Intl !== 'undefined' && 'Segmenter' in Intl ? new Intl.Segmenter() : undefined
15
16const graphemes = (s: string): string[] => (segmenter ? [...segmenter.segment(s)].map(g => g.segment) : [...s])
17
18export const width = (s: string): number =>
19 graphemes(s).reduce((w, g) => (/^\p{M}+$/u.test(g) ? w : w + (WIDE.test(g) ? 2 : 1)), 0)
20
21// Where a line may break: between words, and between Chinese or Japanese characters, which take no spaces.
22// Closing punctuation stays with the character before it and opening punctuation with the one after, so no
23// line starts with 「,」 or ends with 「「」. Korean puts spaces between words, so it breaks there.
24const OPEN = '「『(《〈【〔“‘'
25const HAN = '\\p{Script=Han}\\p{Script=Hiragana}\\p{Script=Katakana}'
26const CLOSE = '」』)》〉】〕”’,。、:;!?…‥ー・%'
27const BREAKS = new RegExp(`[${OPEN}]*[${HAN}][${CLOSE}]*|[${OPEN}]*[^\\s${HAN}${OPEN}]+|[${OPEN}]+`, 'gu')
28const HAS_HAN = new RegExp(`[${HAN}]`, 'u')
29
30// The text cut where a line may break, each piece with the spaces after it.
31export const breakUnits = (text: string): string[] => {
32 const starts = [...text.matchAll(BREAKS)].map(m => m.index)
33 return starts.map((start, i) => text.slice(start, starts[i + 1] ?? text.length))
34}
35
36// The text measured once: the width up to each grapheme boundary, so a slice's width is a subtraction.
37// A Chinese paragraph breaks between every two characters, and measuring each candidate line from its
38// start made wrapping quadratic: 2,880 characters took 150 ms, on every streamed delta.
39type Measured = { ends: number[]; widths: number[]; boundary: Int32Array }
40
41const measure = (text: string): Measured => {
42 const ends = [0]
43 const widths = [0]
44 const boundary = new Int32Array(text.length + 1).fill(-1)
45 let at = 0
46 let w = 0
47 boundary[0] = 0
48 for (const g of graphemes(text)) {
49 at += g.length
50 w += /^\p{M}+$/u.test(g) ? 0 : WIDE.test(g) ? 2 : 1
51 boundary[at] = ends.length
52 ends.push(at)
53 widths.push(w)
54 }
55 return { ends, widths, boundary }
56}
57
58// The grapheme boundary at an offset, or the nearest one in the direction given: a break unit can start
59// or end inside a cluster (a combining mark or variation selector after a character), and then the
60// cluster's start stands for the unit's start and its end for the unit's end, so the cluster's width
61// is counted once and it is never cut.
62const boundaryAt = (m: Measured, offset: number, direction: -1 | 1): number => {
63 let o = offset
64 while (o > 0 && o < m.boundary.length && m.boundary[o] === -1) o += direction
65 return Math.max(m.boundary[o] ?? 0, 0)
66}
67
68export const wrapRanges = (text: string, w: number): [number, number][] => {
69 // Most texts fit (every short table cell): one width pass, no tables built.
70 if (width(text) <= w) return [[0, text.length]]
71 const m = measure(text)
72 const between = (a: number, b: number) => m.widths[boundaryAt(m, b, 1)]! - m.widths[boundaryAt(m, a, -1)]!
73 const out: [number, number][] = []
74 let line: [number, number] | undefined
75 for (const word of text.matchAll(BREAKS)) {
76 let start = word.index
77 const end = start + word[0].length
78 while (between(start, end) > w) {
79 if (line) out.push(line)
80 line = undefined
81 // The longest run of whole graphemes from start that fits, at least one; a unit's end inside a
82 // cluster takes the whole cluster.
83 const from = boundaryAt(m, start, -1)
84 const last = boundaryAt(m, end, 1)
85 let i = from + 1
86 while (i + 1 <= last && m.widths[i + 1]! - m.widths[from]! <= w) i++
87 const cut = Math.min(m.ends[i]!, Math.max(end, m.ends[last]!))
88 out.push([start, cut])
89 start = cut
90 if (start >= end) break
91 }
92 if (start === end) continue
93 if (line && between(line[0], end) <= w) line = [line[0], end]
94 else {
95 if (line) out.push(line)
96 line = [start, end]
97 }
98 }
99 if (line) out.push(line)
100 return out.length ? out : [[0, 0]]
101}
102
103const sliceInline = (nodes: Inline[], from: number, to: number): Inline[] => {
104 const out: Inline[] = []
105 let at = 0
106 for (const n of nodes) {
107 const length = inlineText([n]).length
108 const a = Math.max(from - at, 0)
109 const b = Math.min(to - at, length)
110 at += length
111 if (a >= b) continue
112 if ('children' in n) out.push({ ...n, children: sliceInline(n.children, a, b) })
113 else out.push({ ...n, text: n.text.slice(a, b) })
114 }
115 return out
116}
117
118const hasLink = (nodes: Inline[]): boolean => nodes.some(n => n.kind === 'link' || ('children' in n && hasLink(n.children)))
119
120const mostLines = (text: string, w: number): number => (text.match(/\S+/g)?.length ?? 0) + Math.ceil(width(text) / w)
121
122const wrapInline = (nodes: Inline[], w: number): Inline[][] => {
123 const text = inlineText(nodes)
124 const ranges = wrapRanges(text, w)
125 return ranges.length === 1 && ranges[0]![0] === 0 && ranges[0]![1] === text.length ? [nodes] : ranges.map(([a, b]) => sliceInline(nodes, a, b))
126}
127
128const flowOf = (style: Style, nodes: Inline[], columns: number) => (style.reorder ? flow(nodes, columns, width, style.shape) : null)
129
130const renderInline = (el: ElementTable, style: Style, nodes: Inline[], keyBase: string): RenderElement[] => {
131 const { Text } = el
132 const t = style.theme
133 return nodes.map((n, i) => {
134 const key = `${keyBase}.${i}`
135 switch (n.kind) {
136 case 'text':
137 return <Text key={key}>{n.text}</Text>
138 case 'strong':
139 return <Text key={key} bold color={t.strong}>{renderInline(el, style, n.children, key)}</Text>
140 case 'emphasis':
141 return <Text key={key} italic color={t.emphasis}>{renderInline(el, style, n.children, key)}</Text>
142 case 'strike':
143 return <Text key={key} strikethrough dimColor>{renderInline(el, style, n.children, key)}</Text>
144 case 'code':
145 return <Text key={key} color={t.inlineCode}>{n.text}</Text>
146 case 'link':
147 return /^[a-z][\w+.-]*:/i.test(n.href)
148 ? n.text === n.href ? <el.Link key={key} href={n.href} /> : <el.Link key={key} href={n.href}><Text color={t.link} underline>{n.text}</Text></el.Link>
149 : <Text key={key} color={t.link} underline>{n.text}</Text>
150 case 'number':
151 return <Text key={key} color={t.number}>{n.text}</Text>
152 case 'path':
153 return <Text key={key} color={t.path}>{n.text}</Text>
154 case 'dim':
155 return <Text key={key} dimColor>{n.text}</Text>
156 }
157 })
158}
159
160type TextProps = { italic?: boolean; color?: string; bold?: boolean; dimColor?: boolean; strikethrough?: boolean }
161
162const renderFlow = (el: ElementTable, style: Style, lines: Inline[][], key: string, props: TextProps = {}) => {
163 const { Text } = el
164 return lines.map((line, i) => <Text key={`${key}.${i}`} {...props}>{renderInline(el, style, line, `${key}.${i}`)}</Text>)
165}
166
167// The terminal wraps only at spaces, so a Chinese or Japanese run too long for the rest of a line moves
168// whole to the next one and leaves the line before nearly empty. Such text is broken into lines here.
169const renderWrapped = (el: ElementTable, style: Style, nodes: Inline[], w: number, key: string, props: TextProps = {}) => {
170 const text = inlineText(nodes)
171 if (!HAS_HAN.test(text) || width(text) <= w) return <el.Text key={key} {...props}>{renderInline(el, style, nodes, key)}</el.Text>
172 return <el.Box key={key} flexDirection="column">{renderFlow(el, style, wrapInline(nodes, w), key, props)}</el.Box>
173}
174
175const PRISM_COLORS: Record<string, keyof Theme> = {
176 comment: 'codeComment', prolog: 'codeComment', doctype: 'codeComment', cdata: 'codeComment',
177 string: 'codeString', char: 'codeString', 'template-string': 'codeString', 'attr-value': 'codeString', url: 'codeString',
178 number: 'number', boolean: 'number', constant: 'number', symbol: 'number', inserted: 'number',
179 keyword: 'codeFlag', important: 'codeFlag', atrule: 'codeFlag', rule: 'codeFlag', deleted: 'codeFlag',
180 function: 'codeCommand', 'class-name': 'codeCommand', builtin: 'codeCommand', key: 'codeCommand', selector: 'codeCommand',
181 property: 'link', tag: 'link', 'attr-name': 'emphasis', variable: 'emphasis', regex: 'path',
182}
183
184type Segment = { text: string; color?: string; italic: boolean }
185
186const flatten = (tokens: PrismToken[], style: Style, color?: string, italic = false): Segment[] =>
187 tokens.flatMap(token => {
188 if (typeof token === 'string') return [{ text: token, color, italic }]
189 const names = [token.type, ...(Array.isArray(token.alias) ? token.alias : token.alias ? [token.alias] : [])]
190 const slot = names.map(n => PRISM_COLORS[n]).find(Boolean)
191 const inner = Array.isArray(token.content) ? token.content : [token.type === 'comment' && typeof token.content === 'string' && style.reorder ? commentVisual(token.content, style.shape) : token.content]
192 return flatten(inner, style, slot ? style.theme[slot] : color, italic || token.type === 'comment')
193 })
194
195export const remember = <T,>(cache: Map<string, T>, key: string, make: () => T, limit = 200): T => {
196 const hit = cache.get(key)
197 if (hit !== undefined) return hit
198 const value = make()
199 cache.set(key, value)
200 if (cache.size > limit) cache.delete(cache.keys().next().value!)
201 return value
202}
203
204const highlighted = new WeakMap<Style, Map<string, Segment[][]>>()
205
206const grammarFor = (lang: string) => {
207 const name = lang.toLowerCase()
208 const grammar = Object.hasOwn(languages, name) ? languages[name] : undefined
209 return grammar !== null && typeof grammar === 'object' ? grammar : undefined
210}
211
212export const highlightBlock = ({ Text }: ElementTable, style: Style, lines: string[], lang: string, key: string): RenderElement[] | null => {
213 const grammar = grammarFor(lang)
214 if (!grammar) return null
215 const code = lines.join('\n')
216 const cache = highlighted.get(style) ?? new Map<string, Segment[][]>()
217 highlighted.set(style, cache)
218 const rows = remember(cache, `${lang}\0${code}`, () => {
219 const out: Segment[][] = [[]]
220 for (const seg of flatten(tokenize(code, grammar), style)) {
221 seg.text.split('\n').forEach((piece, i) => {
222 if (i > 0) out.push([])
223 if (piece) out[out.length - 1]!.push({ ...seg, text: piece })
224 })
225 }
226 return out
227 })
228 return rows.map((row, r) => (
229 <Text key={`${key}.${r}`} color={style.theme.codeText}>
230 {row.length ? row.map((s, i) => <Text key={`${key}.${r}.${i}`} color={s.color} italic={s.italic}>{s.text}</Text>) : ' '}
231 </Text>
232 ))
233}
234
235const isShellLang = (lang: string) => lang === '' || /^(sh|bash|zsh|shell|console|fish|powershell|ps1)$/i.test(lang)
236
237export const codeLine = (el: ElementTable, style: Style, line: string, lang: string, key: string): RenderElement => {
238 const { Text } = el
239 const t = style.theme
240 const isShell = isShellLang(lang)
241 if (/[\u2500-\u257F]/.test(line)) return <Text key={key} color={t.codeText}>{line}</Text>
242 const comment = style.reorder ? commentTail(line, style.shape) : null
243 if (comment) {
244 return (
245 <Text key={key} color={t.codeText}>
246 {comment.head ? codeLine(el, style, comment.head, lang, `${key}.h`) : null}
247 <Text color={t.codeComment}>{comment.marker + comment.tail}</Text>
248 </Text>
249 )
250 }
251 if (!isShell) return <Text key={key} color={t.codeText}>{line || ' '}</Text>
252 if (/^\s*#/.test(line)) return <Text key={key} color={t.codeComment}>{line}</Text>
253 const parts = line.split(/("[^"]*"|'[^']*'|\s+)/).filter(p => p !== '')
254 let seenCommand = false
255 return (
256 <Text key={key} color={t.codeText}>
257 {parts.map((p, i) => {
258 if (/^\s+$/.test(p)) return <Text key={`${key}.${i}`}>{p}</Text>
259 if (/^["']/.test(p)) return <Text key={`${key}.${i}`} color={t.codeString}>{p}</Text>
260 if (/^--?[\w-]/.test(p)) return <Text key={`${key}.${i}`} color={t.codeFlag}>{p}</Text>
261 if (!seenCommand && !/^[$>|&;]+$/.test(p)) {
262 seenCommand = true
263 return <Text key={`${key}.${i}`} color={t.codeCommand}>{p}</Text>
264 }
265 if (/^(\||&&|;|\|\|)$/.test(p)) seenCommand = false
266 return <Text key={`${key}.${i}`}>{p}</Text>
267 })}
268 </Text>
269 )
270}
271
272const columnWidths = (natural: number[], available: number, gap: number): number[] => {
273 const room = Math.max(natural.length, available - gap * (natural.length - 1))
274 const total = natural.reduce((a, b) => a + b, 0)
275 if (total <= room) return natural
276 const widths = natural.map(() => 0)
277 let open = natural.map((_, c) => c)
278 let left = room
279 for (let fits = [-1]; fits.length; ) {
280 const share = Math.floor(left / open.length)
281 fits = open.filter(c => natural[c]! <= share)
282 fits.forEach(c => (widths[c] = natural[c]!, left -= natural[c]!))
283 open = open.filter(c => !fits.includes(c))
284 }
285 open.forEach((c, i) => (widths[c] = Math.max(1, Math.floor(left / open.length) + (i < left % open.length ? 1 : 0))))
286 while (widths.reduce((a, b) => a + b, 0) > room) {
287 const widest = widths.indexOf(Math.max(...widths))
288 if (widths[widest]! <= 1) break
289 widths[widest]!--
290 }
291 return widths
292}
293
294const displayText = (inline: Inline[]): string =>
295 inline.map(n => (n.kind === 'link' && n.text !== n.href ? `${n.text} (${n.href})` : 'children' in n ? displayText(n.children) : n.text)).join('')
296
297const isRtlTable = (style: Style, block: Extract<Block, { kind: 'table' }>): boolean => {
298 const cells = [...block.header, ...block.rows.flat()].filter(cell => displayText(cell).trim() !== '')
299 return cells.filter(cell => flowOf(style, cell, Infinity)?.base === 'R').length * 2 > cells.length
300}
301
302const ART_WIDTH = 100
303
304export const tableArt = (block: Extract<Block, { kind: 'table' }>): string => {
305 const cells = [block.header, ...block.rows].map(r => block.header.map((_, c) => displayText(r[c] ?? [])))
306 const widths = columnWidths(block.header.map((_, c) => Math.max(...cells.map(r => width(r[c]!)))), ART_WIDTH - 4, 3)
307 const pad = (text: string, c: number, align: 'left' | 'right' | 'center') => {
308 const room = widths[c]! - width(text)
309 const left = align === 'right' ? room : align === 'center' ? Math.floor(room / 2) : 0
310 return ' '.repeat(left) + text + ' '.repeat(room - left)
311 }
312 const line = (l: string, m: string, r: string) => l + widths.map(w => '─'.repeat(w + 2)).join(m) + r
313 const row = (r: string[], header: boolean) => {
314 const lines = r.map((text, c) => wrapRanges(text, widths[c]!).map(([a, b]) => text.slice(a, b)))
315 return Array.from({ length: Math.max(...lines.map(l => l.length)) }, (_, i) =>
316 `│ ${lines.map((l, c) => pad(l[i] ?? '', c, header ? 'center' : block.align[c] ?? 'left')).join(' │ ')} │`)
317 }
318 const art = [line('┌', '┬', '┐'), ...row(cells[0]!, true), ...cells.slice(1).flatMap(r => [line('├', '┼', '┤'), ...row(r, false)]), line('└', '┴', '┘')]
319 return ['```', ...art, '```'].join('\n')
320}
321
322const renderTable = (el: ElementTable, style: Style, block: Extract<Block, { kind: 'table' }>, columns: number, key: string) => {
323 const { Box, Text } = el
324 const t = style.theme
325 const rtl = isRtlTable(style, block)
326 const box = style.tableStyle === 'box'
327 const gap = box ? 0 : style.tableStyle === 'grid' ? 3 : 2
328 const natural = block.header.map((head, c) =>
329 Math.max(width(displayText(head)), ...block.rows.map(r => width(displayText(r[c] ?? [])))),
330 )
331 const widths = box ? columnWidths(natural, columns - 4, 3) : columnWidths(natural, columns, gap)
332 const order = natural.map((_, c) => c)
333 if (rtl) order.reverse()
334 const ruleChar = style.tableStyle === 'grid' ? '━' : '─'
335 const justify = (c: number) =>
336 block.align[c] === 'right' ? 'flex-end' : block.align[c] === 'center' ? 'center' : 'flex-start'
337
338 const rule = (k: string, heavy: boolean) => (
339 <Box key={k} flexDirection="row" columnGap={gap}>
340 {order.map(c => (
341 <Text key={`${k}.${c}`} color={t.tableRule} dimColor={!heavy && !t.tableRule}>
342 {(heavy ? ruleChar : '─').repeat(widths[c]!)}
343 </Text>
344 ))}
345 </Box>
346 )
347
348 const bar = (k: string, text: string, lines = 1) => (
349 <Text key={k} color={t.tableRule} dimColor={!t.tableRule}>{Array.from({ length: lines }, () => text).join('\n')}</Text>
350 )
351 const clipped = (lines: number) => (k: string, text: string) => (
352 <Box key={k} minWidth={width(text)}>
353 <Box position="absolute" top={0} bottom={0} left={0} minWidth={width(text)} overflow="hidden">
354 {bar(`${k}.b`, text, lines)}
355 </Box>
356 </Box>
357 )
358 const edge = (k: string, [left, fill, mid, right]: string) =>
359 bar(k, left + order.map(c => fill!.repeat(widths[c]! + 2)).join(mid) + right)
360
361 const row = (cells: Inline[][], k: string, isHeader: boolean, border: (k: string, text: string) => RenderElement = bar) => (
362 <Box key={k} flexDirection="row" columnGap={gap} alignItems="stretch">
363 {box && border(`${k}.l`, '│ ')}
364 {order.map((c, i) => {
365 const w = widths[c]!
366 const cell = flowOf(style, cells[c] ?? [], Infinity)
367 const content = cell ? cell.lines[0]! : (cells[c] ?? [])
368 const side = cell?.base === 'R' && block.align[c] !== 'center' ? 'flex-end' : justify(c)
369 const cellBox = (
370 <Box key={`${k}.${c}`} width={w} flexShrink={0} justifyContent={side}>
371 {isHeader
372 ? <Text bold color={t.tableHeader}>{inlineText(content)}</Text>
373 : <Text>{renderInline(el, style, content, `${k}.${c}`)}</Text>}
374 </Box>
375 )
376 return box && i > 0 ? [border(`${k}.${c}s`, ' │ '), cellBox] : cellBox
377 })}
378 {box && border(`${k}.r`, ' │')}
379 </Box>
380 )
381
382 const wrappedRow = (cells: Inline[][], k: string, isHeader: boolean) => {
383 if (!isHeader && cells.some(hasLink)) return [row(cells, k, isHeader, clipped(Math.max(1, ...widths.map((w, c) => mostLines(displayText(cells[c] ?? []), w)))))]
384 const wrapped = widths.map((w, c) => {
385 const content = cells[c] ?? []
386 if (natural[c]! <= w) return [content]
387 return wrapInline(isHeader ? [{ kind: 'text', text: inlineText(content) }] : content, w)
388 })
389 return Array.from({ length: Math.max(...wrapped.map(l => l.length)) }, (_, i) =>
390 row(wrapped.map(l => l[i] ?? []), `${k}.${i}`, isHeader))
391 }
392
393 if (box) {
394 const lines: RenderElement[] = [edge(`${key}.t`, '┌─┬┐'), ...wrappedRow(block.header, `${key}.h`, true), edge(`${key}.hr`, '╞═╪╡')]
395 block.rows.forEach((r, i) => {
396 if (i > 0) lines.push(edge(`${key}.r${i}r`, '├─┼┤'))
397 lines.push(...wrappedRow(r, `${key}.r${i}`, false))
398 })
399 lines.push(edge(`${key}.b`, '└─┴┘'))
400 return <Box key={key} flexDirection="column" {...(rtl ? { alignSelf: 'flex-end' as const } : {})}>{lines}</Box>
401 }
402
403 const body: RenderElement[] = [row(block.header, `${key}.h`, true), rule(`${key}.hr`, true)]
404 block.rows.forEach((r, i) => {
405 body.push(row(r, `${key}.r${i}`, false))
406 if (style.tableStyle !== 'minimal' && i < block.rows.length - 1) body.push(rule(`${key}.r${i}r`, false))
407 })
408 return <Box key={key} flexDirection="column" {...(rtl ? { alignSelf: 'flex-end' as const } : {})}>{body}</Box>
409}
410
411const renderHeading = (el: ElementTable, style: Style, block: Extract<Block, { kind: 'heading' }>, key: string) => {
412 const rtl = flowOf(style, block.inline, Infinity)
413 if (!rtl) return drawHeading(el, style, block, block.inline, key)
414 const heading = drawHeading(el, style, block, rtl.lines[0]!, key)
415 return rtl.base === 'R' ? <el.Box key={key} alignSelf="flex-end">{heading}</el.Box> : heading
416}
417
418const drawHeading = (el: ElementTable, style: Style, block: Extract<Block, { kind: 'heading' }>, inline: Inline[], key: string) => {
419 const { Box, Text } = el
420 const t = style.theme
421 const color = block.level <= 2 ? t.heading : t.accent ?? t.heading
422 const label = inlineText(inline)
423 switch (style.headingStyle) {
424 case 'uppercase':
425 return <Text key={key} bold color={color}>{block.level === 1 ? label.toUpperCase() : label}</Text>
426 case 'underline':
427 return <Text key={key} bold underline={block.level <= 2} color={color}>{label}</Text>
428 case 'banner':
429 if (block.level === 1) return <Box key={key} alignSelf="flex-start" borderStyle="bold" borderColor={color} paddingX={1}><Text bold color={color}>{renderInline(el, style, inline, key)}</Text></Box>
430 return block.level === 2
431 ? <Box key={key} flexDirection="column" alignSelf="flex-start"><Text bold color={color}>{renderInline(el, style, inline, key)}</Text><Text color={color}>{'━'.repeat(width(label))}</Text></Box>
432 : <Text key={key} bold color={block.level === 3 ? color : t.strong}>{renderInline(el, style, inline, key)}</Text>
433 default:
434 return <Text key={key} bold color={color}>{renderInline(el, style, inline, key)}</Text>
435 }
436}
437
438const ALERT_COLOR = { note: 'blue', tip: 'green', important: 'magenta', warning: 'yellow', caution: 'red' } as const
439
440const renderParagraph = (el: ElementTable, style: Style, block: Extract<Block, { kind: 'paragraph' }>, columns: number, key: string) => {
441 const { Box } = el
442 const rtl = flowOf(style, block.inline, columns)
443 if (rtl?.base === 'R') return <Box key={key} flexDirection="column" alignItems="flex-end">{renderFlow(el, style, rtl.lines, key)}</Box>
444 return renderWrapped(el, style, rtl ? rtl.lines[0]! : block.inline, columns, key, { bold: style.narration })
445}
446
447const renderQuote = (el: ElementTable, style: Style, block: Extract<Block, { kind: 'quote' }>, columns: number, key: string) => {
448 const { Box, Text } = el
449 const t = style.theme
450 const rtl = flowOf(style, block.inline, columns - 2)
451 if (rtl?.base === 'R') {
452 return (
453 <Box key={key} flexDirection="row" justifyContent="flex-end">
454 <Box flexDirection="column" alignItems="flex-end">{renderFlow(el, style, rtl.lines, key, { italic: true, color: t.quote })}</Box>
455 <Text color={t.accent}> │</Text>
456 </Box>
457 )
458 }
459 return (
460 <Box key={key} flexDirection="row">
461 <Text color={t.accent}>│ </Text>
462 {renderWrapped(el, style, rtl ? rtl.lines[0]! : block.inline, columns - 2, key, { italic: true, color: t.quote })}
463 </Box>
464 )
465}
466
467const renderAlert = (el: ElementTable, style: Style, block: Extract<Block, { kind: 'alert' }>, columns: number, key: string) => {
468 const { Box, Text } = el
469 const color = ALERT_COLOR[block.level]
470 const title = <Text bold color={color}>{block.level[0]!.toUpperCase() + block.level.slice(1)}</Text>
471 const rtl = flowOf(style, block.inline, columns - 4)
472 if (rtl?.base === 'R') {
473 return (
474 <Box key={key} flexDirection="column" alignSelf="flex-end" alignItems="flex-end" borderStyle="round" borderColor={color} paddingX={1}>
475 {title}
476 {renderFlow(el, style, rtl.lines, key)}
477 </Box>
478 )
479 }
480 const inline = rtl ? rtl.lines[0]! : block.inline
481 return (
482 <Box key={key} flexDirection="column" alignSelf="flex-start" borderStyle="round" borderColor={color} paddingX={1}>
483 {title}
484 {inline.length ? renderWrapped(el, style, inline, columns - 4, key) : null}
485 </Box>
486 )
487}
488
489const TASK_GLYPHS = { checks: ['[ ]', '[✓]'], ticks: ['○', '✓'], box: ['□', '✓'], progress: ['○', '✓'] } as const
490
491const renderList = (el: ElementTable, style: Style, block: Extract<Block, { kind: 'list' }>, columns: number, key: string) => {
492 const { Box, Text } = el
493 const t = style.theme
494 const tasks = block.items.filter(item => item.task !== undefined)
495 const done = tasks.filter(item => item.task).length
496 const filled = tasks.length ? Math.round((done / tasks.length) * 20) : 0
497 const strike = style.taskStyle === 'checks' || style.taskStyle === 'box'
498 const tick = style.taskStyle === 'ticks' || style.taskStyle === 'progress'
499 return (
500 <Box key={key} flexDirection="column">
501 {style.taskStyle === 'progress' && tasks.length > 0 && (
502 <Text>
503 <Text color={t.accent}>{'━'.repeat(filled)}</Text>
504 <Text color={t.bullet} dimColor>{'─'.repeat(20 - filled)}</Text>
505 <Text color={t.bullet}>{` ${done}/${tasks.length} done`}</Text>
506 </Text>
507 )}
508 {block.items.map((item, i) => {
509 const k = `${key}.${i}`
510 const glyph = item.task !== undefined ? TASK_GLYPHS[style.taskStyle][item.task ? 1 : 0] : /\d/.test(item.marker) ? item.marker : item.depth ? '◦' : '•'
511 const glyphColor = item.task && tick ? t.accent : t.bullet
512 const rtl = flowOf(style, item.inline, columns - item.depth * 2 - glyph.length - 1)
513 if (rtl?.base === 'R') {
514 return (
515 <Box key={k} flexDirection="row" justifyContent="flex-end" paddingRight={item.depth * 2}>
516 <Box flexDirection="column" alignItems="flex-end">{renderFlow(el, style, rtl.lines, k)}</Box>
517 <Text color={glyphColor}>{` ${glyph}`}</Text>
518 </Box>
519 )
520 }
521 return (
522 <Box key={k} flexDirection="row" paddingLeft={item.depth * 2}>
523 <Text color={glyphColor}>{`${glyph} `}</Text>
524 {renderWrapped(el, style, rtl ? rtl.lines[0]! : item.inline, columns - item.depth * 2 - glyph.length - 1, k, { dimColor: item.task === true, strikethrough: item.task === true && strike })}
525 </Box>
526 )
527 })}
528 </Box>
529 )
530}
531
532// Rough token count: about four Latin characters or one CJK character per token.
533export const roughTokens = (text: string) => {
534 const cjk = (text.match(/[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]/gu) ?? []).length
535 return Math.max(1, Math.round(cjk + (text.length - cjk) / 4))
536}
537
538// A prompt written for another agent or tool: boxed, wrapped, unhighlighted, copied verbatim.
539const renderPrompt = (el: ElementTable, style: Style, lines: string[], columns: number, key: string, button: RenderElement | null | undefined): RenderElement => {
540 const { Box, Text } = el
541 const t = style.theme
542 return (
543 <Box key={key} flexDirection="column" borderStyle="round" borderColor={t.accent} paddingX={1} width={Math.min(columns, 100)}>
544 <Box flexDirection="row" justifyContent="space-between" columnGap={2}>
545 <Text color={t.accent} bold>{`prompt · ≈${roughTokens(lines.join('\n'))} tokens`}</Text>
546 {button ?? null}
547 </Box>
548 {lines.map((line, i) => <Text key={`${key}.${i}`}>{line === '' ? ' ' : line}</Text>)}
549 </Box>
550 )
551}
552
553// Which copy a button makes; the hooks module names it in the person's language.
554export type CopyKind = 'block' | 'prompt' | 'source' | 'art'
555export type CopyButton = (text: string | (() => string), key: string, kind?: CopyKind) => RenderElement | null
556export type Drawn = Map<number, { element: RenderElement; art: string }>
557
558const copySource = (block: Block): string | undefined =>
559 block.kind === 'code' ? block.lines.join('\n') : block.kind === 'table' || block.kind === 'list' ? block.raw : block.kind === 'quote' || block.kind === 'alert' ? block.raw.split('\n').map(line => line.replace(/^\s*>\s?/, '')).join('\n') : undefined
560
561export const renderBlocks = (el: ElementTable, style: Style, blocks: Block[], columns: number, drawn: Drawn = new Map(), copy?: CopyButton): RenderElement[] => {
562 const { Box, Text } = el
563 const t = style.theme
564 const rendered = blocks.map((block, b) => {
565 const key = `b${b}`
566 switch (block.kind) {
567 case 'heading':
568 return renderHeading(el, style, block, key)
569 case 'paragraph':
570 return renderParagraph(el, style, block, columns, key)
571 case 'quote':
572 return renderQuote(el, style, block, columns, key)
573 case 'alert':
574 return renderAlert(el, style, block, columns, key)
575 case 'rule':
576 return <Text key={key} color={t.rule} dimColor={!t.rule}>{'─'.repeat(Math.max(8, Math.min(columns, 80)))}</Text>
577 case 'code':
578 if (block.lang === 'prompt') return renderPrompt(el, style, block.lines, columns, key, copy?.(block.lines.join('\n'), `copy${b}`, 'prompt'))
579 return drawn.get(b)?.element ?? (
580 <Box key={key} flexDirection="column" alignSelf="flex-start">
581 <Box flexDirection="row" justifyContent="space-between" columnGap={4}>
582 <Text color={t.codeComment}>{`── ${block.lang || 'code'}`}</Text>
583 {copy?.(block.lines.join('\n'), `copy${b}`) ?? null}
584 </Box>
585 <Box flexDirection="column" paddingLeft={2}>
586 {(isShellLang(block.lang) ? null : highlightBlock(el, style, block.lines, block.lang, key)) ?? block.lines.map((line, i) => codeLine(el, style, line, block.lang, `${key}.${i}`))}
587 </Box>
588 </Box>
589 )
590 case 'list':
591 return renderList(el, style, block, columns, key)
592 case 'table':
593 return renderTable(el, style, block, columns, key)
594 }
595 })
596 const copied = rendered.map((element, b) => {
597 const block = blocks[b]
598 const text = block ? copySource(block) : undefined
599 const isPlainCode = block?.kind === 'code' && !drawn.has(b)
600 const art = drawn.get(b)?.art ?? (block?.kind === 'table' ? () => tableArt(block) : undefined)
601 const first = text === undefined || isPlainCode ? null : copy?.(text, `copy${b}`, art === undefined || block?.kind === 'table' ? undefined : 'source')
602 const second = first && art !== undefined ? copy?.(art, `art${b}`, 'art') : null
603 const button = second ? (
604 <el.Box key={`copies${b}`} flexDirection="row" columnGap={1}>
605 {first}
606 {second}
607 </el.Box>
608 ) : first
609 if (!button) return element
610 const { Box } = el
611 const rtl = style.reorder && block !== undefined && hasRtl(block.raw)
612 return block?.kind === 'quote' || block?.kind === 'alert' || block?.kind === 'list' ? (
613 <Box key={`c${b}`} flexDirection="row" columnGap={2} {...(rtl ? { justifyContent: 'flex-end' as const } : {})}>
614 {element}
615 {button}
616 </Box>
617 ) : (
618 <Box key={`c${b}`} flexDirection="column" {...(rtl && block?.kind === 'table' && isRtlTable(style, block) ? {} : { alignSelf: 'flex-start' as const })}>
619 <Box justifyContent="flex-end">{button}</Box>
620 {element}
621 </Box>
622 )
623 })
624 const isFigure = (b: number) => blocks[b]?.kind === 'table' || drawn.has(b)
625 const out: RenderElement[] = []
626 for (let b = 0; b < rendered.length; b++) {
627 if (!isFigure(b) || !isFigure(b + 1)) {
628 out.push(copied[b]!)
629 continue
630 }
631 const start = b
632 while (isFigure(b + 1)) b++
633 out.push(
634 <Box key={`row${start}`} flexDirection="row" flexWrap="wrap" columnGap={4} rowGap={1}>
635 {copied.slice(start, b + 1).map((figure, i) => <Box key={`f${start + i}`} flexShrink={0}>{figure}</Box>)}
636 </Box>,
637 )
638 }
639 return out
640}
641
642export type ToolRow = { tool: string; input: unknown; isRunning: boolean; isErrored: boolean; isInterrupted: boolean }
643
644
645const field = (input: unknown, ...keys: string[]): string | undefined => {
646 if (input === null || typeof input !== 'object') return undefined
647 for (const k of keys) {
648 const v = (input as Record<string, unknown>)[k]
649 if (typeof v === 'string' && v.trim() !== '') return v
650 }
651 return undefined
652}
653
654// Claude Code names a file by its path from the working directory; the model passes absolute paths.
655export const shortPath = (path: string, base: string | undefined): string => {
656 if (base === undefined) return path
657 const norm = (p: string) => p.replace(/\\/g, '/').replace(/\/+$/, '')
658 const root = norm(base)
659 const isWindows = /^[a-z]:\//i.test(root)
660 const within = isWindows ? norm(path).toLowerCase().startsWith(`${root.toLowerCase()}/`) : norm(path).startsWith(`${root}/`)
661 return within && root !== '' ? path.slice(root.length + 1) : path
662}
663
664const toolDim = (style: Style) => style.toolStyle !== "classic"
665
666const toolGutter = ({ Box, Text }: ElementTable, style: Style, color: string | undefined, running: boolean) =>
667 style.toolStyle.startsWith("tree")
668 ? <Box width={4} flexShrink={0}><Text color={color}>{' ⎿ '}</Text></Box>
669 : <Box width={2} flexShrink={0}><Text color={color}>{running ? '◌' : '●'}</Text></Box>
670
671const toolLayout = (el: ElementTable, style: Style, columns: number, label: string, color: string | undefined, running: boolean, text: RenderElement) => {
672 const { Box, Text } = el
673 if (style.toolStyle !== "chat") return <Box flexDirection="row">{toolGutter(el, style, color, running)}{text}</Box>
674 const w = Math.min(width(label) + 2, Math.max(20, Math.floor(columns * 0.6)))
675 return (
676 <Box flexDirection="row" justifyContent="flex-end" width="100%">
677 <Box width={w} flexDirection="row">{text}<Text color={color}>{running ? " ◌" : " ●"}</Text></Box>
678 </Box>
679 )
680}
681
682// With diffLines 0 an edit's row carries its counts (`+73 -19`) and the expand button, and its result block
683// draws nothing, so each edit is one line: the file, how much changed, and the way to see the diff.
684export type RowFold = { added: number; removed: number; expand?: { label: string; onPress: () => void } }
685
686export const renderToolRow = (el: ElementTable, style: Style, row: ToolRow, columns = 100, cwd?: string, words: ToolWords = STRINGS.en.toolWords, fold?: RowFold): RenderElement => {
687 const { Box, Text, Button } = el
688 const t = style.theme
689 const isShell = row.tool === 'Bash' || row.tool === 'PowerShell'
690 const verb = words.verbs[row.tool] ?? row.tool.replace(/^mcp__([^_]+)__/, '$1 ')
691 const file = isShell ? undefined : field(row.input, 'file_path', 'notebook_path', 'path')
692 const target = isShell
693 ? field(row.input, 'command')?.split('\n')[0]
694 : file !== undefined ? shortPath(file, cwd) : field(row.input, 'pattern', 'url', 'query', 'description')
695 const dot = row.isErrored ? t.codeFlag : row.isInterrupted ? t.codeComment : row.isRunning ? t.accent : t.number
696 const isPath = target !== undefined && /^(~|\.{0,2}\/|[A-Za-z]:\\)/.test(target)
697
698 const counts = fold === undefined ? "" : `+${fold.added} -${fold.removed}`
699 const label = `${verb}${target === undefined ? "" : ` ${target}`}${row.isInterrupted ? words.interrupted : row.isErrored ? words.failedRow : ""}${fold === undefined ? "" : ` ${counts}${fold.expand ? ` [ ${fold.expand.label} ]` : ""}`}`
700 const text = (
701 <Text wrap="truncate-end" dimColor={toolDim(style)}>
702 <Text bold={!toolDim(style)} dimColor={toolDim(style)}>{verb}</Text>
703 {target === undefined ? null : <Text> </Text>}
704 {target === undefined ? null : isShell ? codeLine(el, style, target, 'bash', 'cmd') : <Text color={isPath ? t.path : t.inlineCode} dimColor={toolDim(style)}>{target}</Text>}
705 {row.isInterrupted ? <Text dimColor>{words.interrupted}</Text> : row.isErrored ? <Text color={t.codeFlag}>{words.failedRow}</Text> : null}
706 </Text>
707 )
708 if (fold === undefined) return toolLayout(el, style, columns, label, dot, row.isRunning, text)
709 return toolLayout(el, style, columns, label, dot, row.isRunning, (
710 <Box flexDirection="row" gap={1}>
711 {text}
712 <Text>
713 <Text color={t.codeString}>{`+${fold.added}`}</Text>
714 <Text color={t.codeFlag}>{` -${fold.removed}`}</Text>
715 </Text>
716 {fold.expand ? <Button key="diff-expand" label={fold.expand.label} onPress={fold.expand.onPress} /> : null}
717 </Box>
718 ))
719}
720
721const OUTPUT_LINES = 120
722
723const lines = (value: unknown): string[] => (typeof value === 'string' && value !== '' ? value.replace(/\n$/, '').split('\n') : [])
724
725export const renderExpandedShell = (el: ElementTable, style: Style, row: ToolRow & { output?: unknown }): RenderElement => {
726 const { Box, Text } = el
727 const t = style.theme
728 const command = (field(row.input, 'command') ?? '').split('\n')
729 const out = row.output !== null && typeof row.output === 'object' ? (row.output as Record<string, unknown>) : {}
730 const stdout = lines(out.stdout)
731 const stderr = lines(out.stderr)
732 const shown = [...stdout.map(text => ({ text, color: undefined as string | undefined })), ...stderr.map(text => ({ text, color: t.codeFlag as string | undefined }))]
733 const visible = shown.slice(0, OUTPUT_LINES)
734 const dot = row.isErrored ? t.codeFlag : row.isInterrupted ? t.codeComment : row.isRunning ? t.accent : t.number
735 return (
736 <Box flexDirection="column">
737 <Box flexDirection="row">
738 <Box width={2} flexShrink={0}>
739 <Text color={dot}>{row.isRunning ? '◌' : '●'}</Text>
740 </Box>
741 <Box flexDirection="column">
742 {command.map((line, i) => (
743 <Text key={`c${i}`}>
744 {i === 0 ? <Text bold>{`${row.tool}(`}</Text> : null}
745 {codeLine(el, style, line, 'bash', `cmd${i}`)}
746 {i === command.length - 1 ? <Text bold>)</Text> : null}
747 </Text>
748 ))}
749 </Box>
750 </Box>
751 {row.isRunning ? null : (
752 <Box paddingLeft={2}>
753 <Box flexDirection="column" alignSelf="flex-start" borderStyle="round" borderColor={t.codeComment} paddingX={1}>
754 {visible.length === 0 ? <Text dimColor>(No output)</Text> : visible.map((l, i) => <Text key={`o${i}`} color={l.color}>{l.text === '' ? ' ' : l.text}</Text>)}
755 {shown.length > visible.length ? <Text dimColor>{`\u2026 +${shown.length - visible.length} lines`}</Text> : null}
756 </Box>
757 </Box>
758 )}
759 </Box>
760 )
761}
762
763const GROUPS: [RegExp, ToolKind][] = [
764 [/^(Bash|PowerShell)$/, 'command'],
765 [/^Read$/, 'read'],
766 [/^(Write|Edit|MultiEdit|NotebookEdit)$/, 'edit'],
767 [/^(Grep|Glob)$/, 'pattern'],
768 [/^(WebFetch|WebSearch)$/, 'page'],
769 [/^(Agent|Task)$/, 'task'],
770]
771
772export const groupSummary = (calls: readonly { tool: string }[], words: ToolWords = STRINGS.en.toolWords): string => {
773 // A known kind is counted under its kind, any other tool under its own name. ToolSearch only loads other
774 // tools, so it is left out beside them.
775 const counts = new Map<string, { kind?: ToolKind; name: string; n: number }>()
776 const counted = calls.some(c => c.tool !== 'ToolSearch') ? calls.filter(c => c.tool !== 'ToolSearch') : calls
777 for (const call of counted) {
778 const kind = GROUPS.find(([re]) => re.test(call.tool))?.[1]
779 const name = kind ?? call.tool.replace(/^mcp__([^_]+)__/, '$1 ')
780 const entry = counts.get(name) ?? { kind, name, n: 0 }
781 counts.set(name, { ...entry, n: entry.n + 1 })
782 }
783 const text = [...counts.values()].map(c => (c.kind ? words.group(c.kind, c.n) : words.other(c.name, c.n))).join(words.join)
784 return text.charAt(0).toUpperCase() + text.slice(1)
785}
786
787export const renderToolGroup = (el: ElementTable, style: Style, calls: readonly ToolRow[], isActive: boolean, columns = 100, cwd?: string, words: ToolWords = STRINGS.en.toolWords): RenderElement => {
788 const { Text } = el
789 const t = style.theme
790 const failed = calls.filter(c => c.isErrored).length
791 const running = isActive && calls.some(c => c.isRunning)
792 const dot = failed ? t.codeFlag : running ? t.accent : t.number
793 const last = calls[calls.length - 1]
794 const lastLine = last ? field(last.input, 'command', 'file_path', 'notebook_path', 'path', 'pattern', 'url', 'query', 'description')?.split('\n')[0] : undefined
795 const lastTarget = lastLine === undefined ? undefined : shortPath(lastLine, cwd)
796 const label = `${groupSummary(calls, words)}${failed ? words.failed(failed) : ""}${lastTarget ? `${words.last}${lastTarget}` : ""}`
797 return toolLayout(el, style, columns, label, dot, running, (
798 <Text wrap="truncate-end" dimColor={toolDim(style)}>
799 <Text bold={!toolDim(style)} dimColor={toolDim(style)}>{groupSummary(calls, words)}</Text>
800 {failed ? <Text color={t.codeFlag}>{words.failed(failed)}</Text> : null}
801 {lastTarget ? <Text dimColor>{`${words.last}${lastTarget}`}</Text> : null}
802 </Text>
803 ))
804}
805
806export type FoldLabels = { summary: string; hidden: string; expand: string }
807
808// A long edit diff as a few of its lines under Claude Code's own header, with what is left and a button to
809// show it all; with no lines to show (diffLines 0), one row: the counts and the button.
810export const renderFoldedDiff = (el: ElementTable, style: Style, folded: Folded, labels: FoldLabels, onExpand: () => void): RenderElement => {
811 const { Box, Text, Button } = el
812 if (folded.shown.length === 0) {
813 return (
814 <Box flexDirection="row" gap={2}>
815 <Text>
816 <Text dimColor>{' ⎿ '}</Text>
817 {labels.summary}
818 </Text>
819 <Button key="diff-expand" label={labels.expand} onPress={onExpand} />
820 </Box>
821 )
822 }
823 return (
824 <Box flexDirection="column">
825 <Text>
826 <Text dimColor>{' ⎿ '}</Text>
827 {labels.summary}
828 </Text>
829 {diffRows(el, style, folded.shown)}
830 <Box flexDirection="row" gap={2} paddingLeft={8}>
831 <Text dimColor>{`… ${labels.hidden}`}</Text>
832 <Button key="diff-expand" label={labels.expand} onPress={onExpand} />
833 </Box>
834 </Box>
835 )
836}
837
838const diffRows = (el: ElementTable, style: Style, shown: readonly DiffLine[]): RenderElement[] => {
839 const { Text } = el
840 const t = style.theme
841 const color = (mark: string) => (mark === '+' ? t.codeString : mark === '-' ? t.codeFlag : undefined)
842 return shown.flatMap((line, i) => [
843 ...(line.gap ? [<Text key={`g${i}`} color={t.codeComment}>{'⋮'.padStart(8)}</Text>] : []),
844 <Text key={`d${i}`} wrap="truncate-end">
845 <Text color={t.codeComment}>{String(line.number).padStart(8)}</Text>
846 <Text color={color(line.mark)}>{` ${line.mark}${line.text}`}</Text>
847 </Text>,
848 ])
849}
850
851export type ShellEdit = { verb: string; path: string; folded: Folded }
852
853// The files a shell command changed, under the engine's own drawing of the command's output (`base`): one
854// row per file with its counts, a few diff lines where there are any to show, and one button to show it all.
855export const renderShellEdits = (el: ElementTable, style: Style, base: RenderElement, files: readonly ShellEdit[], labels: Pick<FoldLabels, 'hidden' | 'expand'>, onExpand: () => void): RenderElement => {
856 const { Box, Text, Button } = el
857 const t = style.theme
858 const hidden = files.reduce((n, f) => n + f.folded.hidden, 0)
859 return (
860 <Box flexDirection="column">
861 {base}
862 {files.map((f, i) => (
863 <Box key={`f${i}`} flexDirection="column">
864 <Text wrap="truncate-end">
865 <Text dimColor>{' ⎿ '}</Text>
866 <Text bold>{f.verb}</Text>
867 <Text color={t.path}>{` ${f.path}`}</Text>
868 <Text color={t.codeString}>{` +${f.folded.added}`}</Text>
869 <Text color={t.codeFlag}>{` -${f.folded.removed}`}</Text>
870 </Text>
871 {diffRows(el, style, f.folded.shown)}
872 </Box>
873 ))}
874 <Box flexDirection="row" gap={2} paddingLeft={hidden > 0 ? 8 : 5}>
875 {hidden > 0 ? <Text dimColor>{`… ${labels.hidden}`}</Text> : null}
876 <Button key="shell-edits-expand" label={labels.expand} onPress={onExpand} />
877 </Box>
878 </Box>
879 )
880}
881
882export const formatDuration = (ms: number): string => {
883 const s = Math.round(ms / 1000)
884 if (s < 60) return `${Math.max(s, 0)}s`
885 if (s < 3600) return `${Math.floor(s / 60)}m ${s % 60}s`
886 return `${Math.floor(s / 3600)}h ${Math.floor((s % 3600) / 60)}m`
887}
888
889export const renderTurnDuration = ({ Text }: ElementTable, style: Style, word: string, durationMs: number): RenderElement => (
890 <Text color={style.theme.codeComment}>
891 {`✻ ${word} for `}
892 <Text color={style.theme.number}>{formatDuration(durationMs)}</Text>
893 </Text>
894)
895
896export const renderUserPrompt = (el: ElementTable, style: Style, text: string, columns: number): RenderElement => {
897 const { Box, Text } = el
898 const t = style.theme
899 const color = style.promptStyle === 'chevron' ? t.accent : t.heading
900 const lines = text.split('\n').map(line => flowOf(style, [{ kind: 'text', text: line }], columns - 4))
901 const rtl = lines.some(l => l?.base === 'R')
902 const body = (
903 <Box flexDirection="column" {...(rtl ? { alignItems: 'flex-end' as const } : {})}>
904 {text.split('\n').map((line, i) => {
905 const flow = lines[i]
906 return flow
907 ? renderFlow(el, style, flow.lines, `p${i}`, { color, bold: style.promptStyle === 'chevron' })
908 : renderWrapped(el, style, [{ kind: 'text', text: line }], columns - 4, `p${i}`, { color, bold: style.promptStyle === 'chevron' })
909 })}
910 </Box>
911 )
912 if (style.promptStyle === 'bubble') {
913 return <Box borderStyle="round" borderColor={t.accent} paddingX={1} alignSelf={rtl ? 'flex-end' : 'flex-start'}>{body}</Box>
914 }
915 const mark = <Text color={t.accent} bold>{style.promptStyle === 'bar' ? (rtl ? ' ▐' : '▌ ') : rtl ? ' ‹' : '› '}</Text>
916 return <Box flexDirection="row" {...(rtl ? { justifyContent: 'flex-end' as const } : {})}>{rtl ? body : mark}{rtl ? mark : body}</Box>
917}
918hooks/help.ts 181 lines1export const showcaseText = (themes: readonly string[]): string => `
2# tessera
3
4Colored markdown for Claude Code replies: **bold**, *italic*, ~~struck~~, \`inline code\`, a [link](https://github.com/OG-Matcha/tessera) and a bare URL https://github.com/OG-Matcha/tessera/issues, both clickable, numbers like 99.9% and 250ms, paths like ~/src/app.ts.
5
6## Commands
7
8| Command | Does |
9|---------|------|
10| \`/tessera\` | This screen |
11| \`/tessera setup\` | Pick the features you want on |
12| \`/tessera peek <file>\` | Preview a document: .md .csv .json .docx .xlsx .pptx |
13| \`/tessera theme <name>\` | Switch theme on the spot |
14| \`/tessera copy\` | Copy the last reply; \`copy code\` its last code block, \`copy prompt\` its prompt card |
15| \`/config\` | Edit any option |
16
17> [!NOTE]
18> ${themes.length} themes ship with it. \`mono\` uses no color, only bold and dim.
19
20### Pick a theme
21
22\`\`\`bash
23/tessera theme nord
24/tessera theme github-light
25\`\`\`
26
271. Dark: ${themes.filter(t => !/latte|light|dawn/.test(t) && t !== 'mono').join(', ')}
282. Light: ${themes.filter(t => /latte|light|dawn/.test(t)).join(', ')}
293. Plain
30 - mono
31
32> [!TIP]
33> Any color slot beats the theme. Set \`headingColor\` or \`numberColor\` to a hex value in \`/config\`.
34
35## Everything it draws
36
37### Alerts
38
39> [!IMPORTANT]
40> After updating the plugin, open sessions need \`/reload-plugins\`.
41
42> [!WARNING]
43> Terminals that copy on select (Warp) can turn a click on a copy button into a selection. Use the keyboard shortcut.
44
45> [!CAUTION]
46> Claude Code refuses trees over 20000 nodes. A code block past about 500 highlighted lines falls back to plain text.
47
48### Task lists
49
50- [x] Parse the reply
51- [x] Draw it
52 - [x] Tables and code
53 - [ ] Diagrams on the desktop app
54- [ ] Ship the next release
55
56### Your prompts
57
58Scroll up: what you typed draws in a bubble. \`promptStyle\` switches to \`bar\`, \`chevron\` or \`off\` in \`/config\`.
59
60### Tool rows
61
62Tool calls draw as one line, dimmed on the right by default. Set \`toolStyle\` in \`/config\` to \`chat\`, \`tree-dim\`, \`tree-bold\` or \`classic\`.
63
64### Quotes and rules
65
66> A quote keeps its text when you copy it, without the \`> \` markers.
67
68---
69
70### Code
71
72\`\`\`json
73{ "theme": "dracula", "headingStyle": "banner", "mermaid": true }
74\`\`\`
75
76#### Diagrams
77
78\`\`\`mermaid
79flowchart LR
80 R[Reply] --> P[Parse]
81 P --> D[Draw]
82 D --> S[Screen]
83\`\`\`
84
85\`\`\`mermaid
86sequenceDiagram
87 participant U as You
88 participant C as Claude
89 participant P as tessera
90 U->>C: prompt
91 C->>P: markdown
92 P-->>U: colored reply
93\`\`\`
94
95\`\`\`mermaid
96xychart-beta
97 title "Color options per group"
98 x-axis [text, head, num, code, diag]
99 y-axis "options" 0 --> 8
100 bar [7, 3, 2, 6, 2]
101\`\`\`
102`
103
104export const helpText = (themes: readonly string[]): string => `
105## Commands
106
107| Command | Does |
108|---------|------|
109| \`/tessera setup\` | Pick the features you want on |
110| \`/tessera peek <file>\` | Preview a document: .md .csv .json .docx .xlsx .pptx |
111| \`/tessera theme <name>\` | Switch theme on the spot |
112| \`/tessera copy\` | Copy the last reply; \`copy code\` its last code block, \`copy prompt\` its prompt card |
113| \`/tessera demo\` | Full showcase, every element and diagram |
114| \`/tessera demo-rtl\` | Hebrew right-to-left showcase |
115| \`/tessera inbox\` | Client feedback inbox (turn on feedbackInbox in /config); \`inbox fixed 3 5\` marks items fixed |
116| \`/tessera record\` | Record mode: API keys, tokens, passwords, emails and phone numbers masked in what tessera draws; again, or \`record off\`, turns it off |
117
118### ${themes.length} themes
119
120- Dark: ${themes.filter(t => !/latte|light|dawn/.test(t) && t !== 'mono').join(', ')}
121- Light: ${themes.filter(t => /latte|light|dawn/.test(t)).join(', ')}
122- Plain: mono, no color, only bold and dim
123
124Docs and issues: https://github.com/OG-Matcha/tessera
125
126> [!TIP]
127> Any color slot beats the theme. Set \`headingColor\` or \`numberColor\` to a hex value in \`/config\`.
128
129### Task lists
130
131- [x] Tables, diagrams and charts drawn in the terminal
132- [x] A copy button on every block
133- [ ] Pick a \`taskStyle\` in \`/config\`: checks, ticks, box or progress
134
135\`\`\`mermaid
136flowchart LR
137 R[Reply] --> P[Parse]
138 P --> D[Draw]
139 D --> S[Screen]
140\`\`\`
141
142\`\`\`mermaid
143xychart-beta
144 title "Color options per group"
145 x-axis [text, head, num, code, diag]
146 y-axis "options" 0 --> 8
147 bar [7, 3, 2, 6, 2]
148\`\`\`
149
150> [!CAUTION]
151> Claude Code refuses trees over 20000 nodes. A code block past about 500 highlighted lines falls back to plain text.
152`
153
154export const rtlShowcaseText = (): string => `
155# עברית מימין לשמאל
156
157**שלום חברים**, זו הדגמה של עברית עם מונחים באנגלית כמו \`kubectl\`, מספרים כמו 99.9% ו-250ms, נתיב כמו ~/src/app.ts וגם [קישור](https://github.com/OG-Matcha/tessera).
158
159## רשימות
160
161- פרוסים בשני אזורים (us-east ו-eu-west)
162- מחליפים ערכת נושא עם \`/tessera theme nord\`
163
1641. מתקינים את התוסף
1652. שואלים שאלה בעברית
166
167> עברית נקראת מימין לשמאל, גם בטרמינל בלי תמיכה בכיווניות
168
169> [!TIP]
170> כל ערכת נושא עובדת גם בעברית
171
172| שירות | אזור | גרסה |
173| :--- | :--- | ---: |
174| שער | us-east | 2.14.0 |
175| חיוב | eu-west | 1.8.3 |
176
177\`\`\`bash
178ls -la # רשימת הקבצים בתיקייה
179\`\`\`
180`
181hooks/help-zh.ts 88 lines1const dark = (themes: readonly string[]) => themes.filter(t => !/latte|light|dawn/.test(t) && t !== 'mono').join('、')
2const light = (themes: readonly string[]) => themes.filter(t => /latte|light|dawn/.test(t)).join('、')
3
4export const helpTextZh = (themes: readonly string[]): string => `
5## 指令
6
7| 指令 | 用途 |
8|------|------|
9| \`/tessera setup\` | 選擇要開啟的功能 |
10| \`/tessera peek <檔案>\` | 預覽文件:.md .csv .json .docx .xlsx .pptx |
11| \`/tessera theme <名稱>\` | 立即切換主題 |
12| \`/tessera copy\` | 複製上一則回覆;\`copy code\` 只複製最後一個程式碼區塊,\`copy prompt\` 複製 prompt 卡片 |
13| \`/tessera demo\` | 完整示範:每種元素和圖表 |
14| \`/tessera inbox\` | 客戶回饋收件匣(需在 /config 開啟 feedbackInbox);\`inbox fixed 3 5\` 標為已修 |
15| \`/tessera record\` | 錄影模式:tessera 畫的內容裡的 API 金鑰、token、密碼、email、電話遮住;再輸入一次或 \`record off\` 關閉 |
16
17### ${themes.length} 套主題
18
19- 深色:${dark(themes)}
20- 淺色:${light(themes)}
21- 單色:mono,只用粗體和淡色
22
23說明與回報問題:https://github.com/OG-Matcha/tessera
24
25> [!TIP]
26> 個別顏色的設定優先於主題。在 \`/config\` 把 \`headingColor\` 或 \`numberColor\` 設成色碼即可。
27
28### 貼圖預覽
29
30在輸入框貼圖後,上方會出現縮圖。支援 kitty 圖片協定的終端機(kitty、Ghostty)顯示原圖;其他終端機用色塊縮圖,按「原圖」用系統檢視器打開。
31`
32
33export const showcaseTextZh = (themes: readonly string[]): string => `
34# tessera
35
36在終端機裡把 Claude 的回覆畫得更好讀:**粗體**、*斜體*、~~刪除線~~、\`行內程式碼\`、[連結](https://github.com/OG-Matcha/tessera),數字如 99.9% 與 250ms、路徑如 ~/src/app.ts 都會上色。
37
38## 表格會算中文寬度
39
40| 功能 | 狀態 | 何時出現 |
41|------|------|------|
42| 貼上預覽 | ✅ 開 | 貼上圖片或長文字 |
43| 繁簡守門 | ✅ 開 | 寫入簡體字或簡中用語 |
44| 接續未完成 | ✅ 開 | 新 session 開始 |
45| 摺疊長差異 | ✅ 開 | 改檔差異超過 12 行 |
46
47> [!NOTE]
48> 共 ${themes.length} 套主題。深色:${dark(themes)};淺色:${light(themes)};mono 不用顏色。
49
50> [!WARNING]
51> 會「選取即複製」的終端機(例如 Warp)點複製按鈕時可能變成選取文字,請改用 \`/tessera copy\`。
52
53### 待辦清單
54
55- [x] 解析回覆
56- [x] 畫出來
57 - [x] 表格與程式碼
58 - [ ] 桌面版的圖表
59- [ ] 發布下一版
60
61### 程式碼
62
63\`\`\`powershell
64claude plugin install tessera@og-matcha --scope user
65\`\`\`
66
67### 圖表:中文節點不跑版
68
69\`\`\`mermaid
70flowchart LR
71 A[貼上圖片] --> B[輸入框預覽]
72 B --> C[送出]
73 C --> D[回覆上色]
74\`\`\`
75
76\`\`\`mermaid
77sequenceDiagram
78 participant U as 你
79 participant C as Claude
80 participant T as tessera
81 U->>C: 提問
82 C->>T: markdown
83 T-->>U: 上色後的回覆
84\`\`\`
85
86> 引言複製時不會帶 \`> \` 符號。
87`
88hooks/carry.ts 65 lines1export type ItemStatus = 'pending' | 'in_progress' | 'completed'
2
3// What one session left to do, kept per repository: the newest sessions only. `tasks` keeps the task
4// ids, so a reloaded module can follow later updates; `ended` says the session is over, so another
5// terminal in the same repository does not take its live list for leftovers.
6export type CarryStore = Record<string, { at: number; open: string[]; ended?: true; tasks?: Record<string, { subject: string; status: ItemStatus }> }>
7
8export type TaskLog = {
9 tasks: Map<string, { subject: string; status: ItemStatus }>
10 todos: { content: string; status: ItemStatus }[]
11}
12
13const KEEP = 5
14const isOpen = (status: ItemStatus) => status !== 'completed'
15
16export const openItems = (log: TaskLog): string[] => [
17 ...[...log.tasks.values()].filter(t => isOpen(t.status)).map(t => t.subject),
18 ...log.todos.filter(t => isOpen(t.status)).map(t => t.content),
19]
20
21export function recordSession(store: CarryStore, sessionId: string, at: number, log: TaskLog): CarryStore {
22 const next = { ...store, [sessionId]: { at, open: openItems(log), tasks: Object.fromEntries(log.tasks) } }
23 return Object.fromEntries(Object.entries(next).sort(([, a], [, b]) => b.at - a.at).slice(0, KEEP))
24}
25
26// Repositories are kept while they are among the newest this many; the store is read whole at every
27// access, and a machine running tests makes a repository per run.
28export const REPOSITORIES_KEPT = 30
29
30// The carry keys to drop so that only the newest REPOSITORIES_KEPT repositories stay, the age of a
31// repository being its latest session's; `own` is never dropped.
32export function staleCarryKeys(records: Record<string, CarryStore>, own: string): string[] {
33 const latest = (store: CarryStore) => Math.max(0, ...Object.values(store).map(s => s.at))
34 return Object.entries(records)
35 .filter(([key]) => key !== own)
36 .sort(([, a], [, b]) => latest(b) - latest(a))
37 .slice(Math.max(0, REPOSITORIES_KEPT - 1))
38 .map(([key]) => key)
39}
40
41// The task list this session kept before the module was reloaded.
42export const restoredTasks = (store: CarryStore, sessionId: string): TaskLog['tasks'] => new Map(Object.entries(store[sessionId]?.tasks ?? {}))
43
44export function endSession(store: CarryStore, sessionId: string, at: number): CarryStore {
45 const entry = store[sessionId]
46 return entry === undefined ? store : { ...store, [sessionId]: { ...entry, at, ended: true } }
47}
48
49// A session that never said it ended counts as over after this long, when the registry of running
50// sessions could not be read.
51const STALE_MS = 2 * 60 * 60_000
52
53// The latest other session in this repository that is over, when it stopped with items still open. `live`
54// is the set of session ids Claude Code's registry lists as running (~/.claude/sessions): a session not in
55// it is over, whatever its record says, since /exit seldom lets a mod write its ended mark, and one in it
56// is running however old its record, so a long session's open items are not offered to every terminal
57// opened beside it. The two-hour rule stands in only when the registry could not be read.
58export function carriedFrom(store: CarryStore, sessionId: string, now: number, live?: ReadonlySet<string>): { from: string; items: string[] } | undefined {
59 const over = (id: string, s: CarryStore[string]) => s.ended === true || (live !== undefined ? !live.has(id) : now - s.at > STALE_MS)
60 const [from, latest] = Object.entries(store)
61 .filter(([id, s]) => id !== sessionId && over(id, s))
62 .sort(([, a], [, b]) => b.at - a.at)[0] ?? []
63 return from !== undefined && latest !== undefined && latest.open.length > 0 ? { from, items: latest.open } : undefined
64}
65hooks/i18n.ts 274 lines1export type Lang = 'en' | 'zh-TW'
2
3export type ToolKind = 'command' | 'read' | 'edit' | 'pattern' | 'page' | 'task'
4
5// The words of tessera's tool rows: one verb per tool, a phrase per kind for a group of calls.
6export type ToolWords = {
7 verbs: Record<string, string>
8 group: (kind: ToolKind, n: number) => string
9 other: (name: string, n: number) => string
10 join: string
11 failed: (n: number) => string
12 failedRow: string
13 interrupted: string
14 last: string
15 deleted: string
16}
17
18const EN_GROUPS: Record<ToolKind, [string, string]> = {
19 command: ['ran', 'command'],
20 read: ['read', 'file'],
21 edit: ['edited', 'file'],
22 pattern: ['searched', 'pattern'],
23 page: ['fetched', 'page'],
24 task: ['delegated', 'task'],
25}
26const plural = (noun: string, n: number) => (n === 1 ? noun : noun.endsWith('h') ? `${noun}es` : `${noun}s`)
27
28const TOOL_WORDS_EN: ToolWords = {
29 verbs: {
30 Bash: 'Ran', PowerShell: 'Ran', Read: 'Read', Write: 'Wrote', Edit: 'Edited', MultiEdit: 'Edited', NotebookEdit: 'Edited',
31 Grep: 'Searched', Glob: 'Listed', WebFetch: 'Fetched', WebSearch: 'Searched the web for', Agent: 'Delegated', Task: 'Delegated',
32 },
33 group: (kind, n) => `${EN_GROUPS[kind][0]} ${n} ${plural(EN_GROUPS[kind][1], n)}`,
34 other: (name, n) => `used ${n} ${plural(name, n)}`,
35 join: ', ',
36 failed: n => ` · ${n} failed`,
37 failedRow: ' failed',
38 interrupted: ' interrupted',
39 last: ' · last: ',
40 deleted: 'Deleted',
41}
42
43const ZH_GROUPS: Record<ToolKind, [string, string]> = {
44 command: ['執行', '個指令'],
45 read: ['讀取', '個檔案'],
46 edit: ['編輯', '個檔案'],
47 pattern: ['搜尋', '個模式'],
48 page: ['抓取', '個網頁'],
49 task: ['委派', '個任務'],
50}
51
52const TOOL_WORDS_ZH: ToolWords = {
53 verbs: {
54 Bash: '執行', PowerShell: '執行', Read: '讀取', Write: '寫入', Edit: '編輯', MultiEdit: '編輯', NotebookEdit: '編輯',
55 Grep: '搜尋', Glob: '列出', WebFetch: '抓取', WebSearch: '網路搜尋', Agent: '委派', Task: '委派',
56 },
57 group: (kind, n) => `${ZH_GROUPS[kind][0]} ${n} ${ZH_GROUPS[kind][1]}`,
58 other: (name, n) => `使用 ${name} ${n} 次`,
59 join: ',',
60 failed: n => ` · ${n} 個失敗`,
61 failedRow: ' 失敗',
62 interrupted: ' 已中斷',
63 last: ' · 最後:',
64 deleted: '刪除',
65}
66
67// The names the guards give their rules in the toast; the reason the model reads stays English.
68const RULES_EN = {
69 'node_modules link': 'node_modules link',
70 'delete through a link': 'delete through a link',
71 'git add -A': 'git add -A',
72 'git tree rewrite': 'git tree rewrite',
73 'force push': 'force push',
74 'discard changes': 'discarding changes',
75 'zh-TW wording': 'zh-TW wording',
76 'project glossary': 'project glossary',
77 'unquoted heredoc': 'unquoted heredoc',
78 'Workflow model': 'Workflow model',
79 'Workflow authorization': 'Workflow authorization',
80 'CJK as \\u escapes': 'CJK as \\u escapes',
81 'Agent model': 'Agent model',
82 'file encoding': 'file encoding',
83 'root delete': 'delete of a root, home or the session directory',
84 'data reset': 'database reset',
85 'other session': 'file another session edited',
86}
87
88export type Rule = keyof typeof RULES_EN
89
90const RULES_ZH: Record<Rule, string> = {
91 'node_modules link': '連結 node_modules',
92 'delete through a link': '刪除會穿過連結',
93 'git add -A': 'git add -A',
94 'git tree rewrite': '改寫主工作區',
95 'force push': '強制推送',
96 'discard changes': '丟棄未提交的改動',
97 'zh-TW wording': '繁中用語',
98 'project glossary': '專案用語表',
99 'unquoted heredoc': '未加引號的 heredoc',
100 'Workflow model': 'Workflow 未指定模型',
101 'Workflow authorization': 'Workflow 未引用你的話',
102 'CJK as \\u escapes': 'CJK 寫成 \\u 跳脫',
103 'Agent model': 'Agent 未指定模型',
104 'file encoding': '檔案編碼',
105 'root delete': '刪除根目錄、家目錄或 session 目錄',
106 'data reset': '重置資料庫',
107 'other session': '另一個 session 剛改過的檔案',
108}
109
110const EN = {
111 copied: 'Copied',
112 toolWords: TOOL_WORDS_EN,
113 copyLabels: { block: '⧉ copy', reply: '⧉ copy reply', prompt: '⧉ copy prompt', source: '⧉ source', art: '⧉ art' },
114 copyFailed: 'Copy failed',
115 nothingToCopy: 'Nothing to copy yet.',
116 noCodeBlock: 'The last reply has no code block.',
117 noPromptBlock: 'The last reply has no prompt card.',
118 copiedPrompt: 'Copied the prompt.',
119 setupTitle: 'tessera features',
120 setupHint: 'tessera: /tessera setup picks the features you want on.',
121 setupOpened: 'tessera setup opened.',
122 closePane: '✕ close',
123 peekUsage: 'Usage: /tessera peek <file> or @file (.md, .csv, .json, .docx, .xlsx, .pptx)',
124 peekUnreadable: (path: string) => `Cannot read ${path} (missing, or over 4 MiB).`,
125 peekUnknown: (path: string) => `tessera does not preview this kind of file: ${path}`,
126 pastedText: (n: number, lines: number) => `Pasted text #${n} · ${lines} lines`,
127 carryTitle: (n: number) => `${n} unfinished from your last session here`,
128 carryContinue: 'continue',
129 agentPicked: (task: string, model: string) => `tessera: ${task} → ${model}`,
130 cacheWarm: (minutes: number, tokens: string) => `⏱ Prompt cache cold in ${minutes} min · the next message re-caches ${tokens} tokens`,
131 cacheCold: (tokens: string) => `⏱ Prompt cache cold · the next message re-caches ${tokens} tokens`,
132 veiled: (n: number) => `tessera masked ${n} secret ${n === 1 ? 'value' : 'values'} in a tool result; Claude reads •••• too (maskSecrets in /tessera setup)`,
133 carryDismiss: 'dismiss',
134 diffSummary: (added: number, removed: number) => `Added ${added} ${added === 1 ? 'line' : 'lines'}, removed ${removed} ${removed === 1 ? 'line' : 'lines'}`,
135 diffHidden: (n: number) => `${n} more ${n === 1 ? 'line' : 'lines'}`,
136 diffExpand: 'expand',
137 updateTitle: 'tessera gets no updates: auto-update is off for its marketplace',
138 updateOpen: 'open /plugin',
139 updateLater: 'not now',
140 updateSteps: (market: string) => `In /plugin: Marketplaces → ${market} → Enable auto-update`,
141 movedTitle: (marketplace: string, old: string) => `tessera's install moved to tessera@${marketplace}: the marketplace added as ${old} no longer updates it`,
142 movedCopy: '⧉ copy the commands',
143 movedSteps: 'Run the four commands (README → Install), start a new session, then pick your options again in /tessera setup',
144 movedCommands: (old: string) => `claude plugin uninstall tessera@${old}\nclaude plugin marketplace remove ${old}\nclaude plugin marketplace add OG-Matcha/tessera\nclaude plugin install tessera@og-matcha --scope user\n`,
145 carryPrompt: (items: string[]) => `Unfinished tasks from the last session in this project:\n${items.map(i => `- ${i}`).join('\n')}\nCheck which still apply and carry on with them.`,
146 quietTitle: (n: number, minutes: number) => (n > 1 ? `${n} background commands have written nothing for ${minutes} min` : `A background command has written nothing for ${minutes} min`),
147 quietAskButton: 'ask Claude',
148 quietIgnore: 'ignore',
149 quietToast: (command: string, minutes: number) => `tessera: no output for ${minutes} min from ${command}`,
150 quietAsk: (ids: string[], minutes: number) => ids.length > 1 ? `Background tasks ${ids.join(', ')} have written nothing for ${minutes} minutes. Read their output so far and tell me which are still running and which are stuck; stop the stuck ones.` : `Background task ${ids[0]} has written nothing for ${minutes} minutes. Read its output so far and tell me whether it is still working or stuck; if stuck, stop it and say what to do instead.`,
151 copiedReply: 'Copied the last reply.',
152 copiedCode: 'Copied the last code block.',
153 unknownTheme: (name: string, themes: string) => `Unknown theme "${name}". Themes: ${themes}`,
154 themeFailed: 'Could not switch theme',
155 themeSet: (name: string) => `Theme set to ${name}.`,
156 commandDescription: 'Pick tessera features, go back to a prompt you sent, preview a document, switch theme, copy the last reply, or show the demo',
157 original: 'original',
158 noPreview: '(no preview)',
159 blocked: (rule: Rule) => `tessera blocked: ${RULES_EN[rule]}`,
160 reminded: (rule: Rule) => `tessera asked Claude to confirm: ${RULES_EN[rule]}`,
161 stashSaved: 'tessera: the changes being discarded are in git stash (stash@{0}); git stash pop brings them all back, git checkout stash@{0} -- <file> one file',
162 stashFailed: 'tessera: could not stash the changes being discarded; they are gone with the command',
163 inboxFiled: (count: number, regressed: number[]) => `Inbox: filed ${count}${regressed.length ? ` · looks like fixed ${regressed.map(n => `#${n}`).join(', ')} again` : ''}`,
164 inboxMarked: (ids: number[], commit: string) => `Marked ${ids.map(n => `#${n}`).join(', ') || 'nothing'} fixed in ${commit}.`,
165 inboxHeaders: ['#', 'Time', 'From', 'Message', 'Status'],
166 inboxEmpty: 'The inbox is empty. Paste a chat log with timestamped lines (22:55 Name message) to fill it.',
167 inboxOff: 'The feedback inbox is off. Turn on feedbackInbox in /config.',
168 drawingOff: 'tessera drawing is off (enabled in /config).',
169 recordOn: 'Record mode on: in what tessera draws (replies, your prompts, tool rows, folded diffs, paste previews, the prompt log) API keys, tokens, passwords, emails and phone numbers show as ••••. What Claude Code draws itself (tool results, permission dialogs, the prompt box) is not masked. Screen only: the transcript, what Claude reads and /tessera copy are unchanged; copy buttons copy what is shown. /tessera record again turns it off.',
170 recordOff: 'Record mode off.',
171 recordStatus: '⏺ tessera record: keys, emails and phone numbers masked on screen',
172 logTitle: (n: number) => `Prompt log · ${n} ${n === 1 ? 'prompt' : 'prompts'}`,
173 logEmpty: 'No prompts in this session yet.',
174 logOff: 'The prompt log is off. Turn on promptLog in /tessera setup.',
175 logOpened: 'Prompt log opened.',
176 logImage: '(image)',
177 logKinds: { text: 'prompt', command: 'command', paste: 'with pasted text', image: 'image', remote: 'sent remotely' } as Record<string, string>,
178 logKeys: 'Tab or j k select · ⏎ jump · f put back · esc close',
179 logUp: '↑',
180 logDown: '↓',
181 logFill: 'put back',
182 logTooOld: (n: number) => `#${n} is too far back for the screen to keep; press f to put it back in the prompt`,
183 logNoRow: (n: number) => `#${n} drew no row to jump to; press f to put it back in the prompt`,
184 logCannotJump: (n: number, reason: string) => `Cannot jump to #${n} (${reason}); press f to put it back in the prompt`,
185 logFilled: (n: number) => `Put #${n} back in the prompt`,
186}
187
188const ZH: typeof EN = {
189 copied: '已複製',
190 toolWords: TOOL_WORDS_ZH,
191 copyLabels: { block: '⧉ 複製', reply: '⧉ 複製回覆', prompt: '⧉ 複製 prompt', source: '⧉ 原始碼', art: '⧉ 文字圖' },
192 copyFailed: '複製失敗',
193 nothingToCopy: '還沒有可以複製的回覆。',
194 noCodeBlock: '上一則回覆沒有程式碼區塊。',
195 noPromptBlock: '上一則回覆沒有 prompt 卡片。',
196 copiedPrompt: '已複製 prompt。',
197 setupTitle: 'tessera 功能',
198 setupHint: 'tessera:輸入 /tessera setup 選擇要開的功能。',
199 setupOpened: '已開啟 tessera 功能設定。',
200 closePane: '✕ 關閉',
201 peekUsage: '用法:/tessera peek <檔案> 或 @檔案(.md、.csv、.json、.docx、.xlsx、.pptx)',
202 peekUnreadable: path => `讀不到 ${path}(不存在或超過 4 MiB)。`,
203 peekUnknown: path => `tessera 還不能預覽這種檔案:${path}`,
204 pastedText: (n, lines) => `貼上的文字 #${n} · ${lines} 行`,
205 carryTitle: n => `上次在這個專案還有 ${n} 項沒完成`,
206 carryContinue: '接續',
207 agentPicked: (task, model) => `tessera:${task} → ${model}`,
208 cacheWarm: (minutes, tokens) => `⏱ 快取 ${minutes} 分後冷掉 · 下一則要重新快取 ${tokens} tokens`,
209 cacheCold: tokens => `⏱ 快取已冷 · 下一則要重新快取 ${tokens} tokens`,
210 veiled: n => `tessera 遮住了工具結果裡的 ${n} 個祕密;Claude 讀到的也是 ••••(/tessera setup 的 maskSecrets)`,
211 carryDismiss: '略過',
212 diffSummary: (added, removed) => `新增 ${added} 行,刪除 ${removed} 行`,
213 diffHidden: n => `還有 ${n} 行未顯示`,
214 diffExpand: '展開',
215 updateTitle: 'tessera 收不到更新:它的 marketplace 沒開自動更新',
216 updateOpen: '打開 /plugin',
217 updateLater: '不用了',
218 updateSteps: market => `在 /plugin 裡:Marketplaces → ${market} → Enable auto-update`,
219 movedTitle: (marketplace, old) => `tessera 的安裝位置改為 tessera@${marketplace}:以 ${old} 加入的 marketplace 不會再更新它`,
220 movedCopy: '⧉ 複製指令',
221 movedSteps: '執行這四個指令(README → 安裝),開新 session,再到 /tessera setup 重選一次選項',
222 movedCommands: old => `claude plugin uninstall tessera@${old}\nclaude plugin marketplace remove ${old}\nclaude plugin marketplace add OG-Matcha/tessera\nclaude plugin install tessera@og-matcha --scope user\n`,
223 carryPrompt: items => `上次在這個專案沒完成的待辦:\n${items.map(i => `- ${i}`).join('\n')}\n請確認哪些還需要做,接著處理。`,
224 quietTitle: (n, minutes) => (n > 1 ? `${n} 個背景指令已經 ${minutes} 分鐘沒有輸出` : `有個背景指令已經 ${minutes} 分鐘沒有輸出`),
225 quietAskButton: '問 Claude',
226 quietIgnore: '忽略',
227 quietToast: (command, minutes) => `tessera:${command} 已 ${minutes} 分鐘沒有輸出`,
228 quietAsk: (ids, minutes) => ids.length > 1 ? `背景工作 ${ids.join('、')} 已經 ${minutes} 分鐘沒有輸出。請讀它們目前的輸出,判斷哪些還在跑、哪些卡住了;卡住的就停掉。` : `背景工作 ${ids[0]} 已經 ${minutes} 分鐘沒有輸出。請讀它目前的輸出,判斷它還在跑還是卡住了;卡住就停掉它,並說明該怎麼做。`,
229 copiedReply: '已複製上一則回覆。',
230 copiedCode: '已複製上一則回覆的最後一個程式碼區塊。',
231 unknownTheme: (name, themes) => `沒有「${name}」這個主題。可用主題:${themes}`,
232 themeFailed: '無法切換主題',
233 themeSet: name => `主題已切換為 ${name}。`,
234 commandDescription: '挑選 tessera 功能、跳回你送出過的輸入、預覽文件、切換主題、複製上一則回覆,或顯示示範',
235 original: '原圖',
236 noPreview: '(無法預覽)',
237 blocked: rule => `tessera 已攔下:${RULES_ZH[rule]}`,
238 reminded: rule => `tessera 已請 Claude 再確認:${RULES_ZH[rule]}`,
239 stashSaved: 'tessera:被丟棄的改動已存進 git stash(stash@{0});git stash pop 全部拿回,git checkout stash@{0} -- <檔案> 拿回一個檔案',
240 stashFailed: 'tessera:無法把被丟棄的改動存進 stash,它們會隨指令消失',
241 inboxFiled: (count, regressed) => `收件匣:新增 ${count} 則${regressed.length ? ` · 疑似 ${regressed.map(n => `#${n}`).join('、')} 又壞了` : ''}`,
242 inboxMarked: (ids, commit) => `已將 ${ids.map(n => `#${n}`).join('、') || '(無)'} 標為已修(${commit})。`,
243 inboxHeaders: ['#', '時間', '誰', '內容', '狀態'],
244 inboxEmpty: '收件匣是空的。貼上帶時間的聊天紀錄(22:55 名字 訊息)就會建立項目。',
245 inboxOff: '回饋收件匣沒有開啟,請到 /config 打開 feedbackInbox。',
246 drawingOff: 'tessera 的畫面美化已關閉(/config 的 enabled)。',
247 recordOn: '錄影模式開啟:tessera 畫的內容(回覆、你的輸入、工具列、摺疊差異、貼上預覽、輸入紀錄)裡的 API 金鑰、token、密碼、email 和電話會顯示成 ••••。Claude Code 自己畫的(工具結果、權限對話框、輸入框)不會遮。只改畫面:transcript、Claude 讀到的內容和 /tessera copy 都不變;複製按鈕複製的是畫面上的樣子。再輸入一次 /tessera record 關閉。',
248 recordOff: '錄影模式關閉。',
249 recordStatus: '⏺ tessera 錄影模式:畫面上的金鑰、email、電話已遮住',
250 logTitle: n => `輸入紀錄 · ${n} 則`,
251 logEmpty: '這個 session 還沒有輸入。',
252 logOff: '輸入紀錄沒有開啟,請到 /tessera setup 打開。',
253 logOpened: '已開啟輸入紀錄。',
254 logImage: '(圖片)',
255 logKinds: { text: '輸入', command: '指令', paste: '含貼上內容', image: '圖片', remote: '遠端送出' },
256 logKeys: 'Tab 或 j k 選 · ⏎ 跳 · f 放回 · esc 關',
257 logUp: '↑',
258 logDown: '↓',
259 logFill: '放回輸入框',
260 logTooOld: n => `#${n} 太早,畫面已不保留,按 f 放回輸入框`,
261 logNoRow: n => `#${n} 沒有可以跳的那一列,按 f 放回輸入框`,
262 logCannotJump: (n, reason) => `#${n} 跳不過去(${reason}),按 f 放回輸入框`,
263 logFilled: n => `已把 #${n} 放回輸入框`,
264}
265
266export const STRINGS: Record<Lang, typeof EN> = { en: EN, 'zh-TW': ZH }
267
268// The first locale hint that names a language decides: any Chinese reads Traditional Chinese.
269export function pickLang(option: unknown, hints: (string | undefined)[]): Lang {
270 if (option === 'en' || option === 'zh-TW') return option
271 const hint = hints.find(h => h !== undefined && h !== '' && h !== 'C' && h !== 'POSIX')
272 return hint !== undefined && /^zh|chinese|中文/i.test(hint) ? 'zh-TW' : 'en'
273}
274hooks/session.ts 18 lines1import type { Lang } from './i18n'
2import { STRINGS } from './i18n'
3import type { Env } from './platform'
4import type { Voice } from './voice'
5
6// What the session settles at start and from the person's prompts, read by every feature module.
7export const session = {
8 lang: 'en' as Lang,
9 // The language the person writes in, from their last prompt that told.
10 voice: undefined as Voice | undefined,
11 // Every variable the platform decisions read, read once at session start.
12 env: {} as Env,
13 // Record mode (/tessera record): what tessera draws has keys, emails and phone numbers masked.
14 recording: false,
15}
16
17export const t = () => STRINGS[session.lang]
18hooks/guard.ts 358 lines1export type Risk = 'tree-rewrite' | 'stage-all' | 'link-node-modules'
2
3// A heredoc: `<<` or `<<-`, a delimiter, quoted or not, and the body from the next line to the line that
4// is the delimiter (a trailing \r allowed). `<<<` is a herestring and `<<` inside `$(( ))` a shift, not
5// one. Several on one line take their bodies in order. A `<<word` with no line equal to word after it is
6// not one (a `<<` in a message or in prose), or the lines after it would go unjudged. `shell` is a body
7// fed to a local shell (bash <<'EOF', sudo bash, pwsh -), which is commands, not data.
8type Heredoc = { quoted: boolean; bodyStart: number; bodyEnd: number; delimiterLine: number; shell: boolean }
9
10const HEREDOC_START = /(?<![<$(])<<(?!<)(-?)\s*(["']?)([A-Za-z_][\w-]*)\2/g
11const inArithmetic = (line: string, at: number) => /\$\(\((?![\s\S]*\)\))/.test(line.slice(0, at))
12const LOCAL_SHELL = /(?:^|[;&|]\s*)(?:sudo\s+(?:-\w+\s+)*)?(?:\S*[\\/])?(?:(?:ba|z|da)?sh|pwsh|powershell)(?:\.exe)?\b[^;&|]*$/i
13
14export function heredocs(command: string): Heredoc[] {
15 const out: Heredoc[] = []
16 const lines = command.split('\n')
17 const offsets: number[] = []
18 for (let o = 0, i = 0; i < lines.length; i++) {
19 offsets.push(o)
20 o += lines[i]!.length + 1
21 }
22 for (let i = 0; i < lines.length; i++) {
23 const line = lines[i]!
24 const starts = [...line.matchAll(HEREDOC_START)].filter(m => !inArithmetic(line, m.index))
25 let next = i + 1
26 for (const m of starts) {
27 const strip = m[1] === '-'
28 const ends = (l: string) => (strip ? l.replace(/^\t+/, '') : l).replace(/\r$/, '') === m[3]
29 let j = next
30 while (j < lines.length && !ends(lines[j]!)) j++
31 if (j >= lines.length) continue
32 out.push({ quoted: m[2] !== '', bodyStart: Math.min(offsets[next] ?? command.length, command.length), bodyEnd: offsets[j]! + lines[j]!.length, delimiterLine: j, shell: LOCAL_SHELL.test(line.slice(0, m.index)) })
33 next = j + 1
34 }
35 i = next - 1
36 }
37 return out
38}
39
40// A heredoc's body is data (a commit message, a file), not commands, so it is left out before a line is
41// split, unless a local shell reads it; the `<<` line itself stays.
42const withoutHeredocs = (command: string): string => {
43 let out = command
44 for (const h of heredocs(command).filter(h => !h.shell).reverse()) out = `${out.slice(0, h.bodyStart)}${out.slice(h.bodyEnd)}`
45 return out
46}
47
48// What may stand before the command word without changing what it does: VAR=value assignments and sudo
49// with its flags (a flag's value, as in -u root, is left; a verb that is a user name matches nothing).
50const PREFIX = /^(?:[A-Za-z_]\w*=\S*\s+)*(?:sudo\s+(?:-\w+\s+)*)?(?:[A-Za-z_]\w*=\S*\s+)*/
51
52// One shell command line split at ;, &&, || and | so each git call is judged on its own.
53const pieces = (command: string) => withoutHeredocs(command).split(/;|&&|&|\|\||\||\n/).map(p => p.trim().replace(PREFIX, ''))
54
55// git with the options that may come before its verb: the ones that take a value (-C <dir>, -c k=v,
56// --git-dir <path>) and the flags (--no-pager, -P, --no-optional-locks, --bare).
57const GIT_OPTIONS = String.raw`(?:(?:-[Cc]|--git-dir|--work-tree|--namespace|--exec-path|--config-env)\s+(?:"[^"]*"|'[^']*'|\S+)|--[\w-]+(?:=\S*)?|-[A-Za-z])\s+`
58const GIT = new RegExp(String.raw`^(?:git|git\.exe)\s+(?:${GIT_OPTIONS})*([^-\s]\S*)(.*)$`, 'i')
59
60export function shellRisks(command: string): Risk[] {
61 const risks = new Set<Risk>()
62 for (const piece of pieces(command)) {
63 const git = GIT.exec(piece)
64 if (git) {
65 const verb = (git[1] ?? '').toLowerCase()
66 const rest = git[2] ?? ''
67 if (verb === 'checkout' || verb === 'switch' || verb === 'reset' || verb === 'restore') risks.add('tree-rewrite')
68 if (verb === 'stash' && !/^\s+(list|show)\b/.test(rest)) risks.add('tree-rewrite')
69 if (verb === 'clean' && /\s-\w*f/.test(rest)) risks.add('tree-rewrite')
70 if (verb === 'add' && /\s(-A|--all|\.)(\s|$)/.test(rest)) risks.add('stage-all')
71 if (verb === 'commit' && rest.split(/\s+/).some(w => w === '--all' || /^-[a-zA-Z]*a/.test(w))) risks.add('stage-all')
72 }
73 const links = /\bmklink\s+\/[JD]\b|\bNew-Item\b.*-ItemType\s+['"]?(Junction|SymbolicLink)|\bln\s+-\w*s/i.test(piece)
74 if (links && /node_modules/i.test(piece)) risks.add('link-node-modules')
75 }
76 return [...risks]
77}
78
79// A force push to the default branch rewrites history that others and CI build on. Each forced push
80// names its destination branches; undefined stands for the current branch, which a push with no refspec
81// (or HEAD) sends.
82export function forcePushes(command: string): (string | undefined)[] {
83 const found: (string | undefined)[] = []
84 for (const piece of pieces(command)) {
85 const git = GIT.exec(piece)
86 if (git?.[1]?.toLowerCase() !== 'push') continue
87 const words = (git[2] ?? '').trim().split(/\s+/).filter(w => w !== '')
88 const forced = words.some(w => /^(--force(-with-lease)?(=.*)?|-[a-zA-Z]*f[a-zA-Z]*)$/.test(w))
89 const refspecs = words.filter(w => !w.startsWith('-')).slice(1)
90 for (const spec of refspecs) {
91 if (!forced && !spec.startsWith('+')) continue
92 const dest = spec.replace(/^\+/, '').split(':').pop() ?? ''
93 found.push(dest === 'HEAD' || dest === '' ? undefined : dest)
94 }
95 if (forced && refspecs.length === 0) found.push(undefined)
96 }
97 return found
98}
99
100// Git calls that throw away uncommitted work: reset --hard (every tracked change), checkout or restore of
101// paths, or checkout -f (unstaged changes to them), clean -f (untracked files). A plain checkout of a
102// branch is left out: git itself refuses it when it would overwrite changes.
103export type Discard = { verb: 'reset' | 'checkout' | 'restore' | 'clean'; args: string[] }
104
105export function discards(command: string): Discard[] {
106 const found: Discard[] = []
107 for (const piece of pieces(command)) {
108 const git = GIT.exec(piece)
109 const verb = git?.[1]?.toLowerCase()
110 const words = tokens(git?.[2] ?? '')
111 if (verb === 'reset' && words.includes('--hard')) found.push({ verb, args: [] })
112 if (verb === 'checkout') {
113 const dashes = words.indexOf('--')
114 const paths = dashes === -1 ? words.filter(w => w === '.') : words.slice(dashes + 1)
115 if (dashes !== -1 || paths.length > 0 || words.some(w => /^(-f|--force)$/.test(w))) found.push({ verb, args: paths })
116 }
117 if (verb === 'restore' && (!words.some(w => /^(-S|--staged)$/.test(w)) || words.some(w => /^(-W|--worktree)$/.test(w))))
118 found.push({ verb, args: words.filter(w => !w.startsWith('-')) })
119 // Every word, not only the dashed ones: -e takes the next word as its pattern.
120 if (verb === 'clean' && words.some(w => /^(-\w*f\w*|--force)$/.test(w))) found.push({ verb, args: words })
121 }
122 return found
123}
124
125// The options of git clean that only narrow or describe a run. The preview keeps these and drops every
126// other word, so no spelling of force (-ff, -fdf, --forc) or of interactive reaches it.
127const CLEAN_FLAGS = new Set(['d', 'x', 'X', 'q', 'n'])
128const CLEAN_LONG = new Set(['--quiet', '--dry-run'])
129
130// The dry run that lists what a git clean would remove. -e keeps its pattern: a pattern left behind once
131// let the closing -n become it, and `git clean -ffdx -e .env` previewed as a forced delete of .env.
132// clean.requireForce is pinned on as well, so an option read wrong makes git refuse rather than delete.
133export function cleanPreview(args: readonly string[]): string[] {
134 const kept: string[] = []
135 for (let i = 0; i < args.length; i++) {
136 const arg = args[i]!
137 if (arg === '--') break
138 if (CLEAN_LONG.has(arg) || /^--exclude=./.test(arg)) kept.push(arg)
139 else if (arg === '--exclude' || arg === '-e') {
140 const pattern = args[++i]
141 if (pattern !== undefined) kept.push('-e', pattern)
142 } else if (/^-[A-Za-z]/.test(arg)) {
143 let flags = ''
144 let pattern: string | undefined
145 for (let j = 1; j < arg.length && pattern === undefined; j++) {
146 if (arg[j] === 'e') pattern = arg.slice(j + 1) || args[++i]
147 else if (CLEAN_FLAGS.has(arg[j]!)) flags += arg[j]
148 }
149 if (flags !== '') kept.push(`-${flags}`)
150 if (pattern !== undefined) kept.push('-e', pattern)
151 }
152 }
153 return ['-c', 'clean.requireForce=true', 'clean', ...kept, '-n']
154}
155
156export const isDefaultBranch =(branch: string) => /^(refs\/heads\/)?(main|master)$/.test(branch)
157
158export const isAbsolute = (path: string) => /^([a-z]:)?[\\/]/i.test(path)
159
160// A path under base, with `.` and `..` folded, one slash style and a lower-case drive letter, so two
161// spellings of one place compare equal: git prints --git-dir absolute and --git-common-dir relative
162// when run from a subdirectory.
163export function resolvePath(base: string, path: string): string {
164 const parts: string[] = []
165 for (const part of (isAbsolute(path) ? path : `${base}/${path}`).replace(/\\/g, '/').split('/')) {
166 if (part === '..') parts.pop()
167 else if (part !== '.' && (part !== '' || parts.length === 0)) parts.push(part)
168 }
169 return parts.join('/').replace(/^[a-z]:/i, drive => drive.toLowerCase())
170}
171
172// A heredoc with an unquoted delimiter is expanded before it is written: ${x}, $(cmd) and backticks are
173// replaced and \\ becomes \, so code written through one loses its template literals and escapes.
174const EXPANDED = /\$\{|\$\(|`|\\[\\$`]/
175
176export function expandedHeredoc(command: string): string | undefined {
177 const lines = command.split('\n')
178 for (const h of heredocs(command)) {
179 if (h.quoted) continue
180 const body = command.slice(h.bodyStart, h.delimiterLine < lines.length ? h.bodyEnd - lines[h.delimiterLine]!.length : h.bodyEnd)
181 const hit = EXPANDED.exec(body)
182 if (hit) return hit[0]
183 }
184 return undefined
185}
186
187// The git -C directory, after any other option before the verb; -c is a config value, so the case counts.
188const GIT_DASH_C = new RegExp(String.raw`\b[gG]it(?:\.exe)?\s+(?:${GIT_OPTIONS.replace('-[Cc]', '-c')})*-C\s+("[^"]+"|'[^']+'|[^\s;&|]+)`)
189
190const unquote = (s: string) => s.replace(/^["']|["']$/g, '')
191const CD = /^\s*(?:cd|Set-Location|sl|pushd)\s+(?:\/d\s+)?("[^"]+"|'[^']+'|[^\s;&|]+)/i
192
193export function commandDir(command: string): string | undefined {
194 const cd = CD.exec(command)
195 if (cd?.[1]) return unquote(cd[1])
196 const dashC = GIT_DASH_C.exec(command)
197 return dashC?.[1] ? unquote(dashC[1]) : undefined
198}
199
200// A path as Git Bash on Windows spells it (/c/w, ~/w) as the file system does: C:/w, <home>/w.
201export const hostPath = (path: string, home: string | undefined, windows: boolean): string => {
202 const expanded = home !== undefined ? path.replace(/^~(?=[\\/]|$)/, home) : path
203 // A bare drive (C:, d:, /c) is its root.
204 return windows ? expanded.replace(/^\/([a-zA-Z])(?=\/|$)/, (_, drive: string) => `${drive.toUpperCase()}:`).replace(/^([A-Za-z]:)$/, '$1/') : expanded
205}
206
207const QUOTE = 10
208const flat = (s: string) => [...s.replace(/\s+/g, ' ')]
209
210export function quotesUser(script: string, userPrompts: string[]): boolean {
211 const chars = flat(script)
212 const grams = new Set<string>()
213 for (let i = 0; i + QUOTE <= chars.length; i++) grams.add(chars.slice(i, i + QUOTE).join(''))
214 return userPrompts.some(p => {
215 const words = flat(p)
216 for (let i = 0; i + QUOTE <= words.length; i++) {
217 const gram = words.slice(i, i + QUOTE).join('')
218 if (gram.trim().length === QUOTE && grams.has(gram)) return true
219 }
220 return false
221 })
222}
223
224// A Workflow script whose agent() calls name no model runs them all on the session's model.
225export const scriptNamesModel = (script: string) => !/\bagent\s*\(/.test(script) || /\bmodel\s*:/.test(script)
226
227const tokens = (piece: string) => [...piece.matchAll(/"([^"]*)"|'([^']*)'|(\S+)/g)].map(m => m[1] ?? m[2] ?? m[3] ?? '')
228const words = tokens
229
230// The commands whose switches are written /s /q, joined as /s/q too; for rm, /c is the Git Bash C: drive.
231const CMD_STYLE = new Set(['rd', 'rmdir', 'del'])
232
233// The paths a command deletes recursively: rm -r, Remove-Item -Recurse, rmdir /s, rd /s and git worktree
234// remove, also behind cmd /c (with its command quoted as one word, or //c from Git Bash). A trailing /*
235// names the directory's contents, which for a root, home or the working directory is as good as itself.
236export function recursiveDeletes(command: string): string[] {
237 return deleteSites(command).map(s => s.target)
238}
239
240// A recursive delete and the directory the command has moved to by then: each cd, pushd or Set-Location
241// before it in the chain (relative ones stacked), or a git -C of its own. `make && cd .. && rm -rf repo`
242// deletes repo beside the session directory, not inside it.
243export type DeleteSite = { target: string; dir?: string }
244
245export function deleteSites(command: string): DeleteSite[] {
246 const sites: DeleteSite[] = []
247 let dir: string | undefined
248 for (const piece of pieces(command)) {
249 const cd = CD.exec(piece)
250 if (cd?.[1]) {
251 const to = unquote(cd[1])
252 dir = dir === undefined || isAbsolute(to) || /^~/.test(to) ? to : `${dir}/${to}`
253 continue
254 }
255 const dashC = GIT_DASH_C.exec(piece)?.[1]
256 for (const target of deletesIn(piece)) sites.push({ target, ...(dashC !== undefined ? { dir: unquote(dashC) } : dir !== undefined ? { dir } : {}) })
257 }
258 return sites
259}
260
261function deletesIn(piece: string): string[] {
262 const targets: string[] = []
263 {
264 let [verb = '', ...args] = words(piece)
265 if (/^cmd(\.exe)?$/i.test(verb) && /^\/\/?c$/i.test(args[0] ?? '')) {
266 const inner = args.slice(1)
267 ;[verb = '', ...args] = inner.length === 1 && /\s/.test(inner[0]!) ? words(inner[0]!) : inner
268 }
269 const name = verb.toLowerCase().replace(/\.exe$/, '')
270 // git takes options before its verb (-C <dir>, -c k=v, --no-pager); the verb comes after them.
271 if (name === 'git') while (args[0]?.startsWith('-')) args.splice(0, /^(?:-[Cc]|--git-dir|--work-tree)$/.test(args[0]) ? 2 : 1)
272 const cmdStyle = CMD_STYLE.has(name)
273 if (cmdStyle) args = args.flatMap(a => (/^\/[a-z](?:\/[a-z])+$/i.test(a) ? a.slice(1).split('/').map(s => `/${s}`) : [a]))
274 const plain = args.filter(a => !a.startsWith('-') && !(cmdStyle && /^\/[a-z]$/i.test(a)))
275 if (name === 'rm' && args.some(a => /^-\w*r/i.test(a) || a === '--recursive' || /^-Recurse$/i.test(a))) targets.push(...plain)
276 else if ((name === 'remove-item' || name === 'ri' || cmdStyle) && args.some(a => /^-Recurse$/i.test(a) || /^\/s$/i.test(a))) {
277 const named = args.findIndex(a => /^-(Literal)?Path$/i.test(a))
278 targets.push(...(named >= 0 && args[named + 1] ? [args[named + 1] as string] : plain))
279 } else if (name === 'git' && args[0] === 'worktree' && args[1] === 'remove') targets.push(...plain.slice(2))
280 }
281 // The home variables are read as ~, which hostPath expands; any other variable makes a target unknowable.
282 return targets
283 .map(t => t.replace(/^(?:\$HOME|\$\{HOME\}|%USERPROFILE%|\$env:USERPROFILE|\$\{env:USERPROFILE\}|%HOMEDRIVE%%HOMEPATH%|\$env:HOMEDRIVE\$env:HOMEPATH)(?=[\\/]|$)/i, '~').replace(/^([\\/])\*$/, '$1').replace(/(?<=.)[\\/]\*$/, ''))
284 .filter(t => t !== '' && !/[$*?`]/.test(t))
285}
286
287// Commands that throw a database or its volumes away: the ORM and framework resets, Docker's volume
288// removals, and dropdb. Each is named as written, for the reminder.
289const DATA_RESETS: [RegExp, string][] = [
290 [/^(?:npx\s+|pnpm\s+(?:exec\s+)?|yarn\s+|bunx\s+)?prisma\s+(?:migrate\s+reset\b|db\s+push\b.*--force-reset)/, 'prisma migrate reset'],
291 [/^(?:npx\s+)?supabase\s+db\s+reset\b/, 'supabase db reset'],
292 [/^(?:\.\/)?(?:bin\/|bundle\s+exec\s+)?(?:rails|rake)\s+db:(?:drop|reset|purge)\b/, 'rails db:drop'],
293 [/^(?:php\s+)?artisan\s+(?:migrate:(?:fresh|refresh)|db:wipe)\b/, 'artisan migrate:fresh'],
294 [/^docker(?:-compose|\s+compose)\s+(?:\S+\s+)*down\b.*(?:\s-\w*v|\s--volumes)/, 'docker compose down -v'],
295 [/^docker\s+volume\s+(?:rm|prune)\b/, 'docker volume rm'],
296 [/^docker\s+system\s+prune\b.*--volumes/, 'docker system prune --volumes'],
297 [/^dropdb\b/, 'dropdb'],
298]
299
300export const dataResets = (command: string): string[] => [...new Set(pieces(command).flatMap(piece => DATA_RESETS.filter(([re]) => re.test(piece)).map(([, name]) => name)))]
301
302// A recursive delete of one of these has no good reading: the file system's root, a drive, the home
303// directory, or the directory the session works in or one above it. Windows paths compare without case.
304export function rootLike(path: string, cwd: string, home: string | undefined, windows = false): boolean {
305 const norm = (p: string) => {
306 const resolved = resolvePath('', p.replace(/^([a-zA-Z]:)$/, '$1/')).replace(/\/+$/, '')
307 return windows ? resolved.toLowerCase() : resolved
308 }
309 const target = norm(path)
310 if (target === '' || /^[a-z]:$/.test(target)) return true
311 if (home !== undefined && target === norm(home)) return true
312 const work = norm(cwd)
313 return target === work || work.startsWith(`${target}/`)
314}
315
316// Hangul, kana, CJK ideographs and their punctuation: scripts a model should write as themselves.
317const CJK_RANGES: [number, number][] = [
318 [0x1100, 0x11ff],
319 [0x3000, 0x30ff],
320 [0x3130, 0x318f],
321 [0x3400, 0x4dbf],
322 [0x4e00, 0x9fff],
323 [0xac00, 0xd7a3],
324 [0xf900, 0xfaff],
325 [0xff00, 0xffef],
326]
327const CJK = (code: number) => CJK_RANGES.some(([from, to]) => code >= from && code <= to)
328
329const ESCAPE = /\\u([0-9a-fA-F]{4})/g
330const hex = (code: number) => code.toString(16).padStart(4, '0')
331const LITERAL_CJK = new RegExp(`[${CJK_RANGES.map(([from, to]) => `\\u${hex(from)}-\\u${hex(to)}`).join('')}]`)
332
333function cjkEscape(text: string): string | undefined {
334 for (const m of text.matchAll(ESCAPE)) if (CJK(parseInt(m[1] ?? '', 16))) return m[0]
335 return undefined
336}
337
338export const isProse = (path: string) => /\.(md|mdx|markdown|txt|rst|adoc|org)$/i.test(path)
339
340// Text a tool call writes where a CJK escape is a mistake rather than code: anything in a prompt-like
341// parameter, and in files only for prose files or when the same text also holds literal CJK.
342const texts = (v: unknown): string[] => (typeof v === 'string' ? [v] : Array.isArray(v) ? v.flatMap(texts) : v !== null && typeof v === 'object' ? Object.values(v).flatMap(texts) : [])
343
344export function writtenFile(tool: string, input: Record<string, unknown>): { path: string; texts: string[] } | undefined {
345 if (tool !== 'Write' && tool !== 'Edit' && tool !== 'MultiEdit' && tool !== 'NotebookEdit') return undefined
346 return {
347 path: String(input.file_path ?? input.notebook_path ?? ''),
348 texts: [input.content, input.new_string, input.new_source, ...(Array.isArray(input.edits) ? input.edits.map(e => (e as { new_string?: unknown }).new_string) : [])].flatMap(texts),
349 }
350}
351
352export function misEscapedCjk(tool: string, input: Record<string, unknown>): string | undefined {
353 const file = writtenFile(tool, input)
354 if (file !== undefined) return file.texts.map(t => (isProse(file.path) || LITERAL_CJK.test(t) ? cjkEscape(t) : undefined)).find(Boolean)
355 if (tool === 'AskUserQuestion' || tool === 'TodoWrite' || tool === 'TaskCreate' || tool === 'TaskUpdate' || tool === 'Agent') return texts(input).map(cjkEscape).find(Boolean)
356 return undefined
357}
358