GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — apex/DESIGN.md at main · mariusae/apex

Expand file tree

/

DESIGN.md

Copy path
More file actions
More file actions

Latest commit

 

History

History
History
2827 lines (2602 loc) · 169 KB
/

DESIGN.md

Copy path

File metadata and controls

2827 lines (2602 loc) · 169 KB
Raw
Copy raw file
Download raw file
Outline
Edit and raw actions

apex — design

apex is a modernised acme: text-first, mouse-oriented, plumbing everywhere, fast and simple. It keeps acme's interaction model and adds what acme lacks for today's work: a client–server split so the UI can detach and re-attach locally or over ssh, embedded terminals for running coding agents, and an extensibility API that does not depend on 9P or a mounted filesystem.

This document is the source of truth for the architecture. Sections marked v1 are in scope for the first milestone; everything else is design intent. The current gpui prototype (acme-gpui) is the seed of the client.


1. Goals and non-goals

Goals:

  • The acme experience. Three-button mouse, tags, columns, B2 executes, B3 looks, chords, everything is text. Colours, fonts and geometry follow plan9port. Speed is a feature: no perceptible latency for local editing.
  • All state on the server. The UI is a renderer plus an input device. A client can detach at any time and re-attach with full fidelity; the server keeps scrollback and history and serves them on demand.
  • Remotable. apex attach host over ssh is the remote story. Files stay where the server runs; nothing is synchronised.
  • Agents. Terminal windows are first-class. An agent runs in one and drives the editor through the same CLI a shell script would use.
  • Extensibility at least as good as acme's, with few concepts, exposed through the apex command (tmux-style) and a typed protocol for programs.
  • Modern extensions fit: LSP, formatters, file watchers, agents.

Non-goals (for now): multiple simultaneous UI clients editing the same session ("single player mode": one UI attachment per session at a time), a plugin language, a configuration language, web windows, persistence of the server's state across restarts (its logs; the sessions are kept, §12), Windows.

Terminology

  • Session: what tmux calls a session — a whole workspace (its shards, layout, windows, terminals) living on one server. A server hosts many.
  • Attachment: the fenced identity a client gets when it attaches to a session. Leases are granted to attachments. A client may hold several attachments at once, to sessions on local and remote servers.
  • Connection: a socket. Connections drop and resume without affecting attachments or sessions.

Principles

  • Nothing is ever lost. Whenever the system must set something aside — unflushed edits from a fenced attachment, a buffer overwritten by Get, a disk change under a dirty buffer — every version is kept and shown, with provenance, in a +Recovered buffer or in the tag. Silent discard is a bug.
  • State on the server, rendering on the client. The client is a renderer and input device with a replica; if it lacks data for an operation it hands the operation to the server (§5) rather than blocking.

2. Overview

flowchart TB
    subgraph server["server (one per host)"]
        direction LR
        logs["logs + snapshots<br/>fencing / attachments"]
        core["state machine (core crate)<br/>plumber, Edit language"]
        io["ptys / files / procs<br/>file watcher"]
    end
    ui["UI client (gpui)<br/>state machine<br/>(core crate, leader for its shards)"]
    cli["apex CLI / scripts<br/>win, Watch, ..."]
    tools["tools: lsp, agent<br/>formatter, ..."]
    server <-->|"attach protocol<br/>(unix socket / ssh stdio)"| ui
    server <-->|"control protocol<br/>(same frames)"| cli
    server <-->|"control protocol"| tools
Loading

Three kinds of process:

  • Server. A daemon, one per host, hosting many sessions. Owns the logs (in memory), sequences or stores every change, runs ptys and external programs, watches files, hosts the plumber. Runs where the files are.
  • UI client. Attaches to one or more sessions (one OS window each). Mirrors each session's state, renders it, and while attached leads the shards a user edits (buffers, windows, layout) so editing never waits on a round trip.
  • Tools. Anything else: the apex CLI, shell scripts, apex lsp, an agent harness. Tools read state and propose changes through the server.

The core crate (apex-core) is shared by server and client: buffers, selections, undo, plumbing rules, built-in commands, and the state machine that applies log entries. The Edit language is its own crate (apex-edit, §8a) that core depends on. Neither has UI, I/O or a dependency on gpui, so both nodes run the identical code and hold the identical state, and the UI is a separate layer that only reads state and emits entries.


3. Model

3.1 Nouns

Four nouns, mirroring acme's files:

noun acme equivalent contents
Buffer File id, name, rope, version, undo history, dirty/stale flags, disk hash
Window Window/Text id, tag view, body view, kind (text | term | web), column slot
Event event file the log itself: edits, selections, layout changes, executions
Command writing to ctl, B2 "execute this string in the context of that window"

A view is (buffer id, q0, q1, origin): acme's Text. A window has a tag view and, for text windows, a body view. Two windows may view one buffer (Zerox) with independent selections and origins; an edit in either shows in both, undo is per buffer, and only the last window on a dirty buffer warns on Del. Every tag is its own buffer. +Errors is a buffer.

Terminal and web windows have no body buffer; their body state is a server-owned emulator grid or page.

3.2 Shards

State is partitioned into shards, each an independent replicated state machine with its own log and its own lease. A shard is either leasable (its lease moves between attachments) or pinned (its leader is fixed and the lease never moves):

shard one per entries default leader
buffer buffer Create, Edit{version, q0, nd, text, group}, Undo/Redo{version}, Clean{version}, Stale{hash}, Rename, ViewAdd/Del{view}, Select{view, q0, q1}, Origin{view, off} server
window window Create{tag, body}, Font, Exec{text, handler, at}, Status{exec, Done|Failed|Unknown}, Delete; as built also Tab, Indent, TagExpand, Live{by}, Working{by} server
layout session Init{top}, ColNew/Del/Resize, WinPlace{window, col, at}, WinRemove, WinResize, Snarf, Exec from column tags and the top row; as built also Arrange{r, cols}, Status, Visit{from, to}, NavPop{back, at} (the navigation stacks, Layout{nav_back, nav_forward} of Loc{name, pos}) server
term terminal Rows{seq, rows: [cells]}, Cursor, Mode, Resize, Exit server, pinned
metalog session ShardNew/Del, Attach/Detach, LeaseRequest/Release/Grant/Reclaim{shard, attachment, epoch, seq}, PlumbRuleInstall/Remove{attachment, priority, predicate, action}; as built also Set/Unset{owner, key, value} (settings, the session's or an attachment's) server, pinned
registry server SessionNew/Del/Rename server, pinned

The metalog is the session's authority on everything about shards rather than in them: which shards exist, which attachment holds which lease at which epoch, every transfer or reclaim, and the plumbing rule table (§8), so a reader can tell what happened and why. Fencing is decided there and enforced by the log store against its latest state. Layout cross-references windows and buffers but, being leasable, cannot be the source of truth for what exists. The server-wide registry lists sessions.

Views (selections and origins) live in the buffer shard, not the window shard: a buffer edit adjusts every view on the buffer, so Select and Edit must share one sequence or replicas could interleave them differently and disagree. Column tags and the top row have views too.

Cross-shard operations are several entries in several logs with no atomicity between them. acme has none either. Zerox is a layout.WinNew plus a window.* entry naming the buffer and version; the reader tolerates seeing them in either order.

3.3 The state machine

state(shard) = apply*(snapshot(shard, N), entries N+1..)

Rules that keep both nodes identical:

  1. apply is deterministic and pure: no clock, no randomness, no I/O.
  2. Anything with an effect is an exec entry (§5) naming its handler. apply records it as state; the node matching the handler performs the effect and its outcome comes back as further entries referencing the exec's sequence. Effects fire on live observation only, once: a performer acts on an exec it sees arrive at the head of a live stream, never while replaying a tail on attach or restart, and appends Done{exec_seq} or Failed{exec_seq, reason} (or Unknown after a crash between the two — at-most-once, the right default for a shell command; Put is idempotent anyway).
  3. An edit to a buffer adjusts every view on that buffer (selection and origin), in one place in the core crate, exactly as acme's textinsert walks file->text[].
  4. Snapshots are a pure function of the log prefix. Either node may take one.
  5. Divergence is detectable: nodes hash shard state at attach and periodically; a mismatch is a bug in apply, surfaced immediately. Tests feed random entry sequences to two instances and compare.

Terminal grids are the one thing not reconstructible from their raw input (the emulator has no serialisable state), so terminal entries are grid rows, not pty bytes. The raw pty byte stream is still logged to disk for apex term log, search and agent transcripts, but correctness never depends on replaying it.


4. Leadership: attachments, leases, fencing

4.1 Attachments

An attachment is explicit and server-issued (apex attach creates one, recorded in the session's metalog), with a monotonically increasing id. Leases are granted to attachments, never to connections. A dropped connection does not end an attachment: the client reconnects, presents its attachment id, and both sides resume from the last acknowledged sequence, keeping their tails. Nothing is lost on a network blip.

Resuming is decided per shard, and the two directions differ:

  • Shards the attachment leads (buffers, windows, layout): the client is ahead of the server, not behind. It flushes its unflushed tail; there is nothing to replay.
  • Shards the attachment follows (terminals, tool-led buffers): the server chooses, by size, between replaying the tail since the last acknowledged sequence and sending a fresh snapshot. If the tail is larger than the snapshot (or over a fixed threshold), it re-snapshots — an hour of agent output is a huge tail and a small grid. Time away is only a hint; bytes decide.

Proposals addressed to a leader whose attachment is disconnected are held briefly, then rejected with "leader unreachable" so tools retry rather than hang. Once the attachment is fenced, proposals go to the new leader.

As built: a client that has lost its leases (another UI attached and took them) sees it in the metalog it follows, and shows it: the square at the top-left of the top row fills red, the session's tab in the title bar fades into the strip (its name greyed, "fenced" after it), and the window title says another client leads.

As built, notifications: the same square is the session's, and is otherwise inert, so it is where the session says a tool is asking for the user: an agent ready for more, a build done. A notification is a window's -- the one it is about, where taking it goes -- so notified is a window state beside dirty, live and the rest, and the session is notified while any of its windows is. It is kept in the metalog (MetaOp::Notify{attachment, window}, Unnotify{window}), in Meta::notifications oldest first: one a window, so a window notified again keeps its place in the queue. Kept there and not in the window's shard, the daemon orders it and no lease is involved; one whose window has gone counts for nothing (Node::notifications, window_notified). It goes when the tool retracts it, when the user attends to it, when its window goes, and when the tool that raised it detaches (the Detach entry takes it, as it takes the attachment's settings), so a tool that dies leaves nothing waiting. On the wire, ClientMsg::Notify{window} raises one and Unnotify{window} lowers one: a tool only what it raised, a UI any, since attending is the user's. The user attends to a window by taking its notification from the square, by a click or a key in it (B4's menu too), or by already being in it when the notification comes. Being in a window is the client's own business, never the daemon's: the window is active while the pointer, which the keyboard follows, is on it and apex is in front. A client catching up dismisses a notification that has come to its active window at once and never draws it, telling one that came from one already there by the entry that raised it (Notification::at); the tool still sees it raised and lowered, as it would any the user attended to. Coming to a window that is already notified is not attending to it: that one stays.

A notified window's handle says so, and nothing else of the window does (its header was once tinted, and pjw's face once sat on the handle): as the notification comes, a ring ripples out of the handle, the disc it leaves behind a pale halo of the accent round it, there until the notification goes. Dirty, live or working still shows in the handle itself, and a halo is a shape apart from any of their colours. Every handle shows it: a tag's, a minimized column's, a stash card's, a sidebar row's.

A notification moves nothing. (It once did: Node::notice, proposed as the daemon recorded one, undid a maximize that hid the window so its haloed handle would show. A status that rearranged the columns under the user was the louder thing, and so it went.) A window hidden behind one grown to its column or the row is not on screen, and so its status is said where windows not in sight are: the sidebar's row for it (the only place a status is said in words but its tag), the session's square and ⌘G, which takes the user there. A stashed window stays stashed: its card, if under the top one, is drawn out of the bunch far enough to show its handle and the start of its name (each further notified card as far again), keeping its place in the order; a click on it brings it back, as on any card.

The session's square says nothing of it -- it filled with an azure once, which the face in the tab (below) made one signal too many -- but a click on it still takes the oldest: the window is revealed and the pointer landed on it, as a new window is, and its notification dismissed; the next click takes the next. ⌘G does the same across every tab the app has open: the oldest of them all, the tab it is in brought forward first when it is not this one, and a beep (NSBeep) when there is none left to take. The order across sessions is the app's own, since the entry that raised each is a sequence in its session's metalog and means nothing beside another's: the client keeps a queue of what it has seen, in the order it saw it (attention::advance), each session's own in the order the metalog has them. The Dock icon carries how many are waiting as its badge, and still bounces once for one that comes while no window of the app's is in front. The session's tab says it with Peter J. Weinberger's face before its name -- the face Plan 9 has shown when something wants you since faces(1), its outline from plan9port's pjw.char.ps (assets/pjw.svg), 15 high in the name's own ink -- the two centred together, and the tab changes in no other way: a tab is a wide thing to colour, and the colour that suits a handle galls across that much of the strip. So a session wanting the user shows from any other tab; a parked session's entries arrive off the window, so each window looks at its tabs' queues on its tick and draws the strip again when that changes. With no window of the app's in front, a notification coming to any session it has open, shown or parked, bounces the dock icon once (requestUserAttention, informational): each tick compares every session's notifications, by at, with the last tick's, and a session seen for the first time brings no bounce for what it already had. apex notify [-win=WIN] notifies a window, $winid by default, from a script and waits until the user attends to it.

4.2 Leases

Every shard has exactly one leader at any time: the holder of its lease. Only the leader appends to the shard's log; everyone else proposes to the leader (§5). The lease carries a fence epoch, bumped on every transfer and every reclaim.

  • On attach, the UI attachment takes the leases for layout, every window, and every buffer it shows, in one bulk grant. It takes further buffer leases lazily as it opens them. Editing, selecting and rearranging then happen locally with no round trip; entries stream to the server asynchronously, batched per frame.
  • term shards are pinned to the server: the lease never moves. The client is a follower that renders rows and proposes keystrokes. Terminals therefore never suffer lease loss.
  • A tool may take a buffer lease for exclusive multi-step work (an agent rewriting a file). While it holds it, the UI's edits to that buffer become proposals routed through the tool, so human and agent edits are serialised without interleaving. Tool leases have a TTL so a crashed tool cannot lock a file forever. This is opt-in; the default for tools is to propose.

4.3 Fencing

Every append and every proposal — terminal keystrokes included — carries (attachment id, fence epoch) for the shard. The server's log store, which every attachment must go through, refuses anything stale. A client that still believes it leads cannot append, cannot propose and cannot type into a terminal.

4.4 Transfer and reclaim

Both are driven through the metalog, and a new UI attachment always tries the first before the second:

  • Transfer (cooperative): the server appends LeaseRequest; the holder, if connected, flushes and appends LeaseRelease{seq}; the server appends LeaseGrant{new holder, epoch+1, seq}. Lossless.
  • Reclaim: the holder does not answer within a short deadline (it is disconnected or wedged). The server appends LeaseReclaim{epoch+1, last flushed seq} and grants from there; the old attachment is dead from that instant, whether or not it ever returns. The deadline is the one timeout that is not garbage collection, and it is safe because a reclaim is only ever lossy, never incorrect. Other timeouts only collect attachments nobody will resume and expire tool leases.
  • Recovery: a fenced client re-attaches only as a new attachment, takes fresh snapshots, and re-submits its unflushed tail as base-versioned proposals. Where versions still match they apply and nothing is lost; where they don't, the text goes into +Recovered with provenance (attachment, time, base version) so work is un-sequenced rather than lost.

The UI flushes every frame, so the unflushed tail is milliseconds of typing.

Every entry records the attachment and epoch that wrote it. apex log shows provenance: "this edit came from the agent's attachment".


5. Proposals and commands

Tools write through one verb:

propose(shard, base_version, ops) -> Accepted{seq} | Rejected{current_version}

The server routes a proposal to the shard's current leader (itself included); the caller never learns who that was. A proposal is applied atomically and in order within its shard, so a formatter's hundred edits travel as one proposal and cannot interleave with typing. There are no cross-shard proposals.

Commands are what B2 does, and they are log entries, exactly as acme writes every B2 and B3 to its event file:

Exec{ text, window, at_seq, handler }      handler ∈ { leader, server, tool(name) }

The leader appends the exec like any entry (provenance, and apex events shows what was executed). The node matching handler performs it and appends the outcome. Resolution of the handler is recorded in the entry so it replays as data:

command handler outcome
Cut Paste Snarf Undo Redo Look Edit Font Zerox, layout commands leader concrete entries, no round trip
Put Get, New on a path, Newterm, |cmd <cmd >cmd, unknown words (shell) server proposals the leader applies; terminal rows
words a tool registered for (Definition, Format, ...) tool(name) proposals
B3 text server (plumber) a further exec, or a window

This is acme's model where a tool may consume an event and act instead of acme, made explicit. Locally the split is invisible; remotely it is ssh's: editing is instant, running things costs one round trip.

The |cmd, <cmd, >cmd forms are commands whose input is the selection. The input text is not stored in the entry: the exec sits at a sequence and any replica reconstructs the text from the state there. What the entry does carry is the buffer id, its version and the range, because the exec lives in the window log and the text in a buffer log; cross-shard ordering must never be guessed. The output, being an effect, returns as a proposal against that version.

Handlers also give the client a fallback. A command the client can satisfy from mirrored state runs locally; one it cannot — Look past the mirrored part of a huge buffer, Edit over paged text — it appends with handler: server. The server evaluates it and proposes the resulting selection and origin; the client's ordinary "not in view, page it" path fetches the text. Full mirroring (§6.1) is therefore an optimisation, not an invariant.

Proposals may be intents; entries are always concrete. A proposal is either concrete ops against a base version (a formatter that diffed the version it read) or an intent the leader evaluates against its exact current state and lowers into concrete entries: SetContent{text} (the result of Get or a file-watch reload), an Edit program (apex edit), a selection by address. Intents have no base-version race, because the leader runs them on the live text.

The lease never moves for a server-side action. Get on a client-led buffer is: leader appends Exec{Get, handler: server} → server sees it live, reads the file → server Propose{SetContent} → leader diffs, appends the edits and Clean{version} → server appends Done. Put is the mirror: server applies its replica to at_seq (the entries are ahead of the exec on the same stream), writes the file, records the hash so the watcher ignores the event, and proposes Clean{version}. Handing the lease to the server instead would cost two transfers, stall typing while the server held it, and open a fencing window on a buffer being edited.

Clean{v} means clean as of version v; dirty is derived as "current version ≠ clean version", so typing during a slow Put leaves the buffer correctly dirty afterwards. Between the exec and its Done the UI knows a Put is in flight and shows it; a Failed{exec, reason} is shown in place rather than as an +Errors line that scrolls away.

As built (apex-server/src/proposal.rs). The server never writes a shard it does not lead. Every effect it has on buffers, windows or the layout is a value of one Proposal enum — OpenWindow, NewWindow, TermWindow, SetContent, Clean, Rename, ReplaceRange{version}, Errors, Status, Look — which the leader lowers into entries with proposal::apply. In-process the client applies proposals the moment the server returns them; over the socket they travel as Propose messages. Only ReplaceRange and Clean carry a base version; the rest are intents lowered against the leader's live state, as this section says. The handler predicate is not a general predicate yet: Handler::Server is resolved by the leader at exec time from the command table.


6. Protocols

One schema (protobuf), one framing (length-prefixed messages), two "services" on it. Transport is a Unix socket locally. Remotely, apex attach host runs ssh host apex attach -stdio and speaks the same frames over the pipe — no socket forwarding, no daemon beyond sshd. gRPC is not the transport (HTTP/2 over stdio is awkward and the attach path must be the fastest thing in the system); it can be a later gateway.

6.1 Attach protocol (UI ⇄ server) — v1

Tuned for one thing: the client mirrors only what it can see.

client → server
  Hello{session, attachment?: id}            attach to a session, or resume an attachment
  Take{shards}                               bulk lease request (on attach)
  Append{shard, epoch, entries}              leader appends (incl. Exec), batched per frame
  Propose{shard, epoch, base, ops}           for shards it doesn't lead (term input)
  Page{term, rows: range}                    demand-page scrollback
  Ack{shard, seq}

server → client
  Welcome{attachment, fenced?: reason}
  Grant{shard, epoch, seq} | Deny
  Snapshot{shard, seq, state}                full buffer / window / layout / term grid
  Entries{shard, from, entries}              tail, or server-authored rows
  Propose{shard, base, ops}                  server asking the leader to apply
  Ack{shard, seq}
  Hash{shard, seq, hash}                     divergence check
  • Buffers a window shows are mirrored in full by default (acme loads whole files; they are bounded by what a person opens), so Look, Edit and B2 built-ins run locally. Where a buffer is too large to mirror, the client pages it and hands those commands to the server (§5).
  • Terminal scrollback and +Errors-like unbounded output are demand-paged by row range. Attach sends the visible grid (a 200×50 grid is ~50 KB).
  • Frames coalesce per display refresh; nothing is sent per keystroke.
  • Attach and re-attach are the same code path: snapshot plus tail per shard, lazily per shard as windows become visible.

As built (apex-server/src/{proto,daemon,remote}.rs). Framing is postcard with a u32 little-endian length prefix — the entries already derive serde, so one schema serves the log, snapshots and the wire; protobuf stays an option for a gateway. What differs from the sketch:

  • No Take/Grant round trip. Hello{session, name} makes a new attachment, grants it every leasable shard, and answers Welcome {attachment, snapshot} with the whole state (§12 on its size). A client that attaches while another holds the leases reclaims them at once — single-player mode collapses transfer-then-reclaim to reclaim. The fenced client stays connected and sees its appends refused. Resuming an attachment by id, Page, and Hash are not implemented yet.
  • Mirror logs. The client runs its Node over Log::mirror, a log store built from the snapshot that assigns the same sequence numbers the server will store. The client leads with no round trip at all; flush ships Append{shard, entries} for every led shard, the server answers Ack{shard, seq}. Leases are derived from the log store on both sides (Log::held_by); the metalog is streamed to the client like any followed shard.
  • Shard creation is a fire-and-forget request. CreateShard{shard} (sent by the mirror's hook) is processed by the server before the Append that follows it on the same connection, and the grant it makes (creator, epoch 1) is the one the mirror assumed. DeleteShard likewise.
  • Terminal input is not a Propose but its own messages (TermKey, TermPaste, TermResize, TermScroll); the server's log store still fences them by connection. OpenFile and Plumb ask the server to look at the file system and answer with a proposal.
  • The daemon keeps a follower replica of the whole session (the "view") for execs and snapshots, and forwards the metalog before any other shard so a client learns of a shard before its entries.

As built, the wire (proto.rs, proposal.rs; postcard frames, u32 LE length):

client → server
  Hello{session, name, kind, attach?}     attach; a UI ships its ~/.apex/attach
  NewSession{name}                        make a session labelled name (idempotent); its host's profile runs
                                          (Hello/EndSession/RenameSession name a session by its id, a
                                          unique prefix of it, or its label; Sessions lists {id, label};
                                          Ended{id, label})
  ListSessions · RenameSession{from, to} · Stop · Ping{t}
  Append{shard, entries}                  entries this client sequenced as leader
  CreateShard{shard} · DeleteShard{shard}
  TermKey{term, key} · TermPaste · TermResize · TermScroll{term, delta}
  TermText{term, p0, p1}                  snarf a terminal range (answer: a Snarf proposal)
  TermRead{term, from, to}                a terminal's lines, scrollback included → TermLines
  OpenFile{col, ctx, name}                the server reads the file and proposes OpenWindow
  Plumb{ctx, text, dir?, edit_only, dry, at?, sel?, alt?, reverse, verb?}
                                          B3 / apex plumb / B; at: the pointer, sel: what was taken,
                                          reverse: shift-B3; verb: a rule's verb at the pointer
                                          instead of plumb (cmd-B3 is Def)
  PlumbAck{id, ok}                        a tool's answer to a Plumb it was handed (the Plumb names
                                          the rule that matched, so a tool with several can tell)
  RuleAdd{rule, priority, mine} · RuleRm{id}
  Propose{id, proposal} · Applied{id, result}
  Env{set} · EnvImport{vars} · Set{key, value, attachment?} · Kill{targets}
  EndSession{name, force}                 the session ended: killed, everyone cut off (Ended)
  Named{name, group, pid, cmd}            what a program is called: the entry of its process
                                          group (the shell the server started) takes the name in
                                          the top row, ps and Kill; a group the server did not
                                          start is adopted under pid until this connection goes
  Io{stream, frame}                       the I/O plane (WEB.md §1): Request opens a stream
                                          the client numbers; Body, End, Reset

server → client
  Build{protocol, id}                     first frame, frozen: refuse another protocol version
  Welcome{attachment, snapshot} · Entries{shard, entries} · Ack{shard, seq}
  Propose{id, proposal} · Applied{id, result}
  Sessions{names} · Error{text} · Pong{t} · Env{vars} · RuleAdded{id}
  PlumbTrace{lines}                       a dry run's report
  Plumbed{ok, why}                        a plumb asked here is over: taken, or why not
  Plumb{id, ctx, verb, text, dir, groups, at?, sel?}
                                          a rule named this tool; answer PlumbAck within a second
  Io{stream, frame}                       Response{status, headers}, Body, End, Reset
  Ended{session}                          the session this connection was on is gone
  TermLines{term, text}

proposals (tools and the server → the leader; applied by whoever leads)
  OpenWindow{col, from?, name, text, hash, select_line?} · NewWindow{col, name} · TermWindow{col, name, term}
  SetContent{buffer, version?, text, hash} · Clean · Rename{buffer, window, name} · Stale
  Switch{session, window?}                 show another session (by id, prefix or label), at a
                                           window there: the leading UI switches to it
  ReplaceRange{select, dir?, buffer, version, q0, q1, text}
                                                       select: pipe output, left selected as acme's |
                                                       does; else a tool's write, dot left alone as a
                                                       write to acme's data file leaves it
  Insert{buffer, version, at, text, follow}            at a point, the selection left alone (win);
                                                       follow: a dot at the point moves past the text
  Errors{dir?, text} · Snarf{text} · TermName{window, name}
  CommandStart{name} · CommandExit{name} · Status{ctx, exec, status}
                                          (the top row edited without moving seltext: a command
                                          ending never steals where keys and looks go)
  Look{ctx, text, reverse} · ClientDo{verb, args}     the last resort of a plumb; a UI's own verbs
  Exec{ctx, text} · Edit{window, program} · Select{view, q0, q1}
  Live{window, by?}                                    a process behind a window
  Working{window, by?}                                 work going on behind a window
  Builtin{ctx, text}                                   a word's own meaning, the rules already asked
  PutTrimmed{buffer, version, runs, hash}              Put's trim: blanks deleted as one undo step, then clean
  Goto{loc} · Nav{back}                                a jump; Back and Fwd along the stack
  OpenPage{col, page} · Navigate{window, url}          a page (ARCHITECTURE.md §5); one at an address moved
  Reload{window} · PageScroll{window, scroll}          a page loaded again everywhere; a buffer page scrolled

As built, versions: the daemon's first frame on every connection is ServerMsg::Build{protocol, id}: PROTOCOL, a number in proto.rs bumped by hand with every change to anything on the wire (messages, proposals, entries, ops, state, since postcard is not self-describing), and the build id, a hash of the workspace sources computed at build time (the same on every target), which only says which binary it is. The variant stays first and unchanged. A client of another protocol version stops at that frame with an Unsupported error that says what to do: when the daemon's sessions can be let go, apex stop on its machine, then attach again (Reconnect, ⌘⇧R). Builds of the same protocol talk to each other, so a rebuild for a bug fix in the client needs no restart of the daemon. The daemon is never restarted behind the user's back: its sessions may hold work. When the local daemon refuses at startup, the app opens an in-process window showing the error, pointed at the session so Reconnect tries it again.

6.2 Control protocol (tools ⇄ server) — v1

Same frames, request/response plus subscription:

Read{buffer, range|addr}                     text at the latest flushed version
Info{window|buffer|layout}
Propose{...}                                 §5
Exec{window, text}
Subscribe{shards?, since}                    stream of entries (the acme event file, generalised)
Lease{take|release, buffer, ttl}             opt-in exclusive editing
Term{new|send|read|log}
Plumb{text, context}

Reads answer from the server's replica, which lags the leader by microseconds locally or by link latency remotely; every answer carries the version it is valid at.

6.3 Schema sketch

message Entry   { uint64 seq = 1; uint64 attachment = 2; uint32 epoch = 3; oneof op { ... } }
message Edit    { uint64 version = 1; uint64 start = 2; uint64 end = 3; string text = 4; }
message Select  { Part part = 1; uint64 q0 = 2; uint64 q1 = 3; }
message Rows    { uint32 first = 1; repeated Row rows = 2; }        // Row = repeated Cell
message Cell    { uint32 ch = 1; uint32 fg = 2; uint32 bg = 3; uint32 flags = 4; }
message Propose { Shard shard = 1; uint64 base = 2; repeated Op ops = 3; }
message Exec    { uint64 window = 1; string text = 2; uint64 at_seq = 3; Handler handler = 4; }
message Done    { uint64 exec_seq = 1; }   // also Failed{reason}, Unknown

7. The apex command — v1 subset marked ●

The CLI is the stable public API. Scripts never see the wire.

● apex server [--socket P]           start the daemon (also auto-started by attach)
● apex ls [host]                     list sessions on a server
● apex new-session [host/]name       create a session
● apex attach [host/]session [--stdio]  attach a UI to a session (transfer, else fence, other UI attachments)
● apex detach                        drop the current attachment (leases return to the server)
● apex new <path>...                 open files (windows in the current column)
● apex win list|del|move|resize      layout
● apex text read <buf> [--addr A]    read a buffer or address range
● apex edit <buf> '<Edit program>'   run the Edit language (a proposal)
● apex sel <win> [q0 q1]             read/set a selection
● apex show <win> [q | :line]        bring a place on screen, nothing else moved
● apex exec <win> '<command>'        as if B2
● apex events [--since N] [--shard S] stream entries as JSON lines
● apex term new|send|read|log        terminals
  apex plumb <text>
  apex lease take|release <buf>
  apex lsp ...                       LSP bridge (§8)
  apex log [<shard>]                 provenance

Configuration is a script of apex commands run at server start (~/.config/apex/init): plumb rules, tools to launch, defaults. Client-side settings (fonts, scale) are apex commands the client interprets. There is no configuration language.

As built (apex-cli). apex is the command; the gpui client is apex-ui, which apex attach launches. Every subcommand attaches to the session as a tool: it receives the same snapshot a UI would, reads from its own replica, and proposes to the leader — there is no separate control protocol, only Propose{id, proposal} / Applied{id, result} on the attach protocol, plus NewSession and ListSessions. A session with no UI attached is led by the daemon itself, so scripts work headless and a UI that attaches later takes over what they did. apex attach starts the daemon if the socket does not answer. Implemented: server ls new-session attach [-stdio] new open win text edit sel show exec events term plumb B env set cat lsp label awd version; flags are Go's (-flag=value) and apex help documents everything, apex help <topic> included; apex ps and apex kill see and end what the server runs (the Running list behind the top row's names: pid, name, origin, start time, directory, command line). apex end-session [-f] [NAME] ends a session: refused while a window there is unsaved unless forced; else its commands and terminals are killed, everything attached gets Ended and is cut off (a window on it goes offline saying so, a parked one is dropped), and the daemon goes on for the others; the picker's end on a session row does the same, on the host through apex end-session there, and so does End in the top row, which then closes the window. End asks as Del does, by Del's rule (winclean): each modified file warns in +Errors, once for what it holds, and the session stays; End again with nothing changed ends it whatever the daemon's own check would say. End -f ends it at once. A program says what it is called with Named, so apex tool lsp is lsp in the top row, not apex: the server renames the entry of the announcer's process group (the exit reports the new name too), or adopts an announcer it did not start for as long as its connection lasts, ending it by pid. What a script (profile, attach) leaves in the background, apex tool lsp &, is adopted the same way, its own entry; and a command is over when it exits, not when its pipes close, so the script is gone from ps and the top row while the tool it started lives on. apex tool win and apex tool lsp announce themselves once, after attaching. WIN is an id or a unique substring of a window's name. Not yet: detach lease lsp log, the init script.

Every session is a URL: local:///name on this machine's daemon (local is the pseudo-provider that takes no argument), ssh://user@host/name, sprite://box/name — scheme is the provider, authority its argument, path the session. A daemon's first session is default. The selector lists this window's session, the recent ones (~/Library/Application Support/apex/recent-sessions, latest first), this machine's, and for a remote window the destination's; what is typed filters them, and typed as a name or URL and not listed, becomes "Create …" — a bare name is local:///name, so making a session never lands on the current window's provider by accident. "Rename this session…" renames it on its daemon, attachments staying attached (RenameSession; sessions have ids inside the daemon, names are labels).

Commands run as plan9port acme runs them: rc -c command, with $winid set to the window's id (or the last selected window's), and $% and $samfile naming the window's file; $acmeshell names another shell. The rc is mariusae/rustrc, a drop-in port of plan9port's; the app carries it beside apex for this machine and for each remote target, deploy puts both in ~/.apex/bin on a destination, and the daemon puts that directory and its own on the session's PATH. Without an rc, commands fall back to sh.

apex attach dest/session (or a URL) goes through providers.rs. A provider is an executable apex-remote-<provider> on the PATH, called as apex-remote-<provider> DESTINATION COMMAND: it runs COMMAND, a single shell command line, on the destination with stdio connected — ssh's own convention, and ssh is the built-in provider, so user@host needs nothing. Other destinations are provider:name (sprite:mybox) and need only that script (providers/apex-remote-sprite is one: sprite exec -s "$1" -- sh -c "$2"). This keeps the rule that there is no configuration file: the provider script is the whole configuration. The destination needs nothing but the provider's access. We ask uname -sm, pick the apex we carry for that OS and architecture (the Mac app bundles linux-amd64, cross-compiled statically against musl with Zig as the linker, and its own darwin-arm64), compare its sha256 with ~/.apex/bin/apex there, upload it over ssh's stdin if it differs, and run ~/.apex/bin/apex -session=S attach -stdio, which starts the daemon on the host if it must and copies bytes between its stdio and the daemon's socket. The bridge knows nothing of frames; the UI speaks them to the child's stdin/stdout exactly as to a socket. A remote window's selector lists the host's sessions (apex --ensure-server ls there); "Local sessions" leads back. Remembered sessions are host/session; one that cannot be reached at launch falls back to the local local with the error in +Errors. APEX_SSH names the ssh program, which the tests point at a script running the commands under a scratch HOME.


As built, session identity: every session has an identity, a UUID minted when it is made and recorded as the second entry of its metalog (MetaOp::Identity{id}, so every replica knows it from its snapshot), and a label for people (MetaOp::Label{label}, appended again on a rename, so attached clients learn the new label from the log). The daemon keys sessions by id and resolves whatever names one — the id, a unique prefix of four characters or more, or the label. A label starts with a letter, then lowercase letters, digits and - (providers::valid_label, checked by the daemon, the CLI and the picker alike). Commands and terminals get apexsession = the id and apexsessionlabel = the label; apex ls prints label<TAB>id; a window is nameable anywhere as id.N: a bare id or name is the session at hand's, and the CLI takes a SESSION.N argument as choosing that session for the command. The socket names the daemon, not a session, and stays as it is. Places across sessions: a Loc carries the session it is in (by identity; None is the session at hand) and names a window by name or by id as digits, so <session>.<win> is a place anywhere. A Goto or Nav (Back, Fwd) whose place is in another session is not landed by the node but handed to the UI as a switch (Node::take_switches); the UI switches to that session (parking this one, taking or attaching the other by its identity) and lands there once it is up. current_loc records the session, so the navigation stack spans sessions and Back returns across them. Proposal::Switch{session, window?} is the same for a tool that only wants the session shown (apex switch, the tool API's switch, the bridge's switch, Go's Switch); apex B session.N[:line] makes the Goto. All of this is within one daemon: a session id is meaningful anywhere but is acted on where its daemon is. Intended, not built: places across daemons go through the client UI, the one party that knows several — as a URL scheme the app registers (apex://<session>/<win>), so a tool on any host emits a URL the plumber already carries and the app resolves the session id against its known hosts and switches, by the same path as Switch.

As built, profile and attach: two scripts, named by what they configure. The host's ~/.apex/profile is the session's setup on the daemon's machine; the client's ~/.apex/attach is its own per attachment, the UI's tweaks. On one machine both live in the same ~/.apex and each runs once in its role. (A third, the creator's ~/.apex/session shipped in NewSession to provision hosts with no profile of their own, was built and then dropped, for now: a host configures itself.) A new session runs one rc on its host that sources the host's profile, as a command named profile with output in +Errors, and apexsession, APEX_SOCKET set, and EDITOR to apex-editor, a link beside the binary the CLI knows by name as apex editor (editinacme: the file plumbed to edit, exit when its window goes; one word, since zsh and rc do not split $EDITOR into words). Beside it too, and $BROWSER, is xdg-open, the same binary under the name programs call to open a URL or a file (gh, cargo doc --open, git web--browse, anything on a Linux host without a desktop): its one argument is plumbed from the working directory, as B3 on it would be, and it exits non-zero when no rule takes it (ServerMsg::Plumbed, which apex plumb also reports; the daemon's own verbs have no asker). The binary's directory leads the session's PATH, so the link shadows a host's own xdg-open there. The profile's environment at its end is the session's: the server prefixes the script with an exit hook (rc's fn sigexit, sh's trap ... EXIT) that runs apex env -import, which sends the shell's whole environment (ClientMsg::EnvImport); against the environment the profile was given, variables set or changed are set in the session's and dropped ones unset, the shell's own bookkeeping (pid, status, path, PWD...) ignored. rc exports lists (\x01-joined) and functions (fn#name) as variables, so a profile's fn g {...} works in every terminal and B2 command. The rc is run in its own process, not embedded: rust-rc forks for pipelines and & with the interpreter running on in the child, no fit for the threaded daemon. apex env KEY=VALUE (ClientMsg::Env) still sets the session environment from anywhere at any time. A client's ~/.apex/attach runs the same way on every attach (Hello carries it), with apexattachment set, so apex set there records the attachment's own settings (MetaOp::Set{owner}, dropped on detach); apex set from the profile records the session's. Clients resolve a key through their own settings, then the session's. Preview is a live pipe through a converter (WEB.md §3, built): Preview.EXT names a command that reads the file on stdin and writes HTML (apex md for Markdown, cat for HTML and SVG unless set), the server keeps one rule per such extension running apex tool preview $file, and the tool renders the buffer into an HTML window beside it as it changes: a preview (kind Preview) at FILE's path. Preview alone names the app a rule's -client=preview falls back to, else Quick Look. The client drives file I/O on the I/O plane (WEB.md §1, built): GET file://path is one-shot, with a Watch header the stream stays open and every change brings a Body holding a FileFrame{version, path, bytes} (the daemon adds the path to the watcher and fans changes out to every watch stream) until the client ends the stream or its connection goes; PUT file://path writes. A stream belongs to its connection, so fencing changes nothing. A remote preview is a watch stream feeding a local copy under a path mirroring the host's, ended with the previewer's process, the file's window, or the lead. CONNECT host:port tunnels bytes to the host's network and http(s):// is fetched by the host (stage 2, built). apex io is the plane from a shell; apex cat is GET.

8. Extensibility

acme's tools port directly because the event model is the same, generalised:

  • win → apex term new.
  • Watch → twenty lines over apex events.
  • acme-lsp → apex lsp: subscribes to versioned buffer edits, feeds language servers incrementally (the log is an incremental sync protocol), writes diagnostics into a buffer, and installs plumb rules so B3 on an identifier goes to its definition. Formatting is one proposal.
  • Agents run in a terminal window and edit files directly; the server detects the edits through the file watcher (§9): a clean buffer takes them as proposals, a dirty one is flagged stale with Get in the tag, and by the nothing-is-lost principle a person's unsaved edit and the agent's write both stay visible. The CLI is a second door for agents that want to read selections, open windows or write to +Errors; a harness that needs exclusivity may take a buffer lease.
  • Plumbing is a rule table, as in acme, with two additions. Tools install and remove rules at runtime, with a priority, as metalog entries: the table is replicated state, the client can display it, apex log shows who installed what, and a tool's rules are tied to its attachment — when the tool detaches or is garbage-collected, a metalog entry removes them. A rule may target a tool, which may NACK, after which the server falls through to the next matching rule. Predicates are richer than acme's: file type, syntactic context ("in a comment"), selection shape. So "LSP handles identifiers in source files; paths in comments get the default" is two rules, and only the tool a rule names is consulted. The exec entry records the chain (rule matched, tool NACKed, next rule fired), and apex plumb --dry-run shows it. Bidding — every plumber voting on every B3 — is deliberately not the model: it makes each click wait for the slowest plumber and its outcome hard to predict; a rule that fans out to several tools in priority order emulates it if ever needed.

As built (plumbing): the rule is PlumbRule{verb, unlisted, owner, text, file, kind, isfile, isdir, action, to} in the metalog (PlumbRuleInstall{id, attachment, priority}), owned by the session (SERVER) or by an attachment, whose rules go with it. A verb is the command a rule answers: plumb is B3; any other verb is offered in the window's tools menu on B4 (shift-click without a fourth button): libdraw's menuhit as mariusae/plan9port's acme pops it up (client/menu.rs, the numbers and colours menuhit's) — the verbs the rules offer this window, opened so that the last one chosen sits under the pointer, which is warped onto it, so a click alone repeats it; tracked while the button is held, the item under the pointer highlighted in negative, none outside; released on an item it runs as B2 would, released outside nothing runs; more than 25 items scroll. A rule may be unlisted (Rule::unlisted, -unlisted, the bridge's unlisted), which keeps its verb out of that menu without taking it away: B2 still runs it wherever it is written. It is for verbs that want a place or an argument and would only crowd the menu -- a word a tool writes into its window to be clicked where it stands (apex-acp's Allow Always Deny Never on the line asking), or one that means nothing without what follows it (Mode plan, Resume ID). Whether a verb is listed is the rule's to say, not the window's, so the same word may be a menu item for one tool and a thing to click for another. exec is unlisted by its nature: it is every word, and so no word. Verbs are not written into tags either: apex does not put a rule's word there. A tool may furnish its own window's tag (set_tag, the text after |), as apex-acp does with Send — that is the window saying what it is for, not the rule table leaking into tags. B2 on a verb's word walks the rules with it, ahead of the shell.

As built, claiming a word apex knows: a word resolves the same way wherever it is written -- typed in a tag and B2'd, picked from the tools menu, apex exec, a tool's own exec -- and the order is one: a rule that claims the word here, then apex's own meaning of it, then the shell. Acme has this through the event file: a program holding a window's event sees every command in it, built-ins included, with a flag bit saying whether acme knows the word, and may write the event back for acme to perform it (exec.c, the nopen[QWevent] test before exectab is consulted). Apex has no event file, so the claim is a rule, and the bar for claiming is that the rule says which windows it is about -- -win, -file or a kind -- since a claim on Put is a claim to be Put, and a rule that says nothing about where it applies would be making it everywhere. Node::claimed answers this from the replicated rule table, so every node agrees and it costs nothing when nothing is claimed; a claimed word resolves to Handler::Server whatever it means, so the walk runs where the rules are.

Three answers, and apex's own meaning is the last step of the walk, as opening a file is for B3. A tool that takes the word has defined it: nothing else happens. A tool that declines hands it back, and the walk goes on to the next rule and at last to the built-in (Proposal::Builtin, which performs a word's own meaning without resolving it again, so a tool cannot loop by re-issuing the word). A tool that never answers has decided nothing: the walk goes on, but the built-in does not run, because silence is not a decision and Get would reload a generated window over a tool that merely died (Server::plumb_failed, beside plumb_next). The budget for an answer is a second for B3, which is a search, and ten for a verb, which may be the work the word names -- a formatter claims Put, reshapes the buffer, then declines so the ordinary Put writes the tidy text. A Plumb carries where it came from: at, the pointer or dot as a Span, and sel, what was swept or the selection the pointer was in; a click sends at alone. A verb B2 took from a window's body carries word too, where that word was -- acme's event file says where a command was -- so that a word written into a list acts on the item it is in, wherever dot is (ExecOp::from, Proposal::ExecFrom for a client that does not lead the window). The expansion is acme's, one for one (look.c's expand/expandfile, apex_core::expand), and runs on the server, where the files are, at the start of the walk: from the pointer, the text runs over isfilec characters to the first colon on the right (a scheme's http:/https: colon excepted), back over file, address and regexp characters, then over address characters after the colon; when the name before the colon is a window's name or a file relative to the window's directory (an empty name, :12, is the window's own), that is what B3 took, with the address text up to white space (123:1 gives line 123, the rest ignored as acme's address stops there; #12 a character); a http:// or https:// run is taken whole; otherwise the word (acme's isalnum). A sweep or selection is taken as it is, still read for a name and address. The rules see that text; when none takes it, a file opens at its address (acme's look3 after plumbing) and anything else is looked for in the body of the window B3 was in, its tag's included, as acme's look3 searches (ct = &t->w->body) -- not in the text last selected with B1 (seltext), which a window never selected in (one apex new made) is not, so its looks went off into whichever window was; only outside a window (the top row, a column's tag) does the look go to seltext. Not from a terminal's or a page's own text (a B3 without at/sel spans from a window whose body is not text): there is nothing there to look in, and a look must not go and select in another window; that plumb is refused. apex plumb -win=WIN plumbs as from a window, dry runs included. alt is no longer sent. Left out: <name> as an include file. Actions: Edit (open in the session), Run (a host command, the selection on stdin), Client{verb,args} (a ClientDo proposal to the UI, which may refuse; a headless leader always does), Tool(name) (ServerMsg::Plumb to the attachment of that name, PlumbAck within a second or taken as NACK). As built, the tool API: apex-tool is the Rust API for tools, a curated surface on Remote with nothing of the wire or the replicated state showing through: Tool::attach(name), next_event (Plumb, Edit, Renamed, Deleted; None when the session is over), answer(plumb, taken), offer(Rule)/withdraw, new_window new_page open read replace append insert_following select selection show show_line line rename tag set_tag set_clean set_owner set_live set_working notify unnotify notified alive delete exec exec_in errors watch unwatch set setting. notify(w) asks for the user's attention about a window (§4.1, notifications) and notified(w) says whether the window still is, false once the user has attended to it; alive says whether the session is, which is how a tool with no window of its own -- one that only offers verbs on others' windows, or only raises notifications -- knows it is over. tag/set_tag are the user's half of a window's tag, what follows |: the words before it are apex's own and stay the leader's business. new_page makes a window whose body is HTML, shown as a page: a tool with something to show that is not text keeps one window and writes it again with replace, rather than opening a window a turn. set_working is the pulsing handle (§11). A rule whose verb is a word apex knows claims it where the rule applies, and answer(plumb, false) hands it back to apex's own meaning of it (§6.2). open is a jump (acme's plumbing a file:line: the origin on the back stack, the line selected and shown, the mouse warped there); show is acme's show after addr=: the place brought on screen if it is off it, and nothing else moved. A tool that edits a window and wants its change kept in sight uses show; open is for taking the user somewhere. A window a tool writes to is written with insert_following (Proposal::Insert{follow}, which win has always used and the crate now offers): a dot sitting exactly at the point written at is moved past the text by the leader in the same round trip, so the typing point rides the output and nothing has to be clicked to go on typing at the end, while a dot anywhere else -- in a draft half-typed -- is left where it is and only shifted along by the text going in before it. replace moves no dot at all, which is what rewriting a status glyph or a block in place wants. Neither needs a show: the window follows its own output by acme's rule (§8), so having scrolled back to read something holds it still. Edit events are others' edits only: the leader applies every proposal as itself, so an edit's entries do not say who asked for it, and the crate recognises its own replacements in a watched window by their shape (buffer, offset, length, text) and drops them as they come back. Depending on apex-server directly is the internals, not the API. The bundled tools (win, lsp, preview) stay on the internals on purpose: they ship with the daemon and are rebuilt with it, so the lockstep costs them nothing, and win in particular needs what the crate hides. Tools in other languages: apex tool bridge NAME attaches as the tool NAME and speaks JSON, one object a line, on stdin and stdout (apex-tool-bridge, a client of apex-tool, its commands and events the crate's methods and events one for one): commands in (windows new open read write select show line rename live delete exec errors rule unrule ack watch unwatch set setting), each answered in order by id; events out (hello, plumb with the rule that matched, edit for a watched window's body by others, renamed, deleted, bye). The bridge is one Remote with the win-style before hook for edits; nothing of the wire protocol or the replicated state shows through. The Go package under go/ (github.com/mariusae/apex/go/apex) is a client of it: Attach, Window methods, Offer(rule, handler), Watch, Serve. The daemon drives a walk across those answers (Server::plumb_start/plumb_next); an in-process client walks synchronously. The trace of a walk is what apex plumb --dry-run prints; recording it in the exec entry is still to do. Clients say what they can do by installing rules on attach (macOS: URLs to open), so the server holds no platform knowledge. apex B is plan 9's B, and rc's rcmain defines B in apex terminals. The one-line rule form was chosen over plan 9's rules file: each rule prints as the flags that made it.

As built (apex tool lsp, crate apex-tool-lsp): unprivileged, as intended: a tool attachment named lsp that keeps a replica, reads Entries before applying them to turn BufferOp::Edit into incremental didChange (positions computed against the text as it still is), proposes Select/ReplaceRange/Errors/NewWindow+SetContent for what servers answer, and installs rules owned by its attachment: B3 on an identifier at priority 10, the verbs Def Refs Type Hov Sig Fmt Rn in the tools menu. Servers from settings (lsp.LANG), one per workspace root found by markers; diagnostics in root/+lsp. Not yet: completion, format on Put (needs rules ahead of builtins), semantic predicates for rules ("in a comment"). apex tool win (crate apex-tool-win) is acme's win ported from win.c: the shell on a cooked, echoing pty, the output point and typing run kept from the buffer's entry stream (our own inserts told apart by a queue of what we proposed), echo cancelled, ^C/DEL/^D as win reads them, raw mode when echo is off; Win in the top tag runs it as a command named Win. Unbound control keys are inserted as acme inserts them, which is what lets win see ^D. Fn-backspace is plan9port's DEL: devdraw maps the Mac's forward delete (NSDeleteFunctionKey) to Kdel, 0x7F, which acme's texttype has no case for and so types into the window like any key, and win reads a single typed 0x7F as the interrupt (removed from the window, the pty's interrupt character written, the typing dropped). The client does the same in the body of a live window, the kind a process keeps; anywhere else fn-backspace stays the Mac's forward delete, since a DEL typed into a file is only a hazard. The rules that make the window win's are the window's own (-win=ID, an id never reused), so the shell renaming it (awd on cd) changes nothing and two wins never overlap; Home and End are acme's Khome/Kend with iq1, the last insertion point (where typing or erasing last left the cursor, moved along by output before it): Home brings its line to the top when it has scrolled off above (a win's output ran past the prompt typed at), else shows the top; End brings it back when it is below, else shows the end; neither moves the selection. The client keeps, per buffer, where the last Insert or ReplaceRange proposal it applied as the lead ended, which is how win's output arrives. The window follows that output by acme's rule (xfidwrite's shouldscroll): when the point the text went in at was on screen, the end of it is shown, three quarters of the window down as for a window with an event reader; scrolled away from it, the window stays where it is. Win's Select after its output moves dot only; a Select proposal names no window, so it neither scrolls to nor focuses it. B2 on any text in its window (win's 'x'/'X' events, sende) types it to the shell, appended after the typing with a newline, dot after it: win holds a rule with the special verb exec, which takes every B2 command in the windows it applies to that no builtin and no other verb took, the whole line as its text, and is no word in the tools menu.

Win and the round trip: every proposal from win is a round trip to the leader, and with a UI attached the leader is the UI, across the network when the daemon is far. Programs print a line per write (stdio is line-buffered on a tty), so win reads a line or two at a time; it proposes everything the shell has produced since its last proposal as one Insert (the batch grows to fill the wait, so the RTT bounds the latency of output, not its throughput), and the leader moves a dot sitting at the output point past the text in the same proposal (Insert{follow}), where a second Select round trip used to. Measured locally: seq 1 1000000 into a win went from 46s to under 2s; the proposal count for 100k lines from 53k to 2. The daemon's watch sync, run after every message, skips the disk when the set of open files is the one it saw last.

Typed client libraries (Rust, Go) are generated from the schema for programs that want more than the CLI.


8a. The Edit language — apex-edit — v1

The Edit language is an independent crate, a careful port of plan9port's acme implementation rather than a reimplementation from the manual:

source (plan9port src/cmd/acme, src/libregexp) role
edit.c parser: addresses, commands, text and regexp arguments, { } blocks
ecmd.c command semantics: a c i d s m t x y g v p = u B D < | >, address evaluation
elog.c the change log: a command's edits are collected against the original text and applied atomically at the end, with acme's ordering and overlap rules
libregexp plan 9 regular expressions: leftmost-longest matching, \n in classes, no backreferences; Rust's regex crate is leftmost-first and is not a substitute

Scope is acme's table exactly: sam's language minus k n q ! cd, plus acme's B and D. Everything with an effect (u e r w b B D < | >) is not performed by the crate; it is returned as an intent for the caller (core, then the handler) to carry out, so the crate stays pure. Where acme and sam disagree (dot after a change, changes out of sequence, $ at the end of an unterminated text, the bare newline command) the crate follows acme; the crate's README lists them. X/Y are not supported (no file menu).

Interface: the crate takes a text (a trait over char-indexed, read-only text, satisfied by a rope or a &str), a dot, and a program, and returns the resulting change log (Vec<Change{start, end, text}> in original coordinates, already validated non-overlapping and ordered), the new dot, any output (p, =), and any intents. Core lowers the change log into concrete Edit entries (§5).

Acceptance tests are the definition of "carefully ported":

  1. Golden tests written from sam(1) and acme's documented semantics, one file per feature: each address form and combination, default addresses per command, s with & \1..\9 and g, x/y/g/v nesting, empty matches (x/^/, x/$/), { } blocks, m/t including moves into the moved range, u counts, error cases (overlapping changes, changes out of order, bad addresses) with acme's exact messages.
  2. Differential tests against plan9port. sam -d runs the same language from stdin on a file. A test harness builds plan9port's sam from source (clang only, no dependencies) into the test directory, feeds it each program and input, and compares the resulting file and p/= output with the crate's. Skipped when plan9port cannot be built; run in CI. Programs come from the golden corpus and from a generator (random addresses and commands over random small texts), so the comparison covers cases nobody thought to write down.
  3. Regexp differential tests. ,x/re/ =# in sam -d prints the char address of every match, which makes sam itself the regexp oracle: generated patterns and texts, compared match by match, including the leftmost-longest cases and empty-match stepping.
  4. Performance: x/re/ c/.../ over multi-megabyte texts, thousands of matches, and deep nesting, with criterion, so regressions are visible before the UI exists.

9. Files

The server runs where the files are; that is the whole remote story.

  • Two derived flags per buffer, each with its own signal: dirty = version differs from the version at last load or Put (acme's Put appears in the tag); stale = the disk changed underneath (Get in the tag).
  • Watching. The server watches the parent directories of open files (editors and git checkout replace files by rename, which breaks per-file watches) with FSEvents/inotify via the notify crate, debounced. On an event it hashes the file; an unchanged hash (touch, the server's own Put) is ignored.
  • Clean buffer, disk changed: the server diffs the new content against its replica at version V and proposes the edits with base V. Diffing rather than replacing lets every view's selection and origin adjust through the normal edit path. If the proposal is rejected because the user typed meanwhile, the buffer is now dirty and falls into the next case. The clean-buffer case works by version alone; no lease is taken.
  • Dirty buffer, disk changed: the buffer is marked stale with the disk hash and Get appears in the tag — the word is the signal and the affordance, as with Put. Put refuses once with acme's "modified since last read" message and overwrites on the second Put. Get reloads. A later Merge may three-way merge base, buffer and disk.
  • Directory windows refresh from the same watches. Deleted or renamed files are flagged the same way instead of failing at the next Put.

As built (apex-server/src/watch.rs). Parent directories are watched with notify; the server hashes the file on every event and ignores it if the hash equals what it last wrote there or the buffer's recorded disk hash. A clean buffer gets SetContent{version} — base-versioned, which matters: the daemon's replica lags the UI by a round trip, so it can judge a buffer clean that the user has just typed into. The leader lowers a SetContent whose version has moved on into Stale instead, so typing is never overwritten by a reload; Get sends an unversioned SetContent. A dirty buffer gets Stale{hash}; Put on a stale buffer refuses once with "modified since last read" and writes on the second. Directory windows are watched too (the directory itself, for its entries): a change under it lists the directory anew when the window is clean, and flags it stale when edited, the same flow. A stale window has its own handle colour, gold (STALE), a caution in one of acme's yellows, chosen by simulating deuteranopia to stand clear of every other handle colour and the tag's border (a dark cyan fell on the raspberry live once was, an orange on the scrollbar's olive, a medium blue on the border's purple-blue): dirty, and the disk has moved on underneath, so Get would drop the edits. Diffing rather than replacing and delete/rename flags are not done.


10. Terminals and web windows

Terminals are libghostty-vt on the server, with the pty apex's own (crate::pty, term_loop): Ghostty's VT library parses the stream and keeps the screen, and opens no pty and starts no program (it makes no threads at all), so the pty, its loop and the keys are ours. The term shard is pinned to the server. The client renders rows from its mirror and proposes keystrokes. Attach sends the visible grid; scrollback is paged. Resizing is a proposal (Resize{cols, rows}) the server applies to the pty. Selection inside a terminal (v2) is a window shard entry like any other selection, computed over the mirrored rows, so B2/B3 on terminal text work exactly as in text windows.

As built: terminal selection is client-side, not a shard entry. The term shard carries View{top}, the history line in the viewport's first row, and a selection is two (column, history line) positions, so it stays on its text as the terminal scrolls. B1 drag selects (acme's yellow), and a double-click selects as it does in a text window -- the same node::double_click, over the rows on screen taken as lines without the blanks after their text: the word, what brackets or quotes enclose, and the whole line at either end of it (so a double-click anywhere past the end of a row's text takes the row); cmd-c / Edit ▸ Copy, Snarf in the window's tag, or the B1+B2 chord send TermText to the server, which has the scrollback, and its answer is a Snarf proposal (so Paste and Send have the text); the clipboard follows the snarf buffer. Wrapped lines join, as a terminal's own selection does. cmd-a selects the viewport. B2 and B3 sweep too (acme's textselect23, in but2col/but3col): what was swept is executed or plumbed, a plain click takes the word under it, and the B1 selection is left alone. Keys and pastes first scroll the terminal back to the bottom, republishing the rows at once. History lines are numbered from the oldest line kept, so a selection drifts once the scrollback limit truncates; a selection does not outlive that.

As built, a grid is drawn cell by cell: a row is shaped as one line, so the font system still does what it does -- ligatures, fallbacks, the right glyph for a combining sequence -- but every glyph is then painted at its own cell's x (window.paint_glyph, the row's byte-to-column map), and the underlines with it. A glyph whose advance is not a cell's width cannot push the rest of the row along: an icon from a Nerd Font is a whole em wide where a cell is 0.6 of one, and a CJK ideograph is two cells and a spacer. apex carries the symbols font itself (assets/SymbolsNerdFontMono-Regular.ttf), registered with CoreText for its own process at launch and named as the fallback behind Menlo and Lucida Grande, so exa --icons, a powerline prompt and the rest draw their private-use glyphs whether or not the user has installed a patched font. Icons are drawn at their own size, overflowing into the cell after them as they do in other terminals -- which is why the programs that print them print a space after.

As built, the VT library: ghostty-vt-sys builds libghostty-vt from a pinned Ghostty commit with Zig (its C API is on main alone; the tagged releases carry the OSC and SGR parsers and no terminal), keeping the source and the archive under ~/.cache/apex so it is built once per commit. APEX_GHOSTTY_SRC builds a checkout instead, APEX_GHOSTTY_LIB takes a built one and builds nothing, and ZIG says which Zig. A C shim (shim.c) walks the grid and hands back the cells of a term shard -- a character, a foreground, a background, flags, a link -- so the library's enums and sized structs, which are not stable yet, are read from its headers by the compiler rather than copied into Rust by hand. Colours come packed as the shard carries them: one of the sixteen by its index, for the client's theme to colour, and anything else exactly. A cell with no text but a colour of its own -- what an erase leaves behind while a background is set, which is how a program paints the part of a row it writes nothing on -- keeps that colour in the cell rather than in a style, so the shim reads the cell's own content as well as its style; a style alone leaves the colour showing under the text and nowhere else. What a program asks for the library answers itself -- device attributes, the cursor's position, the colours (OSC 4, 10, 11) -- writing the answer through a callback that the loop puts on the pty; the colours it answers with are the client's, given to every terminal as they change.

As built, labels and environment: the pty loop is ours, with win's label scan in front of the parser. A terminal's window is placed by one rule (term::place): its path is the directory OSC 7 (file://host/path) reports, with its slash, and once it has reported, nothing else ever is; its label is an xterm title (OSC 0/2) or plan9port's ESC ] ; text BEL label (apex label), whole, blanks, bars and all -- a coding agent writes its state into one over and over (renaming... ⠹ | proj), and the label is state beside the path, not a word in the tag, so nothing needs making into one word. apex awd [LABEL] reports the directory and labels the window LABEL (the host), as plan9port's awd names it. The reported directory is the terminal's, where B2/B3 resolve relative names. The win tool places its window by the same rule. A new terminal is at its directory, labelled with the host; Newterm cmd args runs that through the login shell instead of a shell, labelled with the command, as win cmd does. The shell is a truecolor xterm-256color with TERM_PROGRAM=apex, apexsession (the session's id), apexsessionlabel, APEX_SOCKET and winid (the terminal's window, as acme's win has it) set, so apex inside it addresses the session and the window it runs in; commands run from tags get the same. The shell starts once its window exists (the TermWindow proposal applied wherever the leader is), since the id is only known then; a resize that arrives first sets its starting size. The shell keeps Newterm.scrollback lines of history (apex set Newterm.scrollback 50000 in the profile; 10000 by default, read when the terminal is made), and Clear, offered in a terminal's tools menu by a server rule (apex term clear $win), drops the scrollback and keeps the screen. A terminal's scrollbar is a text window's: the bar dark, and the part of it the viewport takes of the whole screen -- the history and the viewport together -- in the paper, so how much of the output is in view, and where, reads the same in a terminal as anywhere else. TermOp::View carries both what it needs, the viewport's first row and the screen's rows (total). A resize keeps the viewport where it was in the history as far as it can (a taller screen takes its extra lines from the history above, so a viewport scrolled back by fewer lines than the growth ends at the bottom); and a size the window takes while the terminal is scrolled back is held (TermHost::held_size), neither the grid nor the pty resized, until the terminal is back at the bottom (a key, a paste, a scroll), so the program hears of one resize then and its redraw (a coding agent's, which clears the scrollback) cannot take away what is being read. The shell is the Newterm.shell setting (apex set Newterm.shell zsh in the profile), else the daemon's $SHELL. Keys go xterm-style with option as meta: ESC before the key itself (opt-b is ESC b, not ∫), opt-left/right as ESC b/ESC f (Terminal.app's defaults, what zsh and bash bind for words), opt-backspace ESC DEL, and other modified keys in xterm's CSI 1;m form (opt-up is ESC [1;3A). OSC 8 hyperlinks travel in the term shard (Cell::link into TermOp::Links), draw underlined (bold cells in the font's bold weight), and B3 on one plumbs the link rather than its text; B3 on a bare URL takes the whole of it (a file word would stop at ?), less the punctuation closing a sentence. OSC 52 (a program setting the clipboard: tmux, neovim, apex snarf from afar) goes into the snarf buffer as a Snarf proposal and, as ServerMsg::Clipboard, onto the clipboard of every UI on the session. A tool's snarf (Tool::snarf, the bridge's snarf {text}) is the same: a Snarf proposal, which the daemon, seeing it come from no UI, also sends to the UIs as ServerMsg::Clipboard. Chords in a terminal: B1+B2 (or option while B1 is held) copies the sweep, B1+B3 (or command) types the clipboard into the shell, which the snarf buffer gets too. A terminal's tag has Send, win's: the text swept with B1, else the snarf buffer, typed into the shell with a newline (the client sends a visible selection itself; the server sends the snarf buffer). Typed, not pasted: newlines go as Return and nothing is bracketed (TermHost::type_in, ClientMsg::TermType), so what is sent runs. A shell that asked for bracketed paste holds a paste on the line to be read, which is right for Paste and wrong for Send, whose whole purpose is to hand the program its input. B2 in a terminal is the same by another route: a word, or the selection when the click lands inside one (acme's execute), goes to the program there rather than to a shell of its own — win's rule for an old command line, and the window already has a shell. Built-ins and the verbs of rules are still taken first, so Clear and Snarfout mean what they say; only a word nothing else took is typed. A terminal scrolled back stays on what it shows while output goes on below, as win does, until a key or paste brings it back to the live screen. The wheel over a terminal goes to the program when it asked for the mouse (DECSET 1000/1002/1003: wheel buttons 64 and 65 at the cell, SGR or X10 form) or runs on the alternate screen with alternate scroll (DECSET 1007, xterm's default: up and down arrows); otherwise it scrolls the scrollback. So does the scrollbar, except on the alternate screen, where a full-screen program keeps no history for it to scroll: there B1 on the bar is Page Up to the program and B3 Page Down, one a click (and repeating while held, as the bar does), however far down the bar -- the program knows how far its page is (TermHost::page). The scrollbar says it by sending no cell.

Web windows are out of v1. The prototype's headless-Chrome screencast is a server-side renderer and fits the model, but it is bandwidth-heavy over ssh, and the alternative (URL as server state, client-side rendering) breaks "all state on the server" for page state. Decided: the URL is the state, rendering is the client's, and network and file I/O go through the server on an I/O plane beside the log; see WEB.md, which also makes Preview a live pipe through a converter. As built (ARCHITECTURE.md §5): a page is one window kind, Body::Page(Source): its document a buffer of HTML or at an address (the window's name, as a terminal's directory is), fetched via the host, the client or a tool; its navigation, a reload counter and a buffer page's scroll in the log (OpenPage, Navigate, Reload, PageScroll); the client's wry view over the body draws it from that state. Pages are tools': apex tool web answers Web and Newweb URL, owns their pages, keeps their history and answers Back, Fwd and Get; apex tool preview offers Preview. A Goto to a URL nobody shows opens a page on it, which the Web tool takes over. The view's traffic goes through the host: a localhost CONNECT proxy per link whose tunnels are streams on the I/O plane; apexfile:///path is a host file fetched on the plane and watched, the page reloading when it changes (WEB.md §2.3, §2.4). A buffer page (cmd | apex web, a preview) is patched in place as it changes (WEB.md §2.5).


11. Client

The gpui prototype becomes the client. It holds one attachment per OS window, each to a session on a local or remote server. The window title is host/session; clicking it opens the session selector, listing sessions on the servers the client knows, with "new local session" and "new remote session" at the bottom. Switching is opening another window or re-pointing this one (detach, attach).

  • Holds a full replica of the shards it leads and a paged replica of terminals. Rendering reads only local state; the element code (text_element, term_element, web_element) already paints from its own records and needs no change.
  • Input routing: B1/keys on a led buffer → local apply + append. B2 → §5 split. B3 → plumb command to the server unless it is a plain Look, which runs locally. Keys over a terminal → proposal. Wheel/scroll → local window.Origin entry (leased) or a page request for terminals.
  • Scroll origin is a window entry so re-attach lands where you were; it is cheap because it is coalesced per frame like everything else.
  • The system clipboard is client-side, so Snarf/Paste work remotely with no protocol support.
  • Fonts, geometry and colours are client-side. Colours follow plan9port exactly (README.md, Colours).
  • As built: +Errors behaves as acme's flushwarnings: new text is appended, selected (textshow(q0, end, 1)), and when its start is off screen the origin is set so that it sits a quarter of the window down (Node::errors records the position; the client's element applies textshow's rule).
  • As built: navigation is session state, so a session re-attached elsewhere keeps its headspace: Layout{nav_back, nav_forward} of Loc{name, pos} (Pos::Keep|Chars|Line|LineCol), moved by LayoutOp::Visit{from, to} and NavPop{back, at}. One proposal makes a jump, Goto{loc}: the leader records the origin (its seltext and dot), lands (select, reveal, warp) when the window is open, else leaves the place for whoever opens files (the app asks the server and lands when the window arrives; a headless daemon opens it itself). The lsp tool lands through Goto; plumbs to file:line and apex B are Gotos; ⌘P picks are too. Back and Fwd are verbs the lsp tool offers everywhere and answers with Nav{back}, which pops; ⌘[ and ⌘] are a UI hack that executes those words in the window under the pointer, on purpose: the keys are not the functionality.
  • As built: ⌘P (File ▸ Go to…) is Zed's file finder in acme's colours (client/finder.rs): every open window of the session (files, directories, terminals, win, +Errors, marked ● or ▶) and the files closed lately (○, "closed": the last fifty per session, each once, kept in recent-files on this machine, noticed as windows go), ranked as Zed ranks: nothing typed, the open windows alone, in layout order (the closed files are there to be found by name, not scrolled through); a query, a fuzzy score in the spirit of Zed's matcher (file name best, then after / and at word starts, runs of consecutive matches, a penalty for the wrong case and for long paths), open before closed at equal scores. Enter or a click shows the window or opens the file, and warps the pointer to it as acme's warps do. ⌘⇧P (Go to in All Tabs…) is the same across the window's tabs: each tab's open windows, from its session's replica (this one's, and the parked ones' in the pool, Pool::parked_nodes), in the tabs' order, and each one's files closed lately; every row carries a badge naming its tab as the strip does (with the host for one elsewhere), this tab's in the accent colour and marked "here", and this tab's rows come first at equal scores. A pick in another tab switches to it and goes there as a pick in it would; a tab still attaching lands on the window once it is.
  • As built, tabs: the title bar carries a tab per session the app has open, in the order first shown (Pool::order), the current one selected. A tab is the app's own: TabId is made by the client, never changes and means nothing to any host, and the session behind it is data the tab carries (Tab::url) -- the host and label always, the session's own identity once an attach has said what it is. Identity cannot be leaned on: end a session and attach to its label again and the host makes a new one with a new id, so two attaches disagree about what a name means. Every window, key, click and notification therefore means a tab by its id; Pool::open is the one place a url becomes a tab (the picker's pick, the launch target, a place in another session), and the one place two urls are weighed against each other -- the same identity, or, while either side has none or holds one the session has left behind, the same label on the same host. What comes off a link names the tab's session (Pool::named); nothing else does. Before this the pool held sessions by url and identity churn showed as two tabs for one session -- one attaching, one offline -- with the window waiting on a link that had already landed under another name, and a failing attach could let go of a live tab that shared the label. A tab is the app's own state, not the link's: it is made when the user makes it and brought back at launch, and it goes only when the user closes it (or its session is gone). So a tab keeps its place while its link is being made, and keeps it when the link fails or ends, saying what it is doing after its name -- "connecting…", "restoring…", "fenced", "offline" (Pool::Tab, and the fuller sentence in its card). A tab whose session is not there any more is the one exception: nothing can bring it back, so it goes. Showing a tab with no link asks for one; the link is made off the UI thread, and moving to another tab meanwhile loses nothing -- what lands goes to the window if the window is still on that tab, and is parked otherwise. While a tab has nothing attached the window is not acme at all but a blank page with what it is waiting for in the middle of it, and the bar, the keys that reach the other tabs and the picker still work over it. The tabs share the bar between them, as ghostty's do: every one the same width, the row reaching the far right, with + after it. Each is a pill inset in the bar, its name centred in it and the key that reaches it (⌘1 to ⌘9) at its right end. The colours are one rule, not a palette: the bar is acme's own paper, a tab lies a step off it, the pointer on one lifts it another step, and the one in front lies a step beyond that (theme::step, each step 4.5% toward the ink on light paper and toward the light on dark, so the same rule reads on either). A tab's × shows while the pointer is on it, at its left end, centred and a little larger than the name, over the tab's own paper; it takes no room of its own, so a tab is the same width whether the pointer is on it or not and no tab shifts as the pointer passes. + is a round chip at the far right. There is no chevron in the bar and no key of its own for searching the tabs: ⌘T opens the picker, which is that search and everything else besides. The bar is 34 high, the traffic lights sit on its centre line, and it keeps a margin on the right so the + is not flush with the edge. A session's host, dimmed after its name, sits on the name's baseline rather than centred in a line box of its own, where the smaller glyphs would ride high. Another tab switches to its × lets a parked one go, the current tab's × (and ⌘⇧W) lets this session go and shows the one parked last (the last tab's closes the window, as a browser's does), and + (⌘T) opens the picker. There is one picker, however it is opened -- + or ⌘T -- and it is every way into a session at once: the window goes quiet behind it and it sits in the middle, a field with the rows under it, each a name and, dimmed beside it, what picking it does. The rows are the tabs this window has open ("Go to session"), the sessions that are there to open -- what the hosts answer with and what was closed lately -- ("Open session"), then, for a name typed that no session on that host has, the making of it on each host ("Create on "), and "Add a host…" at the very bottom. So typing another with a tab anotherfoobaz and a closed session anotherfoobar offers to go to the one, open the other, and make another on each host. A name that is no label says so and offers nothing to make. The card that tells a tab's state hangs from the strip's bottom edge, not from the tab's, and in a layer under it, so it can never cover the tab it belongs to; a tab right-clicked renames its session, this window's or another's (on its host, through the CLI's rename-session). The A tab hovered shows a card: the session, its host, the link's state (leading, fenced, disconnected; parked and when last heard from) and the round trips spelled out, the heartbeat's as "Ping" and a log append's acknowledgement as "Log" (the strip's "ms/ms" readout and the ⚡ are gone: a fenced or disconnected tab shows it by fading). A tab held shows no card, nor do tabs passed over while one is dragged; the card comes back only when the pointer comes to rest on a tab again. In full screen the strip stays, with View ▸ Always Show Tabs in Full Screen (on by default, kept in fullscreen-tabs); off, it hides, and the pointer at the top brings it over the top of the layout as the menu bar comes (the pointer is asked of the system each tick, since the menu bar takes its moves), going once the pointer is below it; AppKit's own title bar container, which would slide down empty with the menu bar, is hidden while full screen lasts. ⌘1…⌘9 go to the Nth tab, and ⌘⇧[ and ⌘⇧] to the tab on either side, wrapping at both ends (macOS hands over the shifted character, so the bindings are on ⌘{ and ⌘}). Tabs drag to reorder, as a browser's: a tab held with B1 is a click on release until it has moved a few pixels; after that the tab floats under the pointer (keeping the grip it was taken by, kept within the strip's tabs), its place in the row stays as an empty slot, and it passes a neighbour once it has come to occupy the neighbour's place: rightwards when its left edge is past the neighbour's left edge, leftwards when its right edge is past the neighbour's right, and a narrower tab (which can sit wholly inside a neighbour) by its centre passing the neighbour's; measured against the neighbours' places with it out of the row, the two tests excluding each other, so a swap cannot undo itself; the order is kept on release. The tab order is kept in open-sessions beside the other state files, and at launch every tab of last time is in the bar from the first frame, saying "restoring…" while its link is made in the background, by identity: one whose session is gone (ended, or a new daemon) is forgotten rather than made anew, and one that could not be reached for any other reason stays, offline, to be attached again by showing it. Sessions shown by other windows are theirs, not tabs here. A tab is compared against what the windows show as their links know it now, not the launch target: a window attached by label has the session's current id, where the target carried last time's, stale once the daemon has been restarted; the same label on the same host under another id is last time's, skipped. Nor is a link parked for a session a window shows: the daemon lets the latest UI attachment lead, so a second attachment of this client's own would fence the window it shows.
  • As built, one tab: one tab is no tab. The strip is then a plain title bar with the session's name (its host and state dimmed after it) in the middle and the + at the right, as ghostty's and Terminal's are; the chips come back as soon as there is a second tab.
  • As built, the picker: while it (or the finder, ⌘P) is up it has the keyboard. Its field is a one-line editor (field.rs) with a cursor and a selection and the keys a Mac field answers: arrows with shift, option and command, delete back and forward, ^A ^E ^B ^F ^D ^H ^U ^W ^K, and the Edit menu's ⌘A ⌘X ⌘C ⌘V ⌘Z on it; the window keys do nothing below it. As hosts answer, the cursor keeps the row it is on wherever that row moves to (Selector::keeping); untouched, it lands on the first row (the tabs' list on this window's tab). ⌘⇧K switches to the session parked most recently, and ⌘, opens (or makes) the host's ~/.apex/profile. ⌃Tab steps through the connected sessions, the title bar's tabs, live, as a browser steps its tabs (switcher.rs): each press switches the window to the next one, most recently settled on first (this one, then the parked ones by when a window last stopped on them; the ones passed through in a walk do not count, so from a walk a→b→c the next ⌃Tab goes back to a), ⌃⇧Tab to the one before; the order is the one when control was pressed and holds while it is held, so the presses walk the list rather than bouncing between the last two; letting go ends the walk where it is, and ⎋ with control still held goes back to where it began. (There is no list to look at: the tabs are the list. ⌘Tab is the system's; no app can take it.) The new tab's picker remembers hosts, not sessions (known-hosts beside the other state files, seeded from the recent sessions; local always first). It is a section per host, the host's name with its provider in parentheses dimmed and a × to forget it, holding the host's sessions and "+ new session", which asks for a name and creates it there. A section opens with the sessions the host had when last asked (known-sessions beside the other state files, plus what the recent sessions say: they are mostly the same), and each host is asked again in the background (the section says "asking…" meanwhile, then shows the answer, or keeps what it had and says why the host could not be reached), so a host that is down holds nothing up; an answer for an earlier opening is dropped. "+ new host…" opens a form: the providers as pills (ssh and every apex-remote-NAME on the PATH; ←→ or a letter picks one) and the host; enter remembers it and asks for its sessions; a host without apex yet gets ours first, as attaching would, and is asked again. "+ new session" is offered on every host, reachable or not (attaching tries again and says what is wrong). The search narrows sessions and hosts, and a URL typed in still creates directly.
  • As built, parked sessions: switching a window to another session (a tab, ⌃Tab, the pickers) or closing it (the red button, Exit) does not detach: the session is parked, still attached and still leading, in an app-wide pool (client/pool.rs, a gpui global), where a task tends every parked link: entries applied, tools' proposals answered, tags refreshed, gotos opened, the rules' asks answered as far as an unseen session can (open yes; the rest declined). A window asked for a parked session, by a tab or a picker or as a new window, takes it back at once with its state as it was left (web views are made again). A link's wake goes through a target that moves between the window and the pool. Eight stay parked, the least recently parked let go beyond that; a parked link that ends is let go too. Neither takes the tab with it: the tab stays, offline, and showing it attaches again. Quitting closes them all, and nothing is parked across a launch (a remembered window attaches afresh). Every link the app makes -- a tab switched to, a tab of last time, a Reconnect -- is made by the pool, off the UI thread, and lands in the window if the window is still waiting on that tab (Pool::start, Pool::landed).
  • As built: Enter repeats the leading whitespace of the line it ends, up to dot, in every body: acme's -a, always on. The title bar shows, left of the connection mark, the heartbeat's round trip and the log's (an entry flushed to its Ack), as 1ms/2ms.
  • As built: full screen (⌘⌃F, View ▸ Enter Full Screen) hides the title bar, acme's area is the whole screen, and a window's full-screen state is remembered with its frame. B3 is acme's look and shift-B3 looks backwards (the mariusae/plan9port acme's look3(..., reverse): search with reverse, the last occurrence ending before dot, wrapping), always: no rule changes what B3 does with an identifier. The lsp's Def is ⌘-B3 (Plumb{verb: Def} at the pointer, walked as a verb: the lsp's rule takes it in a source window, elsewhere "no rule takes it here") and Back is ⇧⌘-B3, exactly what ⌘[ issues -- and B5, a mouse's forward button (the fifth, past B4's back), issues it too, in the window under the pointer, on the press. On a laptop, where ⌘-click is B3, ⌃⌘-click is ⌘-B3 and ⇧⌃⌘-click is ⇧⌘-B3. The picker's recent sessions carry a × that forgets them.
  • As built: a window is live when a process is behind it: a terminal whose program runs, or a text window a tool keeps so (WindowOp::Live{by}, the win tool's attachment; the state ends with the program, or with that attachment, so a crashed tool leaves nothing stuck). Not a colour of its own but a mark over one: the handle is stippled, ░, in the dirty colour -- dirty, but going on; on dark a paler one, since a dot a pixel wide shows only by how much lighter it is than what is under it (Theme::live_ink) -- or in the paper's over a dirty handle, where the dirty colour would not show (text_element::handle: a handle is its colour, clean, dirty or stale, and over it the marks, live's stipple, working's, and a notification's face, any of them with any other). Dirty there is what Del asks about (Node::window_unsaved), not the buffer's flag: a live, owned or scratch window's text is a transcript and never unsaved, so a terminal or a win is clean under its stipple however much it has printed. It was a raspberry of its own once, one colour more to tell from the rest. Del does not ask (the text is a transcript, not a file), and apex win list marks it >. The tag says the same: a live window is offered no Put, since there is no file of that name to write it to. A window's scratch flag says it too, and says it whether or not anything is behind it just now: a scratch window (an errors window, a terminal's, a tool's pane or transcript, a page) has no file behind its path -- no Undo, Redo, Put or Get for it, and Del asks nothing. The flag is the buffer's, set when the window is made (BufferOp::Create{kind, scratch}), where once a name's last part beginning with - or + said so; see Windows are what they are.
  • As built: a window is owned when a tool says it made it and writes it (WindowOp::Own{by}, Tool::set_owner), which is a different thing from live and outlasts it: live comes and goes with the work, where a window is owned for as long as its tool is there. What it holds is the tool's doing and not a file's contents, so its tag has no file menu at all and Del asks nothing. This is acme's rule exactly: acme turns w->filemenu off the moment a program opens the window's event file and on again when it closes it (xfid.c), which is how win and every acme-integrated program has always worked; acme also lets a program say it outright, nomenu on ctl. The owner is named -- the name the tool attached under -- so a rule may say -owner=RE and be about one tool's windows and no others: the client's Snarfout is -owner='win-.*' -kind=file where it used to guess at -file='/-[^/]+$'. A window no tool owns is owned by nobody and its name is the empty one, so -owner='' is how a rule says it is about real files and not any tool's windows: the lsp's Back and Fwd are -kind=file -owner='', the session's jump stack being for going about the source and not for a terminal, an agent's window or a win's, each of which has its own words in its menu. Tool::set_clean is acme's ctl clean: the writing dirties a window, and this says the writing was the point, leaving dirty to mean what it means everywhere else -- your text, not acted on -- so a tool can spend the three states on saying something better than that it has been written to. The app offers Snarfout in terminals and win windows: the last command as $ cmd (the prompt normalised) and its output, the lines between the last two prompts (transcript::last_output: the last line is the prompt, earlier prompts begin like it and carry its marker), read from the host for a terminal (TermRead), into the snarf buffer and clipboard.
  • As built: a window is working when a tool says so (WindowOp::Working{by}, Tool::set_working): its handle is stippled, ░, in a colour that breathes between the colour work is drawn in and the handle's own, a second and a half to the cycle, for as long as the work lasts -- on the other half of the ░ lattice from live's, so a live window working shows both. That colour is the one a terminal's progress bar is (Theme::progress, a blue no handle colour is), so a handle and a bar saying the same thing look the same; on dark a paler blue of the same kind (Theme::work_ink), for the reason live's is. It is not a state but a mark over one: a clean, dirty, stale or live window can be working, and shows as it was the moment the work ends. It is for work with nothing to show while it runs, where a window would otherwise look idle: an agent thinking, a language server indexing, a build. Like Live, it holds only while the attachment that set it is there, so a tool that dies leaves no window pulsing for ever, and the client draws those windows again each tick while any of them is working. A loading web page, which pulsed before any of this existed, is the same thing said by the client itself. A program in a terminal says it too: OSC 9;4, ConEmu's progress report (1;PERCENT going, 3 going with no telling how far, 0 done, 2 failed, 4 waiting), which shells and build tools emit and other terminals draw as a bar, pulses the terminal's window while the work goes on and stops when it ends, fails, pauses -- or when the program does, whatever it last said. The bar is drawn too, as those terminals draw it: two pixels across the top of the terminal's text, in a blue that is no handle's colour, as far along as the program says and the whole width while it does not say (TermOp::Progress{going, at}, the terminal's own state, so every client draws the same bar). The session itself says this one (SERVER), which is in no attachment table and outlives every tool, so window_working takes it as always there. A tool may say how far along too (WindowOp::Working{by, at}, Tool::set_progress): busy is what progress is said of, and the handle says both -- its arc turning while the work does not say how far, the circle round it filled clockwise from the top as far as it does, over a faint whole one, wherever the handle is drawn (a tag, a stash card, a minimized column, the sidebar). A terminal's program saying it (OSC 9;4) fills its window's handle so too, and still has the bar across the terminal's top that other terminals draw, the terminal's own state; the two are one thing in two places, which may yet become one.
  • As built: a window may be diagnostic (WindowOp::Diagnostic, Tool::new_diagnostic, apex new -diagnostic): a tool's report on how things stand -- its errors, a language server's diagnostics and what it says, its state -- that is not the user's work and is not laid out over it. Every +Errors window is one. A diagnostic window is made in the stash, in the same layout entry that places it, so it is never seen in a column first; what is new in it is a toast (toasts.rs), whatever wrote it: added at its end (an errors window's appends), or, its text written anew (a server's diagnostics, replaced whole), the lines that were not there before -- never lines going, and not the lines about the file the user is typing in (the window the keys go to, unsaved), which are in front of them and come and go with each key. The windows already there when a client first sees the session say nothing of what they held. One the user has brought out and is showing lines is seen as it is written, and toasts nothing; one laid out but showing none goes back to the stash, as an errors window always has. Working, its card comes out of the stash's bunch as a notified one does, its handle turning (or filling), and goes back when the work ends.
  • As built: apex tool lsp gives each server it starts (one a language and a project root) a diagnostic window at the root, labelled with the server's name (its command's, or its script's when an interpreter runs one), made as the server starts: working from then until the server is ready, and while any of its $/progress goes on (indexing), as far along as the least far that says. Its text is the server's diagnostics, written once they have been still for a second and a half -- a line being typed has errors that go with the next key -- and below them what the server said for the user (window/showMessage), and that it exited, if it does. The preview tool says a converter's complaint in the file's directory's errors window, the page left as it was, rather than ending.
  • As built: apex has one window. Everything else it has open is a tab in it, so two views of one session -- which could only fence each other -- cannot happen, and a session is where the user left it. The app remembers that window with its session URL and its frame (last-sessions), saved on every move or resize and on Quit, and opens it again at launch, on its session and where it was, with the sessions beside it back as its tabs (Pool::restore). A second apex-ui process, which apex attach starts for a host, is its own app with its own window; nothing inside one opens another. The name in a tag is editable, as acme's is: winsettag leaves a typed first word alone, a click in the tag or a command from the window commits it (wincommit: the buffer takes the name), and Put resolves a relative name where the window is and makes it absolute. The bar that divides apex's half of the tag from the user's is the first one after the name (tag_bar): a name may hold a bar of its own (a file called a|b), and it is not that one. New in a tag is an empty window; apex new [LABEL] is the same with stdin in it (acme's cmd | New); apex open opens files.
  • Over a WAN, mosh-style predictive echo is unnecessary for editing (the client leads) and only relevant for terminals; it can come later.

Tiling, as built (apex-core/src/tiling.rs). Window and column placement is plan9port acme's, ported function for function from cols.c, rows.c and the geometry of wind.c: coladd (a new window steals the lower half of the last one, or lands at the pointer), colclose (the next window extends up, else the previous extends down), colgrow (button 1 a few lines from the neighbours, 2 as big as can be, 3 the whole column, leaving the others obscured until the column is "safe" again), colresize, colsort, coldragwin (click, shuffle, move to another column, flick right, resize against the window above), rowadd (40% of the last column), rowresize, rowclose, rowdragcol, and makenewwindow's choice of where New and plumbed files go (the biggest empty space, else the biggest window; activecol first). The layout shard therefore stores pixel rectangles, like acme's Dump: each column's and window's rectangle, the body rectangle, tag lines, lines shown, and acme's maxlines. Every operation is computed by the leader against its copy and appended as one Arrange entry, so replicas take geometry, not recompute it; the client reacts to an OS window resize with rowresize. What acme reads off its frames the tiling asks through an Info trait: tag line counts and body lines measured in the client's last frame, or one-line tags and full bodies for a headless leader. Mouse warps are acme's too: into a new window's body near its box, onto Del of the window that took a closed one's place (or back to where the mouse was before the closed window was made), to the layout box after a grow or drag, and to the selection when an already open file is plumbed. macOS gives no mouse event for a warp, so the client remembers where it put the pointer for keyboard routing until the mouse really moves.

Columns grown as windows are (apex's, acme has none). A click on a column's box does to the row what a click on a window's box does to its column: rowgrow, colgrow turned on its side, called by rowdragcol for a press and release under five pixels apart, as coldragwin calls colgrow. Button 1 widens the column by a step smaller than a window's: a fifth of its width, or a twelfth of the row if that is more, taking from the columns beside it, nearest first, right then left, each giving at most a third of what it has beyond a strip. (Half again, as a window grows, took most of a neighbour at a click; columns are few and wide, and are adjusted by little.) Button 2 makes it as wide as can be and every other column a strip: STRIP wide, the box's width and a border's, which is a squeezed window's tag turned on its side -- its box at the top and its windows' boxes down it, each still showing dirty, live or working, and nothing else. A strip has no room for text, so the tiling gives its windows one-line tags whatever the text would wrap to, and the client draws no text, body, terminal or page there: nothing is laid out in no width, a terminal is not shrunk to one column, and what a view would scroll to waits until the column is wide again. Button 3 gives the column the whole row and hides the others, the row's safe: Layout::full, carried in Arrange like the rest of the tiling, with the hidden columns' rectangles left stale as acme leaves obscured windows'. Nothing draws, finds (rowwhichcol) or places a window in a hidden column: a window meant for one lands in the full column. A click on the full column's box lays the row out again with the others back as strips -- acme's windows come back as tags after one took the column. Anything else that changes the row first lays a hidden row out so (rowadd, rowclose, a drag), except a resize of the OS window, which simply gives the full column the new row. rowadd's 40% of the last column comes from the widest column instead when the last is too narrow to give, which a strip always is.

Collapsing a column into its side. B4 on a column's box (shift-click on a laptop; a column has no tools menu for B4 to open) collapses the outermost column that is not a strip, on either side, into that side's strips. It is next to them already, so it becomes a strip where it stands and nothing moves; its width goes to the next column in with room. B4 on a column between two with room does nothing, nor on the last column with room, since the row needs one. Strips therefore gather at the two edges, which is also where B2 leaves them. B4 on a strip brings it back, and so does B1, the one way back: a strip remembers the width it had when it became one (Column::restore, a share of the row in parts per million, so a resized window gives it the same part of the row) -- collapsed by B4, squeezed by B2, or hidden by B3 -- and returns to it, taken from the columns with room nearest it, each keeping 80 pixels and a box for its text. Bringing back an outer strip brings back every strip between it and the columns with room too, so no strip is left stranded between two columns that have it. They return innermost first, each undoing the collapse that made it: a column that took a collapsed neighbour's width and then collapsed itself remembers the sum, and hands the neighbour's part back when the neighbour returns, so undoing a stack of collapses returns the row to how it was, as far as the columns beside it have the room to give. A click on the box of a window in a strip is a click on the column's box: the column comes back and nothing else happens, and the window grows from the next click, once it can be seen (coldragwin, instead of its colgrow). Being taken to a window in a strip, or in a column hidden behind one given the row, brings its column back too (Node::uncover, tiling::uncover): every warp onto a window -- a new one, a Goto landing, a notification taken -- passes through the client's take_warp, which uncovers the column first and lands the pointer on the frame that shows it. A new window is not taken to a strip, though: one meant for a column down to its strip (the last column, say, where acme puts what it opens) goes to the nearest column with room instead -- the rightmost of those for a strip on the right, the leftmost for one on the left (tiling::nearest_open, in Node::place) -- so opening something does not undo a collapse.

A session starts as acme does: the top row and two columns (acme's -c defaults to 2), files given at launch opening in the last column (init_session returns it, as acme loads into row.col[ncol-1]).

Resizing, as built: acme's colresize scales each window's last height by the column's new height over its old, and each window but the last is then trimmed to whole lines; scaled again from the trimmed height, every resize handed a window's remainder to the one below it, and a window dragged back and forth gave the bottom windows the column a few pixels a step. Each window keeps its share of the column's window space (Slot::share, parts per million, Slot::extra the pixels trimmed), read off the rectangles after any change the user makes (a drag, a grow, an add, a close: every winresize but a column resize's clears it) and left alone by a resize, which sizes the windows by their shares; so a resize undone returns the layout it started from.

The borders are acme's to the device pixel: acme's Border is scalesize(display, 2), 2 device pixels at 1x and (2*dpi+66)/133 above it (devdraw reports 110 dpi per unit of scale), 3 at 2x, and the line between a tag and its body is 1 device pixel unscaled. The tiling keeps its gaps at 2 logical pixels (integer layout, crisp text); the client paints the device pixels beyond acme's in the neighbour's colour (a tag reaching up, a column's contents reaching left), so the black that shows is acme's width.

Themes (Settings ▸ Appearance: Match System, Light, Dark; kept in the theme state file): acme's colours are the light theme; the dark one keeps its make (theme.rs): two tinted papers, warm for bodies and cool for tags, inverted to deep grounds; selections the tints lit; the mid tone borders as they are; ink warm white; the handle colours kept where they read on dark and lifted where they would not (the dirty blue, the fenced red), each pair checked under a deuteranopia simulation as the light ones were. System follows the window's appearance as macOS reports it. Every colour the client paints comes from the theme, the sixteen ANSI colours of terminals included: a cell whose colour the program named by index (the palette entry not set by the program) carries the index, and a program's inverse of the defaults carries "the ink" and "the paper", for the client to colour by its theme (Cell in entry.rs on the packing); a colour given as RGB, or a palette entry the program set, is drawn as given. Web pages and previews keep their own colours. What is not presentation alone travels to the daemon as ClientMsg::ClientConfig, sent when a link is made (an attach, a reattach) and again when the theme in effect changes, a choice in the View menu or, under System, the appearance macOS reports (which a window's first link is made before, so it is told again once the window is up), to parked links too: the terminal colours (TermColors: ink, paper, the sixteen) that programs asking with OSC 10, 11 and 4 are told, so one deciding its palette by the background learns the paper it is drawn on; a session with no UI answers acme's light ones, and with several the latest to say. Focus: a terminal has the keyboard while the pointer is over it and the app is in front (acme's model), and as that changes the client sends TermFocus, which the daemon passes to a program that asked (DECSET 1004, xterm's CSI I/CSI O); many ask their colours again on gaining focus, and a theme change is followed by focus lost and regained on the keyboard's terminal for that reason. (DECSET 2031's dark/light notification is a possible follow-on for the rest.)

Automatic contrast correction (View ▸ Correct Terminal Contrast, on by default; kept in the contrast state file): programs choose their colours for a dark terminal and name them outright -- a 256-colour index, a truecolor triple, which the theme cannot touch -- so on light paper ls comes out in pale yellow and lazygit in greys nobody can read, and the few that choose for light paper do the reverse on dark. As it paints, the client checks every cell's ink against the paper it sits on, the cell's own background or the theme's, and where the two do not read moves the ink -- only the ink, never a program's background -- in lightness toward the ink of the paper it is on (contrast.rs). Reads is WCAG AA, 4.5:1, in the eye of a normal viewer and of a deuteranope (Machado 2009's simulation) both: a red reads lighter to a deuteranope, and one that passes for the first fails for the second. Hue and chroma stay, so a yellow is a deeper yellow, the hue turned halfway toward the nearest of the theme's own sixteen when one is within 40°, so the corrected colours belong with the theme's; greys are not given a hue. The ink is not set on the edge of reading but mirrored about it: one that lay a little beyond the edge lands a little inside, one far beyond lands deep, half as far in as it was out, so the shades a program tells its things apart by stay apart -- to a deuteranope, who has lightness where others have hue, two colours stay two where setting both on the edge would make them one -- and a dark terminal's bright red is a light one's deep red, which is what bright means on paper. Ink that reads is not touched, the theme's own sixteen included: the light theme's bright yellow on its paper does not, and is corrected like anything else. The moves are in Oklab, where a step in lightness is the same size on any hue, judged as drawn in eight bits (the edge found in floats can fall a hair short once packed), and every answer is cached by the pair, so a cell costs a lookup.

Fidelity audit against plan9port acme (2026-09-05). Read side by side with acme.c, text.c, exec.c, look.c, wind.c, cols.c, rows.c and scrl.c. Matching now: the three buttons and their chords, including B1 while B2 is down passing the last selection as the command's argument; a B1 sweep's chords (B2 cuts, B3 pastes) being the sweep's wherever the pointer has gone -- another window, a page, off the window altogether (Acme::chord, before anything is located, and mouse_down_out) -- as textselect acts on its own text for as long as a button is held; double-click selection of bracketed and quoted spans and lines (textdoubleclick/textclickmatch); Del/Delete/Delcol/Get through winclean (scratch windows such as +Errors and directories go at once; a dirty window warns "name modified" once and goes the second time; a small unnamed window never whines); the tag's words Undo Redo Put Get coming and going as acme's winsettag1; Newcol making an empty window; the last column being deletable, New making a column when there is none; Look searching the window it runs in, wrapping, and moving the mouse to the match; Tab, Indent on|off (autoindent, on in every new window, as acme started with -a), ID; Put in an autoindent window trimming the blanks at the ends of lines and at the end of the text (plan9port 1617427, acme's trimspaces), since autoindent is the leading cause of them: the file is written without them, and the buffer loses them as an undo step of its own (Proposal::PutTrimmed, the runs deleted from the end back under one group, then Clean at the version that leaves), so the first Undo after Put brings them all back -- only spaces and tabs before a newline or the end, so a CRLF file keeps its blanks and Indent off keeps everything; Up and Down in a tag shrinking it to one line and expanding it; Up/Down scrolling a third of the window and PageUp/PageDown two thirds; Home and End; the erase keys; over web and preview bodies the page's own pointer: WebKit never sets a cursor inside this window (hover reaches the page, its cursor request does not reach the screen), so a script in every page reports the CSS cursor under the pointer over wry's IPC (auto read as WebKit reads it: a hand within a link, a beam in a field), the app maps it to a system cursor and sets it itself, and while the pointer is over a page gpui's cursor rect asks for a style behind which cursor.rs puts a cursor whose set does nothing, so gpui cannot undo it (APEX_CURSOR_DEBUG=1 logs every cursor set and by whom); double-click expansion with acme's isalnum (_ and any rune above Latin-1 are word characters, ASCII punctuation is not); scrolling as acme's is, by the rows of the frame and not the text's lines: the origin is any rune, in the middle of a line as well as at its start, and the view starts at the row the origin is on, the line wrapped from its own start whatever row of it is at the top (so it wraps the same wherever it is scrolled to). The wheel, the arrow and page keys, and B1 and B3 on the scrollbar step across rows, so a line that wraps to a screen of them scrolls through as any text does, and the last row can come to the top; B2 on the scrollbar goes as far into the text as the pointer is down the bar, by the rune (acme's textsetorigin, not exact: on to the start of the next line when one is within 256 runes, else in the middle of the line), and the thumb is acme's, the runes shown of all of them. (Snapping the origin to a line's start, as the client once did, left a window that is one long line no place to scroll to but its start and past its end, and a long last line no way to its bottom.) A wheel that clicks by lines has its fractions carried over; a text body under the trackpad scrolling as a native view does (Acme::smooth_scroll): by the pixel, carried on by the system's momentum, which gpui passes on as more deltas once the finger has lifted (its momentum phase is not given, so what follows a touch's end is taken for it), and past either end -- the start, or the text's end at the bottom of the view, as a native view's end is and not acme's last line at the top (which the scrollbar still reaches, and from which the trackpad only bounces) -- against AppKit's rubber band, which a finger holds and which springs back once none does. The spring is critically damped and runs on the time that passed, not on its ticks; momentum that reaches an end is handed to it as its speed, so the text goes out and back once, and what more momentum comes that way is spent until a finger is down again. (Momentum pushing the pull out while the spring pulled it in, each at its own rate -- scrolls at the display's 120 a second, the spring at 60 -- shook the text on some machines.) Only whole rows crossed reach the session, as the view's origin (the row's first rune); the pixels between them and the pull past an end are this client's (Smooth), dropped whenever the origin moves by anything else (the scrollbar, a key, a jump, another client), and the body is laid out from them, with the rows a screen above measured every frame (TextLayout::rows) so that scrolling up crosses them without a jump. What brings a view to a place (a jump, textshow) puts it at a whole row and drops the pixels; typing, which asks only that the selection be in view, keeps them while it is, or each key would draw the body at its row and the next frame back between rows. Where a view is brought to (a quarter down for dot, three quarters for a win's output, half for the selection) is measured in rows (top_for), and the row at the top may be any row of a line: a long line of output is many rows, and counting it as one left what was to be shown below the bottom. The rest of the line is kept in view when it fits, and a line taller than the view is brought to where the place was to go; and the pointers: plan9port's big arrow always, the box while a layout box is held. Also matching: the scrollbar scrolling continuously while a button is held, the pointer kept on the bar (textscroll: 200 ms, then every 80 ms, by the pointer's height in the bar); ^F/Insert filename completion (textcomplete, with the file system on the server: a unique match completes with / or a space, a common extension is inserted, otherwise the candidates are listed in +Errors); B1 dragging past the top or bottom scrolling by the distance (framescroll); the mouse pulled up as a tag closes under it and pushed down as one expands over it (winresize); Kill name ending every running command whose first word is name (the server tracks the commands it starts); the session showing each running command while it runs (a pill in its tag, Processes are the session's), "name: exit status" in +Errors when one ends badly (waitthread, runproc's naming: the first word without its directory, |sort for a pipe); Zerox refusing directories; newline ignored in column and top tags; acme's +Errors an errors window (kind Errors, scratch) at the directory of the window whose command produced the output, made in the last column (errorwin1), with no Undo or Put for it. Decided against acme, by design: Exit detaches this window and the session lives on (acme refuses while windows are dirty; nothing is lost here); sessions are kept on disk by the daemon as they change (§12), and Dump [file] writes one to a file of its own (~/apex.dump when none is named, as acme's $home/acme.dump), which Load [file] makes a new session of -- its label made unique, the UI going to it -- rather than replacing the session at hand, as acme's must; Send on a terminal types the snarf buffer plus a newline into the shell and on a text window appends it to the body; Local, Incl and Abort are not commands.

^H, ^U and ^W erase exactly as acme's textbswidth: ^W skips non-alphanumerics, then erases the alphanumeric run, never past the start of the line or the window's origin; with a selection, the selection is cut first and then the width is erased, as acme does.

As built (apex-client/src/shell.rs, mac/). mac/build-app.sh makes Apex.app: apex-ui as the executable, the apex command beside it, and an icon of a space bunny (mac/space-bunny.svg, and drawn at 1024 in mac/space-bunny-1024.png -- the sticker's own outline filling the height, on nothing). Since macOS 26 a bundle's icon is set in a rounded square, so the bundle's is an Icon Composer icon, mac/apex.icon -- the sticker on navy -- compiled by Xcode's actool into Assets.car and apex.icns (without Xcode, the sticker alone, scaled by sips). While the app runs it sets the sticker alone as its Dock icon: the outline, with no square round it. Launched with no arguments the app makes sure a daemon answers on the default socket — starting one through the bundled apex with the home directory as its working directory — and opens its window on the session it had last time (~/Library/Application Support/apex/last-sessions), else the first existing session, else a new local. The title bar is the app's own: tabs for the connected sessions and + (⌘T) opening the picker, which is every way into a session: going to a tab, opening a session that is there, making one by the name typed on any host, or adding a host. Choosing re-points the window. The menu bar carries Quit, Hide, Sessions, Close Window and the Edit menu, whose items act on the text under the pointer, as acme's keys do. Not yet: remote sessions in the selector, an About window.


12. Logs in memory; compaction; sessions on disk

Logs live in the server's memory; the server is a long-running daemon. Snapshots are taken periodically (and on detach) by the node holding the state, and compaction truncates a log below its snapshot, so logs stay bounded. The logs are never written to disk; the sessions are, as acme's Dump writes its windows: what each window is and what of it is nowhere else, so a session outlives its server -- a restart, a crash, a reboot (#40).

As built (apex-core/src/dump.rs, apex-server/src/persist.rs): a dump is not a snapshot. It is versioned JSON saying what the windows are -- a file at a path, a directory, a terminal in a directory, a page at an address -- with the text that is nowhere else (unsaved changes, the scratch windows', a terminal's last 2000 lines), each window's tag, selection, font and tabs, the columns' tags, the tiling as it was, the session's identity, label, directory and settings. A file or directory as it was read is read again. Loading makes each window again with the ordinary ops under new ids and lays the tiling out in one Arrange, so a dump written by one build reads in the next; a tiling that does not read is laid out anew. Unsaved text comes back over the file as it is now -- dirty, stale if the file moved on, one Undo from the file -- and a terminal comes back as Terminal.app restores one: its old output, a faint line saying when it was restored, and a new shell in its directory, never the command it ran. What belonged to the process goes with it: attachments and leases, running commands, notifications, the statuses programs said, undo.

The daemon (Daemon::run; not a test's, run_with) keeps its sessions in ~/.apex/sessions/, under its socket's path: each written when it changed (every five seconds at most; a terminal's output alone is no change), atomically, and all of them when it stops (apex stop, a SIGTERM or SIGINT). Starting, it restores each, oldest first -- the same identity, so a UI's tab finds it -- and runs its profile as for a new one; a dump that will not load is set aside as id.json.bad. Ending a session forgets it.

As built: the daemon compacts every shard's log after each round of shipping, below what every connection has been sent and both its replicas have applied, and a mirror compacts each shard as it applies entries (a led shard once the server has acked them too), so a log holds what is outstanding, not the session's history. A terminal publishes only what changed since it last did (the rows that differ, the top, the links, the cursor), nothing on a wakeup that changed nothing, and the file watcher forwards writes, creations, removals and renames, never opens or reads (on Linux every open of a watched file is an event, the server's own reads included, which fed a loop). A daemon and a win tool that had grown to gigabytes on a spewing terminal and a watched file were what showed the need.

Measured: the attach snapshot carries each buffer's undo and redo history, so a session that has absorbed 100k keystrokes ships a 770 KB snapshot for 115 KB of text. Undo should be bounded (acme keeps it all, but acme never ships it) or left out of the attach snapshot and paged on demand; either brings attach down to the cost of the text.


13. Security

Local access is the Unix socket's file permissions. Remote access is ssh; the server never listens on the network. Attachments are unforgeable server-issued ids; fencing prevents a stale attachment from writing. Tools run with the server's credentials, as acme's do.


14. Milestones

  1. apex-edit — the Edit language and libregexp port with the acceptance suite of §8a, including the sam -d differential harness. Done.
  2. apex-core — buffers, views, undo, shards, entries, apply, snapshots, hashing, built-in commands, lowering of Edit change logs. Property tests: two instances, random entries, equal hashes. Criterion benches for apply, view adjustment, snapshot/hash, and replay. No UI: a headless driver replays recorded logs for profiling. Done.
  3. Server + attach — registry and metalogs, sessions, attachments, leases with transfer-then-reclaim, fencing, the attach protocol over a Unix socket, detach/re-attach, terminal rows paged, +Recovered. Done except: transfer (reclaim only), resume by attachment id, row paging, +Recovered.
  4. Client — the gpui prototype re-layered as a pure renderer and input device over core state, first in-process, then over the socket. Zerox becomes two views on one buffer. Multiple sessions per client and the session selector. Done except the session selector.
  5. CLI + control protocol — apex subcommands, events, proposals, win/Watch ports, plumbing rules as commands. Done except Watch, plumbing rules, detach/lease/log, the init script.
  6. Files — watcher, stale/dirty flow, Get in the tag. Done except directory refresh and diff-based reload.
  7. Remote — apex attach host/session over ssh stdio; hash checks. Done except hash checks; exercised with the bridge run locally, not yet over a real ssh session.
  8. Tools — apex lsp, agent harness, tool leases.

15. Measurements

Release builds on an M-series laptop. Core (apex-core/benches): a keystroke applies in ~260 ns, an edit adjusting 100 views in 0.7 µs, a 1 MB buffer hashes in 0.9 ms and snapshots round-trip in 0.3 ms, 20k entries replay in 2.2 ms. Edit (apex-edit/benches): x/fox/ c/cat/ over 1M runes in 3.2 ms.

Socket (apex-bench, daemon on a thread of the same process, one round trip = client → kernel → daemon → kernel → client):

what p50 p99
ping round trip 12–20 µs 18–42 µs
one keystroke: local apply, flush, server ack 14 µs 20 µs
100 000 keystrokes in one flush 1.8 M entries/s
attach: connect, snapshot, decode; 120 KB text, 770 KB snapshot 4.2 ms
attach; 1.2 M runes, 1.9 MB snapshot 6.2 ms
attach; 11.5 M runes, 11.9 MB snapshot 32 ms
terminal key → new rows on the client 180 µs 260–540 µs

Through apex attach --stdio run locally (the ssh path minus the network: two more processes and two pipes per direction): ping 26 µs, keystroke → ack 21 µs, throughput unchanged, attach +4.5 ms flat (the snapshot crosses two more pipes), terminal key → rows 195 µs.

The transport is nowhere near the budget of a frame; the attach cost is the snapshot's undo history (§12), and terminal latency is the pty and the parser, not the socket.


16. Open questions and exploration

Exploration: tool-defined shards

Not for v1, but worth keeping in view. Today the shard kinds are fixed (buffer, window, layout, term, metalog, registry) and tools reach the system through proposals, execs and metalog entries. The generalisation is to let a tool register its own shard kind with its own entry schema: the shard is created through the metalog like any other, leased to the tool (pinned to it while it lives), replicated to clients that subscribe, snapshotted, hashed and paged by the same machinery. A plumber would then be a shard whose entries are rules rather than a set of metalog entry types; an LSP tool would keep diagnostics in a shard the client renders in the gutter; an agent harness would keep its transcript in one. The appeal is that "extension" would mean "another shard", with fencing, provenance and re-attach for free. The cost is a schema-registration story, clients that must render entries they do not understand, and a harder question of what a client-led shard kind would even mean. Do it only if a second or third concrete need for it appears beyond plumbing.

Exploration: agents over ACP

exp/acp is a spike, outside the workspace's supported surface: an Agent Client Protocol client (apex-acp) written against the public tool API only, so it is also a test of that API's reach. An ACP agent runs as its child; the session is a window DIR/-claude, named for the agent after a - as win names its own, with +run and +transcript beside it for what it puts out, in the acme manner of +Errors: a program's window is the -, its auxiliary output the +. All of them are live, so none is offered a Put. The agent's text streams in at an output point, what the user types after it is the next prompt (Send, which the window puts in its own tag; Enter is Enter, since a prompt is as many lines as it wants, and a Send during a turn queues behind it), the plan a block replaced in place, and a permission request a line offering Allow Always Deny Never to B2, which then says what was decided. Interrupt ends the turn the agent is in (session/cancel), as Esc does in the Claude CLI, and takes anything queued behind it with it: it is an end to the work and not to one turn of it, and the window is told how many prompts went so that it knows it is no longer busy. The handle says what the window is waiting for: it pulses (set_working) and is live while the agent works, is clean when the answer is whole and nothing of the user's is left in it, and is dirty when a prompt is typed and not yet sent -- dirty meaning here what it means of a file, your text and not acted on (set_clean after every settle is what leaves it free to mean that). It rests while the agent waits on an answer, so the window says whose turn it is, and Preview toggles a page beside it (new_page) holding the last exchange the agent finished, rendered through the session's markdown converter: what was asked, quoted as markdown quotes it, and then the answer to it. The answer is the agent's last message of the turn and not every message of it: the ones before are the commentary it made on the way, which the window keeps a line of each and which read as nothing at all run together on a page. It stands still until the next answer is whole, where the transcript has the half-said. What was asked is held against its turn (the agent takes prompts in order, so the prompts wait in a queue and each comes off with its answer), so a prompt queued during a turn is still shown with the reply it got.

What the agent is doing is one line at the end of the session's window, written over as the work moves on and gone as soon as there is anything else to say: the agent's own words for the call (ACP's title -- what the agent would say it is doing), with the status glyph in front. One line, and a short one: a title is often the command itself, heredoc and all, and a window meant to hold the summary of the work must not swell with the code in it while it is going on, so what runs past the first line or past its width is cut with a …. That window holds the conversation and the decisions in it and nothing else -- not a log of every read and grep -- so it does not grow by a line a tool call. The line lives at the end because the window's own output point is there; anything else written takes its place, so a position remembered across a write is taken after it is gone, not before.

The left margin says who is speaking. What is said in the session's window is marked, so that a glance down the column tells one from another without reading a word: – is apex itself (what the agent is, what it is ready for, what was asked of it that could not be done, a listing it was asked for -- marked once at the head of a block, as a message is) and • is what the agent answered. Shapes rather than dots -- a bar, a bullet -- since nothing in a window has a colour to be told by, and a size is a poor difference; of a width, since a wide one would stand out for no reason, so the bar is an en dash and not an em, which is also not the hyphen a Markdown list begins with, a reply being full of those. ? on a question and ⋯▶✓✗ on the work are the other two things the margin holds, and neither is a voice.

~ ends a turn, and so begins the next thing said: what stands under it is the user's, which is why a prompt wants no mark of its own -- it is what lies between the ~ ending the last turn and the bullets answering it. At the end of the window the marker is also where to type: it is set off on both sides and the cursor is left on the line below it, the output carrying the dot along (§ the tool API), so nothing has to be clicked to answer. It is put down when the window settles and taken away by anything written after it (with the action line, in out, and the blank lines around it go with it, so that taking it away leaves what was there and no more); a prompt sent under one leaves it where it is, and it stays as the record of where that exchange began. A prompt queued during a turn never waited for the window to settle, and a replayed one never had a window to settle in, so each is given a marker as it is written: a prompt is never without one. The transcript beside the window is marked the same way, though nothing is typed in it, since the record wants the boundaries the conversation had.

What the agent says begins with a •, a message to a bullet. The calls are taken away again as they finish and the messages are not, so what the window keeps is a line a step of the work, which is what the agent itself thought worth saying about it. Where one message ends and the next begins is the agent's to say (ACP's messageId on each chunk); an agent that does not say is taken to have ended one wherever anything else is written. The bullet waits for the words it stands in front of, since a message that opens with a blank line would else leave it on a line of its own, and it is ours rather than the agent's: the page Preview renders has what was said and not our mark on it.

The transcript is the whole of what the session said, machinery and all: a line a tool call whose glyph is ticked off in place, the files they work on plumbable path:line, their edits as diffs, the plans, the questions and what was answered. Transcript (or -transcript) opens a window on it, DIR/-claude+transcript, and closes it again, as Del there does. It is kept whether or not a window is showing it -- the text and the offsets it is written over at -- so a window opens on the whole of the conversation rather than on the rest of it, and one closed and opened again says the same. Nothing is shown at: it is written at the end with insert_following, as the session's own window is, so it follows its output by acme's rule (§8, win's) and carries the dot with it: scrolling back to read a diff holds it still, and the run window beside it does the same. Only a rewrite in place -- a status glyph, the plan block -- goes through replace, which moves nothing. The two are written from the one update: what the conversation says goes to both, and only the machinery differs. Decisions go to both, and a question asked under a tool call's line in the transcript has to name itself in the window, where no such line stands.

Mode reaches the agent's modes (Claude's manual, accept edits, plan, auto, bypass), Commands its slash commands, Login its authentication when it wants one. The agent reads files through apex when a window has them (unsaved edits included) and writes them back the same way, as an edit followed by a Put, so the change is visible and undoable and on disk for whatever the agent builds next; with no window open it writes to disk, where the watcher (§9) brings it into clean windows. Anthropic's claude-agent-acp is the default agent, run from an install or fetched with npx, on the Claude Code CLI's own credentials.

Taking a session up again. Two things outlive the program and disagree: the agent keeps the conversation, and the window keeps dead text. The agent's record is the one still true, so a resume rebuilds the window rather than adding to it. Resume lists what the agent has had in this directory (session/list, filtered by cwd, newest first) a line each: the id the agent knows it by, when it was last worked in, and what it is about. Nothing of a session is kept on our side -- the agent knows them all, and the id is the name we call one by. The time is shown at the resolution that tells it apart, the clock today, the weekday within the week and the date beyond it, in this machine's zone; the column is as wide as the widest of them, as every other listing here is sized. The listing is text like any other, so B3 on an id takes that session up (Rule::plumb, scoped to the window). A click stops at the hyphens -- they are not word characters, so what B3 hands us is one part of a uuid and not the whole -- and a part that tells the sessions apart is enough; a sweep gives the whole. A hex word naming no session of ours is refused rather than left unanswered, so B3 falls through to what it would have done: the plumber's hand-back (above) is what makes a rule this broad safe to offer. Resume ID says the same in words, and -resume starts on the newest without asking. session/load then says the whole of it again as ordinary session/update notifications, which is why the rest needs no special case: tool calls, plans and diffs rebuild themselves through the code that shows them live. Three things differ. What is replayed is gathered until the whole of it is here, so a load that fails leaves the session we had standing. The window is not scrolled to on every chunk of two hundred, but once, at the end. And user_message_chunk, which is dropped live because the user's words are in the window already -- they typed them there -- is on a replay the only source of their half, and is written as the prompt it was. The one line saying what the agent is doing earns its keep here: in brief the tool calls collapse into it as they go, and a resumed window reads as the conversation rather than as the machinery, while the transcript takes the whole reconstruction whether or not a window was showing one at the time. An agent that can continue a session but not say it again (session/resume without loadSession) hands back the session alone, and the window says so.

Terminals (the protocol's terminal/*, advertised as a client capability) are how an agent runs commands: it asks us to start one, to say what it has written, to wait for its end, to kill it, to let it go. A terminal here is a child of ours with its output captured, not a pty -- what the protocol asks for is a command run, its bytes kept and its exit status reported, and nothing in it is interactive. Every command's output goes to one window beside the session's, DIR/-claude+run, acme's +Errors for what the agent runs: one window rather than one a command, so a turn that builds and tests and greps does not bury the column. Each command's output is headed by the command itself whenever another wrote last, and followed by how it ended, and it arrives live, so a build is watched as it runs and a compiler's path:line is plumbable the moment it is printed; the window follows its output by acme's rule (§8, win's), so scrolling back to read an error holds it still. The handle pulses while anything is running. Stop in the session's window ends every command going; Del on the run window clears it, and what is still running goes on into a fresh one; deleting the session's window, or releasing a terminal, ends the commands it holds. A command is started in a process group of its own so that ending it reaches what it started -- killing the shell alone would leave the build running. What the agent reads is the command's own bytes, to the byte limit it asked for (truncated from the front, at a character boundary, as the protocol says); the heading and the exit line are the window's, not the transcript's. Left out so far: images, several agents in one window.

What the spike says, back to apex. Tools that write a window they also watch need their own edits filtered out, which the crate now does. An agent's transcript wants to be a shard (above), not a buffer the tool patches: the tool keeps offsets for the output point, each tool call's status glyph and the plan block, and shifts them through every edit by hand. The prompt/output split wants a first-class mark. And agents resend a tool call's whole content with each update, so a client that appends must remember what it has already shown; a shard of entries keyed by tool call would make that the model's problem, not the renderer's. And the terminal capability wants a terminal: the tool API has no way to make one (a term shard is the server's, §3.2), so the spike captures a child's pipes instead and gets no pty, no ^C, no interactive command -- the one place where the public surface fell short of what the experiment needed.

Exploration: a pane of agents

apex tool agent began as a second spike on the same API (exp/agent, apex tool agent) and now comes with apex. It says what every agent in the session is doing, fed by the hooks Claude Code and Codex offer rather than by a protocol of our own. apex tool agent install puts the hooks in; each one is apex tool agent hook AGENT, which appends a line to ~/.apex/agent/SESSION.jsonl and exits. It reads the logs and nothing else -- no socket, no daemon -- so nothing need be running when an agent starts, one started late sees what came before it, and two see the same; the logs' directory and each open transcript's are watched with notify as §9 watches files, a slow pass every few seconds catches what a watch let by, and an agent whose process is gone (found once, asked after with kill(pid, 0) on that pass) goes the way of one that said SessionEnd.

It has no window of its own by default: what it offers, it offers on the windows the agents are already in, and what it says, it says with a notification. An agent that wants the user -- its turn over and the next prompt theirs, a permission to answer, a turn that failed -- has the terminal it runs in notified, so the window's handle and the session's square (§4.1) say so and a click on the square goes to that agent, one agent a click; it is lowered as the agent goes back to work. The notifications are the tool's, so it dying leaves none waiting. One the user has attended to is not raised again until the agent has been back to work and come to want something afresh. An agent with no terminal in this session has no notification. A tool with no window of its own cannot tell it is over by its window going, so Tool::alive says whether the session is.

-a adds the overview window, DIR/-agent, a block an agent, the margin its state in the order they want attention -- ? asking, ✗ failed, ~ your turn, ▶ at work -- with what it was asked and what it is doing about it under, the tool call in the agent's own words as the action line of apex-acp has it; a block that changes is written in place. B3 in a block (a plumb rule on the window, refused outside any block so that B3 keeps its meaning there) opens the agent's transcript, AGENTDIR/-claude+ID, named for the agent's directory so its path:lines resolve from where the agent worked, and read from the agent's own record as it grows, in the transcript window's idiom. Preview is apex-acp's: the last exchange the agent finished as a page, the prompt quoted and the answer under it through the session's markdown converter, written afresh as each turn ends, since the Stop hook carries the agent's last word whole. Goto goes to the agent itself: the hook keeps the apexsession and winid apex put in the environment of the command that started it, and Tool::switch takes the pane's UI to that window, in that session, so the pane is a way straight to any agent from anywhere. What the pane says back to an agent goes the way apex already has: a permission is answered where it stands (Allow Deny Ask, written into the block), the answer is a Decision event in the agent's own log, and the hook that asked, having seen a pane's presence file, waits on the log and hands the decision to the agent; a prompt is apex term send into the agent's terminal; an agent is Newterm claude; its changes since the session began are its repository's own diff (git, sapling, mercurial), in a window at the repository's root with each hunk located as path:line; the directory's past sessions are listed as apex-acp's Resume lists them, and an id B3'd anywhere opens a transcript by a plumbing rule the tool offers. An agent in a terminal of the tool's own session (the recorded apexsession is this one's, which Tool::session says) has the verbs offered on its window, by rules naming it -- Transcript, Preview, Changes while it runs, Allow Deny Ask while it asks -- so the agent's own window answers it, as apex-acp's does; that, and the notifications, are the whole of it without -a. And CopyContext, a rule by window kind in every text window, copies the window's selection, or the current line when there is none (Tool::snarf, so the clipboard too), headed by path:line: and fenced, for the user to put into a prompt as they see fit; it is copied rather than sent to an agent, so how it joins the prompt stays the user's. Both are the session's agents, -all every agent on the machine, whichever terminal or editor it was started from. The same logs read as text: ls, wait (the agent's state as the exit status) and events, for scripts to chain on. What the spike says back: the hooks carry the call's id, so a call's status can be written over in place in a transcript the agent itself keeps; and the same offsets-by-hand that apex-acp keeps are kept here too, a second vote for the transcript being a shard.

Open questions

  • Granularity of layout leasing when a tool wants to open windows while the UI leads layout: proposals suffice, but a burst of apex new from a script is many round trips; batch in the CLI.
  • Whether window selections for terminals should be cell-based or offset-based over the paged rows.
  • Web windows (deferred): server-side screencast vs client-side Chrome with server-side URL state.
  • Multiple UI attachments to one session with independent layouts (multi-player) — explicitly out of scope; the per-shard design leaves the door open.
  • Naming: keep acme's command vocabulary verbatim (Newcol, Delcol, Zerox, Putall) so muscle memory and existing scripts carry over.

Windows are what they are

As built (protocol 38): a window's path, label, kind and scratch flag are its state, not words in its tag. acme names a window by the first word of its tag, and apex did too, which made the tag a little language -- name verbs | yours -- that everything parsed: a name with a space in it could not be one word, a terminal's title had its blanks turned into ␣, auxiliary windows were told by a + or - in their last part (+Errors, FILE+Preview, dir/-host), apex rewrote the words before the | as the window's state changed (update_tags), and a name typed there was taken up when the pointer left (commit_tag).

  • The path is a text window's buffer's name, and a terminal's or a page's own (Window.path, WindowOp::Path): the file, the directory (with its slash), the terminal's directory, the URL. Node::set_window_path sets it; SetPath proposes it.
  • The label is words beside the path (Window.label, WindowOp::Label): a terminal's title or host, a tool's name for its pane (agents, claude 0b1c1425). SetLabel proposes it.
  • The kind is stored (Buffer.kind): File, Dir, Term, Errors, Web, Preview; an errors window is one at its directory, a preview one at its file, found by path and kind (Node::window_of).
  • Scratch is stored (Buffer.scratch): never saved, never dirty.
  • The verbs apex offers (Del, Snarf, Undo, Redo, Put, Get, Back, Fwd, Send) follow from these and the buffer's state (Node::window_verbs), computed, not written anywhere.
  • The tag's text is the user's words alone (Look to begin).

The client draws a tag's head from this state before the text: the path (its folders dim, its name strong; Untitled for a new window), the label on a chip, the verbs as icons, a hairline. B1 or B2 on a verb runs it; B3 on a folder or the name plumbs the path to there; a double-click on the path makes it a field, return renaming the window; one click on a folder or the name brings down a picker of that folder's entries, listed by the host as ^F's are, return opening one (a file or a folder) in its own window and ⌥return in this one, → going into a folder and ← back up. Tools and the CLI say the same things explicitly: WindowInfo{path, label, kind, scratch}, Tool::rename, set_label, new_scratch(path, label); apex win list prints each, and apex win rename, label and tag set them.

Processes are the session's

As built (protocol 39): what the server runs for a session is a record in its metalog, not a word in its top row. acme's waitthread put a running command's name at the front of the top row and took it out when the command ended; apex did the same, editing the top row's text on the side, so what ran was known only as a word in a buffer -- with no identity, no status once it ended, nothing of where it came from or where its output went.

  • MetaOp::ProcStart records a process as it starts: its pid, name (the command's first word, or what it calls itself), command line, directory, where it was run from (a window, a column, the top row), its kind (a command, a script of the session's, a program that announced itself) and where its output goes (a directory's errors window, a buffer's selection). ProcRename follows a program naming itself; ProcExit records its status (acme's wait message, empty for a clean exit) and when. Meta::procs keeps those running and the last few that ended (PROCS_ENDED).
  • The server reports a shell command's start with its pid from the thread that runs it, before it can end, on the channel its end comes by; it appends the record as it pumps (Server::flush_procs).
  • A terminal's shell is a process too (kind Term), started when its window's shell is, ended when it exits or is hung up with its window. apex ps lists the record (with -a, the last few that ended and how); the pills and the sidebar leave terminals to their windows.
  • The top row is the user's text; the client draws the running processes before it as pills (Head::procs), each its name and a ×. The × ends it (Kill by its pid); B1 on it goes to its output (the errors window, made if its output has not come yet, or the window whose selection it replaces); B3 to the window it was run from. The sidebar lists them under the session's windows, the same three ways. The pointer on a pill brings a card under it: the whole command line, the pid, the directory, when it started (the clock's time, and how long ago) and where it was run from.

The session's place

As built (protocol 41): a session has a current directory, and knows the host it runs on: MetaOp::Cwd { host, dir } in its metalog, made with the session and changed by ClientMsg::Cd (apex cd DIR, the title bar's crumbs), which the daemon checks is a directory on the host -- resolved lexically, as a shell's cd, not through links, so it stays a prefix of the paths opened in it. The server's own directory follows it: commands run from the session's tag or a column's, and terminals made from them, run there.

The title bar shows the host, dim, and the directory as crumbs, left of the session's tag. A crumb clicked lists the folders in it (folders only), typed after the crumbs to narrow them; ./ first, the folder itself: return cds there, → goes into a folder, ← up out of one.

A window's tag draws a path inside the directory from there on, with no mark -- src/main.rs -- and any other path whole, from /, so the two cannot be taken for each other. The directory itself is drawn as ./, set as one mark, its dot a middle dot a little apart from the slash: the window's name, a click on it listing the directory, B3 plumbing its whole path. (A chevron where ./ would be, //, a slash on a chip, a bookmark and a bolt were tried and let go.) The title bar shows the directory itself, as crumbs, without the icon. Only drawn so (Head::build_in): the state has the whole path, and each part of it is still the whole path's, so a click on src/ lists where it really is and the path's picker goes up past the directory into whole paths. The tag is drawn from the state every frame, so it follows a cd at once.

Lenses

As built (protocol 62), but for what is marked otherwise. A lens is a window that stands in for another, its base, in the base's place: a file's preview, an agent's conversation over its terminal, the file $EDITOR edits over the terminal that ran it. It replaces the window stacks (Layout::covers, cover_window, swap_window, raise_window, the Swap builtin, ClientMsg::EditOver, OpenWindow{cover}). A stack could be reordered; a lens can only be made and taken away, and everything a lens does beyond that is its tool's.

  • Made and removed, nothing else. Proposal::Lens { base, body } makes a window on body (a buffer, or a page) as base's lens. Deleting the lens removes it, and the base shows again. There is no swap, raise or reorder.
  • A chain, grown and shrunk at its top. A lens on a window that already has one goes on the top lens; its base is the lens under it. $EDITOR from an agent's terminal whose conversation is showing goes over the conversation, and the conversation comes back when the file's window goes.
  • It goes with its base. Deleting a base deletes its lens, and so on up the chain: the terminal exiting takes its conversation with it.
  • It goes with its owner. A lens is its maker's attachment's, and goes when that detaches, as a status does: a tool that dies leaves no face over the window it was showing.
  • The place is the chain's. Stash, move, grow, minimize act on the place and take the chain with them. Keys and clicks are the top's. A jump to any window in the chain (B3, Goto, a notification) shows the place as it is, top lens and all. Not built: telling the lens's owner (Revealed { base, at }), so Preview could scroll its page to the line, or take itself away if it would rather the text were seen.
  • The status is the place's. The handle shows the most pressing status in the chain: an agent done under its conversation is done.
  • Not written down. A dump leaves lenses out: a page lens is its tool's to make again, and an editor lens is gone with its process.

The tool keeps what a lens was: it can only be removed, so what is in it -- a page's scroll, a draft -- is the tool's to keep and give back the next time. Preview puts the file at the page's top line as its lens goes (by the page's data-line, from PageScroll), and the page at the file's when it is made; the agent tool keeps an unsent draft and puts it back.

$EDITOR is a lens

apex editor FILE, run in a window ($winid), proposes a lens on that window whose body is FILE's buffer -- a window of its own on the file's text, as EditOver made -- and waits for the lens to go. Del removes it (a dirty buffer warns first, as Del does), the terminal shows again, and editor exits. Interrupted, it detaches, and its lens goes with it. There is no peeking at the terminal meanwhile: Swap is gone.

⌘↩ is a word

A key runs a word, as if B2'd in the window under the pointer, and the rules say whose it is. ⌘↩ runs View. apex gives View no meaning of its own; tools offer it:

  • Preview, on a file it converts: View makes the rendered page its lens; View on the lens removes it.
  • The agent tool, on an agent's terminal (sync_targets already offers it verbs there): View makes the conversation its lens -- the prompts, tool calls folded to a line, the replies rendered, kept as the agent goes -- with an input strip; View on it removes it.

At first the binding is the client's; later the keys a session binds can be settings (apex set key.cmd-enter View).

The input strip

A window can have an input strip: a second text buffer, its owner's, drawn under the body, a few lines tall and growing as it is typed into. It is apex text -- B2, snarf, Edit, undo all work in it -- and it is replicated as any buffer is, so a draft is in every UI and survives switching. Submitting is a word (Send), run in the strip's context, so a key can mean it there (⌘↩ in the strip is Send, not View) while ↩ stays a newline. The owner hears it, reads the strip and clears it. The agent lens uses one for prompts, and Stop in its tag interrupts the agent; a REPL, a search, a notebook's prompt could use one too.

The agent tool needs to type into a terminal for this, prompts and Stop: a Tool::term_send, not apex term send run as a process.

Outlines

A tool can give a window an outline: Proposal::Outline { window, items }, each item a level, a title and an anchor -- in text an offset apply moves with edits, as it moves views; in a page an element or a data-line; in a terminal a prompt mark. It is the tool's and goes with it. The client draws it as it draws a page's headings now (outline.rs: ticks on the bar, the list the pointer brings out), from the page or from a tool.

The lsp tool gives each file window it serves its symbols (textDocument/documentSymbol), kept up as the file changes. As built an outline is a text's (Buffer::outline), its anchors offsets; a page's outline is its headings still, and the agent tool gives its conversation its turns by making each a heading, not by an outline of its own. A text's stops show where its scrollbar does (a text that fits its window has none).

The outline lens

Built after the rest, as a tool and nothing else, to see that the API is enough for one: apex tool outline, behind Outline in every window's tools menu (shift-B1), the session's rule starting it.

  • One outline per window, read by anyone (apex_server::outline::of): a text's as its tool gave it, a terminal's commands, a buffer page's parsed from its HTML as the client's TOC_SCRIPT finds it (marked elements, else h1 to h4). A page's maker overrides its headings by marking elements, as the agent does its turns; there is no outline a tool gives a page. The client's scrollbar reads the same thing for texts and terminals (a page's has its pixel positions from the page itself).
  • Each entry where it is in its own terms (At): a place in the text, a terminal's history line, the page's nth entry. Tool::reveal(w, at) shows the window there on every client: a text's origin and dot, a terminal's scroll, a page's Scroll::Outline(i) (Window::scrolls counts page scrolls, so going to the same entry twice scrolls twice).
  • The lens is text (Tool::lens_text, a scratch buffer PATH+Outline): an entry a line, indented by depth, a command's when and how long after it, ✗ before a failure. B1 or B3 on a line goes there and the lens goes; its input strip filters (the title's letters in order), ↩ or ⌘↩ there going to the entry selected; Outline or ⌘↩ on the lens takes it away. Kept as the outline changes.
  • Not yet: which entry a page is showing (its scroll is the client's, so the lens starts on its first); outlines composed from several windows (a workspace's), which the same calls would make.

Order

As built, one commit each (the input strip and the agent's lens two):

  1. Lens and its removal, replacing the stacks: the layout's model, going with the base and the owner, the place's status; apex editor moved onto it; covers, Swap and EditOver taken out.
  2. ⌘↩ running View; Preview's lens, scroll carried both ways.
  3. The input strip and Send; Tool::term_send; the agent lens.
  4. Outlines from tools; the lsp tool's symbols.
  5. The outline lens: one outline per window, reveal, lens_text, apex tool outline.
You are visitor 01402775 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.