diff --git a/.changeset/recorder-voice-over.md b/.changeset/recorder-voice-over.md new file mode 100644 index 0000000..5d5915a --- /dev/null +++ b/.changeset/recorder-voice-over.md @@ -0,0 +1,5 @@ +--- +'@interactive-learning/recorder': minor +--- + +The recorder gives a guide its voice-over. `addVoiceOver` has ElevenLabs read each line of the story aloud and writes on each line the `audio` and the `words` that the player plays and shows as captions. A line already read is kept next to the guide under a name that follows from its text, its voice and its model, so it is never billed twice. Steps get longer where a line lasts longer than them, so the voice always ends before the next line. The key comes from `ELEVENLABS_API_KEY`; without it, new lines stay silent. diff --git a/.changeset/skill-scenarios-first.md b/.changeset/skill-scenarios-first.md new file mode 100644 index 0000000..18b01fc --- /dev/null +++ b/.changeset/skill-scenarios-first.md @@ -0,0 +1,5 @@ +--- +'@interactive-learning/recorder': patch +--- + +The AI skill now makes guides from Playwright scenarios run headless, which build the guide with the recorder, give it its voice-over and publish it to the public folder of the project. Each step says something, read aloud as the guide plays. The desktop studio is described as coming, and the skill no longer uses it unless the user asks for it. diff --git a/packages/recorder/README.md b/packages/recorder/README.md index 5da7732..7ac423f 100644 --- a/packages/recorder/README.md +++ b/packages/recorder/README.md @@ -107,6 +107,46 @@ Open an existing guide with `new RecordingSession('guides/demo/guide.json')`. PN The package also exports `validateGuide`, `createGuide`, `GuideValidationError`, `SCHEMA_VERSION` and the guide types. +## Voice-over + +A guide can tell a story under its screenshots: `story` lines, each with the moment it starts. `addVoiceOver` has [ElevenLabs](https://elevenlabs.io) read each line aloud, like the voice-over of a video, and gives each line the two fields that the player plays: `audio`, the sound, and `words`, each word with the moment it is said, which the player shows as captions lit as they are spoken. + +```ts +import { readFile, writeFile } from 'node:fs/promises'; +import { addVoiceOver, validateGuide } from '@interactive-learning/recorder'; + +const guide = validateGuide(JSON.parse(await readFile('public/guides/demo/guide.json', 'utf8'))); +let atMs = 0; +guide.story = guide.steps.map((step) => { + const line = { atMs, text: step.description || step.title }; + atMs += step.durationMs; + return line; +}); +const result = await addVoiceOver(guide, { guideDirectory: 'public/guides/demo' }); +await writeFile('public/guides/demo/guide.json', `${JSON.stringify(guide, null, 2)}\n`); +console.log(result); // { spoken: 12, reused: 0, silent: 0, addedMs: 4300 } +``` + +- **Each line starts with a step**, and covers the steps until the next line. When a line, plus a pause of 800 ms, lasts longer than its steps, they get longer in proportion to their length, and the lines that follow move with them, so the voice always ends before the next line. `addedMs` gives the time added. A line that starts in the middle of a step is refused (`STORY_OFF_STEP`) before anything is read. +- **A line already read is never billed again.** Its sound is `voice/.mp3` next to `guide.json`, with `voice/.json` that keeps its length and its words, the fingerprint following from the text, the voice and the model. Run it again after an edit and only the new or rewritten lines are read. Publish the `voice` folder with the guide. Sounds that no line uses any more are deleted from that folder, and other files there are left alone. +- **The key comes from `ELEVENLABS_API_KEY`**, or `apiKey`. Never write it in the repository. Without a key, lines already read keep their voice and the others stay silent: `silent` counts them. +- Each request sends the lines before and after, so the voice keeps one tone from a line to the next. A refusal of ElevenLabs throws a `RecorderError` with the code `VOICE_OVER_FAILED`; the lines read before it stay in the folder, so the next run does not pay them again. +- `addVoiceOver` changes the guide in place and checks it. Write it afterwards. + +| Option | Default | What it sets | +| ---------------- | --------------------------- | ------------------------------------------------------------------ | +| `guideDirectory` | required | The folder of `guide.json`; sound paths are relative to it. | +| `apiKey` | `ELEVENLABS_API_KEY` | The ElevenLabs key. | +| `voiceId` | `YxrwjAKoUKULGd0g8K9Y` | The voice (`DEFAULT_VOICE_ID`). | +| `modelId` | `eleven_v4_turbo` | The model (`DEFAULT_MODEL_ID`). | +| `folder` | `voice` | The folder of the sounds, a single name inside `guideDirectory`. | +| `pauseMs` | `800` | The silence left after a line before the next one. | +| `prune` | `true` | Deletes the sounds of the folder that no line uses any more. | +| `fetch` | the global `fetch` | The HTTP client, to go through a proxy or to test without network. | +| `baseUrl` | `https://api.elevenlabs.io` | The address of the API. | + +The sounds are MP3 at 128 kbit/s, read through the `with-timestamps` endpoint of ElevenLabs. Players before 0.5.0 ignore `audio` and `words`. + ## License MIT diff --git a/packages/recorder/src/index.ts b/packages/recorder/src/index.ts index 4761e59..e60d098 100644 --- a/packages/recorder/src/index.ts +++ b/packages/recorder/src/index.ts @@ -9,6 +9,8 @@ export type { } from './recording-session.js'; export { GuideExporter } from './guide-exporter.js'; export type { ExportGuideOptions, ExportGuideResult } from './guide-exporter.js'; +export { addVoiceOver, DEFAULT_VOICE_ID, DEFAULT_MODEL_ID } from './voice-over.js'; +export type { VoiceOverOptions, VoiceOverResult } from './voice-over.js'; export { startStudio } from './studio-server.js'; export type { Studio, StudioOptions } from './studio-server.js'; export type { @@ -16,6 +18,8 @@ export type { GuideAsset, GuideStep, GuideAnnotation, + GuideStoryLine, + GuideWord, GuideCursor, CaptureContext, ImageMimeType, diff --git a/packages/recorder/src/voice-over.ts b/packages/recorder/src/voice-over.ts new file mode 100644 index 0000000..67acdb6 --- /dev/null +++ b/packages/recorder/src/voice-over.ts @@ -0,0 +1,342 @@ +import { createHash } from 'node:crypto'; +import { mkdir, readdir, readFile, unlink, writeFile } from 'node:fs/promises'; +import { resolve } from 'node:path'; +import { validateGuide } from '@interactive-learning/protocol'; +import type { GuideDocument, GuideWord } from '@interactive-learning/protocol'; +import { isNodeError, RecorderError } from './errors.js'; +import { rejectSymlink } from './files.js'; + +/** The voice read by default: a calm French voice of the ElevenLabs library. */ +export const DEFAULT_VOICE_ID = 'YxrwjAKoUKULGd0g8K9Y'; +/** The model read by default: v4 Turbo, the cheapest one. */ +export const DEFAULT_MODEL_ID = 'eleven_v4_turbo'; +/** MP3 at a constant 128 kbit/s, which every browser plays. */ +const OUTPUT_FORMAT = 'mp3_44100_128'; +/** 128 kbit/s is 16 bytes per millisecond. */ +const BYTES_PER_MS = 16; +/** A sound of the voice-over folder: the 16 hex digits of its fingerprint. */ +const VOICE_FILE = /^([0-9a-f]{16})\.(mp3|json)$/; + +export interface VoiceOverOptions { + /** The folder of `guide.json`: sound paths are relative to it, as the screenshots are. */ + guideDirectory: string; + /** Defaults to the `ELEVENLABS_API_KEY` environment variable. */ + apiKey?: string; + /** Defaults to {@link DEFAULT_VOICE_ID}. */ + voiceId?: string; + /** Defaults to {@link DEFAULT_MODEL_ID}. */ + modelId?: string; + /** The folder of the sounds, inside `guideDirectory`. Defaults to `voice`. */ + folder?: string; + /** The silence left after a line before the next one, in milliseconds. Defaults to 800. */ + pauseMs?: number; + /** Deletes the sounds of the folder that no line uses any more. Defaults to `true`. */ + prune?: boolean; + /** Defaults to the global `fetch`. */ + fetch?: typeof fetch; + /** Defaults to `https://api.elevenlabs.io`. */ + baseUrl?: string; +} + +export interface VoiceOverResult { + /** Lines read by ElevenLabs during this run, and billed. */ + spoken: number; + /** Lines whose sound was already in the folder, and not billed again. */ + reused: number; + /** Lines left without a voice because no API key was given. */ + silent: number; + /** The time added to the steps so that each line ends before the next one, in milliseconds. */ + addedMs: number; +} + +/** What the folder keeps next to each sound: its length and the moments of its words. */ +interface Reading { + durationMs: number; + words: GuideWord[]; +} + +interface Alignment { + characters: string[]; + character_start_times_seconds: number[]; + character_end_times_seconds: number[]; +} + +/** + * Reads each line of the story of `guide` aloud with ElevenLabs, like the voice-over of a video. + * Each line gets its `audio`, a sound in `//`, and its `words` with the + * moment each is said, which the player shows as captions. Steps get longer where a line, plus a + * pause, lasts longer than the steps it covers, and the lines that follow move with them. + * + * A sound is named after a fingerprint of its text, voice and model, so a line already read is + * reused and never billed again. Without an API key, lines already read keep their voice and the + * others stay silent. Changes `guide` in place; write it afterwards. + * + * Each line must start with a step, as a story built from the steps does. + */ +export async function addVoiceOver( + guide: GuideDocument, + options: VoiceOverOptions, +): Promise { + const result: VoiceOverResult = { spoken: 0, reused: 0, silent: 0, addedMs: 0 }; + const story = guide.story ?? []; + if (story.length === 0) return result; + + const apiKey = options.apiKey ?? process.env.ELEVENLABS_API_KEY; + const voiceId = options.voiceId ?? DEFAULT_VOICE_ID; + const modelId = options.modelId ?? DEFAULT_MODEL_ID; + const folderName = options.folder ?? 'voice'; + const pauseMs = options.pauseMs ?? 800; + if (!/^[A-Za-z0-9_-][A-Za-z0-9._-]*$/.test(folderName)) { + throw new RecorderError( + 'INVALID_ARGUMENT', + 'The voice-over folder is a single folder name inside the guide folder.', + ); + } + if (!Number.isFinite(pauseMs) || pauseMs < 0) { + throw new RecorderError('INVALID_ARGUMENT', 'The pause after a line is zero or more.'); + } + // Check the timing before anything is billed. + const firstSteps = storySteps(guide); + + const folder = resolve(options.guideDirectory, folderName); + await rejectSymlink(folder); + await mkdir(folder, { recursive: true }); + + const durations: Array = []; + for (const [index, line] of story.entries()) { + const fingerprint = createHash('sha256') + .update(JSON.stringify([modelId, voiceId, OUTPUT_FORMAT, line.text])) + .digest('hex') + .slice(0, 16); + const soundPath = resolve(folder, `${fingerprint}.mp3`); + const readingPath = resolve(folder, `${fingerprint}.json`); + let reading = await readReading(soundPath, readingPath); + if (reading) { + result.reused++; + } else if (apiKey) { + const spoken = await speak({ + text: line.text, + previousText: story[index - 1]?.text, + nextText: story[index + 1]?.text, + apiKey, + voiceId, + modelId, + fetch: options.fetch ?? fetch, + baseUrl: options.baseUrl ?? 'https://api.elevenlabs.io', + }); + reading = { durationMs: spoken.durationMs, words: spoken.words }; + await writeFile(soundPath, spoken.mp3); + await writeFile( + readingPath, + `${JSON.stringify( + { + durationMs: reading.durationMs, + words: reading.words, + text: line.text, + voiceId, + modelId, + }, + null, + 2, + )}\n`, + ); + result.spoken++; + } + if (reading) { + line.audio = `${folderName}/${fingerprint}.mp3`; + line.words = reading.words; + durations.push(reading.durationMs); + } else { + delete line.audio; + delete line.words; + durations.push(undefined); + result.silent++; + } + } + + if (options.prune ?? true) { + const kept = new Set(story.flatMap((line) => (line.audio ? [line.audio] : []))); + for (const name of await readdir(folder)) { + const match = VOICE_FILE.exec(name); + if (match && !kept.has(`${folderName}/${match[1]}.mp3`)) { + await unlink(resolve(folder, name)).catch((error: unknown) => { + if (!isNodeError(error, 'ENOENT')) throw error; + }); + } + } + } + + result.addedMs = fitSteps(guide, firstSteps, durations, pauseMs); + validateGuide(guide); + return result; +} + +/** The index of the step each line starts with. */ +function storySteps(guide: GuideDocument): number[] { + const starts = stepStarts(guide); + return (guide.story ?? []).map((line) => { + const index = starts.indexOf(line.atMs); + if (index < 0) { + throw new RecorderError( + 'STORY_OFF_STEP', + `The story line "${line.text.slice(0, 40)}" does not start with a step.`, + ); + } + return index; + }); +} + +function stepStarts(guide: GuideDocument): number[] { + let time = 0; + return guide.steps.map((step) => { + const start = time; + time += step.durationMs; + return start; + }); +} + +/** A sound already read, with its reading, or nothing when either file is missing or broken. */ +async function readReading(soundPath: string, readingPath: string): Promise { + try { + await readFile(soundPath).then((bytes) => { + if (bytes.length === 0) throw new Error('empty sound'); + }); + const reading = JSON.parse(await readFile(readingPath, 'utf8')) as Partial; + if (typeof reading.durationMs !== 'number' || !Array.isArray(reading.words)) return undefined; + return { durationMs: reading.durationMs, words: reading.words }; + } catch { + return undefined; + } +} + +async function speak(request: { + text: string; + previousText: string | undefined; + nextText: string | undefined; + apiKey: string; + voiceId: string; + modelId: string; + fetch: typeof fetch; + baseUrl: string; +}): Promise { + const url = `${request.baseUrl}/v1/text-to-speech/${encodeURIComponent(request.voiceId)}/with-timestamps?output_format=${OUTPUT_FORMAT}`; + let response: Response; + try { + response = await request.fetch(url, { + method: 'POST', + headers: { + 'xi-api-key': request.apiKey, + 'Content-Type': 'application/json', + Accept: 'application/json', + }, + // The neighbouring lines keep one tone from a line to the next. + body: JSON.stringify({ + text: request.text, + model_id: request.modelId, + previous_text: request.previousText, + next_text: request.nextText, + }), + }); + } catch (error) { + throw new RecorderError('VOICE_OVER_FAILED', 'ElevenLabs could not be reached.', { + cause: error, + }); + } + if (!response.ok) { + const detail = (await response.text().catch(() => '')).slice(0, 300); + throw new RecorderError( + 'VOICE_OVER_FAILED', + `ElevenLabs refused to read "${request.text.slice(0, 40)}": HTTP ${response.status} ${detail}`.trim(), + ); + } + const body = (await response.json()) as { audio_base64?: string; alignment?: Alignment | null }; + if (typeof body.audio_base64 !== 'string' || body.audio_base64.length === 0) { + throw new RecorderError('VOICE_OVER_FAILED', 'ElevenLabs answered without a sound.'); + } + const mp3 = Buffer.from(body.audio_base64, 'base64'); + const end = body.alignment?.character_end_times_seconds.at(-1); + // Without timestamps, the length follows from the constant bit rate of the MP3. + const durationMs = Math.ceil(end !== undefined ? end * 1000 : mp3.length / BYTES_PER_MS); + return { mp3, durationMs, words: splitWords(body.alignment, request.text, durationMs) }; +} + +/** + * The words of a reading and the moment each is said, from the timestamp of each character. Without + * timestamps, each word takes its share of the length, in proportion to its length. A lone mark, + * such as the colon of « étape : », stays with the word before it. + */ +export function splitWords( + alignment: Alignment | null | undefined, + text: string, + durationMs: number, +): GuideWord[] { + const words: GuideWord[] = []; + if (alignment?.characters.length) { + let current: GuideWord | undefined; + for (const [index, character] of alignment.characters.entries()) { + if (/\s/.test(character)) { + current = undefined; + continue; + } + const start = Math.round((alignment.character_start_times_seconds[index] ?? 0) * 1000); + const end = Math.round((alignment.character_end_times_seconds[index] ?? 0) * 1000); + if (current) { + current.text += character; + current.endMs = Math.max(current.endMs, end); + } else { + current = { text: character, atMs: start, endMs: Math.max(start, end) }; + words.push(current); + } + } + } else { + const parts = text.split(/\s+/).filter(Boolean); + const total = parts.reduce((sum, word) => sum + word.length + 1, 0); + let time = 0; + for (const word of parts) { + const share = (durationMs * (word.length + 1)) / total; + words.push({ text: word, atMs: Math.round(time), endMs: Math.round(time + share) }); + time += share; + } + } + return words.reduce((list, word) => { + const previous = list.at(-1); + if (previous && /^[\p{P}\p{S}]+$/u.test(word.text)) { + previous.text += ` ${word.text}`; + previous.endMs = Math.max(previous.endMs, word.endMs); + } else list.push(word); + return list; + }, []); +} + +/** + * Gives each line the time to be said: when its reading plus the pause outlasts the steps it + * covers, those steps get longer in proportion to their length. Each line then starts again with + * its step. Returns the time added to the guide. + */ +function fitSteps( + guide: GuideDocument, + firstSteps: number[], + durations: Array, + pauseMs: number, +): number { + const story = guide.story ?? []; + let added = 0; + for (const [index, duration] of durations.entries()) { + if (duration === undefined) continue; + const steps = guide.steps.slice(firstSteps[index], firstSteps[index + 1] ?? guide.steps.length); + const available = steps.reduce((sum, step) => sum + step.durationMs, 0); + const missing = duration + pauseMs - available; + if (missing <= 0) continue; + let rest = missing; + for (const [position, step] of steps.entries()) { + const share = + position === steps.length - 1 ? rest : Math.round((missing * step.durationMs) / available); + step.durationMs += share; + rest -= share; + } + added += missing; + } + const starts = stepStarts(guide); + for (const [index, line] of story.entries()) line.atMs = starts[firstSteps[index]!]!; + return added; +} diff --git a/packages/recorder/test/voice-over.test.ts b/packages/recorder/test/voice-over.test.ts new file mode 100644 index 0000000..63f81ed --- /dev/null +++ b/packages/recorder/test/voice-over.test.ts @@ -0,0 +1,294 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { mkdtemp, readdir, readFile, rm, writeFile } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { basename, dirname, resolve } from 'node:path'; +import type { GuideDocument } from '@interactive-learning/protocol'; +import { RecordingSession } from '../src/recording-session.js'; +import { addVoiceOver, splitWords } from '../src/voice-over.js'; + +const png = Buffer.from( + 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+aR1UAAAAASUVORK5CYII=', + 'base64', +); +let directory: string; +let guideDirectory: string; +let built = 0; + +beforeEach(async () => { + directory = await mkdtemp(resolve(tmpdir(), 'interactive-learning-voice-')); + guideDirectory = resolve(directory, 'guide'); + vi.stubEnv('ELEVENLABS_API_KEY', ''); +}); + +afterEach(async () => { + vi.unstubAllEnvs(); + if (!basename(directory).startsWith('interactive-learning-voice-')) + throw new Error('Refusing to clean a path outside the test directory.'); + await rm(directory, { recursive: true, force: true }); +}); + +/** A guide of three 2-second steps that tells `lines`, each starting with the step of its index. */ +async function guideTelling(lines: Array<[step: number, text: string]>): Promise { + const imagePath = resolve(directory, 'screen.png'); + await writeFile(imagePath, png); + // Each guide is built apart; its voice goes to the same `guideDirectory`. + const session = await RecordingSession.create({ + filePath: resolve(directory, 'work', String(++built), 'guide.json'), + title: 'Banque', + }); + for (const title of ['Ouvrir', 'Voir', 'Régler']) + await session.addCapture({ imagePath, title, durationMs: 2000 }); + const guide = await session.validate(); + guide.story = lines.map(([step, text]) => ({ atMs: step * 2000, text })); + return guide; +} + +/** The answer of ElevenLabs for `text`, each character lasting `msPerCharacter`. */ +function answer(text: string, msPerCharacter: number): Response { + const characters = [...text]; + return Response.json({ + audio_base64: Buffer.from(`mp3 of ${text}`).toString('base64'), + alignment: { + characters, + character_start_times_seconds: characters.map((_, i) => (i * msPerCharacter) / 1000), + character_end_times_seconds: characters.map((_, i) => ((i + 1) * msPerCharacter) / 1000), + }, + }); +} + +/** A `fetch` that reads each line at `msPerCharacter` and remembers each request. */ +function fakeElevenLabs(msPerCharacter = 10) { + return vi.fn(async (_url: string | URL | Request, init?: RequestInit) => { + const body = JSON.parse(String(init?.body)) as { text: string }; + return answer(body.text, msPerCharacter); + }); +} + +describe('addVoiceOver', () => { + it('reads each line, writes its sound and gives it the words with their moments', async () => { + const guide = await guideTelling([ + [0, 'Le groupe :'], + [2, 'Chaque filiale.'], + ]); + const fetch = fakeElevenLabs(); + + const result = await addVoiceOver(guide, { guideDirectory, apiKey: 'key', fetch }); + + expect(result).toEqual({ spoken: 2, reused: 0, silent: 0, addedMs: 0 }); + const [url, init] = fetch.mock.calls[0]!; + expect(String(url)).toBe( + 'https://api.elevenlabs.io/v1/text-to-speech/YxrwjAKoUKULGd0g8K9Y/with-timestamps?output_format=mp3_44100_128', + ); + expect(init?.method).toBe('POST'); + expect((init?.headers as Record)['xi-api-key']).toBe('key'); + expect(JSON.parse(String(init?.body))).toEqual({ + text: 'Le groupe :', + model_id: 'eleven_v4_turbo', + next_text: 'Chaque filiale.', + }); + expect(JSON.parse(String(fetch.mock.calls[1]![1]?.body)).previous_text).toBe('Le groupe :'); + + const [first] = guide.story!; + expect(first!.audio).toMatch(/^voice\/[0-9a-f]{16}\.mp3$/); + // The colon said alone stays with the word before it. + expect(first!.words).toEqual([ + { text: 'Le', atMs: 0, endMs: 20 }, + { text: 'groupe :', atMs: 30, endMs: 110 }, + ]); + const sound = await readFile(resolve(guideDirectory, first!.audio!), 'utf8'); + expect(sound).toBe('mp3 of Le groupe :'); + expect((await readdir(resolve(guideDirectory, 'voice'))).sort()).toHaveLength(4); + }); + + it('lengthens the steps of a line that lasts longer than them, and moves the next lines', async () => { + // 30 characters at 100 ms: 3 s, plus the 800 ms pause, over one 2 s step. + const guide = await guideTelling([ + [0, 'Une phrase lue en trois s.....'], + [1, 'Courte.'], + ]); + + const result = await addVoiceOver(guide, { + guideDirectory, + apiKey: 'key', + fetch: fakeElevenLabs(100), + }); + + expect(result.addedMs).toBe(1800); + expect(guide.steps.map((step) => step.durationMs)).toEqual([3800, 2000, 2000]); + expect(guide.story!.map((line) => line.atMs)).toEqual([0, 3800]); + }); + + it('shares the extra time among the steps a line covers, in proportion to their length', async () => { + const guide = await guideTelling([[1, 'Une phrase lue en cinq secondes, sur deux étapes.']]); + guide.steps[2]!.durationMs = 1000; + + await addVoiceOver(guide, { guideDirectory, apiKey: 'key', fetch: fakeElevenLabs(100) }); + + // 4.9 s read plus 0.8 s of pause over 3 s of steps: 2.7 s more, two thirds to the longer step. + expect(guide.steps.map((step) => step.durationMs)).toEqual([2000, 3800, 1900]); + expect(guide.story![0]!.atMs).toBe(2000); + }); + + it('reuses a line already read without calling ElevenLabs, even without a key', async () => { + const first = await guideTelling([[0, 'Le groupe a trois filiales.']]); + await addVoiceOver(first, { guideDirectory, apiKey: 'key', fetch: fakeElevenLabs() }); + + const again = await guideTelling([[0, 'Le groupe a trois filiales.']]); + const fetch = fakeElevenLabs(); + const result = await addVoiceOver(again, { guideDirectory, fetch }); + + expect(fetch).not.toHaveBeenCalled(); + expect(result).toMatchObject({ spoken: 0, reused: 1, silent: 0 }); + expect(again.story![0]).toEqual(first.story![0]); + }); + + it('reads the line again with another voice', async () => { + const guide = await guideTelling([[0, 'Le groupe a trois filiales.']]); + await addVoiceOver(guide, { guideDirectory, apiKey: 'key', fetch: fakeElevenLabs() }); + const before = guide.story![0]!.audio; + + const fetch = fakeElevenLabs(); + await addVoiceOver(guide, { guideDirectory, apiKey: 'key', voiceId: 'other', fetch }); + + expect(fetch).toHaveBeenCalledOnce(); + expect(String(fetch.mock.calls[0]![0])).toContain('/text-to-speech/other/'); + expect(guide.story![0]!.audio).not.toBe(before); + }); + + it('leaves a new line silent without a key, and calls nothing', async () => { + const guide = await guideTelling([[0, 'Le groupe a trois filiales.']]); + guide.story![0]!.audio = 'voice/0000000000000000.mp3'; + const fetch = fakeElevenLabs(); + + const result = await addVoiceOver(guide, { guideDirectory, fetch }); + + expect(fetch).not.toHaveBeenCalled(); + expect(result).toEqual({ spoken: 0, reused: 0, silent: 1, addedMs: 0 }); + expect(guide.story![0]).toEqual({ atMs: 0, text: 'Le groupe a trois filiales.' }); + }); + + it('deletes the sounds no line uses any more, and nothing else of the folder', async () => { + const guide = await guideTelling([[0, 'Ancienne phrase.']]); + await addVoiceOver(guide, { guideDirectory, apiKey: 'key', fetch: fakeElevenLabs() }); + await writeFile(resolve(guideDirectory, 'voice', 'notes.txt'), 'kept'); + + guide.story![0]!.text = 'Nouvelle phrase.'; + await addVoiceOver(guide, { guideDirectory, apiKey: 'key', fetch: fakeElevenLabs() }); + + const names = await readdir(resolve(guideDirectory, 'voice')); + expect(names.sort()).toEqual( + [ + basename(guide.story![0]!.audio!), + basename(guide.story![0]!.audio!, '.mp3') + '.json', + 'notes.txt', + ].sort(), + ); + }); + + it('keeps unused sounds when told not to prune', async () => { + const guide = await guideTelling([[0, 'Ancienne phrase.']]); + await addVoiceOver(guide, { guideDirectory, apiKey: 'key', fetch: fakeElevenLabs() }); + guide.story![0]!.text = 'Nouvelle phrase.'; + await addVoiceOver(guide, { + guideDirectory, + apiKey: 'key', + fetch: fakeElevenLabs(), + prune: false, + }); + + expect(await readdir(resolve(guideDirectory, 'voice'))).toHaveLength(4); + }); + + it('writes the sounds in the folder it is given', async () => { + const guide = await guideTelling([[0, 'Le groupe.']]); + await addVoiceOver(guide, { + guideDirectory, + apiKey: 'key', + fetch: fakeElevenLabs(), + folder: 'voix', + }); + + expect(dirname(guide.story![0]!.audio!)).toBe('voix'); + expect(await readdir(resolve(guideDirectory, 'voix'))).toHaveLength(2); + }); + + it('refuses a folder outside the guide folder', async () => { + const guide = await guideTelling([[0, 'Le groupe.']]); + for (const folder of ['..', '../voice', 'a/b', '']) + await expect(addVoiceOver(guide, { guideDirectory, folder })).rejects.toMatchObject({ + code: 'INVALID_ARGUMENT', + }); + }); + + it('refuses a line that does not start with a step, before anything is billed', async () => { + const guide = await guideTelling([[0, 'Le groupe.']]); + guide.story![0]!.atMs = 500; + const fetch = fakeElevenLabs(); + + await expect( + addVoiceOver(guide, { guideDirectory, apiKey: 'key', fetch }), + ).rejects.toMatchObject({ code: 'STORY_OFF_STEP' }); + expect(fetch).not.toHaveBeenCalled(); + }); + + it('reports a refusal of ElevenLabs without the key, and keeps the lines already read', async () => { + const guide = await guideTelling([ + [0, 'Première phrase.'], + [1, 'Deuxième phrase.'], + ]); + const fetch = vi + .fn() + .mockImplementationOnce(async () => answer('Première phrase.', 10)) + .mockImplementationOnce(async () => new Response('quota_exceeded', { status: 401 })); + + const error = (await addVoiceOver(guide, { + guideDirectory, + apiKey: 'secret-key', + fetch, + }).catch((caught: unknown) => caught)) as Error & { code: string }; + + expect(error.code).toBe('VOICE_OVER_FAILED'); + expect(error.message).toContain('HTTP 401 quota_exceeded'); + expect(error.message).not.toContain('secret-key'); + expect(await readdir(resolve(guideDirectory, 'voice'))).toHaveLength(2); + }); + + it('measures a sound without timestamps from its size', async () => { + const guide = await guideTelling([[0, 'Deux mots']]); + const fetch = vi.fn(async () => + Response.json({ audio_base64: Buffer.alloc(16_000).toString('base64'), alignment: null }), + ); + + await addVoiceOver(guide, { guideDirectory, apiKey: 'key', fetch }); + + // 16 000 bytes at 128 kbit/s last one second, shared by the words in proportion to their length. + expect(guide.story![0]!.words).toEqual([ + { text: 'Deux', atMs: 0, endMs: 500 }, + { text: 'mots', atMs: 500, endMs: 1000 }, + ]); + }); + + it('does nothing for a guide without a story', async () => { + const guide = await guideTelling([]); + delete guide.story; + const fetch = fakeElevenLabs(); + + expect(await addVoiceOver(guide, { guideDirectory, apiKey: 'key', fetch })).toEqual({ + spoken: 0, + reused: 0, + silent: 0, + addedMs: 0, + }); + expect(fetch).not.toHaveBeenCalled(); + }); +}); + +describe('splitWords', () => { + it('keeps a lone mark with the word before it', () => { + expect(splitWords(null, 'Ouvrez la Banque !', 900).map((word) => word.text)).toEqual([ + 'Ouvrez', + 'la', + 'Banque !', + ]); + }); +}); diff --git a/skills/interactive-learning/SKILL.md b/skills/interactive-learning/SKILL.md index e2ae5b5..cfadeaa 100644 --- a/skills/interactive-learning/SKILL.md +++ b/skills/interactive-learning/SKILL.md @@ -1,16 +1,16 @@ --- name: interactive-learning -description: Build or update an Interactive Learning guide, a step-by-step walkthrough of a web application made of real screenshots, a cursor and numbered markers. Use it when the user asks to document, record or explain a flow of a website with screenshots, or to make a tutorial in Interactive Learning Studio. Do not use it to write end-to-end tests. +description: Build or update an Interactive Learning guide, a narrated step-by-step walkthrough of a web application made of real screenshots, a cursor, numbered markers and a voice-over. Use it when the user asks to document, record or explain a flow of a website with screenshots, or to make a tutorial or a video guide of it. The Playwright scenarios it writes publish guides and check nothing; do not use it to write end-to-end tests. --- # Interactive Learning guides -A guide, which the studio calls a tutorial, is a `guide.json` file plus an `assets` folder of screenshots, played by the `` player. There are two ways to make one. Prefer the first. +A guide is a `guide.json` file, an `assets` folder of screenshots and a `voice` folder of sounds, played by the `` player like a narrated video. -- **Interactive Learning Studio, through its MCP server.** The desktop app of the user records the flow in its own browser, keeps the tutorial in the user's library and publishes it to the project. The user watches in its window, can take over at any moment, and comes back to the tutorial later to refine it. -- **The command line**, when the studio is not connected. You drive a browser, and the `interactive-learning` tool writes the guide into the public folder of the project. +**Make it with the recorder, driven from the web.** A Playwright scenario, run headless, signs in, follows the flow through the menus, takes the screenshots, builds the guide with the API of `@interactive-learning/recorder`, gives it its voice-over and publishes it into the public folder of the project. Running the scenario again regenerates the guide, so it stays true to the application. Sections 1 to 7 describe this way. -When the user wants guides that a test run regenerates, with no studio and no agent, write them as scenarios of the project's end-to-end tests instead, as section 8 says. +- Without Playwright, or for a single quick guide, the command line of the recorder builds a guide from screenshots taken by hand (section 8). +- Interactive Learning Studio, the desktop app, is coming but is not ready yet. Do not use it and do not offer it, unless the user asks for it by name (section 9). ## Teach, do not just click @@ -18,60 +18,27 @@ A guide is watched by people who do not know the application yet. However you ma - **Start where the viewer already is.** The viewer is signed in: never show the sign-in page. Sign in before the first capture, start from the home page and follow the menu as a user would, one step per click, rather than opening an address directly. - **Open a screen, then visit it.** For each screen the guide talks about, one step clicks to it, then the screen is visited element by element: one step for each of its three to five key elements, all on the same screenshot. In each, the cursor glides to the element without clicking (`"action": "move"`) and one marker sits beside it, so the viewer follows the pointer from point to point. Never name a tab or a section without opening it. -- **The step text carries the explanation.** One or two sentences on what the element or the screen does. A marker opens only when the viewer clicks it, so its text adds a detail, not the point. -- **Tell the story.** A few lines under the video say why: who works on the screen and what for, such as a group of companies that keep their own accounts. They are told on their own timing, not the steps': `story` lines `{ "atMs", "text" }` in the guide, each starting with a step and lasting until the next line, the last one ending with the guide. A player that knows `story` shows the line of the moment under the screen and stops it while a marker is read; an older one ignores it. +- **Let the voice teach.** Each step says something, read aloud while the step plays and shown as captions: two to four sentences of spoken French, or of the language of the application, that say what the screen or the element is for, who uses it, when and why, and what comes next, such as a group of companies that keep their own accounts. Write it as you would explain it to a new colleague beside you, not as a label. Two lines said before the same step, such as the opening of a part and what its first step says, are read in one go. The voice sets the pace: a step lasts until its line is said (section 5). +- **The step text stays short.** One sentence that the voice does not need to repeat. A marker opens only when the viewer clicks it, so its text adds a detail, not the point. - **Markers sit beside the words, never on them.** The player draws a 24 px disc, about 30 px of a screenshot 1280 px wide shown in a 1000 px player, which hides any word under it. Measure the text of the target, not its box, since icons and padding are not text, and put the marker about 20 px from the text on a free side: right of a menu label, under a tab, left of a button and outside it. The cursor stays on the clicked element without covering its label, beside the text in a wide row, just under the word otherwise. - **Number in reading order.** In a step that presents a screen and then clicks, the markers of what the screen shows come first and the marker of the click last. -- **Zoom now and then.** `"zoom": 1.6` on a step closes the camera in on its click while the cursor gets there, then goes back before the markers appear. Keep it for a few clicks of a guide, on a small target or a key action, and give the step 1.5 seconds more so its markers keep their time. An older player ignores it. -- **Give time to read.** About 5 seconds for a click, and 4 to 7 seconds for a visited element: 3 seconds plus about 20 ms per character of its text. Some 25 steps lasting two minutes is fine. +- **Zoom now and then.** `"zoom": 1.6` on a step closes the camera in on its click while the cursor gets there, then goes back before the markers appear. Keep it for a few clicks of a guide, on a small target or a key action, and give the step 1.5 seconds more so its markers keep their time. +- **Give time to read.** At least about 5 seconds for a click, and 4 to 7 seconds for a visited element: 3 seconds plus about 20 ms per character of its text. The voice-over lengthens a step whose line lasts longer. Some 25 steps lasting three minutes is fine. - **One format, 16:9.** Capture every step at the same 16:9 viewport, such as 1280 × 720 at a device scale factor of 2. The player takes the shape of the screenshot, and a taller one puts the bottom of the screen under its controls. -- **No personal data.** Do not capture lists of people, e-mail addresses or the real figures of a client when the guide is shown beyond that client. Present such a screen by its click and its text only, or record on demo data. +- **No personal data.** Do not capture lists of people, e-mail addresses or the real figures of a client when the guide is shown beyond that client. Present such a screen by its click and its voice only, or record on demo data. +- **Never fake a screen.** Never change the page, its DOM or its styles to get a nicer screenshot, and never invent an image. Use demo data: everything the scenario does in the browser really happens in the application. - **Check every step before you publish**, with its markers drawn on its screenshot. Recapture a step where a marker hides a word, the cursor misses its target or the wrong element is hovered. -## 1. Use the studio when it is connected +## 1. Set up the scenarios -The studio is connected when you have the tools of its MCP server, `interactive-learning`, such as `list_library`, `create_tutorial`, `look` and `click` (in Claude Code, `mcp__interactive-learning__look`). The studio starts by itself when a tool needs it. Its server instructions give the whole workflow; here it is in short. +- Write each guide as a scenario, such as `e2e/tuto//.spec.ts`, beside the end-to-end tests when the project has Playwright. Give the scenarios their own configuration, such as `e2e/tuto.config.ts`, and a script such as `pnpm tuto`. These scenarios publish guides; they check nothing, and the test runs of the project never pick them up. +- The configuration runs headless Chromium at the viewport of the guides (`viewport: { width: 1280, height: 720 }`, `deviceScaleFactor: 2`), with one worker, no retries, a timeout of several minutes and the address of the local application as `baseURL`. +- If the project has no Playwright yet, tell the user: Playwright downloads a browser of about 150 MB. Add `@playwright/test` as a development dependency once they agree, or use the command line of section 8. +- Add `@interactive-learning/recorder` as a development dependency, at least the version that exports `addVoiceOver`. +- Sign in through the fixtures or the stored session of the tests, before the first capture. Never type real credentials in a scenario: read the test accounts the project already uses. +- Put what every scenario shares in one helper beside them, such as `e2e/tuto/guide.ts`: open a screen by a click, visit its elements, say a line, publish. Each scenario then reads like the guide: the clicks, the elements, and what the voice says at each. -1. Call `list_library`. Reuse the site whose address matches the application, or call `create_site`. When the user works in the project of the site, set `publish_to` to the folder that serves guides, such as `/public/guides`. Section 4 tells how to find that folder. -2. Call `create_tutorial` with a short title that starts with a verb. Its editor opens on the site, in the browser of the studio. -3. Call `open_page` on the first page of the flow. If the flow needs a signed-in user, ask the user to sign in in the browser of the studio, and wait for them. Never type real credentials. -4. Call `start_recording`, then repeat: `look`, read its screenshot and its elements, then `click` a ref. Each click becomes a step with the screen just before it, the cursor and a marker named after what was clicked. `type_text` fills a field with demo data, and the next click shows it filled. `capture_step` adds a screen without a click, such as the result at the end, with a marker on an element. -5. Call `stop_recording`, then `read_tutorial`. Give each step a title that starts with a verb and its explanation with `update_step`, and each marker a short name and what it does with `update_marker`, as the first section says. Check every step with `show_step`, the markers included. Delete a step that repeats the previous screen with nothing new. -6. Call `publish_tutorial` when the site has a publish folder. The tutorial lands in `//guide.json`, which the page of section 6 shows. -7. Report the tutorial with its site, theme and title, its steps, where it was published, and anything you could not capture. Tell the user it stays in their library, where they can open it, refine it and publish it again. - -To change a tutorial of the studio, call `list_library` and `open_tutorial`, then `read_tutorial`, and record more steps or edit them the same way. Never write its `guide.json` yourself: go through the tools, so the studio shows each change and can undo it. - -If the user has the studio but its tools are missing, tell them to open Settings in the studio, then MCP, to click Connect for their agent and to start a new session. Meanwhile, or when they do not use the studio, continue with the command line below. - -## 2. Check the command line tool - -The tool comes from the npm package `@interactive-learning/recorder`, which is usually not installed. Run it with npx, which downloads it on first use. It needs Node.js 22.18 or later. - -```sh -npx -y @interactive-learning/recorder doctor -``` - -If `doctor` fails, stop and report the error. Below, `il` stands for `npx -y @interactive-learning/recorder`. - -## 3. Choose the browser - -Use the first of these that you have. Each screenshot must reach you as a file, because `capture add` imports files. An image that only appears in the conversation cannot be imported. - -1. **The browser built into your harness.** Prefer it whenever your harness provides one, such as the browser of Claude Code or Claude in Chrome. Some harnesses save each screenshot and give you its path; import that file as is. Measure positions with its page or JavaScript tools. -2. **Playwright, only when your harness has no browser**, or when its screenshots never reach you as files. - - If the project already depends on `playwright` or `@playwright/test`, use that copy. Run `npx playwright install chromium` if its browser is missing. - - Otherwise tell the user, since Playwright downloads a browser of about 150 MB. Then install it in a temporary folder outside the project, so the project and its `package.json` stay untouched. - -```sh -mkdir -p /tmp/il-browser && cd /tmp/il-browser -npm init -y && npm install playwright -npx playwright install chromium -``` - -With Playwright, drive the flow from a short Node script kept outside the project. Keep a fixed 16:9 viewport, such as 1280 by 720 with `deviceScaleFactor: 2`. Before each action, take `page.screenshot({ path, fullPage: false })`, read the click target with `locator.boundingBox()` and the address with `page.url()`. This script only drives the browser: never write it as a test and never add it to the project, unless the user wants guides that the tests regenerate (section 8). - -## 4. Put the guide in the public folder of the site +## 2. Find the public folder of the site The site serves the guide as static files. Find the folder it serves as is at its root, from the stack of the project. @@ -79,51 +46,80 @@ The site serves the guide as static files. Find the folder it serves as is at it - `static/` for SvelteKit. - The folder that holds `index.html` for a plain HTML site. -If you cannot tell, ask the user. Then create the guide in a `guides/` folder there, with a short kebab case slug. - -```sh -il create --title "Register a trainee" --out public/guides/register-trainee/guide.json -``` - -Every screenshot you import is copied into `public/guides/register-trainee/assets/`, and `guide.json` refers to it with a relative path. The paths are therefore right without any other setting. Never embed images in the JSON as base64. - -## 5. Add one step per screen +If you cannot tell, ask the user. Each guide goes in `/guides///`, with short kebab case names. -Save your raw screenshots in a temporary folder outside the public folder, because `capture add` copies them. Repeat for every step of the flow. +## 3. Capture a step 1. Bring the page to the state you want to show and wait until it is stable, with content loaded and animations finished. Hover the element you are about to click, then hover it again just before the screenshot: an animation, such as a menu that scrolls as a group opens, can slide another element under the pointer. -2. Screenshot the visible viewport only, not the full page, as PNG, JPEG or WebP. Take it before the click you want to show. For a form, take it once the form is filled in and before it is submitted, then take the result on the next step. -3. Measure the click target in that same viewport, in CSS pixels, and place the cursor and its marker as the first section says. Then `x = targetX / viewportWidth` and `y = targetY / viewportHeight`, both between 0 and 1. If you are not sure of the position, leave `--x` and `--y` out. -4. Import the screenshot with the address of the page in `--url`. The player can show it above the screenshot. The JSON output gives the `stepId`. - -```sh -il capture add --guide public/guides/register-trainee/guide.json --image /tmp/captures/01.png --url http://localhost:5173/trainees --title "Open the sign-up form" --description "Click Add above the trainee list." --x 0.82 --y 0.18 +2. Take `page.screenshot({ path, fullPage: false })` into a working folder outside the public folder, before the click you want to show. For a form, take it once the form is filled in and before it is submitted, then show the result on the next step. +3. Measure the target in that same viewport with `locator.boundingBox()`, and the text inside it with a `Range` in `page.evaluate`, to place the cursor and the marker as the first section says. Positions go from 0 to 1: `x = targetX / viewportWidth`, `y = targetY / viewportHeight`. Keep `page.url()` as the address of the step. +4. A visit takes one screenshot and adds one step per element with that same file and `cursor: { x, y, action: 'move' }`: the guide keeps one image and the cursor glides from element to element. +5. A position always belongs to the screenshot of the same step. Never reuse a click position on the next page. + +## 4. Build and publish the guide + +Build the guide in a working folder, then replace the published guide in one go. + +```ts +import { addVoiceOver, RecordingSession, validateGuide } from '@interactive-learning/recorder'; + +const session = await RecordingSession.create({ + filePath: `${work}/guide.json`, + title, + description, +}); +for (const capture of captures) { + const step = await session.addCapture({ + imagePath: capture.image, + title: capture.title, + description: capture.text, + durationMs: capture.durationMs, + cursor: capture.cursor, // { x, y, action: 'click' | 'move' } + source: { capturedAt: capture.at, url: capture.url, viewport, dpr: 2 }, + }); + for (const marker of capture.markers) await session.addAnnotation(step.id, marker); +} +const guide = await session.validate(); +// Keep the id and the creation date of the guide already published. +// Add `zoom` to a few steps, and `transition: 'fade'` where a new screen comes in. + +let atMs = 0; +const starts = guide.steps.map((step) => (atMs += step.durationMs) - step.durationMs); +guide.story = lines.map((line) => ({ atMs: starts[line.beforeStep]!, text: line.text })); + +const published = `public/guides/${module}/${slug}`; +const voice = await addVoiceOver(guide, { guideDirectory: published }); +// Replace `${published}/assets` with the new screenshots, then write the guide. +await writeFile(`${published}/guide.json`, `${JSON.stringify(validateGuide(guide), null, 2)}\n`); ``` -5. Optionally add a numbered marker that the viewer can open. +- Each line of the story starts with the step it was said before, and covers the steps until the next line. A line said after the last step would never be heard: refuse it. +- The scenario is the source. A text edited by hand in `guide.json` is lost at the next run, so texts change in the scenario. +- On Windows, copy and delete the files one by one: with Node.js 24, `fs.cpSync` stops the process on a path that holds a character outside ASCII, and `fs.rmSync` leaves such a folder in place without an error. -```sh -il annotate --guide public/guides/register-trainee/guide.json --step STEP_ID --x 0.82 --y 0.18 --title "Add" --body "Opens the sign-up form." -``` +## 5. The voice-over -Follow these rules, with the studio too. +`addVoiceOver` has ElevenLabs read each line of the story and writes on it `audio`, the sound, and `words`, each word with the moment it is said, which the player shows as captions. -- Never change the page, its DOM or its styles to get a nicer screenshot, and never invent an image. -- A position always belongs to the screenshot of the same step. Never reuse a click position on the next page. -- Use demo data. Everything you do in the browser really happens in the application. -- Keep titles short and start them with a verb. The step text explains, and markers add details. -- Set `--duration-ms` from the reading times of the first section. +- The key is read from `ELEVENLABS_API_KEY`. Never write it in the repository, a scenario or a report. When it is missing, tell the user: lines already read keep their voice and the new ones stay silent, which the result counts in `silent`. +- A line already read is never billed again. Its sound is `voice/.mp3` in the folder of the guide, named after its text, its voice and its model, so a run only pays for the lines that changed. Publish and commit the `voice` folder with the guide. The sounds that no line uses any more are deleted. +- Steps get longer where a line lasts longer than them, so the voice always ends before the next line: `addedMs` says by how much. Report the result of each guide: lines read, reused and silent. +- The default voice and model suit French guides. Pass `voiceId` or `modelId` only when the user asks for another voice: every line is then read again, and billed. -## 6. Validate and show the guide +## 6. Run the scenarios and check the guide -```sh -il validate --guide public/guides/register-trainee/guide.json -``` +Run the script of the scenarios, such as `pnpm tuto`, or one scenario with its file name. Then play the guide once, with the sound on, as the next section says. Check that each cursor points at the right element, that markers sit on the right spot, that the voice says what the screen shows and ends before the next line, and that no sensitive data is visible. Fix the scenario and run it again, then report the guide path and anything you could not capture. -The page that shows the guide only needs the tag of the npm package `@interactive-learning/player`. The public folder is served at the site root, so the URL drops the folder name. +## 7. Show the guide + +The page that shows the guide only needs the tag of the npm package `@interactive-learning/player`, version 0.5.0 or later for the voice, the captions and `zoom`. The public folder is served at the site root, so the URL drops the folder name. `frame="browser"` shows the guide like a video in a browser window, and the speaker button mutes the voice. ```html - + @@ -134,41 +130,40 @@ If the project does not use the player yet, check the guide without adding a dep ```html - + ``` -Play the guide once. Check that each cursor points at the right element, that markers sit on the right spot and that no sensitive data is visible. Fix and recapture what is wrong, then report the guide path and anything you could not capture. +## 8. Without Playwright: the command line -## 7. Offer the web studio +The recorder also builds a guide from screenshots taken one by one, in the browser of your harness. Below, `il` stands for `npx -y @interactive-learning/recorder`, which needs Node.js 22.18 or later. Run `il doctor` first, and stop and report its error if it fails. -After the command line, end by offering to open the guide in the web studio, where the user can place markers, rewrite texts and replace screenshots by hand. If they accept, start it in the background, because it keeps running until it is stopped. +- Use the browser built into your harness, such as the browser of Claude Code or Claude in Chrome, at a 16:9 viewport. Each screenshot must reach you as a file, because `capture add` imports files. +- Follow the rules of the first section and the captures of section 3, then build the guide in the public folder. ```sh -il studio --guide public/guides/register-trainee/guide.json +il create --title "Register a trainee" --out public/guides/register-trainee/guide.json +il capture add --guide public/guides/register-trainee/guide.json --image /tmp/captures/01.png --url http://localhost:5173/trainees --title "Open the sign-up form" --description "Click Add above the trainee list." --x 0.82 --y 0.18 --duration-ms 5000 +il annotate --guide public/guides/register-trainee/guide.json --step STEP_ID --x 0.80 --y 0.18 --title "Add" --body "Opens the sign-up form." +il validate --guide public/guides/register-trainee/guide.json ``` -It opens their browser and prints its address; give them that address too. Each save writes `guide.json` and its images in place, so read `guide.json` again before you change the guide afterwards. +- `capture add` copies the screenshot into `assets/` and prints the `stepId`. Leave `--x` and `--y` out when you are not sure of the position. +- To give this guide its voice, add its `story` and run `addVoiceOver` from a short Node script, as in section 4. +- `il studio --guide ` opens the guide in a web page where the user can move markers, rewrite texts and replace screenshots by hand. Offer it at the end, and start it in the background when they accept, because it runs until it is stopped. Read `guide.json` again afterwards. +- `il capture replace --guide --step STEP_ID --image ` replaces a screenshot and keeps its texts, without its cursor. `il export --guide --out ` copies a guide, and `--zip` makes an archive for the browser extension. `il --help` lists every command. -## 8. Regenerate guides from the end-to-end tests +## 9. The desktop studio, coming -When the project has Playwright end-to-end tests and the user wants guides that a test run regenerates, with no studio and no agent, write each guide as a scenario beside the tests, such as `e2e/tuto//.spec.ts`, with its own Playwright configuration and a script such as `pnpm tuto`. These scenarios publish guides; they check nothing. +Interactive Learning Studio, the desktop app of the user, will record a flow in its own browser, keep the tutorial in a library and publish it to the project. It is not ready yet: make guides with the scenarios above, and do not offer the studio. -- Sign in through the fixtures of the tests before the first capture, then follow the rules of the first section. -- Add `@interactive-learning/recorder` as a dev dependency and build the guide with its API: `RecordingSession.create`, `addCapture`, `addAnnotation` and `validate`. Build it in a temporary folder, then replace the published guide in `/guides///` in one go. Keep the `id` and `createdAt` of the guide already published. -- A visit takes one screenshot and adds one capture per element with that same file, `cursor: { x, y, action: 'move' }`: the guide keeps one image and the cursor glides from element to element. Compute the `atMs` of each story line from the durations of the steps before it, and add `story` to the guide once it is validated. -- The scenario is the source: a text edited by hand in `guide.json` is lost at the next run, so texts change in the scenario. -- On Windows, copy and delete the files one by one: with Node.js 24, `fs.cpSync` stops the process on a path that holds a character outside ASCII, and `fs.rmSync` leaves such a folder in place without an error. +Only when the user asks for the studio by name and its MCP tools are connected (`interactive-learning`, such as `list_library`, `look` and `click`), follow its server instructions: find or create the site in `list_library`, `create_tutorial`, `open_page`, ask the user to sign in in the browser of the studio, `start_recording`, then `look` and `click` for each step, `stop_recording`, write the texts with `update_step` and `update_marker`, check with `show_step` and `publish_tutorial`. Change a tutorial of the studio only through its tools, never by writing its `guide.json`. ## Update an existing guide -- A tutorial of the studio changes through its tools, as section 1 says. -- To replace a screenshot and keep its texts, run `il capture replace --guide public/guides/register-trainee/guide.json --step STEP_ID --image /tmp/captures/new.png`. It removes the cursor of that step. Check the markers, and to show the click again add `"cursor": { "x": 0.82, "y": 0.18, "action": "click" }` to the step in `guide.json`. -- To change texts, edit `guide.json`, then run `il validate`. -- After an update, offer the web studio again, as in section 7. -- When the user wants to refine the guide in the browser extension, run `il export --guide public/guides/register-trainee/guide.json --out register-trainee.zip --zip` and tell them to import that ZIP from the extension panel. -- To copy a guide somewhere else, `il export --guide --out ` writes `guide.json` and its `assets` folder. -- `il --help` lists every command. +- A guide made by a scenario changes in its scenario: edit the clicks, the texts or what the voice says, then run it again. Only the lines that changed are read again. +- A guide made with the command line changes with `il capture replace`, or by editing `guide.json` and running `il validate`. +- Ask before replacing a published guide that a scenario did not make.