SLOPSHOPPER

coachline

A split-pane panel for Claude Code: this thread's prompts in colour-coded cards (your prompt, what can be improved, the enhanced prompt), analysed by Claude on…

panespinnerpromptprocesstimer
★ 2v0.18.0MITupdated 2026-10-22teransarathchandra/coachline
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · coachline
│ ┃ coachline ✕ › fix the failing auth test and add an audit log call │ ┃ coachline: pane.py gave a bad answer · run │ ┃ /coach doctor ⏺ Read(src/auth.ts) │ ⎿ Read 6 lines │ ⏺ Update(src/auth.ts) │ ⎿ Added 2 lines, removed 1 line │ ⏺ Bash(bun test) │ ⎿ 3 pass, 1 fail │ │ ● Done. refresh now rejects expired claims and logs an audit event. │ │ ✻ Worked for 42s · done 4:20 PM │ │ │ │ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Pane · coachline
coachline: pane.py gave a bad answer · run /coach doctor
README

<img src="docs/assets/banner.svg" alt="coachline: a side panel for Claude Code that coaches every prompt" width="100%">

<a href="https://github.com/teransarathchandra/coachline/releases"><img src="https://img.shields.io/badge/dynamic/json?url=https%3A%2F%2Fraw.githubusercontent.com%2Fteransarathchandra%2Fcoachline%2Fmain%2F.claude-plugin%2Fplugin.json&query=%24.version&label=version&color=d97757" alt="Version"></a> <a href="https://github.com/teransarathchandra/coachline/actions/workflows/ci.yml"><img src="https://github.com/teransarathchandra/coachline/actions/workflows/ci.yml/badge.svg" alt="CI"></a> <img src="https://img.shields.io/badge/python-%E2%89%A53.9-3776ab?logo=python&logoColor=white" alt="Python 3.9 or newer"> <img src="https://img.shields.io/badge/dependencies-none-2ea44f" alt="No dependencies"> <img src="https://img.shields.io/badge/API_key-not_needed-2ea44f" alt="No API key needed"> <a href="LICENSE"><img src="https://img.shields.io/badge/license-MIT-blue" alt="MIT license"></a>

coachline sits next to <b>Claude Code</b>, shows the prompts of your conversation, says how each one could be better<br> and hands you an enhanced version to copy. Claude does the analysis on <b>your own subscription</b>.

<a href="https://teransarathchandra.github.io/coachline/"><img src="https://img.shields.io/badge/Website-coachline-E8735A?style=for-the-badge" alt="The coachline website"></a> <a href="#install"><img src="https://img.shields.io/badge/Claude_Code-Install_plugin-D97757?style=for-the-badge&logo=claude&logoColor=white" alt="Install in Claude Code"></a> <a href="#install"><img src="https://img.shields.io/badge/macOS_·_Linux-Opens_by_itself-555555?style=for-the-badge&logo=apple&logoColor=white" alt="macOS and Linux: opens by itself"></a> <a href="#windows"><img src="https://img.shields.io/badge/Windows-Terminal_split-0078D4?style=for-the-badge" alt="Windows: Windows Terminal split"></a> <a href="#desktop"><img src="https://img.shields.io/badge/Claude_desktop_app-Opens_by_itself-555555?style=for-the-badge&logo=claude&logoColor=white" alt="Claude desktop app: opens by itself"></a> <a href="#editors"><img src="https://img.shields.io/badge/VS_Code_·_Cursor_·_Windsurf-Opens_by_itself-007ACC?style=for-the-badge" alt="VS Code, Cursor, Windsurf and Antigravity: opens by itself"></a>

<img src="docs/assets/screenshot.png" alt="Claude Code with the coachline panel beside it: the prompt, what to improve, including a skill to use, and the enhanced prompt, each in its own coloured card" width="100%">

How it works

1 · Install, and the panel opens beside Claude Code

Two commands in Claude Code, and coachline opens in a side panel right away. No restart, no API key.

<img src="docs/assets/install.gif" alt="In Claude Code, /plugin marketplace add and /plugin install coachline@coachline; the coachline panel opens on the right at once" width="100%">

2 · Type a prompt, see how to make it better

Work as usual. While Claude works on your prompt, the panel shows what to improve and an enhanced prompt, with [ASK: …] where only you know the answer. Use puts it in your prompt box; while you type, the line under the box says what your draft lacks, or that a prompt like it worked before. Those land in your Library.

<img src="docs/assets/prompt.gif" alt="A vague prompt is sent in Claude Code; while Claude works on it, the coachline panel shows tips and an enhanced prompt, and the view zooms in on them" width="100%">

3 · Starting something new? Get the skills, tools and references for it

For a new task, coachline names the skills and plugins you have that fit, then searches the web for tools, docs and reference sites, and checks each link before you see it.

<img src="docs/assets/newtask.gif" alt="Illustration: the prompt &quot;make the shoe site look more premium&quot; gets tips and the frontend-design skill, then two finds from the web, Radix Colors and Refactoring UI, each shown once its link is checked" width="100%">

<img src="docs/assets/browse.gif" alt="The panel's own frames: moving back through the thread shows each earlier prompt's card, then Enter opens the whole of it" width="100%">

i shows the habits and repeated requests Claude spotted in your history. s turns a repeated request into a skill.

<img src="docs/assets/patterns.gif" alt="The panel's own frames: i shows patterns from past chats, a request asked 6 times and a habit, then s installs the drafted skill" width="100%">

4 · Keep what works

  • Use puts the enhanced prompt in your prompt box with its [ASK: …] gaps in bold. You fill them and send; nothing is sent for you.

<img src="docs/assets/use.gif" alt="Illustration: with a draft in the box, Use first asks before replacing it, then puts the enhanced prompt in the box with its [ASK] gap in bold, and the gap is filled in; nothing is sent" width="100%">

  • A hint as you type: pause, and the line under the box shows how concrete your draft is (▰▰▱▱▱) and the one thing it lacks most.

<img src="docs/assets/hint.gif" alt="Illustration: typing &quot;fix it now please&quot; shows an empty meter and &quot;say what 'it' or 'this' is&quot; under the box; naming the file and when it is done fills the meter" width="100%">

  • Evidence: coachline notes when you stop a turn or say "no, I meant…", and shows how often vague prompts led to rework compared with concrete ones.
  • Library: a prompt that worked first time is kept. Type something like it later and you are told so; the Library puts it back in the box.

<img src="docs/assets/library.gif" alt="The panel's own frames: l opens the Library of three saved prompts, the second is chosen and c copies it" width="100%">

  • Hold, if you turn it on: a clearly vague prompt stops at Enter with what it lacks. Enter again sends it as is.

<img src="docs/assets/hold.gif" alt="Illustration: with hold on, Enter on &quot;clean this up properly&quot; is held with what it lacks and the text stays in the box; Enter again sends it" width="100%">

All of it is worked out on your machine. More on the website.

<sub>Install and the vague prompt are recorded in Claude Code. The GIFs marked as illustrations above show coachline's real messages; the panel's GIFs are its own frames, rendered from its code.</sub>

Install

You need Claude Code (signed in, claude works in your terminal) and Python 3.9+. In Claude Code:

/plugin marketplace add teransarathchandra/coachline
/plugin install coachline@coachline

coachline is active straight away.

<img src="docs/assets/desktop.png" alt="The coachline pane in the Claude desktop app, light and dark: your prompt, Improve with its tips, and the enhanced prompt with a Copy button, each in the app's own rounded card" width="70%">

/coach auto-open on

<img src="docs/assets/editor.png" alt="The coachline pane beside Claude Code in VS Code, light and dark themes: your prompt, Improve with its tips, and the enhanced prompt with a Copy button, in the editor's own cards and colours" width="70%">

Check your setup: /coach doctor checks Python, the claude CLI and your history; /coach setup shows your settings.

Keys

↑ ↓choose a promptccopy the enhanced prompt
Enterread it full widtheanalyse it now
ipatterns from past chatssinstall a drafted skill
lthe Library of saved promptsxforget one (in the Library)
mmouse on or offqquit

In the Claude Code pane, the desktop app and the editors, click its buttons ([ Copy ], [ Analyse ]); the keys are for the standalone panel (Windows and /coach watch). Every key, mark and /coach command: usage guide.

Private by design

  • 🔑 No API key. Claude runs through your own Claude Code login, and there's no telemetry.
  • 🧹 Redacted first. Emails, keys and tokens are removed and pasted text is never sent. List a project in ~/.claude/coach/llm-off.txt to keep it out entirely.
  • ✅ Checked on your machine. Counts are recomputed, skill names must exist, and every link must load before you see it.
  • 🔌 Off in one command. /coach panel-ai off keeps only the built-in local hints.

What is sent and when: privacy.

Documentation

Usage · Privacy and accuracy · Troubleshooting · Changelog

Contributing

Issues and pull requests are welcome: see CONTRIBUTING.md. Security reports go through SECURITY.md.

MIT © Teran Sarathchandra

Source 2 files
hooks/coachline.tsx 621 lines
1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register, RenderChildren } from 'claude-code'
3
4import type { PaneEntry, PaneLine, PaneState } from '../types'
5
6const PANE = 'coachline'
7const NO_PYTHON = 'coachline needs Python 3.9+ · run /coach doctor'
8const NO_CLIPBOARD = 'no clipboard here: select the text instead'
9
10const state = atom({ plugin: 'coachline', key: 'state' } as const, null as PaneState | null)
11const error = atom({ plugin: 'coachline', key: 'error' } as const, '')
12const sel = atom({ plugin: 'coachline', key: 'sel' } as const, -1)
13const full = atom({ plugin: 'coachline', key: 'full' } as const, false)
14const showPatterns = atom({ plugin: 'coachline', key: 'showPatterns' } as const, false)
15const showLibrary = atom({ plugin: 'coachline', key: 'showLibrary' } as const, false)
16const closed = atom({ plugin: 'coachline', key: 'closed' } as const, false)
17const msg = atom({ plugin: 'coachline', key: 'msg' } as const, '')
18// the hint under the prompt box: the draft it was worked out for, and the tail to draw while the box still holds that draft
19const hint = atom({ plugin: 'coachline', key: 'hint' } as const,
20  null as { draft: string; tail: string | null; hint: string | null; hold: boolean } | null)
21
22const DEBOUNCE_MS = 600   // a pause in typing, not every key: one pane.py --score per pause
23const HOLD_REARM_MS = 30000   // hold: the same prompt sent again within this goes through
24let held = { text: '', at: -Infinity }
25// the prompt hold just put back in the box, until the box next changes: Claude Code (2.1.308) hands a dropped prompt back to the
26// box too, joined to what hold put there, and the doubled text would then be held again at every Enter
27let back: string | null = null
28const twice = (box: string, text: string) => box.trim() !== text.trim() && box.replace(text, '').trim() === text.trim()
29const ARM_MS = 5000       // Use over a draft: the second press within this replaces it
30const ASK = /\[ASK:[^\]]*\]/g
31let armedAt = -Infinity
32
33// the brand accent (watch.py's TRUECOLOR): the terminal pane's name only; the desktop app and the editors keep their own theme
34const ACCENT = '#E8735A'
35// watch.py's colours (see CODE in scripts/watch.py): text by line kind, and each section's box and title by section
36const COLOR: Record<string, string> = {
37  prompt: 'whiteBright', blue: 'blueBright', bluedim: 'blueBright', enh: 'cyanBright', task: 'blueBright', meta: 'gray',
38  better: 'magentaBright', src: 'gray',
39}
40const SECTION_COLOR: Record<string, string> = {
41  prompt: 'whiteBright', improve: 'blueBright', enh: 'cyanBright', web: 'magentaBright', info: 'gray', bad: 'redBright',
42}
43// The desktop app and the editors (VS Code and its forks: Cursor, Windsurf, Antigravity, ...) draw in their own design systems,
44// where a theme key follows their light and dark themes and an ANSI name is a fixed colour on the desktop (whiteBright is white
45// on its light theme). There each section is the app's own card (a neutral rounded border), its small title in one accent, the
46// text in the app's text colour, the quiet rows in its secondary text. The editors know no `skill` key: their terminal magenta.
47const APP_SECTION: Record<string, Record<string, string>> = {
48  desktop: { prompt: 'text', improve: 'suggestion', enh: 'claude', web: 'skill', info: 'inactive', bad: 'error' },
49  vscode: { prompt: 'text', improve: 'suggestion', enh: 'claude', web: 'magenta', info: 'inactive', bad: 'error' },
50}
51// the surfaces that draw panes in a session they attach to after it started
52const APPS = ['desktop', 'vscode']
53const QUIET = new Set(['bluedim', 'meta', 'src'])
54
55// discover.item_lines: "1. better: Name (kind) · you use this - why"
56const FIND = /^(\d+\. )better: (.+?) \(([a-z]+)\)( · you use this)? - (.*)$/s
57
58type Section = { section: string; head: PaneLine | null; rows: PaneLine[] }
59
60// watch.py's boxed(): a section's title opens its box, and a blank line, a new title or another section closes it
61function sections(lines: PaneLine[]): Section[] {
62  const out: Section[] = []
63  let cur: Section | null = null
64  for (const l of lines) {
65    const [section, kind] = l
66    if (cur && (kind === 'blank' || section !== cur.section || kind === 'head')) cur = null
67    if (kind === 'blank') continue
68    if (!cur) {
69      cur = { section, head: kind === 'head' ? l : null, rows: [] }
70      out.push(cur)
71      if (kind === 'head') continue
72    }
73    cur.rows.push(l)
74  }
75  return out
76}
77
78// Background work can outlive the module (a reload, the session ending): nothing is left to report to then.
79const ignore = () => undefined
80
81type Run = { ok: true; out: string } | { ok: false; err: string }
82
83let active = false          // an interactive terminal session on macOS / Linux, or one the desktop app or an editor attached to; false
84                            // under `claude -p`, the SDK and in the Windows terminal, which has watch.py's panel instead
85let py: string[] | null = null
86let pyChecked = false         // asked once: on a Mac without developer tools, each `python3` call can raise the install dialog
87let inflight: Promise<PaneState | null> | null = null
88let again = false
89let width = 80
90let poll: { cancel: () => void } | null = null
91// after a prompt: the count of prompts that shows it, and until when to wait for it. An editor's session runs prompt.submit
92// before the prompt is in its transcript, where pane.py reads it
93let want = 0
94let wantUntil = 0
95
96// Windows often has neither python3 nor python, or has them as the Microsoft Store's stand-ins, which fail `--version`; the
97// launcher python.org installs there is `py -3`
98async function python($: EngineInterface): Promise<string[] | null> {
99  if (pyChecked) return py
100  pyChecked = true
101  for (const cmd of [['python3'], ['python'], ['py', '-3']]) {
102    try {
103      const r = await $.process.run([...cmd, '--version'], { timeoutMs: 5000 })
104      if (r.exitCode === 0) return (py = cmd)
105    } catch {
106      // not on PATH: try the next name
107    }
108  }
109  return null
110}
111
112async function run($: EngineInterface, args: string[], stdin?: string): Promise<Run> {
113  const p = await python($)
114  if (!p) return { ok: false, err: NO_PYTHON }
115  try {
116    // a draft to score waits 3 s at most: a hung Python must not hold the hint for long
117    const r = await $.process.run([...p, `${$.plugin.root}/scripts/pane.py`, ...args], stdin === undefined ? { timeoutMs: 20000 } : { timeoutMs: 3000, stdin })
118    if (r.exitCode !== 0) {
119      const last = r.stderr.trim().split('\n').pop() || `pane.py exited ${r.exitCode}`
120      return { ok: false, err: `coachline: ${last} · run /coach doctor` }
121    }
122    return { ok: true, out: r.stdout }
123  } catch (x) {
124    return { ok: false, err: `coachline: ${String(x)} · run /coach doctor` }
125  }
126}
127
128// One pane.py at a time: a refresh asked for while one runs is folded into a single rerun when it ends.
129async function refresh($: EngineInterface): Promise<PaneState | null> {
130  if (inflight) {
131    again = true
132    return inflight
133  }
134  inflight = (async () => {
135    let s: PaneState | null = null
136    do {
137      again = false
138      s = await refreshOnce($)
139    } while (again)
140    return s
141  })()
142  try {
143    return await inflight
144  } finally {
145    inflight = null
146  }
147}
148
149async function refreshOnce($: EngineInterface): Promise<PaneState | null> {
150  // --width 0: unwrapped. The pane may sit beside the conversation, narrower than the viewport's columns, so its Text wraps each line
151  const p = await folder($)
152  const r = await run($, ['--json', '--session', await $.session.id(), '--width', '0', ...(p ? ['--project', p] : [])])
153  let s: PaneState | null = null
154  if (r.ok) {
155    try {
156      s = JSON.parse(r.out) as PaneState
157    } catch {
158      await update($, error, () => 'coachline: pane.py gave a bad answer · run /coach doctor')
159      return null
160    }
161  } else {
162    await update($, error, () => r.err)       // the last good state stays
163    return null
164  }
165  await update($, error, () => '')
166  await update($, state, () => s)
167  // an analysis or this session's web research still to come: keep checking, since the turn may go on long after either lands
168  const waiting = s.entries.length < want && (await $.clock.now()) < wantUntil
169  const busy = s.entries.some(e => e.state === 'pending') || !!s.researching || waiting
170  if (busy && !poll) poll = $.clock.every(3000, () => void refresh($).catch(ignore))
171  if (!busy && poll) {
172    poll.cancel()
173    poll = null
174  }
175  return s
176}
177
178// Opens when the last answer says auto-open is on, or when there is no answer at all (no Python, pane.py failing): the pane then
179// shows why, and the person can close it.
180async function openIfWanted($: EngineInterface, s: PaneState | null): Promise<void> {
181  if (s ? s.auto_open : (await read($, state)) === null) await open($)
182}
183
184async function startUp($: EngineInterface): Promise<void> {
185  await openIfWanted($, await refresh($))
186}
187
188function wake($: EngineInterface): void {
189  if (active) return
190  active = true
191  void startUp($).catch(ignore)              // the first prompt never waits for pane.py
192}
193
194async function open($: EngineInterface): Promise<void> {
195  if (await read($, closed)) return
196  const panes = await $.ui.panes()
197  if (panes.some((p: { id: string; isPlaced: boolean }) => p.id === PANE && p.isPlaced)) return
198  await $.ui.open({ id: PANE, title: 'coachline' })
199}
200
201// The draft goes to pane.py on stdin only (never argv, never a file, never Claude), after DEBOUNCE_MS without a change. One score
202// runs at a time; an answer for a draft the box no longer holds is dropped.
203let waiting: { cancel: () => void } | null = null
204let planned = ''
205let scoring = false
206
207function schedule($: EngineInterface, draft: string) {
208  if (draft === planned) return
209  planned = draft
210  waiting?.cancel(); waiting = null
211  // the drawn line is reused until the hint changes: a tail for another draft must go now, not when the next score lands
212  void update($, hint, h => (h && h.draft === draft ? h : null)).catch(ignore)
213  if (!draft.trim()) return
214  waiting = $.clock.after(DEBOUNCE_MS, () => {
215    waiting = null
216    void score($, draft).catch(ignore)
217  })
218}
219
220// the session's folder: known from session.start, else (after a reload of this module) asked for
221async function folder($: EngineInterface): Promise<string> {
222  const now = await $.session.cwd().catch(() => '')      // asked each time: /cd or a worktree move changes it
223  if (now) project = now
224  return project
225}
226
227async function score($: EngineInterface, draft: string) {
228  if (scoring) return                     // the running score picks up the newest draft when it ends
229  scoring = true
230  try {
231    if ((await read($, state))?.hints === false) return
232    const p = await folder($)
233    const r = await run($, p ? ['--score', '--project', p] : ['--score'], draft)
234    if (!r.ok) return
235    const d = JSON.parse(r.out) as { meter: string | null; hint: string | null; words: number; hold?: boolean; match?: { id: string; text: string } | null }
236    if ((await $.prompt.read()).text !== draft) return
237    const tail = d.meter && d.words >= 3 ? `· ${d.meter}${d.hint ? `  ${d.hint}` : ''}${d.match ? '  ↻ similar prompt worked before' : ''}` : null
238    await update($, hint, () => ({ draft, tail, hint: d.words >= 3 ? d.hint : null, hold: !!d.hold }))
239  } finally {
240    scoring = false
241    if (planned !== draft && planned.trim() && !waiting) void score($, planned).catch(ignore)   // typed while this one ran
242  }
243}
244
245// The outcome loop: the last prompt YOU sent (not a plugin's, a schedule's or a peer's), reported when you interrupt its turn, and
246// with your next prompt so pane.py can tell a correction ("no, I meant…"). Texts go on stdin; pane.py keeps a redacted line, locally.
247const HUMAN = ['composer', 'sdk', 'bridge']
248let last: string | null = null
249// the main loop's running turn, and its prompt only when it is the one you sent: a schedule's or /compact's turn blames nothing
250let running: { turnId: string; text: string | null } | null = null
251let project = ''      // the session's folder: the library's project, and where a similar saved prompt is looked for
252let asked = false     // the last answer ended in a question: "no, just the parser" answers it, it corrects nothing
253
254// Use: a text into the prompt box, its [ASK] gaps in bold; never sent (Q7). A draft in the box is replaced only on a second press
255// within ARM_MS. Where the box does not take it, it is copied. Answers what to tell the person, and whether the text got anywhere.
256async function fillBox($: EngineInterface, text: string, surface: string): Promise<{ note: string; done: boolean }> {
257  const now = await $.clock.now()
258  if ((await $.prompt.read()).text.trim() && now - armedAt > ARM_MS) {
259    armedAt = now
260    return { note: 'your prompt box has a draft: press Use again to replace it', done: false }
261  }
262  armedAt = -Infinity
263  const decorations = [...text.matchAll(ASK)].map(m => ({ start: m.index ?? 0, end: (m.index ?? 0) + m[0].length, bold: true }))
264  const r = await $.prompt.fill({ text, mode: 'replace', decorations })
265  if (r.isFilled) return { note: text.includes('[ASK:') ? 'in your prompt box: fill the [ASK] parts, then send' : 'in your prompt box: send it when ready', done: true }
266  if (r.refusal === 'dialog') return { note: 'close the dialog first, then press Use', done: false }
267  // no box here (the desktop app, an editor), or a cause unknown: the clipboard never touches the box, so copy
268  const c = await $.ui.copy({ text, surface: surface as never })
269  const why = r.refusal === 'no_composer' ? 'no prompt box here' : 'the prompt box did not take it'
270  return c.isCopied ? { note: `copied instead: ${why}`, done: true } : { note: NO_CLIPBOARD, done: false }
271}
272
273export const register: Register = on => {
274  // The terminal's pane, but not the Windows terminal's, which has watch.py's panel. The desktop app and the editors' Claude Code
275  // extension run their session as an SDK host does (no surface, not interactive) and attach afterwards, after its first
276  // prompt: session.attach; at a reload they are already attached
277  on('session.start', async ($, e, next) => {
278    last = null; running = null; asked = false; held = { text: '', at: -Infinity }; back = null     // a new conversation (/clear, a resume)
279    project = e.cwd
280    const r = await next(e)
281    if ((e.isInteractive && (await $.env.get('OS')) !== 'Windows_NT') || (await $.session.surfaces()).some(x => APPS.includes(x))) wake($)
282    return r
283  })
284
285  on('session.attach', async ($, e, next) => {
286    const r = await next(e)
287    if (APPS.includes(e.surface)) wake($)
288    return r
289  })
290
291  on('prompt.submit', async ($, e, next) => {
292    // hold (opt-in): only on the hint already worked out for exactly this text, so Enter never waits on Python; and only when the
293    // text can go back in the box, so nothing is lost
294    const h = await read($, hint)
295    if (h?.hold && h.hint && h.draft === e.text && !e.command && !e.attachments?.length && (!e.origin || HUMAN.includes(e.origin.kind))) {
296      const now = await $.clock.now()
297      if (!(held.text === e.text && now - held.at < HOLD_REARM_MS) && (await $.prompt.fill({ text: e.text, mode: 'replace' })).isFilled) {
298        held = { text: e.text, at: now }; back = e.text
299        return { drop: `coachline held this: ${h.hint}. Press Enter again to send it as is` }
300      }
301    }
302    const r = await next(e)
303    if (r.drop === undefined && !e.command && (!e.origin || HUMAN.includes(e.origin.kind))) {
304      const prev = last
305      last = e.text
306      if (prev && !asked) void run($, ['--outcome', 'next'], JSON.stringify({ prev, text: e.text, project })).catch(ignore)
307      asked = false
308    }
309    if (!active) return r
310    await update($, sel, () => -1)             // follow the newest prompt
311    let s = await read($, state)
312    if (!s && inflight) s = await inflight     // the session start's first answer, if it is still coming
313    want = (s?.entries.length ?? 0) + 1
314    wantUntil = (await $.clock.now()) + 60000
315    await openIfWanted($, s)                   // from a prompt the person entered: placed at any width
316    void refresh($).catch(ignore)
317    return r
318  })
319
320  on('turn.start', async ($, e, next) => {
321    const r = await next(e)
322    if (!e.agentId) running = { turnId: e.turnId, text: e.text && e.text === last ? e.text : null }
323    return r
324  })
325
326  on('turn.complete', async ($, e, next) => {
327    const r = await next(e)
328    if (!e.agentId) {
329      const t = running?.turnId === e.turnId ? running.text : null
330      if (e.isAborted && t) void run($, ['--outcome', 'aborted'], t).catch(ignore)
331      if (!e.isAborted && t) void run($, ['--outcome', 'done'], JSON.stringify({ text: t, project })).catch(ignore)   // a library candidate
332      asked = !e.isAborted && e.answer.trim().endsWith('?')
333      running = null
334    }
335    if (active) await refresh($)
336    return r
337  })
338
339  on('ui.close', async ($, e, next) => {
340    if (e.id === PANE && e.origin.kind === 'person') await update($, closed, () => true)
341    return next(e)
342  })
343
344  on('prompt.edit', async ($, e, next) => {
345    back = null     // you typed: the box is yours again, whatever hold put back
346    const box = await next(e)
347    schedule($, box.text)
348    return box
349  })
350
351  on('prompt.change', async ($, e, next) => {
352    if (back !== null && e.text !== back) {
353      const text = back
354      back = null
355      // the engine's hand-back after hold's own fill: the held prompt once, as the second Enter sends it
356      if (twice(e.text, text)) void $.prompt.fill({ text, mode: 'replace' }).catch(ignore)
357    }
358    schedule($, e.text)
359    return next(e)
360  })
361
362  on('ui.render', { component: 'PromptHint' }, async ($, e, next) => {
363    if (!e.props.isDraft || e.props.isWorking) return next(e)
364    const { text } = await $.prompt.read()
365    schedule($, text)
366    const h = await read($, hint)
367    return h && h.draft === text && h.tail ? next({ ...e, props: { ...e.props, tail: h.tail } }) : next(e)
368  })
369
370  on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
371    const { Box, Button, Text } = $.ui.resolve(e)
372    // the desktop app or an editor: their own design system. An editor spaces in cells, not the desktop's step names, and pads no
373    // bordered Box by itself
374    const app = APPS.includes(e.surface)
375    const ed = e.surface === 'vscode'
376    const sp = (step: 'xs' | 'sm', cells: number) => (ed ? cells : step)
377    // an editor wraps a row Box by default: a bullet's dot would land on a line of its own
378    const nw = ed ? 'nowrap' : undefined
379    const accentOf = APP_SECTION[e.surface] ?? APP_SECTION.desktop!
380    // an app's body is narrower than its viewport, which counts the conversation beside it
381    width = (app ? e.props.bodyColumns : e.viewport?.columns) ?? width
382    const s = await read($, state)
383    const err = await read($, error)
384    const note = await read($, msg)
385    if (!s) return <Text dimColor>{err || 'coachline: loading…'}</Text>
386
387    const count = `${s.entries.length} prompt${s.entries.length === 1 ? '' : 's'}`
388    // an app names the pane in its own title bar: the row only says what it shows
389    const header = app ? (
390      <Box key="header" justifyContent="space-between" flexWrap={nw}>
391        <Text size="footnote" dimColor>This thread · {count}</Text>
392        <Text size="footnote" color={s.ai ? 'success' : 'inactive'}>{s.ai ? '● Claude on' : '○ Claude off'}</Text>
393      </Box>
394    ) : (
395      <Box key="header">
396        <Text bold color={ACCENT}>coachline</Text>
397        <Text bold> · this thread · {count}</Text>
398        <Text>{'  '}</Text>
399        <Text color={s.ai ? 'green' : 'gray'}>{s.ai ? '● Claude on' : '○ Claude off'}</Text>
400      </Box>
401    )
402    const footer = [
403      err ? <Text key="err" color={app ? 'error' : 'red'}>{err}</Text> : null,
404      note ? <Text key="msg" dimColor>{note}</Text> : null,
405      s.notice && !s.entries.length ? <Text key="notice" dimColor>{s.notice}</Text> : null,
406    ]
407    if (!s.entries.length) {
408      return (
409        <Box flexDirection="column" gap={app ? sp('sm', 0.5) : 0}>
410          {header}
411          <Text dimColor>Send a prompt: coachline coaches it here.</Text>
412          {footer}
413        </Box>
414      )
415    }
416
417    const at = await read($, sel)
418    const i = at < 0 || at >= s.entries.length ? s.entries.length - 1 : at
419    const cur: PaneEntry | undefined = s.entries[i]
420    if (!cur) return <Text dimColor>coachline: loading…</Text>
421    const isFull = await read($, full)
422    const isLibrary = await read($, showLibrary)
423    const saved = s.library ?? []
424    const pats = await read($, showPatterns)
425
426    const copy = async () => {
427      const r = await $.ui.copy({ text: cur.after, surface: e.surface })
428      await update($, msg, () => (r.isCopied ? `copied the enhanced prompt (${cur.after.length} characters)` : NO_CLIPBOARD))
429    }
430    // the enhanced prompt into the prompt box, its [ASK] gaps in bold; never sent: you fill the gaps and press Enter (Q7)
431    const use = async () => {
432      const r = await fillBox($, cur.after, e.surface)
433      await update($, msg, () => r.note)
434    }
435    const useSaved = async (id: string, text: string) => {
436      const r = await fillBox($, text, e.surface)
437      await update($, msg, () => r.note)
438      if (r.done) void run($, ['--library', 'used', id]).then(() => refresh($)).catch(ignore)
439    }
440    const forgetSaved = async (id: string) => {
441      const r = await run($, ['--library', 'forget', id])
442      await update($, msg, () => (r.ok ? 'forgotten: it will not be offered again' : r.err))
443      await refresh($)
444    }
445    const analyse = async () => {
446      const r = await run($, s.session ? ['--enhance', cur.key, '--session', s.session] : ['--enhance', cur.key])
447      await update($, msg, () => (r.ok ? r.out.trim() : r.err))
448      await refresh($)
449    }
450    const mark = async (status: 'dismissed' | 'adopted', id: string) => {
451      const r = await run($, ['--mark', status, id])
452      await update($, msg, () => (r.ok ? r.out.trim() : r.err))
453      await refresh($)
454    }
455    const research = async () => {
456      const r = await run($, s.session ? ['--research', cur.key, '--session', s.session] : ['--research', cur.key])
457      await update($, msg, () => (r.ok ? r.out.trim() : r.err))
458    }
459    const install = async () => {
460      if (!s.skill) return
461      const r = await run($, ['--install', s.skill])
462      await update($, msg, () => (r.ok ? r.out.trim() : r.err))
463    }
464
465    const line = (l: PaneLine, n: number) => {
466      const [section, kind, text, , action] = l
467      const accent = accentOf[section]
468      if (kind === 'itemacts' && action?.startsWith('item:')) {
469        const id = action.slice('item:'.length)
470        return (
471          <Box key={`l${n}`} paddingLeft={3} marginTop={app ? sp('xs', 0.25) : 0} flexWrap={nw}>
472            <Button key={`hide:${id}`} label="Hide" onPress={() => mark('dismissed', id)} />
473            {!app && <Text>{'  '}</Text>}
474            <Button key={`use:${id}`} label="I use this" onPress={() => mark('adopted', id)} />
475          </Box>
476        )
477      }
478      if (action === 'enter') return <Button key="whole" label="Show the whole prompt" onPress={() => update($, full, () => true)} />
479      const find = kind === 'better' ? FIND.exec(text) : null
480      if (find) {
481        const [, num, name, type, used, why] = find
482        return (
483          // a web find: its name and kind, then why, the source and the buttons beneath, each item apart from the one before
484          <Box key={`l${n}`} marginTop={n % 1000 ? 1 : 0} alignItems={app ? 'flex-start' : undefined} flexWrap={nw}>
485            <Text color={app ? accent : COLOR.better}>{num}</Text>
486            <Box flexDirection="column">
487              <Box flexWrap={nw}>
488                {app ? <Text weight="semibold" bold>{name}</Text> : <Text bold color={COLOR.better}>{name}</Text>}
489                <Text dimColor size={app ? 'footnote' : undefined}>{`  ${type}${used ?? ''}`}</Text>
490              </Box>
491              <Text>{why}</Text>
492            </Box>
493          </Box>
494        )
495      }
496      if (kind === 'src') {
497        return (
498          <Box key={`l${n}`} paddingLeft={3} flexWrap={nw}>
499            <Text dimColor size={app ? 'footnote' : undefined}>{text.trim()}</Text>
500          </Box>
501        )
502      }
503      const dot = /^[•-] /.exec(text)?.[0]
504      if (app) {
505        // the app's text; a bullet's dot in the section's accent, on its first line, its wrapped lines under its text
506        if (dot) {
507          return (
508            <Box key={`l${n}`} alignItems="flex-start" flexWrap={nw}>
509              <Text color={accent}>{dot}</Text>
510              <Text dimColor={QUIET.has(kind)}>{text.slice(dot.length)}</Text>
511            </Box>
512          )
513        }
514        // an empty Text has no height in an app: a blank line of the enhanced prompt keeps its row
515        return <Text key={`l${n}`} dimColor={QUIET.has(kind)} weight={kind === 'task' ? 'medium' : undefined}>{text || ' '}</Text>
516      }
517      if (dot) {
518        return (
519          // a bullet's wrapped lines start under its text, as watch.py's bullet() wraps them
520          <Box key={`l${n}`}>
521            <Text color={COLOR[kind]} dimColor={kind === 'bluedim'}>{dot}</Text>
522            <Text color={COLOR[kind]} dimColor={kind === 'bluedim'}>{text.slice(dot.length)}</Text>
523          </Box>
524        )
525      }
526      return <Text key={`l${n}`} color={COLOR[kind]} dimColor={QUIET.has(kind)} bold={kind === 'prompt'}>{text}</Text>
527    }
528
529    // as on watch.py's panel: each section a rounded box in its colour. The title opens it (an element set on the border is not
530    // drawn), its label or Copy button right after, never against the pane's right edge, where the pane's own close mark is.
531    // In an app: its own card, which the desktop pads itself and an editor in cells; your prompt on the surface of your own
532    // messages, its title row spread across the card, the close mark being in the app's title bar
533    const box = (sec: Section, n: number, body: RenderChildren[]) => {
534      const [, , title, right, action] = sec.head ?? []
535      // in an app a note with no title (the first-run notice) is plain text, not a card
536      if (!sec.section || (app && sec.section === 'info' && !title)) return <Box key={`s${n}`} flexDirection="column">{body}</Box>
537      const copyButton = (
538        <Box key="acts" gap={1} flexWrap={nw}>
539          <Button key="use" label="Use" onPress={use} />
540          <Button key="copy" label="Copy" variant={app ? 'primary' : undefined} onPress={copy} />
541        </Box>
542      )
543      if (app) {
544        const color = accentOf[sec.section] ?? 'inactive'
545        return (
546          <Box key={`s${n}`} flexDirection="column" borderStyle="round" gap={sp('xs', 0.25)}
547            paddingX={ed ? 1 : undefined} paddingY={ed ? 0.5 : undefined}
548            backgroundColor={sec.section === 'prompt' ? 'userMessageBackground' : undefined}>
549            {title && (
550              <Box justifyContent="space-between" alignItems="center" gap={sp('sm', 1)} flexWrap={nw}>
551                <Text size="footnote" weight="semibold" bold color={color}>{title}</Text>
552                {action === 'copy' ? copyButton : right ? <Text size="footnote" dimColor>{right}</Text> : null}
553              </Box>
554            )}
555            {body}
556          </Box>
557        )
558      }
559      const color = SECTION_COLOR[sec.section] ?? 'gray'
560      return (
561        <Box key={`s${n}`} flexDirection="column" borderStyle="round" borderColor={color} paddingX={1}>
562          {title && (
563            <Box>
564              <Text bold color={color}>{title}</Text>
565              <Text>{'  '}</Text>
566              {action === 'copy' ? copyButton : right ? <Text dimColor>{right}</Text> : null}
567            </Box>
568          )}
569          {body}
570        </Box>
571      )
572    }
573
574    const library = [box({ section: 'enh', head: ['enh', 'head', 'Library', `${saved.length} saved in this project`, null], rows: [] }, 0,
575      saved.length
576        ? saved.flatMap(x => [
577            <Text key={`lt${x.id}`} color={app ? undefined : COLOR.enh}>{x.text}</Text>,
578            <Box key={`lb${x.id}`} gap={1} flexWrap={nw}>
579              <Button key={`libuse:${x.id}`} label="Use" onPress={() => useSaved(x.id, x.text)} />
580              <Button key={`libforget:${x.id}`} label="Forget" onPress={() => forgetSaved(x.id)} />
581            </Box>,
582          ])
583        : [<Text key="libempty" dimColor>Prompts that worked first time land here: none yet in this project.</Text>])]
584    const card = isLibrary ? library : isFull
585      ? [box({ section: 'prompt', head: ['prompt', 'head', 'Your prompt', '', null], rows: [] }, 0, [
586          <Text key="fulltext" color={app ? undefined : 'whiteBright'}>{cur.text}</Text>,
587          <Button key="less" label="Show less" onPress={() => update($, full, () => false)} />,
588        ])]
589      : sections(cur.lines).map((sec, n) => box(sec, n, sec.rows.map((l, k) => line(l, n * 1000 + k))))
590    // watch.py's card names keys ("press e"); here one Analyse button stands for them, whatever the prompt's state
591    const canAnalyse = !cur.after && cur.state !== 'off' && !isLibrary
592
593    return (
594      <Box flexDirection="column" gap={app ? sp('sm', 0.5) : 0}>
595        {header}
596        <Box flexDirection="column" marginY={app ? 0 : 1} gap={app ? sp('sm', 0.5) : 1}>{card}</Box>
597        {canAnalyse && <Button key="analyse" label={cur.state === 'pending' ? 'Analyse again' : 'Analyse'}
598          variant={app ? 'primary' : undefined} onPress={analyse} />}
599        {s.research && !!cur.after && cur.state !== 'off' && !isLibrary && <Button key="research" label="Look again on the web" onPress={research} />}
600        <Button key="library" label={isLibrary ? 'Back to the prompt' : `Library (${saved.length})`} onPress={() => update($, showLibrary, v => !v)} />
601        {s.patterns.length > 0 && (
602          <Box flexDirection="column" gap={app ? sp('xs', 0.25) : 0}>
603            <Button key="patterns" label={pats ? 'Hide patterns' : `${s.patterns.length} pattern${s.patterns.length === 1 ? '' : 's'} from your past chats`}
604              onPress={() => update($, showPatterns, v => !v)} />
605            {pats && s.patterns.map((p, n) => <Text key={`p${n}`} color={app ? undefined : 'blueBright'}>{p}</Text>)}
606            {s.skill && <Button key="skill" label={`Install the drafted skill /${s.skill}`} onPress={install} />}
607          </Box>
608        )}
609        <Box flexDirection="column" gap={app ? sp('xs', 0.25) : 0}>
610          {app ? <Text size="footnote" weight="semibold" dimColor>Prompts in this thread</Text> : <Text dimColor>Prompts in this thread</Text>}
611          {s.entries.map((x, n) => (
612            <Button key={`e${n}`} label={`${n === i ? '›' : ' '} ${x.glyph} ${x.stamp}  ${x.text.replace(/\s+/g, ' ').slice(0, Math.max(10, width - (app ? 0 : 16)))}`}
613              dimColor={app && n !== i ? true : undefined} onPress={() => update($, sel, () => n)} />
614          ))}
615        </Box>
616        {footer}
617      </Box>
618    )
619  })
620}
621
types/index.d.ts 43 lines
1export type PaneLine = [section: string, kind: string, text: string, right: string, action: string | null]
2
3export type PaneEntry = {
4  key: string
5  stamp: string
6  glyph: string
7  state: string
8  words: string
9  text: string
10  after: string
11  lines: PaneLine[]
12}
13
14export type PaneState = {
15  ai: boolean
16  research: boolean
17  researching: boolean
18  auto_open: boolean
19  session: string | null
20  entries: PaneEntry[]
21  patterns: string[]
22  skill: string | null
23  notice: string | null
24  hints?: boolean
25  library?: { id: string; text: string; uses: number }[]
26}
27
28declare module 'claude-code' {
29  interface PluginState {
30    coachline: {
31      state: PaneState | null
32      error: string
33      sel: number
34      full: boolean
35      showPatterns: boolean
36      showLibrary: boolean
37      closed: boolean
38      msg: string
39      hint: { draft: string; tail: string | null; hint: string | null; hold: boolean } | null
40    }
41  }
42}
43