SLOPSHOPPER

english-coach

Practise English by talking to Claude in English only: Chinese glosses on hard words, Chinese key points and translations of long replies, Chinese-to-English…

bandspinnerrowscommandtoaststatus
v0.7.2MITupdated 2026-10-18chinayuren2022-2025/claude-english-coach
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · english-coach
› fix the failing auth test and add an audit log call ⏺ 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 › /english ⎿ english-coach: English coach is on · level B1? (measuring) · goal IELTS 7.5 · glosses on · key points on · Chinese input: rev ⎿ english-coach: ⎿ english-coach: /english on | off turn the mode on or off ⎿ english-coach: /english level auto measure your level from what you write (default) ⎿ english-coach: /english level A2|B1|B2|C1 fix the level of Claude's English ⎿ english-coach: /english goal <text> your target, e.g. IELTS 7.5 ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts auto-accept edits · EN A1─A2─ B1? ─B2─C1★─C2 measuring 0/3
README

English Coach for Claude Code

Practise English by working with Claude in English only. Made for Chinese-speaking learners (for example, aiming for IELTS 7.5).

在 Claude Code 里只用英语和 Claude 交流,练英语。为中文母语的学习者设计。

What it does

  • Claude replies in English. Its system prompt gets one line, "write every reply in English", and nothing else, so no learner rules shape how it thinks or writes. After each reply, Haiku picks the hard words and the mod adds a short Chinese gloss to what you see: idempotent(幂等的). Claude's stored reply, which it reads back later, stays exactly as it wrote it. Code, links and URLs are never glossed.
  • Your level is measured automatically from what you write (CEFR A2–C1), and shown as a slider under the prompt, with your goal marked: EN A1─A2─[B1]─B2─C1★─C2 (in the desktop app, where the footer is short, only the stretch from your level to your goal: EN [B1]─B2─C1★).
  • Check before you send. When you press Enter, your English is checked first, with Claude's last reply as context, so "you" and "I" keep their meaning. Haiku lists each error as an exact quote with its fix, and the mod applies only the ones it can trust: real errors (grammar, wrong word, spelling, collocation), never style rewrites, casing or punctuation, and never a change to who does what ("you", "I", "we"). If there is something to fix, the message is not sent: the corrected version goes straight into the box, as a Chinese draft does, and a card above the prompt shows your sentence with the mistakes struck out in red and the fixes in green, and short numbered tips in Chinese. Press Enter to send the fix; click ↩ Mine on the card, or type ` (with a Chinese input method that key types ·, 、 or `, and those work too), to swap the box back to your own version and Enter to send that; or edit it and it is checked again. (Tab can't be used: Claude Code keeps Tab and the arrow keys for itself, and a plugin only sees typed characters.) A message with images is sent at once and checked afterwards, so nothing is lost.
  • Out of your way. A "natural" result is one line, and cards hide by themselves once nothing waits on them (8 seconds; 20 for a Chinese message translated and sent in auto mode). A held message or an English draft keeps its card until you send.
  • Level up. Even when your English is natural, you get one stronger word or phrase toward your goal: fix this bug → track down this bug.
  • Write in Chinese when you're stuck. Chinese or mixed input becomes an English draft in the box for you to check, with the key phrases shown: 优化 → optimize. Click ↩ 中文 on the card (or type ) to get your Chinese back, and Enter sends it as typed; → English brings the draft back. Chinese in file references (@笔记.md, paths, file names) and in quotes doesn't count, so an English message about a Chinese-named file is checked as English. Start a prompt with zh:` to send Chinese as typed.
  • Read a long reply in Chinese. /zh has Haiku translate Claude's last reply into Chinese and draws it under the English, paragraph by paragraph, so you can compare the two. Code stays as it is, and technical terms keep their English: 竞态条件(race condition). /zh again hides it; /zh 2 translates the reply before. Only you see it: the Chinese is drawn on screen and never written to the conversation, so Claude's context doesn't grow and Claude keeps replying in English.
  • Key points of a long reply. When Claude writes more than about 150 words, up to three short Chinese lines appear under the reply: 做了, what Claude did (files changed, commands run, test results); 结论, its conclusion or advice; and, in yellow, 问你, the question it asks you or what it needs from you, shown only when there is one. So you know what a long reply says, and what you have to answer, before you read it all. While /zh shows the full translation, the key points give way to it. Like /zh, they are only drawn on screen and never written to the conversation. /english points off turns them off.

The checks, drafts, glosses, translations and key points use a small, fast model (Haiku): one call per message you send, one per reply block Claude writes (at most 6 per turn), one per paragraph you translate with /zh, and one per long reply for its key points.

Install

At the prompt of a Claude Code terminal session:

/plugin install english-coach --marketplace chinayuren2022-2025/claude-english-coach

Answer y to add the marketplace, then choose a scope (user scope loads it in every session).

From a shell:

claude plugin install english-coach --marketplace chinayuren2022-2025/claude-english-coach

In the desktop app, where /plugin does not run: click + next to the prompt box, then Plugins, Add marketplace with chinayuren2022-2025/claude-english-coach, then Add plugin.

Commands

CommandWhat it does
/englishShow settings and help
/english on / offTurn the mode on or off
/english level autoMeasure your level from your writing (default)
`/english level A2\B1\B2\C1`Fix the level of Claude's English
/english goal IELTS 7.5Set your target
`/english gloss on\off`Chinese glosses after hard words
`/english points on\off`Key points in Chinese under Claude's long replies
`/english feedback before\after\off`Check before sending (default), feedback after sending, or none
`/english chinese review\auto\off`Chinese input: draft to check (default), translate and send, or send as typed
/english demoShow a sample feedback card
/en <text>Turn Chinese or rough English into an English draft in the box
/zh / /zh 2Chinese translation of Claude's last reply (or the one before), drawn under it for you alone; again hides it

Settings are kept across sessions.

Notes

  • Where an organization manages Claude Code, the English-only system prompt part does not run for plugins a person installs; the input help still works.
  • In the desktop app, the /zh translation and the key points are drawn as a quote under the reply, still on screen only.
  • Develop: claude --plugin-dir . loads it from this folder; claude plugin test . runs the tests.

License

MIT

Source 2 files
hooks/register.tsx 1063 lines
1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, PromptOrigin, Register, RenderChildren, SessionMessage } from 'claude-code'
3
4import type { Feedback, Gloss, LevelView, Phrase, ReplyGlosses, ReplyPoints, ReplyTranslation } from '../types'
5
6const feedback = atom({ plugin: 'english-coach', key: 'feedback' } as const, null)
7const levelView = atom({ plugin: 'english-coach', key: 'level' } as const, null)
8const replyGlosses = atom({ plugin: 'english-coach', key: 'glosses' } as const, {} as ReplyGlosses)
9const translations = atom({ plugin: 'english-coach', key: 'translations' } as const, [] as ReplyTranslation[])
10const keyPoints = atom({ plugin: 'english-coach', key: 'points' } as const, [] as ReplyPoints[])
11
12// Glosses per reply: at most this many replies kept, this many new blocks glossed per turn.
13const GLOSSED_KEPT = 100
14const BLOCKS_PER_TURN = 6
15const GLOSSES_PER_BLOCK = 6
16
17const LEVELS = ['A2', 'B1', 'B2', 'C1'] as const
18type Level = (typeof LEVELS)[number]
19const SCALE = ['A1', 'A2', 'B1', 'B2', 'C1', 'C2'] as const
20type ChineseMode = 'review' | 'auto' | 'off'
21type CheckWhen = 'before' | 'after' | 'off'
22
23type Settings = {
24  isOn: boolean
25  level: Level | 'auto'
26  goal: string
27  gloss: boolean
28  chinese: ChineseMode
29  checkWhen: CheckWhen
30  // Key points in Chinese under Claude's long replies.
31  points: boolean
32}
33
34const DEFAULTS: Settings = { isOn: true, level: 'auto', goal: 'IELTS 7.5', gloss: true, chinese: 'review', checkWhen: 'before', points: true }
35
36// Prefix that sends a prompt as typed, Chinese included.
37const RAW_PREFIX = 'zh:'
38
39// How long a check before sending may hold a message up; past it, the message is sent.
40const HOLD_TIMEOUT_MS = 10_000
41
42// How long a card stays once nothing waits on it: a checked message, an English draft.
43const HIDE_CHECKED_MS = 8_000
44const HIDE_DRAFT_MS = 20_000
45
46// Auto level: the median of the last estimates the feedback check made.
47const ESTIMATES_KEPT = 20
48const ESTIMATES_NEEDED = 3
49// A message shorter than this says too little about a level to count.
50const WORDS_TO_ESTIMATE = 8
51
52const loadSettings = async ($: EngineInterface): Promise<Settings> => {
53  const saved = (await $.store.get('settings')) as Partial<Settings> | undefined
54  return { ...DEFAULTS, ...(saved ?? {}) }
55}
56
57const loadEstimates = async ($: EngineInterface) => ((await $.store.get('estimates')) as string[] | undefined) ?? []
58
59const addEstimate = async ($: EngineInterface, cefr: string) => {
60  if (!(SCALE as readonly string[]).includes(cefr)) return
61  await $.store.set('estimates', [...(await loadEstimates($)), cefr].slice(-ESTIMATES_KEPT))
62}
63
64const currentLevel = async ($: EngineInterface, s: Settings): Promise<Level> => {
65  if (s.level !== 'auto') return s.level
66  const ranks = (await loadEstimates($)).map(c => SCALE.indexOf(c as never)).sort((a, b) => a - b)
67  if (ranks.length < ESTIMATES_NEEDED) return 'B1'
68  const median = SCALE[ranks[Math.floor(ranks.length / 2)] ?? 2] ?? 'B1'
69  return median === 'A1' ? 'A2' : median === 'C2' ? 'C1' : median
70}
71
72// "IELTS 7.5" → C1, "C1" → C1; null for a goal that names neither.
73const goalLevel = (goal: string): string | null => {
74  const cefr = goal.toUpperCase().match(/\b([ABC][12])\b/)
75  if (cefr?.[1]) return cefr[1]
76  const ielts = goal.match(/ielts\s*(\d+(?:\.\d)?)/i)
77  if (!ielts?.[1]) return null
78  const band = Number(ielts[1])
79  return band >= 8.5 ? 'C2' : band >= 7 ? 'C1' : band >= 5.5 ? 'B2' : band >= 4 ? 'B1' : 'A2'
80}
81
82const publishLevel = async ($: EngineInterface, s: Settings) => {
83  const samples = (await loadEstimates($)).length
84  const view: LevelView = {
85    isOn: s.isOn,
86    level: await currentLevel($, s),
87    isMeasuring: s.level === 'auto' && samples < ESTIMATES_NEEDED,
88    samples: Math.min(samples, ESTIMATES_NEEDED),
89    needed: ESTIMATES_NEEDED,
90    goal: s.goal,
91    goalLevel: goalLevel(s.goal),
92  }
93  await update($, levelView, () => view)
94}
95
96const levelLabel = async ($: EngineInterface, s: Settings) => {
97  const level = await currentLevel($, s)
98  if (s.level !== 'auto') return level
99  const n = (await loadEstimates($)).length
100  return n < ESTIMATES_NEEDED ? `${level}? (measuring)` : `~${level}`
101}
102
103const saveSettings = async ($: EngineInterface, s: Settings) => {
104  await $.store.set('settings', s)
105  await publishLevel($, s)
106}
107
108const isPerson = (origin: PromptOrigin) =>
109  origin.kind === 'composer' ||
110  origin.kind === 'bridge' ||
111  (origin.kind === 'plugin' && origin.asUser === true && origin.name !== 'english-coach')
112
113// Placeholders the box puts in for pasted images and long pastes.
114const PLACEHOLDERS = /\[(?:Image|Pasted text) #\d+[^\]]*\]/g
115
116// File references, whose Chinese must stay as it is: an @-mention (quoted when it holds spaces),
117// a quoted path, a path with spaces in it up to its file name, a bare file name.
118const FILE_REFS = [
119  /@"[^"\n]*"|@\S+/g,
120  /(["“'‘「])[^"”'’」\n]*[\/\\][^"”'’」\n]*["”'’」]/g,
121  /(?<![\p{L}\p{N}])(?:~|\.{1,2}|[A-Za-z]:)?[\/\\][^\n]*?\.[A-Za-z0-9]{1,8}(?![\p{L}\p{N}])/gu,
122  /[^\s"“”'‘’「」()()<>]+\.[A-Za-z0-9]{1,8}(?![\p{L}\p{N}])/gu,
123]
124
125// Code, inline code, URLs, file references, paths and placeholders are not the person's prose.
126const prose = (text: string) =>
127  FILE_REFS.reduce(
128    (t, re) => t.replace(re, ' '),
129    text
130      .replace(/```[\s\S]*?```/g, ' ')
131      .replace(/`[^`]*`/g, ' ')
132      .replace(PLACEHOLDERS, ' ')
133      .replace(/https?:\/\/\S+/g, ' '),
134  ).replace(/\S*[\/\\]\S*/g, ' ')
135
136// Quoted text is kept as it is, so Chinese in quotes alone does not make a message Chinese.
137const QUOTED = /"[^"\n]*"|“[^”\n]*”|「[^」\n]*」|『[^』\n]*』/g
138
139const hasChinese = (text: string) => /[㐀-鿿]/.test(prose(text).replace(QUOTED, ' '))
140
141const wordCount = (text: string) => (prose(text).match(/[A-Za-z]+(?:'[a-z]+)?/g) ?? []).length
142
143const isCheckable = (text: string) => wordCount(text) >= 3 && text.length <= 800
144
145type Piece = { text: string; kind: 'same' | 'del' | 'add' }
146
147const tokenize = (text: string) => text.match(/[\p{L}\p{N}'’-]+|[^\s\p{L}\p{N}]/gu) ?? []
148
149// Word diff of the person's text against the better one, by longest common subsequence.
150export const diffWords = (from: string, to: string): Piece[] => {
151  const a = tokenize(from)
152  const b = tokenize(to)
153  const lcs: number[][] = Array.from({ length: a.length + 1 }, () => new Array<number>(b.length + 1).fill(0))
154  for (let i = a.length - 1; i >= 0; i--)
155    for (let j = b.length - 1; j >= 0; j--)
156      lcs[i]![j] = a[i] === b[j] ? lcs[i + 1]![j + 1]! + 1 : Math.max(lcs[i + 1]![j]!, lcs[i]![j + 1]!)
157
158  const ops: { tok: string; kind: Piece['kind'] }[] = []
159  let i = 0
160  let j = 0
161  while (i < a.length || j < b.length) {
162    if (i < a.length && j < b.length && a[i] === b[j]) ops.push({ tok: a[i++]!, kind: 'same' }), j++
163    else if (j < b.length && (i === a.length || lcs[i]![j + 1]! >= lcs[i + 1]![j]!)) ops.push({ tok: b[j++]!, kind: 'add' })
164    else ops.push({ tok: a[i++]!, kind: 'del' })
165  }
166
167  // Each run of changes is drawn whole: what goes first, then what replaces it.
168  const ordered: typeof ops = []
169  let run: typeof ops = []
170  const flush = () => {
171    ordered.push(...run.filter(o => o.kind === 'del'), ...run.filter(o => o.kind === 'add'))
172    run = []
173  }
174  for (const o of ops) {
175    if (o.kind === 'same') flush(), ordered.push(o)
176    else run.push(o)
177  }
178  flush()
179
180  const pieces: Piece[] = []
181  ordered.forEach(({ tok, kind }, k) => {
182    const text = k === 0 || /^[,.!?;:)\]}%’]/.test(tok) ? tok : ` ${tok}`
183    const last = pieces.at(-1)
184    if (last?.kind === kind) last.text += text
185    else pieces.push({ text, kind })
186  })
187  return pieces
188}
189
190const parseJson = (text: string): Record<string, unknown> | null => {
191  const start = text.indexOf('{')
192  const end = text.lastIndexOf('}')
193  if (start < 0 || end <= start) return null
194  try {
195    return JSON.parse(text.slice(start, end + 1))
196  } catch {
197    return null
198  }
199}
200
201const ask = async ($: EngineInterface, system: string, prompt: string, timeoutMs = 20_000) => {
202  const r = await $.model.complete({ model: 'haiku', system, prompt, effort: 'low', maxTokens: 800, timeoutMs })
203  return r.isAnswered ? parseJson(r.text) : null
204}
205
206const translate = async ($: EngineInterface, text: string, level: Level) => {
207  const json = await ask(
208    $,
209    `You turn a learner's message, written in Chinese or mixed Chinese and English, into the English they meant to write. ` +
210      `Write natural, plain English a CEFR ${level} learner can read. Keep code, commands, identifiers, file paths, URLs and quoted text exactly as they are. ` +
211      `Keep the intent and tone; do not answer the message. ` +
212      `Reply with JSON only: {"english": "<the message in English>", "phrases": [{"zh": "<Chinese phrase from the message>", "en": "<its English in your version>"}]} ` +
213      `with up to 4 phrases worth learning.`,
214    text,
215  )
216  if (!json || typeof json.english !== 'string' || !json.english.trim()) return null
217  const phrases: Phrase[] = Array.isArray(json.phrases)
218    ? json.phrases
219        .filter((p: any) => typeof p?.zh === 'string' && typeof p?.en === 'string')
220        .slice(0, 4)
221        .map((p: any) => ({ zh: p.zh, en: p.en }))
222    : []
223  return { english: json.english.trim(), phrases }
224}
225
226// The end of Claude's last reply: what the person's message answers.
227const lastReply = async ($: EngineInterface) => {
228  try {
229    const messages = await $.session.messages()
230    const reply = [...messages].reverse().find(m => m.role === 'assistant' && m.text.trim() !== '')
231    return reply?.text.slice(-1500) ?? ''
232  } catch {
233    return ''
234  }
235}
236
237// Words that say who does what: a fix must not change them.
238const PERSONS = /\b(i|me|my|mine|you|your|yours|we|us|our|ours|he|him|his|she|her|they|them|their)\b/gi
239const persons = (t: string) => (t.match(PERSONS) ?? []).map(w => w.toLowerCase()).join(' ')
240// What a fix must change beyond casing and punctuation; an apostrophe is spelling (dont → don't).
241const bare = (t: string) => t.toLowerCase().replace(/’/g, "'").replace(/[\s.,!?;:"]/g, '')
242
243export type Fix = { wrong: string; right: string; tip: string }
244
245// The model's fixes the mod trusts: each a real error, quoted exactly, changing more
246// than casing or punctuation and never who does what. Applied left to right, no overlaps.
247export const applyFixes = (text: string, raw: unknown) => {
248  const str = (v: unknown) => (typeof v === 'string' ? v : '')
249  const candidates = (Array.isArray(raw) ? raw : [])
250    .map((f: any) => ({ wrong: str(f?.wrong), right: str(f?.right), tip: str(f?.tip).trim(), type: str(f?.type).toLowerCase() }))
251    .filter(f => f.wrong.trim() !== '' && f.type !== 'style' && text.includes(f.wrong))
252    .filter(f => bare(f.wrong) !== bare(f.right) && persons(f.wrong) === persons(f.right))
253    .map(f => ({ ...f, at: text.indexOf(f.wrong) }))
254    .sort((x, y) => x.at - y.at)
255
256  const fixes: Fix[] = []
257  let better = ''
258  let from = 0
259  for (const f of candidates) {
260    if (f.at < from) continue
261    better += text.slice(from, f.at) + f.right
262    from = f.at + f.wrong.length
263    fixes.push({ wrong: f.wrong, right: f.right, tip: f.tip })
264  }
265  return { better: better + text.slice(from), fixes }
266}
267
268const check = async ($: EngineInterface, text: string, s: Settings, level: Level, timeoutMs?: number) => {
269  const context = await lastReply($)
270  const message = text.replace(PLACEHOLDERS, '').trim()
271  const json = await ask(
272    $,
273    `You check the English of a message a Chinese-speaking learner (around CEFR ${level}, goal ${s.goal}) is about to send to an AI assistant, Claude. ` +
274      `In it "you" is Claude and "I" is the learner. Ignore code, paths and commands. Claude's previous reply may be shown so you know what they mean; never judge it. ` +
275      `List only real errors: wrong grammar, a wrong word, a misspelling, or a collocation a native reader would stumble on. ` +
276      `Do not list what is merely less elegant, casing, punctuation or a missing final period. If the message reads fine, list nothing. ` +
277      `For each error: "wrong" is the shortest span copied character for character from the message, "right" is that span corrected with the smallest change, ` +
278      `keeping the meaning and who does what; "type" is grammar, word, spelling or collocation; "tip" says why in Simplified Chinese, under 30 characters, and must be true of this message. ` +
279      `Separately, give one "upgrade": a more precise or higher-level word, collocation or structure a ${s.goal} candidate would use for part of the message, written "plain → better" (empty if nothing fits). ` +
280      `Estimate the CEFR level (A1, A2, B1, B2, C1 or C2) the message shows. ` +
281      `Reply with JSON only: {"errors": [{"wrong": "<exact span>", "right": "<fix>", "type": "<type>", "tip": "<中文>"}], "upgrade": "<plain → better, or empty>", "cefr": "<level>"}`,
282    (context ? `Claude's previous reply (context only):\n"""\n${context}\n"""\n\n` : '') +
283      `The learner's message to check:\n"""\n${message}\n"""`,
284    timeoutMs,
285  )
286  if (!json || !Array.isArray(json.errors)) return null
287  const { better, fixes } = applyFixes(text, json.errors)
288  return {
289    isNatural: fixes.length === 0,
290    better: fixes.length === 0 ? '' : better,
291    tips: fixes.map(f => f.tip).filter(Boolean).slice(0, 3),
292    upgrade: typeof json.upgrade === 'string' ? json.upgrade.trim() : '',
293    cefr: typeof json.cefr === 'string' ? json.cefr.trim().toUpperCase() : '',
294  }
295}
296
297// Only the language Claude writes in: everything else the mod does after the reply.
298const systemSection = () =>
299  [
300    `# English`,
301    `Write every reply in English, even when the person writes in Chinese. Code, commands and quoted text stay as they are.`,
302  ].join('\n')
303
304const pickGlosses = async ($: EngineInterface, text: string, level: Level, s: Settings, known: string[]): Promise<Gloss[]> => {
305  const json = await ask(
306    $,
307    `You help a Chinese-speaking English learner, around CEFR ${level} and aiming for ${s.goal}, read an English reply. ` +
308      `Pick up to ${GLOSSES_PER_BLOCK} words or phrases in it that are likely above ${level} and worth learning: rare words, idioms, phrasal verbs, collocations, technical terms whose meaning is not obvious. ` +
309      `Copy each term exactly as it appears in the text, outside code. Skip code identifiers, file names, commands, product names` +
310      (known.length ? `, and these terms the learner has already seen glossed: ${known.join(', ')}` : '') +
311      `. Give each a short Simplified Chinese gloss of its meaning here, 2 to 8 characters. ` +
312      `Reply with JSON only: {"glosses": [{"term": "<exact text>", "zh": "<释义>"}]}`,
313    text.slice(0, 6000),
314  )
315  if (!json || !Array.isArray(json.glosses)) return []
316  return json.glosses
317    .filter((g: any) => typeof g?.term === 'string' && typeof g?.zh === 'string' && g.term.trim() && g.zh.trim())
318    .slice(0, GLOSSES_PER_BLOCK)
319    .map((g: any) => ({ term: g.term.trim(), zh: g.zh.trim() }))
320}
321
322const escapeRegExp = (s: string) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
323
324// Puts "term(释义)" after the first use of each term, outside code, links and URLs.
325const applyGlosses = (markdown: string, glosses: Gloss[]) => {
326  const parts = markdown.split(/(```[\s\S]*?```|`[^`\n]*`|\]\([^)]*\)|https?:\/\/\S+)/)
327  const done = new Set<string>()
328  return parts
329    .map((part, i) => {
330      if (i % 2 === 1) return part
331      let out = part
332      for (const g of glosses) {
333        const key = g.term.toLowerCase()
334        if (done.has(key)) continue
335        const re = new RegExp(`(?<![\\p{L}\\p{N}])(${escapeRegExp(g.term)})(?![\\p{L}\\p{N}(])`, 'iu')
336        if (!re.test(out)) continue
337        done.add(key)
338        out = out.replace(re, `$1(${g.zh})`)
339      }
340      return out
341    })
342    .join('')
343}
344
345// /zh keeps at most this many replies translated, and translates this many paragraphs at once.
346const ZH_KEPT = 20
347const ZH_AT_ONCE = 4
348
349const FENCE = /^\s*(```|~~~)/
350
351// A reply's paragraphs: blank lines part them, and a code block, blank lines and all, is one.
352export const paragraphs = (text: string) => {
353  const out: string[] = []
354  let lines: string[] = []
355  let isInCode = false
356  const end = () => {
357    const p = lines.join('\n').trim()
358    if (p) out.push(p)
359    lines = []
360  }
361  for (const line of text.split('\n')) {
362    if (FENCE.test(line)) {
363      if (!isInCode) end()
364      lines.push(line)
365      isInCode = !isInCode
366      if (!isInCode) end()
367    } else if (!isInCode && line.trim() === '') end()
368    else lines.push(line)
369  }
370  end()
371  return out
372}
373
374const isCode = (para: string) => FENCE.test(para)
375
376// Claude's replies, oldest first: what it wrote after each of the person's prompts, tool output left out.
377export const repliesOf = (messages: readonly SessionMessage[]) => {
378  const out: string[] = []
379  let texts: string[] = []
380  const end = () => {
381    if (texts.length) out.push(texts.join('\n\n'))
382    texts = []
383  }
384  for (const m of messages) {
385    if (m.role === 'user' && !m.toolResults?.length) end()
386    else if (m.role === 'assistant' && m.text.trim()) texts.push(m.text)
387  }
388  end()
389  return out
390}
391
392const sameReply = (t: { paras: string[] }, paras: string[]) => t.paras.length === paras.length && t.paras.every((p, i) => p === paras[i])
393
394const translatePara = async ($: EngineInterface, para: string, before: string) => {
395  const r = await $.model.complete({
396    model: 'haiku',
397    system:
398      `You translate a paragraph of a reply that Claude, an AI coding assistant, wrote to a Chinese-speaking developer, into natural Simplified Chinese. ` +
399      `Translate all of it faithfully: never summarize, add or leave out anything. ` +
400      `Keep markdown (lists, bold, headings, tables), inline code, file paths, commands, identifiers and URLs exactly as they are. ` +
401      `Give a technical term as its usual Chinese term with the English in full-width brackets the first time it appears, e.g. 竞态条件(race condition); keep product names in English. ` +
402      `Reply with the translation only.`,
403    prompt: (before ? `The paragraph before it, for context only:\n"""\n${before}\n"""\n\n` : '') + `Translate this paragraph:\n"""\n${para}\n"""`,
404    effort: 'low',
405    maxTokens: 2000,
406    timeoutMs: 30_000,
407  })
408  if (!r.isAnswered) return null
409  return r.text.trim().replace(/^"""\s*|\s*"""$/g, '').trim() || null
410}
411
412// Paragraphs Haiku is translating now, so a second /zh does not ask for them again.
413const translating = new Set<string>()
414
415// Translates the paragraphs of a reply that have no Chinese yet, a few at a time, top first.
416const translateMissing = async ($: EngineInterface, paras: string[]) => {
417  const entry = (await read($, translations)).find(t => sameReply(t, paras))
418  if (!entry) return
419  const todo = entry.zh.flatMap((zh, i) => (zh === null && !translating.has(paras[i]!) ? [i] : []))
420  todo.forEach(i => translating.add(paras[i]!))
421  let k = 0
422  const work = async () => {
423    while (k < todo.length) {
424      const i = todo[k++]!
425      const zh = await translatePara($, paras[i]!, paras[i - 1] ?? '')
426      translating.delete(paras[i]!)
427      await update($, translations, list =>
428        list.map(t => (sameReply(t, paras) ? { ...t, zh: t.zh.map((was, j) => (j === i ? (zh ?? false) : was)) } : t)),
429      )
430    }
431  }
432  await Promise.all(Array.from({ length: ZH_AT_ONCE }, () => work()))
433}
434
435// The Chinese drawn under a reply block: its paragraphs' translations, from a reply /zh shows.
436const chineseFor = (list: readonly ReplyTranslation[], text: string): string | null => {
437  const paras = paragraphs(text)
438  if (paras.length === 0) return null
439  for (const t of [...list].reverse()) {
440    if (!t.isShown) continue
441    const at = paras.map(p => t.paras.indexOf(p))
442    if (at.some(i => i < 0)) continue
443    return at
444      .map(i => {
445        const zh = t.zh[i]
446        return zh === '' ? '〔代码见上〕' : zh === null ? '…' : zh === false ? '(这一段没翻译成功,再输入 /zh 重试)' : zh
447      })
448      .join('\n\n')
449  }
450  return null
451}
452
453// A reply this long, in English words outside code, gets key points under it; this many replies are kept.
454const POINTS_MIN_WORDS = 150
455const POINTS_KEPT = 20
456
457const makePoints = async ($: EngineInterface, reply: string) => {
458  // What was done comes first in a reply and the question last, so a very long one keeps both ends.
459  const text = reply.length > 12_000 ? `${reply.slice(0, 3_000)}\n\n[…]\n\n${reply.slice(-9_000)}` : reply
460  const json = await ask(
461    $,
462    `You help a Chinese-speaking developer, who reads long English slowly, follow a reply that Claude, an AI coding assistant, wrote to them. ` +
463      `Give the reply's key points in Simplified Chinese, so they know what it says before reading it all. ` +
464      `"did": what Claude did in this turn (files changed, commands run, tests and their results), in one sentence; empty if it only explained or answered. ` +
465      `"point": the reply's main conclusion, answer or recommendation, in one sentence. ` +
466      `"ask": the question Claude asks them, or the decision or action it needs from them, in one sentence; empty if the reply asks nothing, and never make one up. ` +
467      `Each one short sentence under 50 characters: only what matters most, plain text, no markdown. Keep file names, commands, identifiers and numbers as they are, and technical terms in English where a Chinese developer would. ` +
468      `Say only what the reply says. Reply with JSON only: {"did": "<中文>", "point": "<中文>", "ask": "<中文>"}`,
469    `The reply:\n"""\n${text}\n"""`,
470    30_000,
471  )
472  const str = (v: unknown) => (typeof v === 'string' ? v.trim() : '')
473  const points = { did: str(json?.did), point: str(json?.point), ask: str(json?.ask) }
474  return points.did || points.point || points.ask ? points : null
475}
476
477// Key points for Claude's last reply, if it is long and has none yet.
478const pointLastReply = async ($: EngineInterface) => {
479  const s = await loadSettings($)
480  if (!s.isOn || !s.points) return
481  const reply = repliesOf(await $.session.messages()).at(-1)
482  if (reply === undefined || wordCount(reply) < POINTS_MIN_WORDS) return
483  const paras = paragraphs(reply)
484  if ((await read($, keyPoints)).some(p => sameReply(p, paras))) return
485  await update($, keyPoints, all => [...all, { paras, points: null }].slice(-POINTS_KEPT))
486  const points = await makePoints($, reply)
487  // Nothing is drawn for a reply Haiku could not read.
488  await update($, keyPoints, all =>
489    points ? all.map(p => (sameReply(p, paras) ? { ...p, points } : p)) : all.filter(p => !sameReply(p, paras)),
490  )
491}
492
493// The key points drawn under a reply block: those of the reply the block ends.
494const pointsFor = (list: readonly ReplyPoints[], text: string) => {
495  const paras = paragraphs(text)
496  const last = paras.at(-1)
497  return [...list].reverse().find(p => p.paras.at(-1) === last && paras.every(q => p.paras.includes(q)))
498}
499
500// What goes under a reply, as markdown added to its text: the desktop draws a reply as its text alone
501// in places, where a tree of ours would be dropped.
502const quoted = (markdown: string) => markdown.split('\n').map(line => (line ? `> ${line}` : '>')).join('\n')
503
504const zhMarkdown = (zh: string) => quoted(`**中文** · /zh hides it\n\n${zh}`)
505
506const pointsMarkdown = (p: ReplyPoints['points']) => {
507  const rows = p ? [p.did && `- **做了** ${p.did}`, p.point && `- **结论** ${p.point}`, p.ask && `- **问你 ${p.ask}**`] : ['…']
508  return quoted(['**要点** · /zh 看全文中文', ...rows.filter(Boolean)].join('\n'))
509}
510
511const HELP = async ($: EngineInterface, s: Settings) =>
512  [
513    `English coach is ${s.isOn ? 'on' : 'off'} · level ${await levelLabel($, s)} · goal ${s.goal} · glosses ${s.gloss ? 'on' : 'off'} · key points ${s.points ? 'on' : 'off'} · Chinese input: ${s.chinese} · feedback ${s.checkWhen}`,
514    ``,
515    `/english on | off              turn the mode on or off`,
516    `/english level auto            measure your level from what you write (default)`,
517    `/english level A2|B1|B2|C1     fix the level of Claude's English`,
518    `/english goal <text>           your target, e.g. IELTS 7.5`,
519    `/english gloss on|off          Chinese glosses after hard words`,
520    `/english points on|off         key points in Chinese under Claude's long replies`,
521    `/english chinese review        Chinese input becomes an English draft in the box for you to check (default)`,
522    `/english chinese auto          Chinese input is translated and sent at once`,
523    `/english chinese off           Chinese input is sent as typed`,
524    `/english feedback before       check your English when you press Enter; the fix goes in the box (default)`,
525    `/english feedback after        send at once, show the feedback afterwards`,
526    `/english feedback off          no feedback on your English`,
527    `/english demo                  show a sample feedback card`,
528    `/en <text>                     turn Chinese or rough English into an English draft in the box`,
529    `/zh                            Chinese translation of Claude's last reply, under it; again hides it (/zh 2: the reply before)`,
530    `Start a prompt with "${RAW_PREFIX}" to send it as typed.`,
531  ].join('\n')
532
533const DEMO: Feedback = {
534  kind: 'checked',
535  isNatural: false,
536  original: 'The 135 score is in college entrance exam, and i made a mistake. The suggestions only shows when the message is send.',
537  better: 'The 135 score is from the college entrance exam, and I made a mistake. The suggestions only appear when the message is sent.',
538  tips: ['表示来源用 from,不用 in', 'suggestions 是复数,动词用 appear', '被动语态:is sent,不是 is send'],
539  upgrade: 'only appear when → only show up once',
540  isHeld: true,
541}
542
543const applyArgs = (s: Settings, args: string): Settings | string => {
544  const trimmed = args.trim()
545  const [key = '', value = ''] = trimmed.toLowerCase().split(/\s+/)
546  const flag = value === 'on' ? true : value === 'off' ? false : undefined
547  if (key === 'on' || key === 'off') return { ...s, isOn: key === 'on' }
548  if (key === 'level') {
549    if (value === 'auto') return { ...s, level: 'auto' }
550    const level = value.toUpperCase() as Level
551    return LEVELS.includes(level) ? { ...s, level } : `Level must be auto or one of ${LEVELS.join(', ')}.`
552  }
553  if (key === 'goal') {
554    const goal = trimmed.slice(4).trim()
555    return goal ? { ...s, goal } : 'Give a goal, e.g. /english goal IELTS 7.5'
556  }
557  if (key === 'gloss' && flag !== undefined) return { ...s, gloss: flag }
558  if (key === 'points' && flag !== undefined) return { ...s, points: flag }
559  if (key === 'feedback') {
560    const when = value === 'on' ? 'before' : value
561    if (when === 'before' || when === 'after' || when === 'off') return { ...s, checkWhen: when }
562  }
563  if (key === 'chinese' && (value === 'review' || value === 'auto' || value === 'off')) return { ...s, chinese: value }
564  return `Unknown option "${trimmed}".`
565}
566
567// Reply blocks drawn, newest last, with their latest text; and terms already glossed.
568const seen = new Map<string, string>()
569const glossedTerms = new Set<string>()
570
571const glossNewBlocks = async ($: EngineInterface) => {
572  const s = await loadSettings($)
573  if (!s.isOn || !s.gloss) return
574  const level = await currentLevel($, s)
575  const made = await read($, replyGlosses)
576  const todo = [...seen].filter(([id, text]) => made[id]?.text !== text && text.trim().length >= 40).slice(-BLOCKS_PER_TURN)
577  for (const [id, text] of todo) {
578    const glosses = await pickGlosses($, text, level, s, [...glossedTerms].slice(-100))
579    glosses.forEach(g => glossedTerms.add(g.term.toLowerCase()))
580    await update($, replyGlosses, all => {
581      const next = { ...all, [id]: { text, glosses } }
582      const ids = Object.keys(next)
583      for (const old of ids.slice(0, Math.max(0, ids.length - GLOSSED_KEPT))) delete next[old]
584      return next
585    })
586  }
587}
588
589// Hides the card later, unless another one has taken its place by then.
590const hideLater = ($: EngineInterface, card: Feedback, ms: number) => {
591  const was = JSON.stringify(card)
592  $.clock.after(ms, () => void update($, feedback, shown => (JSON.stringify(shown) === was ? null : shown)))
593}
594
595// The key that swaps a held message between the fix and the person's own: the engine keeps
596// Tab and the arrows, so a mod sees only typed characters. Backtick, by Tab; Chinese input
597// methods type that key as "·", "、" or a full-width "`".
598const SWAP_KEY = '`'
599const SWAP_TYPED = new Set([SWAP_KEY, '·', '、', '`'])
600const isSwap = (typed: string) => SWAP_TYPED.has(typed)
601
602// A message waiting in the box, a held fix or an English draft: the version in the box now,
603// the one a swap puts there, and the card once swapped.
604type Waiting = { now: string; other: string; swapped: Feedback }
605
606const waiting = (fb: Feedback | null): Waiting | null => {
607  if (fb?.kind === 'checked' && fb.isHeld) {
608    const isFix = fb.inBox === 'better'
609    return { now: isFix ? fb.better : fb.original, other: isFix ? fb.original : fb.better, swapped: { ...fb, inBox: isFix ? 'original' : 'better' } }
610  }
611  if (fb?.kind === 'translated' && fb.inBox) {
612    const isEnglish = fb.inBox === 'english'
613    return { now: isEnglish ? fb.english : fb.original, other: isEnglish ? fb.original : fb.english, swapped: { ...fb, inBox: isEnglish ? 'chinese' : 'english' } }
614  }
615  return null
616}
617
618// The card once its message is sent: nothing waits on it any more.
619const settled = (fb: Feedback): Feedback =>
620  fb.kind === 'checked'
621    ? { ...fb, isHeld: false }
622    : fb.kind === 'translated'
623      ? { kind: 'translated', original: fb.original, english: fb.english, phrases: fb.phrases }
624      : fb
625
626// Turns the card of a waiting message to its other version; returns that version's text for the box.
627const swapCard = async ($: EngineInterface, w: Waiting) => {
628  await update($, feedback, shown => waiting(shown)?.swapped ?? shown)
629  return w.other
630}
631
632// The card's button: the other version into the box, whatever the box has now. Returns it, or null.
633const swapBox = async ($: EngineInterface) => {
634  const w = waiting(await read($, feedback))
635  if (w === null) return null
636  const text = await swapCard($, w)
637  await $.prompt.fill({ text })
638  return text
639}
640
641// An English draft into the box, its card waiting on it until something is sent.
642const showDraft = async ($: EngineInterface, original: string, t: { english: string; phrases: Phrase[] }) => {
643  await update($, feedback, (): Feedback => ({ kind: 'translated', original, ...t, inBox: 'english' }))
644  $.clock.after(50, () => void $.prompt.fill({ text: t.english }))
645}
646
647export const register: Register = on => {
648  // The text a waiting message has in the box: Enter on it sends it as it is.
649  let held: string | null = null
650  on('session.start', async ($, e, next) => {
651    await $.command.register({
652      name: 'english',
653      description: 'English coach: show or change its settings',
654      argumentHint: '[on|off|level auto|goal IELTS 7.5|gloss on|chinese review|feedback before|demo]',
655    })
656    await $.command.register({
657      name: 'en',
658      description: 'Turn Chinese or rough English into an English draft in the prompt box',
659      argumentHint: '<text>',
660    })
661    await $.command.register({
662      name: 'zh',
663      description: "Chinese translation of Claude's last reply, drawn under it for you alone; again hides it",
664      argumentHint: '[2 for the reply before, 3, …]',
665    })
666    // The level is drawn under the prompt now; clear the status line of earlier versions.
667    $.ui.status(undefined)
668    await publishLevel($, await loadSettings($))
669    return next(e)
670  })
671
672  on('command.run', { command: 'english' }, async ($, e) => {
673    const s = await loadSettings($)
674    if (!e.args.trim()) return { text: await HELP($, s) }
675    if (e.args.trim().toLowerCase() === 'demo') {
676      await update($, feedback, () => DEMO)
677      return { text: 'A sample feedback card is above the prompt. Press ✕ to close it.' }
678    }
679    const changed = applyArgs(s, e.args)
680    if (typeof changed === 'string') return { text: `${changed}\n\n${await HELP($, s)}` }
681    await saveSettings($, changed)
682    if (!changed.isOn) await update($, feedback, () => null)
683    // Settings are not state a drawn reply follows, so points already drawn go with the points made.
684    if (!changed.isOn || !changed.points) await update($, keyPoints, () => [])
685    return { text: (await HELP($, changed)).split('\n')[0] ?? '' }
686  })
687
688  on('command.run', { command: 'en' }, async ($, e) => {
689    const text = e.args.trim()
690    if (!text) return { text: 'Usage: /en <Chinese or rough English>' }
691    const s = await loadSettings($)
692    const t = await translate($, text, await currentLevel($, s))
693    if (!t) return { text: 'Could not make an English draft just now. Try again.' }
694    held = t.english
695    await showDraft($, text, t)
696    return { text: 'English draft is in the prompt box: edit it, then press Enter.' }
697  })
698
699  // The translation is drawn under the reply, never printed as the command's output, which can go into what Claude reads.
700  on('command.run', { command: 'zh' }, async ($, e) => {
701    const arg = e.args.trim()
702    const back = arg === '' ? 1 : Number(arg)
703    if (!Number.isInteger(back) || back < 1) return { text: 'Usage: /zh, or /zh 2 for the reply before the last.' }
704    const reply = repliesOf(await $.session.messages()).at(-back)
705    if (reply === undefined) return { text: 'No reply from Claude to translate yet.' }
706
707    const paras = paragraphs(reply)
708    const list = await read($, translations)
709    const found = list.find(t => sameReply(t, paras))
710    if (found?.isShown && !found.zh.includes(false)) {
711      await update($, translations, all => all.map(t => (sameReply(t, paras) ? { ...t, isShown: false } : t)))
712      return {}
713    }
714    // Paragraphs translated before, in this reply or another, are not asked for again; failed ones are.
715    const known = new Map<string, string>()
716    for (const t of list)
717      t.paras.forEach((p, i) => {
718        const zh = t.zh[i]
719        if (typeof zh === 'string' && zh !== '') known.set(p, zh)
720      })
721    const entry: ReplyTranslation = { paras, zh: paras.map(p => (isCode(p) ? '' : (known.get(p) ?? null))), isShown: true }
722    await update($, translations, all => [...all.filter(t => !sameReply(t, paras)), entry].slice(-ZH_KEPT))
723    $.clock.after(0, () => void translateMissing($, paras))
724    return {}
725  })
726
727  on('prompt.compose', async ($, e, next) => {
728    const composed = await next(e)
729    const s = await loadSettings($)
730    if (!s.isOn) return composed
731    const section = { id: 'english-coach:mode', text: systemSection(), scope: 'session' as const }
732    return { sections: [...composed.sections, section] }
733  })
734
735  on('prompt.submit', async ($, e, next) => {
736    if (e.command || e.isMeta || !isPerson(e.origin)) return next(e)
737    const s = await loadSettings($)
738    if (!s.isOn) return next(e)
739
740    // Anything sent settles a message waiting in the box; Enter on it as it was put there sends it
741    // as it is: a fix, the person's own, an English draft or their Chinese.
742    const shown = await read($, feedback)
743    if (shown !== null && waiting(shown) !== null) {
744      const card = settled(shown)
745      await update($, feedback, () => card)
746      hideLater($, card, HIDE_CHECKED_MS)
747    }
748    const wasHeld = held
749    held = null
750    if (wasHeld !== null && e.text.trim() === wasHeld.trim()) return next(e)
751
752    if (e.text.startsWith(RAW_PREFIX)) return next({ ...e, text: e.text.slice(RAW_PREFIX.length).trimStart() })
753
754    const level = await currentLevel($, s)
755
756    if (s.chinese !== 'off' && hasChinese(e.text)) {
757      const t = await translate($, e.text, level)
758      if (!t) {
759        $.ui.toast('English coach: translation failed, sent as typed.')
760        return next(e)
761      }
762      if (s.chinese === 'auto') {
763        const card: Feedback = { kind: 'translated', original: e.text, ...t }
764        await update($, feedback, () => card)
765        hideLater($, card, HIDE_DRAFT_MS)
766        return next({ ...e, text: t.english })
767      }
768      held = t.english
769      await showDraft($, e.text, t)
770      return { drop: `Not sent: your English draft is in the box. Enter sends it; ${SWAP_KEY} or ↩ 中文 on the card brings your Chinese back.` }
771    }
772
773    if (s.checkWhen === 'off' || !isCheckable(e.text)) return next(e)
774
775    const original = e.text
776    const record = async (r: Awaited<ReturnType<typeof check>>, isHeld: boolean) => {
777      if (r && wordCount(original) >= WORDS_TO_ESTIMATE) {
778        await addEstimate($, r.cefr)
779        await publishLevel($, s)
780      }
781      const card: Feedback | null = r
782        ? {
783            kind: 'checked',
784            original,
785            isNatural: r.isNatural,
786            better: r.better,
787            tips: r.tips,
788            upgrade: r.upgrade,
789            isHeld,
790            ...(isHeld ? { inBox: 'better' as const } : {}),
791          }
792        : null
793      await update($, feedback, shown => (shown?.original !== original ? shown : card))
794      if (card && !isHeld) hideLater($, card, HIDE_CHECKED_MS)
795    }
796
797    // A message with images is never held: filling the box again would lose them.
798    if (s.checkWhen === 'after' || (e.attachments?.length ?? 0) > 0) {
799      await update($, feedback, (): Feedback => ({ kind: 'pending', original }))
800      // Off the dispatch, so the turn is not held up by the check.
801      $.clock.after(0, async () => record(await check($, original, s, level), false))
802      return next(e)
803    }
804
805    await update($, feedback, (): Feedback => ({ kind: 'pending', original }))
806    const r = await check($, original, s, level, HOLD_TIMEOUT_MS)
807    const isHeld = r !== null && !r.isNatural && r.better !== '' && r.better.trim() !== original.trim()
808    await record(r, isHeld)
809    if (!isHeld) return next(e)
810
811    // The fix goes straight into the box, as a Chinese draft does.
812    const fixed = r.better
813    held = fixed
814    $.clock.after(50, () => void $.prompt.fill({ text: fixed }))
815    return { drop: `Not sent yet: the corrected message is in the box. Enter sends it; ${SWAP_KEY} or ↩ Mine on the card brings yours back.` }
816  })
817
818  // The swap key on an untouched waiting message trades its versions; Enter sends either as it is.
819  // In the person's Chinese, · and 、 are punctuation they may be typing: there only the button swaps.
820  on('prompt.edit', async ($, e, next) => {
821    if (!isSwap(e.inputText) || e.start !== e.end) return next(e)
822    const fb = await read($, feedback)
823    const w = waiting(fb)
824    if (w === null || e.text.trim() !== w.now.trim() || (fb?.kind === 'translated' && fb.inBox === 'chinese')) return next(e)
825    const text = await swapCard($, w)
826    held = text
827    return { text, cursor: text.length }
828  })
829
830  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
831    const fb = await read($, feedback)
832    if (e.props.hasSurvey || fb === null) return next(e)
833
834    const { Box, Button, Text } = $.ui.resolve(e)
835    const hide = <Button key="hide" plain label="✕" onPress={() => update($, feedback, () => null)} />
836
837    // A click swaps too: some input methods type the swap key as punctuation the person wants.
838    const card = (color: string, title: string, hint: string, swapLabel: string, ...body: RenderChildren[]) => (
839      <Box key="card" flexDirection="column" borderStyle="round" borderColor={color} paddingX={1}>
840        <Box justifyContent="space-between">
841          <Text>
842            <Text color={color} bold>
843              {title}
844            </Text>
845            <Text dimColor>{hint ? `   ${hint}` : ''}</Text>
846          </Text>
847          <Box gap={1}>
848            {swapLabel ? (
849              <Button
850                key="swap"
851                label={swapLabel}
852                onPress={async () => {
853                  const text = await swapBox($)
854                  if (text !== null) held = text
855                }}
856              />
857            ) : null}
858            {hide}
859          </Box>
860        </Box>
861        {body.filter(Boolean)}
862      </Box>
863    )
864
865    if (fb.kind === 'pending') {
866      return <Text dimColor>✎ Checking your English…</Text>
867    }
868
869    if (fb.kind === 'translated') {
870      return card(
871        'cyan',
872        '中 → EN',
873        fb.inBox === 'english'
874          ? `Your English draft is in the box: edit it, then Enter · ${SWAP_KEY} back to your Chinese`
875          : fb.inBox === 'chinese'
876            ? 'Your Chinese is back: Enter sends it as typed, or edit it for a new draft'
877            : 'Sent in English',
878        fb.inBox === 'english' ? '↩ 中文' : fb.inBox === 'chinese' ? '→ English' : '',
879        fb.phrases.length > 0 && (
880          <Box key="phrases" flexDirection="column">
881            {fb.phrases.map(p => (
882              <Text>
883                <Text dimColor>• </Text>
884                {p.zh}
885                <Text dimColor> → </Text>
886                <Text color="cyan">{p.en}</Text>
887              </Text>
888            ))}
889          </Box>
890        ),
891      )
892    }
893
894    const upgrade = fb.upgrade !== '' && (
895      <Text key="upgrade">
896        <Text color="magenta" bold>
897          ↑{' '}
898        </Text>
899        {fb.upgrade}
900      </Text>
901    )
902
903    // All good: one line, no border.
904    if (fb.isNatural) {
905      return (
906        <Box key="natural" justifyContent="space-between">
907          <Text>
908            <Text color="green" bold>
909              ✓ Natural English
910            </Text>
911            {upgrade ? <Text dimColor>{'   '}</Text> : ''}
912            {upgrade}
913          </Text>
914          {hide}
915        </Box>
916      )
917    }
918
919    return card(
920      'yellow',
921      fb.isHeld && fb.inBox === 'better' ? '✎ Fixed in the box' : '✎ Almost there',
922      !fb.isHeld ? '' : fb.inBox === 'better' ? `Enter send it · ${SWAP_KEY} back to yours` : `${SWAP_KEY} use the fix · Enter send yours as is`,
923      !fb.isHeld ? '' : fb.inBox === 'better' ? '↩ Mine' : '✎ The fix',
924      <Box key="diff">
925        <Text>
926          {diffWords(fb.original, fb.better).map(p =>
927            p.kind === 'same' ? (
928              p.text
929            ) : p.kind === 'del' ? (
930              <Text color="red" strikethrough>
931                {p.text}
932              </Text>
933            ) : (
934              <Text color="green" bold>
935                {p.text}
936              </Text>
937            ),
938          )}
939        </Text>
940      </Box>,
941      fb.tips.length > 0 && (
942        <Box key="tips" flexDirection="column">
943          {fb.tips.map((tip, i) => (
944            <Text>
945              {i === 0 ? '💡 ' : '   '}
946              {fb.tips.length > 1 ? <Text dimColor>{i + 1}. </Text> : ''}
947              {tip}
948            </Text>
949          ))}
950        </Box>
951      ),
952      upgrade,
953    )
954  })
955
956  // Glosses and key points are made once the turn's reply is whole, off the dispatch.
957  on('turn.complete', async ($, e, next) => {
958    const done = await next(e)
959    if (e.agentId === undefined) $.clock.after(300, () => void Promise.all([glossNewBlocks($), e.isAborted ? null : pointLastReply($)]))
960    return done
961  })
962
963  // Draws a reply with its glosses and, under it, its Chinese after /zh or else the key points of a long one:
964  // a tree on the terminal, markdown added to the drawn text elsewhere. The stored reply, which Claude reads, is unchanged.
965  on('ui.render', { component: 'AssistantMessage' }, async ($, e, next) => {
966    if (e.props.isSummary) return next(e)
967    seen.delete(e.requestId)
968    seen.set(e.requestId, e.props.text)
969    if (seen.size > 200) seen.delete(seen.keys().next().value!)
970
971    const s = await loadSettings($)
972    const made = (await read($, replyGlosses))[e.requestId]
973    const isGlossed = s.isOn && s.gloss && made?.text === e.props.text && made.glosses.length > 0
974    const reply = isGlossed && made ? { ...e, props: { ...e.props, text: applyGlosses(e.props.text, made.glosses) } } : e
975
976    const zh = chineseFor(await read($, translations), e.props.text)
977    const found = zh === null && s.isOn && s.points ? pointsFor(await read($, keyPoints), e.props.text) : undefined
978    if (zh === null && found === undefined) return next(reply)
979    if (e.surface !== 'terminal') {
980      const under = zh !== null ? zhMarkdown(zh) : pointsMarkdown(found?.points ?? null)
981      return next({ ...reply, props: { ...reply.props, text: `${reply.props.text}\n\n${under}` } })
982    }
983    const { Box, Markdown, Text } = $.ui.resolve(e)
984    if (zh !== null)
985      return (
986        <Box key="with-zh" flexDirection="column">
987          {await next(reply)}
988          <Box key="zh" flexDirection="column" paddingLeft={2}>
989            <Text dimColor>── 中文 · /zh hides it ──</Text>
990            <Markdown key="zh-text" text={zh} dimColor />
991          </Box>
992        </Box>
993      )
994    const p = found?.points
995    // The label and its text side by side, so a long line wraps under its text; the question stands out.
996    const row = (key: string, label: string, text: string) => {
997      const look = key === 'ask' ? { color: 'yellow', bold: true } : {}
998      return text ? (
999        <Box key={key}>
1000          <Text {...look} dimColor={key !== 'ask'}>{`${label}  `}</Text>
1001          <Text {...look}>{text}</Text>
1002        </Box>
1003      ) : null
1004    }
1005    return (
1006      <Box key="with-points" flexDirection="column">
1007        {await next(reply)}
1008        <Box key="points" flexDirection="column" paddingLeft={2}>
1009          <Text>
1010            <Text color="cyan">── 要点 </Text>
1011            <Text dimColor>· /zh 看全文中文 ──</Text>
1012          </Text>
1013          {p ? (
1014            [row('did', '做了', p.did), row('point', '结论', p.point), row('ask', '问你', p.ask)]
1015          ) : (
1016            <Text key="reading" dimColor>
1017              …
1018            </Text>
1019          )}
1020        </Box>
1021      </Box>
1022    )
1023  })
1024
1025  // The level slider, at the right of the footer under the prompt.
1026  on('ui.render', { component: 'SessionMode' }, async ($, e, next) => {
1027    const v = await read($, levelView)
1028    if (!v?.isOn) return next(e)
1029
1030    const { Text } = $.ui.resolve(e)
1031    // The desktop cuts the footer label short: there, only the stretch from the level to the goal.
1032    const isNarrow = e.surface !== 'terminal'
1033    const here = SCALE.indexOf(v.level as never)
1034    const goal = v.goalLevel ? SCALE.indexOf(v.goalLevel as never) : -1
1035    const shown = isNarrow ? SCALE.slice(Math.min(here, goal < 0 ? here : goal), Math.max(here, goal) + 1) : SCALE
1036    const marks = shown.flatMap((c, i) => {
1037      const isYou = c === v.level
1038      const isGoal = c === v.goalLevel
1039      const mark = isYou ? (
1040        <Text color="cyan" bold inverse>
1041          {` ${c}${v.isMeasuring ? '?' : ''}${isGoal ? '★' : ''} `}
1042        </Text>
1043      ) : isGoal ? (
1044        <Text color="magenta" bold>
1045          {`${c}★`}
1046        </Text>
1047      ) : (
1048        <Text dimColor>{c}</Text>
1049      )
1050      return i === 0 ? [mark] : [<Text dimColor>─</Text>, mark]
1051    })
1052
1053    return (
1054      <Text>
1055        {e.props.modes.length > 0 ? <Text dimColor>{`${e.props.modes.join(' & ')} · `}</Text> : ''}
1056        <Text dimColor>EN </Text>
1057        {marks}
1058        {v.isMeasuring && !isNarrow ? <Text dimColor>{` measuring ${v.samples}/${v.needed}`}</Text> : ''}
1059      </Text>
1060    )
1061  })
1062}
1063
types/index.d.ts 76 lines
1export type Phrase = { zh: string; en: string }
2
3export type Feedback =
4  | { kind: 'pending'; original: string }
5  | {
6      kind: 'translated'
7      original: string
8      english: string
9      phrases: Phrase[]
10      // While a draft waits in the box, which version it has: the English (the first) or the person's Chinese.
11      inBox?: 'english' | 'chinese'
12    }
13  | {
14      kind: 'checked'
15      original: string
16      isNatural: boolean
17      better: string
18      // Short tips in Chinese, one per main mistake.
19      tips: string[]
20      upgrade: string
21      // True while the message waits in the box for the person to send it.
22      isHeld: boolean
23      // Which version a held message has in the box: the fix (the first) or the person's own.
24      inBox?: 'better' | 'original'
25    }
26
27// What the level slider under the prompt draws.
28export type LevelView = {
29  isOn: boolean
30  level: string
31  isMeasuring: boolean
32  samples: number
33  needed: number
34  goal: string
35  // The goal on the CEFR scale (IELTS 7.5 is C1), null when it cannot be read.
36  goalLevel: string | null
37}
38
39// A Chinese gloss for a word or phrase in one of Claude's replies.
40export type Gloss = { term: string; zh: string }
41
42// The glosses of each reply block, by its requestId, for the text they were made from.
43export type ReplyGlosses = Record<string, { text: string; glosses: Gloss[] }>
44
45// A Chinese translation of one of Claude's replies, drawn under it for the person alone.
46export type ReplyTranslation = {
47  // The reply's paragraphs as Claude wrote them; a code block is one.
48  paras: string[]
49  // Each paragraph's Chinese, '' for a code block; null while Haiku translates it, false when that failed.
50  zh: (string | null | false)[]
51  isShown: boolean
52}
53
54// The key points of one of Claude's long replies, in Chinese, drawn under it for the person alone.
55export type ReplyPoints = {
56  // The reply's paragraphs as Claude wrote them.
57  paras: string[]
58  // What Claude did, what it concluded, what it asks of the person: '' for one the reply has not.
59  // null while Haiku reads the reply.
60  points: { did: string; point: string; ask: string } | null
61}
62
63declare module 'claude-code' {
64  interface PluginState {
65    'english-coach': {
66      feedback: Feedback | null
67      level: LevelView | null
68      glosses: ReplyGlosses
69      // The replies /zh translated, newest last.
70      translations: ReplyTranslation[]
71      // The long replies given key points, newest last.
72      points: ReplyPoints[]
73    }
74  }
75}
76