mirror of
https://github.com/deunix-educ/PyQuest.git
synced 2026-11-25 08:19:44 +01:00
Add real input() support via SharedArrayBuffer and level 03
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
+3
-2
@@ -42,8 +42,9 @@ Le brief original est [`prompt-pyquest.md`](prompt-pyquest.md) (résumé fidèle
|
|||||||
3. Branchement du client de synchronisation (jeton Bearer + `ProgressStore.export/import`) :
|
3. Branchement du client de synchronisation (jeton Bearer + `ProgressStore.export/import`) :
|
||||||
le backend (`backend/sync`) existe, pas encore le côté client ni l'UI.
|
le backend (`backend/sync`) existe, pas encore le côté client ni l'UI.
|
||||||
4. Documentation MkDocs bilingue (`docs/mkdocs/`).
|
4. Documentation MkDocs bilingue (`docs/mkdocs/`).
|
||||||
5. Niveaux 03 à 14 (voir `docs/design/05-curriculum.md`). `input()` doit d'abord être tranché :
|
5. Niveaux 04 à 14 (voir `docs/design/05-curriculum.md`). Niveau 03 fait ; `input()` est réel
|
||||||
actuellement `EOFError` (pas de saisie synchrone dans le worker).
|
(option b : `Atomics.wait` + SharedArrayBuffer, formulaire dans la cellule, tests à `inputs`
|
||||||
|
scriptés rejoués en isolation). Sans isolation cross-origin : `EOFError`.
|
||||||
6. Audit accessibilité réel (lecteur d'écran, axe) et compilation des traductions Django
|
6. Audit accessibilité réel (lecteur d'écran, axe) et compilation des traductions Django
|
||||||
(`compilemessages`, gettext absent sur le poste actuel).
|
(`compilemessages`, gettext absent sur le poste actuel).
|
||||||
7. Kinds de test non encore définis : `stdout_contains_any_name`, `function_called_with`.
|
7. Kinds de test non encore définis : `stdout_contains_any_name`, `function_called_with`.
|
||||||
|
|||||||
@@ -39,6 +39,12 @@ Français d'abord, English below.
|
|||||||
| `var_equals` | `name`, `value` | variable égale à la valeur |
|
| `var_equals` | `name`, `value` | variable égale à la valeur |
|
||||||
| `var_type_is` | `name`, `value` | type de la variable (`str`, `int`, `float`…) |
|
| `var_type_is` | `name`, `value` | type de la variable (`str`, `int`, `float`…) |
|
||||||
|
|
||||||
|
Tout test accepte un champ optionnel `inputs` (liste de chaînes). Pour un code qui appelle
|
||||||
|
`input()`, le test est alors évalué sur un **rejeu** du code (sur une copie de l'état) où chaque
|
||||||
|
`input()` reçoit la valeur suivante de la liste : la validation est déterministe, quelle que soit
|
||||||
|
la saisie réelle de l'apprenant. Les tests sans `inputs` portent sur l'exécution de l'apprenant.
|
||||||
|
L'invite de `input()` est écrite dans la sortie standard (comme en Python), pas la réponse.
|
||||||
|
|
||||||
Un niveau ne contient **jamais de code exécutable** autre que le code de départ et la solution
|
Un niveau ne contient **jamais de code exécutable** autre que le code de départ et la solution
|
||||||
affichés à l'apprenant : toute nouvelle sorte de validation passe par le moteur
|
affichés à l'apprenant : toute nouvelle sorte de validation passe par le moteur
|
||||||
(`app/js/core/ValidationEngine.js`), pas par un fichier de niveau.
|
(`app/js/core/ValidationEngine.js`), pas par un fichier de niveau.
|
||||||
|
|||||||
@@ -2,6 +2,11 @@
|
|||||||
// Protocole des messages : voir app/js/workers/python-worker.js.
|
// Protocole des messages : voir app/js/workers/python-worker.js.
|
||||||
|
|
||||||
const SIGINT = 2;
|
const SIGINT = 2;
|
||||||
|
// Zone de réponse à input() : 8 octets d'en-tête (état, longueur) puis le texte UTF-8.
|
||||||
|
const INPUT_HEADER_BYTES = 8;
|
||||||
|
const INPUT_MAX_BYTES = 4096;
|
||||||
|
const INPUT_STATE_ANSWER = 1;
|
||||||
|
const INPUT_STATE_EOF = 2;
|
||||||
// Délai après lequel une interruption qui n'aboutit pas est remplacée par un terminate().
|
// Délai après lequel une interruption qui n'aboutit pas est remplacée par un terminate().
|
||||||
const INTERRUPT_GRACE_MS = 2000;
|
const INTERRUPT_GRACE_MS = 2000;
|
||||||
|
|
||||||
@@ -10,6 +15,8 @@ export class PyodideWorkerClient {
|
|||||||
#indexURL;
|
#indexURL;
|
||||||
#worker = null;
|
#worker = null;
|
||||||
#interruptView = null;
|
#interruptView = null;
|
||||||
|
#inputControl = null;
|
||||||
|
#inputData = null;
|
||||||
#interruptible = false;
|
#interruptible = false;
|
||||||
#ready = null;
|
#ready = null;
|
||||||
#readyHandlers = null;
|
#readyHandlers = null;
|
||||||
@@ -47,14 +54,17 @@ export class PyodideWorkerClient {
|
|||||||
* @param {string[]} [options.collect] Variables à relire après l'exécution.
|
* @param {string[]} [options.collect] Variables à relire après l'exécution.
|
||||||
* @param {(text: string) => void} [options.onStdout]
|
* @param {(text: string) => void} [options.onStdout]
|
||||||
* @param {(text: string) => void} [options.onStderr]
|
* @param {(text: string) => void} [options.onStderr]
|
||||||
|
* @param {(prompt: string) => Promise<string|null>} [options.onInput] Répond à input() ;
|
||||||
|
* null ou absent = fin de saisie (EOFError côté Python).
|
||||||
|
* @param {boolean} [options.isolated] Exécute sur une copie de l'état, sans le modifier.
|
||||||
* @returns {Promise<{ok: boolean, error: object|null, variables: object}>}
|
* @returns {Promise<{ok: boolean, error: object|null, variables: object}>}
|
||||||
*/
|
*/
|
||||||
async run(code, { collect = [], onStdout = () => {}, onStderr = () => {} } = {}) {
|
async run(code, { collect = [], onStdout = () => {}, onStderr = () => {}, onInput = null, isolated = false } = {}) {
|
||||||
await this.start();
|
await this.start();
|
||||||
const id = this.#nextId++;
|
const id = this.#nextId++;
|
||||||
return new Promise((resolve) => {
|
return new Promise((resolve) => {
|
||||||
this.#pending.set(id, { resolve, onStdout, onStderr });
|
this.#pending.set(id, { resolve, onStdout, onStderr, onInput });
|
||||||
this.#worker.postMessage({ type: 'run_code', id, code, collect });
|
this.#worker.postMessage({ type: 'run_code', id, code, collect, isolated });
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -93,6 +103,9 @@ export class PyodideWorkerClient {
|
|||||||
const canShare = typeof SharedArrayBuffer !== 'undefined' && globalThis.crossOriginIsolated === true;
|
const canShare = typeof SharedArrayBuffer !== 'undefined' && globalThis.crossOriginIsolated === true;
|
||||||
const buffer = canShare ? new SharedArrayBuffer(1) : null;
|
const buffer = canShare ? new SharedArrayBuffer(1) : null;
|
||||||
this.#interruptView = buffer ? new Uint8Array(buffer) : null;
|
this.#interruptView = buffer ? new Uint8Array(buffer) : null;
|
||||||
|
const inputBuffer = canShare ? new SharedArrayBuffer(INPUT_HEADER_BYTES + INPUT_MAX_BYTES) : null;
|
||||||
|
this.#inputControl = inputBuffer ? new Int32Array(inputBuffer, 0, 2) : null;
|
||||||
|
this.#inputData = inputBuffer ? new Uint8Array(inputBuffer, INPUT_HEADER_BYTES) : null;
|
||||||
|
|
||||||
this.#worker = new Worker(this.#workerUrl, { type: 'module' });
|
this.#worker = new Worker(this.#workerUrl, { type: 'module' });
|
||||||
this.#worker.addEventListener('message', (event) => this.#onMessage(event.data));
|
this.#worker.addEventListener('message', (event) => this.#onMessage(event.data));
|
||||||
@@ -100,7 +113,7 @@ export class PyodideWorkerClient {
|
|||||||
|
|
||||||
return new Promise((resolve, reject) => {
|
return new Promise((resolve, reject) => {
|
||||||
this.#readyHandlers = { resolve, reject };
|
this.#readyHandlers = { resolve, reject };
|
||||||
this.#worker.postMessage({ type: 'init', indexURL: this.#indexURL, interruptBuffer: buffer });
|
this.#worker.postMessage({ type: 'init', indexURL: this.#indexURL, interruptBuffer: buffer, inputBuffer });
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -120,6 +133,9 @@ export class PyodideWorkerClient {
|
|||||||
case 'stderr':
|
case 'stderr':
|
||||||
this.#pending.get(message.id)?.onStderr(message.text);
|
this.#pending.get(message.id)?.onStderr(message.text);
|
||||||
break;
|
break;
|
||||||
|
case 'input_request':
|
||||||
|
this.#answerInput(message);
|
||||||
|
break;
|
||||||
case 'result': {
|
case 'result': {
|
||||||
const entry = this.#pending.get(message.id);
|
const entry = this.#pending.get(message.id);
|
||||||
if (entry) {
|
if (entry) {
|
||||||
@@ -135,6 +151,33 @@ export class PyodideWorkerClient {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Transmet la réponse de l'apprenant au worker bloqué dans input(). */
|
||||||
|
async #answerInput({ id, prompt }) {
|
||||||
|
const worker = this.#worker;
|
||||||
|
const handler = this.#pending.get(id)?.onInput;
|
||||||
|
let answer = null;
|
||||||
|
try {
|
||||||
|
answer = handler ? await handler(prompt) : null;
|
||||||
|
} catch {
|
||||||
|
answer = null;
|
||||||
|
}
|
||||||
|
// Le worker a pu être remplacé (interruption forcée) pendant l'attente.
|
||||||
|
if (worker !== this.#worker || !this.#inputControl) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let length = 0;
|
||||||
|
if (answer !== null) {
|
||||||
|
// encodeInto refuse une vue sur SharedArrayBuffer (navigateurs) : on encode d'abord en
|
||||||
|
// mémoire locale, en ne gardant que des caractères entiers, puis on recopie.
|
||||||
|
const local = new Uint8Array(INPUT_MAX_BYTES);
|
||||||
|
length = new TextEncoder().encodeInto(answer, local).written;
|
||||||
|
this.#inputData.set(local.subarray(0, length));
|
||||||
|
}
|
||||||
|
Atomics.store(this.#inputControl, 1, length);
|
||||||
|
Atomics.store(this.#inputControl, 0, answer === null ? INPUT_STATE_EOF : INPUT_STATE_ANSWER);
|
||||||
|
Atomics.notify(this.#inputControl, 0);
|
||||||
|
}
|
||||||
|
|
||||||
/** Termine le worker, rejoue les cellules en attente comme interrompues, puis le recrée. */
|
/** Termine le worker, rejoue les cellules en attente comme interrompues, puis le recrée. */
|
||||||
#hardRestart() {
|
#hardRestart() {
|
||||||
clearTimeout(this.#graceTimer);
|
clearTimeout(this.#graceTimer);
|
||||||
|
|||||||
@@ -16,6 +16,8 @@
|
|||||||
"cell.solution": "Show the solution",
|
"cell.solution": "Show the solution",
|
||||||
"cell.output": "Output",
|
"cell.output": "Output",
|
||||||
"cell.output_empty": "(nothing printed)",
|
"cell.output_empty": "(nothing printed)",
|
||||||
|
"cell.input_label": "Answer requested by the program",
|
||||||
|
"cell.input_send": "Send",
|
||||||
"cell.shortcut": "Ctrl/Cmd + Enter to run",
|
"cell.shortcut": "Ctrl/Cmd + Enter to run",
|
||||||
"cell.passed": "Well done, that's correct!",
|
"cell.passed": "Well done, that's correct!",
|
||||||
"cell.failed": "Not yet. Here is what is wrong:",
|
"cell.failed": "Not yet. Here is what is wrong:",
|
||||||
|
|||||||
@@ -16,6 +16,8 @@
|
|||||||
"cell.solution": "Voir la solution",
|
"cell.solution": "Voir la solution",
|
||||||
"cell.output": "Résultat",
|
"cell.output": "Résultat",
|
||||||
"cell.output_empty": "(aucun affichage)",
|
"cell.output_empty": "(aucun affichage)",
|
||||||
|
"cell.input_label": "Réponse demandée par le programme",
|
||||||
|
"cell.input_send": "Envoyer",
|
||||||
"cell.shortcut": "Ctrl/Cmd + Entrée pour exécuter",
|
"cell.shortcut": "Ctrl/Cmd + Entrée pour exécuter",
|
||||||
"cell.passed": "Bravo, c'est correct !",
|
"cell.passed": "Bravo, c'est correct !",
|
||||||
"cell.failed": "Pas encore. Voici ce qui ne va pas :",
|
"cell.failed": "Pas encore. Voici ce qui ne va pas :",
|
||||||
|
|||||||
@@ -76,7 +76,7 @@ export class CellManager extends EventTarget {
|
|||||||
const cell = new CellView(i18n, step);
|
const cell = new CellView(i18n, step);
|
||||||
notebook.add(cell.element);
|
notebook.add(cell.element);
|
||||||
cell.focus();
|
cell.focus();
|
||||||
cell.addEventListener('stop', () => this.#deps.client.interrupt());
|
cell.addEventListener('stop', () => this.#stop(cell));
|
||||||
let continueShown = false;
|
let continueShown = false;
|
||||||
cell.addEventListener('run', async (event) => {
|
cell.addEventListener('run', async (event) => {
|
||||||
const passed = await this.#execute(cell, event.detail.code, step.tests);
|
const passed = await this.#execute(cell, event.detail.code, step.tests);
|
||||||
@@ -100,7 +100,7 @@ export class CellManager extends EventTarget {
|
|||||||
const cell = new CellView(i18n, { starter: mission.starter, instruction: mission.goal });
|
const cell = new CellView(i18n, { starter: mission.starter, instruction: mission.goal });
|
||||||
notebook.add(cell.element);
|
notebook.add(cell.element);
|
||||||
cell.focus();
|
cell.focus();
|
||||||
cell.addEventListener('stop', () => this.#deps.client.interrupt());
|
cell.addEventListener('stop', () => this.#stop(cell));
|
||||||
cell.addEventListener('run', async (event) => {
|
cell.addEventListener('run', async (event) => {
|
||||||
if (await this.#execute(cell, event.detail.code, mission.tests)) {
|
if (await this.#execute(cell, event.detail.code, mission.tests)) {
|
||||||
await this.#completeLevel(mission);
|
await this.#completeLevel(mission);
|
||||||
@@ -108,7 +108,17 @@ export class CellManager extends EventTarget {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Exécute le code d'une cellule et valide. Renvoie vrai si tous les tests passent. */
|
#stop(cell) {
|
||||||
|
// Ordre important : l'interruption doit être posée avant d'annuler la saisie en attente,
|
||||||
|
// pour que Python reçoive KeyboardInterrupt plutôt qu'une fin de fichier.
|
||||||
|
this.#deps.client.interrupt();
|
||||||
|
cell.cancelInput();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Exécute le code d'une cellule et valide. Renvoie vrai si tous les tests passent.
|
||||||
|
* Les tests qui déclarent `inputs` rejouent le code, en isolation, avec ces saisies scriptées.
|
||||||
|
*/
|
||||||
async #execute(cell, code, tests) {
|
async #execute(cell, code, tests) {
|
||||||
const { client, validator, translator, audio, i18n } = this.#deps;
|
const { client, validator, translator, audio, i18n } = this.#deps;
|
||||||
await audio.unlock(); // le clic sur « Exécuter » est le geste utilisateur requis
|
await audio.unlock(); // le clic sur « Exécuter » est le geste utilisateur requis
|
||||||
@@ -123,20 +133,62 @@ export class CellManager extends EventTarget {
|
|||||||
collect: ValidationEngine.variablesToCollect(tests),
|
collect: ValidationEngine.variablesToCollect(tests),
|
||||||
onStdout: onOutput,
|
onStdout: onOutput,
|
||||||
onStderr: onOutput,
|
onStderr: onOutput,
|
||||||
|
onInput: (prompt) => cell.requestInput(prompt),
|
||||||
});
|
});
|
||||||
cell.setBusy(false);
|
|
||||||
|
|
||||||
if (result.error) {
|
if (result.error) {
|
||||||
|
cell.setBusy(false);
|
||||||
cell.showError(translator.translate(result.error, i18n.lang));
|
cell.showError(translator.translate(result.error, i18n.lang));
|
||||||
audio.play('error');
|
audio.play('error');
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
const validation = validator.validate(tests, { stdout, result });
|
const validation = await this.#validate(code, tests, { stdout, result });
|
||||||
|
cell.setBusy(false);
|
||||||
cell.showValidation(validation);
|
cell.showValidation(validation);
|
||||||
audio.play(validation.passed ? 'success_small' : 'error');
|
audio.play(validation.passed ? 'success_small' : 'error');
|
||||||
return validation.passed;
|
return validation.passed;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Valide : tests sans `inputs` sur l'exécution de l'apprenant, les autres sur des rejeux scriptés. */
|
||||||
|
async #validate(code, tests, interactive) {
|
||||||
|
const { validator, client } = this.#deps;
|
||||||
|
const groups = new Map();
|
||||||
|
tests.forEach((test, index) => {
|
||||||
|
const key = JSON.stringify(test.inputs ?? null);
|
||||||
|
groups.set(key, [...(groups.get(key) ?? []), { test, index }]);
|
||||||
|
});
|
||||||
|
|
||||||
|
const results = new Array(tests.length);
|
||||||
|
for (const [key, members] of groups) {
|
||||||
|
const inputs = JSON.parse(key);
|
||||||
|
let execution = interactive;
|
||||||
|
if (inputs !== null) {
|
||||||
|
execution = await this.#replay(code, inputs, ValidationEngine.variablesToCollect(members.map((m) => m.test)), client);
|
||||||
|
}
|
||||||
|
const { results: partial } = validator.validate(
|
||||||
|
members.map((m) => m.test),
|
||||||
|
execution,
|
||||||
|
);
|
||||||
|
partial.forEach((entry, i) => (results[members[i].index] = entry));
|
||||||
|
}
|
||||||
|
const passed = interactive.result.ok && results.every((entry) => entry.passed);
|
||||||
|
return { passed, results };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Rejoue le code sur une copie de l'état, en répondant aux input() avec `inputs`. */
|
||||||
|
async #replay(code, inputs, collect, client) {
|
||||||
|
let stdout = '';
|
||||||
|
const queue = [...inputs];
|
||||||
|
const result = await client.run(code, {
|
||||||
|
collect,
|
||||||
|
isolated: true,
|
||||||
|
onStdout: (text) => (stdout += text),
|
||||||
|
onStderr: (text) => (stdout += text),
|
||||||
|
onInput: async () => (queue.length > 0 ? queue.shift() : null),
|
||||||
|
});
|
||||||
|
return { stdout, result };
|
||||||
|
}
|
||||||
|
|
||||||
async #completeLevel(mission) {
|
async #completeLevel(mission) {
|
||||||
const { progress, toast, audio, i18n, notebook } = this.#deps;
|
const { progress, toast, audio, i18n, notebook } = this.#deps;
|
||||||
const outcome = await progress.completeLevel(this.#session.id, this.#session.xp);
|
const outcome = await progress.completeLevel(this.#session.id, this.#session.xp);
|
||||||
|
|||||||
+50
-1
@@ -14,6 +14,9 @@ export class CellView extends EventTarget {
|
|||||||
#runButton;
|
#runButton;
|
||||||
#stopButton;
|
#stopButton;
|
||||||
#busy = false;
|
#busy = false;
|
||||||
|
#inputForm;
|
||||||
|
#inputField;
|
||||||
|
#resolveInput = null;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @param {import('../i18n/i18n.js').I18n} i18n
|
* @param {import('../i18n/i18n.js').I18n} i18n
|
||||||
@@ -44,7 +47,7 @@ export class CellView extends EventTarget {
|
|||||||
});
|
});
|
||||||
this.#editor.value = starter;
|
this.#editor.value = starter;
|
||||||
|
|
||||||
this.#runButton = el('button', { type: 'button', class: 'btn btn-primary', text: i18n.t('cell.run'), onclick: () => this.#emitRun() });
|
this.#runButton = el('button', { type: 'button', class: 'btn btn-primary cell-run', text: i18n.t('cell.run'), onclick: () => this.#emitRun() });
|
||||||
this.#stopButton = el('button', {
|
this.#stopButton = el('button', {
|
||||||
type: 'button',
|
type: 'button',
|
||||||
class: 'btn',
|
class: 'btn',
|
||||||
@@ -57,6 +60,17 @@ export class CellView extends EventTarget {
|
|||||||
this.#output = el('pre', { id: outputId, class: 'cell-output', 'aria-live': 'polite', 'aria-label': i18n.t('cell.output') });
|
this.#output = el('pre', { id: outputId, class: 'cell-output', 'aria-live': 'polite', 'aria-label': i18n.t('cell.output') });
|
||||||
this.#feedback = el('div', { class: 'cell-feedback', role: 'status' });
|
this.#feedback = el('div', { class: 'cell-feedback', role: 'status' });
|
||||||
|
|
||||||
|
// Saisie demandée par input() : formulaire affiché seulement pendant l'attente.
|
||||||
|
const inputId = uniqueId('input');
|
||||||
|
this.#inputField = el('input', { id: inputId, type: 'text', class: 'cell-input-field', autocomplete: 'off', spellcheck: 'false' });
|
||||||
|
this.#inputForm = el(
|
||||||
|
'form',
|
||||||
|
{ class: 'cell-input', hidden: true, onsubmit: (event) => this.#submitInput(event) },
|
||||||
|
el('label', { for: inputId, text: i18n.t('cell.input_label') }),
|
||||||
|
this.#inputField,
|
||||||
|
el('button', { type: 'submit', class: 'btn btn-primary', text: i18n.t('cell.input_send') }),
|
||||||
|
);
|
||||||
|
|
||||||
const solutionBlock = solution
|
const solutionBlock = solution
|
||||||
? el('details', { class: 'solution' }, el('summary', { text: i18n.t('cell.solution') }), el('pre', {}, el('code', { text: solution })))
|
? el('details', { class: 'solution' }, el('summary', { text: i18n.t('cell.solution') }), el('pre', {}, el('code', { text: solution })))
|
||||||
: null;
|
: null;
|
||||||
@@ -69,6 +83,7 @@ export class CellView extends EventTarget {
|
|||||||
el('p', { id: `${editorId}-hint`, class: 'cell-shortcut', text: i18n.t('cell.shortcut') }),
|
el('p', { id: `${editorId}-hint`, class: 'cell-shortcut', text: i18n.t('cell.shortcut') }),
|
||||||
el('div', { class: 'cell-actions' }, this.#runButton, this.#stopButton, resetButton, new HintPanel(i18n, hints).element),
|
el('div', { class: 'cell-actions' }, this.#runButton, this.#stopButton, resetButton, new HintPanel(i18n, hints).element),
|
||||||
this.#output,
|
this.#output,
|
||||||
|
this.#inputForm,
|
||||||
this.#feedback,
|
this.#feedback,
|
||||||
solutionBlock,
|
solutionBlock,
|
||||||
);
|
);
|
||||||
@@ -103,6 +118,40 @@ export class CellView extends EventTarget {
|
|||||||
this.#output.append(document.createTextNode(text));
|
this.#output.append(document.createTextNode(text));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Demande une saisie à l'apprenant (appelé par input()). Résout avec le texte saisi, ou null
|
||||||
|
* si la saisie est annulée (arrêt de la cellule).
|
||||||
|
* @param {string} prompt Invite déjà affichée dans la sortie par Python ; sert de repère pour les lecteurs d'écran.
|
||||||
|
* @returns {Promise<string|null>}
|
||||||
|
*/
|
||||||
|
requestInput(prompt) {
|
||||||
|
this.cancelInput();
|
||||||
|
this.#inputField.value = '';
|
||||||
|
this.#inputField.setAttribute('aria-description', prompt);
|
||||||
|
this.#inputForm.hidden = false;
|
||||||
|
this.#inputField.focus();
|
||||||
|
return new Promise((resolve) => {
|
||||||
|
this.#resolveInput = resolve;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Annule une saisie en attente (la promesse résout null). */
|
||||||
|
cancelInput() {
|
||||||
|
this.#inputForm.hidden = true;
|
||||||
|
this.#resolveInput?.(null);
|
||||||
|
this.#resolveInput = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
#submitInput(event) {
|
||||||
|
event.preventDefault();
|
||||||
|
const answer = this.#inputField.value;
|
||||||
|
this.#inputForm.hidden = true;
|
||||||
|
// L'écho n'est que de l'affichage : il n'entre pas dans la sortie standard validée.
|
||||||
|
this.appendOutput(`${answer}\n`);
|
||||||
|
this.#resolveInput?.(answer);
|
||||||
|
this.#resolveInput = null;
|
||||||
|
}
|
||||||
|
|
||||||
/** Remet le code de départ et vide la sortie. */
|
/** Remet le code de départ et vide la sortie. */
|
||||||
reset() {
|
reset() {
|
||||||
this.#editor.value = this.#starter;
|
this.#editor.value = this.#starter;
|
||||||
|
|||||||
@@ -1,26 +1,35 @@
|
|||||||
// Worker du moteur Python : charge Pyodide (vendorisé) et exécute le code des cellules.
|
// Worker du moteur Python : charge Pyodide (vendorisé) et exécute le code des cellules.
|
||||||
//
|
//
|
||||||
// Protocole (messages entrants) :
|
// Protocole (messages entrants) :
|
||||||
// { type: 'init', indexURL, interruptBuffer? } charge Pyodide ; répond 'ready' ou 'init_error'
|
// { type: 'init', indexURL, interruptBuffer?, inputBuffer? } charge Pyodide ; répond 'ready' ou 'init_error'
|
||||||
// { type: 'run_code', id, code, collect? } exécute une cellule ; répond 'result'
|
// { type: 'run_code', id, code, collect?, isolated? } exécute une cellule ; répond 'result'
|
||||||
// { type: 'reset' } vide l'espace de noms Python
|
// { type: 'reset' } vide l'espace de noms Python
|
||||||
//
|
//
|
||||||
// Messages sortants :
|
// Messages sortants :
|
||||||
// { type: 'ready', interruptible }
|
// { type: 'ready', interruptible }
|
||||||
// { type: 'init_error', message }
|
// { type: 'init_error', message }
|
||||||
// { type: 'stdout' | 'stderr', id, text } flux brut, au fil de l'exécution
|
// { type: 'stdout' | 'stderr', id, text } flux brut, au fil de l'exécution
|
||||||
|
// { type: 'input_request', id, prompt } input() attend une réponse (voir ci-dessous)
|
||||||
// { type: 'result', id, ok, error, variables } error = { type, message, lineno, traceback }
|
// { type: 'result', id, ok, error, variables } error = { type, message, lineno, traceback }
|
||||||
//
|
//
|
||||||
// Interruption : pas de message 'interrupt'. Pendant qu'une cellule tourne, le worker est
|
// Interruption : pas de message 'interrupt'. Pendant qu'une cellule tourne, le worker est
|
||||||
// occupé et ne lirait pas ses messages ; le client écrit donc 2 (SIGINT) directement dans le
|
// occupé et ne lirait pas ses messages ; le client écrit donc 2 (SIGINT) directement dans le
|
||||||
// SharedArrayBuffer fourni à 'init'. Python lève alors KeyboardInterrupt dans la cellule.
|
// SharedArrayBuffer fourni à 'init'. Python lève alors KeyboardInterrupt dans la cellule.
|
||||||
|
|
||||||
|
// Saisie (input) : le worker est bloqué dans Python pendant input(), il ne peut donc pas lire de
|
||||||
|
// message. Le client répond via un SharedArrayBuffer : Int32[0] = état (0 attente, 1 réponse,
|
||||||
|
// 2 fin de saisie/EOF), Int32[1] = longueur en octets, puis le texte UTF-8 à partir de l'octet 8.
|
||||||
const SIGINT = 2;
|
const SIGINT = 2;
|
||||||
|
const INPUT_WAIT_SLICE_MS = 50;
|
||||||
|
const INPUT_HEADER_BYTES = 8;
|
||||||
|
const INPUT_STATE_ANSWER = 1;
|
||||||
|
|
||||||
class PythonWorker {
|
class PythonWorker {
|
||||||
#pyodide = null;
|
#pyodide = null;
|
||||||
#runner = null;
|
#runner = null;
|
||||||
#interruptView = null;
|
#interruptView = null;
|
||||||
|
#inputControl = null;
|
||||||
|
#inputData = null;
|
||||||
#currentId = null;
|
#currentId = null;
|
||||||
#ready = null;
|
#ready = null;
|
||||||
|
|
||||||
@@ -42,7 +51,7 @@ class PythonWorker {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async #init({ indexURL, interruptBuffer }) {
|
async #init({ indexURL, interruptBuffer, inputBuffer }) {
|
||||||
try {
|
try {
|
||||||
// Import dynamique : le worker est de type module, Pyodide est servi en local (COEP).
|
// Import dynamique : le worker est de type module, Pyodide est servi en local (COEP).
|
||||||
const { loadPyodide } = await import(`${indexURL}pyodide.mjs`);
|
const { loadPyodide } = await import(`${indexURL}pyodide.mjs`);
|
||||||
@@ -61,6 +70,13 @@ class PythonWorker {
|
|||||||
this.#pyodide.runPython("import sys; sys.path.insert(0, '/pyquest')");
|
this.#pyodide.runPython("import sys; sys.path.insert(0, '/pyquest')");
|
||||||
this.#runner = this.#pyodide.pyimport('pyquest_runner');
|
this.#runner = this.#pyodide.pyimport('pyquest_runner');
|
||||||
|
|
||||||
|
// Sans SharedArrayBuffer, pas de saisie : input() lève EOFError (comportement par défaut).
|
||||||
|
if (inputBuffer instanceof SharedArrayBuffer) {
|
||||||
|
this.#inputControl = new Int32Array(inputBuffer, 0, 2);
|
||||||
|
this.#inputData = new Uint8Array(inputBuffer, INPUT_HEADER_BYTES);
|
||||||
|
this.#runner.set_input_bridge((prompt) => this.#requestInput(prompt));
|
||||||
|
}
|
||||||
|
|
||||||
// Sans SharedArrayBuffer (page non isolée), pas d'interruption propre :
|
// Sans SharedArrayBuffer (page non isolée), pas d'interruption propre :
|
||||||
// le client doit alors se rabattre sur worker.terminate().
|
// le client doit alors se rabattre sur worker.terminate().
|
||||||
let interruptible = false;
|
let interruptible = false;
|
||||||
@@ -88,7 +104,32 @@ class PythonWorker {
|
|||||||
|
|
||||||
#decoders = { stdout: new TextDecoder(), stderr: new TextDecoder() };
|
#decoders = { stdout: new TextDecoder(), stderr: new TextDecoder() };
|
||||||
|
|
||||||
async #run({ id, code, collect = [] }) {
|
/** Bloque jusqu'à la réponse de l'apprenant. Renvoie le JSON attendu par pyquest_runner. */
|
||||||
|
#requestInput(prompt) {
|
||||||
|
const control = this.#inputControl;
|
||||||
|
Atomics.store(control, 0, 0);
|
||||||
|
self.postMessage({ type: 'input_request', id: this.#currentId, prompt });
|
||||||
|
// Attente par tranches : permet de réagir à une interruption pendant la saisie.
|
||||||
|
while (Atomics.load(control, 0) === 0) {
|
||||||
|
if (this.#interruptView?.[0] === SIGINT) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
Atomics.wait(control, 0, 0, INPUT_WAIT_SLICE_MS);
|
||||||
|
}
|
||||||
|
// L'interruption prime sur une réponse arrivée dans la même tranche.
|
||||||
|
if (this.#interruptView?.[0] === SIGINT) {
|
||||||
|
this.#interruptView[0] = 0;
|
||||||
|
return JSON.stringify({ status: 'interrupted' });
|
||||||
|
}
|
||||||
|
if (Atomics.load(control, 0) !== INPUT_STATE_ANSWER) {
|
||||||
|
return JSON.stringify({ status: 'eof' });
|
||||||
|
}
|
||||||
|
// TextDecoder refuse certaines vues sur SharedArrayBuffer : copie préalable.
|
||||||
|
const bytes = this.#inputData.slice(0, Atomics.load(control, 1));
|
||||||
|
return JSON.stringify({ status: 'ok', text: new TextDecoder().decode(bytes) });
|
||||||
|
}
|
||||||
|
|
||||||
|
async #run({ id, code, collect = [], isolated = false }) {
|
||||||
try {
|
try {
|
||||||
await this.#ready;
|
await this.#ready;
|
||||||
} catch {
|
} catch {
|
||||||
@@ -101,7 +142,7 @@ class PythonWorker {
|
|||||||
this.#interruptView[0] = 0;
|
this.#interruptView[0] = 0;
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
const raw = this.#runner.run_cell(code, JSON.stringify(collect));
|
const raw = this.#runner.run_cell(code, JSON.stringify(collect), isolated);
|
||||||
self.postMessage({ type: 'result', id, ...JSON.parse(raw) });
|
self.postMessage({ type: 'result', id, ...JSON.parse(raw) });
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
// Erreur hors du code de l'apprenant (bug du runner ou de Pyodide).
|
// Erreur hors du code de l'apprenant (bug du runner ou de Pyodide).
|
||||||
|
|||||||
Binary file not shown.
@@ -6,21 +6,53 @@ noms persistant (comme un notebook), puis renvoie un résultat structuré sous f
|
|||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import builtins
|
||||||
import json
|
import json
|
||||||
import linecache
|
import linecache
|
||||||
import math
|
import math
|
||||||
|
import sys
|
||||||
import traceback
|
import traceback
|
||||||
from typing import Any
|
from typing import Any, Callable
|
||||||
|
|
||||||
CELL_FILENAME = "<cell>"
|
CELL_FILENAME = "<cell>"
|
||||||
|
|
||||||
_namespace: dict[str, Any] = {}
|
_namespace: dict[str, Any] = {}
|
||||||
|
# Copie (superficielle) de l'espace de noms avant la dernière exécution normale : point de départ
|
||||||
|
# des exécutions isolées (tests avec saisies scriptées), qui ne doivent rien modifier.
|
||||||
|
_baseline: dict[str, Any] = {}
|
||||||
|
_input_bridge: Callable[[str], str] | None = None
|
||||||
|
|
||||||
|
|
||||||
def reset_namespace() -> None:
|
def reset_namespace() -> None:
|
||||||
"""Repart d'un espace de noms vierge (changement de niveau, bouton « Recommencer »)."""
|
"""Repart d'un espace de noms vierge (changement de niveau, bouton « Recommencer »)."""
|
||||||
_namespace.clear()
|
_namespace.clear()
|
||||||
_namespace["__name__"] = "__main__"
|
_namespace["__name__"] = "__main__"
|
||||||
|
_baseline.clear()
|
||||||
|
_baseline.update(_namespace)
|
||||||
|
|
||||||
|
|
||||||
|
def set_input_bridge(bridge: Callable[[str], str]) -> None:
|
||||||
|
"""Branche input() sur le pont JavaScript.
|
||||||
|
|
||||||
|
Le pont reçoit l'invite et renvoie un JSON `{"status": "ok"|"eof"|"interrupted", "text": str}`.
|
||||||
|
"""
|
||||||
|
global _input_bridge
|
||||||
|
_input_bridge = bridge
|
||||||
|
builtins.input = _input
|
||||||
|
|
||||||
|
|
||||||
|
def _input(prompt: object = "") -> str:
|
||||||
|
"""Remplace input() : bloque côté JavaScript jusqu'à la réponse de l'apprenant."""
|
||||||
|
sys.stdout.write(str(prompt))
|
||||||
|
sys.stdout.flush()
|
||||||
|
if _input_bridge is None:
|
||||||
|
raise EOFError("EOF when reading a line")
|
||||||
|
reply = json.loads(_input_bridge(str(prompt)))
|
||||||
|
if reply["status"] == "interrupted":
|
||||||
|
raise KeyboardInterrupt
|
||||||
|
if reply["status"] == "eof":
|
||||||
|
raise EOFError("EOF when reading a line")
|
||||||
|
return str(reply["text"])
|
||||||
|
|
||||||
|
|
||||||
def _describe(value: Any) -> dict[str, Any]:
|
def _describe(value: Any) -> dict[str, Any]:
|
||||||
@@ -56,12 +88,21 @@ def _error_info(exc: BaseException, code: str) -> dict[str, Any]:
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
def run_cell(code: str, collect_json: str = "[]") -> str:
|
def run_cell(code: str, collect_json: str = "[]", isolated: bool = False) -> str:
|
||||||
"""Exécute `code` et renvoie un JSON : {ok, error, variables}.
|
"""Exécute `code` et renvoie un JSON : {ok, error, variables}.
|
||||||
|
|
||||||
`collect_json` est une liste JSON de noms de variables à relire après l'exécution.
|
`collect_json` est une liste JSON de noms de variables à relire après l'exécution.
|
||||||
|
Si `isolated`, le code s'exécute sur une copie de l'état d'avant la dernière exécution et
|
||||||
|
l'espace de noms de l'apprenant n'est pas modifié (utilisé pour valider avec des saisies
|
||||||
|
scriptées).
|
||||||
"""
|
"""
|
||||||
|
global _baseline
|
||||||
collect: list[str] = json.loads(collect_json)
|
collect: list[str] = json.loads(collect_json)
|
||||||
|
if isolated:
|
||||||
|
namespace = dict(_baseline)
|
||||||
|
else:
|
||||||
|
_baseline = dict(_namespace)
|
||||||
|
namespace = _namespace
|
||||||
error: dict[str, Any] | None = None
|
error: dict[str, Any] | None = None
|
||||||
|
|
||||||
# Permet aux tracebacks d'afficher la ligne de code fautive.
|
# Permet aux tracebacks d'afficher la ligne de code fautive.
|
||||||
@@ -73,12 +114,12 @@ def run_cell(code: str, collect_json: str = "[]") -> str:
|
|||||||
)
|
)
|
||||||
try:
|
try:
|
||||||
compiled = compile(code, CELL_FILENAME, "exec")
|
compiled = compile(code, CELL_FILENAME, "exec")
|
||||||
exec(compiled, _namespace)
|
exec(compiled, namespace)
|
||||||
except BaseException as exc: # noqa: BLE001 - KeyboardInterrupt et SystemExit inclus
|
except BaseException as exc: # noqa: BLE001 - KeyboardInterrupt et SystemExit inclus
|
||||||
error = _error_info(exc, code)
|
error = _error_info(exc, code)
|
||||||
|
|
||||||
variables = {
|
variables = {
|
||||||
name: _describe(_namespace[name]) for name in collect if name in _namespace
|
name: _describe(namespace[name]) for name in collect if name in namespace
|
||||||
}
|
}
|
||||||
return json.dumps({"ok": error is None, "error": error, "variables": variables})
|
return json.dumps({"ok": error is None, "error": error, "variables": variables})
|
||||||
|
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
Schéma complet et à jour : [`levels/schema/level.schema.json`](../../levels/schema/level.schema.json).
|
Schéma complet et à jour : [`levels/schema/level.schema.json`](../../levels/schema/level.schema.json).
|
||||||
|
|
||||||
Exemples complets conformes au schéma : `levels/00-intro`, `levels/01-hello`,
|
Exemples complets conformes au schéma : `levels/00-intro`, `levels/01-hello`,
|
||||||
`levels/02-variables` (validés avec `jsonschema`).
|
`levels/02-variables` (validés avec `jsonschema`) ainsi que `levels/03-input`.
|
||||||
|
|
||||||
## Forme des tests (`tests[]`) utilisée par les niveaux
|
## Forme des tests (`tests[]`) utilisée par les niveaux
|
||||||
|
|
||||||
@@ -19,6 +19,11 @@ Le schéma laisse `additionalProperties: true` ; les champs ci-dessous sont la c
|
|||||||
| `var_equals` | `name`, `value` | variable globale égale à la valeur (`10.0` = float, `10` = int) |
|
| `var_equals` | `name`, `value` | variable globale égale à la valeur (`10.0` = float, `10` = int) |
|
||||||
| `var_type_is` | `name`, `value` (`str`/`int`/`float`…) | type de la variable |
|
| `var_type_is` | `name`, `value` (`str`/`int`/`float`…) | type de la variable |
|
||||||
|
|
||||||
|
**`inputs` (optionnel, tout test)** : liste de saisies scriptées pour `input()`. Le test est évalué
|
||||||
|
sur un rejeu isolé du code (copie de l'état d'avant l'exécution) ; sans `inputs`, sur l'exécution
|
||||||
|
interactive de l'apprenant. Décision de conception du niveau 03 (saisie réelle bloquante via
|
||||||
|
`Atomics.wait` + SharedArrayBuffer ; sans isolation cross-origin, `input()` lève `EOFError`).
|
||||||
|
|
||||||
`stdout_contains_any_name` et `function_called_with` : forme à fixer quand un niveau en aura
|
`stdout_contains_any_name` et `function_called_with` : forme à fixer quand un niveau en aura
|
||||||
besoin. Un niveau sans test de mission (ex. `00-intro`) se valide par un simple bouton dans l'UI.
|
besoin. Un niveau sans test de mission (ex. `00-intro`) se valide par un simple bouton dans l'UI.
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,146 @@
|
|||||||
|
id: 03-input
|
||||||
|
title:
|
||||||
|
fr: Demander à l'utilisateur
|
||||||
|
en: Asking the user
|
||||||
|
difficulty: 1
|
||||||
|
xp: 40
|
||||||
|
requires:
|
||||||
|
- 02-variables
|
||||||
|
steps:
|
||||||
|
- type: explain
|
||||||
|
voice: true
|
||||||
|
text:
|
||||||
|
fr: "`input()` pose une question et attend une réponse. Ce que tu tapes est rangé dans une variable."
|
||||||
|
en: "`input()` asks a question and waits for an answer. What you type is stored in a variable."
|
||||||
|
- type: code
|
||||||
|
starter: |
|
||||||
|
name = input("Ton prénom ? ")
|
||||||
|
print("Bonjour", name)
|
||||||
|
instruction:
|
||||||
|
fr: Exécute le code, tape ton prénom dans le champ qui apparaît, puis valide.
|
||||||
|
en: Run the code, type your first name in the field that appears, then submit.
|
||||||
|
tests:
|
||||||
|
- kind: stdout_contains
|
||||||
|
value: "Bonjour Léa"
|
||||||
|
inputs:
|
||||||
|
- Léa
|
||||||
|
message:
|
||||||
|
fr: Le programme doit afficher « Bonjour » suivi du prénom saisi.
|
||||||
|
en: The program must show "Bonjour" followed by the name entered.
|
||||||
|
solution: |
|
||||||
|
name = input("Ton prénom ? ")
|
||||||
|
print("Bonjour", name)
|
||||||
|
- type: explain
|
||||||
|
voice: true
|
||||||
|
text:
|
||||||
|
fr: "Attention : `input()` renvoie toujours du texte (`str`), même si tu tapes un nombre. Pour calculer, convertis avec `int()` pour un entier."
|
||||||
|
en: "Careful: `input()` always returns text (`str`), even if you type a number. To calculate, convert with `int()` for a whole number."
|
||||||
|
- type: code
|
||||||
|
starter: |
|
||||||
|
text = input("Un nombre entier ? ")
|
||||||
|
number = text
|
||||||
|
print(number * 2)
|
||||||
|
instruction:
|
||||||
|
fr: "Avec 21, ce code affiche 2121 au lieu de 42. Convertis `text` avec `int()` pour que `number` soit un entier."
|
||||||
|
en: "With 21, this code shows 2121 instead of 42. Convert `text` with `int()` so that `number` is a whole number."
|
||||||
|
tests:
|
||||||
|
- kind: var_type_is
|
||||||
|
name: number
|
||||||
|
value: int
|
||||||
|
inputs:
|
||||||
|
- "21"
|
||||||
|
- kind: stdout_contains
|
||||||
|
value: "42"
|
||||||
|
inputs:
|
||||||
|
- "21"
|
||||||
|
message:
|
||||||
|
fr: Avec la saisie 21, le programme doit afficher 42.
|
||||||
|
en: With the input 21, the program must show 42.
|
||||||
|
hints:
|
||||||
|
fr:
|
||||||
|
- "`int()` se place autour de la valeur à convertir."
|
||||||
|
- "Écris `number = int(text)`."
|
||||||
|
en:
|
||||||
|
- "`int()` goes around the value to convert."
|
||||||
|
- "Write `number = int(text)`."
|
||||||
|
solution: |
|
||||||
|
text = input("Un nombre entier ? ")
|
||||||
|
number = int(text)
|
||||||
|
print(number * 2)
|
||||||
|
- type: explain
|
||||||
|
voice: true
|
||||||
|
text:
|
||||||
|
fr: "Pour un nombre à virgule, utilise `float()`. Écris le nombre avec un point : 2.5."
|
||||||
|
en: "For a decimal number, use `float()`. Write the number with a dot: 2.5."
|
||||||
|
- type: code
|
||||||
|
starter: |
|
||||||
|
text = input("Un prix ? ")
|
||||||
|
price = text
|
||||||
|
print(price)
|
||||||
|
instruction:
|
||||||
|
fr: "Convertis `text` avec `float()` dans `price`, puis affiche `price + 0.5`."
|
||||||
|
en: "Convert `text` with `float()` into `price`, then print `price + 0.5`."
|
||||||
|
tests:
|
||||||
|
- kind: var_type_is
|
||||||
|
name: price
|
||||||
|
value: float
|
||||||
|
inputs:
|
||||||
|
- "2.5"
|
||||||
|
- kind: stdout_contains
|
||||||
|
value: "3.0"
|
||||||
|
inputs:
|
||||||
|
- "2.5"
|
||||||
|
message:
|
||||||
|
fr: Avec la saisie 2.5, le programme doit afficher 3.0.
|
||||||
|
en: With the input 2.5, the program must show 3.0.
|
||||||
|
hints:
|
||||||
|
fr:
|
||||||
|
- "Utilise `float(text)` pour obtenir un nombre à virgule."
|
||||||
|
- "Change aussi la dernière ligne : `print(price + 0.5)`."
|
||||||
|
en:
|
||||||
|
- "Use `float(text)` to get a decimal number."
|
||||||
|
- "Also change the last line: `print(price + 0.5)`."
|
||||||
|
solution: |
|
||||||
|
text = input("Un prix ? ")
|
||||||
|
price = float(text)
|
||||||
|
print(price + 0.5)
|
||||||
|
mission:
|
||||||
|
title:
|
||||||
|
fr: Combien de bougies ?
|
||||||
|
en: How many candles?
|
||||||
|
goal:
|
||||||
|
fr: "Demande l'année de naissance avec `input()`, convertis-la en entier, puis calcule `age` (l'année courante est déjà dans `current_year`) et affiche-le."
|
||||||
|
en: "Ask for the birth year with `input()`, convert it to a whole number, then compute `age` (the current year is already in `current_year`) and print it."
|
||||||
|
starter: |
|
||||||
|
current_year = 2025
|
||||||
|
# Demande l'année de naissance, puis calcule age
|
||||||
|
tests:
|
||||||
|
- kind: var_equals
|
||||||
|
name: age
|
||||||
|
value: 15
|
||||||
|
inputs:
|
||||||
|
- "2010"
|
||||||
|
message:
|
||||||
|
fr: "Avec la naissance en 2010, `age` doit valoir 15."
|
||||||
|
en: "With a birth year of 2010, `age` must be 15."
|
||||||
|
- kind: var_equals
|
||||||
|
name: age
|
||||||
|
value: 25
|
||||||
|
inputs:
|
||||||
|
- "2000"
|
||||||
|
message:
|
||||||
|
fr: "Avec la naissance en 2000, `age` doit valoir 25."
|
||||||
|
en: "With a birth year of 2000, `age` must be 25."
|
||||||
|
- kind: var_type_is
|
||||||
|
name: age
|
||||||
|
value: int
|
||||||
|
inputs:
|
||||||
|
- "2010"
|
||||||
|
- kind: stdout_contains
|
||||||
|
value: "15"
|
||||||
|
inputs:
|
||||||
|
- "2010"
|
||||||
|
message:
|
||||||
|
fr: Le programme doit afficher l'âge.
|
||||||
|
en: The program must print the age.
|
||||||
|
reward_sound: success_small
|
||||||
@@ -3,6 +3,7 @@
|
|||||||
"levels": [
|
"levels": [
|
||||||
{ "id": "00-intro", "requires": [] },
|
{ "id": "00-intro", "requires": [] },
|
||||||
{ "id": "01-hello", "requires": ["00-intro"] },
|
{ "id": "01-hello", "requires": ["00-intro"] },
|
||||||
{ "id": "02-variables", "requires": ["01-hello"] }
|
{ "id": "02-variables", "requires": ["01-hello"] },
|
||||||
|
{ "id": "03-input", "requires": ["02-variables"] }
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -127,6 +127,11 @@
|
|||||||
"message": {
|
"message": {
|
||||||
"$ref": "#/$defs/i18nString",
|
"$ref": "#/$defs/i18nString",
|
||||||
"description": "Message affiché si le test échoue, en complément de la traduction d'erreur générique."
|
"description": "Message affiché si le test échoue, en complément de la traduction d'erreur générique."
|
||||||
|
},
|
||||||
|
"inputs": {
|
||||||
|
"type": "array",
|
||||||
|
"items": { "type": "string" },
|
||||||
|
"description": "Saisies scriptées pour input(). Si présent, le test est évalué sur un rejeu du code (état isolé) où chaque input() reçoit la valeur suivante de la liste ; sinon il porte sur l'exécution de l'apprenant."
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"additionalProperties": true
|
"additionalProperties": true
|
||||||
|
|||||||
+68
-2
@@ -40,7 +40,7 @@ test('parcours complet des niveaux 00 et 01', { skip, timeout: 180000 }, async (
|
|||||||
const run = async (code) => {
|
const run = async (code) => {
|
||||||
const cell = page.locator('.cell').last();
|
const cell = page.locator('.cell').last();
|
||||||
await cell.locator('textarea').fill(code);
|
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.waitForFunction(() => document.querySelector('.cell:last-of-type')?.getAttribute('aria-busy') !== 'true');
|
||||||
await page.waitForTimeout(150);
|
await page.waitForTimeout(150);
|
||||||
return (await cell.locator('.cell-feedback').textContent()).trim();
|
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.
|
// Boucle infinie interrompue, puis cellule réutilisable.
|
||||||
const cell = page.locator('.cell').last();
|
const cell = page.locator('.cell').last();
|
||||||
await cell.locator('textarea').fill('while True:\n pass');
|
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 page.waitForTimeout(500);
|
||||||
await cell.locator('.btn', { hasText: 'Arrêter' }).click();
|
await cell.locator('.btn', { hasText: 'Arrêter' }).click();
|
||||||
await page.waitForFunction(() => document.querySelector('.cell:last-of-type')?.getAttribute('aria-busy') !== 'true', null, { timeout: 15000 });
|
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, []);
|
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, []);
|
||||||
|
});
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ const root = new URL('../../', import.meta.url).pathname.replace(/\/$/, '');
|
|||||||
const e = new LessonEngine({ levelsUrl: 'http://x/levels/', fetchFn: async (u) => {
|
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 }; }
|
try { const t = await readFile(root + new URL(u).pathname, 'utf8'); return { ok: true, text: async () => t }; }
|
||||||
catch { return { ok: false, status: 404 }; } } });
|
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');
|
const s = await e.startLevel('02-variables', 'en');
|
||||||
assert.equal(s.title, 'Variables and types'); assert.equal(s.stepCount, 7);
|
assert.equal(s.title, 'Variables and types'); assert.equal(s.stepCount, 7);
|
||||||
assert.equal(s.step.type, 'explain');
|
assert.equal(s.step.type, 'explain');
|
||||||
|
|||||||
@@ -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` },
|
workerData: { workerPath: `${root}app/js/workers/python-worker.js`, runnerPath: `${root}app/python/pyquest_runner.py` },
|
||||||
});
|
});
|
||||||
const interruptBuffer = new SharedArrayBuffer(1);
|
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 waiters = new Map();
|
||||||
const stdout = [];
|
const stdout = [];
|
||||||
worker.on('message', (message) => {
|
worker.on('message', (message) => {
|
||||||
if (message.type === 'stdout') stdout.push(message.text);
|
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';
|
const key = message.type === 'result' ? message.id : 'init';
|
||||||
if (['result', 'ready', 'init_error'].includes(message.type)) waiters.get(key)?.(message);
|
if (['result', 'ready', 'init_error'].includes(message.type)) waiters.get(key)?.(message);
|
||||||
});
|
});
|
||||||
const wait = (key) =>
|
worker.on('error', (error) => {
|
||||||
new Promise((resolve, reject) => {
|
throw error;
|
||||||
waiters.set(key, resolve);
|
});
|
||||||
worker.once('error', reject);
|
const wait = (key) => new Promise((resolve) => waiters.set(key, resolve));
|
||||||
});
|
const run = (id, code, collect = [], isolated = false) => {
|
||||||
const run = (id, code, collect = []) => {
|
|
||||||
const done = wait(id);
|
const done = wait(id);
|
||||||
worker.postMessage({ type: 'run_code', id, code, collect });
|
worker.postMessage({ type: 'run_code', id, code, collect, isolated });
|
||||||
return done;
|
return done;
|
||||||
};
|
};
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const init = wait('init');
|
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 });
|
assert.deepEqual(await init, { type: 'ready', interruptible: true });
|
||||||
|
|
||||||
let result = await run(1, 'x = 10.0\nprint("hé")\nprint(x)', ['x']);
|
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
|
result = await run(3, 'y = x + 1', ['y']); // l'espace de noms persiste
|
||||||
assert.equal(result.variables.y.value, 11);
|
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');
|
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');
|
const looping = run(5, 'while True:\n pass');
|
||||||
setTimeout(() => (new Uint8Array(interruptBuffer)[0] = 2), 500);
|
setTimeout(() => (new Uint8Array(interruptBuffer)[0] = 2), 500);
|
||||||
assert.equal((await looping).error.type, 'KeyboardInterrupt');
|
assert.equal((await looping).error.type, 'KeyboardInterrupt');
|
||||||
|
|||||||
@@ -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.
@@ -2,6 +2,7 @@
|
|||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import builtins
|
||||||
import json
|
import json
|
||||||
import sys
|
import sys
|
||||||
import unittest
|
import unittest
|
||||||
@@ -41,6 +42,24 @@ class RunnerTest(unittest.TestCase):
|
|||||||
error = run("def f(:\n pass")["error"]
|
error = run("def f(:\n pass")["error"]
|
||||||
self.assertEqual((error["type"], error["lineno"]), ("SyntaxError", 1))
|
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:
|
def test_non_finite_float_has_no_json_value(self) -> None:
|
||||||
self.assertIsNone(run("x = float('inf')", ["x"])["variables"]["x"]["value"])
|
self.assertIsNone(run("x = float('inf')", ["x"])["variables"]["x"]["value"])
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user