Learn AI with LessonFolk: the learn, progress and review skills, and a side pane showing your course, its lessons and the current lesson's key ideas

Learn AI from zero to advanced with an AI tutor, inside Claude Code. The plugin connects Claude Code to the hosted LessonFolk server, where the open-source courses and your progress live.
learn (onboarding, level check, personal learning path, lessons taught as a conversation), progress (where you are, what you can learn) and review (a quiz on lessons you finished). Each skill follows the procedure served by the LessonFolk server and keeps no progress of its own./course-companion..mcp.json): https://lessonfolk.com/mcp, a remote server you sign in to with GitHub or Google (OAuth). Run /mcp, pick LessonFolk and sign in once.https://lessonfolk.com. Your profile (name, experience, goal, language, level, interests), learning path, lesson status, scores and notes are stored on that server, under your own account. The privacy policy is at https://lessonfolk.com/privacy..mcp.json of the folder you are working in, only to find which LessonFolk server to link to from its Dashboard button.The Course companion is a small mod (hooks/register.tsx, readable source, no bundled or downloaded code). It runs no shell command and starts no process. Here is everything it does:
get_progress, list_courses and get_lesson, with the session's own connection and sign-in. It does this when a session starts, when you open the pane, after the learn, review or progress skill runs, and after the tutor itself calls a LessonFolk tool. Nothing is sent to any other server..mcp.json of the folder you are working in, only to find which LessonFolk server (local or hosted) the Dashboard link should open. The content of that file is not sent anywhere.learn, review and progress skills, of the LessonFolk tools and of its own two tools, and ignores the others. It does not read or send the text of your messages or of Claude's replies.key_idea (marks a key idea of the current lesson in the pane) and choices (shows the answers to a question as buttons above the prompt). The mod answers these calls itself and they only update the pane and the buttons. It also adds the /course-companion command and, when the learn skill starts, a short note to Claude explaining these two tools.continue, quiz me, skip this, show my progress). It adds nothing else to the prompt.permissions.allow snippet for the LessonFolk tools. It never writes your settings itself.claude plugin marketplace add CGSeb/lessonfolk
claude plugin install lessonfolk-tutor@lessonfolk
Then say "start" in Claude Code. More in the LessonFolk guide.
Code under the MIT license; course content under CC BY 4.0.
hooks/register.tsx 526 lines1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register } from 'claude-code'
3
4import type { Choices, IdeaMarks, LessonState, View } from '../types'
5import {
6 changes,
7 DEFAULT_INSTANCE,
8 instanceUrl,
9 load,
10 markIdea,
11 parseChoices,
12 PLUGIN_SERVER,
13 replyOf,
14 SERVER,
15 TOOL_PREFIX,
16 togglePick,
17} from './companion'
18import { type Lang, words } from './i18n'
19import { BRAND, LOGO, PROGRESS_WIDTH, progressBar } from './style'
20
21const PANE = 'course-companion'
22// The tools this mod registers: `mcp__<plugin>__<tool>`.
23const OWN_PREFIX = 'mcp__lessonfolk-tutor__'
24const TOOL = 'mcp__lessonfolk-tutor__key_idea'
25const CHOICES_TOOL = 'mcp__lessonfolk-tutor__choices'
26
27const NO_IDEAS: IdeaMarks = { covered: [] }
28
29const isActive = atom({ plugin: 'lessonfolk-tutor', key: 'isActive' } as const, false)
30const choices = atom({ plugin: 'lessonfolk-tutor', key: 'choices' } as const, null as Choices | null)
31const view = atom({ plugin: 'lessonfolk-tutor', key: 'view' } as const, { state: 'no-progress' } as View)
32const snapshot = atom({ plugin: 'lessonfolk-tutor', key: 'snapshot' } as const, null)
33// Whether the technical details of an unreadable progress are unfolded in the pane.
34const detailsOpen = atom({ plugin: 'lessonfolk-tutor', key: 'detailsOpen' } as const, false)
35const langChoice = atom({ plugin: 'lessonfolk-tutor', key: 'langChoice' } as const, null as Lang | null)
36const ideas = atom({ plugin: 'lessonfolk-tutor', key: 'ideas' } as const, NO_IDEAS)
37// The LessonFolk instance the Dashboard button opens (local or hosted).
38const instance = atom({ plugin: 'lessonfolk-tutor', key: 'instance' } as const, DEFAULT_INSTANCE)
39
40const isSkill = (name: string | undefined, skill: string) => name === skill || name?.endsWith(`:${skill}`)
41
42// The server's name as this session knows it: `lessonfolk` from `.mcp.json` or added by hand,
43// the installed plugin's own, or the name of the connector a hosted instance was added under,
44// learned from the tutor's first call to it. Until one answers, both known names are tried.
45let server: string | undefined
46
47// The server's own tools: a connector added in the desktop app is named by an id, not "lessonfolk",
48// so the tool's name, not the server's, tells it is the tutor's.
49const SERVER_TOOLS = new Set([
50 'get_progress', 'list_courses', 'list_themes', 'get_next_lesson', 'get_lesson', 'start_lesson',
51 'complete_lesson', 'skip_lesson', 'save_lesson_notes', 'set_path', 'set_profile', 'reset_course',
52 'level_check_skip_course', 'record_review_score', 'import_progress',
53])
54
55const isLessonfolkTool = (tool: string) =>
56 tool.startsWith(TOOL_PREFIX) ||
57 (/^mcp__[^_].*lessonfolk.*?__/i.test(tool) && !tool.startsWith(OWN_PREFIX) && !tool.startsWith('mcp__course-')) ||
58 (tool.startsWith('mcp__') && !tool.startsWith(OWN_PREFIX) && SERVER_TOOLS.has(tool.split('__')[2] ?? ''))
59
60// Calls a tool of the LessonFolk MCP server with the session's own connection (and sign-in),
61// so it reads the same progress as the tutor, from a local or a hosted instance.
62const callServer = ($: EngineInterface, failures: string[] = []) => async (tool: string, args?: Record<string, unknown>) => {
63 // The name learned from the tutor first, then the two known ones: a wrong guess never blinds the pane.
64 for (const name of [...new Set([server, SERVER, PLUGIN_SERVER])]) {
65 if (!name) continue
66 try {
67 const { content, isError } = await $.mcp.call(name, tool, args)
68 const text = content.flatMap(block => (block.type === 'text' ? [block.text] : [])).join('\n')
69 if (isError) {
70 failures.push(`${name} ${tool}: ${text.slice(0, 120)}`)
71 continue
72 }
73 server = name
74
75 return text
76 } catch (error) {
77 // Not connected under this name: try the next one.
78 failures.push(`${name} ${tool}: ${error instanceof Error ? error.message : String(error)}`.slice(0, 160))
79 }
80 }
81
82 return undefined
83}
84
85// When the app refused the pane's own reads (auto permission mode, typically), the rules that
86// allow them, spelled for the server name each refusal came from.
87const refusedRules = (reason: string[] = []) => {
88 const names = [...new Set(reason.filter(line => /refused/i.test(line)).map(line => line.split(' ')[0] ?? ''))]
89
90 return names.flatMap(name =>
91 ['get_progress', 'list_courses'].map(tool => `mcp__${name.replace(/[:.]/g, '_')}__${tool}`),
92 )
93}
94
95// The settings.json fragment to paste: the pane's text cannot be selected, so it is copied.
96const rulesSnippet = (rules: string[]) => JSON.stringify({ permissions: { allow: rules } }, null, 2)
97
98// Re-reads the progress and the courses from the server; toasts what changed since the last read.
99async function refresh($: EngineInterface, isQuiet = false) {
100 // A relative path would resolve against the mod's own folder: read from the session's.
101 const root = (await $.session.cwd()).replace(/\\/g, '/')
102 const config = await $.fs.read(`${root}/.mcp.json`).then(text => text, () => undefined)
103 await update($, instance, () => instanceUrl(config))
104
105 const failures: string[] = []
106 const picked = (await read($, langChoice)) ?? undefined
107 const loaded = await load(callServer($, failures), picked)
108 if (loaded.view.state === 'offline') loaded.view = { ...loaded.view, reason: [...new Set(failures)].slice(0, 3) }
109 const before = await read($, snapshot)
110 // Offline, the language of the last read is kept.
111 loaded.view.lang = picked ?? loaded.view.lang ?? lastLang
112 lastLang = loaded.view.lang
113 const previous = before ? { snapshot: before, view: await read($, view) } : undefined
114 await update($, view, () => loaded.view)
115 await update($, snapshot, () => loaded.snapshot)
116 await update($, ideas, marks =>
117 marks.lessonId && marks.lessonId === loaded.view.current?.id ? marks : NO_IDEAS,
118 )
119 if (!isQuiet) for (const text of changes(previous, loaded)) $.ui.toast(text)
120}
121
122// Whether this run of the app opened the pane yet. `isActive` is kept with the session and
123// survives a restart, but the pane does not, so the pane opens once per run of the module.
124let hasOpened = false
125
126// The learner's language as of the last read, for words shown outside a render.
127let lastLang: Lang | undefined
128
129// Opens the pane; when the app keeps it waiting undrawn, says why instead of failing silently.
130async function openPane($: EngineInterface) {
131 hasOpened = true
132 const text = words(lastLang)
133 const opened = await $.ui.open({ id: PANE, title: text.title }).catch((error: unknown) => ({
134 isPlaced: false as const,
135 reason: error instanceof Error ? error.message : String(error),
136 }))
137 if (!opened.isPlaced) $.ui.toast(text.waits(opened.reason))
138
139 return opened
140}
141
142// Learning has started: the commands band shows and the pane opens, once per run.
143async function activate($: EngineInterface) {
144 await update($, isActive, () => true)
145 if (!hasOpened) void openPane($)
146}
147
148export const register: Register = on => {
149 on('session.start', async ($, e, next) => {
150 await $.command.register({
151 name: 'course-companion',
152 description: 'Show the LessonFolk course companion pane',
153 })
154 await $.tool.register({
155 name: 'key_idea',
156 description:
157 'Updates the Course companion pane while you teach a LessonFolk lesson. Call it when ' +
158 'you start teaching a key idea of the current lesson (status "active") and when the ' +
159 'learner has understood it (status "done"). Key ideas are numbered from 1 in the ' +
160 'order of the lesson\'s "## Key ideas" section. Lesson progress comes from ' +
161 'the LessonFolk server on its own; this tool only marks key ideas.',
162 inputSchema: {
163 type: 'object',
164 properties: {
165 lesson: { type: 'string', description: 'Lesson id, e.g. ai-foundations/02-how-machines-learn' },
166 keyIdea: { type: 'integer', minimum: 1, description: 'Key idea number, from 1' },
167 status: {
168 type: 'string',
169 enum: ['active', 'done'],
170 description: 'Started teaching it, or understood (default active)',
171 },
172 },
173 required: ['lesson', 'keyIdea'],
174 },
175 })
176 await $.tool.register({
177 name: 'choices',
178 description:
179 'Shows the answers to the question you just asked the LessonFolk learner as buttons ' +
180 'above the prompt; a press sends that answer as the learner\'s reply. Call it after ' +
181 'asking a question with a fixed set of answers you listed: onboarding (experience, ' +
182 'goal, themes to explore), accepting a path, "continue now or stop here?", yes/no. ' +
183 'Never call it for "Check your understanding", review or level check questions: the ' +
184 'learner answers those in their own words. The learner can always type instead.',
185 inputSchema: {
186 type: 'object',
187 properties: {
188 options: {
189 type: 'array',
190 minItems: 2,
191 maxItems: 8,
192 description: 'The answers, in the order you listed them',
193 items: {
194 type: 'object',
195 properties: {
196 label: { type: 'string', description: 'Short button text (1-4 words)' },
197 reply: { type: 'string', description: 'What a press sends, when not the label' },
198 },
199 required: ['label'],
200 },
201 },
202 multiSelect: {
203 type: 'boolean',
204 description: 'True when the learner may pick several (then a Send button sends them)',
205 },
206 },
207 required: ['options'],
208 },
209 })
210 await refresh($, true)
211 // A resumed session where the learner was already learning gets its pane back.
212 if (await read($, isActive)) void openPane($)
213
214 return next(e)
215 })
216
217 on('command.run', { command: 'course-companion' }, async $ => {
218 await refresh($, true)
219 const opened = await openPane($)
220
221 return {
222 text: opened.isPlaced
223 ? 'Course companion pane opened.'
224 : `Course companion pane could not be shown: ${opened.reason}`,
225 }
226 })
227
228 // The learn skill starting is what opens the pane; review and progress keep it current.
229 on('tool.call', { tool: 'Skill' }, async ($, e, next) => {
230 const ran = await next(e)
231 if (ran.deny !== undefined || ran.isError) return ran
232 if (!['learn', 'review', 'progress'].some(skill => isSkill(e.skill, skill))) return ran
233
234 await refresh($, true)
235 if (!isSkill(e.skill, 'learn')) return ran
236
237 await activate($)
238
239 return {
240 ...ran,
241 context: [
242 ...(ran.context ?? []),
243 `A "Course companion" pane shows the learner their course, lessons and the current lesson's ` +
244 `key ideas. It follows the LessonFolk server on its own. While you teach, call ` +
245 `the ${TOOL} tool as you start each key idea (status "active") and once the learner ` +
246 `has it (status "done"). After asking a question with a fixed set of answers ` +
247 `(onboarding, path, continue or stop), call ${CHOICES_TOOL} so the learner can ` +
248 `answer with a button; never for check-your-understanding, review or level check questions.`,
249 ],
250 }
251 })
252
253 on('tool.call', { tool: TOOL }, async ($, e) => {
254 const input = (e as unknown as { input?: Record<string, unknown> }).input ??
255 (e as unknown as Record<string, unknown>)
256 const lesson = typeof input.lesson === 'string' ? input.lesson : undefined
257 const keyIdea = Number(input.keyIdea)
258 const status = input.status === 'done' ? 'done' : 'active'
259 if (!lesson || !Number.isInteger(keyIdea) || keyIdea < 1) {
260 return { result: 'Nothing updated: give the lesson id and a key idea number from 1.' }
261 }
262
263 const current = (await read($, view)).current
264 if (current?.id !== lesson) await refresh($, true)
265 await update($, ideas, marks => markIdea(marks, lesson, keyIdea, status))
266 await activate($)
267
268 return { result: 'Course companion pane updated.' }
269 })
270
271 on('tool.call', { tool: CHOICES_TOOL }, async ($, e) => {
272 const input = (e as unknown as { input?: Record<string, unknown> }).input ??
273 (e as unknown as Record<string, unknown>)
274 const offered = parseChoices(input)
275 if (!offered) return { result: 'Nothing shown: give 2 to 8 options, each with a label.' }
276
277 await update($, choices, () => offered)
278 // The tutor asking the learner something means a learning session: the band stays once
279 // the question is answered, even before any progress exists (onboarding).
280 await update($, isActive, () => true)
281
282 return { result: 'The answers are shown as buttons above the prompt.' }
283 })
284
285 // Any reply, pressed or typed, answers the question: its buttons go.
286 on('prompt.submit', async ($, e, next) => {
287 await update($, choices, () => null)
288
289 return next(e)
290 })
291
292 // Any call of the tutor to the LessonFolk server (a save, or reading the progress) is the
293 // moment to re-read it: that is the source of truth for lessons and courses.
294 let isRefreshing = false
295 on('tool.call', async ($, e, next) => {
296 if (!isLessonfolkTool(e.tool)) return next(e)
297 const ran = await next(e)
298 if (isRefreshing || ran.deny !== undefined || ran.isError) return ran
299
300 // A tool's name spells the server with `:` and `.` replaced by `_`: the plugin's real name has colons.
301 const spelled = e.tool.split('__')[1]
302 server = spelled === PLUGIN_SERVER.replace(/[:.]/g, '_') ? PLUGIN_SERVER : spelled ?? server
303 isRefreshing = true
304 try {
305 await refresh($)
306 await activate($)
307 } finally {
308 isRefreshing = false
309 }
310
311 return ran
312 })
313
314 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
315 if (e.props.hasSurvey) return next(e)
316 const offered = await read($, choices)
317 if (!offered && !(await read($, isActive))) return next(e)
318
319 const { Box, Button, Link, Text } = $.ui.resolve(e)
320 const text = words((await read($, view)).lang)
321
322 // Always last: the pane, and the dashboard of the instance the tutor works with.
323 const tools = [
324 <Text key="sep" dimColor>·</Text>,
325 <Button key="pane" label={text.companion} onPress={() => void openPane($)} />,
326 <Link key="dashboard" href={await read($, instance)} label={text.dashboard} />,
327 ]
328
329 // The tutor's question takes the band until it is answered; then the commands come back.
330 if (offered) {
331 const send = (reply: string) => {
332 void update($, choices, () => null)
333 void $.prompt.submit({ text: reply, asUser: true })
334 }
335
336 return (
337 <Box flexWrap="wrap" gap={1}>
338 <Text dimColor>{text.answer}</Text>
339 {offered.options.map((o, i) => (
340 <Button
341 key={`choice-${i}`}
342 label={offered.isMulti && offered.picked.includes(i) ? `✓ ${o.label}` : o.label}
343 onPress={() =>
344 offered.isMulti ? void update($, choices, c => (c ? togglePick(c, i) : c)) : send(o.reply)
345 }
346 />
347 ))}
348 {offered.isMulti && offered.picked.length > 0 && (
349 <Button key="send" label={text.send} onPress={() => send(replyOf(offered))} />
350 )}
351 {tools}
352 </Box>
353 )
354 }
355
356 return (
357 <Box gap={1}>
358 <Text dimColor>{text.say}</Text>
359 {text.commands.map(c => (
360 <Button key={c.key} label={c.label} onPress={() => void $.prompt.submit({ text: c.text, asUser: true })} />
361 ))}
362 {tools}
363 </Box>
364 )
365 })
366
367 on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
368 const { Box, Button, Text, Svg } = $.ui.resolve(e)
369 const v = await read($, view)
370 const marks = await read($, ideas)
371 const text = words(v.lang)
372 // The terminal draws no vector images: there the logo is left out and the bar is text.
373 const hasSvg = e.surface !== 'terminal'
374
375 // The logo and the name, with the switch to the other language.
376 const other: Lang = v.lang === 'fr' ? 'en' : 'fr'
377 const header = (
378 <Box flexDirection="row" gap={1} alignItems="center">
379 {hasSvg && <Svg source={LOGO} alt="LessonFolk" width={24} height={24} />}
380 <Text bold color={BRAND.accent}>LessonFolk</Text>
381 <Button
382 key="lang"
383 label={other === 'fr' ? 'Français' : 'English'}
384 dimColor
385 onPress={() => {
386 void (async () => {
387 await update($, langChoice, () => other)
388 await update($, view, current => ({ ...current, lang: other }))
389 // The course and lesson titles come from the server in that language.
390 await refresh($, true)
391 })()
392 }}
393 />
394 </Box>
395 )
396
397 if (v.state === 'no-progress' || v.state === 'offline' || v.state === 'all-done') {
398 const lines = {
399 'no-progress': text.noProgress,
400 offline: text.offline,
401 'all-done': text.allDone,
402 }[v.state]
403
404 const rules = refusedRules(v.reason)
405 const hint = rules.length > 0 ? text.refused : []
406 // The raw errors stay folded: they help to report a problem, not to use the pane.
407 const details = rules.length > 0 ? [] : (v.reason ?? [])
408 const isOpen = details.length > 0 && (await read($, detailsOpen))
409
410 return (
411 <Box flexDirection="column">
412 {header}
413 <Text> </Text>
414 {[...lines, ...hint, ...rules].map((line, i) => (
415 // The first line is the message, the rest explains it.
416 <Text dimColor={i > 0}>{line}</Text>
417 ))}
418 {details.length > 0 && (
419 <Button
420 key="details"
421 label={isOpen ? text.hideDetails : text.showDetails}
422 onPress={() => void update($, detailsOpen, open => !open)}
423 />
424 )}
425 {isOpen && details.map(line => <Text dimColor>{line}</Text>)}
426 {rules.length > 0 && (
427 <Button
428 key="copy-rules"
429 label={text.copyRules}
430 onPress={async press => {
431 const { isCopied } = await $.ui.copy({ text: rulesSnippet(rules), surface: press.surface })
432 $.ui.toast(isCopied ? text.copied : text.copyFailed)
433 }}
434 />
435 )}
436 </Box>
437 )
438 }
439
440 const lessons = v.lessons ?? []
441 const finished = lessons.filter(l => l.status === 'done' || l.status === 'skipped').length
442 const mark = (s: LessonState['status']) =>
443 ({ done: '✓', skipped: '↷', current: '●', todo: '○' })[s]
444 const ideaMark = (i: number) =>
445 marks.covered.includes(i) ? '✓' : marks.active === i ? '●' : '○'
446
447 return (
448 <Box flexDirection="column">
449 {header}
450 <Text> </Text>
451 <Text bold>{v.courseTitle}</Text>
452 {(v.themeTitle || v.level) && (
453 <Text dimColor>{[v.themeTitle, v.level && (text.levels[v.level] ?? v.level)].filter(Boolean).join(' · ')}</Text>
454 )}
455 <Text> </Text>
456 {/* On the desktop the title, the bar and the cards are spaced apart; the terminal packs them. */}
457 <Box flexDirection="column" gap={hasSvg ? 1 : 0}>
458 <Text bold>
459 {text.lessons} {finished}/{lessons.length}
460 </Text>
461 {hasSvg && lessons.length > 0 && (
462 <Svg
463 source={progressBar(finished, lessons.length)}
464 alt={text.progressAlt(finished, lessons.length)}
465 width={PROGRESS_WIDTH}
466 height={8}
467 />
468 )}
469 {/* The terminal's borders already separate the cards; the other surfaces need a gap. */}
470 <Box flexDirection="column" gap={hasSvg ? 1 : 0}>
471 {lessons.map(l => {
472 const isCurrent = l.status === 'current'
473 const faded = l.status === 'done' || l.status === 'skipped'
474
475 // One small rounded card per lesson: the current one is filled with the logo's indigo
476 // and its text takes the logo's amber; finished ones carry a green tick.
477 return (
478 <Box
479 flexDirection="row"
480 gap={1}
481 paddingX={1}
482 borderStyle="round"
483 borderColor={isCurrent ? BRAND.indigo : BRAND.border}
484 borderDimColor={!isCurrent}
485 backgroundColor={isCurrent ? BRAND.indigo : undefined}
486 >
487 <Text bold color={isCurrent ? BRAND.amber : l.status === 'done' ? BRAND.success : undefined} dimColor={l.status === 'todo' || l.status === 'skipped'}>
488 {mark(l.status)}
489 </Text>
490 <Text bold={isCurrent} color={isCurrent ? BRAND.amber : undefined} dimColor={faded}>
491 {l.title}
492 </Text>
493 {l.status === 'skipped' && <Text dimColor>{text.skipped}</Text>}
494 {isCurrent && <Text bold color={BRAND.amber}>· {text.inProgress}</Text>}
495 </Box>
496 )
497 })}
498 </Box>
499 </Box>
500 {v.current && v.current.ideas.length > 0 && <Text> </Text>}
501 {v.current && v.current.ideas.length > 0 && <Text bold>{text.keyIdeas}</Text>}
502 {v.current?.ideas.map((idea, i) => (
503 <Box flexDirection="row" gap={1}>
504 <Text bold color={ideaMark(i + 1) === '✓' ? BRAND.success : ideaMark(i + 1) === '●' ? BRAND.accent : undefined} dimColor={ideaMark(i + 1) === '○'}>
505 {ideaMark(i + 1)}
506 </Text>
507 <Text dimColor={ideaMark(i + 1) === '✓'} bold={ideaMark(i + 1) === '●'} color={ideaMark(i + 1) === '●' ? BRAND.accent : undefined}>
508 {i + 1}. {idea}
509 </Text>
510 </Box>
511 ))}
512 {v.next && <Text> </Text>}
513 {v.next && (
514 // A soft off-white bubble: the next lesson stands out without shouting.
515 <Box paddingX={1} borderStyle="round" borderColor={BRAND.surface} backgroundColor={BRAND.surface}>
516 <Text color={BRAND.ink}>
517 {text.next} {v.next.title}
518 {v.next.courseTitle ? ` (${v.next.courseTitle})` : ''}
519 </Text>
520 </Box>
521 )}
522 </Box>
523 )
524 })
525}
526hooks/companion.ts 240 lines1// Pure logic of the Course companion: reads the learner's progress and the courses from the
2// LessonFolk MCP server through a `call` function, so it runs the same in the mod and in its
3// tests, with a local or a hosted instance.
4
5import type { Choices, IdeaMarks, LessonState, Snapshot, View } from '../types'
6import { type Lang, langOf, words } from './i18n'
7
8// Calls a tool of the LessonFolk MCP server: the tool's text result, or undefined when it
9// failed or the server could not be reached.
10export type Caller = (tool: string, args?: Record<string, unknown>) => Promise<string | undefined>
11
12// The name of the server in `.mcp.json` (what `claude mcp add lessonfolk …` registers).
13export const SERVER = 'lessonfolk'
14export const TOOL_PREFIX = `mcp__${SERVER}__`
15// The same server when the installed plugin brought it (the marketplace entry declares it).
16export const PLUGIN_SERVER = `plugin:lessonfolk-tutor:${SERVER}`
17
18type Progress = {
19 profile?: { level?: string; language?: string }
20 path?: string[]
21 current?: string | null
22 lessons?: Record<string, { status?: string; completedAt?: string }>
23}
24
25type CourseSummary = {
26 id: string
27 title: string
28 level?: string
29 themeTitle?: string
30 lessons: { id: string; title: string; prerequisites?: string[]; status?: string }[]
31}
32
33// The `## Key ideas` items: their bold lead when they have one, else their first words.
34export const keyIdeas = (lesson: string): string[] => {
35 const section = /^## Key ideas\s*$([\s\S]*?)(?=^## |(?![\s\S]))/m.exec(lesson)?.[1] ?? ''
36
37 return [...section.matchAll(/^\d+\.\s+(.+)$/gm)].map(m => {
38 const text = m[1] ?? ''
39 const bold = /^\*\*(.+?)\*\*/.exec(text)?.[1]
40 const label = (bold ?? text).replace(/\*\*|\*|`/g, '').replace(/[.:]\s*$/, '').trim()
41
42 return label.length > 70 ? `${label.slice(0, 67).trimEnd()}…` : label
43 })
44}
45
46// `list_courses` statuses: not_started, in_progress, done, skipped, skipped_after_level_check.
47const isFinished = (status?: string) =>
48 status === 'done' || status === 'skipped' || status === 'skipped_after_level_check'
49
50const courseOf = (lessonId: string) => lessonId.split('/')[0] ?? lessonId
51
52const parseJson = <T>(text?: string): T | undefined => {
53 if (text === undefined) return undefined
54 try {
55 const parsed = JSON.parse(text) as T
56
57 return parsed && typeof parsed === 'object' ? parsed : undefined
58 } catch {
59 return undefined
60 }
61}
62
63export const statusesOf = (progress?: Progress): Snapshot['statuses'] =>
64 Object.fromEntries(
65 Object.entries(progress?.lessons ?? {}).map(([id, l]) => [id, l?.status ?? 'in_progress']),
66 )
67
68export type Loaded = { view: View; snapshot: Snapshot }
69
70// Builds the pane's view: the course in focus (the current lesson's, else the next lesson's),
71// its lessons, the current lesson's key ideas and the next lesson, following the order of
72// "Start or resume" (the learner's path first, then the catalog order of list_courses).
73export const load = async (call: Caller, picked?: Lang): Promise<Loaded> => {
74 const progress = parseJson<Progress>(await call('get_progress'))
75 // The language the learner picked in the pane: the course titles follow it, not the profile's.
76 const asked = picked ? { lang: picked } : undefined
77 const catalog = parseJson<CourseSummary[]>(await call('list_courses', asked))
78 const statuses = statusesOf(progress)
79 const snapshot: Snapshot = { current: progress?.current ?? undefined, statuses }
80 const lang = progress ? langOf(progress.profile?.language) : undefined
81
82 if (!progress || !Array.isArray(catalog)) return { view: { state: 'offline', lang }, snapshot }
83 if (!progress.profile?.level && Object.keys(statuses).length === 0) {
84 return { view: { state: 'no-progress', lang }, snapshot }
85 }
86
87 const byId = new Map(catalog.map(course => [course.id, course]))
88 const order = [...(progress.path ?? []).filter(id => byId.has(id))]
89 for (const course of catalog) if (!order.includes(course.id)) order.push(course.id)
90
91 const lessonTitle = (id: string) =>
92 catalog.flatMap(course => course.lessons).find(lesson => lesson.id === id)?.title ?? id
93
94 // The first unfinished lesson whose prerequisites are finished; `current` counts as finished.
95 const done = (id: string) => isFinished(statuses[id]) || id === progress.current
96 const eligible = (lessons: CourseSummary['lessons']) =>
97 lessons.find(lesson => !done(lesson.id) && (lesson.prerequisites ?? []).every(done))?.id
98
99 // Like the server, stay in the partly finished course whose last lesson was done most
100 // recently (even outside the path), before walking the path and the catalog.
101 let started: CourseSummary | undefined
102 let startedAt = ''
103 for (const course of order.map(id => byId.get(id))) {
104 if (!course) continue
105 const finished = course.lessons.filter(lesson => isFinished(statuses[lesson.id]))
106 if (!finished.length || finished.length === course.lessons.length) continue
107 const latest = finished
108 .map(lesson => (statuses[lesson.id] === 'done' ? progress.lessons?.[lesson.id]?.completedAt : undefined) ?? '')
109 .reduce((a, b) => (b > a ? b : a), '')
110 if (latest > startedAt) {
111 started = course
112 startedAt = latest
113 }
114 }
115
116 const next = (started && eligible(started.lessons)) ??
117 eligible(order.flatMap(id => byId.get(id)?.lessons ?? []))
118
119 const current = progress.current && statuses[progress.current] !== undefined &&
120 !isFinished(statuses[progress.current])
121 ? progress.current
122 : undefined
123 const focus = current ?? next
124 if (!focus) return { view: { state: 'all-done', lang }, snapshot }
125
126 const courseId = courseOf(focus)
127 const course = byId.get(courseId)
128 const lessons: LessonState[] = (course?.lessons ?? []).map(lesson => ({
129 id: lesson.id,
130 title: lesson.title,
131 status: lesson.id === current
132 ? 'current'
133 : isFinished(statuses[lesson.id]) ? (statuses[lesson.id] === 'done' ? 'done' : 'skipped') : 'todo',
134 }))
135 const ideas = current ? keyIdeas((await call('get_lesson', { lessonId: current, ...asked })) ?? '') : []
136
137 return {
138 view: {
139 state: current ? 'lesson' : 'between',
140 lang,
141 courseId,
142 courseTitle: course?.title ?? courseId,
143 themeTitle: course?.themeTitle,
144 level: course?.level,
145 lessons,
146 current: current ? { id: current, title: lessonTitle(current), ideas } : undefined,
147 next: next
148 ? {
149 id: next,
150 title: lessonTitle(next),
151 courseTitle: courseOf(next) === courseId ? undefined : byId.get(courseOf(next))?.title ?? courseOf(next),
152 }
153 : undefined,
154 },
155 snapshot,
156 }
157}
158
159// The LessonFolk instance the Dashboard button opens: the origin of the `lessonfolk` url in the
160// project's `.mcp.json` (the MCP endpoint is `<instance>/mcp`), as in a clone of the repository;
161// otherwise the hosted instance, the one the installed plugin connects to (the same address as
162// in `.claude-plugin/marketplace.json`).
163export const DEFAULT_INSTANCE = 'https://lessonfolk.com/'
164
165export const instanceUrl = (mcpJson?: string): string => {
166 try {
167 const config = JSON.parse(mcpJson ?? '{}') as { mcpServers?: Record<string, { url?: string }> }
168 const url = new URL(config.mcpServers?.[SERVER]?.url ?? '')
169
170 return url.protocol === 'http:' || url.protocol === 'https:' ? `${url.origin}/` : DEFAULT_INSTANCE
171 } catch {
172 return DEFAULT_INSTANCE
173 }
174}
175
176// What changed between two reads of the progress, worth a toast.
177export const changes = (previous: Loaded | undefined, loaded: Loaded): string[] => {
178 if (!previous) return []
179 const { snapshot: before } = previous
180 const { snapshot: after, view } = loaded
181 const toasts: string[] = []
182 const text = words(view.lang)
183 const titleOf = (id: string) =>
184 [...(view.lessons ?? []), ...(previous.view.lessons ?? [])].find(l => l.id === id)?.title ?? id
185
186 for (const [id, status] of Object.entries(after.statuses)) {
187 if (status === 'done' && before.statuses[id] !== 'done') toasts.push(text.lessonComplete(titleOf(id)))
188 }
189
190 const course = after.current ? courseOf(after.current) : undefined
191 const hadStarted = Object.entries(before.statuses).some(
192 ([id, status]) => courseOf(id) === course && (isFinished(status) || id === before.current),
193 )
194 if (course && after.current !== before.current && !hadStarted && view.courseId === course) {
195 toasts.push(text.newCourse(view.courseTitle ?? course, view.themeTitle))
196 }
197
198 return toasts
199}
200
201// The tutor's report on a key idea: `active` starts it, `done` finishes it; earlier ones are covered.
202export const markIdea = (marks: IdeaMarks, lessonId: string, keyIdea: number, status: 'active' | 'done'): IdeaMarks => {
203 const covered = marks.lessonId === lessonId ? marks.covered : []
204 const upTo = status === 'done' ? keyIdea : keyIdea - 1
205 const all = new Set(covered)
206 for (let i = 1; i <= upTo; i++) all.add(i)
207
208 return {
209 lessonId,
210 covered: [...all].sort((a, b) => a - b),
211 active: status === 'active' ? keyIdea : undefined,
212 }
213}
214
215// The tutor's offered answers, from the choices tool's input: 2 to 8 options with a label.
216export const parseChoices = (input: Record<string, unknown>): Choices | undefined => {
217 const raw = Array.isArray(input.options) ? (input.options as unknown[]) : []
218 const options = raw.flatMap(option => {
219 const o = (typeof option === 'string' ? { label: option } : option ?? {}) as Record<string, unknown>
220 const label = typeof o.label === 'string' ? o.label.trim() : ''
221 const reply = typeof o.reply === 'string' && o.reply.trim() ? o.reply.trim() : label
222
223 return label ? [{ label, reply }] : []
224 })
225 if (options.length < 2 || options.length > 8) return undefined
226
227 return { options, isMulti: input.multiSelect === true, picked: [] }
228}
229
230// What the learner sends: the picked options' replies, in the order the tutor listed them.
231export const replyOf = (choices: Choices) =>
232 choices.options.filter((_, i) => choices.picked.includes(i)).map(o => o.reply).join(', ')
233
234export const togglePick =(choices: Choices, index: number): Choices => ({
235 ...choices,
236 picked: choices.picked.includes(index)
237 ? choices.picked.filter(i => i !== index)
238 : [...choices.picked, index].sort((a, b) => a - b),
239})
240hooks/i18n.ts 120 lines1// The words of the Course companion (pane, buttons, toasts) in the learner's language, which
2// is the language saved in their profile (`get_progress`). English is the fallback. What the
3// mod tells the model (tool descriptions and results) stays in English.
4
5export type Lang = 'en' | 'fr'
6
7// A profile language code ("fr", "fr-CA"…) to a language the mod has words for.
8export const langOf = (code?: string): Lang =>
9 code?.trim().toLowerCase().split(/[-_]/)[0] === 'fr' ? 'fr' : 'en'
10
11type Words = {
12 title: string
13 // The learner commands offered as buttons: what the button says, and what a press sends.
14 commands: { key: string; label: string; text: string }[]
15 say: string
16 answer: string
17 send: string
18 companion: string
19 dashboard: string
20 lessons: string
21 keyIdeas: string
22 next: string
23 skipped: string
24 inProgress: string
25 levels: Record<string, string>
26 noProgress: string[]
27 offline: string[]
28 allDone: string[]
29 refused: string[]
30 progressAlt: (finished: number, total: number) => string
31 showDetails: string
32 hideDetails: string
33 copyRules: string
34 copied: string
35 copyFailed: string
36 lessonComplete: (title: string) => string
37 newCourse: (course: string, theme?: string) => string
38 waits: (reason: string) => string
39}
40
41const en: Words = {
42 title: 'Course companion',
43 commands: [
44 { key: 'continue', label: 'Continue', text: 'continue' },
45 { key: 'quiz', label: 'Quiz me', text: 'quiz me' },
46 { key: 'skip', label: 'Skip', text: 'skip this' },
47 { key: 'progress', label: 'My progress', text: 'show my progress' },
48 ],
49 say: 'Say:',
50 answer: 'Answer:',
51 send: 'Send',
52 companion: 'Companion',
53 dashboard: 'Dashboard ↗',
54 lessons: 'Lessons',
55 keyIdeas: 'Key ideas',
56 next: 'Next lesson:',
57 skipped: '(skipped)',
58 inProgress: 'In progress',
59 levels: {},
60 noProgress: ['No course started yet.', 'Say "start" to begin.'],
61 offline: [
62 'Waiting for the tutor.',
63 'This pane fills in once the tutor reads your progress: say "continue" to start or resume a lesson.',
64 'Still empty after that? Check that the LessonFolk server is connected (/mcp).',
65 ],
66 allDone: ['You have finished every course. Well done!', 'Ask the tutor what to explore next.'],
67 refused: ["The app refused the pane's read.", 'Allow it in ~/.claude/settings.json (permissions.allow):'],
68 progressAlt: (finished, total) => `${finished} of ${total} lessons finished`,
69 showDetails: 'Show details ▸',
70 hideDetails: 'Hide details ▾',
71 copyRules: 'Copy rules',
72 copied: 'Copied: paste it into ~/.claude/settings.json',
73 copyFailed: 'Could not copy to the clipboard',
74 lessonComplete: title => `Lesson complete: ${title}`,
75 newCourse: (course, theme) => `New course: ${course}${theme ? ` (${theme})` : ''}`,
76 waits: reason => `Course companion waits: ${reason}`,
77}
78
79const fr: Words = {
80 title: 'Compagnon de cours',
81 commands: [
82 { key: 'continue', label: 'Continuer', text: 'continue' },
83 { key: 'quiz', label: 'Interroge-moi', text: 'interroge-moi' },
84 { key: 'skip', label: 'Passer', text: 'passe cette leçon' },
85 { key: 'progress', label: 'Ma progression', text: 'montre ma progression' },
86 ],
87 say: 'Dites :',
88 answer: 'Répondez :',
89 send: 'Envoyer',
90 companion: 'Compagnon',
91 dashboard: 'Tableau de bord ↗',
92 lessons: 'Leçons',
93 keyIdeas: 'Idées clés',
94 next: 'Prochaine leçon :',
95 skipped: '(passée)',
96 inProgress: 'En cours',
97 levels: { beginner: 'débutant', intermediate: 'intermédiaire', advanced: 'avancé' },
98 noProgress: ['Aucun cours commencé pour l’instant.', 'Dites « commencer » pour démarrer.'],
99 offline: [
100 'En attente du tuteur.',
101 'Ce panneau se remplit dès que le tuteur lit votre progression : dites « continue » pour démarrer ou reprendre une leçon.',
102 'Toujours vide après ça ? Vérifiez que le serveur LessonFolk est connecté (/mcp).',
103 ],
104 allDone: ['Vous avez terminé tous les cours. Bravo !', 'Demandez au tuteur quoi explorer ensuite.'],
105 refused: ['L’application a refusé la lecture du panneau.', 'Autorisez-la dans ~/.claude/settings.json (permissions.allow) :'],
106 progressAlt: (finished, total) => `${finished} leçons terminées sur ${total}`,
107 showDetails: 'Afficher les détails ▸',
108 hideDetails: 'Masquer les détails ▾',
109 copyRules: 'Copier les règles',
110 copied: 'Copié : collez-le dans ~/.claude/settings.json',
111 copyFailed: 'Impossible de copier dans le presse-papiers',
112 lessonComplete: title => `Leçon terminée : ${title}`,
113 newCourse: (course, theme) => `Nouveau cours : ${course}${theme ? ` (${theme})` : ''}`,
114 waits: reason => `Le compagnon de cours attend : ${reason}`,
115}
116
117const WORDS: Record<Lang, Words> = { en, fr }
118
119export const words = (lang?: Lang): Words => WORDS[lang ?? 'en']
120hooks/style.ts 39 lines1// The look of the Course companion: the colours and drawings of the LessonFolk brand
2// (docs/brand.md, "Bright Thread"), kept apart from the logic so the tests can read them.
3// The pane cannot tell the light theme from the dark one, so the colours are mid tones that read on both.
4
5export const BRAND = {
6 indigo: '#4f46e5',
7 // The accent: the learner's side (the current lesson, the key idea in progress).
8 accent: '#818cf8',
9 // The tutor's neutral bubble (--neutral-50): the next lesson's background.
10 surface: '#f1f1f8',
11 // Text on that bubble (--color-text).
12 ink: '#1a1c33',
13 // Finished: the site's success green (--color-success).
14 success: '#16a34a',
15 // The spark: the text on the current lesson's indigo card, as the mark's sparkle on its square.
16 amber: '#fbbf24',
17 // The border of the cards that are not the current one (--neutral-400).
18 border: '#9496b0',
19}
20
21// `assets/brand/icon.svg`: the mark, the same in light and dark.
22export const LOGO = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64">
23 <rect width="64" height="64" rx="16" fill="#4F46E5"/>
24 <path d="M22 14 L22 46 L42 46" fill="none" stroke="#fff" stroke-width="7" stroke-linecap="round" stroke-linejoin="round"/>
25 <path d="M43 13Q44.6 22.4 54 24Q44.6 25.6 43 35Q41.4 25.6 32 24Q41.4 22.4 43 13Z" fill="#FBBF24"/>
26</svg>`
27
28export const PROGRESS_WIDTH = 220
29
30// A rounded bar, filled in proportion to the lessons finished.
31export const progressBar = (finished: number, total: number): string => {
32 const fill = total > 0 ? Math.round((PROGRESS_WIDTH * Math.min(finished, total)) / total) : 0
33
34 return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${PROGRESS_WIDTH} 8">` +
35 `<rect width="${PROGRESS_WIDTH}" height="8" rx="4" fill="#9496b0" fill-opacity="0.3"/>` +
36 (fill > 0 ? `<rect width="${Math.max(fill, 8)}" height="8" rx="4" fill="${BRAND.accent}"/>` : '') +
37 '</svg>'
38}
39types/index.d.ts 51 lines1export type LessonState = {
2 id: string
3 title: string
4 status: 'done' | 'skipped' | 'current' | 'todo'
5}
6
7export type View = {
8 state: 'no-progress' | 'offline' | 'all-done' | 'lesson' | 'between'
9 // The learner's language (profile), for the words of the pane; unknown when offline.
10 lang?: 'en' | 'fr'
11 courseId?: string
12 courseTitle?: string
13 themeTitle?: string
14 level?: string
15 lessons?: LessonState[]
16 current?: { id: string; title: string; ideas: string[] }
17 next?: { id: string; title: string; courseTitle?: string }
18 // Offline only: why each attempt to reach the server failed.
19 reason?: string[]
20}
21
22// Lesson statuses as last read from the server, to spot what a save changed.
23export type Snapshot = { current?: string; statuses: Record<string, string> }
24
25// Key ideas of `lessonId` the tutor reported: 1-based numbers.
26export type IdeaMarks = { lessonId?: string; covered: number[]; active?: number }
27
28// The answers the tutor offered for the question it just asked, shown as buttons above the prompt.
29export type Choices = {
30 options: { label: string; reply: string }[]
31 isMulti: boolean
32 picked: number[]
33}
34
35
36declare module 'claude-code' {
37 interface PluginState {
38 'lessonfolk-tutor': {
39 isActive: boolean
40 instance: string
41 choices: Choices | null
42 view: View
43 snapshot: Snapshot | null
44 ideas: IdeaMarks
45 detailsOpen: boolean
46 // The language the learner picked in the pane, over the profile's.
47 langChoice: 'en' | 'fr' | null
48 }
49 }
50}
51