Chapters
- ·How to read this
- 1The mapThree layers · Four repositories · Where it runs · Vocabulary
- 2Pure foundations: protocol and nbformatganymede-protocol (about 1,400 lines) · ganymede-nbformat (about 7,500 lines)
- 3Kernel host: getting a kernel and talking to itThe seams · KernelSession: the state machine · Starting a kernel
- 4API and contents: the server's logic without HTTPganymede-api (about 5,500 lines) · ganymede-contents (about 9,100 lines) · Saving a notebook
- 5The serverCode map · Who gets in · How a request is served · Running a cell
- 6Rooms: one live notebook for everyoneTwo halves · What a room's task does · An edit in a room · Running cells into a room
- 7The notebook as a programganymede-exec (one 2,100-line file) · The run contract · The host API · Grants
- 8Agent-native: an agent in the same live notebookThe pieces · Design choices visible in the code · How the agent hears about a person's edits · The journal plugin
- 9CLI and embedding: three ways to use the coreganymede-cli (about 19,000 lines) · ganymede-engine (about 1,100 lines) · ganymede-ffi (about 2,700 lines)
- 10cdp-kernel: the TypeScript kernelThe two halves · The cell pipeline · Inside the runtime: jupyter.* · A TypeScript cell on Node
- 11ganymede-ui: the web appCode map · Backends · Saving: two paths · Opening a notebook (browser, Ganymede backend)
- 12The Apple appsCode map (apple/Sources/Ganymede/) · In-app kernels · packages/device: the device API · The Mac app opening a notebook
- 13Building, testing, shippingBuild profiles · Where each promise is tested (ganymede) · How a change lands · Releases
- 14Where to dive nextOpen edges worth knowing about · Keeping this primer current
Before you start
How to read this
This primer explains how Ganymede's code fits together across its three active repositories (ganymede, cdp-kernel, ganymede-ui), so you can pick any part and dive in already knowing where it sits, why it exists and which files to open first. It is written for an experienced engineer who is new to this codebase. It describes main as of the date above.
Each chapter follows the same shape:
- Why it exists: the problem the part solves and what it deliberately does not do.
- How the code is laid out: crates, modules and files, with sizes where they help you judge effort.
- Flows: one or two real paths traced through named files, such as running a cell or an agent editing a live notebook.
- Dive in: where to start reading, and which user docs already go deeper.
The primer does not repeat the user docs. Where a topic is already covered well, it links to the page. The most useful ones to keep open are ganymede's architecture, rooms and host API pages, ganymede-ui's architecture, and cdp-kernel's architecture.
One habit worth knowing from the start: almost every Rust module and many TypeScript files open with a doc comment (//!) that states the module's contract, its edge cases and the issue it came from. Reading those headers is the fastest way through the code, and this primer points to them often.
Chapter 1 of 14
The map
Ganymede is a Rust replacement for the middle of the Jupyter stack, jupyter_server. It keeps both of that server's interfaces: the REST and websocket API above it, and the kernel messaging protocol over ZeroMQ below it. Everything else in the project is either a client of that API (the web UI and the apps) or a kernel behind it (cdp-kernel).
Three layers
- Clients call the Jupyter REST and websocket API. JupyterLab and VS Code work unchanged. ganymede-ui's web app is a client too, and so are agents, through MCP or the host API. No client gets a private side door into the core.
- The Rust core (repo
ganymede) is the server: kernel lifecycle, notebook files, live document rooms, runs, the host API and MCP. It knows no kernel language. - Kernels run code. Any Jupyter kernel works, launched from its kernelspec. cdp-kernel is the first-class one, for TypeScript and JavaScript.
Four repositories
| Repo | Language | What it holds | Size of the main code |
|---|---|---|---|
tlockney/ganymede |
Rust | 15 crates under crates/, the ganymede CLI, docs site, journal plugin for Claude Code |
About 131,000 lines of Rust, tests included; ganymede-server alone is about 60,000 |
tlockney/cdp-kernel |
TypeScript | The kernel (src/) and the code it injects into each runtime (runtime/) |
About 49 files in src/, 19 runtime modules |
tlockney/ganymede-ui |
TypeScript, Swift | Web app (src/), the Mac, iPad and iPhone app (apple/), packages/device, packages/agent |
About 53,000 lines of Swift in apple/Sources |
tlockney/ganymede-device |
Archived. Its code moved into ganymede-ui packages/device on 2026-11-13 |
The repos are joined at four points. ganymede-ui pins a ganymede commit or tag (GANYMEDE_REF in its ci.yml) and links ganymede-ffi built from it as an XCFramework. ganymede-ui depends on @tlockney/cdp-kernel from npm for the in-page kernel. ganymede launches cdp-kernel like any other kernel, from a kernelspec. ganymede's docs site copies ganymede-ui's docs and cell API reference at build time.
Arrows point from a repo to what it uses. The XCFramework is built from the ganymede commit in GANYMEDE_REF, so an app change that needs a server change waits for that pin to move.
Where it runs
The same crates run in four setups (architecture: where it runs has the picture):
- Workstation or server:
ganymede serveorganymede labas a process, kernels as child processes over ZeroMQ. - Mac app: the server runs inside the app's process through
ganymede-ffi, on loopback (or, when Background Server is turned on, as a LaunchAgent running the bundledganymedebinary so kernels and rooms stay alive between launches), and the web view loads ganymede-ui from it. Kernels are the Mac's kernelspecs, plus cdp-kernel in a hidden web view registered with the server in-process or over its kernel provider socket. - iPad and iPhone app: the same app. iOS won't let an app launch processes, so the local kernel is cdp-kernel in a hidden web view (on ganymede-ui's main, also a Pyodide Python kernel in the same web view); others come from a remote server through the gateway.
- Browser only: ganymede-ui alone, notebooks in IndexedDB, kernels in Web Workers. The Rust core is not involved.
Vocabulary
| Term | Meaning here | Where in code |
|---|---|---|
| Kernelspec | A kernel.json saying how to launch a kernel: command line, language, interrupt mode |
ganymede-kernel-host |
| Kernel channels | Five ZeroMQ sockets per kernel: shell, iopub, stdin, control, heartbeat | ganymede-protocol |
| Session | Jupyter's record binding a notebook path to a kernel (/api/sessions) |
ganymede-api |
| Comm | A named channel between kernel and client inside the protocol; carries widgets and the host API | ganymede-host, cdp-kernel runtime/comm.mjs |
| Room | A notebook held live in memory as a Yjs document, which every client and agent edits | ganymede-documents, server collab.rs |
| File id | A stable id for a notebook path, kept across renames and restarts; rooms are keyed by it | server collab.rs, FileIds |
| Run | A notebook executed top to bottom in a fresh kernel, with parameters in and named results out | server run.rs, ganymede-exec |
| Grant | A per-notebook permission for the host API (read, run, edit_self); nested runs only narrow it |
server host.rs |
| Journal | A notebook an agent keeps as it works, through the MCP tools | server mcp.rs, plugins/ganymede-journal |
| Mount | A named local folder served under /api/contents/<name>/… in multi-root mode, with its own file ids, rooms, grants and recovery store (distinct from connected-machine mounts under /machines/{id}/) |
multi.rs, server mounts.rs |
| Backend | In ganymede-ui, what builds the ServiceManager the UI talks to: a server, or services in the page |
ganymede-ui src/lib/backends.ts |
Rules that shape the code
- Only the core is Rust. UIs are API clients and live outside the
ganymederepo. - The host knows no language. Nothing in the host crates special-cases Python or TypeScript; language facts come from the kernelspec,
kernel_info_replyand output MIME types. The test suite runs the same scenarios against cdp-kernel and ipykernel. - The Jupyter API is a compatibility target. A difference from
jupyter_serveris a bug. The e2e suite runsjupyter_server2.21.1 side by side to check. - Conservative security defaults. Grants and permissions are scoped as narrowly as possible, and nested runs can only narrow them.
- The bottom crates do no I/O, so they build for any target, including wasm and iOS.
Chapter 2 of 14
Pure foundations: protocol and nbformat
Two crates sit at the bottom and do no network or file I/O: ganymede-protocol models the Jupyter messages and their byte layouts, and ganymede-nbformat models the .ipynb file. Because they do no I/O, they build for wasm and iOS, and every higher crate can trust one definition of a message and of a notebook. (ganymede-documents, the third no-I/O crate, belongs to rooms and is in chapter 6.)
ganymede-protocol (about 1,400 lines)
It answers one question: given a message, what bytes go on each kind of wire, and back.
| File | What it holds |
|---|---|
message.rs |
Message (header, parent header, metadata, content, binary buffers), Header, the Channel enum. Protocol version 5.5, including subshell_id |
content.rs |
Typed content only for messages the host itself reads or sends: execute_request, kernel_info_reply, status, stream and so on. Everything else stays raw JSON |
wire.rs |
ZeroMQ multipart framing: identities, the <IDS|MSG> delimiter, an HMAC-SHA256 signature, then header, parent header, metadata, content and buffers. Signs and verifies frames |
ws.rs |
The two websocket framings clients use on /api/kernels/{id}/channels: v1.kernel.websocket.jupyter.org (binary, an offset table then the parts) and the legacy JSON form |
connection.rs |
The connection file a host writes for a kernel: ports, transport, key, signature scheme |
Two design rules run through it, stated in lib.rs:
- Unknown fields survive. Every struct has a
#[serde(flatten)] extramap, so a field a kernel adds (a capability list inkernel_info_reply, say) reaches clients untouched. - Content is kept as JSON on
Messageand parsed into a typed struct only on demand (Message::content_as). The server mostly forwards messages, so it avoids parsing what it doesn't need.
Lenience is deliberate too: a header missing username, date or version is accepted, because jupyter_client accepts it and rejecting it would drop a reply the host is waiting for.
ganymede-nbformat (about 7,500 lines)
Its core promise is in the crate doc: a notebook saved by Ganymede is byte for byte what Python's nbformat would write, so saving never produces a spurious git diff. The rest of the crate has grown into the toolkit for anything that turns a notebook into something else.
| File | What it does |
|---|---|
types.rs |
Notebook, Cell, Output, MimeBundle, each with an extra map; unknown cell and output types are kept verbatim |
reader.rs |
Lenient reading, as Python's nbformat: string or list multi-line text, nulls read as defaults, missing or duplicate cell ids repaired. ReadReport says what was repaired |
upgrade.rs |
nbformat 3 upgraded to 4 on read |
writer.rs |
The byte-identical writer: split lines, strip transient metadata, sort keys, indent 1, Python's float formatting (python_float_repr), trailing newline |
atomic.rs |
atomic_write and atomic_write_with: temp file, fsync, optional pre-rename hook (used by the write observer to stamp the temp file before it lands), then rename. Shared with the contents layer |
params.rs, results.rs |
The run contract's data side: parameters go to the kernel in GANYMEDE_PARAMS; named results are outputs of type application/vnd.ganymede.result+json (scrapbook's types are read too) |
html.rs, highlight.rs |
ganymede nb publish: one self-contained HTML page with no scripts from the notebook, HTML outputs in sandboxed iframes, server-side syntax highlighting |
export.rs |
Script and Markdown export, the two nbconvert formats that need no templates |
Note what params.rs and results.rs do not do: they never mention a language. A parameter is JSON in an environment variable, and a result is a MIME type in an output. Each kernel decides how to expose them; cdp-kernel reads them as jupyter.params and writes them with jupyter.result.
Chapter 3 of 14
Kernel host: getting a kernel and talking to it
ganymede-kernel-host (about 7,600 lines) is Ganymede's jupyter_client. It finds kernels, launches them, connects to them and runs the per-kernel state machine. It is built around three seams, so the same code drives a local process over ZeroMQ, a kernel on another server, and a kernel an app or local provider runs itself.
The seams
A kernel comes to life in three steps, each behind a trait:
KernelspecSource(kernelspec.rs) lists what can be launched.FsKernelspecssearches the Jupyter data directories injupyter_client's order, plus extra roots from--kernelspec-root. That is how conda and venv kernels are found without the host knowing what a venv is.Provisioner(process.rs) makes a kernel exist and returns aLaunchedKernel: its connection info (if any) and aKernelProcesshandle for interrupt and kill.SubprocessProvisionerallocates five ports, writes the connection file in the runtime directory and spawns the kernelspec's command.attachadopts a kernel that is already running.TransportFactory(transport.rs) turns aLaunchedKernelinto aKernelTransport: aTransportSinkto send on and a stream of(Channel, Message)coming back.ZmqTransport(zmq.rs) uses the pure-Rustzeromqcrate: DEALER sockets for shell, control and stdin, SUB for iopub, REQ for heartbeat, one task per socket.
Two other implementations fill all three seams at once:
ganymede-gateway(about 1,900 lines insrc/): kernels on another Jupyter server, inlib.rs. Its kernelspecs are the remoteGET /api/kernelspecs(listed alongside this machine's own kernels, reporting when the gateway isn't answering), launch isPOST /api/kernels, and the transport is the remote channels websocket. This is--gateway-url, and how the iPad app reaches a Mac's kernels. Itsmount.rsis the forwarding for connected machines (chapter 5).registered.rs: kernels an app or local provider runs itself. The provider implementsAppKernel(start, optional deferredstarted,send,stop) and pushes messages back withRegisteredKernels::deliver, with spec origin tracking, live unregister and no-restart endings (Ended). No process, no ZeroMQ. The Apple apps register cdp-kernel running in a hidden web view this way, either in-process throughganymede-ffior over a standalone server's local kernel provider socket (kernel_providers.rs, chapter 5), so it appears in/api/kernelsbeside every other kernel (chapter 12).
The Cargo features zmq and subprocess are on by default. Without them the crate is the state machine, kernelspec parsing and the in-process transport, which is what builds for iOS and wasm.
Read each row left to right: the same three questions get a local, a remote or an in-app answer, and KernelSession on the right never knows which.
KernelSession: the state machine
session.rs (about 1,800 lines) is the heart of the crate. One KernelSession wraps one connected kernel and knows what a plain message pipe does not:
- The startup nudge (
nudge). ZeroMQ's PUB/SUB silently drops messages published before the subscriber connects. So the host sendskernel_info_requeston shell and control until both answer and at least one iopub message has arrived. A kernel with an XPUB socket (ipykernel 7) sendsiopub_welcome, which settles the iopub half at once. - Two-part completion. A request is done when its reply has arrived on shell and an iopub
status: idlewith the request as parent has arrived. They come on different sockets, in either order. ThePendingstruct tracks both. - Routing. Replies go to the requester by
parent_header.msg_id; iopub fans out to every subscriber (subscribe, orsubscribe_losslessfor consumers that must not miss a message). - Interrupt by signal or by
interrupt_request, as the kernelspec'sinterrupt_modesays. Shutdown sendsshutdown_request, waits a grace period, then kills. - Death: the process exiting, the transport closing, or missed heartbeats for a kernel with no process handle.
Crash restarts are not here: they belong to the kernel manager in ganymede-api (chapter 4), which restarts a crashed kernel under the same id up to restart_limit times, as jupyter_server's restarter does. A kernel the platform ended (lost, as iOS does to the app's kernel in the background) has its own limit: three losses within 60 seconds of each other restart it, and the next leaves it dead, with the reason on status: dead.
FlowStarting a kernel
- The kernel manager picks a
Kernelspecfrom theKernelspecSource. Provisioner::launchreserves five ports (in-process and in a per-user directory, so two Ganymede processes don't hand out the same port), writeskernel-<id>.json, and spawns the command with the connection file path substituted.TransportFactory::connectopens the five sockets.KernelSession::startbegins reading;nudgeruns the handshake and storeskernel_info_reply.- The session is live: clients can send on shell, and iopub flows to all of them.
Chapter 4 of 14
API and contents: the server's logic without HTTP
Two crates hold the logic behind jupyter_server's REST API, with no HTTP in either. ganymede-api manages kernels, sessions and per-client connections; ganymede-contents manages files. The HTTP server (chapter 5) is a thin mapping onto them. They were kept free of HTTP so an app could call them directly; in practice the apps run the full server on loopback instead, which turned out simpler, but the split still keeps the logic testable on its own.
ganymede-api (about 5,500 lines)
| File | What it holds |
|---|---|
kernels.rs |
KernelManager: start, restart, interrupt, shut down, cull idle kernels, list. Crash restarts under the same id up to restart_limit (default 5), as jupyter_server's KernelRestarter. A lost kernel restarts at most 3 times within 60 s, then stays dead and says why. Holds a weak reference to the host API responder (set_host), resolves per-mount working directories via KernelRootResolver, and supports shutdown_for_mount when a multi-root mount detaches |
sessions.rs |
SessionManager: Jupyter sessions, a notebook path bound to a kernel. notebook_of_kernel is how the host API and MCP find which notebook a kernel belongs to |
bridge.rs |
ClientConnection: one websocket's share of a kernel's traffic |
kernel_log.rs |
The last lines of each kernel's stdout and stderr, for GET /api/kernels/{id}/log. A Ganymede extension, so a client can show why a kernel died |
executions.rs |
Per-kernel execution history ring buffer (last 50 executions per running kernel in memory), backing GET /api/kernels/{id}/executions and GET /api/executions so clients such as the Mac menu bar can inspect recent runs without holding a websocket open; dropped when the kernel leaves the manager |
models.rs |
The JSON models, field for field as jupyter_server returns them |
The bridge is the part worth understanding. jupyter_server gives each websocket its own DEALER sockets to the kernel. Ganymede shares one set of sockets per kernel and dispatches each incoming message to per-client queues instead: iopub to everyone, replies only to the client whose session is in the parent header. It keeps jupyter_server's behaviors on top of that:
- When the last client disconnects, its queue keeps filling. A client that reconnects with the same
session_idgets the buffered messages, so a laptop waking from sleep sees what ran while it was away. - A new connection with the session id of an open one replaces it, since the old one is most likely a dead socket.
- Reply queues are unbounded, so a slow client never loses its own
execute_reply. Iopub beyond a limit is dropped, and the client is told with a stderrstreammessage.
One gotcha from the host API work: KernelManager holds the host responder weakly. A strong reference formed a cycle that kept embedding apps alive after they stopped the server.
ganymede-contents (about 9,100 lines)
The contents API: files, directories, checkpoints. Its design comes from the iPad case, where the notebook folder is in iCloud Drive and other writers touch the same files.
| File | What it holds |
|---|---|
lib.rs |
The Contents trait and the wire model (ContentsModel, SaveRequest, Checkpoint) |
fs.rs |
FsContents, the local filesystem implementation, plus with_write_hook so the server's write observer sees a temp file's stamp before atomic rename |
multi.rs |
MultiRootContents, the virtual Contents router for multi-root named mounts (docs/multi-root.md): serves a read-only virtual root "" listing active mounts, routes <mount>/<rel> to each mount's own FsContents while re-prefixing returned paths, enforces canonical non-overlap and mount-level symlink containment, and attaches or detaches mounts live. Single-root servers still use FsContents directly |
paths.rs |
ApiPath::parse, the only way client input becomes a path. It rejects anything that could leave the root before any filesystem call |
fileid.rs |
FileIds: a stable id per file, kept in SQLite, moved by renames through the API. Rooms are keyed by these ids. Host API grants are stored here too, so they follow a rename, each with a stamp of its file (size, mtime, inode) so a grant is dropped when its file changes outside Ganymede. In multi-root mode each mount opens its own database keyed by canonical root, sharing rows with standalone ganymede serve and ganymede grant |
trust.rs |
Notebook trust, compatible with Jupyter's own nbsignatures.db: a notebook Jupyter trusts is trusted here, and the other way round |
The rules: files are the source of truth and nothing is cached. Writes are atomic (temp file, fsync, rename). The checkpoint directory can live outside the root, so checkpoints aren't synced with notebooks.
FlowSaving a notebook
- A client sends
PUT /api/contents/{path}with the whole notebook, and eitherIf-Matchwith the ETag it read orlast_modifiedin the body. paths.rsparses the path;fs.rsreads the file on disk now.- If the sha256 doesn't match
If-Match, the answer is 412. If the file is more than 500 ms newer thanlast_modified, it is 409. Nothing is written either way: that is how an edit from another device isn't overwritten. - The notebook is validated through
ganymede-nbformat, written to a temp file in the same directory, fsynced and renamed over the old file. trust.rssigns it if every code cell is trusted. The first checkpoint is created if there is none.- The answer is 200 or 201 with the model and its new ETag.
With rooms on (chapter 6), most saves no longer come from clients: the room's own task saves the live document, through this same path, with If-Match on the hash it last wrote. The architecture page's save diagram shows the client path.
Chapter 5 of 14
The server
ganymede-server is the biggest crate (about 60,000 lines with tests, 38,000 in src/). Its own description is "every handler is a thin mapping from a route to an API call", and that holds for the Jupyter API. Most of its size is in the Ganymede extensions that have no jupyter_server equivalent: rooms, multi-root mounts, kernel providers, MCP, the host API, runs.
Code map
| File | Lines | What it does |
|---|---|---|
serve.rs |
2,300 | Flags, config, startup and shutdown. Defaults to the user's home directory (refusing to start when home is unusable or / unless --root-dir or config root_dir is explicit). Startup is how an embedder swaps in its own kernelspecs, provisioner, transports, registered kernels and multi-root mounts. Shared by ganymede serve, ganymede mcp and the apps |
routes.rs |
1,800 | router(state): every route, and the plain REST handlers, including Ganymede's /api/mounts, /api/executions, /api/kernels/{id}/executions and /api/update |
lib.rs |
290 | AppState: the managers, contents, mounts, token, origin rules, base URL, JupyterLab, static dir |
auth.rs, tailscale.rs |
1,800 | Who gets in: the token and its login cookie, mcp_token, tailnet identities, the Host check (below) |
ws.rs |
460 | The websockets: kernel channels, events (/api/events/subscribe, multiplexing server file-write and mount-change events and closing lagging clients with 1011 missed events), terminals, language servers |
lab.rs |
1,500 | Serving JupyterLab itself: its page, bundle, themes, prebuilt extensions and /lab/api/* |
collab.rs, recovery.rs, room_lock.rs, watch.rs |
8,300 | Rooms, recovery copies, room locks and directory watching (chapter 6) |
execute.rs |
2,000 | POST /api/kernels/{id}/execute: run cells into a room (chapter 6) |
room_ops.rs |
200 | Cell edits on a room, shared by MCP, the execute endpoint and the host API's self.* calls |
mounts.rs |
620 | Multi-root named mounts (MountRegistry): live attach (add_mount) and draining detach (remove_mount) across MultiRootContents, Collab, sessions, kernels, terminals, jpserver-<pid>.json and mount events on /api/events/subscribe. Mutated only in-process or through FFI; GET /api/mounts is read-only and never exposes raw host paths |
mount.rs, mount/proxy.rs |
270 | Connected machines: another Ganymede server mounted under /machines/{id}/ once the embedding app adds it (chapter 9). Only this server's own page session may use the mount; a tailnet identity or mcp_token gets 403. mount/proxy.rs is the router: it answers 502 for a machine that doesn't answer, bridges websockets, forwards the machine's notebook access settings, and sets this server's own sandbox policy on every forwarded response, in place of any the machine sent. The route allowlist and what is stripped from each request and response are in ganymede-gateway's mount.rs, beside the kernel gateway |
kernel_providers.rs |
1,350 | Local Unix socket (ganymede-kernels-<pid>.sock, mode 0600, named in jpserver-<pid>.json) where a same-user program (such as the Mac app's in-app TypeScript engine) authenticates with the server's token and registers display-only kernelspecs behind RegisteredKernels. [kernel_providers] reserve pins a name to a macOS code-signature requirement checked against the peer's audit token |
run.rs, host.rs |
1,800 | Runs and the host API (chapter 7) |
stamping.rs, write_observer.rs, path_locks.rs |
4,100 | Wraps Contents to keep host grants stamped across server saves, coordinate write and rename turns, and notify embedding apps (pre-rename pending, wrote, cancelled) and /api/events/subscribe of each local file write |
mcp.rs, mcp/ |
6,300 | The MCP server (chapter 8) |
config.rs, config_file.rs, folder.rs |
2,300 | ganymede.toml, read from Ganymede's config dir (~/.config/ganymede, or GANYMEDE_CONFIG_DIR) and shared with the Mac app through config_file.rs (toml_edit edits that keep comments and order and write atomically at 0600); per-folder .ganymede.toml (which kernel new notebooks in a folder start); log_file with tilde expansion and private permissions. ganymede info prints every directory Ganymede uses |
login_path.rs, update.rs |
850 | login_path.rs asks the user's login shell for its PATH once at Unix startup when path_from_login_shell is on (so launchd and systemd background servers find kernelspecs); update.rs runs an opt-in daily release check (off by default) reported at GET /api/update |
metrics.rs, server_info.rs |
800 | /api/metrics/v1; the jpserver-<pid>.json file (including active mounts and kernel_providers_socket) other tools and attachable CLI commands use to find a running server |
Two neighbor crates fill specific routes: ganymede-terminals (/api/terminals, the user's shell in a pseudo-terminal, with per-mount working directories and teardown when a mount detaches) and ganymede-lsp (/lsp/*, language servers started on demand and shared by every client; turned off in multi-root mode, where virtual / has no single filesystem root). Neither exists on iOS or wasm.
Who gets in
Every request passes auth.rs, which does what jupyter_server does and adds two ways in:
- The token, in an
Authorizationheader or?token=, traded for a signed login cookie in tornado's format, with_xsrfon cookie requests that change state. The apps start their server with a new random token each launch. mcp_token, a second token that only/mcpaccepts and that sets no cookie, so an agent given it can't reach the REST API. The Mac app gives agents this one.- A tailnet identity (
tailscale.rs, off by default). With[tailscale] allowlisting logins or tags, a request gets in without a token whentailscale servenames its sender on loopback, or whentailscale whoissays which login or tagged device owns the peer's tailnet address. The name shows in/api/me, in the log, and in the room's credit for edits (chapter 6)./mcpdoesn't accept it, and a browser request needs same-origin fetch metadata, so another site can't ride on it. Programs such as the gateway (chapter 3) mark their requests with aGanymede-Clientheader.
A Host check against DNS rebinding runs before any of these, and the server refuses to start with tailnet identity on and that check off.
How a request is served
serve.rs builds the KernelManager, SessionManager and FsContents (or MultiRootContents in multi-root mode) from config, or from what the embedder passed in Startup, wraps them in AppState, and hands that to routes::router. Routes nest under base_url. Requests pass the auth layer, then a handler calls into ganymede-api or ganymede-contents, and blocking filesystem work goes through a blocking helper onto tokio's blocking pool. Anything not matched falls through to JupyterLab or --static-dir (which is how ganymede-ui is served).
GET /api reports jupyter_server version 2.21.1, the version whose API this server matches. Clients use it to decide what they're talking to.
FlowRunning a cell
- A client opens
/api/kernels/{id}/channels?session_id=….ws.rspicks thev1.kernel.websocket.jupyter.orgframing if the client offers it, legacy JSON otherwise, and attaches aClientConnectionfromganymede-api/bridge.rs. - The client sends an
execute_requestframe.ganymede-protocol::wsdecodes it into(Channel::Shell, Message). - The bridge notes the client's session and calls
KernelSession::send, whichZmqTransportwrites to the kernel's shell socket, signed with the connection key. - The kernel publishes
status: busy,execute_input, outputs, thenstatus: idleon iopub. The session fans these out; the bridge puts each in every client's queue, so a second tab sees the same outputs. - The
execute_replycomes back on shell, before or after idle. The bridge sends it only to the client whose session is in its parent header. - If the cell calls
input(), aninput_requeston stdin goes to the requesting client, which answers withinput_reply.
Each dot is a layer the message passes through. KernelSession marks the request done only once both the reply (3) and its idle status (2) have arrived.
The architecture page has the same flow as a message sequence.
Chapter 6 of 14
Rooms: one live notebook for everyone
A room is a notebook held live in the server as a Yjs document (the Rust port, yrs), which every client edits at once: JupyterLab with its collaboration extension, ganymede-ui, an agent through MCP, and the server's own cell runner. The room, not any client, owns the file: it loads it, autosaves it and merges in changes other programs make. Rooms are what make priority 3, a person and an agent in one live notebook, possible, and the apps have opened notebooks through rooms since ganymede-ui 0.10.0.
The protocol is jupyter-collaboration's, so JupyterLab's own collaboration extension works against Ganymede unchanged.
Two halves
ganymede-documents (about 6,700 lines, no I/O) is the pure part:
| File | What it holds |
|---|---|
room.rs |
Room: one document and its connections as a state machine. The host feeds it frames and connection events; it returns Effects (frames to send, saves to make). Speaks y-websocket: sync, awareness, and jupyter-collaboration's raw save message. Also keeps, in memory, who last changed each cell (Author), for the agent tools (chapter 8) |
schema.rs |
Maps a ganymede_nbformat::Notebook to and from the Y document shape @jupyter/ydoc expects |
merge.rs |
Three-way merge (base, room, disk), cell by cell by id, part by part (source, outputs, each metadata key). Where both changed the same part, the disk wins that part |
depth.rs |
Refuses an update nested deep enough to overflow the stack when yrs applies it. A defense against a hostile client |
The server side does the I/O:
| File | What it holds |
|---|---|
collab.rs (about 6,900 lines) |
/api/collaboration/session/{path} (gives the file id) and /api/collaboration/room/{format}:{type}:{fileId} (the websocket). Each room is one tokio task, run_room, that owns the Room and the file. In multi-root mode, Collab keeps per-mount FileIds, Stamps, PathLocks and recovery::Store under one room registry and watcher. GET /api/collaboration/rooms lists the open rooms, with who is in each (a person or an agent) and what last changed; the apps' Journals list reads it |
recovery.rs |
Server-side recovery copies (<id>.ipynb and <id>.json in a private shared recovery dir, bounded to 20 per path and 200 MB per root) written when a room would otherwise lose edits: failed saves, a missing file, a read-only room, or a same-cell merge where disk won. Listed, read and discarded through /api/collaboration/recovery |
watch.rs |
Watches the file's parent directory, not the file, since saves by rename leave a file watch on the old inode |
room_lock.rs |
One server per machine owns a notebook's room, by an OS file lock in the runtime directory; embedded app servers take locks too, so the Mac app and a CLI server can't both edit one notebook. A second server's room is read-only until the owner closes |
execute.rs |
POST /api/kernels/{id}/execute: run cells by id and write outputs into the room, with who runs them (execution_by). Rechecks guarded source_hashes when each cell's turn comes and saves metadata.ganymede.ran_source_hash on every cell the server ran |
What a room's task does
- Load the notebook through
Contents, and record the file's hash. - Apply client updates (after
depth.rs) and broadcast them to the other connections. - Autosave one second after the last edit, with
If-Matchon the hash it last read or wrote, so it never overwrites a file that changed since. - Watch for outside changes: file events debounced by half a second, plus a poll every ten seconds (every second where there are no file events). A change whose hash is the room's own last save is ignored. Any other change is merged: a clean room just reloads; a room with unsaved edits keeps them, takes the disk's changes to other cells, and saves the merge.
- Close a minute after its last client leaves, saving first.
- Trust: the room signs the notebook when it saves, if every code cell's outputs came from a run on this server. Outputs read from an unsigned file stay untrusted until the cell runs again or someone trusts the notebook.
JupyterLab and ganymede-ui sync both ways over y-websocket. The MCP tools and the execute worker run inside the server and edit the room directly. Only the room's task touches the file, which is why two writers can't overwrite each other.
FlowAn edit in a room
- ganymede-ui's notebook pane (
src/lib/room.ts) sendsPUT /api/collaboration/session/{path}and gets the file id. - It opens the room websocket for
json:notebook:<fileId>withy-websocket, and syncs. - Typing in a cell produces a Yjs update.
collab.rshands the frame toRoom, which applies it and returns effects: the update for every other connection. - JupyterLab, or an agent following the room, gets the update and shows the edit.
- A second later the room task writes the notebook through
ganymede-contents, atomically, withIf-Match.
FlowRunning cells into a room
An agent or a Shortcut has no websocket, so it can't follow the room to see outputs. execute.rs solves that: the client posts cell ids and each cell's source hash (MurmurHash2, seed 0). The room checks every hash against the current source (409 source_mismatch if the cell changed since the client read it), clears the cells, marks them running and queues the batch, all in one step of its task. One worker per room runs the queue on the kernel through ganymede-exec and writes outputs into the room as they arrive, so they reach every client and the file even with no client connected. An optional wait returns the finished cells. A client can also leave out the hash and run whatever the room holds, name cells by tag, or send "cells": "all". The room resolves these in the same step as the checks, so a notebook with no cell ids on disk (nbformat 4.4) runs by the ids the room gave it, and an unknown id or tag refuses the whole batch.
While a cell runs, the room shows who runs it as execution_by: the caller's tailnet login, else the by name it sent, else "an API client"; a run through MCP shows the agent's name. Like execution_state, it lives only in the room and is never saved. A cell that runs on the server also saves metadata.ganymede.ran_source_hash (the hash of the source that ran, preserved even when a client echoes the server's outputs). A notebook that MCP's notebook_run_all ran top to bottom on a restarted kernel, with every cell succeeding and no edit while it ran, gets a metadata.ganymede.clean_run stamp (at, by, kernel, and a v1:… fingerprint over every cell's type and source in schema.rs) that is saved; the room removes a stamp when its fingerprint is missing or no longer fits the cells (room.rs).
The hash check is the pattern to recognize across the code: a writer names the version it read, and loses if someone else changed it. The host API's self.edit and self.delete use it too.
Chapter 7 of 14
The notebook as a program
Priority 1 is a notebook that takes parameters, returns named results, and can be run from anywhere: the CLI, HTTP, an app link or Shortcut, or another notebook. In code this is three pieces: a headless executor (ganymede-exec), one run function shared by every entry point (run.rs), and the host API that lets a kernel call back into the server under grants (ganymede-host plus host.rs). User docs: programs.md and host-api.md.
ganymede-exec (one 2,100-line file)
Ganymede's nbclient. It runs a notebook's code cells on a KernelSession and turns iopub messages into nbformat outputs, reproducing nbclient's defaults so a notebook executed here and by jupyter execute differ only in timestamps: display_id updates rewrite every matching output, clear_output(wait) clears on the next output, widget state lands in metadata.widgets, the raises-exception and skip-execution tags are honored. NotebookRun is used three ways: by ganymede execute (through ganymede-engine), by run.rs, and by the room's execute worker (chapter 6), which writes outputs into the room as they arrive.
The run contract
- Parameters in: a JSON object in the
GANYMEDE_PARAMSenvironment variable, recorded inmetadata.ganymede.params(ganymede-nbformat/params.rs). The kernel exposes it; cdp-kernel asjupyter.params. - Results out: outputs of type
application/vnd.ganymede.result+jsonholding{name, value}(results.rs). cdp-kernel writes them withjupyter.result(name, value). - Fresh kernel from the notebook's own kernelspec, top to bottom, then shut down.
- Read from the room when one is open, so unsaved edits run. Neither the notebook nor its room is written.
save: "copy"keeps the executed notebook underruns/<path>/<UTC time>.ipynb(or<mount>/runs/<rel>/<UTC time>.ipynbin multi-root mode, refusing read-only mounts with 403 before starting a kernel).
POST /api/notebooks/run and the host API's notebooks.run share run_notebook in run.rs; app links and Shortcuts call that endpoint on the app's own server. ganymede execute takes the same contract through ganymede-engine, which also wraps ganymede-exec.
Four doors, two code paths, one executor. Only the host API door checks the caller against a grant, because there the caller is a kernel; at the other doors it is a person or a token holder (and an app link asks the person the first time). Whatever the door, the run's own kernel gets the grant of the notebook it runs.
The host API
The problem it solves: code in a cell wants to read or run other notebooks, but giving a kernel the server's token would give it everything. Instead the server opens a comm (ganymede.host.v1) to each kernel and answers calls on it, checking what that kernel's notebook was granted. The kernel never holds a credential.
ganymede-host (about 800 lines) is the language-free transport. attach joins a KernelSession once the kernel answers, asks for a kernel subshell (protocol 5.5) so a cell that is awaiting a call still gets the reply, and opens the comm. Calls arrive as comm_msg on iopub ({id, method, params}); replies go back on the subshell. HostLink::is_host_message lets the bridge hide this traffic from other clients. The crate knows no method but hello; a Responder answers the rest. A kernel that doesn't support subshells gets no comm, because an awaited call could never be answered.
host.rs in the server is the Responder: notebooks.list, read, search, results, run, and self.add, self.edit, self.delete on the kernel's own notebook through its room. These share code with the MCP tools: the tools render answers as text for a model, the host API returns JSON.
Grants
A grant says what a notebook's kernel may ask for: read paths, run paths, and edit_self. Defaults come from [host] in the config (read the whole root, edit itself, run nothing). Per-notebook grants are stored by file id in the file id database (per mount in multi-root mode, keeping standalone ganymede grant entries confined to their own mount via GrantPath), so they follow a rename; they're set with ganymede grant or the apps' Notebook Access sheet, never by the notebook itself. A file replaced outside Ganymede (git, Finder, sync) keeps its path's file id, so each grant also carries a stamp of its file (size, mtime and, on Unix, inode): a checked read drops the grant when the file no longer matches. The server's own saves restamp it through stamping.rs, which wraps Contents and also fires pre-rename pending, wrote and cancelled notifications to write_observer.rs; renaming or deleting a folder moves or drops the grants inside it. A notebook can list what it wants in metadata.ganymede.host.wants, which a client shows but which grants nothing.
The security rule worth remembering: grants only narrow. A notebook run from another gets the intersection of its own grant and every caller's up the chain. Runs nest at most 3 deep and each kernel has at most 2 runs in flight. Paths are matched by whole segments after symlinks are resolved, and in multi-root mode symlinks cannot cross from one mount into another.
FlowA notebook running another notebook
- A cell calls
await jupyter.host()and thenhost.notebooks.run({path, params}). cdp-kernel (runtime/host.mjs) sends acomm_msgwith{id, method: "notebooks.run", params}. - The kernel manager's fan-out spots it as host traffic (
ganymede-host) and hands it to the responder instead of the clients. host.rsfinds the kernel's notebook (SessionManager::notebook_of_kernel, then its file id), loads that notebook's grant, and checksrunagainst the target path.- It calls
run_notebook(run.rs), which starts a fresh kernel withGANYMEDE_PARAMSset and a launch variable naming the run, so the inner kernel's own grant is the intersection. ganymede-execruns the target top to bottom;named_resultscollects its results.- The reply
{path, status, results}goes back on the caller's subshell, and the awaiting cell resumes.
Chapter 8 of 14
Agent-native: an agent in the same live notebook
Priority 3 is a person and an agent working in one live notebook. The server makes this possible by exposing notebooks to agents over the Model Context Protocol (MCP), with tools that edit the same room (chapter 6) a person has open in the app or JupyterLab. Nothing is a separate copy: the agent's cells appear live, the person's edits are visible to the agent, and the room saves both.
The pieces
| Piece | Where | What it does |
|---|---|---|
| MCP tools | ganymede-server/src/mcp.rs (4,400 lines) |
16 tools, served at /mcp (streamable HTTP) when the server runs with --mcp, across single-root and multi-root mounts. Takes the server token, or mcp_token, a token that opens /mcp and no other route. Supports both legacy Mcp-Session-Id sessions and sessionless MCP 2026-07-28 (server/discover) clients, keeping bounded, TTL-expiring per-client state (open notebook, room holds, read marks, client name, connection folder) scoped by auth principal and reaped after an hour idle |
| Read marks | mcp/marks.rs |
Per client, per notebook: the cells as the agent last saw them. notebook_read(since) lists what others changed or ran since, and who |
| Room edits | room_ops.rs |
Add, edit and delete cells in a room, with provenance and history. Shared by the MCP tools, the execute endpoint and the host API's self.* calls |
| Search, snapshot | mcp/search.rs, mcp/snapshot.rs |
notebooks_search across notebooks (and across mounts in multi-root mode); cell_snapshot, a cell as Markdown with images as files and tables as Markdown tables |
| Skills extension | mcp/skills.rs |
Serves the journal plugin's skills (journal, page-style) over MCP's Skills extension (io.modelcontextprotocol/skills, skill:// URIs), embedded at build time so clients supporting the extension load them from ganymede mcp without installing the plugin |
| Tool reference | mcp/reference.rs |
Generates docs/mcp-tools.md from the tools' own schemas; a test fails if the page drifts |
| stdio bridge | ganymede-cli/src/mcp.rs, attach.rs |
ganymede mcp: finds a running server covering the current folder (single-root or mounted) via attach.rs and forwards JSON-RPC to its /mcp, or starts one in-process. mcp call runs one tool for scripts and hooks; mcp watch prints a line for each new request a person writes to the agent, reusing one MCP session across its polls (on main, after 0.19.1) |
| Journal plugin | plugins/ganymede-journal/ |
A Claude Code plugin: the journal and page-style skills, hooks, a monitor that runs mcp watch, and a reviewer agent |
The tools: notebook_open, notebook_read, notebook_requests, notebooks_list, notebooks_search, notebook_run_all, notebook_publish, cell_add, cell_edit, cell_move, cell_delete, cell_run, cell_clear_outputs, cell_snapshot, kernel_control, kernelspecs_list.
Design choices visible in the code
- Output for a model, not a browser. Answers use nb-cli's format: an
@@cellline with index, id and type, the source, then an@@outputline per output as plain text. HTML is stripped, ANSI colors removed, tracebacks trimmed, and output over 4,000 characters goes to a file named by its sha256, whose path is returned instead. - Provenance. Cells an agent writes carry
metadata.ganymede.agent = {by, mode, at}, wheremodeisexecuted(ran in the kernel),recorded(a step that ran elsewhere, such as a shell command) ornote.cell_editkeeps the replaced source in ahistory. Onmain, a notebook thatnotebook_opencreates also carriesmetadata.ganymede.journal = true, so frontends open it as a journal before the first agent cell lands. - Scratch runs.
cell_runwithrecord: falseruns in the kernel, sharing its state, and leaves nothing in the notebook. - Cells by id, never by index, so concurrent edits don't shift the target.
- One set of room edits. The tools, the execute endpoint and the host API's
self.*calls (chapter 7) all edit cells throughroom_ops.rs, so they can't drift. The tools render text; the host API returns JSON.
How the agent hears about a person's edits
The room records who last changed each cell (Author in room.rs, kept in memory, not in the file): the name a client sent in its awareness state (the Mac app sends the person's full name, JupyterLab its user name), a tailnet login (chapter 5), or a name the server's caller gives for its own edits. Four mechanisms build on that:
- A pointer on every reply. When others changed or ran cells since the agent's read mark, the tool's reply ends with an
@@changedline naming who. The agent callsnotebook_read(since)for the detail. - The edit check.
cell_edit,cell_deleteandcell_moverefuse a cell someone else changed since the agent last read it, so an agent can't overwrite text it never saw. - Request cells. A Markdown cell a person writes starting
@agent(or@claudefor Claude Code) is a request.notebook_requestslists the open ones;cell_addwithanswersputs the answer below the request and marks it done, in one room edit. - Waking an idle agent.
ganymede mcp watchprints a line for each new request, and the journal plugin runs it as a Claude Code monitor, so a request reaches the agent between turns. A spike,mcp watch --edits(off unlessGANYMEDE_WATCH_EDITSis set), wakes it on any edit once edits settle.
The journal plugin
The plugin makes Claude Code keep its analysis as a notebook. Its hooks (hooks/journal.mjs) run at four points: SessionStart reports the server; UserPromptSubmit asks for cells others changed since the agent's read mark and hands them over with the person's message; PostToolUse follows the agent's notebook tools, passes on the changes an @@changed line points to (so the agent sees a person's edit mid-turn), and records marked Bash steps as recorded cells; Stop checks the journal re-runs cleanly before the agent stops. Its monitor (monitors/monitors.json) runs ganymede mcp watch once the journal skill is in use.
FlowAn agent editing the notebook a person has open
- The person has
journal/2026-11-13-x.ipynbopen in the Mac app, so its room exists and the app is synced to it. - Claude Code calls
cell_runthroughganymede mcp, which forwards it to the app's server at/mcp. The Mac app always writes a0600server info file while running (AppMCP.swift); with MCP turned on in Settings, that file carries themcp_tokenthat opens only/mcp(the app's page token is never written to disk). The setting can also limit agents to reading, or to editing without running. mcp.rsadds a code cell to the room with agent metadata, then runs it through the room's execute queue (chapter 6). The new cell and its outputs reach the person's view as they arrive.- The person edits a cell. The room broadcasts the update and credits it to the person, by the name the app sent in its awareness.
- The agent's next tool reply ends with an
@@changedline naming the person. The plugin'sPostToolUsehook callsnotebook_read(since=<mark>),marks.rsdiffs the notebook against the mark, and the agent gets the change mid-turn. Had it triedcell_editon that cell first, the edit would have been refused. - When the agent is idle, the person writes an
@claudecell instead.mcp watchreports it through the plugin's monitor, and the agent answers withcell_add(answers=<id>).
The agent's edits reach the person at once through the room. The person's edits reach the agent on the dashed path: as an @@changed pointer on its next tool reply while it works, or through mcp watch when a request arrives while it is idle.
The design and the choices behind it are in docs/live-agent-edits.md (tracking issue #763). Still open there: whether waking on any edit stays (the spike, decided in #795), an "Ask the agent" button, and an agent cursor in the notebook.
Chapter 9 of 14
CLI and embedding: three ways to use the core
The core is packaged three ways: a command-line binary for people and scripts (ganymede-cli), a Rust library for programs that want kernels without a server (ganymede-engine), and a C library that runs the whole server inside an app (ganymede-ffi).
ganymede-cli (about 19,000 lines)
main.rs defines the clap subcommands and handles the small ones itself. The larger ones have their own files.
| Command | File | What it does |
|---|---|---|
serve, lab |
ganymede-server::serve, attach.rs, lab.rs, lab_start.rs |
Run the server (default root ~, or named mounts with --mount / --multi-root), or attach to an already-running compatible server covering the target folder after checking its 0600 info file, loopback URL and live PID; lab also serves JupyterLab |
lab install |
lab/pypi.rs, lab/extension.rs |
Downloads JupyterLab's wheel and prebuilt extensions from PyPI and unpacks them, with no Python |
ui |
ui.rs, attach.rs |
Installs and serves a ganymede-ui release, or attaches to a running Ganymede server covering the folder |
execute |
main.rs |
Runs a notebook headless (jupyter execute), with -p parameters and --results; answers host API calls through serve::LocalHost |
run, console, kernel, attach, kernelspec |
main.rs, console.rs |
Run code or a REPL on a kernel; start a standalone kernel; manage kernelspecs |
nb clear, nb publish |
main.rs, render.rs |
Clear outputs; publish one HTML page (chapter 2's html.rs) |
mcp, mcp call, mcp watch |
mcp.rs |
The stdio MCP bridge; one tool call for scripts and hooks; a line per new request to the agent (chapter 8) |
grant, trust |
grant.rs, main.rs |
Host API grants (chapter 7); notebook trust |
update, info |
update.rs, info.rs |
Self-update from GitHub releases; versions and every directory Ganymede reads or writes |
crash.rs |
Opt-in crash reports to Sentry, with no notebook content |
ganymede-engine (about 1,100 lines)
A facade for Rust programs: Engine::new() finds kernelspecs and starts, attaches to or adopts kernels; Kernel executes with streaming output and stdin, completes, inspects, interrupts, restarts and runs notebooks with nbclient's semantics. It re-exports protocol, nbformat, host and exec for anything the facade doesn't cover. ganymede execute is built on it. docs/embedding.md is its guide.
ganymede-ffi (about 2,700 lines)
The C ABI the Apple apps link. The whole surface is in include/ganymede.h:
| Function | Purpose |
|---|---|
ganymede_server_start(config_json, &error) |
Start the server on loopback, with the config as JSON (the keys of ganymede.toml, including mounts for multi-root mode). Runs on its own thread with its own tokio runtime, so the app needs no Rust or async code |
ganymede_server_url, ganymede_server_stop |
Get the URL to load; stop on quit |
ganymede_server_add_machine, _remove_machine, _machines |
Mount another Ganymede server under /machines/{id}/ with its URL and token, unmount it (its waiting requests end with a 502), and list what is mounted. The apps' connected machines (chapter 12) and the Mac's background server routing use these; chapter 5's mount.rs serves them |
ganymede_server_add_mount, _remove_mount, _mounts |
Attach and detach named local folders at runtime on a multi-root server without disturbing other mounts. Detach hides the mount (404), flushes dirty rooms (writing recovery copies on save failure), shuts down its sessions, kernels and terminals, drains writes and runs, and blocks until done so iOS callers can safely release security-scoped access; chapter 5's mounts.rs coordinates them |
ganymede_server_set_write_observer, _set_write_callbacks |
Notifies the app of each save of a local file under the server's root (a REST save, a room's autosave, a run, MCP, a checkpoint restore), with the file's stamp before and after. _set_write_callbacks adds a pre-rename pending callback (with the temp file's stamp before it lands) plus wrote and cancelled, closing the race where the app checks a file between rename and post-write restamping |
ganymede_config_read, ganymede_config_set |
Read ganymede.toml as JSON and apply JSON patches atomically at 0600 via toml_edit (keeping comments and order, rejecting invalid configs), with no server needed: how the Mac app and ganymede serve share one config file |
ganymede_kernel_register, _deliver, _ended |
Register a kernel the app runs itself (the hidden web view's cdp-kernel), push its messages to the server, and report its end. These drive registered.rs from chapter 3 |
ganymede_set_panic_callback |
Lets the app's crash reporter see Rust panics |
ganymede_string_free |
Strings returned to the app are freed here |
scripts/build-xcframework.sh builds it for macOS and iOS. The iOS slices are built without the zmq and subprocess features, since iOS can't launch processes; there the server lists only registered kernels and gateway kernels.
The apps were first planned around a message bridge in place of HTTP, which is why ganymede-api has no HTTP in it. Running the ordinary server on loopback turned out simpler: the web view connects to it as a browser would, so the web app has one code path everywhere.
Chapter 10 of 14
cdp-kernel: the TypeScript kernel
cdp-kernel is a Jupyter kernel for TypeScript and JavaScript, about 17,000 lines across src/ and runtime/. It started as an extraction of Deno's own Jupyter kernel, which is two halves joined by a handful of calls: the Jupyter protocol in plain JS, and a REPL isolate driven over the Chrome DevTools Protocol (CDP). cdp-kernel keeps that split and points the CDP half at other runtimes' --inspect endpoint. That is the name: the kernel drives a runtime over CDP. It is a separate process from the Rust core and knows nothing about Ganymede beyond the standard protocol, plus two optional extras (jupyter.host() and jupyter.params).
The two halves
The kernel (the cdp-kernel kernel process, src/kernel.ts):
| File | What it does |
|---|---|
zmtp.ts, wire.ts, zmq-channels.ts |
Just enough ZMTP 3.0 over node:net to be a ZeroMQ peer with no libzmq, plus framing and HMAC. Ported from Deno |
kernel-core.ts (1,200 lines) |
All Jupyter message handling: execute, complete, inspect, history, comms, interrupt (tagging stderr notices with cdp_kernel.state_reset metadata whenever an interrupt or runtime exit resets the target's state). Imports nothing from Node, so it also runs in a web page |
target-api.ts |
KernelTarget: what the core needs from a runtime. The seam between the halves |
language-service.ts |
Typed completion and hover from a TypeScript language service in a worker thread, started on first use, with a time budget per request. The same service answers two comms for frontends: type errors as you type (cdp-kernel.diagnostics.v1) and signature help, go to definition and rename (cdp-kernel.language.v1). TypeScript itself is found or installed on first use, not shipped in the package. The request handling on both sides (language-client.ts, the kernel's; language-server.ts, the worker's) has no Node imports, so the browser build runs it too |
debugger.ts |
JupyterLab's visual debugger: DAP requests arrive as debug_request and are translated to V8's Debugger domain on Node and Deno. On main, runtime/variables.mjs builds the variables view without running getters (expanding Map and Set, with paging, filter and sort), and evaluate can run read-only under V8's side-effect check |
The target runtime, where cells actually run, is one of five:
| Runtime | How it is driven | File |
|---|---|---|
| Node, Deno | Launched with --inspect running runtime/bootstrap.mjs; driven over CDP with Runtime.evaluate in replMode |
target.ts, cdp.ts |
| Bun | Bun's inspector lacks replMode, so cells go over a private pipe to runtime/bun-channel.mjs |
bun-target.ts |
| workerd | Cells run in a driver Worker over one WebSocket session, so I/O objects survive between cells | workerd-target.ts, runtime/workerd-worker.mjs |
| celld | The same driver Worker, over a token-guarded loopback WebSocket | celld-target.ts |
| Browser | kernel-core.ts on the page, cells in a Web Worker. Published as @tlockney/cdp-kernel/browser; this is what ganymede-ui and the apps run. A page can map import specifiers to files it serves (the modules option), which is how the apps draw charts and run SQL offline. With the typescript option, the language service runs in a Web Worker of its own (browser/language-worker.ts), loading TypeScript and its lib files from URLs the page serves and fetching imported packages' .d.ts declarations, kept in IndexedDB for offline use (browser/package-types.ts) |
src/browser/, runtime/browser-worker.mjs |
The same kernel-core.ts serves every runtime; only the KernelTarget behind it changes. In the browser build there is no ZeroMQ at all: the page talks to the core directly.
The cell pipeline
A cell is written as a TypeScript module, but CDP evaluates scripts. transform.ts closes the gap, as Deno's REPL does with swc:
- A type stripper (esbuild by default, sucrase as an option) removes types and compiles JSX, keeping a source map.
- acorn finds module syntax a script can't hold and rewrites it:
import x from "m"becomesvar x = await __cdpk.import("m"), andexportis dropped, without moving lines. - Node and Deno run the result with
Runtime.evaluateinreplMode, so top-levelawaitand redeclaredletwork. Bun, workerd and celld have noreplMode, so the cell runs inside an async function with its top-level names hoisted to globals. - Imports resolve when
__cdpk.importruns, differently per runtime: on Node, a resolve hook (runtime/node-hooks.mjs) re-parents imports to the notebook's folder, installsnpm:andjsr:packages on first use (each package alias in its own cache directory, onmainafter 0.17.0), and serializescdp-kernel.lock.jsonwrites across npm and Bun installers; Deno uses its own resolution; workerd and celld can't load modules at runtime, so the kernel bundles a cell's imports with esbuild and sends the bundle with the cell. - The last expression's value comes back as
execute_result; the source map lets tracebacks and the debugger point at the cell's own lines.
Inside the runtime: jupyter.*
The runtime/ modules are injected into the target and give cell code its API:
| Module | Gives cells |
|---|---|
display.mjs |
jupyter.display, rich output by MIME type, jupyter.params, jupyter.result (port of Deno's Deno.jupyter), jupyter.version and jupyter.runtime (the cdp-kernel version and the runtime running the cell) |
comm.mjs, widget.mjs |
Comms and anywidget-style widgets |
host.mjs |
jupyter.host(), the client for Ganymede's host API (chapter 7) |
table.mjs, sql.mjs, chart.mjs |
jupyter.table (rows, Arrow, Polars or DuckDB results as a table output), jupyter.sql (a DuckDB tag; in a browser worker it fails cleanly instead of hanging if DuckDB's worker cannot load) and jupyter.chart (Vega-Lite or Plot as one SVG), all standard MIME types |
table-paging.mjs |
Keeps the last 16 tables shown and answers page and sort requests past the embedded rows over the comm ganymede.table.v1 |
deno-compat.mjs |
A Deno namespace on Node, for notebooks written for Deno's kernel |
FlowA TypeScript cell on Node
- Ganymede launches
cdp-kernel kernel --runtime node --conn <file>from the kernelspeccdp-kernel installwrote. That kernelspec points at a copy of the kernel in the Jupyter data directory and at the Node version manager's shim rather than one Node binary, so it survives a Node upgrade (--pinkeeps the exact binary). kernel.tsbinds the five ports withzmtp.ts, startsnode --inspect=127.0.0.1:0 runtime/bootstrap.mjs, and connectscdp.tsto its inspector WebSocket.- An
execute_requestreacheskernel-core.ts, which hands the code totransform.tsand thentarget.ts. target.tscallsRuntime.evaluate. Output fromconsole.logandjupyter.displaycomes back over the runtime's stdout as records the kernel turns into iopub messages.- The core sends
execute_result,execute_replyandstatus: idle.
Chapter 11 of 14
ganymede-ui: the web app
The web app in ganymede-ui's src/ is the notebook people see in a browser and inside every Apple app window. It is React around JupyterLab's notebook packages, used as plain libraries with no JupyterLab application. It reaches notebooks and kernels only through @jupyterlab/services, the client half of the Jupyter API, so it is an ordinary API client of Ganymede and works against jupyter_server too. ganymede-ui's architecture page is long and current; this chapter is the map into it.
Code map
| Area | Files | What it does |
|---|---|---|
| Shell & styling | App.tsx (1,650 lines), components/, styles/app.css, styles/jupyter.css |
Sidebar, toolbar, command palette, update notice (UpdateNotice.tsx), sheets (connect, settings, shortcuts, publish, notebook access, run with parameters, unsaved-changes guard). Color tokens in the app icon's palette (checked by contrast.test.ts) style code cells as cards with a margin run button, quiet selection ring, recessed output well and red error rail, while Markdown cells read as borderless prose |
| Notebook | components/NotebookPane.tsx (2,900), lib/jupyterlab.ts, lib/widgets.ts, components/ExpandedView.tsx |
One file: JupyterLab's Notebook widget, its model and a SessionContext. Rejoins a running kernel but starts none until the first run; notices interrupt state resets (lib/state-reset.ts), routes Edit-mode undo/redo through Yjs, draws the notebook's page-eyebrow above the first cell in the Apple apps, and opens long source or table outputs in an expanded view |
| Backends | lib/backends.ts, lib/lite.ts, lib/mixed.ts, lib/cdp-kernel.ts, lib/kernel-place.ts, lib/kernel-workers.ts |
Build the one ServiceManager the UI talks to, report where each kernel runs (local or remote gateway) and when a remote isn't answering, and track/terminate Web Workers cleanly on shutdown |
| Saving & recovery | lib/saver.ts, lib/room.ts, lib/room-recovery.ts, lib/local-recovery.ts, lib/room-readonly.ts, components/RecoverySheet.tsx |
NotebookSaver for plain servers; NotebookRoom and RoomSaver on Ganymede (sending the person's name in awareness, showing rooms owned by another server or offline as read-only). Surfaces server recovery copies (/api/collaboration/recovery) and keeps bounded per-origin IndexedDB local snapshots (10 MiB per notebook, 50 MiB total) so unsaved edits survive offline reloads and WebKit process termination |
| Service-worker relay | lib/lite-sw.ts, public/lite-service-worker.js |
Lets an in-page kernel's Worker make synchronous requests (file reads, input()) answered by the page |
| Apple bridges | lib/native.ts, lib/kernel-relay.ts, kernel-host.ts, lib/device-remote.ts |
The page's side of the Swift app (chapter 12) |
| Output | lib/output-frames.ts, lib/table-output.ts, lib/anywidget.ts, lib/sanitizer tests |
Sandboxed HTML outputs; the table renderer, which pages and sorts through the kernel past the embedded rows; widgets |
| Kernel modules & SQL | scripts/kernel-modules.ts, lib/kernel-modules.ts, lib/duckdb-files.ts, lib/sql-files.ts, lib/sql-preload.ts |
Bundles the chart libraries and DuckDB's module for the in-page kernel and fetches DuckDB's wasm lazily on first use into Cache Storage so charts and SQL work offline. sql-preload.ts and sql-files.ts let browser and in-app kernels load local data files in jupyter.sql / jupyter.sql.load by fetching file bytes from the active backend over a subshell comm |
| Editing | lib/kernel-comm.ts, lib/type-errors.ts, lib/language-service.ts, lib/language-editor.ts, lib/markdown-preview.ts, lib/markdown-preview-render.ts |
Type errors as you type, signature help, go to definition and rename in TypeScript cells, each over a comm cdp-kernel's language service answers (chapter 10), opened once per kernel and again after a restart; a kernel that doesn't answer closes them and nothing shows. The in-app and browser kernels answer too, from TypeScript 6 shipped with the app and loaded in a Worker of its own on first use (lib/kernel-typescript.ts), including cdp-kernel's cached package types. Live Markdown preview renders full Markdown constructs (headings, emphasis, links, images, lists, block quotes, fenced highlighted code, tables, MathJax, safe inline HTML, rules) as CodeMirror decorations while keeping the raw text untouched (off by default, toggled from the Command Palette or the Mac View menu) |
| Data files | components/DataPane.tsx, lib/data-files.ts, lib/data-read.ts, lib/parquet.ts, components/DuckdbConsole.tsx, lib/duckdb-console.ts |
CSV and TSV open as a table (the table renderer), JSON as a tree, Parquet through DuckDB wasm, in the notebook's place. The DuckDB console is a SQL prompt that opens in the same place, on the DuckDB wasm build a notebook's SQL uses, in a worker of its own; it reads the files a statement names and can export the session to a notebook |
| Journal view | components/JournalView.tsx, lib/journal.ts, lib/journals.ts |
A notebook an agent keeps, read as a lab notebook and followed live from the open notebook's own room model: cells are read-only, provenance comes from metadata.ganymede.agent (chapter 8), fresh-kernel runs show a badge from clean_run, live runs show the execution_by runner line, and a composer at the bottom writes a note or an @agent request (read-only while offline). journals.ts lists a place's journals from GET /api/collaboration/rooms |
| Places | lib/places.ts |
This device or a connected machine, reached through the app's server mount (/machines/{id}/). The page only checks whether a machine answers; the app's native menus switch places |
| Small features | about 60 more files in lib/ |
Shortcuts, palette, search, outline, recents, publish, export, theme, run status, problems, update checks, save guards, each with its test file |
Backends
Everything above the backend sees one ServiceManager. connect(config) in backends.ts builds it three ways:
ganymede: the stockServiceManagerover REST and websockets to a server. The normal case, including inside the apps.ganymedewithkernels: 'page': notebooks on the server, kernels in this page. For a server with no kernels of its own.browser: everything in the page through JupyterLite's@jupyterlite/services, wired by hand inlite.ts. Notebooks in IndexedDB, kernels in Web Workers: cdp-kernel's browser build by default, with a fake websocket (mock-socket). Onmainthe browser build also bundles a Pyodide Python kernel (lib/pyodide-kernel.ts, JupyterLite's Pyodide kernel in a Worker, with aSharedArrayBufferinterrupt when the page is cross-origin isolated and package installs from the internet off unless the person turns them on).
A ganymede backend can also point at a stock Jupyter server on main: lib/server-capabilities.ts probes what the server offers (rooms, Ganymede's own routes) and the UI turns off what it lacks.
Which backend: ?token= or ?kernels= in the URL (how the apps launch it), then the saved connection, then the page's own server's login cookie. With none of these, a first open shows a start screen: Try a Notebook (a sample in this browser), Open a Notebook… and Connect to a Server…, which opens the connect sheet. A saved connection that fails opens the connect sheet with its error.
Saving: two paths
Against a plain Jupyter server, NotebookSaver does what JupyterLab's document context does: one save at a time, last_modified checked before writing, autosave every 120 seconds, a check for outside changes every 5 seconds that locks the pane on conflict (or quietly pulls the new file when there are no local edits).
Against Ganymede, the pane joins the notebook's room instead (room.ts, chapter 6). The notebook model is built on the room's YNotebook, edits flow both ways live, and the server saves. The pane skips its disk checks and autosave, while keeping bounded IndexedDB snapshots (local-recovery.ts) and surfacing server recovery copies (room-recovery.ts) if a save or merge ever needs attention. This switch is why the apps and an agent can share a notebook.
FlowOpening a notebook (browser, Ganymede backend)
App.tsxreads?open=<path>(lib/launch.ts), connects the backend and shows the sidebar's folder.NotebookPanemounts for the path. On Ganymede,NotebookRoom.joincallsPUT /api/collaboration/session/{path}, opens the room websocket and waits for first sync.- JupyterLab's notebook widget renders the room's model. Output renderers come from
jupyterlab.ts; HTML outputs go into sandboxed frames. SessionContextlooks for a kernel already running for the file and rejoins it. If none, the toolbar says the kernel starts when you run a cell.- The first run starts the kernel the file names (
POST /api/sessions), and outputs arrive over the kernel websocket as in chapter 5.
packages/agent
An optional agent built on Pi Durable, off by default, turned on in Settings. settings.ts keeps provider, model and keys (keys in the Keychain in the apps); models.ts loads Anthropic, OpenAI, Google, an external OpenAI-compatible server or a local one on demand. On ganymede-ui's main, controller.ts wraps one Pi Durable session per open notebook and hands plain snapshots to both the browser's AgentPanel.tsx and the Apple apps' inspector tab (AgentInspector.swift). tools.ts gives it notebook reading, cell edits proposed for Accept or Reject (lib/cell-proposals.ts), kernel execution, file tools confined to the workspace folder (lib/agent-workspace.ts) and a shell over /api/terminals; execution, shell commands and file writes wait for the person's approval.
Chapter 12 of 14
The Apple apps
The Mac, iPad and iPhone apps are one SwiftUI codebase in ganymede-ui's apple/ (about 53,000 lines of Swift, built with XcodeGen from project.yml). Each app runs the Rust server inside its own process through ganymede-ffi (or, on the Mac when Background Server is enabled, routes local notebooks through a verified LaunchAgent running the bundled ganymede binary), loads the web app from it in a WKWebView, and draws its own native chrome around the notebook. The page shows only the notebook; Swift draws the sidebar, toolbar, tabs, status bar and menus. Priority 2, the apps as a full runtime, lives here.
Code map (apple/Sources/Ganymede/)
| Area | Files | What it does |
|---|---|---|
| Server & shared config | ServerHost.swift, AppModel.swift, SharedConfig.swift, LoginShell.swift |
Starts the embedded server through the ffi on 127.0.0.1 with a random token, reusing the last port so the page keeps its origin and registering pending, wrote and cancelled write callbacks to close the file-stamp race. On the Mac it serves /, always writes a 0600 jpserver-<pid>.json info file (with mcp_token when MCP is on, never the page token), and reads and updates shared server settings in ganymede.toml through ganymede_config_read and ganymede_config_set (SharedConfig.swift); on iOS it serves the chosen folder. Takes PATH from the login shell so node, deno and python3 kernelspecs start |
| Background server & This Mac | BackgroundServer.swift, BackgroundServerRouting.swift, ThisMacChecks.swift, ThisMacVerifier.swift, MenuBar.swift |
Optional Mac LaunchAgent (SMAppService, off by default) running the bundled Contents/Helpers/ganymede with login-shell PATH and log_file so kernels and rooms stay alive between launches. ThisMacVerifier validates local jpserver-<pid>.json files by PID, code signature (team ID and helper identifier) and listening socket (skipping the app's own ganymede_app file); when verified, BackgroundServerRouting mounts it as this-mac on the embedded server and routes local notebooks and tailnet sharing through it, falling back with a notice if unavailable. MenuBar.swift adds a Mac menu bar extra with server status, kernel controls and recent executions |
| Page & tabs | WebView.swift, PageModel.swift, PageState.swift, DocumentWindow.swift, PersonName.swift, Tabs/ |
Unified per-tab PageModel loading the web app with ?open=, ?kernels= and chrome=native, exchanging state and commands with Swift, and sending the person's name for the room. On macOS, Tabs/ (WorkspaceTabStrip.swift, WorkspaceTabHost.swift, WorkspaceTabStore.swift, TabOverviewOverlay.swift) provides the custom Mac tab strip with drag-reorder, cross-window tab handoff, ⇧⌘\ tab overview and a ZStack host that keeps each tab's web view, editor and terminal alive |
| Native chrome | NativeChrome.swift, NavigatorSidebar.swift, SidebarStyle.swift, FindFocus.swift, StatusBar.swift, IPadChrome.swift, Touch/, Inspector.swift, BottomPanel.swift |
Mac: redesigned toolbar (display title, kernel button, view picker, run group, Share), navy glass / warm cream sidebar with app mark, tab capsule, project foot and unified Find tab (outline + search with verified AppKit focus), slim status bar (save state, kernel version, memory), inspector, bottom panel and menus, colored from Assets.xcassets colorsets matching the web tokens. iPad & iPhone: Touch/ (IPadSidebarChrome.swift, IPadTabStrip.swift, PhoneHeader.swift, PhoneBottomBar.swift, PhoneOutlineSheet.swift) redraws the iPad sidebar (on main with the Mac's single Find tab), touch tabs (on main each tab has its own web view, at most four live at once, with the least recently used hibernated past that or on a memory warning) and Split View, and the iPhone header, single floating glass bottom bar and outline sheet |
| In-app kernels | AppKernels.swift, KernelHost.swift, KernelProviderClient.swift |
cdp-kernel, and on main also Pyodide, in one hidden web view (kernel.html), registered in-process with the embedded server and, on the Mac, over the background server's kernel provider socket (reserving cdp-browser, and on main python, to this signed app's code-signature requirement). Routes device prompts back to the asking tab |
| Remotes | Remote.swift, RemotesView.swift, KernelLocationPicker.swift |
Other servers for kernels and terminals (with optional per-remote start folder, room-name sharing and opt-in device-API access); tokens in the Keychain, or none for a server on the tailnet. On main, a machine can also be reached over an SSH tunnel (MacSSHTunnelConnector.swift, IOSSSHTunnelConnector.swift) |
| Connected machines | Place.swift, PlaceReachability.swift, MachineWindow.swift, FileSource.swift, Journals.swift |
A window's place: this device, This Mac (the verified background server), or a remote machine (a Remote with a server URL) that the app's server mounts with ganymede_server_add_machine (chapter 9). The place switcher shows a dot for reachable or offline. The native sidebar lists files through a FileSource, the disk or the machine's contents API through the mount, and the Journals tab lists from the machine's open rooms. A machine's window has the same native chrome as this device's, including terminals on that machine, the text editor, Notebook Access, app links, agent keys and opt-in device API |
| Command line tool | CommandLineTool.swift |
Mac: the ganymede CLI bundled in Contents/Helpers, and the link Settings makes to it at ~/.local/bin/ganymede |
| Tailnet | AppTailnet.swift |
Mac, off by default: shares the app's server (or the background server via [tailscale] in ganymede.toml when Background Server is on) on the tailnet through tailscale serve, letting listed logins in without the token; lists tailnet devices for the remote picker |
| Automation | AppURL.swift, AppURLHandler.swift, NotebookActions.swift, NotebookIntents.swift, SpotlightIndex.swift, AppMCP.swift |
ganymede:// links (on iPad and iPhone open, in folders the person granted, and on main also settings; LinkOpener.swift), Shortcuts actions (on the Mac; on main also on iPad and iPhone, with kept permissions under Settings › Shortcuts Permissions), Spotlight, the MCP setting, which gives agents an mcp_token |
| Tools | Terminal/, Editor/, Runner/ |
Terminals (local process, Jupyter terminal, SSH, including Tailscale SSH sign-in on iPad and iPhone), movable between the bottom panel and a tab; a code editor for non-notebook files (local and connected machines); Run Script on Device (experimental) |
| Lifecycle | AppUpdater.swift, UpdateFeed.swift, CrashReports.swift, CrashScrub.swift |
Sparkle updates on the Mac (stable Releases by default, plus an opt-in Bleeding edge channel following main-build with hourly checks); opt-in Sentry crash reports, scrubbed in the app |
Other targets: Sources/QuickLook (notebook previews and thumbnails in Finder), Sources/Share (share extension, experimental, off by default), Sources/Widgets (notebook widgets for the home screen and the Mac desktop, and on main the iPhone and iPad lock screen, experimental).
The notebook page talks to the server exactly as a browser would. Swift sits between the hidden kernel web view and the server, carrying kernel messages through the ffi. When the optional Background Server is turned on on the Mac, local notebooks route through that verified LaunchAgent process instead (mounted under /machines/this-mac/), and KernelProviderClient.swift registers the hidden web view's kernels with it over the kernel provider socket. On iPad and iPhone the kernel processes box is gone: only in-app and remote kernels remain.
In-app kernels
iOS won't let an app launch processes, and the Mac app wants a TypeScript kernel that needs no Node install. So the app runs cdp-kernel's browser build in one hidden web view (kernel.html, src/kernel-host.ts), one browser kernel per kernel the server starts. On ganymede-ui's main the same page also runs a Python kernel, python, on Pyodide (lib/pyodide-host.ts): the embedded server's static_headers make kernel.html cross-origin isolated, so Pyodide can interrupt through SharedArrayBuffer, and it reads the notebook folder through a confined contents API that never stores the login cookie. AppKernels.swift registers them through ganymede_kernel_register (chapter 9), and on the Mac KernelProviderClient.swift also registers them over a verified background server's Unix provider socket, so they show up in the server's kernel list and work with sessions, rooms and the execute endpoint like any other kernel. Messages travel server → Swift → kernel page, and back through the kernelHost message handler (src/lib/kernel-relay.ts has the diagram in its header). Because the kernel runs in its own web view, it survives a window reload, and only it gets the device bridge: no output rendered in the notebook page can reach native APIs.
A native in-app V8 engine was tried and set aside (2026-11-20, ganymede-ui#765): on the Mac and the iPhone, jitless V8 ran the benchmarks 2 to 8 times slower than the web view's Worker and added about 7 MB to the download. The in-app kernel stays on the web view, and the spike stays in spikes/v8-engine in ganymede.
packages/device: the device API
packages/device (until 2026-11-13 the ganymede-device repo) gives cells a device global: await device.clipboard.readText(), haptics, dialogs, share sheet, file and photo pickers, Quick Look, and more. The TypeScript side (src/) is a preload installed in the cells' Worker; it sends calls over a comm or webkit.messageHandlers.device to the Swift DeviceBridge (swift/Sources), which checks a permission ledger and answers. Calls from a kernel on a remote server reach the app over a comm, answered by the page (src/lib/device-remote.ts). The contract is in packages/device/docs/protocol.md.
FlowThe Mac app opening a notebook
- You double-click
report.ipynbin Finder. The app delegate records it; the first notebook window to see it takes it (WindowTarget.swift). AppModelalready has the server running:ServerHostcalledganymede_server_startat launch with JSON config (shared settings read fromganymede.tomlviaSharedConfig.swift, root/, static dir = the bundled web app, a token) and got back the URL. If Background Server is enabled and verified byThisMacVerifier.swift,BackgroundServerRouting.swiftmounts it asthis-macand routes local targets through it instead.AppKernelshas registered the in-app TypeScript kernel, on main with a Python one beside it (andKernelProviderClient.swiftregisters them with the background server when active); kernelspecs on disk (Node, Python) are visible too.- The tab's
WebViewloads<url>?open=/Users/…/report.ipynb&kernels=server&chrome=native. The token in the URL becomes a login cookie, and the page drops it from the address bar. - The web app (chapter 11) joins the notebook's room on the server. The page posts
PageStateto the tab'sPageModel.swift, which fills the native toolbar, tab strip, status bar and window title. - You press Run. The page starts the kernel over the server API. If it is the in-app kernel, the server's registered-kernel provisioner asks Swift to start it in the hidden web view; if it is a kernelspec, the server spawns a process and talks ZeroMQ, exactly as
ganymede servewould.
Chapter 13 of 14
Building, testing, shipping
The project's confidence comes from machine checks rather than people reading code: the e2e suites compare Ganymede against the real Jupyter stack, and every PR gets green CI plus an independent Claude review. Knowing which suite checks what tells you where a claim in this primer is enforced.
Build profiles
Cargo features choose what the server can do. ganymede-server defaults to zmq, subprocess, gateway and svg. The iOS slices of the XCFramework drop zmq and subprocess. The bottom crates (protocol, nbformat, documents, and kernel-host without its features) build for wasm; e2e/wasm-smoke/ proves it by running a notebook on the fake kernel under Node's WASI. Supported targets for the server are broad (Linux, macOS, Windows best effort, Intel and ARM); the apps target only macOS 26 and iOS 26 on ARM.
Where each promise is tested (ganymede)
| Promise | Test |
|---|---|
| The host knows no language | tests/kernels.rs runs the same scenarios on cdp-kernel and ipykernel |
Same notebook as jupyter execute |
parity.rs executes e2e/notebooks/ with both and compares files |
Same REST and websocket API as jupyter_server |
server.rs runs one scenario against both servers and compares transcripts |
Rooms interoperate with jupyter-collaboration |
collab.rs syncs a Python jupyter_ydoc client while the file changes on disk |
| No Python needed | The workstation CI job installs and runs everything with Python hidden from PATH, and fails if any Python ran |
| Real clients work | validation/: JupyterLab, widgets, trust, LSP, the VS Code extension's requests, nb-cli |
| Byte-identical saves | ganymede-nbformat/tests/roundtrip.rs |
ganymede's CI has about 20 jobs, 13 of them required on main. A changes job (scripts/ci-changes.sh) skips jobs a PR can't affect, so a docs-only PR builds nothing. A weekly run tests against the latest upstream versions to catch drift. audit runs cargo deny for advisories and licenses.
In ganymede-ui, Vitest unit tests sit beside each source file and Playwright e2e tests run the built app against a real Ganymede and cdp-kernel (plus a nightly WebKit, iPad and iPhone Playwright workflow in e2e-webkit.yml and a weekly run against cdp-kernel main in e2e-cdp-kernel-main.yml); macos-app and ios-app build and test the Swift app on GitHub's macOS runners, ui-tests.yml runs the macOS, iPad and iPhone XCUITest suites (GanymedeUITests and ScreenshotUITests) nightly, and device and device-swift test packages/device. cdp-kernel's CI tests each runtime, the container image, the browser build and JupyterLab.
How a change lands
Every change is a GitHub issue, a PR that says Closes #N, green CI, and a dev-log entry in docs/notes/YYYY-MM-DD-<topic>.md. A scheduled reviewer session reviews each green PR and ends with Review: pass or Review: changes needed. Docs for features not yet released carry an **Unreleased.** note, which the release removes.
Releases
- cdp-kernel first, when it has changes: published to npm.
- Ganymede:
scripts/release.shopens arelease/vX.Y.ZPR whose commit also moves the cdp-kernel pin andganymede ui install's default. Merging tags it;release.ymlbuilds binaries, the container image and the XCFramework. - ganymede-ui: its release script moves
GANYMEDE_REFand cdp-kernel to the latest releases, then builds the web app, the signed and notarized Mac app (with a Sparkle feed) and a TestFlight build.
Ganymede and ganymede-ui share their minor version; patches ship separately. Releases need the maintainer's explicit yes. A rolling main-build of the Mac app powers the opt-in Bleeding edge update channel in Settings.
Chapter 14 of 14
Where to dive next
Pick a path by what you want to be able to talk about. Each path is ordered: read the files in sequence, headers first.
Open edges worth knowing about
These are the places where the code is moving, so a conversation about the project will likely land on them:
- Agents waking on any edit. Request cells, the edit check and
mcp watchare built (chapter 8). Whether the agent should also wake on every settled edit is a spike waiting on a decision (#795). - Tailnet access. Tailnet identity in the server, sharing the Mac app's server on the tailnet, tokenless remotes and Tailscale SSH shipped in 0.12.0 but have not been tried on a real tailnet yet.
- Several folders in one server. The server and C FFI side of named mounts (multi-root.md,
multi.rs,mounts.rs) shipped in Ganymede 0.19.0. ganymede-uimainlists several folders in the web, iPad and iPhone sidebars (ganymede-ui#465). Still open: language servers in multi-root mode (disabled because virtual/has no single filesystem path for.virtual_documentsorrootUri). - Secrets in the apps.
device.secretsas shared named secrets with per-notebook access is on ganymede-ui'smain, not yet released. - Automation on iPad and iPhone. On ganymede-ui's
main, not yet released, Shortcuts actions also run on iPad and iPhone. Because iOS stops the in-app kernel shortly after the app goes to the background, actions that run on this device bring the app to the foreground; with kernels on a remote server they run in the background.ganymede://openlinks work there too, and onmainganymede://settingslinks.
Keeping this primer current
This primer was originally written on 2026-11-13, and checked against the changes merged through 2026-12-01. File names and line counts drift; the module headers it points to live next to the code and change with it, so when the two disagree, trust the header.
Part of the Ganymede docs. Written from the code's module headers and the project docs, and rebuilt by hand, so it describes main as of 1 Dec 2026; where it and a module's header comment disagree, trust the header.