Skip to content

Widget: show a run's code in place, with Copy and Download - #503

Merged
neuromechanist merged 5 commits into
developfrom
feature/issue-491-run-code
Sep 25, 2026
Merged

neuromechanist merged 5 commits into
developfrom
feature/issue-491-run-code

Conversation

@neuromechanist

Copy link
Copy Markdown
Member

Closes #491

Each run's code is now its own disclosure, shown in place in the run's entry, with Copy and Download; the permission gate gets the same Copy.

What the reader sees

Each run is two disclosures, one under the other, joined by a rule down their left:

  • The run (Ran Python: Plot a 10 Hz sine ...): its output, its figures and "Edit and run". It opens by default exactly when it did before: a figure, a reader's own run, or an open editor.
  • Its code (Code · 8 lines), closed until the reader opens it, so it opens without the output, and a figure is not pushed down by the script that drew it. Whether it is open is kept on the run record (_codeOpen, via the toggle event), so a streamed chunk or runtime progress re-rendering the reply does not close it; it is stripped in saveHistory like the other transient fields, so a reload shows it closed.

Opening the code shows a bar over it with two icon buttons, type="button", aria-labeled, with a role="status" line beside them:

  • Copy copies the run record's exact code (never the highlighted page text) and shows "Copied" and a check for two seconds. Where the Clipboard API is missing (an insecure page) or refuses (a frame without clipboard-write), it tries document.execCommand('copy') on an off-screen textarea, handing focus back afterward; where that fails too, it opens the code, selects it, and says "This page cannot copy for you: the code is selected, so press Ctrl+C" (Cmd+C on Apple platforms). Never a browser dialog. copyToClipboard, which the chat's markdown code blocks and message copy use, is untouched, so no other community's behavior changes.
  • Download saves the exact code as a text/x-python Blob through saveFile (the workspace export's link-and-revoke steps, now shared by both), named <dataset>-run-<n>.py: the dataset recorded on the question the reply answers (setDataset when the reader sent it, Dataset pages: suggested questions about the dataset on screen #477), or the community id when there was none; n is the run's place among the conversation's runs, from 1. Only [A-Za-z0-9._-] survive in the name, and a leading dot is dropped.

The gate's code has the same bar with Copy only (nothing has run yet), and copying decides nothing.

Everything the model wrote is escaped as before: the code goes through highlightOrEscape, and the file name and line count are ours.

Done when

  • Tests for the block, its escaping, Copy (exact text) and Download (exact text, filename): frontend/test-widget-tools.js, 73 new checks (385 in all). The block's structure and label, closed by default, the output not inside it; hostile code (the suite's HOSTILE set) leaving no foreign markup and reading back exactly, escaped and highlighted; Copy through happy-dom's own Clipboard, read back with readText, from highlighted code, and "Copied" clearing; Copy when the browser refuses (happy-dom's clipboard-write permission set to denied, which makes its real writeText reject): the code opened and selected in full, the keys named, no alert/confirm/prompt; Copy with no navigator.clipboard, through the copy command (happy-dom has none, so a recorder stands in and records what is selected when it runs): the exact code, the textarea removed, focus back; a refusing command falling through to the selection; Download's Blob text, type and file name for a dataset question and a no-dataset question, via URL.createObjectURL and the clicked link, both recorded on the way through; the gate's Copy; the open state across a re-render and not stored; a reply with no runs rendering none of it, the chat's own code-block Copy unchanged. frontend/test-widget-color-scheme.js adds the dark Copied color (128).
  • Send to notebook: not built. Reasons below.
  • docs/community-widget.md gains "A run in the chat"; docs/community-browser-runtime.md links to it from "The editable re-run panel"; CHANGELOG entry under [Unreleased].

Checked in Chrome

A one-off script against widget_e2e.py (the scripted model's "plot", real Pyodide from the CDN) in headless Chrome 153, with clipboard permission granted and downloads allowed: the gate's Copy put the gate's code on the clipboard; after Run, the run's code block held the code that ran; clicking Code opened it; the run's Copy put its exact code on the clipboard; Download saved nm000132-run-1.py whose bytes equal the code; and the block was still open after the reply finished rendering. Not committed: it needs the network for Pyodide, which is why the committed tests are the happy-dom ones.

Mutation checks

Each applied alone to frontend/osa-chat-widget.js, the suite run, then restored, with the restore confirmed by comparing git diff --stat before and after. All 22 caught, each by the assertion that names it:

Mutation Caught by
code back inside the run's disclosure "each entry is the run's own disclosure, then its code's"
code interpolated unescaped "no foreign element, handler or source survives parsing"
code open by default "the code is closed until the reader opens it"
Copy reads the page's HTML "the clipboard holds the run's code exactly, not the highlighted page text"
no copy-command fallback "the copy command ran once, on the run's exact code"
a refused writeText not caught "the bar says what to press", "the code is opened"
fallback does not select / does not open "selected in full" / "the code is opened"
focus not restored / textarea left in the page "focus is back on Copy" / "the textarea it used is gone"
"Copied" never clears ""Copied" goes after a moment"
download escaped / as text/plain "holding the run's exact code" / "as Python"
run number per reply, not per conversation the file-name check
dataset from the page now, not the question "Download says the file it saves"
a leading dot kept "a leading dot, which would hide the file, is dropped"
link not removed "the link is removed afterward"
open state not kept / stored "the run records that its code is open" / "whether it was open is not stored"
gate Copy also decides "copying neither runs nor denies it"
gate without Copy "the gate has Copy, and no Download"
dark Copied color color-scheme: "dark .osa-code-action.copied color"

Not built: Send to notebook (stretch)

Not clean, for three reasons, so none of it is here:

  1. The bridge side cannot be tested here without a mock. notebook/osa-bridge.js inserting a cell drives JupyterLite's notebook model through window.jupyterapp. Its only real test is notebook/e2e-check.js, which builds the whole site, serves it, and reads live Zarr data, so it needs the network and is not in CI. A Bun test would need a stand-in JupyterLite app, a mock of exactly the API the code would be written against.
  2. The code does not run there as written. A run's code is written for the sealed chat runtime: osa.fetch, osa.save_script and osa.save_artifact exist only there, and eegprep-lean's transport is set by the runtime's prelude. The notebook has no osa module and sets up eegprep-lean in its own setup cell, so a copied cell that calls osa. fails. A clean version needs a decision on translating or flagging those calls.
  3. It is a new trust edge that belongs in an ADR. Today the bridge accepts only a theme message from its parent. Accepting code means any page the notebook site's frame-ancestors allows could write cells into a reader's stored notebook. That is plausibly fine, but it is a decision for docs/adr/0012 (or its successor) to make, not a stretch goal. There is also plumbing to settle: the frame exists only on a capsule page, only for the dataset on screen, after the notebook reports ready, and the pop-out has a frame of its own.

Copy and Download cover the same need for now: the reader can paste the code into the notebook, or upload the .py.

Other suites

Based on current develop (with #499). Every Bun suite tests.yml runs passes (widget suites: tools 385, capsule 133, color scheme 128, notebook tab 168, first paint 82, dataset questions 60, pop-out 132; the runtime bundle is current); uv run ruff check . is clean; uv run pytest --ignore=tests/test_integration -m "not network" passes, 2922 tests. Locally I deselected tests/test_knowledge/test_papers_sync.py::TestPapersSync, whose two tests call the live OpenAlex API without a network mark and hung on this machine's connection twice (unrelated to this change; CI runs them).

@github-actions

github-actions Bot commented Sep 24, 2026 •

Copy link
Copy Markdown
Contributor

Preview Deployment

Name Link
Preview URL https://feature-issue-491-run-code-demo.osc.earth
Branch feature/issue-491-run-code
Commit 0327a6c

This preview will be updated automatically when you push new commits.

Each run's code is now its own disclosure (Code, N lines) beside the
run's output and figures, closed until opened and kept open across
re-renders. Its bar copies the exact code (Clipboard API, then the
copy command, then selecting the code for the reader; never a
dialog) and downloads it as <dataset>-run-<n>.py built as a Blob.
The permission gate gets the same Copy. The workspace export now
shares the download helper.

Tested: bun frontend/test-widget-tools.js (385 passed, 73 new),
test-widget-color-scheme.js (128); 22 mutations each caught and
restored; Copy and Download checked by hand in headless Chrome.
A download's blob: address still serves the file right after the
click and is revoked after the wait (the wait is now a test-hook
variable); a community id with unsafe characters or only dots names
the file safely; Settings' Download workspace reports why it cannot
build a zip, through init's wiring.

Tested: bun frontend/test-widget-tools.js (397 passed); never
revoking, revoking at once, dropping the sanitizer or the fallback
name, and unwiring or silencing the workspace button each fail it.
The pop-out shows a run's code block with the exact code, closed
even when a later save happened while it was open on the page, and
its Copy and Download work there.

Tested: bun frontend/test-widget-popout.js (140 passed); storing and
reading back the open state fails it.
@neuromechanist
neuromechanist force-pushed the feature/issue-491-run-code branch from 5b0c894 to ef106ee Compare September 25, 2026 00:53
@neuromechanist

Copy link
Copy Markdown
Member Author

Review response

Rebased onto current develop (with #508), force-pushed; head ef106ee.

  1. revokeObjectURL untested. Fixed in 49bcc06. saveFile's wait is now SAVE_FILE_REVOKE_MS (5000, shortened through a test hook). The test fetches the download's own blob: address, a real Bun one: right after the click it still serves the exact code, and after the wait fetching it fails. Mutations: never revoking fails "after the wait it is revoked"; revoking at once fails "right after the click, the address still serves the file".
  2. runFileStem's sanitizer untested. Fixed in 49bcc06. Community ids a/b c, ..\x:y, ... and '' (set on the config directly, as a pop-out's unvalidated preset could) name the file a_b_c-run-3, _x_y-run-3, osa-run-3 and osa-run-3. Dropping the character class, or the || 'osa' fallback, each fails it.
  3. No pop-out coverage. Fixed in 365560b (frontend/test-widget-popout.js). The run's code block renders in the pop-out with the exact code; Copy puts it on the pop-out's clipboard; Download saves nm000103-run-1.py with the exact code, through the pop-out's own URL and link. It opens closed there even after a later save while it was open on the page, which is what the docs now say ("closed there, as after a reload"). Two independent guards produce that (saveHistory strips _codeOpen, and normalizePersistedExecutions never reads it back), so removing either alone survives. Removing both fails the test.
  4. The run-NNN numbering claim. Checked against the code and corrected in ef106ee. ClientToolController#persist saves files only when the runtime kept the call's full output, which is for ok and error only. WorkspaceStore._reserveOrdinal numbers per session, and a run gets no ordinal where storage fails. The sentence now says the workspace numbers per chat session, only the runs it saved files for (Python ran to an end, successfully or with an error, in a browser that could store them), so the two numbers agree only while every run ended that way.
  5. Workspace export button. Test added in 49bcc06. Settings' "Download workspace (.zip)", pressed through init's own wiring, with a real WorkspaceStore (genuinely unavailable under happy-dom), shows "Could not build the workspace download: IndexedDB is not available in this browser", logs it, and saves nothing. Unwiring the button or silencing its error each fail it. The success path needs a real IndexedDB, so I checked it in headless Chrome against widget_e2e.py after a real run: Settings saved browsertest-workspace.zip, a real zip (PK) holding scripts/run-001.py. That check is not committed, because it needs Pyodide from the network.

Skipped: the "Copied" label can go stale if a re-render lands inside its 2-second window. It is a temporary indicator, the re-rendered button is correct, and no state is lost.

Every widget suite passes: tools 397 (385 before), pop-out 140 (132), capsule 133, color scheme 128, notebook tab 168, first paint 82, dataset questions 60. The new checks' asserts now tally rather than being swallowed by a captured console.error, so each mutation above shows as a named failure.

@neuromechanist
neuromechanist merged commit 0e0c4e7 into develop Sep 25, 2026
8 checks passed
@neuromechanist
neuromechanist deleted the feature/issue-491-run-code branch September 25, 2026 00:58
neuromechanist added a commit that referenced this pull request Sep 25, 2026
Brings in #502, #503 and #508. The generated runtime bundle and its integrity
line are rebuilt from the merged sources; CHANGELOG keeps both Added entries.

Tested: bun scripts/build-runtime-bundle.js --check; test-worker-core (220),
test-data-lane (106), test-runtime-bundle (25), test-widget-tools (397),
test-runtime-lifecycle and test-egress all passed.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant