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:
@@ -2,6 +2,11 @@
|
||||
// Protocole des messages : voir app/js/workers/python-worker.js.
|
||||
|
||||
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().
|
||||
const INTERRUPT_GRACE_MS = 2000;
|
||||
|
||||
@@ -10,6 +15,8 @@ export class PyodideWorkerClient {
|
||||
#indexURL;
|
||||
#worker = null;
|
||||
#interruptView = null;
|
||||
#inputControl = null;
|
||||
#inputData = null;
|
||||
#interruptible = false;
|
||||
#ready = null;
|
||||
#readyHandlers = null;
|
||||
@@ -47,14 +54,17 @@ export class PyodideWorkerClient {
|
||||
* @param {string[]} [options.collect] Variables à relire après l'exécution.
|
||||
* @param {(text: string) => void} [options.onStdout]
|
||||
* @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}>}
|
||||
*/
|
||||
async run(code, { collect = [], onStdout = () => {}, onStderr = () => {} } = {}) {
|
||||
async run(code, { collect = [], onStdout = () => {}, onStderr = () => {}, onInput = null, isolated = false } = {}) {
|
||||
await this.start();
|
||||
const id = this.#nextId++;
|
||||
return new Promise((resolve) => {
|
||||
this.#pending.set(id, { resolve, onStdout, onStderr });
|
||||
this.#worker.postMessage({ type: 'run_code', id, code, collect });
|
||||
this.#pending.set(id, { resolve, onStdout, onStderr, onInput });
|
||||
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 buffer = canShare ? new SharedArrayBuffer(1) : 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.addEventListener('message', (event) => this.#onMessage(event.data));
|
||||
@@ -100,7 +113,7 @@ export class PyodideWorkerClient {
|
||||
|
||||
return new Promise((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':
|
||||
this.#pending.get(message.id)?.onStderr(message.text);
|
||||
break;
|
||||
case 'input_request':
|
||||
this.#answerInput(message);
|
||||
break;
|
||||
case 'result': {
|
||||
const entry = this.#pending.get(message.id);
|
||||
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. */
|
||||
#hardRestart() {
|
||||
clearTimeout(this.#graceTimer);
|
||||
|
||||
@@ -16,6 +16,8 @@
|
||||
"cell.solution": "Show the solution",
|
||||
"cell.output": "Output",
|
||||
"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.passed": "Well done, that's correct!",
|
||||
"cell.failed": "Not yet. Here is what is wrong:",
|
||||
|
||||
@@ -16,6 +16,8 @@
|
||||
"cell.solution": "Voir la solution",
|
||||
"cell.output": "Résultat",
|
||||
"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.passed": "Bravo, c'est correct !",
|
||||
"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);
|
||||
notebook.add(cell.element);
|
||||
cell.focus();
|
||||
cell.addEventListener('stop', () => this.#deps.client.interrupt());
|
||||
cell.addEventListener('stop', () => this.#stop(cell));
|
||||
let continueShown = false;
|
||||
cell.addEventListener('run', async (event) => {
|
||||
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 });
|
||||
notebook.add(cell.element);
|
||||
cell.focus();
|
||||
cell.addEventListener('stop', () => this.#deps.client.interrupt());
|
||||
cell.addEventListener('stop', () => this.#stop(cell));
|
||||
cell.addEventListener('run', async (event) => {
|
||||
if (await this.#execute(cell, event.detail.code, mission.tests)) {
|
||||
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) {
|
||||
const { client, validator, translator, audio, i18n } = this.#deps;
|
||||
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),
|
||||
onStdout: onOutput,
|
||||
onStderr: onOutput,
|
||||
onInput: (prompt) => cell.requestInput(prompt),
|
||||
});
|
||||
cell.setBusy(false);
|
||||
|
||||
if (result.error) {
|
||||
cell.setBusy(false);
|
||||
cell.showError(translator.translate(result.error, i18n.lang));
|
||||
audio.play('error');
|
||||
return false;
|
||||
}
|
||||
const validation = validator.validate(tests, { stdout, result });
|
||||
const validation = await this.#validate(code, tests, { stdout, result });
|
||||
cell.setBusy(false);
|
||||
cell.showValidation(validation);
|
||||
audio.play(validation.passed ? 'success_small' : 'error');
|
||||
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) {
|
||||
const { progress, toast, audio, i18n, notebook } = this.#deps;
|
||||
const outcome = await progress.completeLevel(this.#session.id, this.#session.xp);
|
||||
|
||||
+50
-1
@@ -14,6 +14,9 @@ export class CellView extends EventTarget {
|
||||
#runButton;
|
||||
#stopButton;
|
||||
#busy = false;
|
||||
#inputForm;
|
||||
#inputField;
|
||||
#resolveInput = null;
|
||||
|
||||
/**
|
||||
* @param {import('../i18n/i18n.js').I18n} i18n
|
||||
@@ -44,7 +47,7 @@ export class CellView extends EventTarget {
|
||||
});
|
||||
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', {
|
||||
type: 'button',
|
||||
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.#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
|
||||
? el('details', { class: 'solution' }, el('summary', { text: i18n.t('cell.solution') }), el('pre', {}, el('code', { text: solution })))
|
||||
: null;
|
||||
@@ -69,6 +83,7 @@ export class CellView extends EventTarget {
|
||||
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),
|
||||
this.#output,
|
||||
this.#inputForm,
|
||||
this.#feedback,
|
||||
solutionBlock,
|
||||
);
|
||||
@@ -103,6 +118,40 @@ export class CellView extends EventTarget {
|
||||
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. */
|
||||
reset() {
|
||||
this.#editor.value = this.#starter;
|
||||
|
||||
@@ -1,26 +1,35 @@
|
||||
// Worker du moteur Python : charge Pyodide (vendorisé) et exécute le code des cellules.
|
||||
//
|
||||
// Protocole (messages entrants) :
|
||||
// { type: 'init', indexURL, interruptBuffer? } charge Pyodide ; répond 'ready' ou 'init_error'
|
||||
// { type: 'run_code', id, code, collect? } exécute une cellule ; répond 'result'
|
||||
// { type: 'init', indexURL, interruptBuffer?, inputBuffer? } charge Pyodide ; répond 'ready' ou 'init_error'
|
||||
// { type: 'run_code', id, code, collect?, isolated? } exécute une cellule ; répond 'result'
|
||||
// { type: 'reset' } vide l'espace de noms Python
|
||||
//
|
||||
// Messages sortants :
|
||||
// { type: 'ready', interruptible }
|
||||
// { type: 'init_error', message }
|
||||
// { 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 }
|
||||
//
|
||||
// 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
|
||||
// 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 INPUT_WAIT_SLICE_MS = 50;
|
||||
const INPUT_HEADER_BYTES = 8;
|
||||
const INPUT_STATE_ANSWER = 1;
|
||||
|
||||
class PythonWorker {
|
||||
#pyodide = null;
|
||||
#runner = null;
|
||||
#interruptView = null;
|
||||
#inputControl = null;
|
||||
#inputData = null;
|
||||
#currentId = null;
|
||||
#ready = null;
|
||||
|
||||
@@ -42,7 +51,7 @@ class PythonWorker {
|
||||
}
|
||||
}
|
||||
|
||||
async #init({ indexURL, interruptBuffer }) {
|
||||
async #init({ indexURL, interruptBuffer, inputBuffer }) {
|
||||
try {
|
||||
// Import dynamique : le worker est de type module, Pyodide est servi en local (COEP).
|
||||
const { loadPyodide } = await import(`${indexURL}pyodide.mjs`);
|
||||
@@ -61,6 +70,13 @@ class PythonWorker {
|
||||
this.#pyodide.runPython("import sys; sys.path.insert(0, '/pyquest')");
|
||||
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 :
|
||||
// le client doit alors se rabattre sur worker.terminate().
|
||||
let interruptible = false;
|
||||
@@ -88,7 +104,32 @@ class PythonWorker {
|
||||
|
||||
#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 {
|
||||
await this.#ready;
|
||||
} catch {
|
||||
@@ -101,7 +142,7 @@ class PythonWorker {
|
||||
this.#interruptView[0] = 0;
|
||||
}
|
||||
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) });
|
||||
} catch (error) {
|
||||
// Erreur hors du code de l'apprenant (bug du runner ou de Pyodide).
|
||||
|
||||
Reference in New Issue
Block a user