Learn a language live in your terminal: a lesson split that opens while Claude works, conversation, role-play and reading with a tutor.

A Claude Code mod that teaches you a language live, right in your terminal: a lesson pane, micro-lessons while Claude works, and a tutor that corrects you the way you prefer.
Status: early, private. It works end to end in the terminal but is still being tried out. Design and what is built:
docs/decisions.md.
1: open lesson button above the prompt opens it instead./lingo opens or closes it by hand, /lingo setup runs the guided setup (languages, level, interests, split width, tutor model, theme), /lingo theme <name> switches colors.Mods run outside the sandbox and can see your prompts and tool calls. What lingo-pane does with that:
[redacted] or [email].🔊 listen: the phrase on screen, opened in Google Translate in your browser.Nothing else leaves your machine.
You need Node 22 or newer. From a clean clone:
npm ci
npm run check # type-check, then the tests
npm test runs claude plugin test ., the plugin's test kit. The Claude Code version is pinned in package.json (2.1.287, the one the types come from): newer versions have changed the engine's behaviour, and two permission-ask tests fail on 2.1.308, so bump the pin on purpose, not by accident.npm run typecheck needs the plugin API's declarations in .claude-plugin/types/. They are written by the Claude Code engine when it loads the mod, and git ignores them because they belong to the installed version. The script creates them for you by loading the mod once with an empty HOME (no credentials, no model call). npm run types writes them again after you change the pinned version.npm run check:readmes compares the headings of README.md, README.es.md and README.fr.md (same count and levels, in the same order), so edit the three in the same commit; check runs it..github/workflows/ci.yml) runs npm run check on every pull request.hooks/register.tsx 1582 lines1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register } from 'claude-code'
3
4import { DEMO_CARDS, DEMO_LESSON_COUNT, DEMO_PACK_TITLE } from '../src/content/demo-english-a1'
5import type { LessonQueue } from '../src/lesson'
6import {
7 IDLE_PRACTICE,
8 advanceLesson,
9 afterAnswer,
10 buildQueue,
11 isCorrectAnswer,
12 isFinished,
13 leaksAnswer,
14 nextCard,
15 recordAttempt,
16 reveal,
17 startPractice,
18 tutorPrompt,
19} from '../src/lesson'
20import { socratic } from '../src/correction/socratic'
21import { badThemeText, parseLingoArgs, unknownSubcommandText } from '../src/command'
22import { failureReason } from '../src/failure'
23import { LABELS } from '../src/labels'
24import { THEMES, themeByName } from '../src/themes'
25import { microLesson, spinnerSuffix } from '../src/microcards'
26import {
27 CLOSED_WIZARD,
28 DEFAULT_SPLIT_SHARE,
29 LEVELS,
30 SPLIT_SHARES,
31 STEPS,
32 STRATEGY_AXES,
33 TUTOR_MODELS,
34 buildSetup,
35 draftFromConfig,
36 draftFromSetup,
37 parseInterests,
38 stepProblem,
39 withTheme,
40 wizardTransition,
41} from '../src/setup'
42import type { WizardEvent } from '../src/setup'
43import {
44 CLOSE_DELAY_MS,
45 INITIAL_WAIT,
46 SHOW_DELAY_MS,
47 closeOnTurnComplete,
48 isClaudeWorking,
49 isKeptOpen,
50 isLessonVisible,
51 isOfferVisible,
52 transition,
53} from '../src/wait-machine'
54import type { WaitEvent } from '../src/wait-machine'
55import { canSeatSplit, claudeStateLine, inlineRows, splitColumns } from '../src/split'
56import type { Viewport } from '../src/split'
57import type { LingoActivity, LingoLesson, LingoPractice, LingoReading, LingoSetup, LingoTutorState, LingoUnit, LingoUnitSummary } from '../types'
58import {
59 ACTIVITIES,
60 activityLabel,
61 levelHint,
62 nextUnit,
63 suggestActivity,
64} from '../src/activities'
65import {
66 IDLE_LESSON,
67 UNIT_REPLIES,
68 askedForHelp,
69 isAwaitingLearner,
70 markedParts,
71 newUnit,
72 summaryText,
73 withHelp,
74 withLearnerLine,
75 withTutorTurn,
76 withoutTutor,
77} from '../src/conversation'
78import {
79 TUTOR_MAX_TOKENS,
80 TUTOR_TIMEOUT_MS,
81 helpPrompt,
82 openingPrompt,
83 parseHelp,
84 parseTutorTurn,
85 replyPrompt,
86 tutorSystem,
87} from '../src/tutor'
88import type { TutorContext } from '../src/tutor'
89import { listenUrl } from '../src/listen'
90import { MAX_ANSWER_EXCERPT, MAX_PROMPT_EXCERPT, NO_CONTEXT, contextForTutor, excerpt } from '../src/context'
91import { ACTIVITY, MISTAKES, PROGRESS, SETUP, commitUnit, keepMistakes, load, modify, save } from '../src/storage'
92import type { FinishedUnit, Store } from '../src/storage'
93import { generatedOpeningPrompt, parseScenario, pickScenario } from '../src/roleplay'
94import {
95 READING_MAX_TOKENS,
96 answerReading,
97 parseReading,
98 readingPrompt,
99 readingSystem,
100 showReadingAnswer,
101} from '../src/reading'
102import {
103 MAX_WOVEN,
104 dueMistakes,
105 isFormCard,
106 mistakeAsCard,
107 pickForTurn,
108 recordMistakeReview,
109 spinnerLine,
110} from '../src/mistakes'
111
112const PANE = 'lingo'
113const PANE_TITLE = 'lingo-pane'
114
115// Waiting-state trigger and the split's standing, kept in `$.state` so the
116// Spinner, the band and the pane redraw when it changes (contract: types/index.d.ts).
117const wait = atom({ plugin: 'lingo-pane', key: 'wait' } as const, INITIAL_WAIT)
118
119// Guided setup (contract: types/index.d.ts). The saved setup lives in `$.store`
120// (the source of truth); `setupCache` mirrors it so the band and the Spinner
121// redraw when it changes, and `$.state` resets on /clear, hence the fallback to
122// the store whenever the mirror is not loaded.
123const setupWizard = atom({ plugin: 'lingo-pane', key: 'setupWizard' } as const, CLOSED_WIZARD)
124const setupCache = atom({ plugin: 'lingo-pane', key: 'setupCache' } as const, { isLoaded: false, setup: null })
125const setupBand = atom({ plugin: 'lingo-pane', key: 'setupBand' } as const, { isHidden: false })
126
127// The practice session in the pane (contract: types/index.d.ts). Progress lives
128// in `$.store` under `progress`; this is only where the learner is right now.
129const practice = atom({ plugin: 'lingo-pane', key: 'practice' } as const, IDLE_PRACTICE)
130
131// The lesson in the split: the activity on screen and its micro-unit (contract: types/index.d.ts).
132const lesson = atom({ plugin: 'lingo-pane', key: 'lesson' } as const, IDLE_LESSON)
133
134// The Spinner's micro-card for the turn, worked out once when the turn's delay ends.
135const spinnerCard = atom({ plugin: 'lingo-pane', key: 'spinnerCard' } as const, { turnId: null, text: null })
136
137// The contextual mode's material (opt-in): the last prompt and Claude's last reply, cut short and redacted.
138const workContext = atom({ plugin: 'lingo-pane', key: 'workContext' } as const, NO_CONTEXT)
139
140// What the `switch ▸` menu offers.
141const AVAILABLE_ACTIVITIES: readonly LingoActivity[] = ['conversation', 'roleplay', 'reading', 'review']
142
143// The review's tutor hint (the flashcard practice kept from the first lesson).
144const HINT_TIMEOUT_MS = 20000
145
146// The setup in force: the mirror once loaded, the store otherwise.
147async function currentSetup($: EngineInterface): Promise<LingoSetup | null> {
148 const cache = await read($, setupCache)
149 return cache.isLoaded ? cache.setup : load(storeOf($), SETUP)
150}
151
152function dispatchWait($: EngineInterface, event: WaitEvent) {
153 return update($, wait, s => transition(s, event))
154}
155
156async function closeSplit($: EngineInterface) {
157 await $.ui.close({ id: PANE })
158 await dispatchWait($, { type: 'pane-closed' })
159}
160
161// Any key typed in the split's field or any press there: the split is in use.
162async function touch($: EngineInterface) {
163 const state = await read($, wait)
164 if (state.pane === 'open' && !state.isTouched) await dispatchWait($, { type: 'touched' })
165}
166
167// `$` cannot be handed to the storage module across an import: it gets the two calls.
168const storeOf = ($: EngineInterface): Store => ({
169 get: key => $.store.get(key),
170 set: (key, value) => $.store.set(key, value),
171})
172
173const nowIso = async ($: EngineInterface) => new Date(await $.clock.now()).toISOString()
174
175// Moving the ring is never worth failing a press over: a pane drawn without the keyboard denies it.
176async function focusKey($: EngineInterface, key: string) {
177 await $.ui.focus({ requestId: PANE, key }).catch(() => undefined)
178}
179
180// What the tutor may read of the learner's session: only with the opt-in.
181async function sessionMaterial($: EngineInterface, setup: LingoSetup): Promise<string | null> {
182 return setup.isContextual ? contextForTutor(await read($, workContext)) : null
183}
184
185// What the tutor knows about this learner and this unit.
186function tutorContext(setup: LingoSetup, unit: LingoUnit | null, material: string | null = null): TutorContext {
187 return {
188 targetLanguage: setup.targetLanguage,
189 nativeLanguage: setup.nativeLanguage,
190 level: setup.level,
191 interests: setup.interests,
192 activity: unit?.activity ?? 'conversation',
193 scenario: unit?.scenario ?? null,
194 weave: unit?.woven ?? [],
195 workContext: material,
196 }
197}
198
199// One call on the learner's own plan, with the model chosen in the setup. The
200// platform's result comes back whole: when there is no text, it says why.
201async function callTutor($: EngineInterface, setup: LingoSetup, system: string, prompt: string, maxTokens = TUTOR_MAX_TOKENS) {
202 return $.model.complete({
203 model: setup.tutorModel,
204 system,
205 prompt,
206 effort: 'low',
207 maxTokens,
208 timeoutMs: TUTOR_TIMEOUT_MS,
209 })
210}
211
212// Why a reply gave nothing to use: the platform's reason, or an answer the parser refused.
213function whyNothing(reply: Awaited<ReturnType<typeof callTutor>>): string {
214 return reply.isAnswered ? LABELS.failureUnreadable : failureReason(reply)
215}
216
217// A change to the unit on screen, only if it is still the same unit.
218async function updateUnit($: EngineInterface, id: string, change: (unit: LingoUnit) => LingoUnit) {
219 await update($, lesson, l => (l.unit === null || l.unit.id !== id ? l : { ...l, unit: change(l.unit) }))
220}
221
222// A new micro-unit of conversation or role-play: the tutor opens it. A role-play
223// takes the next scenario of the learner's level, or one the tutor makes up from
224// their interests in the same call.
225async function openTalkUnit($: EngineInterface, setup: LingoSetup, activity: LingoUnit['activity']) {
226 // The tutor weaves in a couple of the mistakes due at this unit.
227 const log = await load(storeOf($), ACTIVITY)
228 const due = dueMistakes(await load(storeOf($), MISTAKES), nextUnit(log)).filter(isFormCard)
229 const woven = due.slice(0, MAX_WOVEN).map(c => ({ id: c.id, wrong: c.wrong, right: c.right }))
230 const pick = activity === 'roleplay' ? pickScenario(setup.level, setup.interests, log.done.roleplay ?? 0) : null
231 const scenario = pick?.kind === 'fixed' ? pick.scenario : null
232 const unit = newUnit(`${activity}-${await $.clock.now()}`, activity, scenario, woven)
233 await update($, lesson, l => ({ ...l, activity, unit, isMenuOpen: false }))
234 await focusKey($, 'reply')
235 const ctx = tutorContext(setup, unit, await sessionMaterial($, setup))
236 const isMadeUp = pick?.kind === 'generated'
237 const reply = await callTutor($, setup, tutorSystem(ctx), isMadeUp ? generatedOpeningPrompt(ctx) : openingPrompt(ctx))
238 const turn = reply.isAnswered ? parseTutorTurn(reply.text) : null
239 const madeUp = isMadeUp && reply.isAnswered ? parseScenario(reply.text) : null
240 await updateUnit($, unit.id, u => {
241 if (u.pending !== 'opening') return u
242 const opened = turn === null ? withoutTutor(u, LABELS.tutorSilentOpening(whyNothing(reply))) : withTutorTurn(u, turn)
243 return madeUp === null ? opened : { ...opened, scenario: madeUp }
244 })
245}
246
247// A reading: the tutor writes a short text at the learner's level and 2-3 questions.
248async function openReading($: EngineInterface, setup: LingoSetup) {
249 const id = `reading-${await $.clock.now()}`
250 const waiting: LingoReading = {
251 id,
252 title: '',
253 text: '',
254 questions: [],
255 index: 0,
256 misses: 0,
257 isPending: true,
258 notice: null,
259 summary: null,
260 }
261 await update($, lesson, (l): LingoLesson => ({ ...l, activity: 'reading', reading: waiting, isMenuOpen: false }))
262 const ctx = tutorContext(setup, null, await sessionMaterial($, setup))
263 const reply = await callTutor($, setup, readingSystem(ctx), readingPrompt(ctx), READING_MAX_TOKENS)
264 const written = reply.isAnswered ? parseReading(id, reply.text) : null
265 await update($, lesson, (l): LingoLesson =>
266 l.reading === null || l.reading.id !== id
267 ? l
268 : { ...l, reading: written ?? { ...l.reading, isPending: false, notice: LABELS.readingSilent(whyNothing(reply)) } },
269 )
270 if (written !== null) await focusKey($, 'reading-answer')
271}
272
273// The learner's answer to the question on screen; an empty Enter shows it and makes it a card.
274async function answerQuestion($: EngineInterface, value: string) {
275 const before = (await read($, lesson)).reading
276 const question = before?.questions[before.index]
277 if (before === null || question === undefined || before.summary !== null || before.isPending) return
278 const isShown = value.trim() === ''
279 const after = isShown ? showReadingAnswer(before) : answerReading(before, value)
280 await update($, lesson, (l): LingoLesson => (l.reading?.id === before.id ? { ...l, reading: after } : l))
281 if (isShown) {
282 const card = { wrong: '', right: question.answer, note: before.title, sentence: question.question }
283 await keepMistakes(storeOf($), { corrections: [card], woven: [], lines: [] }, await nowIso($))
284 }
285 // Its cards were kept as the answers were shown: only the log is left to record.
286 if (after.summary !== null) {
287 await finishActivity($, { id: after.id, activity: 'reading', summary: after.summary, corrections: [], woven: [], lines: [] })
288 }
289}
290
291// The review: the built-in pack's Pimsleur queue, started at once (zero clicks).
292async function startReview($: EngineInterface) {
293 await update($, lesson, (l): LingoLesson => ({ ...l, activity: 'review', isMenuOpen: false }))
294 const session = await read($, practice)
295 if (session.lesson !== null && session.status !== 'done') return
296 const queue = await reviewQueue($)
297 if (queue.recall.length + queue.fresh.length === 0) return
298 const latest = await load(storeOf($), PROGRESS)
299 await update($, practice, () => startPractice(queue, latest.currentLesson))
300 await focusKey($, 'answer-0')
301}
302
303// The review: the mistakes due at the next unit first, then the built-in pack's Pimsleur lesson.
304async function reviewQueue($: EngineInterface): Promise<LessonQueue> {
305 const log = await load(storeOf($), ACTIVITY)
306 const due = dueMistakes(await load(storeOf($), MISTAKES), nextUnit(log)).map(c => c.id)
307 const latest = await load(storeOf($), PROGRESS)
308 const pack = isFinished(latest, DEMO_LESSON_COUNT)
309 ? { recall: [], fresh: [] }
310 : buildQueue(DEMO_CARDS, latest, new Date(await $.clock.now()))
311 return { recall: [...due, ...pack.recall], fresh: pack.fresh }
312}
313
314async function startActivity($: EngineInterface, setup: LingoSetup, activity: LingoActivity) {
315 if (activity === 'review') return startReview($)
316 if (activity === 'reading') return openReading($, setup)
317 // A talk unit left half done for another one closes here: its mistakes are kept.
318 const left = (await read($, lesson)).unit
319 if (left !== null && left.summary === null) {
320 await keepMistakes(storeOf($), left, await nowIso($))
321 }
322 return openTalkUnit($, setup, activity)
323}
324
325// The split opens straight into the unfinished activity, or into the suggested one.
326async function ensureLesson($: EngineInterface, setup: LingoSetup) {
327 const current = await read($, lesson)
328 if (current.activity === 'review') {
329 const session = await read($, practice)
330 if (session.lesson !== null && session.status !== 'done') return
331 } else if (current.activity === 'reading') {
332 const reading = current.reading
333 if (reading !== null && reading.summary === null && !(reading.isPending && reading.text === '')) return
334 } else if (current.unit !== null && current.unit.summary === null) {
335 // A call lost with a reload leaves the unit waiting forever: give it back.
336 if (current.unit.pending !== null && current.unit.lines.length === 0) {
337 return openTalkUnit($, setup, current.unit.activity)
338 }
339 return
340 }
341 const log = await load(storeOf($), ACTIVITY)
342 return startActivity($, setup, suggestActivity(log, AVAILABLE_ACTIVITIES))
343}
344
345// The summary of the activity on screen when its unit is over; null while one runs.
346function finishedSummary(current: LingoLesson): { activity: LingoActivity; summary: LingoUnitSummary } | null {
347 if (current.activity === 'reading') {
348 return current.reading?.summary == null ? null : { activity: 'reading', summary: current.reading.summary }
349 }
350 if (current.activity === 'review' || current.unit === null || current.unit.summary === null) return null
351 return { activity: current.unit.activity, summary: current.unit.summary }
352}
353
354// A finished unit of any activity: recorded once (log and mistakes together); with
355// Claude idle, a split in use closes and says how it went, else the next activity is one press away.
356async function finishActivity($: EngineInterface, unit: FinishedUnit) {
357 const committed = await commitUnit(storeOf($), unit, await nowIso($))
358 // Already recorded (a repeated event): the learner has been told.
359 if (committed !== null && !committed.isRecorded) return
360 const state = await read($, wait)
361 if (!isClaudeWorking(state) && isKeptOpen(state)) {
362 await closeSplit($)
363 $.ui.toast(`${LABELS.modName}: ${summaryText(unit.summary, unit.activity)}`)
364 return
365 }
366 await focusKey($, 'next-unit')
367}
368
369// A finished talk unit: its mistakes become cards, numbered by it.
370async function finishUnit($: EngineInterface, unit: LingoUnit) {
371 if (unit.summary === null) return
372 await finishActivity($, { ...unit, summary: unit.summary })
373}
374
375// The learner's line: shown at once, then the tutor's answer.
376async function sendReply($: EngineInterface, setup: LingoSetup, text: string) {
377 const before = (await read($, lesson)).unit
378 if (before === null) return
379 const asked = withLearnerLine(before, text)
380 if (asked === before) return
381 await updateUnit($, before.id, () => asked)
382 const ctx = tutorContext(setup, asked, await sessionMaterial($, setup))
383 const reply = await callTutor($, setup, tutorSystem(ctx), replyPrompt(ctx, asked, asked.replies >= UNIT_REPLIES))
384 const turn = reply.isAnswered ? parseTutorTurn(reply.text) : null
385 await updateUnit($, before.id, u =>
386 u.pending !== 'reply' ? u : turn === null ? withoutTutor(u, LABELS.tutorSilentReply(whyNothing(reply))) : withTutorTurn(u, turn),
387 )
388 const after = (await read($, lesson)).unit
389 if (after !== null && after.id === before.id && after.summary !== null) await finishUnit($, after)
390}
391
392// An empty Enter: a scaffold, never the answer.
393async function sendHelp($: EngineInterface, setup: LingoSetup) {
394 const before = (await read($, lesson)).unit
395 if (before === null) return
396 const asked = askedForHelp(before)
397 if (asked === before) return
398 await updateUnit($, before.id, () => asked)
399 const ctx = tutorContext(setup, asked, await sessionMaterial($, setup))
400 const reply = await callTutor($, setup, tutorSystem(ctx), helpPrompt(ctx, asked))
401 const text = reply.isAnswered ? parseHelp(reply.text) : null
402 await updateUnit($, before.id, u => (u.pending !== 'help' ? u : text === null ? withoutTutor(u, LABELS.tutorSilentHelp(whyNothing(reply))) : withHelp(u, text)))
403}
404
405export const register: Register = (on, options) => {
406 // Validated by draftFromConfig, where they are used.
407 const target = options.targetLanguage
408 const native = options.nativeLanguage
409
410 // Timer handles live in module variables: a hot reload drops them together
411 // with the timers themselves (the engine cancels pending waits on reload).
412 let delayTimer: { cancel: () => void } | null = null
413 let closeTimer: { cancel: () => void } | null = null
414 // Redraws the split once a second while Claude works, for the elapsed time.
415 let ticker: { cancel: () => void } | null = null
416 // Bumped on Enter in a wizard field so the field is drawn again with its text.
417 let inputRev = 0
418 // The last size a render event reported: `turn.start` carries none, and a
419 // render hook may not write `$.state`. The terminal's wins over a remote one.
420 let terminalViewport: Viewport | null = null
421 let otherViewport: Viewport | null = null
422 const noteViewport = (e: { surface: string; viewport?: Viewport }) => {
423 if (e.viewport === undefined) return
424 if (e.surface === 'terminal') terminalViewport = e.viewport
425 else otherViewport = e.viewport
426 }
427 const viewport = () => terminalViewport ?? otherViewport
428
429 // What the split asks for: the keyboard (granted only over an empty prompt),
430 // its share of the width when docked, about 40 % of the height inline.
431 const openArgs = (setup: LingoSetup | null, terminalColumns?: number) => {
432 const seen = viewport()
433 const columns = terminalColumns ?? seen?.columns
434 return {
435 id: PANE,
436 title: PANE_TITLE,
437 focus: true as const,
438 ...(columns === undefined ? {} : { columns: splitColumns(columns, setup?.splitShare ?? DEFAULT_SPLIT_SHARE) }),
439 ...(seen === null ? {} : { rows: inlineRows(seen.rows) }),
440 }
441 }
442
443 on('session.start', async ($, e, next) => {
444 await $.command.register({
445 name: 'lingo',
446 description: 'Open the lesson pane; "/lingo setup" runs the guided setup; "/lingo theme <name>" switches colors',
447 argumentHint: '[setup | theme <name>]',
448 // Typed while Claude works it runs at once: that is when the split is useful.
449 immediate: true,
450 })
451
452 // Load what is saved into the mirror; a missing or unreadable value is pending.
453 const setup = await load(storeOf($), SETUP)
454 await update($, setupCache, () => ({ isLoaded: true, setup }))
455 if (setup === null) $.ui.toast(LABELS.setupPendingToast)
456
457 return next(e)
458 })
459
460 // /clear, /resume and /branch start a new session without `session.start`
461 // (the process goes on) and reset `$.state`: reload the mirror from the store
462 // and remind again, since the band's "Later" was forgotten with the state.
463 on('classic.SessionStart', async ($, e, next) => {
464 if (e.source === 'startup' || e.source === 'compact') return next(e)
465
466 const setup = await load(storeOf($), SETUP)
467 await update($, setupCache, () => ({ isLoaded: true, setup }))
468 if (setup === null) $.ui.toast(LABELS.setupPendingToast)
469
470 return next(e)
471 })
472
473 on('command.run', { command: 'lingo' }, async ($, e) => {
474 const parsed = parseLingoArgs(e.args)
475 if (parsed.kind === 'unknown') return { text: unknownSubcommandText(parsed.name) }
476 if (parsed.kind === 'bad-theme') return { text: badThemeText(parsed.name) }
477
478 const setup = await currentSetup($)
479
480 if (parsed.kind === 'theme') {
481 // Re-reads the store before writing: another session may have saved since.
482 // A store that fails is told like a setup that is not there.
483 const changed = await modify(storeOf($), SETUP, latest => (latest === null ? null : withTheme(latest, parsed.theme)))
484 if (changed === null || changed.after === null) return { text: LABELS.themeNeedsSetup }
485 const saved = changed.after
486 await update($, setupCache, () => ({ isLoaded: true, setup: saved }))
487 return { text: LABELS.themeSet(themeByName(parsed.theme).label) }
488 }
489
490 if (parsed.kind === 'setup') {
491 // Always the wizard, never a toggle: re-running it resumes where it was.
492 await update($, setupWizard, s => wizardTransition(s, { type: 'open' }, draftFromConfig(native, target)))
493 const opened = await $.ui.open(openArgs(setup, e.presentation?.columns))
494 if (opened.isPlaced) await dispatchWait($, { type: 'pane-placed', opener: 'person' })
495 return {}
496 }
497
498 // A second /lingo closes a pane that is up and drawn (the person's toggle).
499 const panes = await $.ui.panes()
500 if (panes.some(p => p.id === PANE && p.isPlaced)) {
501 await closeSplit($)
502 return {}
503 }
504
505 // Asked by the person, so it is placed at any width (docked from 110 columns in fullscreen).
506 const opened = await $.ui.open(openArgs(setup, e.presentation?.columns))
507 if (opened.isPlaced) await dispatchWait($, { type: 'pane-placed', opener: 'person' })
508 // Straight into the unfinished activity or the suggested one.
509 if (setup !== null) await ensureLesson($, setup)
510
511 return {}
512 })
513
514 // --- Busy detection -------------------------------------------------------
515
516 // `turn.start` is raised for the main loop only (a subagent's run raises none).
517 on('turn.start', async ($, e, next) => {
518 delayTimer?.cancel()
519 closeTimer?.cancel()
520 await dispatchWait($, { type: 'turn-start', turnId: e.turnId, at: await $.clock.now() })
521
522 ticker?.cancel()
523 ticker = $.clock.every(1000, async () => {
524 if ((await read($, wait)).pane === 'open') $.ui.invalidate('ui.render')
525 })
526
527 const turnId = e.turnId
528 delayTimer = $.clock.after(SHOW_DELAY_MS, async () => {
529 await dispatchWait($, { type: 'delay-elapsed', turnId })
530
531 // The Spinner's card for this turn: one of the learner's own mistakes, due ones first.
532 const setup = await currentSetup($)
533 if (setup !== null) {
534 const log = await load(storeOf($), ACTIVITY)
535 const mistake = pickForTurn(await load(storeOf($), MISTAKES), nextUnit(log), turnId)
536 await update($, spinnerCard, () => ({ turnId, text: mistake === null ? null : spinnerLine(mistake) }))
537 }
538
539 // Nothing opens while the setup is pending, once retired for a permission
540 // ask, or over a split that is already open.
541 const state = await read($, wait)
542 if (setup === null || state.phase !== 'showing' || state.pane !== 'none') return
543 if ((await $.ui.panes()).some(p => p.id === PANE)) return
544
545 // Only a docked split opens by itself: in fullscreen, from 110 columns.
546 const seen = viewport()
547 if (seen === null || !canSeatSplit(seen)) {
548 await dispatchWait($, { type: 'pane-not-placed' })
549 return
550 }
551
552 // Unasked, the engine seats it from 144 columns (110 once the person opened it).
553 const opened = await $.ui.open(openArgs(setup))
554 if (opened.isPlaced) {
555 await dispatchWait($, { type: 'pane-placed', opener: 'mod' })
556 await ensureLesson($, setup)
557 } else {
558 // It would sit undrawn: drop it and offer a button above the prompt.
559 await $.ui.close({ id: PANE })
560 await dispatchWait($, { type: 'pane-not-placed' })
561 }
562 })
563
564 return next(e)
565 })
566
567 on('turn.complete', async ($, e, next) => {
568 // A subagent's turn also reaches this hook; only the main loop's counts.
569 if (e.agentId !== undefined) return next(e)
570
571 // The contextual opt-in keeps a short, redacted excerpt of Claude's reply; off, nothing.
572 const setup = await currentSetup($)
573 if (setup?.isContextual === true && e.answer.trim() !== '') {
574 const answer = excerpt(e.answer, MAX_ANSWER_EXCERPT)
575 await update($, workContext, c => ({ ...c, answer }))
576 }
577
578 const turnId = e.turnId
579 const before = await read($, wait)
580 const complete = { type: 'turn-complete', turnId, isAborted: e.isAborted } as const
581 const isCounting = transition(before, complete).phase === 'closing'
582 const closing = closeOnTurnComplete(before, complete)
583 delayTimer?.cancel()
584 closeTimer?.cancel()
585 ticker?.cancel()
586 await dispatchWait($, complete)
587 // The split's top line turns to "done".
588 $.ui.invalidate('ui.render')
589
590 if (closing === 'now') await closeSplit($)
591 // A split in use whose micro-unit already ended while Claude worked: with
592 // Claude idle now, it goes, and says how the unit went.
593 const atRest = finishedSummary(await read($, lesson))
594 if (closing === 'keep' && isKeptOpen(before) && atRest !== null) {
595 await closeSplit($)
596 $.ui.toast(`${LABELS.modName}: ${summaryText(atRest.summary, atRest.activity)}`)
597 }
598 if (isCounting) {
599 closeTimer = $.clock.after(CLOSE_DELAY_MS, async () => {
600 // Untouched until the end of the countdown: it goes; touched meanwhile, it stays.
601 const state = await read($, wait)
602 await dispatchWait($, { type: 'countdown-elapsed', turnId })
603 if (closing === 'after-countdown' && closeOnTurnComplete(state, complete) !== 'keep') await closeSplit($)
604 })
605 }
606
607 return next(e)
608 })
609
610 // The learner's next prompt closes a split they were using; an untouched one
611 // the mod opened goes with its turn instead.
612 on('prompt.submit', async ($, e, next) => {
613 // A slash command (`/lingo` itself) is not the learner's next prompt.
614 const isCommand = e.text.trimStart().startsWith('/')
615 if (!isCommand && isKeptOpen(await read($, wait))) await closeSplit($)
616 // The contextual opt-in keeps a short, redacted excerpt of the prompt; off, nothing.
617 const setup = await currentSetup($)
618 if (setup?.isContextual === true && !isCommand) {
619 const prompt = excerpt(e.text, MAX_PROMPT_EXCERPT)
620 await update($, workContext, c => ({ ...c, prompt }))
621 }
622 return next(e)
623 })
624
625 // --- Do not cover what the person must answer ----------------------------
626
627 // A real tool call the mode decider will put to the person (a permission ask).
628 // The split stays, dimmed and without its field, so no key meant for the
629 // dialog lands in it.
630 on('tool.check', async ($, e, next) => {
631 const verdict = await next(e)
632 if (verdict.decision !== 'ask' || e.tool_use_id === undefined) return verdict
633
634 delayTimer?.cancel()
635 await dispatchWait($, { type: 'needs-user' })
636
637 return verdict
638 })
639
640 on('tool.call', async ($, e, next) => {
641 if (String(e.tool) !== 'AskUserQuestion') {
642 // A tool is running, so whatever asked before has been answered.
643 await dispatchWait($, { type: 'user-answered' })
644 return next(e)
645 }
646
647 delayTimer?.cancel()
648 await dispatchWait($, { type: 'needs-user' })
649
650 // The call resolves once the question has been answered.
651 const answered = await next(e)
652 await dispatchWait($, { type: 'user-answered' })
653
654 return answered
655 })
656
657 on('ui.close', { id: PANE }, async ($, e, next) => {
658 // The person's mark or key, the mod's own close, or an unload: the split is gone.
659 await dispatchWait($, { type: 'pane-closed' })
660 return next(e)
661 })
662
663 // --- What is drawn --------------------------------------------------------
664
665 // One micro-lesson per turn in the Spinner's suffix: no pane, any terminal.
666 on('ui.render', { component: 'Spinner' }, async ($, e, next) => {
667 noteViewport(e)
668 const state = await read($, wait)
669 if (!isLessonVisible(state) || state.turnId === null) return next(e)
670
671 // Nothing to teach until the setup says which languages and level.
672 const setup = await currentSetup($)
673 if (setup === null) return next(e)
674
675 // The learner's own mistake when there is one; the built-in cards otherwise.
676 const card = await read($, spinnerCard)
677 const line = card.turnId === state.turnId && card.text !== null ? card.text : microLesson(setup.targetLanguage, setup.nativeLanguage, state.turnId)
678 const suffix = spinnerSuffix(line)
679
680 return next({ ...e, props: { ...e.props, suffix } })
681 })
682
683 // The band above the prompt: the setup reminder while setup is pending, and
684 // "open lesson" while Claude works and the split cannot seat by itself.
685 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
686 noteViewport(e)
687 if (e.props.hasSurvey) return next(e)
688
689 const state = await read($, wait)
690 const setup = await currentSetup($)
691 const band = await read($, setupBand)
692 const isSetupShown = setup === null && !band.isHidden
693 const isOfferShown = setup !== null && isOfferVisible(state)
694 if (!isSetupShown && !isOfferShown) return next(e)
695
696 const { Box, Button, Text } = $.ui.resolve(e)
697
698 return (
699 <Box flexDirection="column">
700 {isSetupShown && (
701 <Box columnGap={1}>
702 <Text dimColor>{LABELS.bandSetupPending}</Text>
703 <Button
704 key="setup-start"
705 label={LABELS.bandStartSetup}
706 hotkey="2"
707 plain
708 onPress={async () => {
709 await update($, setupWizard, s => wizardTransition(s, { type: 'open' }, draftFromConfig(native, target)))
710 // Opened by a press, so it is placed at any width.
711 const opened = await $.ui.open(openArgs(setup))
712 if (opened.isPlaced) await dispatchWait($, { type: 'pane-placed', opener: 'person' })
713 }}
714 />
715 <Button
716 key="setup-later"
717 label={LABELS.bandLater}
718 hotkey="3"
719 plain
720 onPress={() => update($, setupBand, () => ({ isHidden: true }))}
721 />
722 </Box>
723 )}
724 {isOfferShown && (
725 <Box columnGap={1}>
726 <Text dimColor>{LABELS.modName}</Text>
727 <Button
728 key="open-lingo"
729 label={LABELS.bandOpenLesson}
730 hotkey="1"
731 plain
732 onPress={async () => {
733 await dispatchWait($, { type: 'offer-taken' })
734 // Opened by a press: placed at any width, inline when it cannot dock.
735 const opened = await $.ui.open(openArgs(setup))
736 if (opened.isPlaced) await dispatchWait($, { type: 'pane-placed', opener: 'person' })
737 if (setup !== null) await ensureLesson($, setup)
738 }}
739 />
740 </Box>
741 )}
742 </Box>
743 )
744 })
745
746 on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
747 noteViewport(e)
748 const setup = await currentSetup($)
749 const wizard = await read($, setupWizard)
750 const state = await read($, wait)
751
752 if (e.surface === 'mobile') {
753 // The mobile app draws no Input yet, so the wizard cannot run there.
754 const { Box, Text } = $.ui.resolve(e)
755 return (
756 <Box flexDirection="column">
757 <Text bold>{LABELS.modName}</Text>
758 <Text dimColor>
759 {setup === null ? LABELS.setupNeedsInput : LABELS.learning(setup.targetLanguage, setup.nativeLanguage)}
760 </Text>
761 </Box>
762 )
763 }
764
765 const { Box, Button, Input, Link, Text } = $.ui.resolve(e)
766
767 // On top of the split: whether the keys are here (Esc hands them back and the
768 // split stays), and what Claude is doing.
769 const isFocused = e.props.isFocused
770 const top = (
771 <Box flexDirection="column" marginBottom={1}>
772 <Text bold={isFocused} dimColor={!isFocused}>
773 {isFocused ? LABELS.keysHere : LABELS.keysAway}
774 </Text>
775 <Text dimColor>{claudeStateLine(state, state.startedAt === null ? 0 : await $.clock.now())}</Text>
776 </Box>
777 )
778
779 // A permission ask or a question: the split waits, dimmed and with no field,
780 // so a key meant for the dialog never lands in it.
781 if (state.phase === 'paused') {
782 return (
783 <Box flexDirection="column">
784 {top}
785 <Text dimColor>{LABELS.waitingForYou}</Text>
786 </Box>
787 )
788 }
789
790 // Setup pending, or being redone: the wizard.
791 const drawWizard = () => {
792 // What an untouched draft stands for: what is saved, else the userConfig.
793 const defaults = setup === null ? draftFromConfig(native, target) : draftFromSetup(setup)
794 const draft = wizard.draft ?? defaults
795 const step = wizard.step
796 const number = STEPS.indexOf(step) + 1
797 const problem = stepProblem(step, draft)
798 const dispatch = async (event: WizardEvent) => {
799 await touch($)
800 await update($, setupWizard, s => wizardTransition(s, event, defaults))
801 }
802 // Enter empties a field on screen; a new key redraws it with the draft.
803 const keepText = () => {
804 inputRev += 1
805 $.ui.invalidate('ui.render')
806 }
807
808 const confirm = async () => {
809 const latest = await read($, setupWizard)
810 const built = buildSetup(latest.draft ?? defaults, new Date(await $.clock.now()).toISOString())
811 if (built === null) return
812 if (!(await save(storeOf($), SETUP, built))) return
813 await update($, setupCache, () => ({ isLoaded: true, setup: built }))
814 await update($, setupWizard, () => CLOSED_WIZARD)
815 $.ui.toast(LABELS.setupSaved)
816 // Straight into the lesson, zero clicks.
817 await ensureLesson($, built)
818 }
819
820 // One row of choice buttons; the picked one is primary. No hotkeys: Tab and Enter.
821 const choices = <T extends string | number>(
822 prefix: string,
823 options: readonly { id: T; label: string }[],
824 picked: T,
825 pick: (id: T) => unknown,
826 ) => (
827 <Box flexWrap="wrap" columnGap={1}>
828 {options.map(option => (
829 <Button
830 key={`${prefix}-${option.id}`}
831 label={option.label}
832 variant={picked === option.id ? 'primary' : 'secondary'}
833 onPress={() => pick(option.id)}
834 />
835 ))}
836 </Box>
837 )
838 const preview = themeByName(draft.theme).colors
839
840 return (
841 <Box flexDirection="column">
842 <Text bold>{LABELS.setupTitle}</Text>
843 <Text dimColor>{LABELS.setupStep(number, STEPS.length)}</Text>
844 <Text dimColor>
845 {step === 'languages' || step === 'interests'
846 ? LABELS.setupHintTyping
847 : step === 'level'
848 ? LABELS.setupHintLevel
849 : LABELS.setupHintButtons}
850 </Text>
851
852 {step === 'languages' && (
853 <Box flexDirection="column">
854 <Text>{LABELS.setupLanguagesAsk}</Text>
855 <Input
856 key={`native-${inputRev}`}
857 label={LABELS.setupNative}
858 value={draft.nativeLanguage}
859 placeholder={LABELS.setupNativePlaceholder}
860 autoFocus
861 onInput={value => dispatch({ type: 'set-field', field: 'nativeLanguage', value })}
862 onSubmit={value => {
863 dispatch({ type: 'set-field', field: 'nativeLanguage', value: value === '' ? draft.nativeLanguage : value })
864 keepText()
865 }}
866 />
867 <Input
868 key={`target-${inputRev}`}
869 label={LABELS.setupTarget}
870 value={draft.targetLanguage}
871 placeholder={LABELS.setupTargetPlaceholder}
872 onInput={value => dispatch({ type: 'set-field', field: 'targetLanguage', value })}
873 onSubmit={value => {
874 dispatch({ type: 'set-field', field: 'targetLanguage', value: value === '' ? draft.targetLanguage : value })
875 keepText()
876 }}
877 />
878 </Box>
879 )}
880
881 {step === 'level' && (
882 <Box flexDirection="column">
883 <Text>{LABELS.setupLevelAsk(draft.targetLanguage.trim())}</Text>
884 <Box flexWrap="wrap" columnGap={1}>
885 {LEVELS.map((level, index) => (
886 <Button
887 key={`level-${level}`}
888 label={level}
889 hotkey={String(index + 1)}
890 plain
891 variant={draft.level === level ? 'primary' : 'secondary'}
892 onPress={() => dispatch({ type: 'set-level', level })}
893 />
894 ))}
895 </Box>
896 <Text dimColor>{draft.level === null ? LABELS.setupLevelNone : LABELS.setupLevelPicked(draft.level)}</Text>
897 </Box>
898 )}
899
900 {step === 'interests' && (
901 <Box flexDirection="column">
902 <Text>{LABELS.setupInterestsAsk}</Text>
903 <Text dimColor>{LABELS.setupInterestsNote}</Text>
904 <Input
905 key={`interests-${inputRev}`}
906 label={LABELS.setupInterests}
907 value={draft.interests}
908 placeholder={LABELS.setupInterestsPlaceholder}
909 autoFocus
910 onInput={value => dispatch({ type: 'set-interests', value })}
911 onSubmit={value => {
912 dispatch({ type: 'set-interests', value: value === '' ? draft.interests : value })
913 keepText()
914 }}
915 />
916 </Box>
917 )}
918
919 {step === 'placement' && (
920 <Box flexDirection="column">
921 <Text>{LABELS.setupPlacementTitle}</Text>
922 <Text dimColor>{LABELS.setupPlacementLater}</Text>
923 </Box>
924 )}
925
926 {step === 'strategies' && (
927 <Box flexDirection="column">
928 <Text>{LABELS.setupStrategiesAsk}</Text>
929 {STRATEGY_AXES.map(info => (
930 <Box key={`axis-${info.axis}`} flexDirection="column">
931 <Text bold>{info.title}</Text>
932 <Box flexWrap="wrap" columnGap={1}>
933 {info.options.map(option =>
934 option.isImplemented ? (
935 <Button
936 key={`${info.axis}-${option.id}`}
937 label={option.label}
938 variant={draft.strategies[info.axis] === option.id ? 'primary' : 'secondary'}
939 onPress={() => dispatch({ type: 'set-strategy', axis: info.axis, id: option.id })}
940 />
941 ) : (
942 <Text key={`soon-${info.axis}-${option.id}`} dimColor>
943 {LABELS.setupComingLater(option.label)}
944 </Text>
945 ),
946 )}
947 </Box>
948 </Box>
949 ))}
950 </Box>
951 )}
952
953 {step === 'preferences' && (
954 <Box flexDirection="column">
955 <Text>{LABELS.setupPreferencesAsk}</Text>
956 <Text bold>{LABELS.setupShareTitle}</Text>
957 {choices('share', SPLIT_SHARES.map(share => ({ id: share, label: LABELS.setupShare(share) })), draft.splitShare, share =>
958 dispatch({ type: 'set-share', share }),
959 )}
960 <Text bold>{LABELS.setupTutorTitle}</Text>
961 {choices('tutor', TUTOR_MODELS, draft.tutorModel, model => dispatch({ type: 'set-tutor', model }))}
962 <Text dimColor>{LABELS.setupTutorNote}</Text>
963 <Text bold>{LABELS.setupThemeTitle}</Text>
964 {choices('theme', THEMES.map(t => ({ id: t.name, label: t.label })), draft.theme, theme =>
965 dispatch({ type: 'set-theme', theme }),
966 )}
967 <Box key="theme-preview" columnGap={1} flexWrap="wrap">
968 <Text color={preview.conversation}>conversation</Text>
969 <Text color={preview.roleplay}>role-play</Text>
970 <Text color={preview.reading}>reading</Text>
971 <Text color={preview.tutor}>tutor</Text>
972 <Text color={preview.you}>you</Text>
973 </Box>
974 <Text bold>{LABELS.setupContextTitle}</Text>
975 {choices(
976 'context',
977 [
978 { id: 'off', label: LABELS.setupContextOff },
979 { id: 'on', label: LABELS.setupContextOn },
980 ],
981 draft.isContextual ? 'on' : 'off',
982 id => dispatch({ type: 'set-contextual', isOn: id === 'on' }),
983 )}
984 <Text dimColor>{LABELS.setupContextNote}</Text>
985 </Box>
986 )}
987
988 {step === 'summary' && (
989 <Box flexDirection="column">
990 <Text>{LABELS.setupSummary}</Text>
991 <Text>{LABELS.setupSummaryLanguages(draft.targetLanguage.trim(), draft.nativeLanguage.trim(), draft.level ?? '?')}</Text>
992 <Text dimColor>{LABELS.setupSummaryInterests(parseInterests(draft.interests))}</Text>
993 <Text dimColor>
994 {LABELS.setupSummaryLook(
995 draft.splitShare,
996 TUTOR_MODELS.find(m => m.id === draft.tutorModel)?.label ?? draft.tutorModel,
997 themeByName(draft.theme).label,
998 )}
999 </Text>
1000 <Text dimColor>{LABELS.setupSummaryContext(draft.isContextual)}</Text>
1001 {STRATEGY_AXES.map(info => (
1002 <Text key={`summary-${info.axis}`} dimColor>
1003 {info.title}: {info.options.find(o => o.id === draft.strategies[info.axis])?.label ?? draft.strategies[info.axis]}
1004 </Text>
1005 ))}
1006 </Box>
1007 )}
1008
1009 <Box marginTop={1} columnGap={1} flexWrap="wrap">
1010 {step !== 'languages' && <Button key="back" label={LABELS.back} plain onPress={() => dispatch({ type: 'back' })} />}
1011 {step !== 'placement' && step !== 'summary' && problem === null && (
1012 <Button key="next" label={LABELS.next} plain onPress={() => dispatch({ type: 'next' })} />
1013 )}
1014 {(step === 'placement' || step === 'strategies') && (
1015 <Button key="skip" label={LABELS.skip} plain onPress={() => dispatch({ type: 'skip' })} />
1016 )}
1017 {step === 'summary' && <Button key="confirm" label={LABELS.confirm} variant="primary" autoFocus onPress={confirm} />}
1018 </Box>
1019 {problem !== null && <Text dimColor>{problem}</Text>}
1020 </Box>
1021 )
1022 }
1023
1024 if (setup === null || wizard.isOpen) {
1025 return (
1026 <Box flexDirection="column">
1027 {top}
1028 {drawWizard()}
1029 </Box>
1030 )
1031 }
1032
1033 // The lesson, in the theme's colors; dim while the keys are elsewhere.
1034 const theme = themeByName(setup.theme).colors
1035 const dim = !isFocused
1036 const current = await read($, lesson)
1037 const activityColor = theme[current.activity]
1038 const chip = (
1039 <Box columnGap={1}>
1040 <Text backgroundColor={activityColor} color={theme.bg} bold dimColor={dim}>
1041 {` ${activityLabel(current.activity)} · ${setup.level} `}
1042 </Text>
1043 {current.activity === 'roleplay' && current.unit?.scenario != null && (
1044 <Text color={theme.roleplay} dimColor={dim}>
1045 {current.unit.scenario.id === null ? LABELS.madeUpScenario(current.unit.scenario.title) : current.unit.scenario.title}
1046 </Text>
1047 )}
1048 {current.activity === 'reading' && current.reading !== null && current.reading.title !== '' && (
1049 <Text color={theme.reading} dimColor={dim}>
1050 {current.reading.title}
1051 </Text>
1052 )}
1053 </Box>
1054 )
1055 // Where a role-play happens and who plays whom, under the chip.
1056 const scene =
1057 current.activity === 'roleplay' && current.unit?.scenario != null ? (
1058 <Text color={theme.dim} dimColor={dim} wrap="wrap">
1059 {LABELS.scene(current.unit.scenario.situation, current.unit.scenario.learnerRole)}
1060 </Text>
1061 ) : null
1062
1063 const openMenu = async () => {
1064 await touch($)
1065 await update($, lesson, l => ({ ...l, isMenuOpen: true }))
1066 await focusKey($, `switch-${current.activity}`)
1067 }
1068 const closeMenu = async () => {
1069 await touch($)
1070 await update($, lesson, l => ({ ...l, isMenuOpen: false }))
1071 const field =
1072 current.activity === 'review'
1073 ? `answer-${(await read($, practice)).index}`
1074 : current.activity === 'reading'
1075 ? 'reading-answer'
1076 : 'reply'
1077 await focusKey($, field)
1078 }
1079 // An activity left half done is resumed where it was; otherwise it starts.
1080 const choose = async (activity: LingoActivity) => {
1081 await touch($)
1082 const latest = await read($, lesson)
1083 const session = await read($, practice)
1084 const isRunning =
1085 activity === 'review'
1086 ? session.lesson !== null && session.status !== 'done'
1087 : activity === 'reading'
1088 ? latest.reading !== null && latest.reading.summary === null && latest.reading.text !== ''
1089 : latest.unit !== null && latest.unit.activity === activity && latest.unit.summary === null
1090 if (!isRunning) return startActivity($, setup, activity)
1091 await update($, lesson, (l): LingoLesson => ({ ...l, activity, isMenuOpen: false }))
1092 await focusKey($, activity === 'review' ? `answer-${session.index}` : activity === 'reading' ? 'reading-answer' : 'reply')
1093 }
1094 const switchButton = <Button key="switch" label={LABELS.switchActivity} plain dimColor={dim} onPress={openMenu} />
1095
1096 if (current.isMenuOpen) {
1097 const menu = ACTIVITIES.filter(a => AVAILABLE_ACTIVITIES.includes(a.id))
1098 return (
1099 <Box flexDirection="column">
1100 {top}
1101 {chip}
1102 <Box flexDirection="column" marginTop={1} borderStyle="single" borderColor={theme.ring} paddingX={1}>
1103 {menu.map((a, index) => (
1104 <Button
1105 key={`switch-${a.id}`}
1106 label={a.id === current.activity ? `${a.label} ${LABELS.current}` : a.label}
1107 hotkey={String(index + 1)}
1108 plain
1109 onPress={() => choose(a.id)}
1110 />
1111 ))}
1112 <Button key="switch-back" label={LABELS.backToField} plain dimColor onPress={closeMenu} />
1113 </Box>
1114 <Text color={theme.dim}>{LABELS.menuHint(menu.length)}</Text>
1115 </Box>
1116 )
1117 }
1118
1119 const log = await load(storeOf($), ACTIVITY)
1120 const suggested = suggestActivity(log, AVAILABLE_ACTIVITIES)
1121 const nextButton = (
1122 <Button
1123 key="next-unit"
1124 label={LABELS.nextActivity(activityLabel(suggested))}
1125 variant="primary"
1126 autoFocus
1127 onPress={async () => {
1128 await touch($)
1129 await startActivity($, setup, suggested)
1130 }}
1131 />
1132 )
1133
1134 // A reading: the text, then one question at a time. An empty Enter shows the
1135 // answer and makes a card of the question.
1136 if (current.activity === 'reading') {
1137 const reading = current.reading
1138 const question = reading?.questions[reading.index]
1139 return (
1140 <Box flexDirection="column">
1141 {top}
1142 {chip}
1143 {reading === null || reading.isPending ? (
1144 <Text color={theme.dim} dimColor={dim}>
1145 {LABELS.readingWriting}
1146 </Text>
1147 ) : (
1148 <Box flexDirection="column" marginTop={1}>
1149 {reading.text !== '' && (
1150 <Text color={theme.fg} dimColor={dim} wrap="wrap">
1151 {reading.text}
1152 </Text>
1153 )}
1154 {reading.text !== '' && (
1155 <Text color={theme.dim} dimColor={dim}>
1156 {LABELS.readingGenerated}
1157 </Text>
1158 )}
1159 {reading.questions.slice(0, reading.index).map((q, at) => (
1160 <Text key={`answered-${at}`} color={q.outcome === 'right' ? theme.you : theme.err} dimColor={dim}>
1161 {LABELS.readingAnswered(at + 1, q.question, q.answer, q.outcome === 'right')}
1162 </Text>
1163 ))}
1164 {question !== undefined && reading.summary === null && (
1165 <Box flexDirection="column" marginTop={1}>
1166 <Text color={theme.fg} bold dimColor={dim}>
1167 {LABELS.readingQuestion(reading.index + 1, reading.questions.length, question.question)}
1168 </Text>
1169 <Box borderStyle="round" borderColor={isFocused ? theme.ring : theme.dim} paddingX={1}>
1170 <Input
1171 key="reading-answer"
1172 placeholder={LABELS.readingPlaceholder}
1173 submitLabel={LABELS.reviewSubmit}
1174 autoFocus
1175 onInput={() => touch($)}
1176 onSubmit={async value => {
1177 await touch($)
1178 await answerQuestion($, value)
1179 }}
1180 />
1181 </Box>
1182 {reading.misses > 0 && (
1183 <Text color={theme.err} dimColor={dim}>
1184 {LABELS.readingNotQuite}
1185 </Text>
1186 )}
1187 </Box>
1188 )}
1189 {reading.notice !== null && (
1190 <Text color={theme.err} dimColor={dim}>
1191 {reading.notice}
1192 </Text>
1193 )}
1194 {reading.summary !== null && (
1195 <Text color={theme.you} bold dimColor={dim}>
1196 {summaryText(reading.summary, 'reading')}
1197 </Text>
1198 )}
1199 </Box>
1200 )}src/content/demo-english-a1.ts 43 lines1// The `en-a1` demo pack: English A1 for Spanish speakers, 6 lessons of 5 cards.
2// A module, not a JSON file, because the mod runs without Node or fs and cannot
3// import JSON (and tests cannot read files either, so the old JSON was removed).
4
5import type { Card } from '../strategies'
6
7export const DEMO_PACK_ID = "demo-english-a1"
8export const DEMO_PACK_TITLE = "English A1 demo (for Spanish speakers)"
9export const DEMO_LESSON_COUNT = 6
10
11export const DEMO_CARDS: readonly Card[] = [
12 { id: "en-a1-01-01", lesson: 1, prompt: "Hola", answer: "Hello", tags: ["en-a1", "greetings", "leccion-01"] },
13 { id: "en-a1-01-02", lesson: 1, prompt: "Buenos días", answer: "Good morning", tags: ["en-a1", "greetings", "leccion-01"] },
14 { id: "en-a1-01-03", lesson: 1, prompt: "Buenas noches", answer: "Good night", tags: ["en-a1", "greetings", "leccion-01"] },
15 { id: "en-a1-01-04", lesson: 1, prompt: "Adiós", answer: "Goodbye", tags: ["en-a1", "greetings", "leccion-01"] },
16 { id: "en-a1-01-05", lesson: 1, prompt: "¿Cómo estás?", answer: "How are you?", tags: ["en-a1", "greetings", "leccion-01"] },
17 { id: "en-a1-02-01", lesson: 2, prompt: "Me llamo Ana", answer: "My name is Ana", tags: ["en-a1", "introductions", "leccion-02"] },
18 { id: "en-a1-02-02", lesson: 2, prompt: "¿Cómo te llamas?", answer: "What's your name?", tags: ["en-a1", "introductions", "leccion-02"] },
19 { id: "en-a1-02-03", lesson: 2, prompt: "Mucho gusto", answer: "Nice to meet you", tags: ["en-a1", "introductions", "leccion-02"] },
20 { id: "en-a1-02-04", lesson: 2, prompt: "Soy de Venezuela", answer: "I'm from Venezuela", tags: ["en-a1", "introductions", "leccion-02"] },
21 { id: "en-a1-02-05", lesson: 2, prompt: "¿De dónde eres?", answer: "Where are you from?", tags: ["en-a1", "introductions", "leccion-02"] },
22 { id: "en-a1-03-01", lesson: 3, prompt: "uno", answer: "one", tags: ["en-a1", "numbers", "leccion-03"] },
23 { id: "en-a1-03-02", lesson: 3, prompt: "dos", answer: "two", tags: ["en-a1", "numbers", "leccion-03"] },
24 { id: "en-a1-03-03", lesson: 3, prompt: "tres", answer: "three", tags: ["en-a1", "numbers", "leccion-03"] },
25 { id: "en-a1-03-04", lesson: 3, prompt: "cuatro", answer: "four", tags: ["en-a1", "numbers", "leccion-03"] },
26 { id: "en-a1-03-05", lesson: 3, prompt: "cinco", answer: "five", tags: ["en-a1", "numbers", "leccion-03"] },
27 { id: "en-a1-04-01", lesson: 4, prompt: "madre", answer: "mother", tags: ["en-a1", "family", "leccion-04"] },
28 { id: "en-a1-04-02", lesson: 4, prompt: "padre", answer: "father", tags: ["en-a1", "family", "leccion-04"] },
29 { id: "en-a1-04-03", lesson: 4, prompt: "hermano", answer: "brother", tags: ["en-a1", "family", "leccion-04"] },
30 { id: "en-a1-04-04", lesson: 4, prompt: "hermana", answer: "sister", tags: ["en-a1", "family", "leccion-04"] },
31 { id: "en-a1-04-05", lesson: 4, prompt: "amigo", answer: "friend", tags: ["en-a1", "family", "leccion-04"] },
32 { id: "en-a1-05-01", lesson: 5, prompt: "agua", answer: "water", tags: ["en-a1", "food", "leccion-05"] },
33 { id: "en-a1-05-02", lesson: 5, prompt: "pan", answer: "bread", tags: ["en-a1", "food", "leccion-05"] },
34 { id: "en-a1-05-03", lesson: 5, prompt: "manzana", answer: "apple", tags: ["en-a1", "food", "leccion-05"] },
35 { id: "en-a1-05-04", lesson: 5, prompt: "café", answer: "coffee", tags: ["en-a1", "food", "leccion-05"] },
36 { id: "en-a1-05-05", lesson: 5, prompt: "Tengo hambre", answer: "I'm hungry", tags: ["en-a1", "food", "leccion-05"] },
37 { id: "en-a1-06-01", lesson: 6, prompt: "Por favor", answer: "Please", tags: ["en-a1", "polite-phrases", "leccion-06"] },
38 { id: "en-a1-06-02", lesson: 6, prompt: "Gracias", answer: "Thank you", tags: ["en-a1", "polite-phrases", "leccion-06"] },
39 { id: "en-a1-06-03", lesson: 6, prompt: "De nada", answer: "You're welcome", tags: ["en-a1", "polite-phrases", "leccion-06"] },
40 { id: "en-a1-06-04", lesson: 6, prompt: "Lo siento", answer: "I'm sorry", tags: ["en-a1", "polite-phrases", "leccion-06"] },
41 { id: "en-a1-06-05", lesson: 6, prompt: "No entiendo", answer: "I don't understand", tags: ["en-a1", "polite-phrases", "leccion-06"] },
42]
43src/lesson.ts 148 lines1// Pure logic of the practice session: answer matching, hints, progress and the
2// queue. No `$`, no I/O; inputs are never mutated.
3
4import { dueCards } from './review/pimsleur'
5import type { Card, Progress } from './strategies'
6import type { LingoPractice, LingoProgress } from '../types'
7
8export const PROGRESS_STORE_KEY = 'progress'
9export const PROGRESS_VERSION = 1
10/** Past attempts kept per card (the store is small and shared). */
11export const MAX_REVIEWS_PER_CARD = 20
12
13export const FRESH_PROGRESS: LingoProgress = { version: PROGRESS_VERSION, currentLesson: 1, cards: {} }
14
15// --- Answers ----------------------------------------------------------------
16
17/** Lowercase, no punctuation, one space between words, no edge spaces. */
18export function normalizeAnswer(text: string): string {
19 return text
20 .toLowerCase()
21 .replace(/[^\p{L}\p{N}\s]/gu, '')
22 .replace(/\s+/g, ' ')
23 .trim()
24}
25
26export function isCorrectAnswer(input: string, answer: string): boolean {
27 const given = normalizeAnswer(input)
28 return given !== '' && given === normalizeAnswer(answer)
29}
30
31/** A deterministic hint: the first letter and the size, never the answer. */
32export function hintFor(answer: string): string {
33 const words = normalizeAnswer(answer).split(' ')
34 const letters = words.join('').length
35 const first = (normalizeAnswer(answer)[0] ?? '?').toUpperCase()
36 const count = (n: number, one: string, many: string) => `${n} ${n === 1 ? one : many}`
37 return `Starts with "${first}", ${count(words.length, 'word', 'words')}, ${count(letters, 'letter', 'letters')}.`
38}
39
40/** True when a tutor reply contains the answer, so it must not be shown. */
41export function leaksAnswer(reply: string, answer: string): boolean {
42 const target = normalizeAnswer(answer)
43 return target !== '' && ` ${normalizeAnswer(reply)} `.includes(` ${target} `)
44}
45
46/** The prompt handed to `$.model.complete`; the answer is for the tutor only. */
47export function tutorPrompt(card: Card, failed: string, targetLanguage: string, nativeLanguage: string): string {
48 return [
49 `Exercise: the learner must translate "${card.prompt}" into ${targetLanguage}.`,
50 `Reference answer (for you only; never write it, spell it out or translate it): "${card.answer}"`,
51 `The learner answered: "${failed}"`,
52 `Reply in ${nativeLanguage} with one short guiding question or hint, at most two lines, without giving the answer.`,
53 ].join('\n')
54}
55
56// --- Progress ---------------------------------------------------------------
57
58const isObject = (value: unknown): value is Record<string, unknown> =>
59 typeof value === 'object' && value !== null && !Array.isArray(value)
60
61/** Whatever `$.store` held under `progress`, as progress; a fresh one when it is not valid. */
62export function parseProgress(raw: unknown): LingoProgress {
63 if (!isObject(raw) || raw.version !== PROGRESS_VERSION) return FRESH_PROGRESS
64 const { currentLesson, cards } = raw
65 if (typeof currentLesson !== 'number' || !Number.isInteger(currentLesson) || currentLesson < 1) return FRESH_PROGRESS
66 if (!isObject(cards)) return FRESH_PROGRESS
67
68 const clean: LingoProgress['cards'] = {}
69 for (const [id, entry] of Object.entries(cards)) {
70 if (!isObject(entry) || !Array.isArray(entry.reviews)) continue
71 const reviews = entry.reviews
72 .filter(isObject)
73 .filter(r => typeof r.at === 'string' && typeof r.isCorrect === 'boolean')
74 .map(r => ({ at: r.at as string, isCorrect: r.isCorrect as boolean }))
75 clean[id] = { reviews: reviews.slice(-MAX_REVIEWS_PER_CARD) }
76 }
77 return { version: PROGRESS_VERSION, currentLesson, cards: clean }
78}
79
80export function recordAttempt(progress: LingoProgress, cardId: string, at: string, isCorrect: boolean): LingoProgress {
81 const before = progress.cards[cardId]?.reviews ?? []
82 const reviews = [...before, { at, isCorrect }].slice(-MAX_REVIEWS_PER_CARD)
83 return { ...progress, cards: { ...progress.cards, [cardId]: { reviews } } }
84}
85
86/** After finishing the current lesson: the next one, or "finished" (lessons + 1). */
87export function advanceLesson(progress: LingoProgress, lessonCount: number): LingoProgress {
88 return { ...progress, currentLesson: Math.min(progress.currentLesson + 1, lessonCount + 1) }
89}
90
91export const isFinished = (progress: LingoProgress, lessonCount: number): boolean =>
92 progress.currentLesson > lessonCount
93
94function toList(progress: LingoProgress): Progress[] {
95 return Object.entries(progress.cards).map(([cardId, entry]) => ({ cardId, reviews: entry.reviews }))
96}
97
98// --- Queue ------------------------------------------------------------------
99
100export type LessonQueue = { recall: string[]; fresh: string[] }
101
102/** Pimsleur recall block (n-1, n-3, n-7), then the new cards of the current lesson. */
103export function buildQueue(cards: readonly Card[], progress: LingoProgress, now: Date): LessonQueue {
104 const all = [...cards]
105 const recall = dueCards(all, toList(progress), { now, currentLesson: progress.currentLesson }).map(c => c.id)
106 const fresh = all
107 .filter(c => c.lesson === progress.currentLesson)
108 .map(c => c.id)
109 .sort()
110 return { recall, fresh }
111}
112
113export const queueIds = (queue: LessonQueue): string[] => [...queue.recall, ...queue.fresh]
114
115// --- Session state ----------------------------------------------------------
116
117export const IDLE_PRACTICE: LingoPractice = {
118 lesson: null,
119 queue: [],
120 recallCount: 0,
121 index: 0,
122 status: 'asking',
123 misses: 0,
124 hint: null,
125 lastAnswer: null,
126 tutor: { kind: 'idle' },
127}
128
129export function startPractice(queue: LessonQueue, lesson: number): LingoPractice {
130 const ids = queueIds(queue)
131 return { ...IDLE_PRACTICE, lesson, queue: ids, recallCount: queue.recall.length, status: ids.length === 0 ? 'done' : 'asking' }
132}
133
134/** After a right or wrong answer: the new state of the card on screen. */
135export function afterAnswer(session: LingoPractice, isCorrect: boolean, answer: string, given: string): LingoPractice {
136 if (isCorrect) return { ...session, status: 'correct', hint: null, tutor: { kind: 'idle' } }
137 return { ...session, misses: session.misses + 1, hint: hintFor(answer), lastAnswer: given, tutor: { kind: 'idle' } }
138}
139
140export const reveal = (session: LingoPractice): LingoPractice => ({ ...session, status: 'revealed', hint: null })
141
142/** Next card, or `done` after the last one. */
143export function nextCard(session: LingoPractice): LingoPractice {
144 const index = session.index + 1
145 if (index >= session.queue.length) return { ...session, index, status: 'done', misses: 0, hint: null, lastAnswer: null, tutor: { kind: 'idle' } }
146 return { ...session, index, status: 'asking', misses: 0, hint: null, lastAnswer: null, tutor: { kind: 'idle' } }
147}
148src/correction/socratic.ts 22 lines1import type { CorrectionStyle } from '../strategies'
2
3// Socratic correction: hints and questions before answers. Derived from the
4// author's own course preferences (guide with a question before showing the
5// correct form; gloss new vocabulary inline without giving away the tested
6// point; ask the learner to justify each option; never assert grammar from
7// memory when unsure).
8export const socratic: CorrectionStyle = {
9 id: 'socratic',
10 instruction({ targetLanguage, nativeLanguage }) {
11 return [
12 `You are a patient ${targetLanguage} tutor for a ${nativeLanguage} speaker. Explain in ${nativeLanguage}; keep examples in ${targetLanguage}.`,
13 'When the learner answers wrong, do not give the correct answer first. Ask one short guiding question that points at the mistake. Give a stronger hint only if they miss again, and the answer last.',
14 'When the learner answers right, confirm briefly and, if useful, ask why it is right in one sentence.',
15 'New vocabulary in an exercise is fine, but gloss it inline in parentheses, and never let the gloss give away what the item is testing.',
16 'For multiple choice, ask the learner to justify each option before confirming.',
17 'If you are not sure a rule or usage is correct, say so instead of stating it as fact.',
18 'Keep every reply to a few lines.',
19 ].join('\n')
20 },
21}
22src/command.ts 52 lines1// What `/lingo` was asked to do, parsed from the text after the command name.
2// Pure: hooks/register.tsx turns the result into panes and answers.
3
4import { THEMES, parseThemeName } from './themes'
5import type { LingoThemeName } from '../types'
6
7export type LingoSubcommand =
8 | { kind: 'open' }
9 | { kind: 'setup' }
10 | { kind: 'theme'; theme: LingoThemeName }
11 /** `/lingo theme` with no name or one that does not exist. */
12 | { kind: 'bad-theme'; name: string }
13 | { kind: 'unknown'; name: string }
14
15/** The subcommands that exist, as `[name, what it does]`, for the help text. */
16export const SUBCOMMANDS: readonly (readonly [string, string])[] = [
17 ['(none)', 'open or close the lesson pane'],
18 ['setup', 'open the guided setup (languages, level, interests, strategies, look)'],
19 ['theme <name>', `switch the color theme (${THEMES.map(t => t.name).join(', ')})`],
20]
21
22/**
23 * `args` is everything after `/lingo` as typed ("" when nothing). Only the
24 * first word counts, case-insensitively; words after a known subcommand are
25 * ignored rather than refused, save the theme's name.
26 */
27export function parseLingoArgs(args: string): LingoSubcommand {
28 const [first = '', second = ''] = args.trim().split(/\s+/)
29 if (first === '') return { kind: 'open' }
30 const name = first.toLowerCase()
31 if (name === 'setup') return { kind: 'setup' }
32 if (name === 'theme') {
33 const theme = parseThemeName(second)
34 return theme === null ? { kind: 'bad-theme', name: second } : { kind: 'theme', theme }
35 }
36 return { kind: 'unknown', name: first }
37}
38
39/** The answer to a subcommand that does not exist: lists the ones that do. */
40export function unknownSubcommandText(name: string): string {
41 const lines = SUBCOMMANDS.map(([sub, what]) => ` /lingo ${sub === '(none)' ? '' : sub}`.trimEnd() + ` ${what}`)
42 return [`lingo-pane: unknown subcommand "${name}". Available:`, ...lines].join('\n')
43}
44
45/** The answer to `/lingo theme` without a known name: the themes that exist. */
46export function badThemeText(name: string): string {
47 const list = THEMES.map(t => `${t.name} (${t.label})`).join(', ')
48 return name === ''
49 ? `lingo-pane: name a theme: /lingo theme <name>. Themes: ${list}.`
50 : `lingo-pane: there is no theme "${name}". Themes: ${list}.`
51}
52src/failure.ts 30 lines1// Why a model call came back without text, as one short sentence for the
2// learner. Pure: `$.model.complete` never rejects, it resolves with a reason,
3// and the callers in hooks/register.tsx pass that result here.
4
5import type { ModelCompleteResult } from 'claude-code'
6
7import { LABELS } from './labels'
8
9/** The arms of `ModelCompleteResult` that carry a reason instead of text. */
10export type ModelFailure = Extract<ModelCompleteResult, { isAnswered: false }>
11
12/** The reason as a sentence; the callers append what the learner can do next. */
13export function failureReason(failure: ModelFailure): string {
14 if (failure.reason === 'empty-reply') return LABELS.failureEmpty
15 if (failure.reason === 'aborted') return LABELS.failureAborted
16 switch (failure.error) {
17 case 'rate_limit':
18 case 'billing_error':
19 return LABELS.failureLimit
20 case 'authentication_failed':
21 case 'oauth_org_not_allowed':
22 case 'account_on_hold':
23 case 'verification_required':
24 case 'cloud_credential_error':
25 return LABELS.failureSignIn
26 default:
27 return LABELS.failureService(failure.status)
28 }
29}
30src/labels.ts 138 lines1// Every label the mod draws, in English, in one table so it can be translated
2// later. Catalogue entries (strategy options, tutor models, themes) keep their
3// labels next to their ids; prompts sent to the model are not labels.
4
5export const LABELS = {
6 modName: 'lingo-pane',
7
8 // --- Setup ------------------------------------------------------------------
9 setupTitle: 'lingo-pane setup',
10 setupStep: (n: number, of: number) => `Step ${n} of ${of}`,
11 setupHintTyping: 'Type, Enter keeps the text, Tab moves to the next field or button.',
12 setupHintLevel: 'Tab moves between buttons and Enter presses, or type the digit shown.',
13 setupHintButtons: 'Tab moves between buttons and Enter presses.',
14 setupLanguagesAsk: 'Which languages? The explanations are in your native language.',
15 setupNative: 'Native language: ',
16 setupTarget: 'Target language: ',
17 setupNativePlaceholder: 'e.g. Spanish',
18 setupTargetPlaceholder: 'e.g. English',
19 setupLevelAsk: (target: string) => `Your level in ${target} (CEFR):`,
20 setupLevelNone: 'None picked yet.',
21 setupLevelPicked: (level: string) => `Picked: ${level}`,
22 setupInterestsAsk: 'What do you like to talk about? Role-play scenarios are made from it.',
23 setupInterestsNote: 'Optional, comma-separated, up to 5.',
24 setupInterests: 'Interests: ',
25 setupInterestsPlaceholder: 'e.g. chess, cooking, startups',
26 setupPlacementTitle: 'Placement test (optional)',
27 setupPlacementLater: 'placement test: coming later',
28 setupStrategiesAsk: 'How should it work? Defaults are fine; "coming later" ones are not built yet.',
29 setupComingLater: (label: string) => `${label} (coming later)`,
30 setupPreferencesAsk: 'How the lesson looks and who teaches. Defaults are fine.',
31 setupShareTitle: 'Split width while Claude works (share of the terminal)',
32 setupShare: (share: number) => `${share} %`,
33 setupTutorTitle: 'Tutor model',
34 setupTutorNote: 'Every tutor reply uses your Claude plan.',
35 setupThemeTitle: 'Theme',
36 setupContextTitle: 'Material from your own session (optional)',
37 setupContextOff: 'Off',
38 setupContextOn: 'On',
39 setupContextNote:
40 "On: short excerpts of your last prompt and of Claude's last reply (secrets and emails redacted) go to the tutor, on your Claude plan, as topic ideas. Off by default.",
41 setupSummaryContext: (isOn: boolean) => `Material from your session: ${isOn ? 'on' : 'off'}`,
42 setupSummary: 'Summary',
43 setupSummaryLanguages: (target: string, native: string, level: string) => `${target} from ${native}, level ${level}`,
44 setupSummaryInterests: (interests: readonly string[]) =>
45 `Interests: ${interests.length === 0 ? '(none)' : interests.join(', ')}`,
46 setupSummaryLook: (share: number, tutor: string, theme: string) => `Split ${share} % · tutor ${tutor} · theme ${theme}`,
47 setupSaved: 'lingo-pane: setup saved',
48 setupPendingToast: 'lingo-pane: setup pending. Run /lingo setup (or press 2 in the band above the prompt).',
49 setupNeedsInput: 'Setup needs a terminal or the desktop app.',
50 learning: (target: string, native: string) => `Learning ${target} from ${native}.`,
51
52 back: 'Back',
53 next: 'Next',
54 skip: 'Skip',
55 confirm: 'Confirm',
56
57 // --- The split -------------------------------------------------------------------
58 keysHere: '● keys here · Esc back to the prompt',
59 keysAway: '○ Ctrl+X Tab to come back',
60 waitingForYou: 'Claude needs you: answer below. The lesson waits here.',
61
62 // --- The lesson ----------------------------------------------------------------
63 tutor: 'tutor ',
64 you: 'you ',
65 help: 'help ',
66 tutorThinking: 'the tutor is thinking…',
67 // Why the tutor is silent (the platform's reason), then what the learner can do.
68 failureUnreadable: 'The tutor did not answer in a way the lesson could use.',
69 failureLimit: 'Your Claude plan or rate limit was reached; wait a while or check /usage.',
70 failureSignIn: 'Claude could not sign you in; run /login.',
71 failureService: (status: number | null) => `Claude's service had an error${status === null ? '' : ` (${status})`}.`,
72 failureEmpty: 'The tutor sent an empty reply.',
73 failureAborted: 'The tutor call was cancelled or took too long.',
74 tutorSilentOpening: (why: string) => `${why} Press "switch ▸" to try again or pick another activity.`,
75 tutorSilentReply: (why: string) => `${why} Your line is back to you: send it again.`,
76 tutorSilentHelp: (why: string) => `${why} Try Enter on the empty field again.`,
77 replyPlaceholder: (target: string) => `reply in ${target}`,
78 replySubmit: 'reply',
79 listen: '🔊 listen',
80 switchActivity: 'switch ▸',
81 talkHint: '⏎ empty = help · Tab = listen and switch',
82 talkHintWaiting: 'the tutor is answering; send your next line once it has',
83 nextActivity: (label: string) => `next: ${label} ▸`,
84 levelHint: (direction: 'up' | 'down', level: string) =>
85 direction === 'up'
86 ? `Tutor: these went smoothly. You could try ${level}; /lingo setup changes it.`
87 : `Tutor: these were hard. ${level} might suit you better for now; /lingo setup changes it.`,
88 madeUpScenario: (title: string) => `${title} (made up from your interests)`,
89 scene: (situation: string, learnerRole: string) => `${situation} You: ${learnerRole}`,
90 readingWriting: 'the tutor is writing a short text for you…',
91 readingSilent: (why: string) => `${why} The text was not written: try again with "next" or pick another activity.`,
92 readingGenerated: 'Written by the tutor for your level; it can make mistakes.',
93 readingQuestion: (n: number, of: number, question: string) => `Q${n} of ${of}: ${question}`,
94 readingPlaceholder: 'a word or three',
95 readingNotQuite: 'Not quite. Look again, or Enter on the empty field shows it.',
96 readingAnswered: (n: number, question: string, answer: string, isRight: boolean) =>
97 `${isRight ? '✓' : '·'} Q${n} ${question} ${answer}`,
98 readingHint: '⏎ empty = show the answer (it becomes a card) · Tab = listen and switch',
99 current: '(current)',
100 backToField: 'back',
101 menuHint: (count: number) => `press 1-${count} · Tab back`,
102
103 // --- Review (the built-in pack) ---------------------------------------------------
104 reviewPackNote: (title: string) => `The built-in pack is ${title}; it is used for now.`,
105 reviewDemoFinished: (count: number) => `Demo finished: all ${count} lessons are done. Come back to review, or wait for the lesson generator.`,
106 reviewLessonIntro: (lesson: number, count: number, recall: number, fresh: number) =>
107 `Lesson ${lesson} of ${count}: ${recall} to recall, ${fresh} new.`,
108 reviewMistakesIntro: (count: number) => `Your mistakes: ${count} to review.`,
109 reviewMistakeOf: (card: number, of: number) => `Your mistake - card ${card} of ${of}: type the right words for the marked ones`,
110 reviewDone: 'Review done',
111 reviewStart: 'Start lesson',
112 reviewLessonDone: (lesson: number) => `Lesson ${lesson} done`,
113 reviewDemoLast: 'Demo finished: that was the last lesson.',
114 reviewContinue: 'Continue',
115 reviewCardOf: (lesson: number, card: number, of: number, isRecall: boolean) =>
116 `Lesson ${lesson} - card ${card} of ${of} (${isRecall ? 'recall' : 'new'})`,
117 reviewIn: (target: string) => `In ${target}: `,
118 reviewPlaceholder: 'type your answer',
119 reviewSubmit: 'answer',
120 reviewNotYet: (hint: string) => `Not yet. ${hint}`,
121 reviewHintFromTutor: 'Hint from tutor',
122 reviewHint: '⏎ empty = show the answer · Tab = hint from tutor, switch',
123 reviewCorrect: (answer: string) => `Correct: ${answer}`,
124 reviewAnswer: (answer: string) => `Answer: ${answer}`,
125 hintUnavailable: (why: string) => `${why} Use the hint above or try again.`,
126 hintLeaked: 'The tutor reply would have given the answer away, so it was dropped. Try again or look at the hint.',
127
128 // --- Band above the prompt -----------------------------------------------------
129 bandSetupPending: 'lingo-pane: setup pending. ',
130 bandStartSetup: 'Start setup',
131 bandLater: 'Later',
132 bandOpenLesson: 'open lesson',
133
134 // --- Theme command -------------------------------------------------------------
135 themeSet: (label: string) => `lingo-pane: theme set to ${label}.`,
136 themeNeedsSetup: 'lingo-pane: finish the setup first (/lingo setup).',
137} as const
138src/themes.ts 106 lines1// The lesson pane's color themes: raw hex colors handed to `color`,
2// `backgroundColor` and `borderColor` on Text and Box. Each activity has its
3// own color, and the tutor and the learner are told apart at a glance. The
4// values come from the UI mockup of the 2026-10-02 grilling.
5
6import type { LingoThemeName } from '../types'
7
8export type ThemeColors = {
9 /** The pane's background. */
10 bg: string
11 /** Ordinary text. */
12 fg: string
13 /** Hints and secondary lines. */
14 dim: string
15 /** Activity colors. */
16 conversation: string
17 roleplay: string
18 reading: string
19 review: string
20 /** Who speaks. */
21 tutor: string
22 you: string
23 /** A mistake. */
24 err: string
25 /** The frame around the answer field. */
26 ring: string
27}
28
29export type Theme = { name: LingoThemeName; label: string; colors: ThemeColors }
30
31export const DEFAULT_THEME: LingoThemeName = 'atardecer'
32
33// The mockup gives no color to `review` (it shows three activities); it borrows
34// the learner's own color, the warmest one that is not an activity's.
35export const THEMES: readonly Theme[] = [
36 {
37 name: 'atardecer',
38 label: 'Atardecer',
39 colors: {
40 bg: '#17202b',
41 fg: '#e8e3da',
42 dim: '#7e8a99',
43 conversation: '#ff8a65',
44 roleplay: '#b39ddb',
45 reading: '#4db6ac',
46 review: '#ffcc80',
47 tutor: '#90caf9',
48 you: '#ffcc80',
49 err: '#ef9a9a',
50 ring: '#ff8a65',
51 },
52 },
53 {
54 name: 'tropico',
55 label: 'Trópico',
56 colors: {
57 bg: '#1b1a22',
58 fg: '#ece6dc',
59 dim: '#8a8494',
60 conversation: '#ffb347',
61 roleplay: '#ff6f91',
62 reading: '#5fd38d',
63 review: '#ffd59e',
64 tutor: '#4fc3f7',
65 you: '#ffd59e',
66 err: '#ff6f91',
67 ring: '#ffb347',
68 },
69 },
70 {
71 name: 'pastel',
72 label: 'Pastel',
73 colors: {
74 bg: '#1e1e2e',
75 fg: '#cdd6f4',
76 dim: '#7f849c',
77 conversation: '#cba6f7',
78 roleplay: '#fab387',
79 reading: '#a6e3a1',
80 review: '#f5c2e7',
81 tutor: '#89dceb',
82 you: '#f5c2e7',
83 err: '#f38ba8',
84 ring: '#cba6f7',
85 },
86 },
87]
88
89/** The theme by name; the default for anything unknown. */
90export function themeByName(name: string): Theme {
91 return THEMES.find(t => t.name === name) ?? (THEMES[0] as Theme)
92}
93
94/** "Trópico", "tropico", " PASTEL " -> the theme's name; null when none matches. */
95export function parseThemeName(text: string): LingoThemeName | null {
96 const plain = text
97 .trim()
98 .toLowerCase()
99 .normalize('NFD')
100 .replace(/\p{M}/gu, '')
101 return THEMES.find(t => t.name === plain)?.name ?? null
102}
103
104export const isThemeName = (value: unknown): value is LingoThemeName =>
105 typeof value === 'string' && THEMES.some(t => t.name === value)
106src/microcards.ts 66 lines1// Provisional micro-lesson content: a short embedded list of English -> Spanish
2// cards. The real source will be a ContentStore (see strategies.ts); until
3// then nothing here pretends to cover other languages.
4
5export type MicroCard = { word: string; gloss: string }
6
7export const ENGLISH_TO_SPANISH: readonly MicroCard[] = [
8 { word: 'deadline', gloss: 'fecha límite' },
9 { word: 'workaround', gloss: 'solución provisional' },
10 { word: 'reliable', gloss: 'confiable' },
11 { word: 'to figure out', gloss: 'averiguar, descifrar' },
12 { word: 'to look into', gloss: 'investigar, revisar' },
13 { word: 'to roll back', gloss: 'revertir' },
14 { word: 'to rely on', gloss: 'depender de, confiar en' },
15 { word: 'to carry out', gloss: 'llevar a cabo' },
16]
17
18const ENGLISH = ['english', 'inglés', 'ingles']
19const SPANISH = ['spanish', 'español', 'espanol']
20
21const normalize = (language: string): string => language.trim().toLowerCase()
22
23/**
24 * The cards for a language pair, or the reason there are none. Only the pair
25 * the embedded list really covers is answered; nothing is translated on the fly.
26 */
27export function cardsFor(
28 target: string,
29 native: string,
30): { kind: 'cards'; cards: readonly MicroCard[] } | { kind: 'unsupported'; message: string } {
31 if (!ENGLISH.includes(normalize(target))) {
32 return { kind: 'unsupported', message: `no built-in cards for ${target.trim()} yet` }
33 }
34 if (!SPANISH.includes(normalize(native))) {
35 return { kind: 'unsupported', message: `no built-in cards explained in ${native.trim()} yet` }
36 }
37 return { kind: 'cards', cards: ENGLISH_TO_SPANISH }
38}
39
40/** A stable index in [0, count) from a seed (FNV-1a), so one turn keeps one card. */
41export function pickIndex(seed: string, count: number): number {
42 if (count <= 0) return 0
43 let hash = 0x811c9dc5
44 for (let i = 0; i < seed.length; i += 1) {
45 hash ^= seed.charCodeAt(i)
46 hash = Math.imul(hash, 0x01000193) >>> 0
47 }
48 return hash % count
49}
50
51/** The one line a turn shows: a card's word and gloss, or the "no cards" note. */
52export function microLesson(target: string, native: string, turnId: string): string {
53 const found = cardsFor(target, native)
54 if (found.kind === 'unsupported') return found.message
55 const card = found.cards[pickIndex(turnId, found.cards.length)]
56 return card === undefined ? '' : `${card.word} = ${card.gloss}`
57}
58
59/**
60 * The Spinner `suffix` carrying the lesson. The engine draws a rewritten
61 * suffix as given, so the ellipsis it would have drawn is kept in front.
62 */
63export function spinnerSuffix(lesson: string): string {
64 return lesson === '' ? '…' : `… · ${lesson}`
65}
66src/setup.ts 354 lines1// The guided setup as pure logic: the wizard's steps, the strategy catalogue,
2// validation, and reading the saved setup back from `$.store`. The pane that
3// draws it and the `$.store` / `$.state` calls live in hooks/register.tsx.
4
5import { DEFAULT_THEME, isThemeName } from './themes'
6import type {
7 LingoLevel,
8 LingoSetup,
9 LingoSetupDraft,
10 LingoSetupStep,
11 LingoSetupWizard,
12 LingoStrategyChoices,
13 LingoThemeName,
14 LingoTutorModel,
15} from '../types'
16
17/** `$.store` key holding the saved setup. */
18export const SETUP_STORE_KEY = 'setup'
19export const SETUP_VERSION = 1
20export const MAX_LANGUAGE_LENGTH = 40
21
22export const LEVELS: readonly LingoLevel[] = ['A1', 'A2', 'B1', 'B2', 'C1', 'C2']
23export const STEPS: readonly LingoSetupStep[] = [
24 'languages',
25 'level',
26 'interests',
27 'placement',
28 'strategies',
29 'preferences',
30 'summary',
31]
32
33/** The split's share of the terminal's width, in percent: the buttons, and the range a stored value may take. */
34export const SPLIT_SHARES: readonly number[] = [33, 40, 45, 50]
35export const DEFAULT_SPLIT_SHARE = 40
36export const MIN_SPLIT_SHARE = 33
37export const MAX_SPLIT_SHARE = 50
38
39/** Interests: a few short topics, typed comma-separated. */
40export const MAX_INTERESTS = 5
41export const MAX_INTEREST_LENGTH = 40
42export const MAX_INTERESTS_TEXT = 200
43
44export const DEFAULT_TUTOR_MODEL: LingoTutorModel = 'sonnet'
45export const TUTOR_MODELS: readonly { id: LingoTutorModel; label: string }[] = [
46 { id: 'sonnet', label: 'Sonnet' },
47 { id: 'haiku', label: 'Haiku (faster, lighter)' },
48 { id: 'opus', label: 'Opus (slower, uses more of your plan)' },
49]
50
51export type StrategyAxis = keyof LingoStrategyChoices
52export type StrategyOption = { id: string; label: string; isImplemented: boolean }
53export type StrategyAxisInfo = { axis: StrategyAxis; title: string; options: readonly StrategyOption[] }
54
55/**
56 * Every option the design names per axis. Only the implemented ones can be
57 * chosen; the rest are listed as "coming later". Ids match the built-ins
58 * (src/correction/socratic.ts, src/review/pimsleur.ts).
59 */
60export const STRATEGY_AXES: readonly StrategyAxisInfo[] = [
61 {
62 axis: 'correctionStyle',
63 title: 'Correction style',
64 options: [
65 { id: 'socratic', label: 'Socratic (hints before answers)', isImplemented: true },
66 { id: 'direct', label: 'Direct', isImplemented: false },
67 { id: 'progressive-hints', label: 'Progressive hints', isImplemented: false },
68 ],
69 },
70 {
71 axis: 'reviewAlgorithm',
72 title: 'Review algorithm',
73 options: [
74 { id: 'pimsleur', label: 'Pimsleur (n-1, n-3, n-7)', isImplemented: true },
75 { id: 'sm2', label: 'SM-2', isImplemented: false },
76 { id: 'fsrs', label: 'FSRS', isImplemented: false },
77 { id: 'leitner', label: 'Leitner', isImplemented: false },
78 ],
79 },
80 {
81 axis: 'contentStore',
82 title: 'Content store',
83 options: [
84 { id: 'local', label: 'Local (in $.store)', isImplemented: true },
85 { id: 'folder', label: 'Markdown/JSON folder', isImplemented: false },
86 { id: 'anki', label: 'Anki', isImplemented: false },
87 { id: 'obsidian', label: 'Obsidian', isImplemented: false },
88 ],
89 },
90 {
91 axis: 'activityLog',
92 title: 'Activity log',
93 options: [
94 { id: 'local', label: 'Local (in $.store)', isImplemented: true },
95 { id: 'markdown', label: 'Markdown file', isImplemented: false },
96 { id: 'none', label: 'None', isImplemented: false },
97 ],
98 },
99]
100
101export const DEFAULT_STRATEGIES: LingoStrategyChoices = {
102 contentStore: 'local',
103 reviewAlgorithm: 'pimsleur',
104 correctionStyle: 'socratic',
105 activityLog: 'local',
106}
107
108export const CLOSED_WIZARD: LingoSetupWizard = { isOpen: false, step: 'languages', draft: null }
109
110const isImplemented = (axis: StrategyAxis, id: string): boolean =>
111 STRATEGY_AXES.find(info => info.axis === axis)?.options.some(o => o.id === id && o.isImplemented) ?? false
112
113/** The one rule for a language name, wherever it enters: text that is not blank and fits the wizard's cap. */
114export const isLanguageName = (value: unknown): value is string =>
115 typeof value === 'string' && value.trim() !== '' && value.trim().length <= MAX_LANGUAGE_LENGTH
116
117const sameLanguage = (a: string, b: string): boolean => a.trim().toLowerCase() === b.trim().toLowerCase()
118
119// --- Drafts -----------------------------------------------------------------
120
121const PREFERENCE_DEFAULTS = {
122 splitShare: DEFAULT_SPLIT_SHARE,
123 tutorModel: DEFAULT_TUTOR_MODEL,
124 theme: DEFAULT_THEME,
125 // The contextual mode is opt-in.
126 isContextual: false,
127} as const
128
129/**
130 * The assistant's starting point: the `userConfig` languages, no level yet. A
131 * value that is not a valid language name starts empty, and the languages step
132 * asks for it.
133 */
134export function draftFromConfig(nativeLanguage: unknown, targetLanguage: unknown): LingoSetupDraft {
135 return {
136 nativeLanguage: isLanguageName(nativeLanguage) ? nativeLanguage : '',
137 targetLanguage: isLanguageName(targetLanguage) ? targetLanguage : '',
138 level: null,
139 strategies: { ...DEFAULT_STRATEGIES },
140 interests: '',
141 ...PREFERENCE_DEFAULTS,
142 }
143}
144
145/** Re-running `/lingo setup` starts from what is saved. */
146export function draftFromSetup(setup: LingoSetup): LingoSetupDraft {
147 return {
148 nativeLanguage: setup.nativeLanguage,
149 targetLanguage: setup.targetLanguage,
150 level: setup.level,
151 strategies: { ...setup.strategies },
152 interests: setup.interests.join(', '),
153 splitShare: setup.splitShare,
154 tutorModel: setup.tutorModel,
155 theme: setup.theme,
156 isContextual: setup.isContextual,
157 }
158}
159
160/** "chess, cooking,, Chess , jazz" -> ["chess", "cooking", "jazz"]: trimmed, capped, no repeats. */
161export function parseInterests(text: string): string[] {
162 const seen = new Set<string>()
163 const result: string[] = []
164 for (const part of text.split(',')) {
165 const interest = part.trim().slice(0, MAX_INTEREST_LENGTH).trim()
166 const folded = interest.toLowerCase()
167 if (interest === '' || seen.has(folded)) continue
168 seen.add(folded)
169 result.push(interest)
170 if (result.length === MAX_INTERESTS) break
171 }
172 return result
173}
174
175export const isSplitShare = (value: unknown): value is number =>
176 typeof value === 'number' && Number.isInteger(value) && value >= MIN_SPLIT_SHARE && value <= MAX_SPLIT_SHARE
177
178export const isTutorModel = (value: unknown): value is LingoTutorModel =>
179 typeof value === 'string' && TUTOR_MODELS.some(m => m.id === value)
180
181/** Why a step cannot be left yet, or null when it can. */
182export function stepProblem(step: LingoSetupStep, draft: LingoSetupDraft): string | null {
183 if (step === 'languages') {
184 if (draft.nativeLanguage.trim() === '' || draft.targetLanguage.trim() === '') {
185 return 'Fill in both languages.'
186 }
187 if (sameLanguage(draft.nativeLanguage, draft.targetLanguage)) {
188 return 'The two languages must differ.'
189 }
190 }
191 if (step === 'level' && draft.level === null) return 'Pick a level.'
192 return null
193}
194
195export const canAdvance = (step: LingoSetupStep, draft: LingoSetupDraft): boolean =>
196 stepProblem(step, draft) === null
197
198// --- The wizard -------------------------------------------------------------
199
200export type WizardEvent =
201 | { type: 'open' }
202 | { type: 'close' }
203 | { type: 'set-field'; field: 'nativeLanguage' | 'targetLanguage'; value: string }
204 | { type: 'set-level'; level: LingoLevel }
205 | { type: 'set-strategy'; axis: StrategyAxis; id: string }
206 | { type: 'set-interests'; value: string }
207 | { type: 'set-share'; share: number }
208 | { type: 'set-tutor'; model: LingoTutorModel }
209 | { type: 'set-theme'; theme: LingoThemeName }
210 | { type: 'set-contextual'; isOn: boolean }
211 | { type: 'next' }
212 | { type: 'back' }
213 /** Placement: leave the optional test. Strategies: take the defaults and go on. */
214 | { type: 'skip' }
215
216const stepAt = (index: number): LingoSetupStep => STEPS[Math.max(0, Math.min(STEPS.length - 1, index))] ?? 'languages'
217
218/**
219 * The next wizard state. `defaults` is what a draft that was never touched
220 * stands for (the `userConfig` languages, or the saved setup being edited).
221 * Opening a wizard that is already open resumes it where it was.
222 */
223export function wizardTransition(
224 state: LingoSetupWizard,
225 event: WizardEvent,
226 defaults: LingoSetupDraft,
227): LingoSetupWizard {
228 const draft = state.draft ?? defaults
229 switch (event.type) {
230 case 'open':
231 return state.isOpen ? state : { isOpen: true, step: 'languages', draft: null }
232 case 'close':
233 return CLOSED_WIZARD
234 case 'set-field':
235 return { ...state, draft: { ...draft, [event.field]: event.value.slice(0, MAX_LANGUAGE_LENGTH) } }
236 case 'set-level':
237 return LEVELS.includes(event.level) ? { ...state, draft: { ...draft, level: event.level } } : state
238 case 'set-strategy':
239 // A "coming later" option cannot be chosen.
240 return isImplemented(event.axis, event.id)
241 ? { ...state, draft: { ...draft, strategies: { ...draft.strategies, [event.axis]: event.id } } }
242 : state
243 case 'set-interests':
244 return { ...state, draft: { ...draft, interests: event.value.slice(0, MAX_INTERESTS_TEXT) } }
245 case 'set-share':
246 return isSplitShare(event.share) ? { ...state, draft: { ...draft, splitShare: event.share } } : state
247 case 'set-tutor':
248 return isTutorModel(event.model) ? { ...state, draft: { ...draft, tutorModel: event.model } } : state
249 case 'set-theme':
250 return isThemeName(event.theme) ? { ...state, draft: { ...draft, theme: event.theme } } : state
251 case 'set-contextual':
252 return { ...state, draft: { ...draft, isContextual: event.isOn === true } }
253 case 'next':
254 return canAdvance(state.step, draft) && state.step !== 'summary'
255 ? { ...state, draft, step: stepAt(STEPS.indexOf(state.step) + 1) }
256 : state
257 case 'back':
258 return { ...state, draft, step: stepAt(STEPS.indexOf(state.step) - 1) }
259 case 'skip':
260 if (state.step === 'placement') return { ...state, draft, step: 'strategies' }
261 if (state.step === 'strategies') {
262 return { ...state, draft: { ...draft, strategies: { ...DEFAULT_STRATEGIES } }, step: 'preferences' }
263 }
264 return state
265 }
266}
267
268// --- Saving and reading back ------------------------------------------------
269
270/** The setup to save from a finished draft, or null when it is not valid. */
271export function buildSetup(draft: LingoSetupDraft, completedAt: string): LingoSetup | null {
272 if (!canAdvance('languages', draft) || draft.level === null) return null
273 if (!isLanguageName(draft.targetLanguage) || !isLanguageName(draft.nativeLanguage)) return null
274 const { strategies } = draft
275 const isValid = (Object.keys(DEFAULT_STRATEGIES) as StrategyAxis[]).every(axis =>
276 isImplemented(axis, strategies[axis]),
277 )
278 if (!isValid || !isSplitShare(draft.splitShare) || !isTutorModel(draft.tutorModel) || !isThemeName(draft.theme)) {
279 return null
280 }
281 return {
282 version: SETUP_VERSION,
283 targetLanguage: draft.targetLanguage.trim(),
284 nativeLanguage: draft.nativeLanguage.trim(),
285 level: draft.level,
286 strategies: { ...strategies },
287 interests: parseInterests(draft.interests),
288 splitShare: draft.splitShare,
289 tutorModel: draft.tutorModel,
290 theme: draft.theme,
291 isContextual: draft.isContextual,
292 completedAt,
293 }
294}
295
296/** The saved setup with another theme (`/lingo theme <name>`). */
297export const withTheme = (setup: LingoSetup, theme: LingoThemeName): LingoSetup => ({ ...setup, theme })
298
299const isObject = (value: unknown): value is Record<string, unknown> =>
300 typeof value === 'object' && value !== null && !Array.isArray(value)
301
302const isText = (value: unknown): value is string => typeof value === 'string' && value.trim() !== ''
303
304/**
305 * Whatever `$.store` held under `setup`, as a setup, or null when it is not one
306 * this version understands: missing, corrupt, another version, an empty or
307 * over-long language name, an unknown strategy id. Null means setup is pending.
308 * The fields added after the first setups were saved (interests, split share,
309 * tutor model, theme, the contextual opt-in) take their defaults when missing
310 * or unreadable, so an earlier setup stays done.
311 */
312export function parseSetup(raw: unknown): LingoSetup | null {
313 if (!isObject(raw) || raw.version !== SETUP_VERSION) return null
314 const { targetLanguage, nativeLanguage, level, strategies, completedAt, interests, splitShare, tutorModel, theme, isContextual } = raw
315 if (!isLanguageName(targetLanguage) || !isLanguageName(nativeLanguage) || !isText(completedAt)) return null
316 if (typeof level !== 'string' || !LEVELS.includes(level as LingoLevel)) return null
317 if (!isObject(strategies)) return null
318
319 const chosen = {} as Record<StrategyAxis, string>
320 for (const axis of Object.keys(DEFAULT_STRATEGIES) as StrategyAxis[]) {
321 const id = strategies[axis]
322 if (typeof id !== 'string' || !isImplemented(axis, id)) return null
323 chosen[axis] = id
324 }
325
326 return {
327 version: SETUP_VERSION,
328 targetLanguage: targetLanguage.trim(),
329 nativeLanguage: nativeLanguage.trim(),
330 level: level as LingoLevel,
331 strategies: chosen,
332 interests: Array.isArray(interests)
333 ? parseInterests(interests.filter((i): i is string => typeof i === 'string').join(','))
334 : [],
335 splitShare: isSplitShare(splitShare) ? splitShare : DEFAULT_SPLIT_SHARE,
336 tutorModel: isTutorModel(tutorModel) ? tutorModel : DEFAULT_TUTOR_MODEL,
337 theme: isThemeName(theme) ? theme : DEFAULT_THEME,
338 // Only an explicit true turns the opt-in on.
339 isContextual: isContextual === true,
340 completedAt,
341 }
342}
343
344/**
345 * The setup in force: the one mirrored in `$.state` once loaded, else what the
346 * store held (`$.state` resets on /clear). Null means pending.
347 */
348export function resolveSetup(
349 cache: { isLoaded: boolean; setup: LingoSetup | null },
350 stored: unknown,
351): LingoSetup | null {
352 return cache.isLoaded ? cache.setup : parseSetup(stored)
353}
354src/wait-machine.ts 132 lines1// The waiting-state trigger as a pure state machine: what to show while Claude
2// is busy, and when the docked split opens and closes. Timers, `$.ui.open` and
3// the rest live in hooks/register.tsx; this file only decides the next state
4// from the current one and an event.
5
6import type { LingoPaneOpener, LingoWaitState } from '../types'
7
8/** Claude must be busy this long before anything is shown. */
9export const SHOW_DELAY_MS = 2000
10/** After the turn completes the lesson lingers this long, then goes. */
11export const CLOSE_DELAY_MS = 3000
12
13export const INITIAL_WAIT: LingoWaitState = {
14 phase: 'idle',
15 turnId: null,
16 startedAt: null,
17 pane: 'none',
18 opener: null,
19 isTouched: false,
20}
21
22export type WaitEvent =
23 | { type: 'turn-start'; turnId: string; at: number }
24 | { type: 'delay-elapsed'; turnId: string }
25 | { type: 'turn-complete'; turnId: string; isAborted: boolean }
26 | { type: 'countdown-elapsed'; turnId: string }
27 /** A permission ask or an AskUserQuestion: the learner is needed elsewhere. */
28 | { type: 'needs-user' }
29 /** A later tool call ran: whatever asked has been answered. */
30 | { type: 'user-answered' }
31 /** The split is on screen, opened by the mod itself while waiting or by the person. */
32 | { type: 'pane-placed'; opener: LingoPaneOpener }
33 /** The split cannot seat (main screen, too narrow, or not placed): the band offers it. */
34 | { type: 'pane-not-placed' }
35 /** The split is gone (the mod closed it, or the person did). */
36 | { type: 'pane-closed' }
37 /** The person pressed the offer button and opened the split themselves. */
38 | { type: 'offer-taken' }
39 /** A key typed in the split's field or one of its buttons pressed. Getting focus does not count. */
40 | { type: 'touched' }
41
42const PANE_CLOSED = { pane: 'none', opener: null, isTouched: false } as const
43
44/** Idle again; a split that is open stays (the hook decides whether to close it). */
45const idle = (state: LingoWaitState): LingoWaitState => ({
46 ...state,
47 phase: 'idle',
48 turnId: null,
49 startedAt: null,
50 pane: state.pane === 'offered' ? 'none' : state.pane,
51})
52
53export function transition(state: LingoWaitState, event: WaitEvent): LingoWaitState {
54 switch (event.type) {
55 case 'turn-start':
56 // A new turn re-evaluates the offer; a split that is open stays as it is.
57 return {
58 ...(state.pane === 'open' ? state : { ...state, ...PANE_CLOSED }),
59 phase: 'armed',
60 turnId: event.turnId,
61 startedAt: event.at,
62 }
63 case 'delay-elapsed':
64 return state.phase === 'armed' && state.turnId === event.turnId
65 ? { ...state, phase: 'showing' }
66 : state
67 case 'needs-user':
68 return state.phase === 'armed' || state.phase === 'showing'
69 ? { ...state, phase: 'paused' }
70 : state
71 case 'user-answered':
72 return state.phase === 'paused' ? { ...state, phase: 'showing' } : state
73 case 'turn-complete':
74 if (state.turnId !== event.turnId || state.phase === 'idle' || state.phase === 'closing') {
75 return state
76 }
77 // Only a lesson that was on screen gets the short countdown; an interrupted
78 // turn, or one that finished before anything showed (or while retired),
79 // goes idle at once.
80 return event.isAborted || state.phase !== 'showing' ? idle(state) : { ...state, phase: 'closing' }
81 case 'countdown-elapsed':
82 return state.phase === 'closing' && state.turnId === event.turnId ? idle(state) : state
83 case 'pane-placed':
84 return { ...state, pane: 'open', opener: event.opener, isTouched: false }
85 case 'pane-not-placed':
86 return { ...state, ...PANE_CLOSED, pane: 'offered' }
87 case 'pane-closed':
88 case 'offer-taken':
89 return { ...state, ...PANE_CLOSED }
90 case 'touched':
91 return state.pane === 'open' ? { ...state, isTouched: true } : state
92 }
93}
94
95/** The micro-lesson belongs in the spinner while the trigger is showing it. */
96export function isLessonVisible(state: LingoWaitState): boolean {
97 return (state.phase === 'showing' || state.phase === 'closing') && state.turnId !== null
98}
99
100/** The "open lesson" button belongs above the prompt only while showing. */
101export function isOfferVisible(state: LingoWaitState): boolean {
102 return state.phase === 'showing' && state.pane === 'offered'
103}
104
105/** Claude is working (or waiting on the person mid-turn). */
106export function isClaudeWorking(state: LingoWaitState): boolean {
107 return state.phase === 'armed' || state.phase === 'showing' || state.phase === 'paused'
108}
109
110/** The mod opened the split by itself and nobody has used it: it goes when the turn does. */
111export function isUntouchedAuto(state: LingoWaitState): boolean {
112 return state.pane === 'open' && state.opener === 'mod' && !state.isTouched
113}
114
115/**
116 * A split the learner is using: touched, or opened by the person (`/lingo`, the
117 * band). It stays after the turn and closes when its micro-unit ends with Claude
118 * idle, when the learner submits their next prompt, or by hand.
119 */
120export function isKeptOpen(state: LingoWaitState): boolean {
121 return state.pane === 'open' && (state.isTouched || state.opener === 'person')
122}
123
124/** When a completed turn closes the split: now, after the short countdown, or not at all. */
125export function closeOnTurnComplete(
126 state: LingoWaitState,
127 event: { turnId: string; isAborted: boolean },
128): 'now' | 'after-countdown' | 'keep' {
129 if (!isUntouchedAuto(state) || state.turnId !== event.turnId) return 'keep'
130 return transition(state, { type: 'turn-complete', ...event }).phase === 'closing' ? 'after-countdown' : 'now'
131}
132src/split.ts 45 lines1// Sizing and seating of the docked split, and the line that tells a learner
2// studying in it what Claude is doing. Pure: hooks/register.tsx reads the
3// viewport off the render events and calls `$.ui.open` with these numbers.
4
5import type { LingoWaitState } from '../types'
6
7/** The engine docks a pane only in fullscreen and from this many columns (144 for one it opens unasked the first time). */
8export const DOCK_MIN_COLUMNS = 110
9/** An inline pane (no room for the split) is opened about this share of the terminal's height. */
10export const INLINE_ROWS_SHARE = 0.4
11export const MIN_INLINE_ROWS = 8
12
13export type Viewport = { columns: number; rows: number; isFullscreen?: boolean }
14
15/** Whether the split may open by itself: fullscreen and wide enough to dock. */
16export function canSeatSplit(viewport: Viewport | null): boolean {
17 return viewport !== null && viewport.isFullscreen === true && viewport.columns >= DOCK_MIN_COLUMNS
18}
19
20/** The columns the docked split asks for: the share of the terminal's width. */
21export function splitColumns(terminalColumns: number, sharePercent: number): number {
22 return Math.max(1, Math.round((terminalColumns * sharePercent) / 100))
23}
24
25/** The rows an inline pane asks for: about 40 % of the terminal's height. */
26export function inlineRows(terminalRows: number): number {
27 return Math.max(MIN_INLINE_ROWS, Math.round(terminalRows * INLINE_ROWS_SHARE))
28}
29
30/** 41s, 2m 05s. */
31export function formatElapsed(ms: number): string {
32 const seconds = Math.max(0, Math.floor(ms / 1000))
33 if (seconds < 60) return `${seconds}s`
34 return `${Math.floor(seconds / 60)}m ${String(seconds % 60).padStart(2, '0')}s`
35}
36
37/** The top line of the split: what Claude is doing right now. */
38export function claudeStateLine(state: LingoWaitState, nowMs: number): string {
39 if (state.phase === 'paused') return '! Claude needs you · answer below'
40 if (state.phase === 'armed' || state.phase === 'showing') {
41 return state.startedAt === null ? '✻ Claude working' : `✻ Claude working · ${formatElapsed(nowMs - state.startedAt)}`
42 }
43 return '✓ Claude done'
44}
45