Skip to content
ardfardPublic

About

Coding exercises in an in-browser Debian sandbox (v86 / WebAssembly) — PoC

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

ngoding — coding exercises in an in-browser Linux sandbox (PoC)

The app shares one in-browser Debian VM image across modes:

  • / is the home page: start a playground session or continue exercises (solved N/total stats).
  • /play?s=<id> is the playground IDE: file tree under ~/, editor tabs, Run, and an auto-detected Build command you can override. Multiple local sessions each keep their own IndexedDB snapshot (vm:play:<id>).
  • /exercise is graded mode (formerly /problems, which redirects here): pick a problem, edit its solution, run it in the shell, and Check sends output to the server. Progress is solved / not yet (ngoding.solved).
  • /learn is learn-by-doing (like Go by Example, for every language, but you write the code): each lesson explains a concept (loops, maps, closures, errors, …) or a common task (files, directories, JSON, running commands, threads, TCP sockets, …) and opens a starter file under ~/learn in the selected language (the example's imports and an empty main, no solution), with the expected output beside it. Check my output runs the file in the shell, captures its stdout and compares it with the expected output (all in the browser); passing lessons are marked solved (ngoding.learn.solved). Lessons live in public/lessons/; every language's reference example (kept for the tests, not shown) prints the same output.

Play sessions, Exercise and Learn keep separate VM snapshots (vm:learn for Learn) so sandbox experiments do not overwrite exercise work.

The VM is v86, a BSD-licensed emulator of a full x86 PC that JIT-compiles to WebAssembly. It runs a real Debian kernel. The root filesystem is served over 9p, one file at a time over HTTP, and the browser resumes from a memory snapshot taken after boot, so students never wait for Linux to start.

All compute happens in the student's browser. The server serves static files; on /problems it also handles two small JSON calls to start a session and grade output.

┌──────────── browser tab ──────────────────────────────────────────────────┐
│ /: home.js — sessions + exercise stats                                     │
│ /play?s=: play-ui.js — tree, tabs, Run/Build                       │ ttyS0 │
│ /exercise: ui.js — exercises, [Check], editor       ghostty-web ⇄ shell   │
│                                                                               │
│ vm.js: boot / save (vm:play:<id> | vm:exercise) ───────────────┼─► ttyS1   │
│   save → IndexedDB                         root agent: FS + grade I/O       │
│ v86 (wasm) ── 9p root fs ── fetches /v86/flat/<hash>.bin.zst on demand     │
└──────────────┬────────────────────────────────────────────────────────────┘
               │ /exercise only: POST /api/session → token, problems, inputs
               │                 POST /api/grade   {token, problemId, output}
┌──────────────┴──────────────── src/main.rs (Rust) ────────────────────────┐
│ static files (cached) + src/problems.rs (solvers) + src/session.rs (HMAC)  │
└───────────────────────────────────────────────────────────────────────────┘

Run it

npm install           # browser deps (ghostty-web, v86), embedded by cargo; Playwright for e2e
npm run build:image   # docker + node: public/v86/{fs.json,flat/,state-<hash>.bin.zst} (~220 MB)
                      # run again after changing image/agent.sh (new agent verbs, etc.)
npm start             # cargo run --release: http://localhost:8080  → /, /play, /exercise
npm test              # cargo test: checks the reference solvers against Python solutions
npm run test:unit     # node --test: build detection, language helpers (no VM)
npm run test:lessons  # compiles and runs every Learn example with local toolchains
                      # (`node test/lessons-run.mjs --starters` checks the starter files build and print nothing)
npm run test:e2e      # with the server running: boots the VM in headless Chromium,
                      # home, Play sessions + Exercise (separate saves), grades problems,
                      # runs uv, checks Ctrl-C, the editor (autocomplete, run), server-side
                      # grading, saving + restoring work,
                      # and that a reload is served from cache
npm run test:e2e:learn # with the server running: Check in Learn passes and fails as it should;
                      # `node test/e2e-learn.mjs /usr/bin/chromium json:rust` checks given lessons
npm run build:image:unkernel # docker (riscv64 emulation): the /新 disk, public/unkernel-image/ (~20 min)
npm run test:e2e:unkernel    # with the server running: /新 play, toolchains, saving, Exercise, Learn

Deploy

cargo build --release produces one ~8 MB binary, target/release/ngoding, with the app (HTML/JS/CSS, ghostty-web, v86's wasm, the BIOS) compiled in; run npm install first. The VM image stays on disk, so it can be rebuilt without rebuilding the server. Copy fs.json, flat/, version.json and state-*.bin.zst from public/v86/ and run:

NGODING_IMAGE_DIR=/srv/ngoding/image NGODING_SECRET=... PORT=8080 \
  DATABASE_URL=postgres://… NGODING_DATA_DIR=/srv/ngoding/data ./ngoding

NGODING_IMAGE_DIR defaults to public/v86, and is served at /v86/. Only the embedded files and that directory are served. Without NGODING_SECRET, the secret is kept in .ngoding-secret in the working directory.

Accounts, cloud saves, and shares

Optional — without DATABASE_URL, local play/exercise still work; account APIs return 503.

Variable Role
DATABASE_URL Postgres for users, play session metadata, shares, exercise progress
NGODING_DATA_DIR Snapshot/share files on disk (default ./data)
SMTP_URL / SMTP_FROM Magic-link email (any SMTP, including Resend)
NGODING_DEV_AUTH If set and SMTP unset, log/return the magic link for local testing
NGODING_PUBLIC_URL Base URL for magic links; an https:// URL also marks the auth cookie Secure (default: the request's Host)
  • Sign in (home, or the Save to cloud dialog on play): email magic link; cookie ngoding_auth. The link can carry a same-origin next path to land on after sign-in.
  • Save to cloud (play): uploads the full VM snapshot; open /play?s= restores from the server if IndexedDB is empty. Signed out, it asks you to sign in first.
  • Share: the Share button shows a link to a snapshot of ~/workspace (no login required). /s/<id> opens it read-only in the editor, without booting the VM; Fork to edit copies it into a new local session.
  • Image builds keep prior state-*.bin.zst and merge flat/ hashes so older saves keep booting.

Starting a shell takes about 1 s and downloads about 18 MiB (mostly the snapshot). Files are then fetched as they're used: ~22 MiB after the first python3, ~78 MiB after uv add (uv itself is ~50 MB). CPU-bound Python runs about 20× slower than native, which is fine for exercises.

Server load and caching

The server does no emulation and no student code execution. Per student it serves static files and answers a couple of tiny JSON requests, so a cheap static host or a CDN in front of the server handles a whole class.

  • Files under /v86/flat/ are named by content hash, and the snapshot is state-<hash>.bin.zst. Both are served with Cache-Control: immutable (one year). version.json points at the current snapshot and is always revalidated.
  • Everything else gets an ETag and no-cache, so unchanged files cost a 304.
  • A returning student downloads about 17 KiB.

What's in the VM

i386 Debian bookworm with a 6.1 kernel, python3 3.11, pip, venv, numpy, uv, gcc/g++, go, rustc, ghc/runghc, node 18, tsc 4.8, git, nano, nvim (vi/vim alias to it), sudo (passwordless), and user user.

The VM has no network by default. So that the package-manager workflow still works, /opt/wheels contains a few wheels (rich, requests, pytest, tabulate), and uv/pip are configured to install from that directory offline:

uv init demo && cd demo && uv add rich && uv run python -c "import rich; rich.print('[green]hi')"

Add more packages on the pip download line in image/Dockerfile. Internet access is possible through v86's websocket relay (the network_relay_url option), but it isn't enabled.

How the image is built (image/)

  • Dockerfile builds i386 Debian with linux-image-686, and an initramfs that mounts the root filesystem from 9p. v86's tools/fs2json.py and copy-to-sha256.py (vendored in image/tools/) turn it into a file index plus content-addressed, zstd-compressed files. The result is exported as a single tar, because Docker's local exporter hangs on tens of thousands of files.

  • The image is trimmed: no docs (except copyright files), man pages, translations, or locale data; kernel modules only for hardware v86 emulates; a list-only initramfs.

  • init.sh is PID 1 (under tini) instead of systemd. It mounts the usual filesystems, starts the agent, and autologs user in on ttyS0. agetty runs under setsid so the shell gets a controlling terminal; without it, Ctrl-C doesn't work.

  • build-state.mjs boots the image in Node (~15 s), waits for the shell, and saves a memory snapshot (44 MiB → 14 MiB zstd) as state-<hash>.bin.zst, plus version.json. The memory size is shared with the browser via public/v86-config.js, because a snapshot only restores into a VM with the same memory size.

  • agent.sh runs as root on the second serial port and accepts a fixed set of verbs:

    • write: push a file (challenge inputs on Problems, editor saves on both pages)
    • read: fetch file contents (grading outputs, editor loads)
    • ls: list one directory (names and d/f type), for the Play file tree
    • mkdir, rm, mv: change the tree under /home/user
    • resize: match the tty to the browser terminal
    • init: set the clock and add fresh entropy, since every visitor restores the same snapshot

    Rebuild the image (npm run build:image) after changing this script so the guest VM picks up new verbs.

How grading works

  • POST /api/session gives each browser a token of the form <seed>.<HMAC>, kept in localStorage. Every problem generates its input from the seed, so students can't share answers. The token is signed, so they can't pick someone else's seed. The server stores nothing: it regenerates inputs and expected answers from the seed.
  • The browser receives the problem text and its inputs, which are written to ~/challenge/<problem>/input.txt through the agent. The reference solvers live in src/problems.rs and are compiled into the server, never served.
  • Check reads the output file through the agent and posts it to /api/grade. The server compares it line by line with the expected output, ignoring trailing whitespace, and returns only pass/fail and a hint about the first wrong line.
  • The signing secret comes from NGODING_SECRET, or .ngoding-secret, which is created on first start. Keep it stable, or every token becomes invalid.

Add a problem by appending to PROBLEMS in src/problems.rs (generate(rng) and solve(input)), then add a Python solution as test/solutions/<id>.py (dashes become underscores); cargo test checks it against the solver.

The editor

Both pages use CodeMirror 6 above the terminal. Files live in the VM; the editor reads and writes through the agent, so the shell always sees the same bytes.

Problems (/problems): one editor buffer per problem's solution file (e.g. ~/word_freq.py; the base name comes from solution_file in src/problems.rs). A Language select (Python, C, C++, Go, Rust, Haskell, JavaScript, TypeScript) is global across problems, remembered in localStorage. Changing it swaps the extension (.py / .c / .cpp / .go / .rs / .hs / .js / .ts), syntax mode, and starter template. Switching problems or languages keeps unsaved edits per path; otherwise the file is reloaded, so changes made with nvim in the terminal show up.

Play (/play): open any text file under ~/ from the tree or tabs. Tabs track open paths; deleting or moving a file in the tree closes its tab. Binary or oversized files show an error instead of opening. Syntax mode follows the file extension. Build walks from the current file's directory up to ~/ looking for Cargo.toml, go.mod, tsconfig.json, Makefile, uv.lock, or pyproject.toml, then runs the matching command (cargo build, go build ., tsc -p ., make, or uv sync). You can type a different command in the build field; that override is stored in localStorage until you clear it.

On both pages:

  • Ctrl-S saves, and Ctrl-Enter (or Run) saves and compiles/runs in the terminal (python3, gcc/g++ then /tmp/ngoding, go run, rustc then /tmp/ngoding, runghc, node, or tsc into /tmp/ngoding-ts then node). Leaving the page with unsaved edits asks for confirmation.
  • Autocomplete: Python, Go, JavaScript, and TypeScript use CodeMirror's built-in keyword/snippet/local-name sources; C, C++, Rust, and Haskell get keywords plus words already in the buffer. None of them know about imported libraries; that would need a language server in the VM.
  • Vim switches on Vim keybindings (@replit/codemirror-vim), with :w to save.
  • The layout button cycles Split / Editor / Shell (drag the bar between editor and terminal to resize the split). Layout, split ratio, Vim, and language are remembered in localStorage.
  • npm install bundles CodeMirror into public/codemirror.js with esbuild (npm run build:editor, entry point editor/codemirror.js), which the binary embeds.

Saving work

The whole VM is saved to IndexedDB under vm:play or vm:problems, depending on the page: memory plus every file the student changed, which v86 keeps in its 9p filesystem state. The browser's CompressionStream gzips it. A reload on the same page resumes exactly where the student was, including running programs, in about 0.6 s. An older single-key save (snapshot) is migrated once into vm:problems.

  • When it saves: after every Check (Problems only), every minute if there was terminal input, and when the tab is hidden.
  • Size: 16 MiB for a fresh session, about 40 MiB after uv add and some Python work. A save takes 1–3 s.
  • When a save is discarded: if the image is rebuilt (the snapshot name changes), the session changes (Reset on Problems), or you switch pages (each page has its own key), so restored work always matches the right context.

/新: the same app on unkernel

/新/, /新/play, /新/exercise and /新/learn are the same pages running on unkernel instead of v86: the Linux kernel compiled to WebAssembly, with riscv64 programs on an emulator that JIT-compiles them to Wasm. It is 64-bit, boots in about 2.5 s with no memory snapshot, and runs compiled code several times faster than v86 (see docs/research/2026-11-17-unkernel.md).

How it differs from the v86 app:

  • Routing: the server serves the same embedded files under /新, rewrites absolute links in the HTML to stay under the prefix, and serves public/vm-unkernel.js as /新/vm.js (same exports as vm.js). public/base.js tells the two copies apart in the browser.
  • Image: npm run build:image:unkernel (image-unkernel/) builds Debian trixie riscv64 with the same tools into one ext4 disk, public/unkernel-image/debian-<hash>.ext4 (6.2 GB, about 3.4 GB on disk, sparse), plus version.json. It needs docker with riscv64 emulation (qemu binfmt) and takes about 20 minutes. The browser reads the disk lazily with HTTP Range requests.
  • Guest access: PID 1 (image-unkernel/init.sh) keeps unkernel's kwtty running. The student's shell is a pty session (su -l user) and file operations are exec() calls; image/agent.sh isn't used.
  • Saving: writes go to a copy-on-write overlay that the SDK keeps in IndexedDB, one per save key (unk:vm:play:<id>, unk:vm:exercise, unk:vm:learn). Saving flushes the guest's file systems into it. Running programs don't survive a reload; files do.
  • Separate state: the play-session list is ngoding.新.play.sessions. Cloud saves, sign-in and shares are off, because they carry v86 snapshots.
  • Browsers: needs JSPI (Chrome/Edge 137+, Firefox 153+, Safari 27+).

First runs on a fresh session (headless Chromium, local server, npm run test:e2e:unkernel):

Step Time
Page to shell 2.5 s
gcc main.c && ./main 4.6 s
python3 + numpy 3.9 s
go run hello.go (std library cache prebuilt in the image) 14.5 s, then 0.9 s
rustc hello.rs 23.6 s
runghc Hello.hs 17 s
uv init && uv add rich && uv run (offline) 7 s
tsc + node 195 s

First runs include fetching each tool from the disk image. tsc is slow because Node's own JIT output runs on the riscv64 emulator.

To deploy it, copy public/unkernel-image/ (keep it sparse: rsync --sparse) to the server and set NGODING_UNKERNEL_IMAGE_DIR (default public/unkernel-image, served at /unkernel-image/ with Range support).

Limits and next steps for production

  • Work lives in one browser. Clearing site data or switching devices loses it. Uploading the gzipped snapshot to object storage would fix that, at ~15–40 MB per student.
  • Grading checks output, not code. A student could compute the answer some other way, for example by hand. If that matters, also submit the .py files and re-run them server-side on hidden inputs in a native sandbox.
  • Progress isn't recorded centrally. The "solved" ticks are in localStorage. For a real course, /api/grade should record results per student, which needs a login.
  • Serve over HTTPS outside localhost. Any static file host works; no special headers are needed.

License

Apache License 2.0; see LICENSE and NOTICE. Third-party parts keep their own licenses: v86's tools in image/tools/ (BSD 2-Clause), SeaBIOS in public/v86/bios/ (LGPL v3), and the npm packages served to browsers (v86: BSD 2-Clause, ghostty-web: MIT, CodeMirror and its Vim mode: MIT).

The built VM image (npm run build:image) contains Debian packages under their own licenses, mostly GPL. If you host the image publicly, the GPL requires you to make the corresponding source available. Pointing to the Debian bookworm source archive for the exact package versions is the usual way to do that.

About

Coding exercises in an in-browser Debian sandbox (v86 / WebAssembly) — PoC

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages