Quiet English feedback on every prompt you type: a small model reviews it in the background and the fixes appear directly under your message. Recurring…

Quiet English feedback on every prompt you type, for non-native speakers who use Claude Code daily. A small model (Haiku) reviews each prompt in a separate background call, and the fixes appear directly under your message. Nothing is added to the main conversation's context.
/plugin marketplace add assert-not-singularity/english-coach
/plugin install english-coach@english-coach
/english-coach:setup
/english-coach:setup asks for your native language so the coach can spot transfer errors (false friends, calques, prepositions). Nothing is assumed: until you set it, the coach gives generic feedback and shows a one-time reminder. Settings live in ~/.config/english-coach/config.json; from a terminal, python3 <plugin-dir>/scripts/english-coach.py setup does the same interactively.
Transfer_Of_Ownership, retry_on_timeout, a place name), even when you read them aloud as ordinary words or they were misheard. They are never reported as errors. Only matching terms are sent, never the chat. Separately, wording you repeat from the assistant's last replies is dropped after the review as a quotation.~ to skip analysis entirely.20m ago, 3 hours ago, 14:32 or Yesterday at 3 PM) is not reviewed at all, so other people's wording never reaches your tips or statistics. Your own text in the same message is skipped with it; start with ~ or leave out the paste if you want it reviewed.[dictated]), set it with config set dictation_marker "[dictated]" or in /english-coach:setup. A message containing the marker, anywhere and in any case, is reviewed in speech mode: likely mis-transcriptions (homophones such as their/there/they're, weather/whether, now/no), missing punctuation, filler words, run-ons and spoken restarts, topic-first questions ("The retry logic, do we keep it?") and asides dropped into a clause ("have not been, in quotation marks, realized") are ignored, and only the grammar and word choice you produced is judged. The marker is removed before Claude reads your message (config set strip_marker off keeps it). Dictated messages are counted apart from typed ones: the main report covers written text only, followed by a short dictated section. The coach only sees the transcript, so pronunciation and fluency are out of its reach.recent and as one line in the report, but not drawn under your message and not counted as errors. If the same omission happens again, it becomes an error with the usual reminder, because a repeated omission points to a gap. A missing preposition or article in typed text always stays an error. In dictated text, a word you added or swapped for one that does not sound alike ("should have been looked", "wondering that") is your own wording, so it is a normal error.show_style. Register, formality, politeness and rare words are not flagged at all.escalate_model, default sonnet; none turns it off) and only that answer is stored. Typed messages and clear dictated ones never trigger it. This is experimental: the small model flags only some garbled passages as unclear.data/false_friends.json, currently German). It is a hint, never a rule: the reviewer decides in context, so correct uses are left alone. To add a language or entries, follow the format of the file./english-coach-overview opens a pane beside the transcript with buttons to switch between written, spoken and both. Its headline is length-independent: errors per 100 words and the share of sentences without an error (the share of clean messages falls with length simply because long messages offer more places for a slip, so it is listed apart, by length bucket). Below: "What to work on", one bar per category (errors of the last 8 weeks, most frequent first) with a one-line pattern, and per category a details button (two more sentences) and an examples button (the changed words), the watchlist as cards, and collapsible sections for slips and "native polish". Weekly trend strips appear once there are two weeks of data. Press r to refresh. The numbers come from english-coach.py overview <mode> as JSON.summary_model, default sonnet; opus takes about as long) receives your corrections grouped by category (your own short fragments, their fixes and explanations, the same ones the reviews already sent) and writes, per category, a headline with the general pattern, a short detail, and a "what to work on" list. The three views are written in parallel (about 15 to 30 seconds), the answer is stored locally, and the pane shows the last report while a new one is prepared. It is prepared automatically in the background, a minute after a session starts and then daily, and when you open the overview and none exists. It needs 10 or more errors in a view, and later summary_every (10) new ones since the last report; at most every six hours (ten minutes after opening the pane); config set auto_summary off stops that. The button "✦ Summarize patterns" (p) writes it on demand.english-coach.py backfill (--dry-run first). It reads your own Claude Code session logs on your machine, matches each message by time and word count, and writes back numbers only; no text is stored or printed.data/phrases.json, about 50, the same for every native language). How often one appears depends on fitting occasions, never the calendar: a phrase is shown on its first fitting occasion, then after 1, 3, 7 and 7 further fitting occasions have passed, and it retires after five showings or once you used it twice yourself. At least four messages lie between two suggestions, and a message with a correction on the same words gets none. phrases lists them and phrases ignore <id|last> stops one for good.config set audit flagged has a larger model (audit_model, default sonnet) recheck every reviewed message that got a tip, in the background and without delaying anything. It sees the whole message and the assistant's recent text, which the small reviewer only partly used, and rates each tip: right, not an error (taste, register, a quote, a mishearing), style, wrong fix, or wrong category. config set audit all also checks clean messages and notes errors the reviewer missed. Only the verdicts are stored, never the message. The overview shows how often the second opinion agrees and lists the tips it doubts, each with buttons to dismiss it or keep it; nothing is changed or hidden automatically. audit in the coach command lists the same. With it on, the full message goes to a second, larger model, so it costs about 600 more tokens per reviewed message, and it is meant for people who want to keep the statistics clean or help tune the prompt./english-coach:forget deletes the latest tip without a trace. Unlike dismiss, the phrase can be flagged again later.defer → derive) gets an extra "keeps coming back" line from the second time on (remind_after). When you then use the right word correctly several times in a row (resolve_after, default 5), it leaves the watchlist; a relapse puts it back. Active entries are also shown to the reviewer. Add your own with watch add <wrong> <right> [note].dismiss marks a tip with a reason; it stays in the database but leaves all statistics, and the same phrase is never flagged again. undismiss takes it back./english-coach:setup # native language, minimum words, tips per message
/english-coach:coach report # weekly sparkline per category, share of clean messages, habit phrases,
# and (if a native language is set) slips that copy its patterns
/english-coach-overview # an interactive pane: written, spoken or both, with trends and examples
/english-coach:coach recent # the latest tips with ids
/english-coach:coach dismiss 12 asr # tip 12 was not my mistake (asr, false, quote or taste)
/english-coach:coach dismiss last # ... every tip of the last message
/english-coach:coach undismiss 12 # take it back
/english-coach:forget # delete the latest tip without a trace (also: message, or an id)
/english-coach:coach config # show the settings; config set <key> <value> changes one (audit, show_style, ...)
/english-coach:coach audit # second opinions on the tips; audit ack <id> keeps a doubted tip
/english-coach:coach phrases # native phrases suggested so far; ignore <id|last> / unignore <id>
/english-coach:coach watch # mistakes that keep coming back; add <wrong> <right> [note] / remove <wrong>
/english-coach:coach off # pause
/english-coach:coach on # resume
Settings (config set <key> <value>): native_language, dictation_marker (none by default), strip_marker (on), min_words (default 6), max_tips (default 2), icon_written (✎) and icon_dictated (🎙︎): the icon in front of each fix, remind_after (2) and resolve_after (5) for the watchlist, audit (off, flagged or all) and audit_model (sonnet), escalate_model (sonnet), summary_model (sonnet) and show_style (off): draw style items under your message, in a quieter style labelled "not an error". Both defaults are text-style symbols, so the pair looks alike and follows the text color; set your own if you prefer, for example Nerd Font icons with config set icon_written $'\uf040' and config set icon_dictated $'\uf130'.
Prompts are sent to Claude (Haiku) through your own Claude Code session, the same destination as the prompt itself. With audit on, each reviewed message is also sent to the larger audit model, the same way. Locally, only the corrected fragments, explanations, word and sentence counts, and whether a message was typed or dictated are stored, never whole prompts, in ~/.local/share/english-coach/log.db (override with ENGLISH_COACH_DIR).
python3 on the PATH.claude plugin validate . # manifests and the mod
claude plugin test . # the mod's tests (mocked engine)
python3 -m unittest discover -s tests -p "test_*.py" # the backend: guards, storage, dismiss (no model calls)
python3 tests/eval.py # prompt regression eval: the real review pipeline on fixture
# messages, several runs each, pass rate per case
python3 tests/eval.py --model sonnet # the same cases with another model (--no-escalation: no second review)
python3 tests/eval.py --script new=scripts/english-coach.py --script old=/path/to/old.py
# compare a candidate against another version
The eval calls Haiku through the claude CLI against throwaway data, never your real database. Run it before changing the prompt or the validation: the model's output is probabilistic, so it reports rates, and cases marked informational (known weak spots) do not fail the run.
This plugin adapts ideas from claude-language-coach by Sergio Alves Junior (MIT): reviewing each prompt out of band with a small model, drawing the fixes under the prompt through a ui.render hook on the message row, calibrating the reviewer with an explicit "do not flag" list, treating errors that copy the user's native language as their own kind, explanations that teach a reusable pattern, and discarding any fix whose original text does not occur verbatim in the prompt. The code here is an independent implementation.
hooks/register.tsx 253 lines1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register } from 'claude-code'
3
4import type { Fix, Review } from '../types'
5import { COMMAND, registerOverview } from './overview'
6
7const MODEL = 'haiku'
8const KEEP = 50
9const CONTEXT_CHARS = 8_000 // how much of the assistant's recent text the quote guard may compare against
10const OWN_WORDS = new Set(['composer', 'bridge'])
11
12const reviews = atom({ plugin: 'english-coach', key: 'reviews' } as const, {} as Record<string, Review>)
13
14const textKey = (text: string) => {
15 let hash = 0x811c9dc5
16 for (const char of text.trim().replace(/\s+/g, ' ')) {
17 hash = Math.imul(hash ^ char.codePointAt(0)!, 0x01000193)
18 }
19
20 return (hash >>> 0).toString(16)
21}
22
23const script = ($: EngineInterface, args: string[], payload: unknown) =>
24 $.process.run(['python3', '-I', `${$.plugin.root}/scripts/english-coach.py`, ...args], {
25 stdin: JSON.stringify(payload),
26 timeoutMs: 15_000,
27 })
28
29// What the assistant said last, for the quote guard: a phrase the user repeats from it is a quotation, not their writing.
30// Read when the prompt is submitted, handed to the script for one call, never stored.
31const recentAssistantText = async ($: EngineInterface): Promise<string> => {
32 try {
33 const messages = await $.session.messages({ as: 'api' })
34 const texts: string[] = []
35 for (let index = messages.length - 1; index >= 0 && texts.length < 2; index--) {
36 const message = messages[index]
37 if (message === undefined || message.role !== 'assistant') continue
38 const content = message.content
39 const text =
40 typeof content === 'string'
41 ? content
42 : content.map(block => ('text' in block && typeof block.text === 'string' ? block.text : '')).join('\n')
43 if (text.trim() !== '') texts.push(text)
44 }
45
46 return texts.reverse().join('\n').slice(-CONTEXT_CHARS)
47 } catch {
48 return ''
49 }
50}
51
52type Prepared = {
53 coach: boolean
54 text: string
55 mode: 'written' | 'dictated'
56 strip: boolean
57 system?: string
58 user?: string
59}
60
61const prepare = async ($: EngineInterface, text: string, context: string): Promise<Prepared> => {
62 try {
63 return JSON.parse((await script($, ['prepare'], { prompt: text, context })).stdout) as Prepared
64 } catch {
65 return { coach: false, text, mode: 'written', strip: false }
66 }
67}
68
69// `shown` is the text as the message row will draw it, which is the key the fixes are looked up by.
70// Prepares the overview's written summaries in the background when the backend says they are due, so opening the pane shows them at once.
71const refreshSummaries = async ($: EngineInterface) => {
72 try {
73 const due = JSON.parse((await script($, ['summary-due'], {})).stdout)
74 for (const mode of due.modes as string[]) {
75 const input = JSON.parse((await script($, ['summary-input', mode], {})).stdout)
76 if (input.categories.length === 0) continue
77 const reply = await $.model.complete({ model: input.model, system: input.system, prompt: input.prompt, maxTokens: 1500, timeoutMs: 180_000 })
78 if (reply.isAnswered) await script($, ['summary-store', mode], { reply: reply.text })
79 }
80 } catch {
81 // The next check tries again.
82 }
83}
84
85type AuditRequest = { model: string; system: string; user: string; prompt_id: number }
86
87// The larger model's second opinion on one review, asked in the background right after it (setting `audit`): it sees the whole message and
88// the recent chat for this one call; only its verdicts are stored. Nothing waits for it, and a failure just skips this one.
89const audit = async ($: EngineInterface, request: AuditRequest, prompt: string) => {
90 try {
91 const reply = await $.model.complete({ model: request.model, system: request.system, prompt: request.user, maxTokens: 900, timeoutMs: 90_000 })
92 if (reply.isAnswered) await script($, ['audit-store'], { reply: reply.text, prompt, prompt_id: request.prompt_id })
93 } catch {
94 // The next review is audited again.
95 }
96}
97
98const review = async ($: EngineInterface, prepared: Prepared, shown: string, context: string) => {
99 try {
100 const reply = await $.model.complete({
101 model: MODEL,
102 system: prepared.system,
103 prompt: prepared.user ?? '',
104 maxTokens: 700,
105 timeoutMs: 30_000,
106 })
107 if (!reply.isAnswered) return
108
109 // A dictated passage the first review found garbled is probably a transcription error: ask the larger model once.
110 let answer = reply.text
111 try {
112 const decision = JSON.parse(
113 (await script($, ['check'], { prompt: prepared.text, mode: prepared.mode, reply: reply.text, context })).stdout,
114 )
115 if (decision.escalate && decision.model) {
116 const second = await $.model.complete({
117 model: decision.model,
118 system: prepared.system,
119 prompt: (prepared.user ?? '') + (decision.note ?? ''),
120 maxTokens: 700,
121 timeoutMs: 45_000,
122 })
123 if (second.isAnswered) answer = second.text
124 }
125 } catch {
126 // Without the second opinion the first review stands.
127 }
128
129 const result = JSON.parse(
130 (await script($, ['ingest'], { prompt: prepared.text, mode: prepared.mode, reply: answer, context })).stdout,
131 )
132 if (!result.ok) return
133 if (result.hint) $.ui.toast(result.hint)
134 if (result.audit) $.clock.after(0, () => void audit($, result.audit as AuditRequest, prepared.text))
135 if (result.careless || (result.fixes.length === 0 && !result.btw && !result.phrase)) return
136
137 const entry: Review = { fixes: result.fixes as Fix[], phrase: result.phrase ?? null, btw: result.btw ?? null, icon: result.icon ?? '✎' }
138 await update($, reviews, held => Object.fromEntries(Object.entries({ ...held, [textKey(shown)]: entry }).slice(-KEEP)))
139 } catch (error) {
140 $.ui.toast(`english-coach: review failed (${String(error).slice(0, 80)})`)
141 }
142}
143
144export const register: Register = on => {
145 registerOverview(on)
146
147 let isInteractive = true // session.start always runs before the first prompt and sets it
148
149 on('session.start', async ($, e, next) => {
150 isInteractive = e.isInteractive
151 await $.command.register({ name: COMMAND, description: 'English coach overview: written, spoken or both' })
152 if (e.isInteractive) {
153 $.clock.after(60_000, () => void refreshSummaries($))
154 $.clock.every(86_400_000, () => void refreshSummaries($))
155 }
156
157 return next(e)
158 })
159
160 on('prompt.submit', async ($, e, next) => {
161 if (!isInteractive || !OWN_WORDS.has(e.origin?.kind ?? 'composer')) return next(e)
162
163 const context = await recentAssistantText($) // the reviewer gets only the names and identifiers in it; the quote guard compares against all of it
164 const prepared = await prepare($, e.text, context)
165 const isStripped = prepared.strip && prepared.text !== e.text.trim()
166 const entered = await next(isStripped ? { ...e, text: prepared.text } : e)
167 if (entered.drop !== undefined) return entered
168
169 if (prepared.coach) {
170 const shown = isStripped ? prepared.text : e.text.trim()
171 $.clock.after(0, () => void review($, prepared, shown, context))
172 }
173
174 return entered
175 }).catch(($, e, next) => next(e))
176
177 on('ui.render', { component: 'UserMessage' }, async ($, e, next) => {
178 const drawn = await next(e)
179 const held = (await read($, reviews))[textKey(e.props.text)]
180 if (held === undefined) return drawn
181
182 const { Box, Text } = $.ui.resolve(e)
183 const mark = `${held.icon} ` // configurable: one icon for typed text, one for dictated text
184 // The correction as word segments: the changed words are coloured, their neighbours stay quiet, and long stretches shrink to "…".
185 const pieces = (segments: [string, boolean][], color: 'error' | 'success') =>
186 segments.map(([text, changed], index) => (
187 <Text key={`piece-${index}`} color={changed ? color : undefined} dimColor={!changed} bold={changed && color === 'success'}>
188 {(index > 0 ? ' ' : '') + text}
189 </Text>
190 ))
191
192 return (
193 <Box flexDirection="column">
194 {drawn}
195 <Box flexDirection="column" paddingLeft={2}>
196 {held.fixes.map((fix, index) => (
197 <Box key={`fix-${index}`} flexDirection="column">
198 <Text wrap="wrap">
199 <Text dimColor>{mark}</Text>
200 {fix.severity === 'style' ? (
201 <Text dimColor>{`${fix.original} → ${fix.fix} style, not an error`}</Text>
202 ) : fix.parts ? (
203 pieces(fix.parts.original, 'error')
204 ) : (
205 <Text color="error">{fix.original}</Text>
206 )}
207 {fix.severity === 'style' ? null : <Text dimColor>{' → '}</Text>}
208 {fix.severity === 'style' ? null : fix.parts ? (
209 pieces(fix.parts.fix, 'success')
210 ) : (
211 <Text color="success" bold>
212 {fix.fix}
213 </Text>
214 )}
215 {fix.severity === 'style' ? null : (
216 <Text dimColor>{` ${fix.category}${fix.transfer ? ' · transfer' : ''}`}</Text>
217 )}
218 </Text>
219 <Text dimColor italic wrap="wrap">
220 {` ${fix.explanation}`}
221 </Text>
222 {fix.reminder ? (
223 <Text dimColor wrap="wrap">
224 {` ↻ ${fix.reminder}`}
225 </Text>
226 ) : null}
227 </Box>
228 ))}
229 {!held.phrase ? null : (
230 <Box flexDirection="column">
231 <Text wrap="wrap">
232 <Text color="suggestion">{'✦ '}</Text>
233 <Text color="suggestion" bold>
234 {held.phrase.phrase}
235 </Text>
236 <Text dimColor>{` ${held.phrase.meaning}`}</Text>
237 </Text>
238 <Text dimColor italic wrap="wrap">
239 {` where you wrote "${held.phrase.original}", for example: ${held.phrase.example}`}
240 </Text>
241 </Box>
242 )}
243 {held.btw === null ? null : (
244 <Text dimColor wrap="wrap">
245 {`${held.icon} ${held.btw}`}
246 </Text>
247 )}
248 </Box>
249 </Box>
250 )
251 })
252}
253hooks/overview.tsx 404 lines1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, On } from 'claude-code'
3
4import type { AuditSuspect, CategoryStats, Mode, Overview, OverviewState } from '../types'
5
6export const PANE = 'english-coach-overview'
7export const COMMAND = 'english-coach-overview'
8
9const MODES: Mode[] = ['both', 'written', 'dictated']
10const LABEL: Record<Mode, string> = { both: 'Both', written: 'Written', dictated: 'Spoken' }
11const HOTKEY: Record<Mode, string> = { both: 'b', written: 'w', dictated: 's' }
12const BARS = '▁▂▃▄▅▆▇█'
13
14const tab = atom({ plugin: 'english-coach', key: 'tab' } as const, 'both' as Mode)
15const overview = atom({ plugin: 'english-coach', key: 'overview' } as const, null as OverviewState)
16const expanded = atom({ plugin: 'english-coach', key: 'expanded' } as const, [] as string[])
17const summarizing = atom({ plugin: 'english-coach', key: 'summarizing' } as const, 0)
18
19// Runs the Python backend and returns what it printed (declared here: the module analyzer only lets `$` reach functions of its own file).
20const backend = async ($: EngineInterface, args: string[], stdin: unknown = {}) =>
21 (
22 await $.process.run(['python3', '-I', `${$.plugin.root}/scripts/english-coach.py`, ...args], {
23 stdin: JSON.stringify(stdin),
24 timeoutMs: 15_000,
25 })
26 ).stdout
27
28const load = async ($: EngineInterface) => {
29 const loadedAt = await $.clock.now()
30 const entries = await Promise.all(MODES.map(async mode => [mode, JSON.parse(await backend($, ['overview', mode])) as Overview] as const))
31 const data = Object.fromEntries(entries) as Record<Mode, Overview>
32 await update($, overview, () => ({ loadedAt, data }))
33}
34
35// Asks the larger model for the general pattern behind each category's corrections, stores the answer, and redraws.
36// `modes` are the views to write for; left out, the ones the backend says are due because the pane was just opened.
37const summarize = async ($: EngineInterface, modes?: Mode[]) => {
38 try {
39 const wanted = modes ?? ((JSON.parse(await backend($, ['summary-due', '--open'])).modes ?? []) as Mode[])
40 await update($, summarizing, () => wanted.length)
41 // The views are written in parallel, and each one redraws the pane as soon as it is stored.
42 await Promise.all(
43 wanted.map(async mode => {
44 try {
45 const input = JSON.parse(await backend($, ['summary-input', mode]))
46 if (input.categories.length > 0) {
47 const reply = await $.model.complete({ model: input.model, system: input.system, prompt: input.prompt, maxTokens: 1500, timeoutMs: 180_000 })
48 if (reply.isAnswered) await backend($, ['summary-store', mode], { reply: reply.text })
49 }
50 await load($)
51 } catch (error) {
52 $.ui.toast(`english-coach: summary failed (${String(error).slice(0, 80)})`)
53 } finally {
54 await update($, summarizing, n => Math.max(0, n - 1))
55 }
56 }),
57 )
58 } catch (error) {
59 $.ui.toast(`english-coach: summary failed (${String(error).slice(0, 80)})`)
60 await update($, summarizing, () => 0)
61 }
62}
63
64const spark = (values: (number | null)[], scale: number) =>
65 values
66 .map(value => (value === null ? '·' : value === 0 ? BARS.charAt(0) : BARS.charAt(Math.min(7, 1 + Math.floor((value / scale) * 6.999)))))
67 .join('')
68
69const TREND = {
70 down: { arrow: '↓', color: 'success' },
71 up: { arrow: '↑', color: 'error' },
72 flat: { arrow: '→', color: undefined },
73 'n/a': { arrow: '', color: undefined },
74} as const
75
76const shareColor = (share: number) => (share >= 0.75 ? 'success' : share >= 0.5 ? 'warning' : 'error')
77const percent = (part: number, whole: number) => (whole === 0 ? 0 : Math.round((100 * part) / whole))
78
79export const registerOverview = (on: On) => {
80 on('command.run', { command: COMMAND }, async $ => {
81 await load($)
82 await $.ui.open({ id: PANE, title: 'English coach', focus: true, closeOnEscape: true })
83 $.clock.after(0, () => void summarize($)) // a missing or outdated report is prepared right away; the pane shows its status meanwhile
84
85 return { text: 'English coach overview opened.' }
86 })
87
88 on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
89 const { Box, Text, Button } = $.ui.resolve(e)
90 const state = await read($, overview)
91 const selected = await read($, tab)
92 const open = await read($, expanded)
93 const busy = (await read($, summarizing)) > 0
94 if (state === null) return <Text dimColor>Loading…</Text>
95
96 const data = state.data[selected]
97 const width = Math.max(30, e.props.bodyColumns - 2)
98 const barWidth = Math.max(10, Math.min(24, width - 24))
99 const rule = '─'.repeat(Math.min(width, 60))
100 const sentenceFilled = data.error_free_sentences === null ? 0 : Math.round(data.error_free_sentences * barWidth)
101 const showTrends = data.weeks_with_data >= 2
102 const topTotal = Math.max(1, ...data.categories.map(c => c.total))
103 const catBar = Math.max(8, Math.min(16, width - 40))
104 const scale = Math.max(0.1, ...data.categories.flatMap(c => c.weekly.filter((v): v is number => v !== null)))
105 const toggle = (id: string) => update($, expanded, list => (list.includes(id) ? list.filter(x => x !== id) : [...list, id]))
106 const loaded = new Date(state.loadedAt)
107 const counts: Record<Mode, number> = {
108 both: data.messages_by_mode['written']! + data.messages_by_mode['dictated']!,
109 written: data.messages_by_mode['written']!,
110 dictated: data.messages_by_mode['dictated']!,
111 }
112
113 const Heading = ({ title, note }: { title: string; note?: string }) => (
114 <Box flexDirection="column">
115 <Text bold color="suggestion">
116 {title}
117 </Text>
118 {note ? <Text dimColor>{note}</Text> : null}
119 </Box>
120 )
121
122 return (
123 <Box flexDirection="column" gap={1}>
124 <Box flexDirection="column">
125 <Text>
126 <Text bold color="suggestion">
127 English coach
128 </Text>
129 <Text dimColor>{data.since ? ` since ${data.since} · ${data.messages} messages · ${data.words} words` : ''}</Text>
130 </Text>
131 <Text dimColor>{rule}</Text>
132 </Box>
133
134 <Box columnGap={2}>
135 {MODES.map(mode => (
136 <Button
137 key={`tab-${mode}`}
138 plain
139 label={`${mode === selected ? '●' : '○'} ${LABEL[mode]} (${counts[mode]})`}
140 hotkey={HOTKEY[mode]}
141 dimColor={mode !== selected}
142 onPress={() => update($, tab, () => mode)}
143 />
144 ))}
145 </Box>
146
147 <Box flexDirection="column">
148 <Heading title="Accuracy" note="measured per word and per sentence, so message length does not skew it" />
149 {data.errors_per_100_words === null ? (
150 <Text dimColor>No messages in this view yet.</Text>
151 ) : (
152 <Text>
153 <Text bold>{data.errors_per_100_words.toFixed(1)}</Text>
154 <Text dimColor>{' errors per 100 words'}</Text>
155 {showTrends ? <Text color={TREND[data.rate_trend].color}>{` ${TREND[data.rate_trend].arrow}`}</Text> : null}
156 {showTrends ? <Text dimColor>{` ${spark(data.rate_weekly, Math.max(0.1, ...data.rate_weekly.filter((v): v is number => v !== null)))}`}</Text> : null}
157 </Text>
158 )}
159 {data.error_free_sentences === null ? null : (
160 <Text>
161 <Text color={shareColor(data.error_free_sentences)}>{'█'.repeat(sentenceFilled)}</Text>
162 <Text dimColor>{'░'.repeat(barWidth - sentenceFilled)}</Text>
163 <Text bold>{` ${Math.round(data.error_free_sentences * 100)}%`}</Text>
164 <Text dimColor>{` of ${data.sentences} sentences without an error`}</Text>
165 </Text>
166 )}
167 <Text>
168 <Text color="error">{`${data.errors} errors`}</Text>
169 <Text dimColor>{' '}</Text>
170 <Text color="warning">{`${data.slips} slips`}</Text>
171 <Text dimColor>{' '}</Text>
172 <Text color="suggestion">{`${data.styles} style items`}</Text>
173 </Text>
174 <Button
175 key="toggle-lengths"
176 plain
177 dimColor
178 label={`${open.includes('lengths') ? '▾' : '▸'} Clean messages by length`}
179 onPress={() => toggle('lengths')}
180 />
181 {open.includes('lengths') ? (
182 <Box flexDirection="column">
183 {data.length_buckets.map(bucket => (
184 <Text key={`len-${bucket.label}`} dimColor>
185 {` ${bucket.label.padEnd(12)} ${String(Math.round(bucket.clean_share * 100)).padStart(3)}% clean ${bucket.per_100_words === null ? '-' : bucket.per_100_words.toFixed(1)} per 100 words (${bucket.messages} messages)`}
186 </Text>
187 ))}
188 <Text dimColor italic wrap="wrap">{' Longer messages are clean less often, simply because they offer more places for a slip. That is why the numbers above are per word and per sentence.'}</Text>
189 </Box>
190 ) : null}
191 </Box>
192
193 {busy && (
194 <Text color="suggestion">{`✦ ${data.summary_state === 'none' ? 'Preparing' : 'Renewing'} the report… 15 to 30 seconds; the overview fills in by itself.`}</Text>
195 )}
196 {!busy && data.summary_state === 'stale' && (
197 <Text dimColor>{'The report below predates your latest corrections. It renews in the background, or press p.'}</Text>
198 )}
199 {!busy && data.summary_state === 'none' && (
200 <Text dimColor>{'No report yet. Press p to write one.'}</Text>
201 )}
202 {!busy && data.summary_state === 'not_enough' && (
203 <Text dimColor>{`A written report of your patterns appears after 10 corrections (${data.errors_needed} more).`}</Text>
204 )}
205
206 {data.focus.length > 0 && (
207 <Box flexDirection="column">
208 <Heading title="What to work on" />
209 {data.focus.map((line, index) => (
210 <Text key={`focus-${index}`} wrap="wrap">{`${index + 1}. ${line}`}</Text>
211 ))}
212 </Box>
213 )}
214
215 {data.categories.length > 0 && (
216 <Box flexDirection="column">
217 <Heading title="Where your errors are" note={showTrends ? 'bar = share of your errors; strip = last 8 weeks, ↓ is improving' : 'bar = share of your errors'} />
218 <Box flexDirection="column" gap={1}>
219 {data.categories.map((cat: CategoryStats) => {
220 const bar = Math.max(1, Math.round((catBar * cat.total) / topTotal))
221
222 return (
223 <Box key={`cat-${cat.category}`} flexDirection="column">
224 <Box columnGap={2}>
225 <Text>
226 <Text bold>{cat.category.padEnd(14)}</Text>
227 <Text color="permission">{'█'.repeat(bar)}</Text>
228 <Text dimColor>{'░'.repeat(catBar - bar)}</Text>
229 <Text>{` ${String(cat.total).padStart(3)}`}</Text>
230 <Text dimColor>{` ${percent(cat.total, data.errors)}%`}</Text>
231 {showTrends ? <Text color={TREND[cat.trend].color}>{` ${spark(cat.weekly, scale)} ${TREND[cat.trend].arrow}`}</Text> : null}
232 </Text>
233 {cat.summary?.detail ? (
234 <Button
235 key={`detail-${cat.category}`}
236 plain
237 dimColor
238 label={open.includes(`detail-${cat.category}`) ? '▾ details' : '▸ details'}
239 onPress={() => toggle(`detail-${cat.category}`)}
240 />
241 ) : null}
242 {cat.examples.length > (cat.summary ? 0 : 1) ? (
243 <Button
244 key={`examples-${cat.category}`}
245 plain
246 dimColor
247 label={open.includes(`examples-${cat.category}`) ? '▾ examples' : '▸ examples'}
248 onPress={() => toggle(`examples-${cat.category}`)}
249 />
250 ) : null}
251 </Box>
252 {cat.summary ? (
253 <Text wrap="wrap">{` ${cat.summary.headline}`}</Text>
254 ) : null}
255 {cat.summary && open.includes(`detail-${cat.category}`) && cat.summary.detail ? (
256 <Text dimColor wrap="wrap">{` ${cat.summary.detail}`}</Text>
257 ) : null}
258 {cat.examples.slice(0, open.includes(`examples-${cat.category}`) ? 3 : cat.summary ? 0 : 1).map((example, index) => (
259 <Text key={`ex-${cat.category}-${index}`} wrap="wrap">
260 <Text dimColor>{' '}</Text>
261 <Text color="error">{example.core?.wrong ?? example.original}</Text>
262 <Text dimColor>{' → '}</Text>
263 <Text color="success">{example.core?.right ?? example.fix}</Text>
264 {example.transfer ? <Text dimColor italic>{` ${data.transfer.native ?? ''} pattern`}</Text> : null}
265 </Text>
266 ))}
267 </Box>
268 )
269 })}
270 </Box>
271 {data.transfer.native !== null && data.transfer.share !== null && (
272 <Text>
273 <Text color="suggestion" bold>{`${data.transfer.native} patterns `}</Text>
274 <Text>{`${Math.round(data.transfer.share * 100)}% of your errors`}</Text>
275 <Text dimColor>{` (${data.transfer.total} of ${data.errors})`}</Text>
276 </Text>
277 )}
278 </Box>
279 )}
280
281 {(data.audit.scope !== 'off' || data.audit.audited > 0) && (
282 <Box flexDirection="column">
283 <Heading title="Second opinion" note="a larger model rechecks each tip with the whole message; you decide" />
284 {data.audit.audited === 0 ? (
285 <Text dimColor>{'No second opinions yet. They appear after the next reviewed message.'}</Text>
286 ) : (
287 <Text>
288 <Text bold>{`${Math.round((100 * data.audit.agree) / data.audit.audited)}%`}</Text>
289 <Text dimColor>{` agree (${data.audit.agree} of ${data.audit.audited} tips)`}</Text>
290 {data.audit.misses > 0 ? <Text dimColor>{` ${data.audit.misses} missed errors noted`}</Text> : null}
291 </Text>
292 )}
293 {data.audit.suspects.map((s: AuditSuspect) => (
294 <Box key={`doubt-${s.id}`} flexDirection="column">
295 <Text wrap="wrap">
296 <Text dimColor>{`#${s.id} `}</Text>
297 <Text color="error">{s.core.wrong}</Text>
298 <Text dimColor>{' → '}</Text>
299 <Text color="success">{s.core.right}</Text>
300 <Text color="warning">{` ${s.verdict}${s.category ? ` (${s.category})` : ''}`}</Text>
301 </Text>
302 <Text dimColor italic wrap="wrap">{` ${s.reason}`}</Text>
303 <Box columnGap={2}>
304 <Button
305 key={`dismiss-${s.id}`}
306 plain
307 dimColor
308 label="dismiss: not my mistake"
309 onPress={async () => {
310 await backend($, ['dismiss', String(s.id), s.verdict === 'wrong-fix' ? 'false' : 'taste'])
311 await load($)
312 }}
313 />
314 <Button
315 key={`keep-${s.id}`}
316 plain
317 dimColor
318 label="keep the tip"
319 onPress={async () => {
320 await backend($, ['audit', 'ack', String(s.id)])
321 await load($)
322 }}
323 />
324 </Box>
325 </Box>
326 ))}
327 </Box>
328 )}
329
330 {data.watchlist.length > 0 && (
331 <Box flexDirection="column">
332 <Heading title="Watchlist" note="mistakes that keep coming back" />
333 {data.watchlist.map(entry => (
334 <Box key={`watch-${entry.wrong}-${entry.right}`} borderStyle="round" borderColor="subtle" paddingX={1} flexDirection="column">
335 <Text>
336 <Text color="error">{entry.wrong}</Text>
337 <Text dimColor>{' → '}</Text>
338 <Text color="success" bold>
339 {entry.right}
340 </Text>
341 </Text>
342 <Text color={entry.status === 'resolved' || entry.streak > 0 ? 'success' : 'warning'}>
343 {`${entry.hits}× flagged · ${entry.status === 'resolved' ? 'resolved' : entry.streak > 0 ? `improving: ${entry.streak} right in a row` : 'active'}${entry.manual ? ' · added by you' : ''}`}
344 </Text>
345 {entry.note ? (
346 <Text dimColor italic wrap="wrap">
347 {entry.note}
348 </Text>
349 ) : null}
350 </Box>
351 ))}
352 </Box>
353 )}
354
355 {(data.slips > 0 || data.styles > 0) && (
356 <Box flexDirection="column">
357 {data.slips > 0 && (
358 <Button
359 key="toggle-slips"
360 plain
361 dimColor
362 label={`${open.includes('slips') ? '▾' : '▸'} Slips (${data.slips}): forgotten or misrecognized small words`}
363 onPress={() => toggle('slips')}
364 />
365 )}
366 {open.includes('slips')
367 ? data.slip_examples.map((example, index) => (
368 <Text key={`slip-${index}`} dimColor wrap="wrap">{` ${example.core?.wrong ?? example.original} → ${example.core?.right ?? example.fix}`}</Text>
369 ))
370 : null}
371 {data.styles > 0 && (
372 <Button
373 key="toggle-style"
374 plain
375 dimColor
376 label={`${open.includes('style') ? '▾' : '▸'} Native polish (${data.styles}): correct, but a native would say it differently`}
377 onPress={() => toggle('style')}
378 />
379 )}
380 {open.includes('style')
381 ? data.style_examples.map((example, index) => (
382 <Text key={`style-${index}`} color="suggestion" wrap="wrap">{` ${example.core?.wrong ?? example.original} → ${example.core?.right ?? example.fix}`}</Text>
383 ))
384 : null}
385 </Box>
386 )}
387
388 <Box columnGap={2}>
389 <Button key="refresh" plain dimColor label="↻ Refresh" hotkey="r" onPress={() => load($)} />
390 <Button
391 key="summarize"
392 plain
393 dimColor={busy}
394 label={busy ? '✦ Summarizing…' : data.focus.length > 0 && !data.focus_stale ? '✦ Summarize again' : '✦ Summarize patterns'}
395 hotkey="p"
396 onPress={() => (busy ? undefined : summarize($, [selected]))}
397 />
398 <Text dimColor>{`updated ${String(loaded.getHours()).padStart(2, '0')}:${String(loaded.getMinutes()).padStart(2, '0')}`}</Text>
399 </Box>
400 </Box>
401 )
402 })
403}
404types/index.d.ts 96 lines1export type Fix = {
2 category: string
3 transfer: boolean
4 original: string
5 fix: string
6 explanation: string
7 severity: 'error' | 'style'
8 reminder?: string | null
9 parts?: { original: [string, boolean][]; fix: [string, boolean][] }
10 id?: number | null
11}
12
13export type AuditSuspect = {
14 id: number
15 verdict: 'not-error' | 'style' | 'wrong-fix' | 'wrong-category'
16 category: string
17 current: string
18 reason: string
19 original: string
20 fix: string
21 core: { wrong: string; right: string }
22}
23
24export type AuditInfo = { scope: 'off' | 'flagged' | 'all'; audited: number; agree: number; suspects: AuditSuspect[]; misses: number }
25
26export type Phrase = { id: string; phrase: string; meaning: string; example: string; original: string }
27
28export type Review = {
29 fixes: Fix[]
30 phrase: Phrase | null
31 btw: string | null
32 icon: string
33}
34
35export type Mode = 'both' | 'written' | 'dictated'
36
37export type Example = { original: string; fix: string; explanation: string; transfer?: boolean; core?: { wrong: string; right: string } }
38
39export type CategoryStats = {
40 category: string
41 total: number
42 weekly: (number | null)[]
43 trend: 'down' | 'up' | 'flat' | 'n/a'
44 examples: Example[]
45 summary: { headline: string; detail: string } | null
46 summary_stale: boolean
47}
48
49export type WatchEntry = {
50 wrong: string
51 right: string
52 hits: number
53 streak: number
54 status: string
55 note: string
56 manual: boolean
57}
58
59export type Overview = {
60 audit: AuditInfo
61 mode: Mode
62 since: string | null
63 messages: number
64 words: number
65 errors: number
66 slips: number
67 styles: number
68 clean_weekly: (number | null)[]
69 clean_now: number | null
70 categories: CategoryStats[]
71 transfer: { native: string | null; weekly: (number | null)[]; trend: 'down' | 'up' | 'flat' | 'n/a'; total: number; share: number | null }
72 weeks_with_data: number
73 focus: string[]
74 focus_stale: boolean
75 summary_state: 'not_enough' | 'none' | 'stale' | 'ready'
76 errors_needed: number
77 errors_per_100_words: number | null
78 rate_weekly: (number | null)[]
79 rate_trend: 'down' | 'up' | 'flat' | 'n/a'
80 sentences: number
81 error_free_sentences: number | null
82 length_buckets: { label: string; messages: number; clean_share: number; per_100_words: number | null }[]
83 watchlist: WatchEntry[]
84 slip_examples: Example[]
85 style_examples: Example[]
86 messages_by_mode: Record<string, number>
87}
88
89export type OverviewState = { loadedAt: number; data: Record<Mode, Overview> } | null
90
91declare module 'claude-code' {
92 interface PluginState {
93 'english-coach': { reviews: Record<string, Review>; tab: Mode; overview: OverviewState; expanded: string[]; summarizing: number }
94 }
95}
96