Session lifecycle and ownership
The process per checkout serving the viewer, compiles and language servers for pcbjs dev, editors and agents. Advanced. Read it for what keeps running after Ctrl-C, how to stop it, and how a client connects; ide-bridge.md has the frames, workspace.md the projects.
pcbjs dev # start or attach, follow its log; Ctrl-C detaches
pcbjs session status # id, pid, socket, projects, clients; exit 3 without one
pcbjs session stop # end it
pcbjs session serve -p 5211 # the session in the foreground, for CI and workersLifetime
- A starter,
pcbjs dev,pcbjs mcporpcbjs lsp --stdio, spawnspcbjs session servedetached and attaches, so closing one never ends it. pcbjs devreads.pcbjs/dev.json, checks the pid and socket, and attaches; else it takes.pcbjs/session.lock, stale after 30 s or with a dead pid, and spawns. Two starters give one session.pcbjs devprints the session id and URL and follows its log. Ctrl-C detaches, a second within 2 s stops it.-p,--host,--edit,--graceand--ui-srcwarn when a session runs.- Clients are socket, pipe and WebSocket connections and HTTP requests in flight; closing a connection detaches. With none left the idle grace runs, 600 s or
--grace <s>. - The session ends on
pcbjs session stop, SIGTERM, SIGINT or SIGHUP, the grace, or, polled every 2 s, its first folder or its dev.json gone or naming another pid. It sendspcbjs:ide:bye{ reason }and removes its dev.json files and socket. pcbjs devattaches again when its session vanishes without a bye, and exits on one.pcbjs session serveexits 0 when a live session serves its root.check,inspect,shot,q,scriptandtestnever start one: they ask a live one, else compile in process, as--freshdoes.eventswithout a session exits 3.
Repositories and worktrees
- A session is keyed by the git checkout of its first folder, else the folder, so each worktree has its own, named by
<runtime>/<hash>.jsonin$XDG_RUNTIME_DIR/pcbjsor<tmpdir>/pcbjs-<uid>, mode 0700. - A starter in the checkout joins through that record. A hello or
session/attachnaming a folder attaches it, with no dev.json in another worktree. session servein a root of its own runs apart.- Each project keeps its caches in its
.pcbjs/. With two or more projects each is a scope of workspace.md under/<scope>/.
Files
| File | Holds |
|---|---|
.pcbjs/dev.json | in every project and folder the session serves, mode 0600, written at start |
.pcbjs/session | the UNIX socket of the session whose first folder this is, mode 0600 |
.pcbjs/session.lock | { pid, at } while a starter spawns |
.pcbjs/log/session.log | the session's output, set aside as session.log.1 past 1 MB |
.pcbjs/log/<date>-desync.json | a view that fell out of sync, the last 20 kept |
interface SessionInfo { session: string; pid: number; version: string; protocol: number; major: number; startedAt: string; root: string; url: string; socket: string; edit: 'localhost' | 'all' | 'none'; checkout?: string; token?: string; tiers: { keystroke: number; quiet: number } }session is 8 base32 characters per start, socket a path or pipe name, checkout that of its first folder, token only under edit: 'all'.
Listeners
- POSIX: the socket at
<first folder>/.pcbjs/session, mode 0600 from the bind. A path of 100 bytes or more binds<runtime>/<hash>.sock, or<tmpdir>/pcbjs-<uid>/<hash>.sockwhen that is long too,hash16 hex of SHA-256 of the real path; dev.json names it. - Windows: the named pipe
\\.\pipe\pcbjs-<user>-<hash>,hashover the lowercased real path; its default DACL lets other users read only. - TCP: a WebSocket at
/__pcbjs/sessionon the dev server, one frame per message. A browser page of another origin is refused. - Frames: newline-delimited JSON on the socket and the pipe, at most 16 MB each, an event
{ event, data }or JSON-RPC 2.0. A client sayspcbjs:ide:hello, itsroleone ofeditor,agent,viewerandcli, and getspcbjs:ide:readywithsession,moderworroandprojects, ide-bridge.md;session/*requests are the session's own, any other JSON-RPC goes to the client's language server.
Each method's params and result are Methods of @pcbjs/core/protocol, ide-bridge.md; the read-write ones are WRITE.
| Method | Answer |
|---|---|
session/status, clients | dev.json's fields, the folders, projects, log, idle time and connections; each connection with its role, mode, version and task |
session/attach, detach | serves folders too, a project as it is, any other folder searched for projects; stops serving attached ones, never the first |
session/stop | ends the session |
session/check, inspect | Envelope<{ stdout, stderr?, exitCode }> as in process; report adds the check report and each board's fab sets |
session/models | Envelope<{ stdout, exitCode, models }>: model inventory, fit and mesh validation; optional entries, read-only, shared with pcbjs model check and MCP models |
session/q, resolve | the record of queries.md; any reference as the current snapshot names it |
session/script, test | output or error; the snapshot written for testing.md |
session/boards, render | the boards for shot; a PNG of render.md, base64, with its legend |
session/facets | an entry's facets for ui.md's ?pcb: imports |
session/events | { events, next, reset? }; with follow each event after as session/event, queries.md |
session/edited, claiming | claims the write for that harness's agent; says claims will come; queries.md |
session/describe, send, ack, inbox | an agent's task and plan; a message to an agent, its acknowledgement, a harness's waiting ones; mcp.md |
session/read, write, findings | a file as compiled, its authority and version; edits through Sources; the findings |
session/select, observe, resync, hover, edit/* | a viewer's selection and view, ide-bridge.md; its tools, editing.md |
- A
session/*request waits until every language server handled what it had, so a query sees all text sent before it. - Every frame on a connection carries
seq, gapless from 1. On one 5 s timer, after each snapshot and as a hold begins or ends, a connection getssession/stateof its project,{ project, run, facets, pending, hold, tiers }: the current snapshot's run, a hash per<facet>:<board>or<facet>:<board>|<target>, viewer.md, whether a compile runs or waits, the draft holding the compile, editor.md, andtiers.
Documents
- One store holds the open text of every connection's language server, full document sync; disk rules every other file. The compile reads it as drafts, vscode.md, and tsc reads it in
session/checkwithout touching.pcbjs/typecheck.json. - The editor connection that synced a file last holds it. A connection whose hello says
role: 'agent'syncs a file only while no editor holds it, else its text stays its own. Save or close by the holder, and its disconnect, hand the file back to disk. - An open editor buffer is authoritative immediately, including recovered hot-exit text opened at version 1. Compilation and preview edits use that text and its current version. Recovery never silently replaces unrelated unsaved content with disk text.
- A disk write under a file an editor holds stays shadowed until the editor saves, reverts or merges: the editor's text compiles, the event
editof queries.md says{ file, source: 'disk', ranges: null, shadowed: true },source: 'agent'andbywhen an agent claimed it throughsession/edited, and the editor gets a warning on the file, codeshadowed. The extension merges three ways, editor.md. Sourcesofsession/sources.tsreads and writes every source:read(file)gives{ text, authority: 'editor' | 'disk', version }, andwritegoes through theworkspace/applyEditof the editor the edits were read from, at that version, else any editor's of the project, and to disk by a rename only with none attached. An editor refusal is final, including file creation; it never falls through to a disk write. Current source authority iseditorordisk. The wire type still acceptsrestoredfrom older compatible servers.
Snapshots
- Every compile is a run, numbered from 1 across the session; facets and invalidates name it. A finished compile of every view commits its run as the snapshot
<session>.<run>: boards, findings, the stamps of the files it read and the text it compiled; the current and previous are kept per project. - Compiled dependencies are registered before completion is announced. Catch-up compares their compiled input stamps, so a later disk edit cannot become the baseline of an older preview. Every 5 s, the heartbeat checks idle projects with connected viewers for missed file-watch events; changed configuration reloads the project, active compiles are left alone, and hidden projects catch up when shown.
- Every query settles first: it rescans files and open text every 50 ms until two scans agree, 1 s at most, compiles what changed and answers within
timeout, 120 s, else from the last snapshot withstale: { reason: 'timeout' }.
interface Stale { reason: 'changed' | 'compiling' | 'failed' | 'timeout' | 'gone'; current?: string }
interface Envelope<T> { snapshot: string; stale: Stale | null; overlay: string[]; value: T }- A reference gone from the current snapshot resolves by lineage, through its call:
TP2renamed answersTPXwithstale: { reason: 'changed', current: 'TPX' }, one whose call is gonereason: 'gone'with the nearest names. A finding id goes by fingerprint first. - An edit cancels the running compile within a few ms, design.md, keeping its finished stages, and says only
pcbjs:statuscancelled. A compile thread that exits is restarted once; a second exit in a row fails its compiles, never the session.
Modes
--edit localhost|all|none on dev and session serve, else session: { edit } in pcb.config.ts, else localhost.
| Mode | Read-write | Read-only |
|---|---|---|
localhost | the socket, the pipe, direct loopback HTTP and WebSocket | LAN and proxied clients |
all | the above, and remote clients with the session token | remote clients without it |
none | nobody; session/stop, attach and detach still work on socket and pipe | everybody |
- The token is 128 random bits per start with
--edit all, including loopback servers exposed through a tunnel.pcbjs devprints LAN URLs with?token=; dev.json holds the token, the config never does. Open the viewer with?token=<token>to pass it to the session handshake. HTTP editor requests use the same token as a bearer credential. - Direct loopback access requires a loopback TCP peer, a localhost or loopback Host header, and no proxy forwarding headers. Forwarding headers only remove privileges; they never grant them. Component proxies preserve this distinction.
- The viewer uses the server hello response's
mode, never the browser hostname, to enable editing. Published bundles and embeds are read-only. Missing permission, incompatible sessions and disconnected sessions cannot enable tools. HTTP source-opening routes, including Vite's editor route, enforce the same policy and reject cross-origin browser requests. Read-only selections still synchronize between viewers but do not trigger local source-editor or diagnostics-editor reveals. - Session credentials are omitted from TCP status and blocked from HTTP file serving. Read-only TCP source reads stay within non-hidden files of the served project; read-only hello messages cannot attach additional projects.
- Read-only connections may run checks, queries, docs and plain renders.
script,write,send,edited,claiming, scripted renders,testand document sync need read-write.
Agents
- An agent,
role: 'agent', states its task and plan withsession/describebefore its first edit, listed bysession/clients, logged as amessagetoeditorfor agent activity without a popup. User-facing updates belong in the agent's main chat; the editor's messages reach it throughsession/send, mcp.md.
Stopping a session
pcbjs session stop in the project, Ctrl-C twice in pcbjs dev, once in session serve, or kill on its pid.
Views
- Each project has its own compile thread, scheduler, snapshots and facets, so projects compile at once. A compile is one stream of
CompileEvent,@pcbjs/core/protocol: the status, the heartbeats, the events log, the language servers and the dev log follow it. - Demand: a viewer declares
session/observe { board, target, scope, facets }, and each board compiles the stages its own viewers need:meta,modelandschno copper,layersandfindingsthrough checks,fabeverything. The status goes to its project's viewers, an invalidate to its board's, a facet to those naming its board, target and facet,fabalways and everymetato all; one that never observed gets none. A changedobservesends what it lacks, by its hashes. Editors, language clients, followers, queries and one-shot runs want everything. A compile of some views mints no snapshot; a board no one observes compiles once one asks. - Cached facets can display while the interactive worker prepares current source, including editor drafts, before reporting editing readiness.
- A PCB rebuild first streams explicit placements and manual route legs before solving placement or routing. Later geometry replaces that base in the same run; the base does not commit a snapshot or complete checks and fabrication outputs.
- An edit supersedes the active compile and coalesces into the next run. The session rejects obsolete final results as well as streamed facets, including final reconciliation from earlier boards in a cancelled run. The worker client still decodes received responses to preserve its transport baseline before rejecting a cancelled result; reusable cached products are validated against the next run's inputs.
- In dev, Build fab requests
fab/latest.zipfor the board and target, waits for current source to settle, and downloads the current named archive. Stale or timed-out outputs return HTTP 503. - The tiers are data,
tiers: { keystroke: 30, quiet: 300 }ms in dev.json and the heartbeat, set byPCBJS_KEYSTROKE_MS,PCBJS_QUIET_MS: Syntax preparation starts immediately for observed edits and is reused by the keystroke tier. The first sketch starts immediately; subsequent keys coalesce at a minimumkeystrokeinterval without postponing pending work. Each sketch sendspcbjs:invalidateof what the edit makes stale and alayersfacet of the edited entity alone, never cached or type checked;quietms after the last key, 60 after a disk write, the compile of what is observed unless a block holds, editor.md; a query, every view at once. No facet of a run up to an invalidate'seditreaches a viewer, viewer.md. - A viewer out of sync asks for its facets again and the session writes
.pcbjs/log/<date>-desync.json, ids, hashes and recent frames, never file content.pcbjs doctorcounts them,--desyncprints the last.
A compile of selected boards preserves the watched source baseline of the other boards. If the operating system misses a sibling-file notification, the heartbeat still detects that change and rebuilds its observed views.