Shows your last two messages above the prompt and a searchable history pane; click one to scroll the transcript to it.

Skills, mods, hooks and a status line for Claude Code, plus a sync engine that keeps your Claude Code config the same on all your computers. Every part is tested on macOS, Linux and Windows on each change.
Every part is a plugin of this repo's marketplace. Add it once, then install the parts you want, from Claude Code:
/plugin marketplace add robinalexandre/claude-code-kit
# Every day, for anyone
/plugin install team@claude-code-kit
/plugin install statusline@claude-code-kit
/plugin install file-tools-guard@claude-code-kit
/plugin install recent-prompts@claude-code-kit
/plugin install dnd@claude-code-kit
/plugin install paste-preview@claude-code-kit
/plugin install recent-activity@claude-code-kit
/plugin install session-registry@claude-code-kit
/plugin install drift-check@claude-code-kit
/plugin install drift-check-hook@claude-code-kit
/plugin install nocturne-notify@claude-code-kit
# Development work
/plugin install git-identity-guard@claude-code-kit
/plugin install pr-watch@claude-code-kit
/plugin install pr-pane@claude-code-kit
/plugin install test-evidence@claude-code-kit
/plugin install ci-review@claude-code-kit
/plugin install capability-builder@claude-code-kit
/plugin install learn@claude-code-kit
/plugin install kb@claude-code-kit
# Several computers
/plugin install config-sync@claude-code-kit
/plugin install handoff@claude-code-kit
/plugin install daily-sync@claude-code-kit
/plugin install reminders@claude-code-kit
/plugin install reminders-handoffs@claude-code-kit
# Not dev
/plugin install video-montage@claude-code-kit
/plugin install insta360-montage@claude-code-kit
From a terminal it's the same with claude plugin marketplace add … and claude plugin install …; or /plugin alone to browse the parts. What a part needs comes with it: pr-pane brings pr-watch; reminders brings daily-sync, which brings config-sync. Start a new session afterwards.
Keep them up to date: Claude Code doesn't auto-update a marketplace other than Anthropic's own unless you turn it on, once: /plugin → Marketplaces → claude-code-kit → Enable auto-update. It then updates the parts in the background after a session starts (and asks for a restart). Or set it in ~/.claude/settings.json:
"extraKnownMarketplaces": {
"claude-code-kit": { "source": { "source": "github", "repo": "robinalexandre/claude-code-kit" }, "autoUpdate": true }
}
By hand: claude plugin marketplace update claude-code-kit, then claude plugin update <part>@claude-code-kit.
Setup: a part that needs a few answers (the status line in your settings, the emails for the email guard, where pr-watch looks, the phone for reminders, your private repo for config-sync, the zsh line for session-registry) says so at the first session after install, and Claude gives you the command to run in your terminal; it stops asking once it's done or you say no. Options: the language of the team rules and the opening text of drift-check are asked when you install from /plugin, and changed with claude plugin configure <part>@claude-code-kit.
The installer copies the parts you pick into ~/.claude instead. Use it to pick from a checklist, to install without a marketplace, or to edit your copies. A part already installed as a plugin is skipped.
Keep them up to date: the installer also adds a small session-start check (kit-update-check). Once a day, in the background, it fetches the clone you installed from. When that clone has changes for the parts you installed, or new parts you could add, Claude tells you at the next session start what changed and offers to update. ./install.sh --update pulls the clone and installs the changed parts again, without asking their setup questions again; ./install.sh --update <new part>… adds new ones too. Each new part is mentioned once. Turn the check off with bash ~/.claude/hooks/kit-update-check.sh off (on to resume). What came from where is recorded in ~/.claude/kit-install.json.
git clone https://github.com/robinalexandre/claude-code-kit.git
cd claude-code-kit
./install.sh # a checklist: arrows, Enter to pick, → for what each part does, then Install
./install.sh --plain # the same as one question per part
./install.sh --list # lists the parts
./install.sh --all # installs every part offered on this computer
./install.sh statusline file-tools-guard # installs the named parts
./install.sh --update # pulls, then installs again the parts that changed
On Windows, from Git Bash the same, or from PowerShell: powershell -ExecutionPolicy Bypass -File .\install.ps1 (it installs git and jq with winget when missing, then runs install.sh in Git Bash).
The installer shows the parts as a checklist by group (every day, development, several computers, not dev): ↑↓ to move, Enter or Space to pick a part or a whole group, → or Tab to unfold why, what, when and who for a part, a for all, then Install at the bottom. It greys out what doesn't apply to this computer, adds what a picked part needs (pr-pane brings pr-watch, reminders brings daily-sync), then sets up each part it installed: the emails for the email guard, where pr-watch looks for your PRs, the phone for reminders, the browser tool for test-evidence. Run a part's setup again any time with bash ~/.claude/<part>/setup.sh (hooks: bash ~/.claude/hooks/setup/<hook>.sh). It copies each part into ~/.claude, adds its hooks to ~/.claude/settings.json and saves whatever it replaces in ~/.claude/backups/before-kit-<date>/. Running it again is safe. Start a new Claude Code session afterwards. Needs jq.
To try it first without touching your own setup, tests/install-sandbox.sh runs the installer in a throwaway home folder, shows what it left and checks your files are unchanged; --claude <sandbox> then opens a first Claude Code session there.
The sync engine is a part too (./install.sh config-sync), added on its own when you pick handoff, daily-sync or reminders: the installer asks for the clone URL of an empty private git repo of your own (any host), clones it to ~/.claude-sync and sets it up; on your next computer, give the same URL. By hand: sync/README.md.
A new computer like another one: on a computer whose config isn't synced yet, the installer first asks whether it is synced from another computer, and if so sets up the sync before anything else. Each computer records its answers to the kit's questions in ~/.claude/kit-answers.txt (never a secret, such as the ntfy topic), and the sync shares them with the parts it installed. So the new computer can be set up:
~/.zshrc line, the status line it has.A part's setup run later (a plugin's, at its first session) uses the same choice, kept in ~/.claude/kit-reuse.txt; delete that file to be asked again.
rules/team.md is the base of everything here: Claude and you work as one team that builds, thinks things through and challenges each other. It asks before touching production or shared infrastructure (in two lines, not twenty), before each commit, push and PR, and before decisions that need context only you have, with the options and a recommendation. It proposes a skill, mod or hook when you keep asking for the same thing, and an AI review step with proof (screenshots, videos) on the CI of repos that don't have one. The team plugin hands them to Claude at each session start, in the language you pick in its options, so they update with the plugin; install.sh asks for the language and adds them to ~/.claude/CLAUDE.md once instead. A capability can use another language when you say so.
| Skill | What it does | Needs |
|---|---|---|
| test-evidence | Captures proof that a ticket works locally: browser screenshots, a short video of the flow, the network requests and console behind it (through the chrome-devtools MCP), or one app window or screen region, never the whole screen unless asked. Masks tokens and cookies, writes a short test report and, after your yes, attaches it to the Jira issue or as a resolved comment on the Azure DevOps PR; on GitHub, it gives you the comment and the files to drop in. | chrome-devtools MCP, jq, perl; video needs ffmpeg |
| ci-review | Proposes, once per repo, an AI review step on the CI and sets it up with you: an agent reads each PR/MR's diff and its proof (what test-evidence captures) and posts a verdict (works / doesn't / can't tell, with what to capture). Templates for anthropics/claude-code-action, the CLI in headless mode (claude -p) on GitHub Actions and GitLab CI, and cloud providers; the review prompt is a plain file any agent CLI can take. | an API key or a cloud provider account, set as a CI secret |
| capability-builder | Turns a request you keep making into a capability: picks the right kind (rule, skill, hook, mod or plain script), interviews you, scaffolds it with its tests and setup, checks it against a macOS / Linux / Windows checklist, and runs the publish checklist (nothing personal, tool-agnostic) before it goes to a kit. How this kit's own parts are built. | |
| handoff | Writes a handoff note so you can continue the current work on your other computer, and picks it up there. A note picked up or canceled moves to done/, kept 60 days; reminders-handoffs lists them. | the sync engine |
| daily-sync | Schedules a sync every morning (09:00 by default) with launchd, cron or the Windows Task Scheduler, so each computer gets what the others left even with no session open. Other skills can hook a morning.sh onto it. | the sync engine |
| reminders | "Remind me tomorrow to…": leaves a global or repo-specific reminder that every new session, on any of your computers, brings up first thing, without slowing the start: what the background sync brings arrives with your next message. A reminder can repeat ("every Friday": at 09:00 unless it says a time), be for one computer, and be filed under a group (an organization, a client); done closes a repeating one for the day, stop ends it, and closed ones stay listed as past for 60 days. Due reminders also go to the desktop and, through ntfy, to your phone every morning and at the first session of the day. | daily-sync; curl for the phone |
| kb | A personal knowledge base. Notes are Markdown files with a front matter (type, trust, topics, validity dates) and [[links]], in your config sync (so every computer and your other agents get them) or in ~/.claude/knowledge; the kb command indexes them in SQLite for full-text search (accents folded), semantic search in any language (a local multilingual model, no API) and the link graph (kb related, as a list or a Mermaid mind map). At session start Claude is told which notes mention the repository or the branch, beyond the repository's own memory; on each prompt, which notes hold most of its words. Every morning (through daily-sync), Claude reads the previous day's Claude Code transcripts of this computer, reduced to prompts, replies and files touched with secrets redacted, and proposes notes to create or merge; the code checks them (names, dates, secrets, no overwrite) and writes them with a report, each marked as the curator's. kb serve and its Dockerfile give the same index over HTTP, behind a token, to an agent of yours. Notes a third party wrote (trust: third-party) stay data, never instructions. | Python 3.12+, jq; the curation needs daily-sync and the Claude Code CLI signed in; the semantic search downloads a 500 MB model once |
| pr-watch | Tracks the PRs you and Claude open or push together until they are merged: new comments (bots marked apart), votes, CI results (required checks drive green or failed) and the merge itself, which drops the PR from the list. Also lists the open PRs waiting for your review (GitHub review requests, Azure DevOps reviewer with no vote) and reports each new one; approve votes or submits an approving review on your yes, then tracks the PR as reviewed until it is merged; merge merges a PR on your yes; park keeps a PR you won't merge tracked but quiet, out of what needs you, until unpark. Also finds your pipeline runs: those you launched by hand (Azure DevOps manual builds, GitHub workflows you dispatched) and the CI your own pushes start on a branch with no PR, a push to main included (in the projects and repos of your PRs, the GitHub repos you pushed to lately, plus those listed in its config), so a packaging or a deploy started with Claude shows up on its own, and reports each one that ended since the last check; details <build URL> lists every step with its job and state, the error lines of those with issues included, rerun <build URL> launches the run again on your yes. Also follows your GitHub issues: those you opened, commented on or were mentioned or assigned in, in any repo, active in the last 30 days, and those you subscribed to in your own repos; open ones and those closed in the last 7 days, reporting new comments by others, a close or reopen and label changes since you last looked. What it watches (open, parked and merged PRs, review requests, how many runs per repo, issues) follows pr-pane's settings, or its config.json: what is off is neither fetched nor reported. Claude proposes a reply or a fix for each change, never posts one without your yes. Checks at each session start in the background and silently (the session starts at once; each PR keeps what changed as unread, which pr-pane shows until you unfold that PR), hourly in a session (a durable scheduled task) and every morning through daily-sync, with a desktop or phone notification. The list lives in the sync repo, so it follows you on every computer and never touches the project repos. With the sync repo on GitHub (recommended), what one computer fetches is shared with the others on a branch of it that never grows, read with one conditional request: each host is asked by one computer only, again once its share is older than 2 minutes while a CI runs or 10 otherwise (asked at setup), the pane opens at once, and a host one computer cannot reach (a company's Azure DevOps from home) is still shown from another. Azure DevOps (az login or a PAT) and GitHub (a token, gh, or anonymous for public repos). | Python 3.9+; the sync engine to share the list across computers |
Mods change Claude Code's own interface. They install as plugins like the other parts; install.sh loads its copies through CLAUDE_CODE_PLUGIN_DIRS. Run a mod's tests with claude plugin test mods/<name>.
| Mod | What it does |
|---|---|
| paste-preview | Shows pasted text in full in the prompt box and the transcript, and previews pasted images above the prompt and under the sent message (macOS, Windows). On Windows, paste an image with Alt+V: in some terminals (Ghostty) Ctrl+V pastes text only. |
| pr-pane | A Dev activity button at the top right of the band above the prompt, whose number counts only what needs you (a PR or a run in red, not acknowledged), colored by what you have to do (red and marked !: something needs you; yellow: · k to review or · k running; green: a PR is ready to merge; dim: everything waits for others) and /prs open a pane of the PRs pr-watch tracks, by priority. At the top, a collapsible "Pipeline runs" section lists your runs (a packaging or a deploy launched by hand, the CI of your pushes outside a PR, marked push to <branch>), one block per repo: the running ones first, then those ended in the last day, each with its pipeline, branch, status, time and duration, open by default while one runs; a run whose host did not answer keeps its last known state, marked cached. A run unfolds from its line: rerun (press twice: a new run of the same pipeline, branch and parameters on Azure DevOps, a re-run on GitHub), diagnose with Claude when it did not succeed (asks the session to read the steps and logs and propose the fix), then every step of the run grouped by job in pipeline order, each job folded unless a step had a problem, each step's messages and log lines under their own toggle. Then, under a red title and one open block per repo, the PRs that need you: a failed or expired CI, a merge conflict, changes requested, or a new comment since the last check (unfolding the PR marks its changes read: the button clears, the PR stays where it is until the session ends). Then the PRs waiting for your review, per repo too, each with review with Claude (a quick review by a subagent, nothing posted) and approve (press twice; it reads approving… while it runs). Then a collapsible "Waiting for others" section with your other open PRs, one collapsible block per repo in merge order (a stacked PR under the one it targets). Then "Issues I follow", per repo with unfollow all (press twice): each issue on one line (yellow when it moved since you last looked, with · n issues updated on the band), unfolding to who opened it, its labels and comments and what changed, which marks it read, with unfollow. A PR you park (its park button, under its details) leaves the red list and the band for a folded "Parked, kept but quiet" section, with unpark. Last, before the recent list, a collapsible "Approved, waiting for the merge" section holds the PRs you approved and your own PRs that only wait for the merge, grouped per repo the same way, each with a merge button (press twice; merging… while it runs; squash on GitHub when the repo allows it, complete on Azure DevOps). Every section and repo block wears the worst color of what it holds (red, then yellow, then green), so a folded one still says where to look. A red PR or run can be acknowledged (ack): it turns blue, leaves the count and the colors above it, and comes back when it changes; ack + remind asks Claude for a reminder and acks until its date, shown beside it. Every PR is one line, a colored dot (red: you have to act, yellow: someone or something else, green: only the merge is left), its number, title and what it waits for; its details fold under it: status, CI, votes, conflicts, the PR's description and the changes since the last check. A PR whose CI runs, and the repo block and section around it, open by default so a CI you just launched is on screen (a folded block hiding one says CI running); what you fold stays folded. Each PR's CI checks fold under it, open while they run or when a required one failed, refreshed every minute until they end; a failed check has details (its failed steps and error lines) and rerun (press twice: re-queue on Azure DevOps, rerun failed jobs on GitHub). A merge conflict is shown in red with a fix with Claude button that asks the session to rebase and resolve it (it asks you before pushing). PRs merged or closed in the last 7 days stay listed at the bottom. An error shared by several PRs and lists (a host this computer cannot reach or sign in to) is shown once, with what it hit. Click a PR to open it in the browser; refresh (or r) fetches them live and lists what changed since the last check, without marking it seen. Its settings, in the Configuration pane or claude plugin configure, turn each section on or off (open PRs, parked, merged and closed, review requests, issues), set how many pipeline runs to show per repo (0 hides them), how long an issue stays followed without moving, how often each part is refreshed by itself, and follow the kit's low power mode (see configuration); pr-watch follows them too, so what is off is no longer fetched or reported. Needs pr-watch. |
| reminders-handoffs | One pane for whichever of reminders and handoff you have, a tab each when you have both. A button at the right of the band above the prompt, named after them (Reminders 1 now · Handoffs 1, yellow when a reminder is due or a note from your other computer waits), /reminders-pane and /handoffs-pane open it. Reminders come in three foldable sections, Now, Upcoming (with when each shows next, repeating ones included) and Past; handoff notes in Open and Done. Several groups in a section (a reminder's group, else its folder, else its computer; a note's repo) each get a foldable title. Each item is one line that unfolds to its dates, repo, branch and text, with pick (hands the reminder or the note to this session now), done (done today on a repeating reminder), stop, cancel and delete (press twice), and restore on a past one (back as it was, dates and repeat days included). |
| recent-prompts | Shows your last two messages above the prompt, and a searchable history pane; click one to scroll the transcript to it. With the learn mod, the history also lists each 💡 lesson between the messages it answered. |
| dnd | Do not disturb for the recent-prompts, pr-pane and reminders-handoffs panes. A profile hides a pane (its band button too), or keeps only some repos, reminder groups or handoff repos, @here being the session's own repo; counts and colors follow what is kept. Turn one on by hand with /dnd work 1h or by asking Claude, for this session, this computer or all computers (asked when you don't say; the status line shows 🔕 work · session while one is on), or let a rule turn it on: a Wi-Fi network, days and hours (days=weekend, from=19:00 to=08:00), a folder (a repo shows only its own). /dnd, or its button in the Configuration pane, opens the Do not disturb pane: a press per profile asks until when and where, then Activate turns it on; a name creates one, and each profile unfolds to what it keeps (a checklist) and the rules that turn it on; dnd.sh edit <profile> is the same checklist on a terminal, with the installer's keys. Profiles live in the sync repo when there is one, so every computer gets them. Offered only beside one of those panes. |
| configuration | A Configuration button at the right of the band and /configuration open the Configuration pane: every mod's settings, grouped per mod (a toggle, a choice, or a number or text typed and saved with Enter), changed for all computers or, with a private sync, for this computer only; a setting kept for this computer says the value the other computers use. Its own setting is the kit's low power mode: on, off, or on battery (the default: while the computer runs on its battery or in its low power mode, read on macOS, Linux and Windows), everything that fetches by itself (the dev activity pane and pr-watch, the reminders and handoffs pane, do not disturb) does it five times less often, and
hooks/register.tsx 865 lines1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, PluginOptions, Register, SessionMessage } from 'claude-code'
3
4import type { Answer, AnswerKind, RecentPrompt } from '../types'
5
6const PANE = 'my-messages'
7const TITLE = 'My messages'
8const COMMAND = 'prompts'
9const BAND_COUNT = 2
10const KEPT = 1000
11const WAITING_KEPT = 20
12const ANSWERS_KEPT = 40
13const ANSWER_CHARS = 20_000
14const JUMP_ICON = '↗'
15// Under the pointer, what folds turns to the theme's suggestion color with the text drawn on it in
16// the theme's inverse text color: readable in a light and a dark theme alike.
17const LIT_BOX = { backgroundColor: 'suggestion' }
18const LIT_TEXT = { color: 'inverseText', dimColor: false }
19// At the end of a line that folds others: unfold everything under it, or fold it all back.
20const UNFOLD_ALL = '▾ all'
21const FOLD_ALL = '▴ all'
22
23// The hover group a fold-all control lights, named after its key.
24const foldScope = (key: string) => `fold:${key}`.replace(/[\x00-\x1f\x7f]/g, ' ').slice(0, 64)
25
26// The band's buttons share one row under everything above the prompt, whatever order the mods
27// draw in: each takes that row out of what the mods beneath drew, adds its own button, and sorts
28// them by key (band-1-history, band-2-prs, band-3-reminders).
29const BAND_ROW = 'band-buttons'
30
31type Drawn = { type?: string; props?: { key?: string }; children?: unknown[] }
32
33const keyOf = (node: unknown) => (node !== null && typeof node === 'object' ? ((node as Drawn).props?.key ?? '') : '')
34
35const byBandKey = (one: unknown, other: unknown) => keyOf(one).localeCompare(keyOf(other))
36
37const takeBandRow = (tree: unknown): { rest: unknown; buttons: unknown[] } => {
38 if (Array.isArray(tree)) {
39 let buttons: unknown[] = []
40 const rest = tree.map(child => {
41 if (buttons.length > 0) {
42 return child
43 }
44
45 const taken = takeBandRow(child)
46 buttons = taken.buttons
47
48 return taken.rest
49 })
50
51 // The engine reads every child of a drawn tree: the row taken out leaves no hole.
52 return { rest: rest.filter(child => child !== null && child !== undefined), buttons }
53 }
54
55 const node = tree as Drawn | null
56
57 if (node === null || typeof node !== 'object' || !Array.isArray(node.children)) {
58 return { rest: tree, buttons: [] }
59 }
60
61 if (node.props?.key === BAND_ROW) {
62 return { rest: null, buttons: node.children.flat(Infinity) }
63 }
64
65 const taken = takeBandRow(node.children)
66
67 return taken.buttons.length > 0 ? { rest: { ...node, children: taken.rest }, buttons: taken.buttons } : { rest: tree, buttons: [] }
68}
69
70const prompts = atom({ plugin: 'recent-prompts', key: 'prompts' } as const, [])
71const query = atom({ plugin: 'recent-prompts', key: 'query' } as const, '')
72const waiting = atom({ plugin: 'recent-prompts', key: 'waiting' } as const, [])
73const unfolded = atom({ plugin: 'recent-prompts', key: 'unfolded' } as const, {})
74// The do-not-disturb profile on now, when the dnd mod is installed: one can hide the history. Read
75// under dnd's shape: another one (an older or newer dnd) reads as nothing on.
76const dndActive = atom({ plugin: 'dnd', key: 'active' } as const, null, { shape: 'dnd-active/1' })
77
78const dndHiding = async ($: EngineInterface) => {
79 const on = await read($, dndActive)
80
81 return on?.profile && on.parts?.history?.mode === 'hide' ? on.profile : ''
82}
83
84type Block = { type: string; [field: string]: unknown }
85type Shown = { before: string; match: string; after: string }
86
87// A plugin's prompt is sent for the person: a button they pressed in a pane, such as a reminder's pick.
88const isPerson = (kind: string) => kind === 'composer' || kind === 'bridge' || kind === 'plugin'
89
90const flatten = (text: string) => text.replace(/\s+/g, ' ').trim()
91
92const textOf = (blocks: Block[]) => blocks.flatMap(block => (typeof block.text === 'string' ? [block.text] : [])).join('\n')
93
94const clockTime = (milliseconds: number) => {
95 const date = new Date(milliseconds)
96
97 return [date.getHours(), date.getMinutes()].map(part => String(part).padStart(2, '0')).join(':')
98}
99
100const remember = async ($: EngineInterface, id: string, text: string, kind?: RecentPrompt['kind']) => {
101 const prompt: RecentPrompt = { id, text, time: clockTime(await $.clock.now()), ...(kind ? { kind } : {}) }
102 await update($, prompts, list => [...list, prompt].slice(-KEPT))
103}
104
105// What follows the "💡 Learn:" heading Claude ends a reply with when the learn mod asks it to.
106const LEARN = /💡\s*\**\s*Learn\b\s*:?\**\s*([\s\S]+)$/
107
108const isMessage = (prompt: RecentPrompt) => prompt.kind !== 'learn'
109
110const answerTo = (list: RecentPrompt[], answer: Answer) => {
111 const at = list.map(isMessage).lastIndexOf(true)
112 const prompt = list[at]
113
114 if (prompt === undefined) {
115 return list
116 }
117
118 const answers = [...(prompt.answers ?? []), { ...answer, text: answer.text.slice(0, ANSWER_CHARS) }].slice(-ANSWERS_KEPT)
119
120 return [...list.slice(0, at), { ...prompt, answers }, ...list.slice(at + 1)]
121}
122
123// A reply goes under the person's last message: the replies of a turn all answer it.
124const keepAnswer = async ($: EngineInterface, id: string, text: string, kind?: AnswerKind) => {
125 const time = clockTime(await $.clock.now())
126 await update($, prompts, list => answerTo(list, { id, text, time, ...(kind ? { kind } : {}) }))
127}
128
129// Which replies besides plain text the person chose to keep (the manifest's userConfig).
130type Keep = { questions: boolean; plans: boolean; files: boolean; notifications: boolean; commands: boolean }
131
132const keepOf = (options: PluginOptions): Keep => ({
133 questions: options.questions !== false,
134 plans: options.plans !== false,
135 files: options.files === true,
136 notifications: options.notifications === true,
137 commands: options.commands !== false,
138})
139
140const stringOf = (value: unknown) => (typeof value === 'string' ? value : '')
141
142const listOf = (value: unknown): unknown[] => (Array.isArray(value) ? value : [])
143
144// A tool call that speaks to the person, as the reply it stands for; undefined for any other.
145const toolAnswer = (tool: string, input: Record<string, unknown>, keep: Keep): { kind: AnswerKind; text: string } | undefined => {
146 if (tool === 'AskUserQuestion' && keep.questions) {
147 const questions = listOf(input.questions).map(question => {
148 const asked = (question ?? {}) as Record<string, unknown>
149 const options = listOf(asked.options).map(option => ` · ${stringOf((option as Record<string, unknown>)?.label)}`)
150
151 return [stringOf(asked.question), ...options].join('\n')
152 })
153
154 return { kind: 'question', text: questions.join('\n\n') }
155 }
156
157 if (tool === 'ExitPlanMode' && keep.plans && stringOf(input.plan) !== '') {
158 return { kind: 'plan', text: stringOf(input.plan) }
159 }
160
161 if (tool === 'SendUserFile' && keep.files) {
162 return { kind: 'file', text: [stringOf(input.caption), ...listOf(input.files).map(stringOf)].filter(Boolean).join('\n') }
163 }
164
165 if (tool === 'PushNotification' && keep.notifications && stringOf(input.message) !== '') {
166 return { kind: 'notification', text: stringOf(input.message) }
167 }
168
169 return undefined
170}
171
172// The picker's result reads `The user answered: "question"="pick", ...`: each pick under its question.
173const pickText = (result: string) => {
174 const picks = [...result.matchAll(/"((?:[^"\\]|\\.)*)"="((?:[^"\\]|\\.)*)"/g)].map(([, question, pick]) => `${question}\n→ ${pick}`)
175
176 return picks.length > 0 ? picks.join('\n\n') : result.trim()
177}
178
179const resultText = (block: Block) =>
180 typeof block.content === 'string' ? block.content : textOf(listOf(block.content) as Block[])
181
182const PICK = '#pick'
183
184const ANSWER_WORDS: Record<AnswerKind, string> = {
185 question: 'asked',
186 pick: 'you picked',
187 plan: 'plan',
188 file: 'sent you',
189 notification: 'notified',
190 output: 'output',
191}
192
193const tagged = (text: string, tag: string) => text.match(new RegExp(`<${tag}>([\\s\\S]*?)</${tag}>`))?.[1]?.trim()
194
195// A slash command's record (`<command-name>/x</command-name>…<command-args>a</command-args>`) as typed: `/x a`.
196const commandLine = (text: string) => {
197 const name = tagged(text, 'command-name')
198
199 return name === undefined ? undefined : [name, tagged(text, 'command-args') ?? ''].join(' ').trim()
200}
201
202// What a command printed, its terminal colors taken out; "(no content)" is nothing.
203const commandOutput = (text: string) => {
204 const printed = [tagged(text, 'local-command-stdout'), tagged(text, 'local-command-stderr')]
205 .filter((part): part is string => part !== undefined)
206 .join('\n')
207 .replace(/\x1b\[[0-9;]*m/g, '')
208 .trim()
209
210 return printed === '(no content)' ? '' : printed
211}
212
213const REBUILT = 'rebuilt-'
214
215// What a transcript row of the person's side is, read back without the flags its row had: a
216// message, a command, a command's output, or engine framing to leave out.
217type ReadBack = { message: string; kind?: 'command' } | { output: string } | undefined
218
219const readUser = (text: string, keep: Keep): ReadBack => {
220 const trimmed = text.trim()
221 const command = commandLine(trimmed)
222
223 if (command !== undefined) {
224 return keep.commands ? { message: command, kind: 'command' } : undefined
225 }
226
227 if (/<local-command-(stdout|stderr)>/.test(trimmed)) {
228 const output = commandOutput(trimmed)
229
230 return keep.commands && output !== '' ? { output } : undefined
231 }
232
233 const queued = trimmed.match(/The user sent a new message while you were working:\n([\s\S]*?)\n\n(?:Address|IMPORTANT)/)?.[1]
234 const sent = trimmed.match(/^The \S+ plugin sent a message:\n([\s\S]*?)\n\nAddress the message above/)?.[1]
235
236 if (queued !== undefined || sent !== undefined) {
237 return { message: (queued ?? sent ?? '').trim() }
238 }
239
240 const isFraming =
241 trimmed === '' ||
242 /^<(system-reminder|task-notification|local-command-caveat|user-prompt-submit-hook)\b/.test(trimmed) ||
243 /^(Base directory for this skill:|This session is being continued from a previous conversation|\[Request interrupted)/.test(trimmed)
244
245 return isFraming ? undefined : { message: trimmed }
246}
247
248// The history as the transcript holds it, for a session whose stored history missed some of it:
249// one resumed, or one whose replies came before this mod kept them. The rows carry no ids, so
250// what comes from a plain row cannot be jumped to; a tool call's reply keeps its call's id.
251const readBack = (rows: SessionMessage[], keep: Keep) =>
252 rows.reduce<RecentPrompt[]>((list, row, index) => {
253 const id = `${REBUILT}${index}`
254
255 if (row.role === 'user') {
256 const found = readUser(row.text, keep)
257
258 if (found === undefined) {
259 return list
260 }
261
262 return 'output' in found
263 ? answerTo(list, { id, text: found.output, kind: 'output' })
264 : [...list, { id, text: found.message, ...(found.kind ? { kind: found.kind } : {}) }]
265 }
266
267 const text = row.text.trim()
268 const lesson = text.match(LEARN)?.[1]?.trim() ?? ''
269 const answered = text === '' ? list : answerTo(list, { id, text })
270 const withTools = row.toolUses.reduce((all, use) => {
271 const answer = toolAnswer(use.tool, use.input, keep)
272
273 if (answer === undefined) {
274 return all
275 }
276
277 const asked = answerTo(all, { id: use.tool_use_id, ...answer })
278
279 return use.tool === 'AskUserQuestion' && use.text !== undefined
280 ? answerTo(asked, { id: `${use.tool_use_id}${PICK}`, text: pickText(use.text), kind: 'pick' })
281 : asked
282 }, answered)
283
284 return lesson === '' ? withTools : [...withTools, { id: `${id}-learn`, text: lesson, kind: 'learn' }]
285 }, [])
286
287// Two replies are one when either's text holds the other's: the transcript may join a response's
288// text blocks the session stored one by one.
289const isSameAnswer = (one: Answer, other: Answer) => {
290 const [a, b] = [flatten(one.text), flatten(other.text)]
291
292 return a !== '' && b !== '' && (a.includes(b) || b.includes(a))
293}
294
295const mergeAnswers = (stored: Answer[], found: Answer[]) => {
296 const used = new Set<Answer>()
297 const merged = found.map(answer => {
298 const same = stored.find(one => !used.has(one) && isSameAnswer(one, answer))
299
300 if (same === undefined) {
301 return answer
302 }
303
304 used.add(same)
305
306 return same
307 })
308
309 return [...merged, ...stored.filter(one => !used.has(one))].slice(-ANSWERS_KEPT)
310}
311
312// What was read back joins what is stored: an empty history takes it whole; otherwise each stored
313// message, matched in order by its text, gains the replies it missed, and nothing stored is lost.
314const merge = (stored: RecentPrompt[], found: RecentPrompt[]) => {
315 if (!stored.some(isMessage)) {
316 return [...found, ...stored].slice(-KEPT)
317 }
318
319 let from = 0
320
321 return stored.map(prompt => {
322 if (!isMessage(prompt)) {
323 return prompt
324 }
325
326 const at = found.findIndex((one, index) => index >= from && isMessage(one) && flatten(one.text) === flatten(prompt.text))
327
328 if (at < 0) {
329 return prompt
330 }
331
332 from = at + 1
333 const answers = mergeAnswers(prompt.answers ?? [], found[at]?.answers ?? [])
334
335 return answers.length > 0 ? { ...prompt, answers } : prompt
336 })
337}
338
339const rebuild = async ($: EngineInterface, keep: Keep) => {
340 const found = readBack(await $.session.messages(), keep)
341
342 if (found.length > 0) {
343 await update($, prompts, list => merge(list, found))
344 }
345}
346
347// A line cut into lines of at most WIDTH columns, at a space when one is near the end.
348const wrap = (line: string, width: number): string[] => {
349 const lines: string[] = []
350 let rest = line
351 while (width > 0 && rest.length > width) {
352 const space = rest.lastIndexOf(' ', width)
353 const cut = space > width / 2 ? space : width
354 lines.push(rest.slice(0, cut).trimEnd())
355 rest = rest.slice(cut).trimStart()
356 }
357 return [...lines, rest]
358}
359
360// A text as the pane's lines: its own line breaks kept, runs of blank lines made one, long lines wrapped.
361const paragraphs = (text: string, width: number) =>
362 text
363 .split(/\r?\n/)
364 .map(line => line.replace(/[\x00-\x1f\x7f]/g, ' ').trimEnd())
365 .filter((line, index, all) => line !== '' || (index > 0 && all[index - 1] !== ''))
366 .flatMap(line => wrap(line, width))
367
368const withoutFirst = (list: string[], text: string) => {
369 const at = list.indexOf(text)
370
371 return at < 0 ? list : [...list.slice(0, at), ...list.slice(at + 1)]
372}
373
374// Folds one UTF-16 unit at a time so indexes in the folded text match the original.
375const fold = (text: string) =>
376 text
377 .split('')
378 .map(unit => unit.normalize('NFD').charAt(0).toLowerCase())
379 .join('')
380
381const truncate = (text: string, width: number) =>
382 text.length > width ? `${text.slice(0, Math.max(0, width - 1))}…` : text
383
384const shownLine = (text: string, search: string, width: number): Shown | null => {
385 const flat = flatten(text)
386 const needle = fold(search.trim())
387
388 if (needle === '') {
389 return { before: truncate(flat, width), match: '', after: '' }
390 }
391
392 const at = fold(flat).indexOf(needle)
393
394 if (at < 0) {
395 return null
396 }
397
398 const start = at + needle.length < width ? 0 : Math.min(at, Math.max(1, at - Math.floor((width - needle.length) / 3)))
399 const prefix = start > 0 ? '…' : ''
400 const room = width - prefix.length
401 const isCut = flat.length - start > room
402 const end = isCut ? start + room - 1 : flat.length
403 const matchEnd = Math.min(end, at + needle.length)
404
405 return {
406 before: prefix + flat.slice(start, at),
407 match: flat.slice(at, matchEnd),
408 after: flat.slice(matchEnd, end) + (isCut ? '…' : ''),
409 }
410}
411
412// Buttons holding styled Text draw from 2.1.306 on; an older build, or a version that cannot be
413// read, gets plain labels.
414const STYLED_SINCE = [2, 1, 306]
415
416let styledFound: boolean | undefined
417
418const isStyled = async ($: EngineInterface) => {
419 if (styledFound === undefined) {
420 try {
421 const parts = ((await $.session.version()).base ?? '').replace(/-.*$/, '').split('.').map(Number)
422 const at = parts.findIndex((part, index) => part !== STYLED_SINCE[index])
423
424 styledFound = parts.length === 3 && parts.every(Number.isInteger) && (at === -1 || (parts[at] ?? 0) > (STYLED_SINCE[at] ?? 0))
425 } catch {
426 styledFound = false
427 }
428 }
429
430 return styledFound
431}
432
433const jump = async ($: EngineInterface, id: string) => {
434 if (id.startsWith(REBUILT)) {
435 $.ui.toast("Can't jump to that message: it was read back from the transcript, which keeps no place for it.")
436
437 return
438 }
439
440 const { deny } = await $.ui.scroll({ to: { requestId: id.replace(PICK, '') }, block: 'start' })
441
442 if (deny !== undefined) {
443 $.ui.toast(`Can't jump to that message: ${deny}`)
444 }
445}
446
447const toggleHistory = async ($: EngineInterface) => {
448 const isOpen = (await $.ui.panes()).some(pane => pane.id === PANE)
449
450 if (isOpen) {
451 await $.ui.close({ id: PANE })
452
453 return 'closed'
454 }
455
456 await $.ui.open({ id: PANE, title: TITLE, focus: true, columns: 56 })
457 await $.ui.scroll({ in: PANE, to: 'end' })
458
459 return 'opened'
460}
461
462const registerCommand = ($: EngineInterface) =>
463 $.command.register({ name: COMMAND, description: 'Open or close the searchable list of your messages' }).catch(() => undefined)
464
465export const register: Register = (on, options) => {
466 const keep = keepOf(options)
467
468 // A start runs again on a resume and on each reload of this module: what the history missed
469 // meanwhile is read back from the transcript.
470 on('session.start', async ($, e, next) => {
471 styledFound = undefined
472 await registerCommand($)
473 $.clock.after(0, () => void rebuild($, keep).catch(() => undefined))
474
475 return next(e)
476 })
477
478 // A /clear starts a fresh session without a session.start: its history starts empty.
479 on('session.end', async ($, e, next) => {
480 const ended = await next(e)
481
482 if (e.reason === 'clear') {
483 $.clock.after(0, () => {
484 void update($, prompts, () => [])
485 void update($, waiting, () => [])
486 void update($, unfolded, () => ({}))
487 void registerCommand($)
488 })
489 }
490
491 return ended
492 })
493
494 on('command.run', { command: COMMAND }, async $ => ({ text: `My messages pane ${await toggleHistory($)}.` }))
495
496 // A message typed while a turn runs is stored later, wrapped in the engine's framing, as a queued_command
497 // attachment (through the delivery door when absorbed mid-turn); a plugin's prompt is stored wrapped
498 // too, even between turns. Its text is kept at submit so that row can be told apart and listed as sent.
499 on('prompt.submit', async ($, e, next) => {
500 if ((e.turnId !== undefined || e.origin.kind === 'plugin') && isPerson(e.origin.kind) && e.text.trim() !== '') {
501 await update($, waiting, list => [...list, e.text].slice(-WAITING_KEPT))
502 }
503
504 return next(e)
505 }).catch(($, e, next) => next(e))
506
507 on('session.append', { door: 'prompt' }, async ($, e, next) => {
508 const stored = await next(e)
509
510 if (!isPerson(e.origin.kind) || e.agentId !== undefined || stored.uuid === undefined) {
511 return stored
512 }
513
514 const blocks: Block[] = stored.message.content
515 const first = blocks.find(block => block.type === 'text')
516 const sent =
517 e.origin.kind === 'plugin' ? (await read($, waiting)).find(one => flatten(textOf(blocks)).includes(flatten(one))) : undefined
518 const text = sent ?? (typeof first?.text === 'string' ? first.text : '')
519 const command = commandLine(text)
520
521 if (command !== undefined) {
522 if (keep.commands) {
523 await remember($, stored.uuid, command, 'command')
524 }
525 } else if (text.trim() !== '') {
526 await update($, waiting, list => withoutFirst(list, text))
527 await remember($, stored.uuid, text)
528 }
529
530 return stored
531 }).catch(($, e, next) => next(e))
532
533 // A lesson is kept between the messages, where it was given, so the history can find it again.
534 on('session.append', { door: 'response' }, async ($, e, next) => {
535 const stored = await next(e)
536
537 if (stored.uuid === undefined || e.agentId !== undefined) {
538 return stored
539 }
540
541 // Only what Claude said to the person: the text, and the tool calls that speak to the person
542 // when kept; the other calls, their results and thinking are left out.
543 const blocks: Block[] = stored.message.content
544 const text = textOf(blocks.filter(block => block.type === 'text')).trim()
545
546 if (text !== '') {
547 await keepAnswer($, stored.uuid, text)
548 }
549
550 for (const block of blocks.filter(one => one.type === 'tool_use')) {
551 const answer = toolAnswer(stringOf(block.name), (block.input ?? {}) as Record<string, unknown>, keep)
552
553 if (answer !== undefined && typeof block.id === 'string') {
554 await keepAnswer($, block.id, answer.text, answer.kind)
555 }
556 }
557
558 const lesson = text.match(LEARN)?.[1]?.trim() ?? ''
559
560 if (lesson !== '') {
561 await remember($, stored.uuid, lesson, 'learn')
562 }
563
564 return stored
565 }).catch(($, e, next) => next(e))
566
567 on('session.append', { door: 'tool-result' }, async ($, e, next) => {
568 const stored = await next(e)
569
570 if (!keep.questions || stored.message === undefined || e.agentId !== undefined || e.origin.kind !== 'tool' || e.origin.tool !== 'AskUserQuestion') {
571 return stored
572 }
573
574 for (const block of (stored.message.content as Block[]).filter(one => one.type === 'tool_result')) {
575 const result = resultText(block)
576
577 if (typeof block.tool_use_id === 'string' && result.trim() !== '') {
578 await keepAnswer($, `${block.tool_use_id}${PICK}`, pickText(result), 'pick')
579 }
580 }
581
582 return stored
583 }).catch(($, e, next) => next(e))
584
585 // A slash command's record and what it printed: some are stored as notices, some as the person's rows.
586 for (const door of ['command', 'notice'] as const) {
587 on('session.append', { door }, async ($, e, next) => {
588 const stored = await next(e)
589
590 if (!keep.commands || stored.uuid === undefined || e.agentId !== undefined || stored.message.isMeta) {
591 return stored
592 }
593
594 const text = textOf(stored.message.content)
595 const command = commandLine(text)
596 const output = commandOutput(text)
597
598 if (command !== undefined) {
599 await remember($, stored.uuid, command, 'command')
600 } else if (output !== '') {
601 await keepAnswer($, stored.uuid, output, 'output')
602 }
603
604 return stored
605 }).catch(($, e, next) => next(e))
606 }
607
608 for (const door of ['attachment', 'delivery'] as const) {
609 on('session.append', { door }, async ($, e, next) => {
610 const stored = await next(e)
611
612 if (stored.uuid === undefined || stored.message.name !== 'queued_command' || e.agentId !== undefined) {
613 return stored
614 }
615
616 const shown = flatten(textOf(stored.message.content))
617 const typed = (await read($, waiting)).find(text => shown.includes(flatten(text)))
618
619 if (typed !== undefined) {
620 await update($, waiting, list => withoutFirst(list, typed))
621 await remember($, stored.uuid, typed)
622 }
623
624 return stored
625 }).catch(($, e, next) => next(e))
626 }
627
628 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
629 const beneath = await next(e)
630
631 if (e.props.hasSurvey || e.props.view.agentId !== undefined || (await dndHiding($)) !== '') {
632 return beneath
633 }
634
635 const recent = (await read($, prompts)).filter(prompt => isMessage(prompt) && prompt.kind !== 'command').slice(-BAND_COUNT)
636 const { Box, Button, Text } = $.ui.resolve(e)
637 const width = Math.max(10, e.props.bodyColumns - 4)
638
639 const { rest, buttons } = takeBandRow(beneath)
640 const mine = (
641 <Box key="band-1-history" flexDirection="row">
642 <Button key="history" label="history" dimColor onPress={() => void toggleHistory($)} />
643 </Box>
644 )
645
646 return (
647 <Box flexDirection="column">
648 {recent.map((prompt, index) => (
649 <Box key={`band-${index}`} flexDirection="row">
650 <Text color="cyan">❯ </Text>
651 <Button
652 key={`prompt-${index}`}
653 label={truncate(flatten(prompt.text), width)}
654 plain
655 dimColor
656 onPress={() => void jump($, prompt.id)}
657 />
658 </Box>
659 ))}
660 {rest as never}
661 <Box key={BAND_ROW} flexDirection="row" gap={2}>
662 {[...buttons, mine].sort(byBandKey) as never}
663 </Box>
664 </Box>
665 )
666 })
667
668 on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e, next) => {
669 if (e.surface !== 'terminal') {
670 return next(e)
671 }
672
673 const { Box, Button, Input, Text } = $.ui.resolve(e)
674 const hiding = await dndHiding($)
675
676 if (hiding !== '') {
677 return <Text dimColor>{`Hidden by the do-not-disturb profile ${hiding}.`}</Text>
678 }
679
680 const list = await read($, prompts)
681 const search = await read($, query)
682 const open = await read($, unfolded)
683 const toggle = (id: string) => void update($, unfolded, all => ({ ...all, [id]: !(all[id] ?? false) }))
684 const styled = await isStyled($)
685 // What folds lights up under the pointer, the jump arrow left out as it does something else.
686 // What a line leaves for its text: the jump arrow, the fold arrow and the time take 10 columns,
687 // the control that unfolds its replies six more, a lesson's 💡 three more.
688 const width = Math.max(10, e.props.bodyColumns - 12)
689 const rows = list.flatMap(prompt => {
690 const shown = shownLine(prompt.text, search, width - 6 - (isMessage(prompt) ? 0 : 3))
691
692 return shown === null ? [] : [{ prompt, shown }]
693 })
694 const setQuery = (value: string) => void update($, query, () => value)
695 const messages = list.filter(isMessage).length
696 const lessons = list.length - messages
697 const counted = `${messages} messages${lessons > 0 ? `, ${lessons} 💡` : ''}`
698 const summary = search.trim() === '' ? counted : `${rows.length} of ${list.length} match`
699
700 // A message's line and its replies fold together: a reply open folds them back, all folded
701 // unfolds them all. The button beside the count does it for every line listed, the lines too.
702 const foldsOf = (prompt: RecentPrompt) => [prompt.id, ...(prompt.answers ?? []).map(answer => answer.id)]
703 const isOpenId = (id: string) => open[id] ?? false
704 const setFolds = (ids: string[], isOpen: boolean) =>
705 void update($, unfolded, all => ({ ...all, ...Object.fromEntries(ids.map(id => [id, isOpen])) }))
706 const listed = rows.flatMap(({ prompt }) => foldsOf(prompt))
707 const isListOpen = rows.some(({ prompt }) => isOpenId(prompt.id))
708
709 // A bar down the left edge of a block, shown only while the pointer is on the control that would
710 // fold the block back; hidden, it is never under the pointer itself.
711 const closingBar = (controlKey: string) => (
712 <Box
713 position="absolute"
714 top={0}
715 bottom={0}
716 left={0}
717 width={1}
718 display="none"
719 backgroundColor="suggestion"
720 hover={{ scope: foldScope(controlKey), display: 'flex' }}
721 />
722 )
723
724 // Drawn in the accent color where the build styles a button's text, named in words for a reader.
725 // Under the pointer it lights the bar beside each block it would fold back (closingBar).
726 const foldAllControl = (key: string, isOpen: boolean, drawn: string, onPress: () => void) =>
727 styled ? (
728 <Button key={key} label={isOpen ? 'collapse all' : 'expand all'} hover={{ scope: foldScope(key) }} onPress={onPress}>
729 <Text color="suggestion">{drawn}</Text>
730 </Button>
731 ) : (
732 <Button key={key} label={drawn} hover={{ scope: foldScope(key) }} onPress={onPress} />
733 )
734
735 // A line's text folds and unfolds it, as its arrow does; a build that draws no styled button
736 // gets the plain label.
737 const foldText = (key: string, plainLabel: string, styledText: unknown, onPress: () => void, dimColor = false) =>
738 styled ? (
739 <Button key={key} plain hover={LIT_TEXT} onPress={onPress}>
740 <Text dimColor={dimColor} hover={LIT_TEXT}>
741 {styledText as never}
742 </Text>
743 </Button>
744 ) : (
745 <Button key={key} label={plainLabel} plain dimColor={dimColor} hover={LIT_TEXT} onPress={onPress} />
746 )
747
748 // An unfolded line: the full message (or lesson), then each reply, folded to its first line
749 // until opened.
750 const details = (prompt: RecentPrompt) => (
751 <Box key={`details-${prompt.id}`} flexDirection="column" paddingLeft={4}>
752 {paragraphs(prompt.text, width - 2).map((line, index) => (
753 <Text key={`text-${prompt.id}-${index}`} color={isMessage(prompt) ? 'cyan' : 'yellow'}>
754 {line || ' '}
755 </Text>
756 ))}
757 {isMessage(prompt) && (prompt.answers ?? []).length === 0 && <Text dimColor>No reply yet.</Text>}
758 {(prompt.answers ?? []).map(answer => {
759 const isAnswerOpen = open[answer.id] ?? false
760 const by = answer.kind === 'pick' ? 'You' : answer.kind === 'output' ? 'Output' : 'Claude'
761 const said = `${answer.kind === undefined ? '' : `${ANSWER_WORDS[answer.kind]}: `}${flatten(answer.text)}`
762 const label = `${answer.time ?? '--:--'} ${isAnswerOpen ? by : truncate(said, width - 6)}`
763
764 return (
765 <Box key={`answer-${answer.id}`} flexDirection="column">
766 <Box flexDirection="row">
767 <Button key={`answer-jump-${answer.id}`} label={JUMP_ICON} plain dimColor onPress={() => void jump($, answer.id)} />
768 <Text> </Text>
769 <Box key={`answer-line-${answer.id}`} flexDirection="row" hover={LIT_BOX}>
770 <Button key={`answer-toggle-${answer.id}`} label={isAnswerOpen ? '▾' : '▸'} plain hover={LIT_TEXT} onPress={() => toggle(answer.id)} />
771 <Text hover={LIT_TEXT}> </Text>
772 {foldText(`answer-text-${answer.id}`, label, label, () => toggle(answer.id), true)}
773 </Box>
774 </Box>
775 {isAnswerOpen && (
776 <Box flexDirection="column">
777 {paragraphs(answer.text, width - 6).map((line, index) => (
778 <Box key={`reply-${answer.id}-${index}`} paddingLeft={2}>
779 <Text>{line || ' '}</Text>
780 </Box>
781 ))}
782 {closingBar(`all-${prompt.id}`)}
783 </Box>
784 )}
785 </Box>
786 )
787 })}
788 {closingBar('fold-all')}
789 </Box>
790 )
791
792 return (
793 <Box flexDirection="column">
794 <Input
795 key="search"
796 label="Search "
797 placeholder="words from your messages"
798 value={search}
799 submitLabel="filter"
800 autoFocus
801 onInput={setQuery}
802 onSubmit={setQuery}
803 />
804 <Box flexDirection="row" justifyContent="space-between">
805 <Text dimColor>{summary}</Text>
806 {listed.length > 0 &&
807 foldAllControl('fold-all', isListOpen, isListOpen ? '▴ collapse all' : '▾ expand all', () => setFolds(listed, !isListOpen))}
808 </Box>
809 {rows.map(({ prompt, shown }) => {
810 const isOpen = open[prompt.id] ?? false
811 const isLesson = prompt.kind === 'learn'
812 const folds = foldsOf(prompt)
813 const hasOpenReply = isOpen && folds.slice(1).some(isOpenId)
814
815 return (
816 <Box key={`entry-${prompt.id}`} flexDirection="column">
817 <Box flexDirection="row" justifyContent="space-between">
818 <Box flexDirection="row">
819 <Button key={`row-${prompt.id}`} label={JUMP_ICON} plain dimColor onPress={() => void jump($, prompt.id)} />
820 <Text> </Text>
821 <Box key={`line-${prompt.id}`} flexDirection="row" hover={LIT_BOX}>
822 <Button key={`toggle-${prompt.id}`} label={isOpen ? '▾' : '▸'} plain hover={LIT_TEXT} onPress={() => toggle(prompt.id)} />
823 <Text dimColor hover={LIT_TEXT}>
824 {' '}
825 {prompt.time ?? '--:--'}{' '}
826 </Text>
827 {foldText(
828 `text-${prompt.id}`,
829 `${isLesson ? '💡 ' : ''}${shown.before}${shown.match}${shown.after}`,
830 [
831 isLesson && (
832 <Text color="yellow" hover={LIT_TEXT}>
833 💡{' '}
834 </Text>
835 ),
836 <Text color={isLesson ? 'yellow' : undefined} dimColor={isLesson} hover={LIT_TEXT}>
837 {shown.before}
838 </Text>,
839 shown.match !== '' && (
840 <Text color="yellow" bold hover={LIT_TEXT}>
841 {shown.match}
842 </Text>
843 ),
844 <Text color={isLesson ? 'yellow' : undefined} dimColor={isLesson} hover={LIT_TEXT}>
845 {shown.after}
846 </Text>,
847 ],
848 () => toggle(prompt.id)
849 )}
850 </Box>
851 </Box>
852 {folds.length > 1 &&
853 foldAllControl(`all-${prompt.id}`, hasOpenReply, hasOpenReply ? FOLD_ALL : UNFOLD_ALL, () =>
854 setFolds(hasOpenReply ? folds.slice(1) : folds, !hasOpenReply)
855 )}
856 </Box>
857 {isOpen && details(prompt)}
858 </Box>
859 )
860 })}
861 </Box>
862 )
863 })
864}
865types/index.d.ts 39 lines1/**
2 * What else than plain text a reply can be, each kept when its setting is on: a question asked
3 * with the picker, the person's pick, a plan, a file sent to the person, a push notification, a
4 * slash command's output.
5 */
6export type AnswerKind = 'question' | 'pick' | 'plan' | 'file' | 'notification' | 'output'
7
8/** One reply to the person: the text of a response, or one of the kinds above; never a tool call's work. */
9export type Answer = { id: string; text: string; time?: string; kind?: AnswerKind }
10
11/**
12 * `kind` `learn`: a "💡 Learn:" block Claude ended a reply with (the learn mod), listed after the message it answered.
13 * `kind` `command`: a slash command the person ran, listed as `/name args`.
14 * An id that starts with `rebuilt-` was read back from the transcript, which gives no row ids to jump to.
15 */
16export type RecentPrompt = { id: string; text: string; time?: string; kind?: 'learn' | 'command'; answers?: Answer[] }
17
18/** What the dnd mod has on, the part of it this pane reads: whether the history is hidden. */
19export type DndActive = {
20 profile: string
21 parts: Partial<Record<string, { mode?: 'show' | 'hide' | 'only' }>>
22}
23
24declare module 'claude-code' {
25 interface PluginState {
26 /** The dnd mod's, read only under its shape `dnd-active/1`: absent when it is not installed. */
27 dnd: {
28 active: Shaped<DndActive | null>
29 }
30 'recent-prompts': {
31 prompts: RecentPrompt[]
32 query: string
33 waiting: string[]
34 /** The messages and replies the person unfolded in the pane, by id. */
35 unfolded: Record<string, boolean>
36 }
37 }
38}
39