Summary
AGI EXT is a presentation and interaction layer over agents-cli. The CLI owns every fact (sessions, devices, accounts, executions, teams, attention, activity) and every mechanism (launch, placement, resume, fork, stop, scheduling, watchdog). The extension owns editor tabs, webviews, the mapping between them, and local presentation preferences. Two rules follow: every live fact on screen arrives through one agents feed watch --json stream that exactly one elected editor window runs, and every user action leaves the extension as exactly one CLI verb. Missing facts are added to the CLI's stream row, never reconstructed from transcripts or fetched on a loop. The PRD states what the user gets; this document explains how the pieces produce it and where the code still falls short.
Read by question: ownership · runtime components · session projection · terminal lifecycle · launch composition · needs-you · module graph and debt · build, test, release.
System boundary and ownership
The CLI owns facts and mechanisms. The extension owns presentation: which tab is visible, sidebar layout, transient selection, and the restoration metadata needed to reopen a tab. When the UI needs a fact the stream lacks, the fact is added to the CLI's SessionWatchRow (backfilled from the index, the way version landed), never reconstructed from transcripts or fetched on a poll (the one exception, an explicit-click timeline filter, is described under the sidebar row below)ing loop. That side channel is how the 2026-08-25 CPU incident happened (agi-cli#3019).
The invariants, each checkable against the file named:
| Invariant | Enforced where |
|---|---|
| One elected child process receives live CLI state for all windows, and only while a window demands it | src/monitor/host.ts MonitorHost, src/monitor/sessionDemand.ts SessionStreamDemand, src/monitor/host.demand.test.ts |
| A reset replaces a scope; increments apply only when newer; stale events are ignored | src/core/sessionPresentationStore.ts apply, sessionPresentationStore.test.ts |
| UI code never parses harness transcripts or reads raw agents configuration for facts | rule; remaining violators are listed under debt |
| Acting timers belong to the CLI daemon, never the extension host or a webview | src/vscode/pollTimers.replacement.test.ts asserts on source text |
| User actions invoke the owning CLI noun exactly once | src/core/agents.ts buildAgentLaunchCommand, src/core/agentsBin.ts runAgents |
| A missing CLI capability fails as an upgrade error, never a filesystem fallback | rule; src/core/agentsBin.ts resolveAgentsBin throws when the binary is absent |
Publisher and URI authority stay swarmify.swarm-ext |
package.json publisher, name; the CLI emits swarm-ext://swarmify.swarm-ext/… |
src/core never imports vscode |
src/testing/vscodeDouble.test.ts |
| The built-in browser is served to agents only over loopback, to a client holding this window's token, and only the tabs that client opens | src/vscode/editorBrowser.vscode.ts startBridge, serveConnection; contract in src/core/editorBrowser.ts, read by browser-cli editor-discovery.ts |
Runtime components
The extension host is a single Node process per editor window. It holds the elected stream leader (or a follower client), the broadcast server or client, the window-local presentation store, the terminal registry, the command adapters, and the webview bridge. React webviews render serializable view models and post typed intent back; native VS Code APIs and CLI execution never leave the host.
| Component | Role | Source |
|---|---|---|
| Stream leader | Spawns and owns the single agents feed watch --json child in its own process group; exponential restart backoff to 30 s; SIGTERM then SIGKILL on stop |
src/monitor/sessionCliStream.ts SessionCliStream, SessionCliReplay |
| Demand gate | Union of every window's demand (Active Session sidebar visible, Project Sessions tab visible, Resume picker open, unresolved agent tab); leases keyed by follower socket so a dropped window releases immediately; 5 s stop debounce | src/monitor/host.ts MonitorHost, src/monitor/sessionDemand.ts |
| Leader election | One window holds the lease: each claim creates the next numbered generation exclusively, so windows starting together elect one leader; a crashed holder (expired, dead pid) is taken over; the holder mirrors itself into the legacy lease file so older installed versions stay followers. Loss triggers election and replay, not one poller per follower. A failed start is retried with backoff to 30 s while the lease is held | src/monitor/leader.ts, src/monitor/lease.ts, src/monitor/gate.ts |
| Broadcast | Unix-socket pub/sub from the leader to follower windows; frames carry monitor facts and session-CLI facts; requests (register tuples, snapshot) flow back | src/monitor/broadcast.ts, src/monitor/protocol.ts, src/monitor/follower.ts |
| Presentation store | Window-local index of rows, attention, activity, per-scope sequence and reset state; selectors derive local/remote groupings and counts without becoming a source of truth | src/core/sessionPresentationStore.ts |
| Terminal registry | Maps a vscode.Terminal to extension-local id, harness, host, version, account, label, and the canonical session id once known; persists per workspace |
src/vscode/terminals.vscode.ts, src/core/sessions.persist.ts, src/core/terminals.ts |
| Launch engine | Turns a command variant and the active workspace into one agents run line |
src/core/launchTarget.ts, src/core/agents.ts buildAgentLaunchCommand, src/core/shellQuote.ts shellQuote |
| CLI location | One resolver and one exec path for the agents binary; nvm node first on PATH, then the binary's dir |
src/core/agentsBin.ts resolveAgentsBin, bootstrapPath, runAgents |
| Command adapters | Every palette command; the swarm-ext:// URI handler for /lead (opens the Lead tab), /focus, and /spawn (the agents-cli terminal engine's vscodium-agent backend resumes a session into an editor tab through it; a request opens only in a window whose folders contain its project (no project is refused), focuses this window's live tab for the session instead of duplicating it, and with a nonce writes ~/.swarmify/agents/spawn-acks/<nonce>.json, contract in src/core/spawn.ts); typing a row's delivery into the tab this window binds (typeTabDeliveries, src/core/tabDelivery.ts); status bar; Go to Terminal, whose description and detail come from the tab's store row (terminalPickFace), never a transcript read |
src/vscode/extension.ts, src/core/terminalPicker.ts, src/vscode/forkCommands.vscode.ts |
| Active Session sidebar | The one session preview; module-local subject; synchronous render from the store | src/vscode/agentPanel.vscode.ts |
| Session cards | The Timeline and Artifacts cards (webview script + stylesheet) the sidebar inlines; their host fields and click actions (openListedArtifact for a Project panel card). What both sidebars share is defined once here and inlined by each: the theme tokens, the outlined .card and the Waiting breath (RUSH_THEME_CSS), the escaper (escapeHtml, the scripts' esc), the GitHub and Linear marks (serviceMark), and the reply box with its mic (replyBoxHtml, REPLY_SCRIPT, REPLY_BOX_CSS in src/shared/replyBox.ts; a draft belongs to its session; the host side is deliverReply and dictationMessage), and the Made shelf (renderMadeShelf in MADE_SCRIPT, MADE_CSS, drawn from one madeShelf() in src/core/sessionCardFields.ts). A webview script reuses a host function by interpolating its compiled source (${relTime}), never by a copy. Harness logos are one .hx-<key> class per built-in agent (harnessLogoCss, src/vscode/theme.vscode.ts) |
src/shared/sessionCards.ts, src/shared/replyBox.ts, src/core/sessionCardFields.ts, src/vscode/sessionCardActions.ts, src/vscode/sessionReply.ts |
| Project sidebar | One view, four tabs (Sessions, Issues, Review, Settings) for one project, under the company and today goal lines; only the active tab loads. Sessions renders store rows filtered on the CLI's confirmedProject (plus, until agents-cli aliases ship, rows whose checkout is one of the project's repository paths: projectSessions(rows, name, projectRepoPaths(p))) and is a stream-demand source only while it is the visible tab. Cards carry data-key (session@host) and data-h (an FNV hash of their markup): patchChildren moves a keyed card instead of rewriting another, and skips one whose hash is unchanged, and never rewrites what is inside a data-keep node, only its attributes (the pinned card's reply box and Made shelf, which the page draws from its data-made). The front tab's session (frontTerminal) is pinned above the list as one opened-up card of one height for every session (a grip sets it, kept in the webview's state), with no arrows of its own, Claude's recap from the row, its Made shelf and a reply box at the bottom; asks lead their own group; a card's title is the row's title as agents-cli made it (cardTitle), while the tab and status bar keep streamTitle; thumbnails are <img data-thumb> filled from THUMB_SCRIPT's 480 px cache (src/shared/sessionCards.ts), shared with the session sidebar. Where a session lives (sessionPlace) comes from this window's tab registry, the row's observerTerminals (with workspaceDir) and its terminal app; what it made (sessionMade) from sessionCardFields; sort, show, group, folded groups and hidden sessions persist in workspace state. A card click selects (the other sidebar follows); focus and resume icons run resumeAndNotify; × closes this window's tabs for the session (terminals.sessionTabs + closeTabs) The other three read one CLI verb when shown or on Refresh, at most once a minute; no timer. A ticket row opens its Linear page as a tab and peeks at the description the Issues read carried (ticketPeek.ts, no read); a tile for a ticket that read does not hold reads linear tasks <ID> --json once for its page; every linear call sets LINEAR_PROFILE to the project's profile (default when none) and names the Linear project by id; ▶ and Start run agents.spawnWithPrompt with the delegated agent, else the default. Settings renders agentSettings and the default/second agent titles and writes one key per change (panelSettings.ts); it reads nothing from the CLI. Harness logos are one .hx-<agent> class per harness built from assets/ |
src/vscode/projectPanel.vscode.ts, src/core/projectPanel.ts, src/core/ticketPeek.ts, src/core/panelSettings.ts |
| Resume | Agents: Resume Session… lists the window's folders' projects' sessions from the store (scoped on confirmedProject, "loading machines" until every dialed peer reports or 8 s pass, then names the silent ones (src/core/streamWait.ts), a stream-demand source while open). Picker Enter, the side panel's Focus and ↻, and Project card clicks all run agents.resumeSession(sessionId): focus this window's tab, else agents run <harness> --resume <id> --terminal vscodium-agent, run from the session's folder (projectWindowResume), opens the live agent in the window owning that folder, and the tab's resume recovers it on its own device. A session from another machine whose folder is not here runs from this window's folder named like its project, else its first folder; a local session whose folder is gone says so. The answer is one notification; nothing is typed into a tab |
src/vscode/resumeSession.vscode.ts, src/core/sessionPicker.ts, src/core/spawn.ts |
| Session state words | One mapping from the CLI row (phase, live status, attention) to a state, its word and its dot color (STATE_TONE), used by the Project panel and the session sidebar; the needs-you order (ATTENTION_KIND_RANK, attentionRank); the time words (ageWords, relTime, waitFor). A PR's status word is prVerdict (src/core/prStatus.ts) on both sidebars |
src/shared/sessionState.ts, src/core/prStatus.ts |
| Settings store | globalState['agentSettings'] with its migrations, the prompt library, and retitling open tabs when a title preference changes |
src/vscode/agentSettings.vscode.ts |
| Lead client | Docked client of the project Lead agents-cli runs: each gesture is one agents lead ask|confirm --json child whose NDJSON is parsed into typed events (parseLeadLine, applyLeadEvent); refs become links (linkify); the last summary is kept per window. The Project panel's ✳ Lead tab draws the conversation from the pure renderLeadTab (src/core/leadView.ts: agents lead history plus live turns, held actions as rows with their own ✓ and ✓ Confirm all, which is confirmAll, one agents lead confirm after another) through the LeadPanelBridge that lead.vscode.ts exposes; history and agents lead status are read when the tab shows and when agents-cli writes the project's history (watchLeadHistory), never on a timer. Its reply box is data-keep, so a redraw never wipes what is typed; the mic and busy state ride on its attributes (syncLeadBox). An ask passes the editor's front tab and agent tabs (--context) and, with agents.lead.speak (off by default; Settings > Lead > Read answers aloud), --speak, so agents-cli speaks the answer on this machine. ~/.agents/lead/surface.json (watched on the folder and on ~/.agents, re-armed when the folder is recreated, plus an unref'd 2 s reread because FSEvents can drop or coalesce; the folder is never created to watch it, a malformed file keeps the last value) decides whether ⌥Space is ours (agents.lead.bubble context key; agents.lead.talk is in terminal.integrated.commandsToSkipShell). ⌥Space brings the Lead tab forward and toggles the mic; a held key is one press (PressGate); the mic is the shared dictation, scoped per recording by the pure nextMic transition, whose effects lead.vscode.ts performs. A turn silent 120 s or past 15 min is killed |
src/core/lead.ts, src/core/leadInput.ts, src/core/leadView.ts, src/vscode/lead.vscode.ts, src/vscode/projectPanel.vscode.ts |
| Reader | Optional custom editors for .md (TipTap) and .html (sandboxed viewer) |
src/vscode/customEditor.ts, src/vscode/htmlReader.ts, ui/editor/* |
| Autogit | Diff and status from the git extension; message from agents run claude --model haiku; stage, commit, push |
src/vscode/git.vscode.ts, src/core/commitgen.ts |
Session projection
Exactly one elected window starts the long-lived child, and only while some window reports demand: a visible sidebar or Project Sessions tab, an open Resume picker, or a tracked agent tab whose identity the stream has not resolved yet. When no window demands it the producer is torn down after a 5 s debounce, so an idle window contributes no watcher. The leader normalizes newline-delimited events, keeps a replay cache so a window that gains demand paints current rows without waiting, and broadcasts each event to followers over the monitor socket. A child that keeps dying is respawned with exponential backoff up to 30 s, and its process group is torn down before a restart so an ssh descendant can never outlive it.
feed watch is the only producer of three things: session rows, attention.* (the sole input to needs-you), and activity.append. A cheaper local journal tail carries none of the attention or activity events and drops every remote session unless something replaces the fleet fan-out; switching to it is not a drop-in and stays blocked on the CLI side.
The row that reaches the sidebar carries the summarizer's goal, checkpoints, summaryChecklist, and summaryState, and the daemon-computed request, timeline, and files. src/core/remoteSessions.ts normalizes all of them at the boundary (2,000 request characters, 8 timeline steps, 8 file rows) and returns undefined for anything the CLI did not send, so an older CLI degrades to the documented fallbacks (request → userPromptClean → topic; timeline → checkpoints; files → nothing) instead of a guess.
The glance fields ride the same row: title (best source first), model, failures (newest 20, failed and blocked), activityHistogram (48 fixed buckets plus user-turn times, for the seek bar), userTurns, subagents, artifact titles joined from .artifact.json sidecars, and image attachments the CLI materialized under ~/.agents/.cache/attachments/. Artifacts carry editedAtMs for newest-first sorting. The sidebar webview's other image root is the home directory, fixed when the view is created (changing roots reloads a webview); it renders a thumbnail only for an image artifact the row names under home for a session on this machine. A remote session's artifacts show as file-type tiles; clicking one copies that single file into ~/.agents/.cache/remote-artifacts/<device>/ with one agents ssh <device> --argv call and opens the local copy in the Reader, because a vscode-remote:// URI fails without a Remote-SSH connection. A request's pasted images resolve by file name in this machine's ~/.agents/.history/attachments/, where the CLI saves them, so they show for remote sessions too. The request carries the owner's Gravatar (sha256(email), d=404, as artifacts-cli uses) over their initial. Each field is absent on an older CLI, and the sidebar then shows counts without lists, or nothing. Three timeline filters (agent messages, tool calls, reasoning) are too large for every row: each is one sessions <id> --include <role> --json call on an explicit click (the standalone sessions CLI, resolved like agents; tools answers with the tool-search envelope), cached in the webview per session and filter (marked stale with a Refresh link once newer activity arrives), never on selection or on a timer, and offered only for a session on this machine because sessions reads the local index. The host answers only a request whose session id is still the panel's subject; a failed load is shown and retried on the next click, never cached.
Failure semantics: a missing CLI binary is a visible prerequisite failure; a malformed feed event is rejected and reported without corrupting the current scope; loss of the leader triggers election and replay; missing facts render as unknown or degraded, and zero is reserved for known zero; a follower that has never observed a reset for a scope renders that scope as degraded; resolved attention cannot reappear from an older snapshot; a historical Previous row cannot reclaim a terminal already rebound to another live session on the same owner host.
Terminal lifecycle
An editor terminal has an extension-local id (CL-<ts>-<n>) before the harness reveals its native session id. Launch metadata and stream facts converge on the terminal registry; once correlated, the canonical CLI session id drives status, labels, resume, fork, stop, and Project panel focus. Labels have two classes: a canonical session-derived title and an explicit user label; the user label wins because it is presentation intent.
Every agent tab is opened by openTrackedTab (src/vscode/extension.ts): New Agent and its variants, the startup auto-open, /spawn, Resume, Reopen Last Closed Session, the resume launches, Fork, the queued launches (dispatch, Continue, Fork (Pick Session), the Reader's Send to Agent) and restore. It fixes the tab's identity at createTerminal (icon, name, an env scrubbed unless the tab is a New Shell, and AGENT_TERMINAL_ID/AGENT_SESSION_ID/AGENT_VERSION), waits at most 10 s for the shell pid (processIdWithin), registers the tab with the registry and readiness, and stamps the harness, host, version, account and session id before the label poller starts. Sending the launch line is sendCommandWhenReady (after promptReady), and a prompt for the agent is submitToTui: typed without a newline, then \r after 300 ms, because Ink TUIs take \r as Enter and a multi-line bracketed paste swallows one sent in the same tick. A tab the extension did not open (found on activation, or opened by the editor later) is registered by terminals.adopt from its creation env, with the persisted entry for its terminal id winning for labels, host, version and session; on activation a tab with no shell is closed so restore reopens its session.
Correlation is not launch-only. A user may stop session A and start session B in the same terminal, so the stable observer terminal id can appear on both rows while the feed settles. On each pushed reset or agent-row change the extension reconciles tracked tabs before the status bar or sidebar refreshes: it ignores Previous rows, treats two distinct live claims as ambiguous within the same observer-device and execution-host scope, and keeps the existing binding during the overlap. When A is removed, B becomes the sole claim and the tab rebinds; a later historical A upsert marked Previous cannot revert it. A terminal-selected sidebar subject stores the terminal's stable id and follows it across the rebind; a subject selected from the Project panel stays tied to its session.
The shell's AGENT_TERMINAL_ID remains stable across agents.clear and harness
restarts. Every open tab with that id gets a live-terminals.json entry
(src/vscode/terminalRegistry.vscode.ts) carrying the terminalId, the harness kind
from the prefix in PRESENTED_AGENTS, and the shell pid. The launch sessionId is
present only when the extension minted one (Claude); Codex, Grok and the rest pick
their id after start, and the CLI joins those tabs by terminalId. The CLI, the file's only reader
(viewing-in.ts, active.ts), dedupes by terminalId. A window's slice is pruned once its at is older than 10 minutes
even when its pids are alive: live windows rewrite it every 4 minutes, and a reload
writes under a new window id. Shell start time never proves session ownership.
Reload restores a session id from the exact persisted terminal-id record before
using the shell's frozen AGENT_SESSION_ID; it does not scan processes, read
transcripts, or pick a recent same-prefix session. A reload revives a tab with its
name and its process only: creationOptions comes back with no env and no icon
(measured in VSCodium 1.135, 2026-10-19), and a tab's name carries no harness text.
So a revived tab with no AGENT_TERMINAL_ID finds its record by the shell pid the
record saved (agentPid, the same process before and after the reload), which gives
back its terminal id, harness, session and host (adopt, src/vscode/terminals.vscode.ts). Focus hydration identifies
unresolved tabs; corrections to established bindings run on pushed stream facts.
agents.setSessionId accepts { terminalId?: string }, defaults to the active
agent terminal, and prefills the current id. It uses the existing canonical-id
and hydration validators, calls the registry's setSessionId, and persists
immediately. A manual id holds until a different session appears for that terminal;
it survives reload. The tab persists the selected id and every superseded canonical
id. Stream reconciliation filters those superseded claims for that tab before
applying the same Previous, observer-device, execution-host, and ambiguity rules.
A different eligible live claim replaces the binding and clears the override.
Clear uses the same mechanism to exclude the pre-clear session. An exact persisted
record is authoritative even when its id is empty, so reload leaves a cleared tab
unbound until a different session appears. This uses only pushed stream facts;
it starts no watcher, poller, subprocess, or transcript read.
Restoration metadata (~/.swarmify/agents/windows/<hash>.yaml, one file per window named by its workspace file or folder and replaced atomically, so no window can rewrite another's tabs: terminal id, prefix, session id, host, label, auto-label, harness, recovery harness, version, pid) is enough to reopen a tab through the CLI's resume path. Restore reopens one tab per session and none for a session the window already shows (restorePlan, src/core/sessions.persist.ts); a tab leaves the file the moment it closes for any reason but window shutdown. The scan snapshots the file before registering anything, so a write during a slow scan cannot erase tabs still waiting to be reopened. An empty or corrupt window file restores nothing; it never falls back to the old shared file. A session another live window shows is not reopened (liveWindows: the pid answers and the file was written since boot). Restore creates each tab hidden and shows it once its process runs: an editor-located terminal opened while the window is still starting is resolved as a text file and shows "The editor could not be opened". An agent terminal whose pty never came back is closed and its session reopens as a live tab. Restored, resumed and reloaded tabs run the resume as the tab's own process (agentTabShell), never typed at a prompt. Limits: a corrupt or empty window file restores nothing (its tabs are lost once, never replaced by the old shared file's); saving an untitled workspace changes its key, so its tabs are not restored that once; two windows on the same folder or workspace (which the editor normally prevents) share one file. On the first launch after the upgrade, each first-folder key of the old shared file is handed to one window only. It is never proof that a process is alive and never a transcript cache. Reload and user close are distinct: reload preserves the session; a genuine user close (TerminalExitReason.User, src/vscode/terminalReadiness.ts) issues one agents ps stop.
Launch command composition
Every Agents: New <Harness> variant routes through one engine (src/core/launchTarget.ts → src/core/agents.ts buildAgentLaunchCommand). The setting agents.launch.defaultTarget (auto default, local, ask) decides the plain command; the five explicit variants pin one axis each and never both.
| Variant | Emits | Never emits |
|---|---|---|
New <Harness> (target auto) |
agents run <h> --interactive --device auto --cwd <workspace> --strategy balanced --mode auto |
a prompt |
(Pick Host) |
--device <name> --cwd <workspace> --strategy balanced --mode auto |
the account picker, --device auto |
(Pick Account) |
<h>@ --interactive --device auto --cwd <workspace> --mode auto |
--strategy, a pinned version |
(Auto) |
--device auto --cwd <workspace> --strategy balanced --mode auto, ignoring the configured target |
a prompt |
(Pick Project) |
--device auto --project <slug> --strategy balanced --mode auto |
--cwd, --remote-cwd, a host prompt |
| pinned version (no host) | <h>@<version> --interactive --local --cwd <workspace> --mode auto |
--device auto, --strategy |
(Local) / target local / Pick Host This Machine |
--local --cwd <workspace> --strategy balanced --mode auto |
--device |
Bare interactive runs auto-place in agents-cli 1.22.118, so local placement must be explicit. Hostless version pins also emit --local to preserve their local intent; an explicit host takes precedence.
Every other launch goes through the same builder. buildTabLaunchCommand (src/core/launchTarget.ts) serves New Agent, its splits, aliases, quick-launch slots, the startup auto-open and Clear: --local, or --device <name> when the tab runs on a device, never --device auto, so Clear relaunches a tab where it was; always --cwd <workspace>. Shell and a user-defined custom agent are not CLI harnesses and keep their own command. Resume (Pick Harness) runs agents run <harness> on the session's device or --local; Resume in Best Profile runs agents run auto on the session's device or --device auto (which a bare run auto also means); both carry --cwd and no --strategy. Fork and Fork (Pick Host) are agents fork <id> [--device <host>] (forkCommand, src/core/forkSession.ts). The Reader's Send to Agent is a queued launch (openSingleAgentWithQueue) with --local and the selection as its prompt. Fork (Pick Session) still launches the harness in the picked session's folder through openSingleAgentWithQueue and types /continue <id>: agents fork starts the sibling in that folder only from agents-cli 1.23.27, and it has no --cwd to pass, so moving it would land a fork of another project's session in this window's folder on older CLIs.
Flag order is fixed by buildAgentLaunchCommand: agent spec, --interactive, --device or --local, --cwd or --project, --session-id (Claude), --strategy, --model, --mode; src/core/launchTarget.test.ts asserts these strings without a workspace. --strategy balanced is set for every variant except the account picker (src/core/launchTarget.ts strategy: options.accountPicker ? undefined : 'balanced') and is dropped for a pinned version, where the CLI would ignore it. The exclusions are thrown as errors inside buildAgentLaunchCommand: cwd with remoteCwd, project with either cwd form, the account picker with a pinned version, the account picker with a strategy. --cwd is emitted once, independent of placement, because the terminal's inherited process.cwd() can differ from the active folder. --session-id is emitted for Claude, and for auto, which applies it only when it picks Claude. Ordinary launches never derive a target from agents projects view <cwd>: that command is a containment attribution lookup and a shared root can belong to several child projects (PHNX-3970). Native-mode launches are wrapped by wrapNativeAgentCommand so exit code 0 closes the tab and the CLI's ssh-loss codes (255, 254) read as a recoverable reconnect rather than a crash.
Needs-you attention as pure projection
The Project panel's pinned "Needs you" group is a projection of the CLI attention rows the stream carries (RemoteAttention in src/core/remoteSessions.ts, joined onto their session in sessionPresentationStore.sessions()). Membership is attention.state === 'open'. Order comes from attention.kind through attentionRank (ATTENTION_KIND_RANK) in src/shared/sessionState.ts: question, permission, plan_review, declared, failure, stall, review. The Active Session sidebar shows the same open item under its header in the harness's own words, with Reply and Focus. A stall is a CLI signal: sessionStateOf reads it as Stopped and SessionStateKey has no stalled member. A tab the stream has not indexed carries no attention and never enters the group from the client side.
Project attribution follows the same rule: the Project panel filters on the CLI's own confirmedProject (projectSessions in src/core/projectPanel.ts). One stopgap until agents-cli resolves a renamed project's old names: a row whose checkout (its cwd, a worktree folded to its repository) is one of the project's own repository paths is shown too, only when its confirmedProject is empty or not a registered project (projectFallback, the registry reread at most once a minute in src/vscode/projectRegistry.vscode.ts; a stale list answers at once while it rereads); the resume picker applies the same rule. That compares against paths the CLI gave for the project; it never guesses a project name from a cwd, and it goes away when the feed carries aliases.
⌘K (agents.searchSessions) reads nothing. ProjectView.openPalette brings the Project panel up on Sessions (its own view, or the window it popped out into) and posts renderPalette (src/core/projectPanel.ts): every session the presentation store holds, any project, live and ended, in paletteOrder (favorites, asks by the CLI's urgency then wait, running and waiting, idle newest first, ended last and capped at 150). Each row carries what the store already gave the cards: the PRs and pages it made (sessionMade), the images the request attached (requestImageThumbs, the attachments folder the webview may read) and its recap's first sentence. While the overlay is open its rows follow every Sessions redraw. The page filters in place with paletteMatch, interpolated into its script (exact id first, then title prefix, title words, other words, then data-said: paletteSaid joins the reply (1,000 characters), question, your last four userTurns, newest four steps, recap and first prompt the row already carries, newest first, 300 characters each otherwise and 2,000 in all so the cap drops the oldest, since the overlay is posted again on every redraw; saidSnippet shows the hit for a row found only there), and Enter is one paletteGo: a tab here comes forward as a card click does, anything else goes where its focus or resume icon would, and resumeSessionTab never resumes a session the store's runningUnshown says is running (pidAlive) with no observerTerminals entry for this machine. A row whose agent is running draws a green dot before its machine on cards and here. VS Code's QuickPick was dropped because it re-sorts by its own label match and can neither align a row's details nor show an image.
The rest of the Project panel composes the same way. Session rows describe conversations and progress; attention facts keep the exact question, choices, and resolution lifecycle; activity facts supply chronological evidence such as plans, pull requests, teams, and artifacts. The panel may group, filter, sort, and decorate them, and must never infer a new canonical status from transcript text or process scans. Its overview, pull request, and ticket tabs arrive through separate bounded CLI reads and do not live in the presentation store. Optimistic UI is limited to transient feedback; durable changes arrive back through the feed.
Findings
The leader's monitor broadcast socket binds through listenOwned
in src/monitor/endpoint.ts: listen on a private path, then link() it to the
shared path, which fails instead of replacing a live server. A leftover path is
removed only when nothing accepts on it. Close unlinks the shared path only
while it is still this server's inode, and destroys every accepted connection
so teardown never waits on a peer. Because the path is reachable before
MonitorHost.start() settles, the host re-evaluates demand reported in that
window once it runs.
Monitor frames are structurally validated before delivery. A complete valid frame has the same result whether received whole, coalesced, or fragmented. Incomplete-frame buffering remains unbounded: the CLI producer defines no maximum reset size, so a consumer-only cap would silently lose legitimate session facts. A shared producer/consumer size contract is required before adding that bound.
The Fleet dashboard (ui/settings), its Foreman voice orb, the watchdog MCP bridge
(src/mcp), and cloud dispatch were deleted on 2026-10-11 (PHNX-4329). Their jobs are
the Project panel, the AGI Menu, and the agents CLI (agents watchdog, agents cloud).
The module graph was measured on this branch on 2026-09-11 with the code:refactor module scanner (its modules.json lives in the session artifacts and is not committed): 140 of 156 TypeScript files under src/ parsed, 7 directory modules, 12 import edges, 2 cycles, 1 god module. Eleven of the twelve edges run between the five source modules and are all drawn below; the twelfth is monitor/testdata importing monitor three times, which is test fixtures and is listed in the footnote instead.
What the graph says. core is healthy in kind and wrong in one edge: it imports monitor once (a type-only path through src/monitor/protocol.ts for SessionCliFactPayload in the presentation store) and shared imports core twice while core imports shared five times, which closes the core ↔ monitor ↔ shared cycle. mcp ↔ vscode is the second cycle: src/mcp/watchdog-bridge.ts imports getAllTerminals from src/vscode/terminals.vscode.ts while vscode imports mcp twice. vscode is the god area by size, not by fan-in: three files hold 12,090 of its 21,897 lines (extension.ts 5,659; settings.vscode.ts 3,625 with a 100-plus-case message router; agentPanel.vscode.ts 2,806 with inline webview HTML), and dynamic import() is what keeps the cycles compiling.
Fleet removal (2026-10-11). The graph above is the historical 2026-09-11 measurement. src/mcp and ui/settings are deleted (PHNX-4329), so its mcp box and edges no longer exist.
Known debt. These violate the thin-client rule. Touching one means deleting it or shrinking it, never adding to it.
| Path | Violation | Fate |
|---|---|---|
src/core/prewarm.simple.ts |
still spawns opencode session list on every OpenCode tab open (the second, workspaceState crash-recovery mapping was deleted; the per-window file is the one restore store) |
delete once the CLI daemon owns restore |
src/monitor/sessionParse.ts |
resolves session-root directories for the readiness detector's file scan; obsolete parsing helpers were deleted in #74 | replace the remaining file scan with CLI-provided fields |
src/monitor/readinessDetector.ts |
extension-invented lifecycle classifier (ps and pgrep loops), the only copy of each readiness probe: the leader runs one for every window's shell pids, and a window runs its own in-process (src/vscode/terminalReadiness.ts) while the monitor is down and to re-await promptReady after a reset, emitting into the same ingestReadinessFact / ingestShellAdoptionFact |
move the signal into the CLI daemon, project it on the stream |
src/vscode/agentPanel.vscode.ts |
messageCount and recentFiles are not on the stream and are dropped from the instant paint (Go to Terminal's detail line, terminalPickFace in src/core/terminalPicker.ts, drops its count for the same reason) |
add them to SessionWatchRow; never a lazy enrich |
Wave 1 of PHNX-4044 (released as 0.9.371) removed 31 dead files and 49 dead exports, installed the knip gate, dropped node-pty and @vscode/webview-ui-toolkit, collapsed twelve shell quoters onto shellQuote and three binary resolvers onto agentsBin.ts, and derived the UI harness tables from the CLI catalog with a drift test.
Gemini's executable integration is deleted: no CLI probes, setup commands, prompt-pack paths, watchdog registration, prewarming, transcript parsing, terminal recognition, or UI choice. agents.cli.ts still mirrors the CLI's legacy id; stale launch choices are rejected. The context-alias writer rejects the retired GEMINI.md basename even when explicitly requested by an old configuration, without touching existing files or narrowing other aliases.
Direction (proposal, not observation). Wave 2 breaks the remaining cycle and splits the large files (the mcp ↔ vscode cycle and settings.vscode.ts went with the Fleet removal): move SessionCliFactPayload and the protocol types under core so core has zero outbound edges; extract launch, status bar, URI handling, first-run, and monitor bootstrap from extension.ts; move the sidebar's inline webview HTML and script to files under ui/; retire the four tests that assert on source text once the behavior they guard is structural. Wave 3 generates package.json contributes.commands and keybindings from harnessLaunchRegistrations with a drift test, so adding a harness stops being four hand-written JSON blocks. The target graph has one edge direction: vscode → monitor → core ← shared.
Evidence
The UI build runs bun run typecheck before either Vite bundle. Its TypeScript
configuration includes tests and source imported through @shared, so shared
helpers must satisfy noUncheckedIndexedAccess and verbatimModuleSyntax as
well as the extension's compiler configuration. Vite transpilation alone is not
the type-check gate. Run cd ui && bun run typecheck to check that boundary
without producing a bundle.
| Check | Command | Baseline on this branch (2026-09-11) |
|---|---|---|
| Unit and boundary tests | bun test --timeout 30000 from the root |
1,853 tests, 165 files, 6 failures, all in ui/ when run from the root (same as origin/main); cd ui && bun test for the UI suite on its own |
| Dead code | bun run lint:dead |
clean apart from knip's own configuration hints |
| Agent integration | EXT_AGENT_INTEGRATION=1 bun run test:agent-integration |
needs the agents binary on the box; hits it for real |
| Package | scripts/build.sh <version> |
VSIX in dist/ |
| Install locally | scripts/install.sh |
installs the VSIX into the local editor |
| Release | scripts/release.sh <x.y.z> --confirm |
dry run without --confirm |
Tests sit beside their source and exercise real command boundaries. The only sanctioned double is src/testing/vscodeDouble.ts; a hand-rolled partial double breaks other files in the same bun run, and src/testing/vscodeDouble.test.ts enforces this. Four tests assert on source text of specific files (autoLabelHydration, statusBarIdentity.spawnStorm, agentPanel.webview-syntax, pollTimers.replacement); read what invariant each protects before touching it. The proof that matters for a release is the installed extension: Agents: New Claude opens a tab with a live prompt, one agents feed watch child serves two windows, and a Project panel card click starts no process.