From 5a41231861447e30340dedbce1f7992c00177356 Mon Sep 17 00:00:00 2001 From: denis Date: Wed, 14 Oct 2026 22:43:39 +0200 Subject: [PATCH] Add real input() support via SharedArrayBuffer and level 03 Co-Authored-By: Claude Sonnet 5.5 --- CONTEXT.md | 5 +- CONTRIBUTING.md | 6 + app/js/core/PyodideWorkerClient.js | 51 +++++- app/js/i18n/en.json | 2 + app/js/i18n/fr.json | 2 + app/js/ui/CellManager.js | 62 +++++++- app/js/ui/CellView.js | 51 +++++- app/js/workers/python-worker.js | 51 +++++- .../pyquest_runner.cpython-313.pyc | Bin 3898 -> 5744 bytes app/python/pyquest_runner.py | 49 +++++- docs/design/04-level-format.md | 7 +- levels/03-input/level.yaml | 146 ++++++++++++++++++ levels/manifest.json | 3 +- levels/schema/level.schema.json | 5 + tests/e2e/e2e.test.mjs | 70 ++++++++- tests/js/lesson-engine.test.mjs | 2 +- tests/js/pyodide-worker.integration.test.mjs | 55 +++++-- tests/js/worker-client-input.test.mjs | 44 ++++++ .../__pycache__/test_runner.cpython-313.pyc | Bin 3882 -> 6085 bytes tests/python/test_runner.py | 19 +++ 20 files changed, 595 insertions(+), 35 deletions(-) create mode 100644 levels/03-input/level.yaml create mode 100644 tests/js/worker-client-input.test.mjs diff --git a/CONTEXT.md b/CONTEXT.md index b79623a..9439bcc 100644 --- a/CONTEXT.md +++ b/CONTEXT.md @@ -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`) : le backend (`backend/sync`) existe, pas encore le côté client ni l'UI. 4. Documentation MkDocs bilingue (`docs/mkdocs/`). -5. Niveaux 03 à 14 (voir `docs/design/05-curriculum.md`). `input()` doit d'abord être tranché : - actuellement `EOFError` (pas de saisie synchrone dans le worker). +5. Niveaux 04 à 14 (voir `docs/design/05-curriculum.md`). Niveau 03 fait ; `input()` est réel + (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 (`compilemessages`, gettext absent sur le poste actuel). 7. Kinds de test non encore définis : `stdout_contains_any_name`, `function_called_with`. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 94825ca..ce74d23 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -39,6 +39,12 @@ Français d'abord, English below. | `var_equals` | `name`, `value` | variable égale à la valeur | | `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 affichés à l'apprenant : toute nouvelle sorte de validation passe par le moteur (`app/js/core/ValidationEngine.js`), pas par un fichier de niveau. diff --git a/app/js/core/PyodideWorkerClient.js b/app/js/core/PyodideWorkerClient.js index 66980dd..429f415 100644 --- a/app/js/core/PyodideWorkerClient.js +++ b/app/js/core/PyodideWorkerClient.js @@ -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} [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); diff --git a/app/js/i18n/en.json b/app/js/i18n/en.json index c5f858c..af0c918 100644 --- a/app/js/i18n/en.json +++ b/app/js/i18n/en.json @@ -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:", diff --git a/app/js/i18n/fr.json b/app/js/i18n/fr.json index 95d46c4..fe38518 100644 --- a/app/js/i18n/fr.json +++ b/app/js/i18n/fr.json @@ -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 :", diff --git a/app/js/ui/CellManager.js b/app/js/ui/CellManager.js index 123f13e..22d1201 100644 --- a/app/js/ui/CellManager.js +++ b/app/js/ui/CellManager.js @@ -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); diff --git a/app/js/ui/CellView.js b/app/js/ui/CellView.js index 0805c04..c0a6339 100644 --- a/app/js/ui/CellView.js +++ b/app/js/ui/CellView.js @@ -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} + */ + 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; diff --git a/app/js/workers/python-worker.js b/app/js/workers/python-worker.js index a0718ba..850df98 100644 --- a/app/js/workers/python-worker.js +++ b/app/js/workers/python-worker.js @@ -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). diff --git a/app/python/__pycache__/pyquest_runner.cpython-313.pyc b/app/python/__pycache__/pyquest_runner.cpython-313.pyc index 0944cbc45030a7fa49c140a02929ab88d52e820d..e4aad3cf3a75fde958fd753e8239b3f933978e5d 100644 GIT binary patch delta 3147 zcmZ`*Z%iD=6`%cccYAl-alpZ0z_471;aqUQvaOmpNo|Bnz=oDBF7?_vmb<}Ty6he^ zyTrJ04@<2=qDrl`X+)|>jnq~(ANrw6KBelH+?Rd}?m2C=K}n=WZ9kHl`b%4>Z+1CA zPWz;tee>R%nYVA=@4bDmbEiM~D3OREpkMv%gT=q6?j>8fKi%scE(;S85>Yrsn2?AB zZ*d|z9wV{wIEl+h36Z)%L=sB)T2hJh!s6^p0PaMNGIt7veedWhh~T6to7aO%UNtK zz^I!xCd4V(xR~vivo^kEg9QZl&fJOEWKJYe@WBfQ0rsSMM>lNUq+ZDPC&zhVKj@gU zua!vyvrbWLAHESxT023Wg@>}ptf8Gc)ZD&ydAqs&2V*~+Bq{ftaD*$m8_}ou=@7f3 z4t5hh&Fo*&!DYP_?J7?*$DW{ryi$EAFm)l0kea9&DqL+B%&Ezmbeehf1Z9y5D+5x$ z>`nPgZkgN+r|=yy!fF+@dRv@7d(+AOD^UKbd@r@qUG3L=p_Ov2Qr&@ zp#{UCH-ik4;DAv=EaHia)H1!0VQEF`HB8{uc}pY37i)Q#aVs@9!c8~rF!w?2EfyfILX^lm4+wxq6_e9Ohiapr6t8@}RxDjqvex`Fouh@>aZTb7aI z3A6O#MNEAV>u@)Rz830Vpqa7egyt>Yd+*PV(GwcPBF3I^eHYR!v*G<%gGi z6(r=WdqK*@56uj|Jl)9ZM|mIHy|Anksm-<3Gw1;KigLcLy*F+yZ(|=t2t|6MIr!v)as$&`puu|E? zH0SQdpDCwE55$8!4TC2Z^@8oU?x2?o1~$DIEg8Da${8guFsmrz3mUXlX!iaqQh->4! z&)VL;R6Wu;wD$E+BK6zp*0+whQ?Eup2d1r>?pcp+r#si9ZYVK+{GrtSMGT#J?vcPZ zguT<}?tkkK(Fb4qW>xB27k{L0MBl8hCj0&<_5JqS?)MWD$7xn{26eeY{_e<#^J%5{5uV2hbhmW>*+@k`2Be z{y7=b$&E3w3gVaKVC&c syWtSmy_BLDyZ delta 1412 zcmYjR&u<$=6n?Y6yjgo~CvLIh6x(U5Gz$bmNLo@zkP}r@X&WI{Muja}x$AZ0XtNv5 z+9>HIIre~%s;M|2Br4HE4{$(Lg~SQy6$#paKwBXy@dwb7zyT!0n_Y+Sr1|E}``*mF zeecaadghBtc30OmK$-vL+tnYnYuOTc@7jseZ%XGm(phH1bUho zQ!T@)L^Gyt4#b*nW=$>DvS!ZAn`y4E5}Lb|ISMoUc$6Bfh{hlj$lnTy#Ja!9bm4f> zNyr36oN$ocdA23I!b&351*)Jik{!=&Qg%~pYFS(#!V#8OPAbXwr83R1ZF%_i=jsL- z8bZd*0zVYcQmav&69aa_ zTz2UQuFLF}_72J1uBN91l4q~$r%Q!+zq#pmn;T~+4JfUmh1S?j-AEtYUt~Y&6BC?@ zho1C`2wffus^R<6%O11y!1d|^wn2LH237SB^G zGyQ04&=3mnh7t;s5TbT=6d-6H_`QVQE%d#Bm1-!~aDO`-cr+9q_kO^(aN!t08XLq< z`HBVXlT4-45KVF(E}k;wXT^QT<1h*qFMTX2XdVXeWvjSvx%k?Ch`v|_%#U1`mz`v8 zlQztuwM{~yhGF|k8w{m)9oRql_t{%R6QkKkS`7m~lD(kW3M0{T{YVSfy-wHb_-;tY z*qx#3)+An*w4}b!4BayujvF^mT)DVaBDvLDTMrGDK83zf#tA&nb-H$Zc&fjmQ=C(s zU~RqQxh-n&rQ~CK&=*h*dDVD}a7o%kr9Izvj=7#k>qzn>huXL-YjA3QR}==7=;Yk3);HyQb#q5Gu1fEAKGbeZ-z$ypWR3f( z@!1M19y+&`8(o-%ucr0I5$S8W$Z=L%EQxo;^kPB0TaZyVgh-)ow@3X*S`K{Ikm7el zC5(hFaNw0Sl=y=v4>HaIrPp$~o+vvqJlyGwZTYWV?hHo(PQOdSkfn(c|X4~x^ z-s{>n#a94yn!}46unX|nAw)`dbG_rQB+-m=bt4 z(-0!^SJ%(?%WFZa=ehIrEZPW;a0%g&NC^2|kcjk02FS5rA^iaI4`Tcoo_LrqZR-!8 ntZr*pmv^ALr-)>HFOw$4y(4*|{5e)44f6OTko*rY7~l0TCC(+% diff --git a/app/python/pyquest_runner.py b/app/python/pyquest_runner.py index 9885a4d..8873bf5 100644 --- a/app/python/pyquest_runner.py +++ b/app/python/pyquest_runner.py @@ -6,21 +6,53 @@ noms persistant (comme un notebook), puis renvoie un résultat structuré sous f from __future__ import annotations +import builtins import json import linecache import math +import sys import traceback -from typing import Any +from typing import Any, Callable CELL_FILENAME = "" _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: """Repart d'un espace de noms vierge (changement de niveau, bouton « Recommencer »).""" _namespace.clear() _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]: @@ -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}. `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) + if isolated: + namespace = dict(_baseline) + else: + _baseline = dict(_namespace) + namespace = _namespace error: dict[str, Any] | None = None # Permet aux tracebacks d'afficher la ligne de code fautive. @@ -73,12 +114,12 @@ def run_cell(code: str, collect_json: str = "[]") -> str: ) try: compiled = compile(code, CELL_FILENAME, "exec") - exec(compiled, _namespace) + exec(compiled, namespace) except BaseException as exc: # noqa: BLE001 - KeyboardInterrupt et SystemExit inclus error = _error_info(exc, code) 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}) diff --git a/docs/design/04-level-format.md b/docs/design/04-level-format.md index 04e9a0a..b75d69f 100644 --- a/docs/design/04-level-format.md +++ b/docs/design/04-level-format.md @@ -3,7 +3,7 @@ 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`, -`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 @@ -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_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 besoin. Un niveau sans test de mission (ex. `00-intro`) se valide par un simple bouton dans l'UI. diff --git a/levels/03-input/level.yaml b/levels/03-input/level.yaml new file mode 100644 index 0000000..93c48af --- /dev/null +++ b/levels/03-input/level.yaml @@ -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 diff --git a/levels/manifest.json b/levels/manifest.json index 3e3eb4f..71e9752 100644 --- a/levels/manifest.json +++ b/levels/manifest.json @@ -3,6 +3,7 @@ "levels": [ { "id": "00-intro", "requires": [] }, { "id": "01-hello", "requires": ["00-intro"] }, - { "id": "02-variables", "requires": ["01-hello"] } + { "id": "02-variables", "requires": ["01-hello"] }, + { "id": "03-input", "requires": ["02-variables"] } ] } diff --git a/levels/schema/level.schema.json b/levels/schema/level.schema.json index 9e2ed3e..aaad8ca 100644 --- a/levels/schema/level.schema.json +++ b/levels/schema/level.schema.json @@ -127,6 +127,11 @@ "message": { "$ref": "#/$defs/i18nString", "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 diff --git a/tests/e2e/e2e.test.mjs b/tests/e2e/e2e.test.mjs index 1d34850..05bcada 100644 --- a/tests/e2e/e2e.test.mjs +++ b/tests/e2e/e2e.test.mjs @@ -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, []); +}); diff --git a/tests/js/lesson-engine.test.mjs b/tests/js/lesson-engine.test.mjs index ed5a361..4426ea4 100644 --- a/tests/js/lesson-engine.test.mjs +++ b/tests/js/lesson-engine.test.mjs @@ -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'); diff --git a/tests/js/pyodide-worker.integration.test.mjs b/tests/js/pyodide-worker.integration.test.mjs index 4677b80..a34d536 100644 --- a/tests/js/pyodide-worker.integration.test.mjs +++ b/tests/js/pyodide-worker.integration.test.mjs @@ -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'); diff --git a/tests/js/worker-client-input.test.mjs b/tests/js/worker-client-input.test.mjs new file mode 100644 index 0000000..f8b0a62 --- /dev/null +++ b/tests/js/worker-client-input.test.mjs @@ -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'); diff --git a/tests/python/__pycache__/test_runner.cpython-313.pyc b/tests/python/__pycache__/test_runner.cpython-313.pyc index d12b3749c2618bf6dcc6a88e0885b42bcc4aba13..0678a50b7acae62d7ec425f4e1dedadcef6e14db 100644 GIT binary patch delta 2400 zcmb_eUrbY17(b`Iy}fO3i&$Z;*jhlr%0wNoDZ?tFDAe$$7ZjoHrnCi1$}Ktf)(BZr z-{u1*!yBWSCgTy8J&>_%WLYwkWf}2hbkyMPd~jKoOrK0NaofxGom&d1Ebd_^;dg%b ze1Fb&&i9?KeB%9Xuj8rRZbdK>zyC0D(>mpF;f|^5edmlpmaqaAn4r0xBb*NbHw7*2 zR$}#`uqjkZZC)H9_lw{3OTb}!1qyTU=V-urd1(98r)AhTweW7Rm~0m8fnJ&cRhqsCL27${yt zVMMTih(W-_DDZ-T?n4-0MxB{}F*;*`nRI3b#_Eg%X4aVn7^gEUFg;pg6Rd6vuZ7~e6YQ*4m2!?eME0y#M#=W?3sRC2Dn!<{Ndr`<< zaJDx0LLyD@DHwHRbu>4uZ0keRN}Xgq8BX`Vvc7?hWzA+7`K=ujCdqfmw||1A)4_up zmU>7zY(#bfJcpn2=%(@TF4`AO|KQ5LRx-VKps+7Wu5<>3hEX}%P*RD8&>`b?G=%+*4*I}W2aOR* z2|uk@d1hw@`jkO1)*1>&*@65_2l0WDhTriUG*(t3N?O(!C4N!4ZO9iOt+?A*W5-Bp zbWD+{`;{8wnv#*x!B`}qwY*Y6(pXv%(=t@tAW6iA<6=aLWkeDmOA$pDgymyMq_E^Jvm)1M6tWM&=3C>kZWiFsZPeL-@(4s)&MtP>>zERpcx@35(Gw00jxVG>7a|900*dm zKCeQA^A{IN76YBRx~_bH=6rB|QcF!L0W|J-XX|l7QY0T+F|5(C7TjuPHjK)akd!zf z=`ncVuZgY^+`b&0XEAUlSJ$UUrxgd|Sx@U7 zIqL~7oXC257Ehne@%;tE3|MyM`0jO<)9#z^&46b8?CGqhX?`Tfw-vNOxi80`{a5A1 zKzEK0J@o9HJb9(#j~jh-`b(yb{OZv?EjIM6&EDcNuCLX(ahn0-!|MBdJGQIe^PR_z z(c7k7fQSHEi73*ynTU!JMInj7G~BW%k_c6xPeX6|g#P291O26y_o`j?a{DumF$M86 z-fF6P?owrYbLk)mCmgXvR2h&J@}{p@8b9ZEsdw#V_>B6Cy%~?Fm5#O}F;LT((MUpi zX&a4e8coI0$#{T_gAQ#7@+80$BgXhA)c+f*_!SlXtloBnN@{Q~{?N5tT#+rVc!ucL LlQ33`ipu^0CX6b4 delta 546 zcmZXRJxCl;5XWck_WSNOcd}o)csbXQsGKAgLI_wKX9U-SgnbDF-4qffc#tdJorNKA ztz|A_+BE5eRNL8GONt<|NFyn<5)?FD-foiO$iN$Z^PfM%y!Q_8?^n&sQpo@j#nYqq z7iD02xHP!;pf9Z`p~}@7Fl6$I7V2EDK`cd9>K%^A9j?=gVO$I#R>djJdxIadx68c3O3Y;X7__A}@(~XLV8$4*LM%sjX$Jj@72B-%=mo&~2!K%QG?%le ztQtuVzaf?>%(ph4irF6_296APjv>!8gXPkxToRPeNERezqzIBTQUxg)X@b;@bf$6R zwLV=qF{15GXOlnM?DozqGNnDVlh0Bg(Mu+kYsB%y*Uk|q6UBIpI7O{ONPR{BVBKJy zepw+FXwiOx4fA{F2#;d@0CO69hd1e#>y54nA^nH$u1FVoMEnk`KOs1!rW;wK W_#EGR$Ccn~CAfmLx_C(YuKyb+ylFuI diff --git a/tests/python/test_runner.py b/tests/python/test_runner.py index 88353ae..1179ebc 100644 --- a/tests/python/test_runner.py +++ b/tests/python/test_runner.py @@ -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"])