File size: 12,951 Bytes
3713433
 
 
 
 
 
 
 
 
0dbbdd5
 
 
 
 
 
 
 
 
 
 
3713433
 
 
 
 
 
0dbbdd5
3713433
 
 
 
 
0dbbdd5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
efd10d1
 
 
 
 
 
 
 
 
0dbbdd5
 
efd10d1
 
 
 
 
 
 
 
 
 
 
 
 
 
0dbbdd5
3713433
 
 
 
 
 
0dbbdd5
3713433
 
479059c
 
3713433
 
 
 
479059c
0dbbdd5
 
3713433
 
 
0dbbdd5
3713433
479059c
3713433
 
0dbbdd5
 
3713433
 
0dbbdd5
 
 
 
 
 
3713433
 
 
 
 
 
 
 
 
0dbbdd5
3713433
 
 
 
 
0dbbdd5
3713433
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0dbbdd5
 
 
3713433
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0dbbdd5
 
3713433
0dbbdd5
3713433
 
 
 
0dbbdd5
3713433
0dbbdd5
 
 
3713433
 
 
 
 
0dbbdd5
 
 
479059c
 
3713433
 
 
 
 
 
 
 
0dbbdd5
3713433
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
// Real, continuous UI demonstration. Code is entered only with keyboard events.
// Requires: pip install soundcard numpy imageio-ffmpeg (Windows audio capture).
import { chromium, expect } from '@playwright/test';
import { mkdir, writeFile, access } from 'node:fs/promises';
import { spawn } from 'node:child_process';
import path from 'node:path';

const out = path.resolve('demo-output', `code-training-${new Date().toISOString().replace(/[:.]/g, '-')}`);
await mkdir(out, { recursive: true });
const demoUrl = process.env.DEMO_URL || 'http://127.0.0.1:5180/';
let server;
try { await fetch(demoUrl, { signal: AbortSignal.timeout(1500) }); }
catch (error) {
  if (process.env.DEMO_URL) throw error;
  server = spawn(process.execPath, ['node_modules/vite/bin/vite.js', '--host', '127.0.0.1', '--port', '5180', '--strictPort'], { windowsHide: true, stdio: 'ignore' });
  for (let attempt = 0; ; attempt++) {
    try { await fetch(demoUrl, { signal: AbortSignal.timeout(1500) }); break; }
    catch { if (attempt >= 100 || server.exitCode !== null) throw new Error('Demo server did not start'); await new Promise((resolve) => setTimeout(resolve, 100)); }
  }
}
const python = process.env.DEMO_PYTHON || 'python';
const audio = spawn(python, ['tools/record-loopback.py', out], { windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] });
audio.stdout.on('data', (data) => process.stdout.write(data));
audio.stderr.on('data', (data) => process.stderr.write(data));
const audioDone = new Promise((resolve, reject) => { audio.on('error', reject); audio.on('exit', (code) => code === 0 ? resolve() : reject(new Error(`Audio capture failed: ${code}`))); });
audioDone.catch(() => {});
const browser = await chromium.launch({ channel: 'chrome', headless: false, ignoreDefaultArgs: ['--mute-audio', '--disable-extensions', '--disable-component-extensions-with-background-pages', '--disable-component-update', '--disable-background-networking'], args: ['--window-position=0,0', '--enable-unsafe-swiftshader', '--autoplay-policy=no-user-gesture-required', '--disable-features=CalculateNativeWinOcclusion'] });
const context = await browser.newContext({ viewport: { width: 1440, height: 900 }, recordVideo: { dir: out, size: { width: 1440, height: 900 } } });
const page = await context.newPage();
const errors = [];
page.on('pageerror', (error) => errors.push(error.message));
const marks = [];
const mark = async (name) => {
  const point = await page.evaluate((name) => {
    const selectors = {
      'Open code training': '.training-launch', 'Typing factorial': '.code-source textarea',
      'Omitted closing for brace': '.code-source textarea', 'Omitted semicolon': '.code-source textarea',
      'Compile misspelled scnaf': '.code-training-toolbar button',
      'Correct scanf and compile': '.code-training-toolbar button',
      'Run': '.code-terminal', 'Analyse': '.code-training-toolbar button:nth-of-type(2)',
    };
    const el = document.querySelector(selectors[name] || '.__missing');
    if (!el) return { at: performance.now() / 1000 };
    const r = el.getBoundingClientRect();
    let x = r.x + r.width / 2, y = r.y + r.height / 2;
    if (el.tagName === 'TEXTAREA') {
      const line = el.value.slice(0, el.selectionStart).split('\n').length - 1;
      x = r.x + 55;
      y = Math.max(r.top + 12, Math.min(r.bottom - 12, r.top + 22 + line * 20.8 - el.scrollTop));
    }
    return { at: performance.now() / 1000, target: [Math.round(x), Math.round(y)] };
  }, name);
  marks.push({ name, ...point });
  await writeFile(path.join(out, 'progress.json'), JSON.stringify(marks)); console.log(name);
};
async function type(text, delay = 6) {
  // Short keyboard bursts keep the writing brisk while still giving the
  // controlled React editor time to commit every change.
  for (let index = 0; index < text.length;) {
    const newline = text.indexOf('\n', index);
    const end = newline < 0 ? text.length : newline;
    for (let cursor = index; cursor < end; cursor += 4) {
      const chunk = text.slice(cursor, Math.min(cursor + 4, end));
      const expected = await page.evaluate((chunk) => {
      const field = document.activeElement;
      if (field?.getAttribute('aria-label') !== 'C source code') return null;
        return field.value.slice(0, field.selectionStart) + chunk + field.value.slice(field.selectionEnd);
      }, chunk);
      await page.keyboard.type(chunk, { delay });
      if (expected !== null) await page.waitForFunction((value) =>
        document.activeElement?.value === value,
      expected, { polling: 10, timeout: 3000 });
    }
    if (newline < 0) break;
    const expected = await page.evaluate(() => {
      const field = document.activeElement; return field?.value.slice(0, field.selectionStart) + '\n' + field?.value.slice(field.selectionEnd);
    });
    await page.keyboard.press('Enter');
    await page.waitForFunction((value) => document.activeElement?.value === value, expected, { polling: 10, timeout: 3000 });
    index = newline + 1;
  }
}
try {
  for (let i = 0; ; i++) {
    try { await access(path.join(out, 'audio-ready.json')); break; }
    catch { if (i > 100 || audio.exitCode !== null) throw new Error('Audio recorder did not start'); await new Promise((r) => setTimeout(r, 100)); }
  }
  await page.goto(demoUrl);
  await page.waitForFunction(() => window.__store?.getState().bootDone, { timeout: 60000 });
  await expect(page.getByRole('heading', { name: 'Microduck x Reachy Mini' })).toBeVisible();
  await page.mouse.click(700, 40);
  await page.waitForFunction(() => speechSynthesis.getVoices().some((voice) => voice.name === 'Google UK English Male'), null, { timeout: 30000, polling: 250 });
  // The calibration square/tone is trimmed out of the delivered video. It
  // aligns the independent, real screen and speaker recordings precisely.
  await page.mouse.click(700, 40);
  await page.evaluate(async () => {
    window.demoSyncPoints = [];
    const calibrationAudio = new AudioContext();
    await calibrationAudio.resume();
    window.demoSync = async (frequency) => {
      const square = document.createElement('div');
      square.style.cssText = 'position:fixed;left:0;top:0;width:64px;height:64px;background:#fff;z-index:2147483647';
      const c = calibrationAudio;
      document.body.append(square);
      window.demoSyncPoints.push({ frequency, at: performance.now() / 1000 });
      const tone = c.createOscillator(), gain = c.createGain(); tone.frequency.value = frequency;
      gain.gain.value = 0.4; tone.connect(gain).connect(c.destination); tone.start(); tone.stop(c.currentTime + 0.25);
      await new Promise((resolve) => setTimeout(resolve, 500)); square.remove();
      await new Promise((resolve) => setTimeout(resolve, 250));
    };
    await window.demoSync(1000);
    window.demoSpeech = []; window.demoQuacks = []; window.demoEmotionSounds = [];
    addEventListener('reachy-emotion-sound-start', (e) => window.demoEmotionSounds.push({ ...e.detail, at: performance.now() / 1000 }));
    addEventListener('reachy-speech-start', (e) => {
      const r = document.querySelector('.code-terminal')?.getBoundingClientRect();
      window.demoSpeech.push({ ...e.detail, at: performance.now() / 1000, target: r ? [r.x + r.width / 2, r.y + r.height / 2] : null });
    });
    const quack = window.__gameApi.quack;
    window.__gameApi.quack = (...args) => { window.demoQuacks.push(performance.now() / 1000); return quack(...args); };
  });
  await page.waitForTimeout(850); await mark('Home');
  await page.screenshot({ path: path.join(out, 'home.png') });
  await page.waitForTimeout(2500);
  await page.getByRole('button', { name: 'Waddle in', exact: true }).click();
  await page.waitForFunction(() => window.rl && !window.rl.inputLocked);
  await page.waitForTimeout(1200);
  await mark('Open code training');
  await page.getByRole('button', { name: 'CODE TRAINING', exact: true }).click();
  const editor = page.getByLabel('C source code');
  await page.waitForTimeout(1400);
  await editor.click(); await page.keyboard.press('Control+a'); await page.keyboard.press('Backspace');
  await mark('Typing factorial');
  await type('#include <stdio.h>\n\nint factorial(int n)\n{\n    int result = 1 ;\n    for(int i = 1 ; i <= n ; i++)\n    {\n        result *= i;\n');
  await mark('Omitted closing for brace');
  await type('    r');
  await expect(page.getByLabel('Syntax hint')).toContainText('closing brace', { timeout: 500 });
  await page.waitForTimeout(1100);
  await type('eturn result;');
  await page.waitForTimeout(650);
  // Insert the omitted brace before return, using only cursor keys and typing.
  await page.keyboard.press('Home'); await type('    }\n');
  await page.keyboard.press('End'); await type('\n}\n\nint main()\n{\n    printf("Which integer would you like the factorial of? \\n");\n    int val = 0 ');
  await mark('Omitted semicolon');
  await page.keyboard.press('Enter');
  await expect(page.getByLabel('Syntax hint')).toContainText('semicolon');
  await page.waitForTimeout(1300);
  await page.keyboard.press('ArrowUp'); await page.keyboard.press('End'); await type(';');
  await page.keyboard.press('ArrowDown'); await page.keyboard.press('Home');
  await type('    scnaf("%d",&val);\n    int res = factorial(val);\n    printf("The factorial of %d is %d \\n",val,res);\n    return 0;\n}');
  await page.waitForTimeout(1800);
  await page.evaluate(() => window.demoSync(1200));
  await mark('Compile misspelled scnaf');
  await page.getByRole('button', { name: 'Compile', exact: true }).click();
  await expect(page.locator('.code-status')).toContainText('Fix the errors', { timeout: 150000 });
  await page.screenshot({ path: path.join(out, 'compile-error.png') });
  await page.waitForTimeout(2500);
  await page.getByLabel('Dismiss compiler message').click();
  await editor.click(); await page.keyboard.press('Control+Home');
  const source = await editor.inputValue();
  const line = source.split('\n').findIndex((value) => value.includes('scnaf'));
  for (let i = 0; i < line; i++) await page.keyboard.press('ArrowDown');
  await page.keyboard.press('Home');
  for (let i = 0; i < 4; i++) await page.keyboard.press('ArrowRight');
  for (let i = 0; i < 5; i++) await page.keyboard.press('Delete');
  await type('scanf', 160);
  await page.waitForTimeout(1300); await mark('Correct scanf and compile');
  await page.getByRole('button', { name: 'Compile', exact: true }).click();
  await expect(page.getByRole('button', { name: 'Run', exact: true })).toBeEnabled({ timeout: 60000 });
  await page.waitForTimeout(1500);
  await page.evaluate(() => window.demoSync(1400));
  await page.getByRole('button', { name: 'Run', exact: true }).click();
  await page.waitForTimeout(150); await mark('Run');
  const input = page.getByLabel('Terminal input');
  await expect(input).toBeEnabled({ timeout: 150000 });
  await page.waitForTimeout(1200); await input.click(); await type('5', 200); await page.waitForTimeout(400); await page.keyboard.press('Enter');
  await expect(page.locator('.code-status')).toContainText('Program finished', { timeout: 150000 });
  await expect(page.getByLabel('Program terminal')).toContainText('The factorial of 5 is 120');
  await page.screenshot({ path: path.join(out, 'execution.png') });
  await page.waitForTimeout(2500);
  await page.evaluate(() => window.demoSync(1600));
  await mark('Analyse');
  await page.getByRole('button', { name: 'Analyse', exact: true }).click();
  await expect(page.locator('.code-status')).toContainText('Analyse terminée', { timeout: 150000 });
  await page.screenshot({ path: path.join(out, 'analysis.png') });
  await page.waitForTimeout(4000); await mark('End');
  await writeFile(path.join(out, 'main.c'), await editor.inputValue());
  await page.evaluate(() => window.demoSync(2000));
  const observed = await page.evaluate(() => ({ speech: window.demoSpeech, quacks: window.demoQuacks, sync: window.demoSyncPoints, emotionSounds: window.demoEmotionSounds }));
  if (!['proud1', 'reprimand1'].every((name) => observed.emotionSounds.some((e) => e.name === name))) throw new Error('Missing Reachy emotion audio');
  if (observed.speech.some((line) => line.voice?.name !== 'Google UK English Male' || line.voice.language !== 'en-GB')) throw new Error('The demo did not use the expected English simulator voice');
  if (observed.speech.some((line) => line.text.includes('One change, then a test.'))) throw new Error('Outdated analysis ending');
  if (observed.quacks.length < 2 || observed.speech.length < 4 || errors.length) throw new Error(JSON.stringify({ observed, errors }));
  await writeFile(path.join(out, 'timeline.json'), JSON.stringify({ marks, ...observed, errors }, null, 2));
} finally {
  const video = page.video();
  await context.close();
  await video.saveAs(path.join(out, 'screen.webm'));
  await browser.close();
  await writeFile(path.join(out, 'STOP'), ''); await audioDone;
  server?.kill();
  console.log(`Recording: ${out}`);
}