Add real input() support via SharedArrayBuffer and level 03

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
denis
2026-10-14 22:43:39 +02:00
parent cd59bbbf5f
commit 5a41231861
20 changed files with 595 additions and 35 deletions
+68 -2
View File
@@ -40,7 +40,7 @@ test('parcours complet des niveaux 00 et 01', { skip, timeout: 180000 }, async (
const run = async (code) => {
const cell = page.locator('.cell').last();
await cell.locator('textarea').fill(code);
await cell.locator('.btn-primary').click();
await cell.locator('.cell-run').click();
await page.waitForFunction(() => document.querySelector('.cell:last-of-type')?.getAttribute('aria-busy') !== 'true');
await page.waitForTimeout(150);
return (await cell.locator('.cell-feedback').textContent()).trim();
@@ -65,7 +65,7 @@ test('parcours complet des niveaux 00 et 01', { skip, timeout: 180000 }, async (
// Boucle infinie interrompue, puis cellule réutilisable.
const cell = page.locator('.cell').last();
await cell.locator('textarea').fill('while True:\n pass');
await cell.locator('.btn-primary').click();
await cell.locator('.cell-run').click();
await page.waitForTimeout(500);
await cell.locator('.btn', { hasText: 'Arrêter' }).click();
await page.waitForFunction(() => document.querySelector('.cell:last-of-type')?.getAttribute('aria-busy') !== 'true', null, { timeout: 15000 });
@@ -79,3 +79,69 @@ test('parcours complet des niveaux 00 et 01', { skip, timeout: 180000 }, async (
assert.deepEqual(errors, []);
});
test('niveau 03 : saisie interactive et validation par rejeu scripté', { skip, timeout: 180000 }, async () => {
const page = await (await browser.newContext()).newPage();
const errors = [];
page.on('pageerror', (error) => errors.push(error.message));
await page.goto(base);
await page.waitForSelector('.progress-map .level-button', { timeout: 60000 });
await page.locator('.level-button', { hasText: 'Demander à l\'utilisateur' }).click();
await page.waitForSelector('.explain');
const next = () => page.locator('.notebook-action button').last().click();
const idle = () => page.waitForFunction(() => document.querySelector('.cell:last-of-type')?.getAttribute('aria-busy') !== 'true', null, { timeout: 30000 });
// Lance le code puis répond aux input() dans l'ordre ; renvoie sortie et retour de validation.
const run = async (code, answers = []) => {
const cell = page.locator('.cell').last();
await cell.locator('textarea').fill(code);
await cell.locator('.cell-run').click();
for (const answer of answers) {
await cell.locator('.cell-input-field').waitFor({ state: 'visible', timeout: 15000 });
await cell.locator('.cell-input-field').fill(answer);
await cell.locator('.cell-input-field').press('Enter');
}
await idle();
await page.waitForTimeout(150);
return {
output: await cell.locator('.cell-output').textContent(),
feedback: (await cell.locator('.cell-feedback').textContent()).trim(),
};
};
await next();
let result = await run('name = input("Ton prénom ? ")\nprint("Bonjour", name)', ['Zoé']);
assert.equal(result.output, 'Ton prénom ? Bonjour Zoé\n'.replace('Bonjour', 'Zoé\nBonjour'));
assert.match(result.feedback, /correct/);
await next();
await next();
result = await run('text = input("Un nombre entier ? ")\nnumber = text\nprint(number * 2)', ['21']);
assert.match(result.output, /2121/);
assert.match(result.feedback, /Pas encore/);
result = await run('text = input("Un nombre entier ? ")\nnumber = int(text)\nprint(number * 2)', ['21']);
assert.match(result.feedback, /correct/);
// Une saisie en attente peut être abandonnée avec « Arrêter ».
const cell = page.locator('.cell').last();
await cell.locator('textarea').fill('input("?")');
await cell.locator('.cell-run').click();
await cell.locator('.cell-input-field').waitFor({ state: 'visible' });
await cell.locator('.btn', { hasText: 'Arrêter' }).click();
await idle();
assert.match(await cell.locator('.cell-feedback').textContent(), /Exécution arrêtée/);
assert.equal(await cell.locator('.cell-input-field').isVisible(), false);
// Étape float, puis mission avec plusieurs rejeux scriptés (2010 -> 15, 2000 -> 25).
await next();
await next();
result = await run('text = input("Un prix ? ")\nprice = float(text)\nprint(price + 0.5)', ['2.5']);
assert.match(result.feedback, /correct/);
await next();
result = await run('current_year = 2025\nyear = int(input("Année ? "))\nage = current_year - year\nprint(age)', ['2010']);
assert.match(result.feedback, /correct/);
await page.waitForSelector('.toast');
assert.match(await page.textContent('.toast-region'), /\+40 XP/);
assert.deepEqual(errors, []);
});
+1 -1
View File
@@ -5,7 +5,7 @@ const root = new URL('../../', import.meta.url).pathname.replace(/\/$/, '');
const e = new LessonEngine({ levelsUrl: 'http://x/levels/', fetchFn: async (u) => {
try { const t = await readFile(root + new URL(u).pathname, 'utf8'); return { ok: true, text: async () => t }; }
catch { return { ok: false, status: 404 }; } } });
assert.deepEqual((await e.listLevels()).map((l) => l.id), ['00-intro', '01-hello', '02-variables']);
assert.deepEqual((await e.listLevels()).map((l) => l.id), ['00-intro', '01-hello', '02-variables', '03-input']);
const s = await e.startLevel('02-variables', 'en');
assert.equal(s.title, 'Variables and types'); assert.equal(s.stepCount, 7);
assert.equal(s.step.type, 'explain');
+46 -9
View File
@@ -13,27 +13,41 @@ test('worker Python sous Pyodide', { skip: !existsSync(`${indexURL}pyodide.mjs`)
workerData: { workerPath: `${root}app/js/workers/python-worker.js`, runnerPath: `${root}app/python/pyquest_runner.py` },
});
const interruptBuffer = new SharedArrayBuffer(1);
const inputBuffer = new SharedArrayBuffer(8 + 4096);
const control = new Int32Array(inputBuffer, 0, 2);
const prompts = [];
let inputAnswer = 'Léa'; // null = fin de saisie ; undefined = ne pas répondre
const answerInput = () => {
if (inputAnswer === undefined) return;
const length = inputAnswer === null ? 0 : new TextEncoder().encodeInto(inputAnswer, new Uint8Array(inputBuffer, 8)).written;
Atomics.store(control, 1, length);
Atomics.store(control, 0, inputAnswer === null ? 2 : 1);
Atomics.notify(control, 0);
};
const waiters = new Map();
const stdout = [];
worker.on('message', (message) => {
if (message.type === 'stdout') stdout.push(message.text);
if (message.type === 'input_request') {
prompts.push(message.prompt);
answerInput();
}
const key = message.type === 'result' ? message.id : 'init';
if (['result', 'ready', 'init_error'].includes(message.type)) waiters.get(key)?.(message);
});
const wait = (key) =>
new Promise((resolve, reject) => {
waiters.set(key, resolve);
worker.once('error', reject);
});
const run = (id, code, collect = []) => {
worker.on('error', (error) => {
throw error;
});
const wait = (key) => new Promise((resolve) => waiters.set(key, resolve));
const run = (id, code, collect = [], isolated = false) => {
const done = wait(id);
worker.postMessage({ type: 'run_code', id, code, collect });
worker.postMessage({ type: 'run_code', id, code, collect, isolated });
return done;
};
try {
const init = wait('init');
worker.postMessage({ type: 'init', indexURL, interruptBuffer });
worker.postMessage({ type: 'init', indexURL, interruptBuffer, inputBuffer });
assert.deepEqual(await init, { type: 'ready', interruptible: true });
let result = await run(1, 'x = 10.0\nprint("hé")\nprint(x)', ['x']);
@@ -47,9 +61,32 @@ test('worker Python sous Pyodide', { skip: !existsSync(`${indexURL}pyodide.mjs`)
result = await run(3, 'y = x + 1', ['y']); // l'espace de noms persiste
assert.equal(result.variables.y.value, 11);
result = await run(4, 'input("?")');
// input() : réponse de l'apprenant, y compris caractères non ASCII.
result = await run(4, 'who = input("Nom ? ")\nprint("Salut " + who)', ['who']);
assert.equal(result.ok, true);
assert.equal(result.variables.who.value, 'Léa');
assert.deepEqual(prompts, ['Nom ? ']);
assert.ok(stdout.join('').includes('Nom ? Salut Léa\n'), 'invite et sortie dans stdout');
// Fin de saisie : EOFError.
inputAnswer = null;
result = await run(7, 'input()');
assert.equal(result.error.type, 'EOFError');
// Interruption pendant l'attente d'une saisie : KeyboardInterrupt, pas EOFError.
inputAnswer = undefined;
const waiting = run(8, 'input("?")');
setTimeout(() => (new Uint8Array(interruptBuffer)[0] = 2), 400);
assert.equal((await waiting).error.type, 'KeyboardInterrupt');
inputAnswer = 'x';
// Exécution isolée : l'espace de noms de l'apprenant n'est pas modifié.
await run(9, 'counter = 1');
result = await run(10, 'counter = 99', ['counter'], true);
assert.equal(result.variables.counter.value, 99);
result = await run(11, 'pass', ['counter']);
assert.equal(result.variables.counter.value, 1);
const looping = run(5, 'while True:\n pass');
setTimeout(() => (new Uint8Array(interruptBuffer)[0] = 2), 500);
assert.equal((await looping).error.type, 'KeyboardInterrupt');
+44
View File
@@ -0,0 +1,44 @@
// Client : réponse à input() via le SharedArrayBuffer partagé avec le worker.
import { PyodideWorkerClient } from '../../app/js/core/PyodideWorkerClient.js';
import assert from 'node:assert';
globalThis.crossOriginIsolated = true;
let inputBuffer = null;
globalThis.Worker = class {
constructor() {
this.listeners = {};
}
addEventListener(type, listener) {
this.listeners[type] = listener;
}
terminate() {}
postMessage(message) {
const reply = (data) => queueMicrotask(() => this.listeners.message({ data }));
if (message.type === 'init') {
inputBuffer = message.inputBuffer;
reply({ type: 'ready', interruptible: true });
}
if (message.type === 'run_code') {
reply({ type: 'input_request', id: message.id, prompt: 'Nom ? ' });
// Le vrai worker attend l'état ; ici on termine la cellule après un délai.
setTimeout(() => reply({ type: 'result', id: message.id, ok: true, error: null, variables: {} }), 20);
}
}
};
const client = new PyodideWorkerClient({ indexURL: '/v/', workerUrl: 'x' });
const prompts = [];
await client.run('ask', { onInput: async (prompt) => (prompts.push(prompt), 'héé') });
await new Promise((resolve) => setTimeout(resolve, 10));
const control = new Int32Array(inputBuffer, 0, 2);
assert.deepEqual(prompts, ['Nom ? ']);
assert.equal(Atomics.load(control, 0), 1);
assert.equal(new TextDecoder().decode(new Uint8Array(inputBuffer, 8, Atomics.load(control, 1))), 'héé');
// Sans gestionnaire : fin de saisie.
await client.run('ask');
await new Promise((resolve) => setTimeout(resolve, 10));
assert.equal(Atomics.load(control, 0), 2);
client.dispose();
console.log('client input ok');
Binary file not shown.
+19
View File
@@ -2,6 +2,7 @@
from __future__ import annotations
import builtins
import json
import sys
import unittest
@@ -41,6 +42,24 @@ class RunnerTest(unittest.TestCase):
error = run("def f(:\n pass")["error"]
self.assertEqual((error["type"], error["lineno"]), ("SyntaxError", 1))
def test_isolated_run_does_not_touch_namespace(self) -> None:
run("n = 1")
isolated = json.loads(runner.run_cell("n = 99", json.dumps(["n"]), True))
self.assertEqual(isolated["variables"]["n"]["value"], 99)
self.assertEqual(run("pass", ["n"])["variables"]["n"]["value"], 1)
def test_input_uses_bridge_and_reports_eof(self) -> None:
original = builtins.input
try:
runner.set_input_bridge(lambda prompt: json.dumps({"status": "ok", "text": "7"}))
self.assertEqual(run("v = input('?')", ["v"])["variables"]["v"]["value"], "7")
runner.set_input_bridge(lambda prompt: json.dumps({"status": "eof"}))
self.assertEqual(run("input()")["error"]["type"], "EOFError")
runner.set_input_bridge(lambda prompt: json.dumps({"status": "interrupted"}))
self.assertEqual(run("input()")["error"]["type"], "KeyboardInterrupt")
finally:
builtins.input = original
def test_non_finite_float_has_no_json_value(self) -> None:
self.assertIsNone(run("x = float('inf')", ["x"])["variables"]["x"]["value"])