Skip to content

Latest commit

 

History

History
2688 lines (2443 loc) · 177 KB

DESIGN.md

File metadata and controls

2688 lines (2443 loc) · 177 KB

AgentTerm design

How AgentTerm is built and why. For what it should do, see SPEC.md.

Overview

 iPhone app ──┐                      ┌── PTY ── claude
              │  WebSocket           │
              ├──(Tailscale)──┐      ├── PTY ── codex
              │               ▼      │
 macOS app ───┴─(loopback)─ agenttermd ┴── PTY ── zsh

One process, agenttermd, owns every terminal session. The macOS app and the iPhone app are both clients of it and speak the same protocol. The macOS app has no private path to the terminals, so everything it can do is something the iPhone can do too, and the protocol is exercised every time the Mac app is used.

Modules

Module Platforms Role
AgentTermProtocol macOS, iOS Message types, binary frame, pairing URL. No dependencies.
AgentTermHost macOS PTYProcess, SizeArbiter, HostServer, agent detection, Tailscale lookup, git diff, daemon launcher.
agenttermd macOS Command line entry point around HostServer.
AgentTermClient macOS, iOS AgentTermConnection, a WebSocket client built on Network.framework.
AgentTermTerminal macOS, iOS TerminalController: a SwiftTerm view bound to one session, plus shared colors.
AgentTermMac macOS SwiftUI app.
iOS/AgentTerm iOS SwiftUI app. Not part of the package.

The package is plain SwiftPM. The iPhone app needs an app bundle, so it has an Xcode project, generated by XcodeGen from iOS/project.yml and not checked in. It depends on the package's AgentTermProtocol, AgentTermClient and AgentTermTerminal products.

The client uses Network.framework rather than URLSession because the host speaks plain ws://. App Transport Security would refuse that for URLSession on iOS, and an exception for arbitrary loads is broader than needed. The connection is made to a URL endpoint: with a host and port endpoint the WebSocket handshake is aborted.

Pseudo terminals

PTYProcess starts the child through agentterm_spawn_pty, a small C function (target CAgentTermPTY) that forks, calls setsid() and ioctl(TIOCSCTTY) on the slave side, sets the window size, and execs.

  • The pseudo terminal has to be the child's controlling terminal, or the child gets no terminal signals: no SIGWINCH on resize, so a full screen program never redraws for a new size. posix_spawn cannot do this, because it cannot run an ioctl in the child, and opening the slave from a spawn file action does not make it the controlling terminal. An earlier version did exactly that and seemed to work, because bash claims the terminal itself at start-up. zsh does not, so everything started through a zsh login shell, which is every agent, ran without one.
  • Between fork() and execve() the child only calls async-signal-safe functions, which is what makes fork() acceptable in a threaded process.
  • The child closes every descriptor but the terminal, so the daemon's sockets and other terminals are not passed on, and resets signal handling.
  • A failed exec is reported back through a close-on-exec pipe.
  • Output is read by a dispatch source on the host queue. Writes run on a separate queue because they block when the program is not reading, and output must keep flowing meanwhile.
  • When the child exits, pending output is drained before the exit is reported.

Programs are started through the user's login shell ($SHELL -l -i -c <command>), so they get the same PATH and environment as in a regular terminal. The environment sets TERM=xterm-256color, COLORTERM=truecolor and a UTF-8 locale when none is set.

Terminal size with several clients

A PTY has one size, but a Mac window and an iPhone screen differ. SizeArbiter implements "the client being used wins":

  • Every attached client reports the grid that fits its view, and reports again when that changes (resize).
  • The driver is the client that most recently took control (takeControl) or typed. The PTY takes the driver's size. resized tells every other client who the driver is (SizeDriver, #120): the name the client gave in its hello, or the Mac's name for the Mac's own app (a local client that called itself "Mac"), and what it is (DeviceKind: mac, iphone, ipad, #157), from its hello or pair; the apps show an iPhone's or an iPad's icon by it, and none for a Mac.
  • Attaching and resizing never make a client the driver, unless it is the only one attached. The Mac app attaches to every session to show it; if that took the size, a session opened on a phone would jump to the Mac's size a moment later and the phone would only see a corner of it.
  • A client's reported size is kept while another client drives, so typing there later switches to its current size at once.
  • When the driver detaches, a driver that used the session (took control or typed) leaves its size: nobody drives until a client uses the session again, and the size stays (SizeArbiter, SIZE-8). The program's questions to its terminal are answered meanwhile by the most recently active client (answerer). A driver that only watched, being the only one there, hands over to the most recently active remaining client. With no client left the size stays as it is.
  • The iPhone takes control of the session open on it whenever its replay ends, so coming back after it was away takes the phone's size at once. The Mac app takes control when a key is typed or the terminal is clicked.
  • After every change the host sends resized to each attached client with a driver flag. A client that is not the driver shows the driver's grid rather than its own, so the content lines up.

tmux's rule, the smallest attached client, was rejected: a phone left connected would keep the Mac window small.

Size reports are debounced by 120 ms, because layout changes arrive in bursts (a window being dragged, the iOS keyboard sliding in) and each report makes the program redraw.

TerminalController keeps two sizes: the natural size that fits its view and the foreign size imposed by another driver. A layout change while another device drives updates the natural size without taking control.

The iPhone attaches only to the session on screen, takes control of it when it opens, and detaches when leaving it, so the Mac gets its size back as soon as the phone stops looking. The Mac takes control only when the user types or asks for it.

While a session has a foreign size, every client's emulator takes that grid, so all of them draw exactly what the driver sees. The terminal view is then made exactly as large as the grid (SwiftTerm's getOptimalFrameSize()), and the container decides how to show it:

  • Mac, where the foreign grid is usually a phone's and small: centered, with a frame and a dimmed surround.
  • iPhone, where it is usually a Mac's and large: scaled down with a view transform until the whole grid fits, against the top.

Because the view no longer has the container's size, what SwiftTerm reports as its size is the foreign grid. The grid that would fit the container, which is what the client asks for when the user comes back to it, is worked out by TerminalController.containerResized from the cell size. Once the client drives again the view fills the container and SwiftTerm's own figure is used.

Keeping the Mac's own, larger grid and letting the narrower output flow into it was tried and dropped: it reads well for programs that draw relative to the cursor, but the picture on the Mac is then not the picture on the phone.

Writing a screen out off the sessions' queue

Each session's ScreenMirror is used only on a queue of its own (mirrorQueue): its output is fed there, it is resized there, and a client that attaches gets the screen written out there, 82 ms for 10,000 lines, while the queue every session's output and every request go through goes on (PERF-7). The client is sent attached at once; what the session writes until the screen is ready is kept for it (awaitingScreen) and sent after the screen, so it counts on from the end of it. A newer attach of the same client drops a screen still on its way.

Earlier lines a page at a time

attach takes history: how many lines above the screen to write out, the nearest ones (ScreenMirror.snapshot(linesAbove:)); nil for all. replaying says, in above, how many the host keeps. The iPhone attaches with 500 (TerminalController.historyAsked); when the view is scrolled to its top by a finger (watched on contentOffset, since the emulator does not say it scrolled while a finger moves it), and the host keeps more, it attaches again with 1,000 more. That replay is drawn over the same terminal, not a new one, and says so in a strip rather than over the screen; it does not take the session's size again. Once drawn, a swipe still coasting is stopped and the row that was at the top is put back by number, again after the emulator's next frames, which follow its output to the bottom, until it stays (HIST-6). A reconnect asks with have and the same history, and gets only what came since.

The size a session starts with

A session is created with the grid that fits the place its terminal will be shown in, worked out by TerminalMetrics from that place's size and the font before any terminal view exists. With a guessed size the shell draws its first prompt for the wrong width. zsh then leaves a stray "%" on screen: it prints that mark and pads the line to the width it believes in, and the padding wraps where the real width is smaller.

That place is the terminal's pane less the room kept around the text (TerminalInsets: 14 points at the sides, 10 above and 8 below on the Mac; 10 at the sides, 8 on its side, and 6 above and below on the iPhone). On the Mac the launch screen, where a first session is started from, has no strip of tabs yet, so the strip's height, as last shown, is taken off too (SIZE-7).

The same mark can still show after the width changes later (rotating the phone, changing the text size, another device taking over), because the padded line is already on screen and gets wrapped again.

Input that is not typing

Every attached emulator answers the program's queries (cursor position, device attributes, colors), and reports focus changes and pointer movement. These arrive the same way keystrokes do. TerminalReply recognizes them, and the host:

  • does not count them as activity, so they never make a client the driver. Before this, Claude Code's start-up queries were answered by the Mac's emulator, the host took that for typing on the Mac, and a session opened on a phone jumped to the Mac's size;
  • passes on only the driver's, so the program gets one answer, from the emulator whose grid matches the PTY.

Protocol

WebSocket over TCP, default port 7717.

Text frames carry JSON messages, encoded with Swift's synthesized Codable for enums ({"attach":{"session":1,"size":{"cols":48,"rows":30}}}).

Large messages go in pieces, both ways. A frame may be at most 4 MB, and one larger closes the connection. A message larger than 256 KB is sent as binary frames of that size (MessageParts: messagePart, then messageEnd, numbered by the sender), and joined before it is read: by a client since #21, by the host since #289 (protocol 41), for a text opened anyway and saved from the iPhone or another Mac, or a page's picture a Mac answers an agent with. The host joins at most 64 MB of one message (MessageParts.largestFromAClient); one larger is answered with error message too large, which both apps say as HostErrorWords.tooLarge, its other pieces are left, and the connection goes on. Only a client that signed in sends pieces.

A client that does not read is not kept for without bound (#270). The host counts the bytes handed to each connection and not yet sent. Past HostServer.mostUnsent (8 MB) a client is no longer sent its sessions' output, and the host notes how far into each it has all; once less than 1 MB is waiting, it is sent what it missed from the scrollback, from there, or the screen as on attaching when that is no longer kept. Nothing is said to the client: it gets all, once.

A program is made to wait for its session's screen (#327). Every piece of a session's output is fed to its screen emulator (ScreenMirror) on the session's own queue, and that emulator is slower than a program that prints without end. The host counts what waits for it; past HostServer.mirrorMostBehind (4 MB) it stops reading the PTY (PTYProcess.pauseReading), so the program waits on a full PTY as it does in a terminal that cannot keep up, and reads again once half of it was taken. Nothing is lost, and a session that ends meanwhile says all it wrote.

Client to host:

Message Meaning
hello(token, client, kind) Must come first. Wrong token closes the connection. kind is what the device is (#157, protocol 30); the host keeps it with the paired device.
list Ask for the session list.
agents(refresh) Ask which agent CLIs are installed.
create(command, cwd, title, size, typed) Start a session and attach to it. typed, when there is one, is typed into it once its shell has written something (its prompt), without Return: the Mac's guide to installing an agent puts its maker's command there for the user to read and run (#50).
attach(session, size, have) / detach(session) Start or stop receiving a session. have is how far into the session's output the client's terminal already is; nil for a terminal that starts empty.
resize(session, size) Report that this client's grid changed. Applied only if it drives the session.
takeControl(session, size) The user is using the session here: become the driver at this size.
kill(session) Hang up the session (SIGHUP, then SIGKILL after 3 s). An agent's session is ended with the shells it opened, and the app that shows the browser is asked to close the pages it opened (browserCall close, as a device's: nobody waits for the answer) (#145, protocol 29). An agent that ends by itself leaves them to the user.
addFolder(path) / removeFolder(path) Change the shared folder list.
diff(path) / diffFile(path, file, staged) A folder's uncommitted changes without the diffs, then one file's diff: its staged part, or what is only in the working tree.
gitStage(path, files) / gitUnstage(path, files) / gitCommit(path, message) Change what the next commit contains (no files means all), and commit it. Answered with diff, after an error carrying git's words if it failed; a commit then with gitCommitted(path, problem), nil when git took it (#285, #302). The apps keep the commit's message until that comes: a diff or an error meanwhile may answer something else.
gitDiscard(path, files) Throw away changes that are not staged (no files means all): git restore --worktree for what git tracks, the Trash for what it does not (GitActions.discard, FileBrowser.trash). Answered as gitStage is. The apps ask first, in the words of DiscardQuestion, and then name each file they asked about, Discard All too: not a change made since, nor a new file past the fifty listed (#50). A worktree of the repository inside the folder (.claude/worktrees) is never thrown away; a folder git tracks nothing of goes to the Trash whole only when all of it was named (GitActions.trashed).
gitBranches(path) The repository's branches, its own first and the checked out one before the rest, then its remotes' (GitActions.branches, one git for-each-ref). Answered with gitBranches(path, branches).
gitSwitch(path, branch) / gitCreateBranch(path, name, from, checkout) / gitRenameBranch(path, from, to) / gitDeleteBranch(path, name, force) Change the branches (#35). Answered with an error carrying what git said if it refused, then gitBranches and diff. A branch with commits of its own is deleted only with force: the apps ask twice before they send it (DeleteBranchQuestion).
gitResolve(path, file, take) / gitContinue(path) / gitAbort(path) While a merge, rebase, cherry-pick or revert is stopped on conflicts (#42). diff says so: DiffSnapshot.operation, from what git keeps in its own folder meanwhile, and the files that conflict first, each a FileDiff with conflict (git's two letters) and the file as it is against both sides. A side is taken with git checkout --ours/--theirs and git add, or git rm where that side has no such file; "edited" is git add, refused while a marker is in the file. Continue runs the operation's own --continue with no editor; a pull, a revert or a pick that stops is no longer aborted by the host.
Submodules (#44) No message of their own. DiffSnapshot.submodules holds, for each submodule git status says has modified or untracked files inside (S.M., S..U), its path and a DiffSnapshot of its own, read by the same code in the submodule's folder, so one inside another nests. The folder's own diff is run with --ignore-submodules=dirty: a submodule is among files only when its commit moved, marked isSubmodule. The apps act inside a submodule with the ordinary messages and the submodule's folder as path; the host then forgets what it kept of every folder around that path, and a client that is answered for a submodule's folder asks for the folder around it again. Discarding a submodule's row runs git submodule update --init for it. GitWorktrees.checkOutSubmodules checks out a new worktree's submodules, theirs too, one by one: each that is checked out in the repository's own checkout is cloned from there (git submodule init, then git -c protocol.file.allow=always -c submodule.<name>.url=<its git folder there> submodule update, then its origin set back to the URL in .gitmodules), and any other is fetched from its URL (git submodule update --init) (#244). It tells the host which one of the worktree's own it is at, of how many, which the host sends every device in worktreesInProgress.
gitApplyPart(path, file, patch, use) One hunk of a file's diff, or lines of one, staged, unstaged or discarded (#40). The app takes the diff apart and puts the part together as a patch (PatchParts): lines left out read as what the side the patch is applied to holds. The hunk a long diff was cut off in (PatchHunk.isCut) is shown and is no part: it may end in the middle of a line. The host applies it with git apply, --cached for the index and --reverse to take it out, after git add --intent-to-add for a file git does not track; from a folder inside its repository with --directory=<prefix>, since the patch names the file from the folder and git reads the names of a patch from the top (#50). Answered as gitStage is.
gitLastCommit(path) / gitAmend(path, message) / gitUndoCommit(path) The commit the checked out branch is at, with its whole message and whether a remote has it (gitLastCommit(path, last)); git commit --amend with what is staged; git reset --soft HEAD~1, or the branch unborn again for the first commit (#41). The apps amend through their commit box, and ask before undoing, twice for a commit that is pushed (RewriteCommitQuestion). Answered as gitPush is, an amend then with gitCommitted as a commit is.
gitStashes(path) / gitStash(path, message, untracked) / gitStashShow(path, hash) / gitStashApply(path, hash, pop) / gitStashDrop(path, hash) The stash (#38). A stash is named by the hash of the commit git keeps it as, not by its place (stash@{1}), which moves when another is dropped: the host looks its place up each time, and says when it is gone. Changes are answered with an error carrying what was said, then gitStashes and diff; gitStashShow with the files and their diffs. The apps ask before gitStashDrop (DropStashQuestion).
gitLog(path, branch, skip, limit) Commits of a branch, the checked out one when none is named, newest first and a page at a time (GitActions.log). Answered with gitLog(path, branch, skip, commits, more). The graph beside the list is worked out by the apps from each commit's parents (CommitGraphRow.rows).
gitShow(path, hash) A commit's message and what it changed, a merge against its first parent, each file with its diff unless together they pass GitActions.showLimit. Answered with gitShow(path, hash, details).
gitRevert(path, hash) / gitCherryPick(path, hash) A new commit on the checked out branch that takes the named one back, or makes its change there too. One that conflicts is left to be resolved and continued, or aborted (gitResolve, #42), and says so; a merge is refused, in words. Answered as gitPush is.
gitFetch(path, automatic) Ask the remotes for what is new (git fetch --all --prune). Answered with gitFetched(path, problem, automatic), then diff. The apps send it by themselves every DisplaySettings.fetchInterval while a folder's changes are shown and fetchAutomatically is on; what an automatic one says when it fails is shown beside the buttons, never in an alert. It holds no button either: what the user asks for in the folder while it is under way is kept by the client (RemoteWork, in AgentTermProtocol, which the Mac and the iPhone both go by) and sent when gitFetched comes, so that the two are never at the remotes together and nothing asked for is thrown away (#116).
gitForcePushPreview(path) What a forced push would overwrite: the host fetches, then lists HEAD..@{upstream}. Answered with gitForcePushPreview(path, upstream, loses, at), at being the commit the upstream is at; the apps ask in the words of ForcePushQuestion before they send gitPush(path, force: true, lease: at), which is git push --force-with-lease=<branch.merge>:<at> <branch.remote> HEAD:<branch.merge>. The lease is named, not left to the remote-tracking branch: the fetch every few minutes moves that one, and a bare --force-with-lease then overwrites a commit that came after the question (#50). A forced push without a lease is refused.
gitPush(path, force, lease) / gitPull(path, mode) Push the checked out branch, or bring in what its upstream has, the way the repository is set up to or by merge or rebase. Answered the same way, then with gitSynced(path): a diff alone may answer something asked while git was still at work.
writeCommitMessage(path) / cancelCommitMessage(path) Have an agent write the message for what is staged, or stop it. Answered with commitMessage(path, message), whose message is nil when it was stopped or failed.
setCommitWriter(settings) Which agent writes commit messages, on which model, with which prompt.
setKeepAwake(on) / setKeepAwakeOptions(options) Keep the Mac awake while sessions run, and how: the display too, only on power, for how long.
setStartAtLogin(on) Have the host start when the user logs in to the Mac, or not. The host writes or removes its launch agent (LoginItem) and tells every client with startAtLogin(on). A host that cannot be started that way, one with a state folder of its own, never sends startAtLogin, and the clients show no switch.
setDisplaySettings(settings) How things are shown on every device: the temperature's unit, diffs in one panel or two, changes as a list or a tree. The host keeps it in settings.json and passes it on as displaySettings. A host that keeps none yet sends nil, and the client hands it its own. Each app also writes the values to its own preferences, which is what its views read.
sshHosts / connectSSH(host, size) The hosts of the Mac's SSH configuration, and ssh <host> in a new session.
history(path) Conversations agents had in a folder, or everywhere when path is nil.
historyOlder(path, before) / readConversation(agent, sessionID, cwd) / searchHistory(search, path, query, titlesOnly) / deleteConversation(…) / deleteConversations(ids) / exportConversation(…) What History does with the conversations (#46), answered with historyOlder(path, conversations, more), conversationRead(id, details), historyFound(search, hits) and historySearchEnded(search), conversationDeleted(id) to every device, conversationExported(id, path). With titlesOnly a search reads no file (#50). deleteConversations deletes those named, or every one on the host when ids is nil, leaving those a session is having, Antigravity's being refused by AgentHistory.delete; each deleted is told to every device with conversationDeleted, and the sender gets conversationsDeleted(deleted, kept) (#50). The host does all of it, for the Mac it runs on too, so that every device shows the same. A conversation is named by its agent, its id and its folder and looked up among the agents' own files (AgentHistory.conversation), never taken as a path from a client. AgentHistory.details reads a file line by line into ConversationDetails: entries (user, agent, tool), first and last time, model, tokens, branch, files written; how each agent writes these was read from the files of the versions in use on 2026-11-14 (Claude Code 2.1, Codex CLI 0.169, Copilot CLI 1.0.112, Antigravity CLI). AgentHistory.search looks first at the file's bytes and reads a file as a conversation only when they hold the words. A client has one search of the history going for each of the two lists the Mac shows side by side, everywhere's and a folder's, and its searches for text apart: each kind is numbered by the client by itself (#50). A transcript is written to transcripts/ in the host's own folder. Filtering and grouping are HistoryFilter in AgentTermProtocol, which both apps apply to what was listed.
resume(agent, sessionID, cwd, size) Reopen a conversation in its agent, in a new session.
handoffPlan(agent) What the receiving agent would be told, to show it before handing off.
handoff(agent, sessionID, cwd, target, plan, prompt, note, size, folder, worktree) Hand a conversation to another agent, in a new session; in folder, or with worktree in a new worktree of it, made first (#150, protocol 31).
files(path) / readFile(path) / writeFile(path, text) A folder's files, what a file holds, and saving it.
findFiles(search, path, query) / findText(search, path, query, caseSensitive) / stopSearch(search) Searching a folder's files (#45), answered with filesFound(search, files, among), and with any number of textFound(search, matches) and one searchEnded(search, truncated, problem). search is a number the client picks, so an answer to what was typed before is told from the answer to what is typed now. FileSearch (host) does it: the files are git ls-files --stage and --others --exclude-standard, each submodule's own the same way, or a walk of a folder that is no repository; names are ranked in Swift; text is git grep --untracked -I -n --column -F -z in the repository and in each submodule, read as it is printed (Subprocess.stream) and ended once 2,000 lines were had or the search was stopped, which is looked at every tenth of a second while git prints nothing, and a walk that reads each file elsewhere. The host keeps a folder's list of files for 30 seconds and reads it again when a search is opened (an empty query). ripgrep is not used: it is not installed on the Mac this was built on, so it could not be tried (decided by the owner on 2026-11-14). On this Mac the Mac app calls FileSearch itself.
createFile(directory, name, isDirectory) / renameFile(path, name) / trashFile(path) Change the files. Answered with the folder's listing.
listDirectory(path) The folders inside a folder, or inside home.
dismissFailure(id) The user has seen the report of a part that stopped: it is dropped for every client.

Host to client: welcome, sessions, agents, folders, attached, resized, exited, error, diff, diffFile, history, directory, commitMessage, sshHosts, failures, and for pairing paired, pairingCode, devices. The session list, the folder list and the host's settings (tabLayout, keepAwake, keepAwakeOptions, commitWriter) are pushed to every client when they change.

welcome also says which release the host is from (release, "0.10.0") and what it is built from (revision), from protocol 23 (#121). The revision is a hash of the host's sources and of the packages it takes (agenttermd, AgentTermHost, AgentTermClient, AgentTermProtocol, CAgentTermPTY, Package.swift, Package.resolved), which scripts/bundle-mac.sh writes into the app's Info.plist (AgentTermHostRevision); the host, which runs from inside the bundle, reads the same. A host keeps running across an update of the app, sessions and all: when the one that answers speaks this app's protocol but was built from other sources, the Mac says from which release it is and offers Restart Host…, which asks first. It never restarts it by itself (decided by the owner on 2026-11-17), and a release that changes nothing of the host says nothing. A build outside an app bundle has no revision, and is not compared.

A host of an earlier protocol is sent nothing it does not have (#214). Right after an update the app talks to the host it found running, of the release before, until the user restarts it; a message that host cannot read it answers with error("malformed message"). Each message added to the protocol is named in ClientMessage.since with the number it came in (from 33: readNotices, 36: deviceInBackground), and AgentTermConnection, which keeps the number the host's welcome gave, leaves unsent what the host does not have, for both apps. Found with a host built from v0.12.0 (protocol 32) and the app of 0.13.0: what it refused was readNotices, which the Mac app sends in answer to noticeLog for what was read in its Inbox. While the host is an earlier one the Mac app says so in its banner only, with Restart Host…, and a "malformed message" from it is not said a second time as a notice; a notice about an older host is taken away once a host of the app's own release answers. A message whose content changed is not covered: nothing is owed to an earlier build (principle 6). A host that cannot read a message writes to its log who sent it and the message's name, never its content. --protocol-version, which tests give a host to have it stand for an earlier one, also has it refuse what came after that number.

The protocol version is 45. 45 took out what 44 added for a question before an agent used a browser profile, which the owner chose not to keep (#251); 43 added gitCommitted from the host, the end of a commit or an amend (#285, #302); 42 the reason a host stopped itself (#274); 41 messages from a client in parts (#289). 40 added worktreesInProgress from the host: the worktrees being made for sessions, handoffs and schedules' runs, each with its folder, its agent, its branch once made and what is being done (making it, checking out its submodules one of how many, starting its session), sent to every device when one starts, moves on or ends, and on connecting (#244). 39 took away the agents' memory again (#220, the owner's decision of 2026-11-22): the messages 38 had added, memories, readMemory, writeMemory and deleteMemory from a client, which ClientMessage.since named with 38 so that a host of an earlier release was not sent them (#214), and memories, memoryRead, memorySaved, memoryDeleted and memoryRefused from the host, are gone, and a host reads none of them. 37 took away markConversation and historyMarks: a conversation in History is no longer pinned or hidden, on either app, and the host no longer reads, keeps or sends which ones were; the history.json an earlier build left in the host's folder is not read, and deleteConversations keeps none for being pinned (#219). 36 added deviceInBackground, which a device's app sends for going to the background and coming back, in place of the appInFront 35 had it send (#190), so that appInFront is only the Mac app's; and CreateRequest.requestID, a number the client picks for a launch, which the host gives back to that client alone in attached's request, or in error's request when it refuses the launch (#189). 35 had the iPhone send appInFront too, for whether its app is in the background (#190). 34 added the browser's pointer, contextAt and copy, and the result context (#147). 33 added readNotices, noticesRead and noticeAlert, and Notice.read (#180). 32 added pushRegister, pushUnregister, pushState, handleNotice, liveActivity, noticeLog, notice and noticeHandled (#66, #168). 15 in 0.7.0. It went up with each message that changed while the release was made (principle 6): 8 added agentShellsFaults and gave agentShellResult's list of shells the asking agent's own (see "Shells an agent opens"); 13 the lease of a forced push, the commit a force-push preview was looked at, and when a schedule's run started; 14 create's typed; 15 searchHistory's titlesOnly, deleteConversations and conversationsDeleted. It was 7 from 0.6.0, which added failures and dismissFailure (see "A part that stopped"), and 6 from 0.4.0, which added the messages for push and pull, commit messages, keep awake options and SSH hosts.

The folder list is host state, saved in folders.json, so the Mac and the iPhone show the same projects and the phone can start an agent in any of them.

Binary frames carry terminal bytes: one byte kind (0 output, 1 input), the session id as 4 bytes big endian, then the raw bytes. Input from a client that is not attached to the session is dropped.

Attaching to a running session

The host keeps each session's screen: a terminal emulator of its own that nobody looks at (ScreenMirror, SwiftTerm without a view) is fed all the session writes and follows its size. A client that attaches is sent that screen written out again as terminal output: the lines above the screen (10,000 of them at most), the screen, the other screen when a full screen program is on it, then the margins, the cursor and the modes the program set (how keys, the mouse and pastes are reported, whether the cursor shows). To the client it is output like any other, so nothing in the protocol changed for it. It goes out in pieces of 256 KB, since one message may not be larger than 4 MB.

Until 0.5.0 the client was sent the last 4 MB of the session's raw output instead. A full screen program then only looked right once it drew again, and what had been drawn for another width, before a phone took the session over, read badly further up. The screen written out again is right for the size the session has now, and is usually much smaller.

Three things about it are deliberate:

  • It holds no question to the terminal (which terminal are you, where is the cursor), so a client has nothing to answer a second time. Clients still treat it as a replay and send none of the emulator's answers on until replayed. What the user types meanwhile is sent: the terminal view (AnsweringTerminalView) hands the emulator's answers over apart from the user's keys, and only those are held back (#293).
  • The emulator's own colors are left out. A client has its own.
  • A program's output arrives in pieces cut anywhere, also inside an escape sequence or a character. A client given the screen at such a moment would get the end of something whose beginning it never saw. So the host also follows the output byte by byte (OutputTracker) and ends what it sends with the beginning of whatever is unfinished. The same tracker remembers the few settings SwiftTerm keeps to itself: how the mouse is reported, whether lines wrap, the cursor's shape and the colors text was being written in.

Not carried over: images, links, tab stops, character sets, origin mode and the palette a program changed.

A phone that lost its connection attaches again within seconds, with its terminal still holding all it was sent. Sending the screen again costs time and cellular data at each change of network, and would throw away what the terminal had scrolled back to. So the host also keeps the last 1 MB of each session's raw output and says where in the session's output what it sends ends up (replaying(session, from), the place of the first byte, counted so that the end of a screen is where the session is now). The terminal counts on from there (TerminalController.position), and attaching again names that place (have): the host then sends only the raw output that came since. When it no longer keeps that far back, or the place is not one of this session's, it sends the screen and says so with another from, and the client starts a new terminal for it. The Mac app does not use this: it loses its connection only when the host itself stops, and its sessions with it.

The replay was drawn for the session's grid, so the emulator takes that grid before the first replayed byte (TerminalController.beginReplay(size:)), and keeps it until its view has been laid out and the grid that fits is known. Before 0.4.0 the emulator replayed at the size it happened to be created with and then went to 80 × 24: lines wrapped in the wrong places, and a program that redraws in place, an agent above all, showed a broken screen. Nothing made it draw again, because the Mac attaches at the session's own size, so the size never changed. It showed whenever the app was opened with an agent already running, which is what the first launch after an update is.

Agent detection

AgentDetector runs one script through the login shell that resolves each known CLI with whence -p (zsh), type -P (bash) or command -v. The result is cached by the host and sent on request; agents(refresh: true) runs it again. Clients only offer agents with a path.

Changes pane

The right side of the Mac window has two tabs, Git and History.

The diff of a file scrolls sideways as far as its longest line, with scroll bars that stay visible: macOS hides them until you scroll, which would give no hint that a line continues.

The two-panel view is laid out by SplitDiff.rows (in AgentTermProtocol) from the same unified patch: lines both sides share are one row, a run of removed lines followed by added ones is paired line by line, and what one side has more of faces an empty row. Line numbers come from the hunk headers. SplitDiffView (in AgentTermTerminal) draws it for both apps, as one TextKit 1 text for each side (#82), worked out off the main thread (SplitDiffTexts) and laid out a piece at a time between which the window answers, the whole diff, where rows of SwiftUI views stopped at 2,500. Each row is one line on both sides, the empty side's an empty line, every line of one height (its paragraph's least and greatest line height) and never wrapped (byClipping), so that both texts are as high and the same height shows the same row on both. A line's number and its tint are attributes, drawn by the layout manager (SplitDiffLayout) before the line and across the panel, not put in the text: what is selected and copied is the file's. On the Mac each text is in a scroll view of its own and one follows the other down (boundsDidChangeNotification); both have their sideways scroll bar always, so that both see as much of their height and the rows still face at the bottom. On the iPhone each text scrolls itself down, and a scroll view around it scrolls it sideways; one follows the other down (scrollViewDidScroll).

GitDiff shells out to git: diff --cached for what is staged, diff for what is not, and ls-files --others plus diff --no-index for untracked files, then splits the output per file. Renames are not detected (--no-renames), so every entry is one path that can be staged on its own. GitActions runs git add, git restore --staged (git rm --cached before the first commit) and git commit, with --literal-pathspecs so a file name is never read as a pattern.

The snapshot also says which branch the checked out one follows and how far the two are apart (git for-each-ref with %(upstream:short) and %(upstream:track), one cheap call that asks nothing of the remote), and, for a branch that follows none, the remote a first push would go to: origin, else the first remote. GitActions.push runs git push, or git push --set-upstream <remote> <branch> for that first push; GitActions.pull runs git pull --no-edit, so it merges or rebases as the repository is set up to. Commit, push and pull all run with GitActions.actionEnvironment: GIT_TERMINAL_PROMPT=0, no askpass program, SSH_ASKPASS_REQUIRE=never and GIT_EDITOR=true, so that neither git nor a hook can sit waiting for a password: credential helpers and the SSH agent still answer, and anything that would wait for typing fails with git's own message, since there is no terminal to type in. A pull that leaves a merge or a rebase under way is aborted, unless one was already under way before it, which is the user's and is left alone.

Commit, push and pull run with the PATH of the user's login shell, not the host's own: the host is started by the app or by launchd, whose PATH is the system's short one, and git starts credential helpers (!gh auth git-credential), hooks' tools and git-lfs by name. LoginShellPath asks $SHELL -l -i -c for it once, prints it behind a marker so whatever the startup files print is left out, and keeps it; when the shell says nothing, the host's PATH is used. When git then says a program was not found ("command not found", "is not a git command"), the shell is asked again, and the action is run once more only if the PATH it gives is another one: the program may have been installed since. The first ask waits for the shell to start (at most 8 seconds), so the actions are never run on the main thread. Under XCTest the user's own shell is never started: LoginShellPath answers nothing there unless a test stands a shell of its own in, so the tests read none of the user's startup files.

Where the agents keep their configuration (#264) is answered in one place, AgentFolders, which setup (the status line, the hooks), a schedule's trust, the history, a conversation's delete and the usage use alike. Claude Code keeps all of it, .claude.json too, in $CLAUDE_CONFIG_DIR when that is set, and Codex in $CODEX_HOME (tried with Claude Code 2.1.330 and Codex 0.171.0, 2026-11-23); otherwise in ~/.claude, ~/.claude.json and ~/.codex. The two variables are taken from the host's own environment, and where it has none, from the login shell, asked with its PATH in the same start: a host started by the app or at login has none of what .zshrc exports, and the agents, started through that shell, do. A conversation is deleted only inside the agent's own folder, links resolved, wherever that is. When a push or pull fails because nothing gave git a sign-in ("could not read Username for ''") and a credential helper was not found, a sentence naming the host and the helper is put above git's words: "git could not sign in to github.com: its credential helper gh was not found."

Commit messages written by an agent

CommitWriter builds the agent's input: the prompt, the list of staged files with their counts (git diff --cached --stat), then each file's diff, capped at 8,000 characters a file and 60,000 in all; files past that are named without their diff. It then runs the agent once, without a terminal, through the login shell as sessions are:

Agent Run as
Claude Code claude -p --no-session-persistence --strict-mcp-config --tools '' --model <m>, the input on stdin
Codex codex exec --skip-git-repo-check --ephemeral --sandbox read-only -o <file> -, the input on stdin
Antigravity agy --print "<input>"
Copilot CLI copilot -p "<input>" --silent --no-custom-instructions --no-ask-user

The agent runs in <state>/commit-writer, not in the project: a headless run inside the project would leave a conversation there, which the History tab would list and SessionSummaries could pair with a session running in that folder. Claude Code and Codex are told not to save one at all; what Antigravity and Copilot save belongs to that folder of the host's, which History leaves out. No agent is given a way to change anything: no tools for Claude Code, a read-only sandbox for Codex, and for the other two no approvals, which without a terminal means every tool request is refused. The answer is taken out of a code fence or quotes if it came in one, and is only ever put in the message field. A run can be stopped; it is also stopped after three minutes.

The settings (agent, model, prompt) are the host's, in settings.json, so the Mac's Write button and the iPhone's do the same. Both apps ask the host with writeCommitMessage, the Mac too, though it runs git itself.

How the Mac is doing

SystemSampler measures the Mac itself every three seconds while a client is connected, and the host sends the result as systemStats:

Figure From
Processor host_statistics(HOST_CPU_LOAD_INFO): busy ticks over all ticks between two samples
Memory host_statistics64(HOST_VM_INFO64): app memory, wired and compressed, less what can be purged, as Activity Monitor counts it; hw.memsize
Network getifaddrs: bytes in and out of every interface but the loopback, between two samples
Temperature The hottest of the processor's sensors, through IOKit's HID event system; ProcessInfo.thermalState always
Battery IOPSCopyPowerSourcesInfo: charge and whether it is charging
Uptime kern.boottime

The calls that read the temperature sensors are in IOKit but not in its headers, so SystemSampler declares them itself. Where they find no sensor, an Intel Mac for one, no temperature is sent and the apps show the thermal state in words. Figures are rounded (a tenth of a gigabyte, a kilobyte a second) so a Mac at rest is not announced again and again. SystemStatsView, in AgentTermTerminal, draws them for both apps.

SSH hosts

SSHConfig.hosts reads ~/.ssh/config: the names after Host, following Include (relative to ~/.ssh, with ~ and wildcards) up to eight deep. Patterns are skipped, and so is any name that is not plain (letters, digits, -, _, .), because a name is put on a command line. Only the names are sent to a client. connectSSH takes a name the host finds in its own reading of the configuration, never a command.

Keeping the Mac awake

SleepGuard holds an IOKit power assertion: PreventUserIdleSystemSleep, or PreventUserIdleDisplaySleep when the display is to stay on. The host holds it while the switch is on, a session exists (with "only while an agent is working", a session whose agent is working: the host looks again whenever a state changes), and, with "only on power", IOPSGetProvidingPowerSourceType does not say battery; it looks again on its timer, so plugging in or pulling the cable is followed within seconds. A hold given a length carries the time it ends in the options; when that passes the host switches it off and tells the clients. The switch, the options and the end time are kept in settings.json. The Mac app calls it directly every few seconds while it is in front. The iPhone asks the host: diff returns the list of files without their diffs, which can be megabytes, and diffFile returns one file's diff. The host keeps the last result per folder for 20 seconds so opening a file right after the list does not run git again. Git and file reading for clients run on a separate concurrent queue, off the queue that moves terminal bytes.

Files tab

FileBrowser (in AgentTermHost) lists a folder, reads a file and tells text from images, other binaries and files too large to open, and creates, renames, writes and trashes. Names are checked to be a single path component, and an existing name is never overwritten. The Mac app calls it directly; it is not in the protocol, so the iPhone has no Files tab.

FilesModel holds the tree (folders load when opened and are read again every 5 seconds while the app is in front) and the open documents. Documents belong to the window, not to the folder being browsed, so switching folders does not close a file with unsaved edits. active names the document in front; it is nil while a terminal shows. The tab strip lists sessions, then documents, and the tab shortcuts count across both.

The editor is an NSTextView whose text storage is Highlightr's CodeAttributedString, which recolors text as it is edited using highlight.js. A Markdown file's preview is a web page (#126): cmark-gfm, the parser MarkdownUI is built on, called directly with GitHub's extensions (tables, struck-through text, links found in the text, task lists), turns the Markdown into HTML and leaves out the raw HTML of the file, and a WKWebView shows it with GitHub's look in the dark. MarkdownUI's own renderHTML() is not used: it builds a table's cells without their spans, which cmark-gfm then takes for fillers and writes no tags for. The page's only scripts are highlight.js (Highlightr's own copy), Mermaid when the document has a diagram, and a few lines that start them, each allowed by a nonce in the page's Content-Security-Policy; nothing of the file runs. The page is made off the main thread and laid out and scrolled in WebKit's process, so a long document holds nothing up. Every preview shares one website data store, kept in memory only: one each had WebKit start a process for each preview. On the Mac, for a document on it, the page is written to a temporary file, so that it may read the pictures the document names: in a folder of the build's and the process's own (<bundle identifier>-preview-<pid> in the temporary folder), each page taken away when its preview is, and the folders that ended apps of the same build left taken away at the first preview. A link opens where the app opens it. What an agent said in a transcript is still drawn by MarkdownUI in place (MarkdownText). The editor and the previews live in the AgentTermEditor target, which both apps use: on the iPhone the editor is a UITextView on the same text storage.

The Mac reads and writes files itself. The iPhone asks the host: files lists a folder, readFile returns text, or an image's bytes up to 8 MB, writeFile saves, and createFile, renameFile and trashFile change the tree and are answered with the folder's new listing. They run FileBrowser, the same code the Mac app calls.

Mermaid diagrams are drawn by MermaidView, a WKWebView, since Mermaid is a JavaScript library. mermaid.min.js (11.4.1, MIT) is checked in under Sources/AgentTermEditor/Resources and shipped in the apps, so nothing is loaded from the network: the page has a content security policy that allows no remote source at all. The diagram's source goes into the page as escaped text, and Mermaid runs with securityLevel: 'strict'.

Highlightr and AgentTermEditor each bring a resource bundle, which scripts/bundle-mac.sh copies into the app's Contents/Resources.

Channels

AppChannel.current is .release only when the code runs in a bundle whose identifier is com.manhpham.agentterm; a development bundle, a bare swift run and the test runner are .dev. The channel decides the app's name, the folder the host keeps its files in, the default port and the scheme of pairing links, which keeps a development build apart from an installed release. See docs/RELEASE.md.

Usage

SessionInfo.usage carries a SessionUsage: model, context tokens and window, limits (window in minutes, percent used, reset time), premium requests. The host fills it on the same six-second timer that names sessions, so both apps get it with the session list.

AgentUsage reads the end of the conversation's file, the last 768 KB: Claude Code's last reply with a usage object, Codex's last token_count event (which carries rate_limits), Copilot's last session.usage_record, Antigravity's last step with input_tokens.

Claude Code writes its rate limits nowhere, but hands them to its status line command. So agenttermd setup claude (#129) puts {"statusLine":{"type":"command","command":"<agenttermd> statusline"}} in its settings, at the user's scope, keeping the one that was there in the setup folder (AgentSetup.previousStatusLine). In a session of AgentTerm's, StatusLineRelay saves the JSON it is given to the file the session's environment names (AppChannel.usageVariable, <state>/usage/session-<id>.json); anywhere, it then runs the status line it took the place of, or the one of the project's or the user's settings, with the same input, and prints what that prints. Claude Code has one status line: of two builds, the one set up last has it and runs the other's after its own, whose own then says it is not known. The other's is run with AGENTTERM_STATUS_LINE_RELAYED set, and a relay run with it runs no relay it keeps, only the user's: two builds set up in turn keep each other's, and would otherwise run each other without end (#259). The one name both builds read, on purpose: it names nothing of either. A build set up again after the other keeps the user's own line, not the other's. The host prefers this report over the conversation file, since it has the limits and the size of the context window. The file is removed when the session ends.

What an account has left is a second thing, AccountUsage, kept per agent and sent to clients as accountUsage when it changes. AccountUsageFetcher asks the agent's service, on the work queue, every five minutes while that agent has a session, or a schedule waiting for its limit to start over (that needs the time, also after the host started again):

Agent Sign-in read from Asked
Claude Code Keychain item Claude Code-credentials, else ~/.claude/.credentials.json GET api.anthropic.com/api/oauth/usage?cedar_ember=1 (the query asks for banked limit resets)
Codex $CODEX_HOME/auth.json GET chatgpt.com/backend-api/wham/usage, and wham/rate-limit-reset-credits when resets are banked
Antigravity Keychain item gemini / antigravity (go-keyring), else ~/.gemini/antigravity-cli/antigravity-oauth-token POST cloudcode-pa.googleapis.com/v1internal:loadCodeAssist, then retrieveUserQuotaSummary
Copilot CLI COPILOT_GITHUB_TOKEN, GH_TOKEN, GITHUB_TOKEN, else gh auth token GET api.github.com/copilot_internal/user

Google answers by client name: the request says antigravity/cli/<version of agy>, which is what returns every group of models.

The rules it keeps: HTTPS only, to those hosts only, redirects not followed; a sign-in is never refreshed or written back, since renewing it is the agent's business and doing it here could sign the agent out; an expired one is not sent at all; nothing of it is logged, stored or put in a message to a client. The outside world is passed in as Environment, so the tests run against canned answers and never touch a keychain or the network.

Conversation history

AgentHistory reads the files each agent CLI keeps about its own conversations and lists those that ran in a folder. Conversations of subfolders are left out by default, so that a workspace holding several projects does not list every project's conversations as its own:

Agent Where it looks Title Resume command
Claude Code ~/.claude/projects/<folder>/<session>.jsonl newest ai-title line, else the first prompt claude --resume <id>
Codex ~/.codex/sessions/**/rollout-*.jsonl (first line has id and directory) first prompt, from ~/.codex/history.jsonl codex resume <id>
Antigravity ~/.gemini/antigravity-cli/conversation_summaries.db (SQLite, since 1.0.16), and cache/conversation_metadata.json of an earlier version its title, else its preview agy --conversation <id>
Copilot CLI ~/.copilot/session-state/<id>/workspace.yaml its name, else the first prompt copilot --resume=<id>

None of these are documented formats, so every reader treats missing or unexpected data as "no conversations", and a CLI update can empty a section until the reader is adjusted. Session files grow to many megabytes, so only the first 256 KB and the last 64 KB are read. Session ids are put on a command line that a shell runs, so ids with anything but letters, digits, -, _ and . are dropped.

Antigravity's store

Antigravity 1.5.12 keeps the list of its conversations in a SQLite store, conversation_summaries.db, and writes no cache/conversation_metadata.json (#224). AntigravityStore reads the store with the system's SQLite (import SQLite3, no dependency added). What was found on 2026-11-21 in a copy of the store of a home that 1.5.12 made, without starting a session:

  • Its table conversation_summaries has a row for each conversation, of 21 columns. History takes five: conversation_id (the id agy --conversation takes, and the name of conversations/<id>.db, brain/<id>/ and annotations/<id>.pbtxt), title, preview, last_modified_time (text, as 2026-11-20 01:02:03.123456+07:00) and workspace_uris (text, a JSON list of file:// addresses). The others are not read, among them parent_conversation_id, nesting_depth, agent_name, source, status, step_count and raw_summary (a protobuf). Beside the table are a search index (conversations_fts, FTS5), search_schema_version and conversation_parents.
  • The transcript is where it was: brain/<id>/.system_generated/logs/transcript_full.jsonl and transcript.jsonl, lines with source, type, content, created_at, status, step_index, and for a model's line model and its tokens. AgentTranscript reads them as before.
  • The store is in SQLite's write-ahead mode (its header says so; its changelog says it checkpoints when it exits). With no Antigravity running only the one file is there, without -wal and -shm.

How it is opened, and why: read-only, by its address with immutable=1. Tried with the system's SQLite 3.54.0 on a copy: a read-only connection of the ordinary kind does not read such a file at all ("unable to open database file"), and one that may write makes -wal and -shm beside it and takes locks in them, which Antigravity's own checkpoint then has to wait behind. With immutable=1 SQLite reads the one file, makes nothing in Antigravity's folder and takes no lock, so nothing AgentTerm does can hold Antigravity up or change what it keeps. The price is that what Antigravity has written to its -wal and not yet brought into the store is not seen: a conversation of a session still running may be listed late, or with the title and time it had before. Reading without a lock, the file is looked at before and after (its size, time and number): when it changed, or SQLite could not read it, it is read again, three times in a tenth of a second, and then given up, never waited on.

When the store is there and not read, or its table has not the five columns, nothing is guessed from it: its conversations are not listed, and AgentHistory.antigravityProblem gives the reason in words ("Antigravity's conversations are not listed: its database of them could not be read. …"). No message of the protocol carries that sentence to the apps yet, so it is not shown: that is still to be decided (#224).

A folder brought over from an earlier version may hold the earlier list beside the store; whether Antigravity leaves it there was not seen, since the one home looked at was made new by 1.5.12, whose binary still names the file. Both are read. A conversation that both have is listed once, as the store says, since the store is what the Antigravity in use reads and writes; one only the earlier list has is listed from it.

Not established, since each needs a session of a signed-in Antigravity: whether a row with a parent_conversation_id (a subagent's, a swarm worker's) is one Antigravity's own /resume lists, so every row with a title or a preview is listed; how long a running Antigravity leaves a new conversation in its -wal; and from which version on the earlier list is no longer written.

Deleting a conversation

Deleting (AgentHistory.delete) moves the agent's own record to the Trash (FileBrowser.trash), whatever a client names being looked up again and kept to the agent's folder: Claude Code's and Codex's file, Copilot CLI's folder.

A conversation of Antigravity is never deleted, whichever of its two lists it was read from (#224, and #222, which was not done). Antigravity has no file for each conversation: its store holds them all, with the search index made from them, and AgentTerm never writes to that store, nor to the earlier list, history.jsonl or cache/last_conversations.json. Taking a conversation's files away while its row stays would leave it listed with nothing behind it. So it is refused in words, "Antigravity keeps its conversations in a store of its own, which AgentTerm does not write to: this one is deleted in Antigravity.", and when several are deleted together Antigravity's are among those kept, which the question says before and the answer after (DeleteConversationsQuestion).

What was found in Antigravity 1.5.12 on 2026-11-21 about deleting, by reading what it keeps and what its binary and agy changelog say, without starting a session:

  • A conversation is named by its row in conversation_summaries.db and the index beside it, conversations/<id>.db (its steps, SQLite since 1.0.4), brain/<id>/, annotations/<id>.pbtxt (its title), presence/<id>.lock, lines of history.jsonl, cache/last_conversations.json (the last one of each folder) and jetbox_summaries_proto.pb.
  • Deleting in Antigravity itself (F4 in the list of /resume) removes the conversation's SQLite file, its annotation since 1.1.24, and its subagents and their worktrees since 1.4.8, as its changelog says.

The Mac app calls this directly, since it runs where the files are. The iPhone asks the host with history, resume and handoff. For resume the host builds the command itself from the agent and the id, after checking both; for handoff it looks the conversation up again on its own disk, so a client only ever names a conversation and never supplies a path or command.

Session names

SessionInfo carries agent, summary and conversationID. The host fills them in, so every client shows the same name without reading any files:

  • agent comes from the command the session was started with.
  • Every 6 seconds SessionSummaries.assign pairs agent sessions with the conversations AgentHistory finds in their folders. Agents do not say which conversation a terminal belongs to, so the pairing uses the agent, the folder and time: the oldest session takes the first conversation that began after it started. For Antigravity, which records no start, it is the conversation touched most recently since the session began.
  • A resumed session's conversation is known from the start, and a pairing once made is kept, so a later, newer conversation does not steal it.
  • Two sessions of one agent started in one folder within the same few seconds can be mixed up.

Handing off a running session uses conversationID when it is set.

What the agent is doing

SessionInfo.state is an AgentState: working(since:), waitingForPermission(AgentQuestion), waitingForAnswer(AgentQuestion), done(said:), or nil when it is not known. stateNote says why it cannot all be known, when there is something to say. The host works both out, so every client shows the same. A note is a mark on the session's row: the Mac shows its words when the pointer rests on it, the iPhone in a popover when it is touched, a button of its own that does not open the session (#87). On the iPhone the row keeps room for the mark and the mark is laid over the row's link (overlayPreferenceValue): inside the link's label, a button's touch, and a gesture's of high priority, opened the session instead.

From the agent itself. An agent's hooks are in its own configuration, at the user's scope, once agenttermd setup added them when the user asked (AgentSetup, #129, below); AgentTerm puts nothing on an agent's command line. How each agent is started, what it asks about itself and what was found by running it, with its version, is in docs/AGENT-CLIS.md.

Agent Where its hooks are Events
Claude Code a plugin (hooks/hooks.json) SessionStart, UserPromptSubmit, PreToolUse, PermissionRequest, PostToolUse, Notification, Stop
Codex its config.toml, each under a comment that says it is AgentTerm's (below): Codex 0.169 removed plugins' hooks (plugin_hooks) SessionStart, UserPromptSubmit, PreToolUse, PermissionRequest, PostToolUse, Stop, Interrupt
Copilot CLI a plugin, in its own layout (hooks.json) sessionStart, userPromptSubmitted, preToolUse, permissionRequest, postToolUse, postToolUseFailure, agentStop
Antigravity a plugin, in its own layout (hooks.json) SessionStart, PreInvocation, PreToolUse, PostToolUse, Stop

Every hook runs agenttermd hook <agent> <event>. It saves what it is told, with the agent, the event and the time, in the file the session's environment names (AppChannel.eventsVariable, each build's own, so that the other build's hooks leave this one's sessions alone): events/session-<id>.json in the usage folder. A host started from inside a session of AgentTerm gives its sessions none of that session's own variables, of either build (HostEnvironment.sessionsOwnVariables, #207), only its own. Every session has one, a shell's too, for an agent typed in it. Outside a session of AgentTerm's it does nothing. The command is the same for every session because Codex trusts a hook by its command and asks again when it changes. For Antigravity's PreToolUse the hook answers {"decision":"allow"}, which leaves the decision to its own rules. The start's event changes no state: it says the hooks are there.

An agent in no terminal is no session's (#140). A session's variables are in the environment of everything started from it, and stay in a program that goes on in the background and works for other terminals after: Codex 0.169 runs its sessions through one app server they share, started by the first of them, which starts every session's hooks and MCP server in that first one's environment. So agenttermd hook, agenttermd mcp and agenttermd statusline go by their environment only when the agent that started them runs in a terminal (ProcessNames.agentInNoTerminal): the process that started them is looked at, past the shells that only ran their command line (sh -c, which some agents keep and some do not), and when it is an agent's own program with no controlling terminal, they do as outside AgentTerm: nothing saved, no tools. What a real agent in a session starts is started by that agent, in the session's terminal, as all four were seen to on 2026-11-18, whether the hook itself has the terminal or not (docs/AGENT-CLIS.md). A process that is no agent's, a test that starts the server itself, is believed as before. An agent another agent runs through its command tool has no terminal either, and is no session's: its hooks no longer change the state of the session it was run in.

The host watches that events folder, which holds nothing else (Claude Code's status line writes its usage next to it several times a second), and reads a session's file when it changes, and on every refresh in case a change was missed; only the latest event is kept, since the state follows from it. AgentHooks.change makes the state from it, from what each agent was seen to tell its hooks on 2026-11-13 (Claude Code 2.1.323, Copilot CLI 1.0.110, Antigravity 1.5.7; Codex 0.167.2 from its documentation, since it runs no hook it was not told to trust). Working stays working since it began.

Whether a session talks to the host (#129). SessionInfo.link has, for an agent's session, whether its hooks were heard (any event) and whether AgentTerm's MCP server was (it says started(agent:) as it starts): true once heard, false when not within linkGrace (20 seconds) of the agent's start, nil until then. Both apps show it as AgentLinkMark at the end of the usage band. A shell's agent typed by hand is found every foregroundInterval (2 seconds) from the leader of the terminal's foreground process group (tcgetpgrp), by the first word of its command line (ProcessNames.command, KERN_PROCARGS2, the last part, as typed; proc_name gives the file's own name, 2.1.326 for Claude Code's link). While it runs, SessionInfo.typedAgent names it and the shell is its session: what was heard before it was found included; hooks name their agent, and the server names the one among its forebears (ProcessNames.agent(above:)). When the shell is in front again, its agent, link, state and turn go.

What cannot be known:

  • Codex 0.169 asks to review the hooks it is given for a session when they are new or changed, and runs none of them when told to go on without. It keeps one trusted hash for each place a hook is given in, whoever gave it ([hooks.state."/<session-flags>/config.toml:stop:0:0"] trusted_hash in ~/.codex/config.toml), and the released and dev builds' hooks name different programs: so the first session after AgentTerm is installed asks, and so does the first after the other build's. Tried on 2026-11-15; the trial of 2026-11-14 (#59) found no question because the hooks had been trusted already. Until its hooks first report, a Codex session's note says its state shows once they run and to choose "Trust all and continue" when Codex asks (AgentHooks.note, AGENT-8).
  • Antigravity says nothing when it waits for permission: its question comes after PreToolUse, with nothing in between, and nothing comes while it is shown nor when it is cancelled (Antigravity 1.5.10, tried 2026-11-18). So while a tool runs, its state is not known, and stateNote says so; except for a tool of AgentTerm's own (#141). Its PreToolUse names it (toolCall.name call_mcp_tool, args.ServerName the build's server, args.ToolName; AgentHooks.ownToolCall), and the call then comes to the host's own server: the host keeps the call it was told of (Session.announcedCall), and when no call of the session's comes to its server within leaveGrace (2 s), the session waits for permission, its question the tool's name (<server>/<tool>). The call that comes (toolCalled(by:), any shell or browser request but a shell's start) makes it work again; input that may stop a turn makes its state not known. A call that came before the hook was read (lastToolCall) is not waited for.
  • The choices of a permission are in no agent's hooks; those of a question are, for all but Codex, which has no question event.
  • A turn the user stops is told by Codex (Interrupt) and not by the others. Escape alone or Control C typed to a working session makes its state not known until the agent says more.

Worktrees

GitWorktrees (host): create(in:agent:branch:from:) runs git worktree add --no-track -b <branch> <top>/.agentterm/worktrees/<branch> <from or HEAD> after listing .agentterm/ in the exclude file, and returns the folder's place inside the new worktree. Paths are written the way the folder is: git gives real paths, and a folder opened through a symbolic link (/var, /tmp) would otherwise not be found in them. list(folder:inUse:) reads git worktree list --porcelain: each worktree's branch, commits ahead of the folder's branch, files changed, and whether its folder is gone; a session counts for the deepest worktree it is in. finish merges (--no-edit, left to be resolved on a conflict as #42 has it, refused with uncommitted changes) and removes, pushes and runs gh pr create --fill through the login shell, or removes with --force.

GitDiff.snapshot leaves out of the untracked files a folder whose .git is a file pointing into the repository's own worktrees folder: a worktree made inside the repository (#43), which git status lists as a folder nobody tracks. Both apps ask for the list again when the changes on show change in number, in branch or in what they are ahead by, so that a worktree's counts are not stale.

Messages: createInWorktree(request:branch:from:), listWorktrees(folder:), finishWorktree(folder:path:finish:deleteBranch:) (refused while a session runs in it); answered with worktrees(folder:list:) and worktreeFinished. No command is run in a new worktree: the folder's setup command of #34 was taken away on 2026-11-16 (#75), and a worktrees.json an earlier build kept is no longer read. What both apps say of a worktree is in WorktreeWords and WorktreeInfo.chipTitle/chipCounts/chipHelp. The worktrees are picked from a list with a search (#217): a popover on the Mac (WorktreePicker, as BranchMenu), a sheet on the iPhone (WorktreeViews.swift, as its branches'); what the search finds is WorktreeInfo.matches(search:), and what the button outside says is pickerCounts and pickerLabel. SessionInfo.branch names a session's worktree branch; WorktreePath tells which folder a session in .agentterm/worktrees belongs to.

On the Mac, AppModel.panelFolder is the worktree shown (shownWorktree) or the selected folder; the side panel's diff, commits, history and files follow it, and selecting a session in a worktree shows that worktree.

Schedules

Schedule (protocol): its agent, folder, prompt, ScheduleTime (once, daily, weekly, limitReset), SchedulePermissions (skipAll, acceptEdits, ask), whether it is on, whether a missed run catches up, whether its warning was accepted, its last 20 runs and its next run. The host keeps them in schedules.json next to folders.json, with until when it looked (checked), from when each schedule is looked at (from, set when it is made or its time changes), and the last limit reset each agent ran for. Clients send saveSchedule, removeSchedule and are told schedules.

What 0.7.0 adds to schedules (#47). ScheduleTime.every(minutes, from, until) comes due at midnight or at from and then every minutes until until, each day; .dates at each of its moments. A run that comes due goes into waitingRuns as before; one whose schedule has a condition or a worktree is got ready off the queue (prepare): the folder's changes are read, or its branch is pulled and its head compared, and its worktree is made (GitWorktrees.create, submodules, the folder trusted for the agent), and it then starts, is recorded as skipped, or is recorded as not started and reported (PartFailure.Part.schedule): also when its submodules or the trust failed, the worktree then kept and named in the run, and when the pull stopped on conflicts, which is aborted first, with nobody there to resolve them (#50). When a run starts, how its folder was is kept (GitActions.baseline: the head, the files as they were as a commit made by git stash create, which changes nothing, and the untracked files); when it ends (runEnded: its agent seen done at a look, or its session gone) its ScheduleRun gets ended, outcome, changes (commits since, git diff --shortstat against the files as they were, new untracked files) and hasOutput: the session's mirror as text, with 5,000 lines above the screen, written to runs/<schedule>-<time>.txt in the host's folder and removed with the run. maxMinutes is looked at each time the schedules are, from the run's startedAt, not from when it came due: a run that waited has its whole time, and its length is counted from then too. A run's session is ended as kill ends one: hung up, and killed three seconds on if it is still there. A run's session is the number of a session of the host that started it, and the next host numbers its own from 1 again: a host that stops ends its runs ("Its session ended with the host"), one that starts ends those a host that died left going, as of when it last looked at the schedules, and both forget every run's session number (#50). Messages: runSchedule(id), stopScheduleRun(id, at), scheduleRunOutput(id, at) answered with scheduleRunOutput(id, at, text), duplicateSchedule(id), pauseSchedules(Bool) answered to every device with schedulesPaused(Bool). The host writes what was changed about a schedule into its edits when it is saved (Schedule.changes(from:)).

Shown. ScheduleOverview (protocol), which both apps use, groups the schedules with the sessions that still run: the runs whose session is one of them (running), every schedule by its next run (then those with none, then those off), and the other runs, newest first. Nothing is added to the protocol: a run names its session, and the session list says which run.

Saving. Refused when the agent does not offer the mode, when it skips permissions without its warning accepted, or without a prompt. Then ScheduleRunner.trustFolder trusts the folder where the agent keeps that: projects[<folder>].hasTrustDialogAccepted in ~/.claude.json, and trustedFolders in ~/.copilot/config.json for Copilot CLI when it does not skip permissions. The rest of those files is left as it was.

Running. Every 20 seconds, on its clock (Configuration.now, which tests set), the host takes each schedule's first time after the later of checked and its from: one that is now or past is due, once, however many came between. A look more than 90 seconds after the last means the Mac slept: a due time older than that is a missed run, run now or recorded as missed as the schedule says. limitReset is due two minutes after the latest resetsAt of the agent's account limits that it has not run for. A due run of a schedule whose last run is still going (its session runs and its agent is not done) is skipped; with two runs going, it waits. A run whose agent's state is not known (its hooks never ran, as Codex's before they are trusted, or it was interrupted) is going until it has written nothing for an hour (quietRunIsDone), then counts as done. A run whose folder is not there is recorded as not started: a session started there would be in the home folder. A run is ScheduleRunner.launch: the agent's command with its switch (claude --permission-mode bypassPermissions|acceptEdits, codex --dangerously-bypass-approvals-and-sandbox --dangerously-bypass-hook-trust, copilot with COPILOT_ALLOW_ALL=true or --allow-tool=write, agy --dangerously-skip-permissions or --mode accept-edits) and the prompt, started as a session with no client attached, SessionInfo.schedule and schedulePermissions set; Antigravity gets the folder among those it trusts for the session. A run's session that has counted as done for 24 hours is closed. The hold on sleep is also taken while a schedule's next run is ten minutes or less away.

When an agent is done or needs you

Each app works out what to tell of from the states the host sends (#3), with AgentNotice.notices(in:told:): a session whose agent is done or waits in a state it was not told in before. told is kept by the app for each Mac across connections, so that coming back to the app tells nothing twice; a session that works again, or whose state is not known, is forgotten in it, so that what it says next is new.

Whether someone is at the Mac. The host works it out on its refresh and when it changes: the Mac app says whether it is in front (appInFront(Bool), only to its own Mac's host), and MacUse.idleSeconds reads macOS's HIDIdleTime. Five minutes without either is no one there. A device that types or takes control of a session makes it no one there, whatever the two say, until this Mac's own app types, takes control or says used (a key or a click in its window, sent once after it was told no one is there) (NOTE-7). Every client is told macInUse(Bool). Since #66 it holds no notice back: every device is told, whoever is at the Mac, and since #234 no notification waits for it either: an agent's waits its 10 seconds whoever is there (#322).

On the iPhone. Since #66 iOS's own banner, in front as behind, for a session other than the one on screen (AgentNotifications, from the host's noticeAlert) while the app is in front. When it leaves the front it tells the host deviceInBackground(true), and deviceInBackground(false) when it comes back, and says which on connecting (#190), a message of its own: appInFront is the Mac app's alone and says only whether someone is at the Mac (updateMacInUse), whoever sends it. iOS suspends an app in the background without closing its socket, so a phone asleep still counted as connected, was sent its notifications over a connection it did not read, and was not pushed to. A device in the background is away (Client.inBackground, HostServer.presentDevices): what comes due reaches it through Apple only, never also over the connection, so nothing shows twice, and its Live Activity is kept true through Apple; back in front it is told, as on connecting, what came due that it was not shown either way (tellUntold, NoticeCenter.untold(to:)). The app still asks iOS for a little more time when it leaves the front (beginBackgroundTask), during which the connection lives for what it shows in the Inbox. A question's or a finished task's notification has a text reply action that asks for the phone to be unlocked; the reply is sent as answer(session:to:text:), naming the state it answers, and the host types it, then Return, only while the session is still in that state; else it answers error and types nothing. A reply given while the connection was gone waits for it. Notifications hide their text where iOS hides previews. A question's choices are actions of its notification (#55): iOS takes a notification's actions from its category, so a question with choices gets a category of its own, named after the request. The text reply comes first so it stays available when iOS shows fewer actions. The first nine choices (AgentNotice.buttons) follow in their original order. The body is the question alone (AgentNotice.words). A choice is sent as a reply is, answer with the choice's words as its text.

How the host types an answer is the agent's list's to say (AgentAnswer.steps, #55). A prompt takes the text, then Return; a finished task's next instruction is sent as the message field sends text (SentText, below under "Vietnamese input"), long ones as a paste when the session's program asked for bracketed paste, which the host reads off its ScreenMirror on the mirror's queue before typing. A question with choices is a list with its first choice marked, and Return chooses what is marked: text and Return there answered every such question with its first choice, in Claude Code, Copilot CLI and Antigravity alike, as trying each showed. So an answer that is one of the choices is typed as Down, once for each choice before it, then Return; any other answer goes to the row after the choices ("Type something.", "Other", "Write-in..."): Down past the choices, the text, Return, with a Return before the text in Antigravity. The steps are typed 0.15 s apart, as a person types them. Only the first of several questions asked together is told and answered.

Notices, from the host to every device (#66, decided 2026-11-19). The host makes each notice once (NoticeCenter, in AgentTermHost), from the sessions' states as AgentNotice.notices has it and from failures (Notice, in AgentTermProtocol): an agent done or waiting, or a PartFailure, which alerts (is a notification) when it stopped work (Notice.tells). It keeps the last 30 days in notices.json (mode 0600), with which device was told of which and which through Apple, so that a device that comes back, or a host that starts again, tells nothing twice; a host that starts again marks what agents asked as over. A client that says what it is (hello's kind) is told; one that does not (agenttermd mcp) is not. Devices are keyed by their registry id, the Mac's own app as local.

  • On connecting, after sessions: noticeLog([Notice]), the 30 days, for the device's Inbox; then noticeAlert(id:) for each one due, not handled nor read, that it was not shown yet. A new notice is notice to every client at once, for the Inbox and the Mac's floating notice. When it alerts, an agent's notice (a question, a permission, a finished task) is a notification 10 seconds later (Notice.alertDelay, Configuration.alertDelay), whether someone is at the Mac or not, and only if it is then neither handled nor read: one the user acted on meanwhile, its agent gone on, is never shown on the Mac nor the iPhone (decided 2026-11-23, #322, over #234's "at once"; #234 had taken away the 30 seconds #180 made a done agent wait). A failure that stopped work is a notification at once (Notice.waitsToAlert). A host that stops during the wait shows, when it starts again, none of those: their sessions ended with it, so their notices moved on, which is read (#321). The wait is short in the host's tests, and AGENTTERM_ALERT_DELAY sets it for the apps' tests. It is due (becameDue, kept in notices.json), and is noticeAlert(id:) to every client in front and a push to each registered device that is away, not connected or in the background (#190), at the same moment. The Mac posts its macOS notification on noticeAlert as before, so it waits the same.
  • Read (#180) is the host's too: readNotices(ids:) from a device marks them read in the log (Notice.read, NoticeCenter.read), and every client is told noticesRead(ids:); each device that had one through Apple and is away has it taken back (gone). Handled by being answered, opened or dismissed is read too (Notice.reads), and so is moved on (#321, the owner's decision of 2026-11-23): an agent that waits goes on only once someone answered it, often in its session, and one that asks something else has a notice of its own for it. A handled notice is taken back from every device whatever the way. A device keeps read in its InboxBook as well, and on noticeLog says what it read while not connected (InboxBook.readHere(notTold:)).
  • A notice is handled once (Notice.Handled: answered, opened, dismissed, moved on): by answer, by noticeSeen for its session and state, by handleNotice(id:how:) (dismissed from a floating notice or Notification Center, customDismissAction), by dismissFailure for a failure's, or when its agent's state changes or its session ends. Every client is told noticeHandled(id:handled:); each device that had it through Apple and is away is sent a push that takes it back (gone).
  • Neither app works notices out any more: each shows what it is told, and posts a notification only on noticeAlert. The iPhone posts one (AgentNotifications.post, content from NoticeContent, shared with the extension), named "<mac>-<notice id>", the name APNs gives a pushed one, and shows it in front too (willPresent → banner, list, sound), except for the session on screen, which it then sees. The Mac shows its floating notice on notice and posts a macOS notification on noticeAlert, in front too and for the session in front too (MacNotifications, willPresent → banner, list, sound; notifyOnMac). On the Mac the session in front is seen only when the user does something (hideNoticeOfTheSessionInFront: choosing it, the app coming to the front, Sessions shown), no longer when its agent's state changes.
  • Permission to notify (#180) is asked up front: on the Mac in the onboarding's Permissions step (Permission.notifications, MacNotifications.askPermission), on the iPhone as the second part of its one first screen (FirstLaunch: ReportingChoices while TelemetryPreferences.needsAsking, then NotificationAsk while PhoneModel.asksNotifications, one cover, never two over each other), once, while iOS was not asked (AGENTTERM_ASK_NOTIFICATIONS shows it to a test). On the iPhone Not Now turns notifyAgents off (#195), and AgentNotifications.askOnce, which pairing, posting and registering for push go through, never asks iOS while it is off: iOS is asked when the switch is turned on again. It goes by PermissionAsk (AgentTermProtocol): the first caller has iOS asked, and every caller that comes while iOS's question is open waits for its answer rather than read the settings, which say "not determined" until then (#200); after it, the settings are read. On the Mac the reporting question is the onboarding's Reports step (OnboardingView.Step.reports, shown while Telemetry.shouldAskAboutCrashReports; AppModel.showOnboarding starts true then), answered by its Next.
  • The Inbox is the device's own InboxBook (AgentTermProtocol), kept by the Mac on show, in its preferences on the Mac, and on the iPhone in a file of the app's own, protected and out of its backups (PrivateFiles, #287): notices newest first, read or not, what was deleted here so that the log does not bring it back, 30 days. Inbox.items(book:sessions:failures:) shows a notice whose agent still says it with its session (answered, continued, handed off there), a failure with the failure, the rest as told.

Through Apple, while the iPhone app is asleep (#66, R1 of the comparison in the issue). A device registers with pushRegister(PushRegistration): its APNs device token, a key it made for this Mac (AES-256, PushSeal.newKey) and its own name for the Mac (SavedHost.id). The host asks the relay to sign a ticket for the token (POST /v1/register) and keeps token, ticket, key and name in pushes.json, mode 0600 (PushCenter). It answers pushState(.on), or .unavailable(reason:) in the words of PushWords: a development build has no relay (PushRelay.url(for:) is nil for it; principle 7), the released one has none until it is deployed, the relay could not be reached. pushUnregister and revoking the device take it out. Each connection registers again, so the ticket (30 days) stays fresh.

  • A notice for a device is a PushNotice (the state shortened to what a notification shows, stateDigest naming the whole of it, a failure's headline and details), sealed with AES-GCM under the device's key, its identifier "<mac>-<notice id>" authenticated with it (PushSeal), and posted to the relay with the ticket. A push that fails is a PartFailure of part push named after the device, one at a time for each device; a token APNs no longer knows (410) or a ticket the relay refuses (401) is forgotten, and the device, told pushState(.off) when it connects, registers again.

  • Taking one back: {gone: identifier} to the relay, which sends a background push (content-available, priority 5) that wakes the app to remove it (AgentNotifications.takeBack), until FILTERING=on: then an alert push the extension removes the notification with and shows nothing for, which needs Apple's filtering entitlement.

  • The relay (relay/worker.js, a Cloudflare Worker, relay/README.md) keeps nothing; it holds the APNs key (Production, restricted to the topic com.manhpham.agentterm), signs the provider token (ES256) and passes the sealed notice on as e, with the identifier as i, under an aps that says "An agent needs you" with mutable-content, sound and interruption-level: time-sensitive, at priority 10 (#233). It signs tickets with HMAC over the token and their expiry, and refuses a push without one or too large; it asks Cloudflare's rate limiting binding to hold a device to 30 pushes a minute and an address to 5 registrations, which Cloudflare does only approximately (relay/README.md).

  • On the iPhone the notification service extension (AgentTermNotifications) reads the key and the Mac's name from a keychain group the app and it share (PushKeys, $(AppIdentifierPrefix)com.manhpham.agentterm.push), which holds nothing else: the pairing tokens stay in the app's own group, listed first in its entitlements. It opens the notice and makes the notification as the app does; a question's choices become a category of its own, which it registers before showing it. One it cannot open is shown as it came. A reply or a choice from a pushed notification carries only the digest: the app goes to its Mac, waits for sessions, and sends answer with the session's state only when its digest is the same, else it says PushWords.movedOn. The device token comes from registerForRemoteNotifications, in the released build only, whose entitlements alone have aps-environment. NoticeContent makes every notification .timeSensitive (#233), whether the app posts it or the extension makes it from a push, which needs com.apple.developer.usernotifications.time-sensitive in the app's entitlements (both builds); without it iOS shows them as active.

  • Priorities (#233, decided by the owner on 2026-11-22), for the notifications and the Live Activity alike (PushPriority, AgentTermProtocol):

    Level When Notification Live Activity
    High An agent asks a question or a permission At once, sound, time-sensitive apns-priority: 10
    High An agent is done At once, sound, time-sensitive 10
    High A part failed that stopped work (Notice.tells) At once, sound, time-sensitive 10
    High An agent stops asking (answered on the Mac or elsewhere) None; the earlier one taken back 10
    Low An agent works, progress, how many run, a done one seen, the end None 5
    Low A notice handled on another device Taken back (background push at 5, or the filtering alert) 5

    Every notice the host pushes is high (Notice.alerts). For the Live Activity, AgentsStatus.priority(since:) compares the status about to be sent with the last one sent (activityStatus, kept whether or not a device was away then): high when the waiting ones change (their counts, names or first), one becomes done, or a failure appears; low otherwise. PushCenter.activity sends it as urgent in activity; the relay sends start and an urgent: true update or end at 10, anything else at 5. A relay of an earlier release ignores urgent and sends 5, as before; nothing else changes for it.

  • The host's log (#233): each push gets one line on the host's standard error, agenttermd: push to <device id, 8 characters>: <kind>, <high|low> (<apns-priority>) (PushCenter.logLine), the kind being a notification, an activity's start, update or end, or a take back (whose priority is the relay's). Never what it says.

  • A device is as its newest connection says (#233). The host counts a device present (presentDevices) while a connection of it is open and not in the background. A connection the phone left behind, say when it changed networks, is not closed on the Mac until TCP gives up on it, and says nothing more: it kept the device present though its newest connection said it was in the background, so nothing went through Apple. A device that connects again marks its earlier connections superseded (admit), which count as away (Client.away) for notices and the Live Activity.

The Live Activity through Apple (#168). Its content is AgentsStatus (AgentTermProtocol), the same struct the host pushes: counts of working, permission, asking, done and unseen, and stopped (a host's or a session's failure), the names of what waits and is done. LiveActivityRule: shown while an agent works or waits, whoever is at the Mac. The app starts it with pushType: .token in the released build and hands the host liveActivity(token:startToken:), the activity's push token and the push-to-start token (iOS 17.2), kept with the device's registration. While the device is away, a change of AgentsStatus is sent 3 s later (a burst is one update) to the relay as {activity: {token, event, state, mac, urgent}}: update to the activity's token, start to the start token when there is none and an agent works or waits, end once none has for LiveActivityRule.keptIdle (15 minutes, Configuration.activityKeptIdle; #180): until then, with nothing working or waiting, it is an update showing so, and a new turn updates the same activity rather than starting one, whose start push must carry an alert; again every 15 minutes while agents work (refreshSummaries). The end is kept for each device (activityEndSent, #192): one that was present when the host's activity ended and goes away later, closed or in the background, before its own keptIdle ran out (iOS suspends the app, and its timer with it) is sent the end when it goes, once. An ended activity is gone: its token is forgotten with the end push (#194), and the next turn sends start. A device that was sent start is sent nothing more for its activity (Target.activityStarted), not a second start, which would show a second activity, until it gives its tokens again (liveActivity, which it sends on every connection): the decision of the owner, 2026-11-21, since the app learns the new activity's token only when it runs. Meanwhile the started activity shows the state it was started with and goes out of date at its stale-date. The app takes up the activity iOS shows each time it updates it (takeUpShownActivity): one the Mac started while it slept is watched for its token, and one that ended is let go, so that a new one is asked for rather than an ended one updated. The relay sends apns-push-type: liveactivity to the topic com.manhpham.agentterm.push-type.liveactivity, priority 10 to start and for an update or end marked urgent, 5 otherwise (#233, above), with stale-date 30 minutes on and, for end, dismissal-date. While connected and in front, the app updates the activity itself.

On the Mac. The agents' notices float over the middle of the window (#225). Until 0.14.0 a notice was a banner in the middle column's VStack, above the terminals: it took its height from them, so the terminal in front lost two or three rows while it showed and got them back when it went, its text moved, and the agent was told a new size each time. Now MiddleColumn draws FloatingNoticeStack as an .overlay(alignment: .top) on the ZStack of the terminals and the place shown over them: an overlay is laid out in the room of what it is over and gives it none of its own, which is why the terminal keeps its size. It is inside the middle column only, under the banners of what stopped (Banners, still in the flow), and not over the toolbar, the list or the side panel. The stack is 560 points wide at most (FloatingNoticeStack.width), each notice a card (FloatingNoticeCard, the banner's content and buttons) on an opaque background with a shadow. Nothing but the cards is drawn, so the pointer reaches the terminal around them; a stack taller than the middle is put in a scroll view (ViewThatFits), which only then takes the pointer over its column.

Which notices are on show is FloatingNotices (AgentTermProtocol), a value with no clock of its own: show(_:id:at:) for each notice the host tells (the same number again takes its own place; another of the same session takes that session's; an eleventh takes the place of the oldest that does not wait, or of the oldest), remove(ids:) for noticesRead and noticeHandled, remove(session:) when its session is opened or comes to the front, keep(where:) with each list of sessions, hover(_:_:at:) from the card's onHover, and expire(at:). One of an agent that is done has goes, 10 seconds on (FloatingNotices.stays; AGENTTERM_NOTICE_SECONDS for the tests); one that waits, or is under the pointer, has none. AppModel.floatingNotices holds it and keeps one timer for nextGoes; a notice that goes by itself tells the host nothing, and stays unread in the Inbox. The app posts an accessibility announcement for each notice shown while VoiceOver is on.

A notice is dropped when its session comes to the front (#60): on the Mac when the session is selected with Sessions shown and the app in front of the others (selectedSession, show(_:), and when the app becomes active: a session chosen in a window behind another app's is not before the user's eyes yet), on the iPhone when its screen is put on the navigation stack (path). The app then tells the host noticeSeen(session:state:), once for each state, when the agent is done or waits. The host passes it on to every other client while the session's state is still that one, and keeps it (noticesSeen) for a client that connects later, which is told after its list of sessions. A client that is told drops its banner of that session and state; the iPhone also takes its notification of the session out of Notification Center (AgentNotifications.remove), as it does when the session is opened on the phone itself.

The Inbox (#67). Which sessions are done and not seen is the host's, so that every device shows the same: SessionInfo.unseen is set when a hook makes the session's state done, and taken away when its agent works again or noticeSeen is told for its done state. That message is what a device sends both when the session is seen there and when its Inbox item is dismissed; a client sends it again while the session is still unseen, since an agent done twice with the same words is done twice. The list is made by both apps the same way, from the sessions and the failures they have (Inbox.items in AgentTermProtocol, with the words both show): the waiting ones, the failures, the unseen ones. The Mac shows it as a place, AppModel.Place.inbox, with its list (InboxList) and the item picked in the middle (InboxDetail), over the terminals as History is; the item picked is kept by its id (inboxPicked), and the first is shown when it is gone. Open goes to Sessions with the session in front, which is what sees it. The iPhone shows it at the top of SessionsView, the failure cards among its items.

What a turn came to (#71). A turn begins when a hook makes the session's agent work while no turn is open (HostServer.beginTurn): a TurnRecord keeps when, the prompt the hooks gave, and, taken on a queue of its own (turnQueue), a GitSnapshot of the repository: git status --porcelain=v1 -z --untracked-files=all and git diff HEAD --numstat, with each file's size and time of writing. It ends when the agent is done, or when the user stops it (Codex's Interrupt, a key that may stop a turn): on the same queue the folder is looked at again and the two are compared (GitSnapshot.changes: a file whose status, lines, size or time changed, or that came or went), and the agent's own record of the turn is read from the end of the file its last event names (TurnTranscript: the prompt and the answers as handoffs read them, the commands and their exit codes in each agent's own way, docs/AGENT-CLIS.md). The TurnResult is kept as the session's lastTurn, in memory, and sent to every device (turnResult), and to a device that connects after its list of sessions. Another agent's session working in the same folder, or one inside or around it, at any moment of the turn makes it shared. A file changed in the moment between the prompt and the first look is taken for the folder as it was. The Mac shows it in InboxDetail; the iPhone in TurnResultScreen. Every item of the iPhone's Inbox opens NoticeScreen (Route.notice), as every item of the Mac's shows in InboxDetail: TurnResultScreen for an agent done whose session runs, the notice whole otherwise (Notice.fullBody, all of what was said; body, the last 300 characters, is a notification's). Continue is the answer a notification's reply sends. A session also counts as seen when it becomes done while it is already in front: both apps look again when the list of sessions comes.

The Live Activity

A widget extension, AgentTermLiveActivity (iOS/AgentTermLiveActivity), with AgentsActivityAttributes (iOS/Shared, in both targets): the Mac's name, and as content how many work and the names of those that wait and are done. The app starts, updates and ends it (PhoneModel.updateLiveActivity) whenever the sessions, the connection or macInUse change, as LiveActivityRule.decide says: shown while an agent works or waits, and for keptIdle after the last one stopped (#180), updated, not ended; ended after that with the last state left showing; ended at once when switched off. Its link, <scheme>://session?id=<n>, opens the session that waits. No push token is asked for: updates come from the app while iOS lets it run.

Its bundle identifier is the app's with .LiveActivity; the release lane signs it with a profile of its own from match.

Shells an agent opens

AgentTerm's MCP server is agenttermd mcp (AgentShellsMCP): JSON-RPC, one message to a line, on standard input and output. Its shells' tools are named alike, as the browser's are: shell_open, shell_run, shell_list, shell_read, shell_send, shell_wait, shell_stop and shell_close. shell_stop types Control C in the shell and waits, five seconds unless told, for what runs to end: one call for what an agent does when the user says stop, rather than shell_send with a key to look up. Each says in its annotations whether it only looks (readOnlyHint: shell_list, shell_read, shell_wait, and the browser's that only look) and whether it ends something (destructiveHint: shell_close, browser_close).

How shells start. The host keeps ShellSettings in its settings.json (setShellSettings, told to every device with shellSettings, with the login shell and the Mac's shells from /etc/shells and Homebrew's folders): the program of a shell (a session with no command; one with a command keeps the login shell), what is run first in the user's shells (pendingStartup, typed a line at a time with Return once the shell first writes) and in the agents' (in AGENTTERM_STARTUP, evaled by the integration's .zshrc after the user's own, before the hooks; typed as in the user's when the shell is not set up), and marks, whether an agent's shell is set up at all. How the terminals look is the Mac app's own (terminalFontName, terminalCursor, cursorBlinks, scrollbackLines), given to each TerminalController and to TerminalStyle.fontName, which TerminalMetrics measures by.

A command and how it ended. A shell an agent opens without a command is set up to say when each command starts and ends, with its exit code, in the marks of OSC 133 (ShellIntegration): zsh is started with ZDOTDIR pointing at the host's shell-integration/zsh, whose startup files read the user's own from their folder as zsh would (a ZDOTDIR their .zshenv sets included), then add a precmd hook, first, that writes D;<exit code> and A, and a preexec hook that writes C, and point zsh back at the user's folder. fish writes the marks by itself; another shell is used as it is. The user's own sessions are never set up. ScreenMirror finds the marks in the output as it comes (CommandMarks, a mark cut in two included) and feeds what a command writes, from its C to its D, to a terminal of its own as well, whose text is the command's output as a terminal shows it. run(session:command:) types the command at the prompt as a paste when the shell takes one (so that lines are one command) and Return, refused while a command runs; command(session:lines:) tells the commands as they stand (AgentCommand: whether the shell says anything, how many started, whether one runs, the last exit code, the last lines of its output). shell_open returns once the shell showed its first prompt. shell_run waits for the command to end, 60 seconds unless told otherwise, and answers its exit code and its last 300 lines; one still running is left running, and the server keeps which it is, so that shell_wait tells how it ended, also when it ended in between. From a shell that says nothing, shell_run answers the screen once it is still. shell_wait with a text waits for it; without, for the command that runs to end; with none running, for the screen to be still, reading it every 0.2 seconds.

The server answers tool calls side by side (#64). Its lines are read in turn; a tools/call is handed to a concurrent queue and answered when its tool is done, under its request's id, so that a shell_wait or a shell_run, which may take as long as the agent lets it, does not hold up the calls that follow it, nor another on another shell. notifications/cancelled with a request's id ends a wait that is going on, and that request is then not answered: each of the four agents sends it when the user stops a call (MCP-25). Antigravity sends its calls one at a time, so a long wait holds up its other calls by its own choice, not the server's. An answer is one line, written whole. The line to the host (AgentShellsLink.ask) already took requests side by side.

Which session's agent it is. The host gives every agent's session a key of its own, with its port and its build, in AGENTTERM_MCP (<port> <key> <release or dev>, then use); the agent passes its environment on to the server it starts. The server signs in to the host as any app on the Mac does, with the Mac's own token from the state folder, and sends each request as agentShell(id:key:request:). The host looks up the session whose key it is and answers agentShellResult(id:result:) to that connection only. A key names a running agent's session or nothing. Without the variable, the server offers no tools. Nor does it when the agent that started it runs in no terminal, whose environment is not the session's it works for (#140, "An agent in no terminal is no session's"). Nor does it in a session of the other build: a released build and a development build each install a server of their own (below), so an agent has both, and the one whose build the variable does not name stays out rather than sign in to a host with another host's token. A variable that names no build is from a host of 0.6, and is the released build's. While the agent is told anything (its words in Settings > Agents are not empty) the variable ends with use, and it names the session's agent (agent:claude).

Whether a session was told (#172). AgentLink.prompt says what AgentTerm's instructions came to in one session: given, missing, disabled or unverified, from how they reach its agent (AgentLink.prompt): through the MCP server for Claude Code and Codex, so given once the server is heard and missing when it is not; through the environment for Copilot CLI, shown as “File provided” once the file is written and its directory is present in the launch environment, or “Not given” if preparation fails. Copilot does not acknowledge reading the file. Instructions come through a rule of its plugin for Antigravity, which the host cannot see for one session. Whether there were instructions is taken when the agent starts (Session.promptGiven): a change in Settings later is the next session's. The mark's popover has a row each for Hooks, MCP and System Prompt. The hook check waits for the first submitted message. If no hook arrives within 20 seconds of submission, the session reports that no hook responded. A later event changes its status to Heard.

What an agent is told. The host works out one text for each agent: what the user saved for it in Settings > Agents (setAgentPrompt, kept in agent-prompts.json of the host's folder and told to every device with agentPrompts, with each agent's default), or else the default: AgentShellsInstructions.useShells and AgentShellsInstructions.browser, whenever the host gives the server (AgentShellsInstructions.told), with no switch since 2026-11-16 (the owner's decision): the words are the switch. An empty text tells nothing, the server's instructions included: without use the server says only what its shells are. The host writes that text for every agent to prompts/<agent>.md of its folder, when it starts and when the user changes it, which the server gives as its instructions, and gives it where each agent reads it (MCP-13, PROMPT-1 to PROMPT-4), nothing on its command line (#129): Claude Code and Codex take the server's instructions (Claude Code 2.1.326 was seen to give them to the model); Copilot CLI takes MCP servers' instructions only from servers it allows (seen not to, 2026-11-17), so every session's environment has COPILOT_CUSTOM_INSTRUCTIONS_DIRS naming a folder of the host's with instructions/agentterm.instructions.md (after any the user's environment names); Antigravity gets them as a rule always on of its plugin, which it reads everywhere, so the rule says it holds only where the server has tools. The server outside a session of AgentTerm's gives no words but that it has no tools.

What the default asks (#156, MCP-33): to run shell commands in a shell of the server's own rather than with the agent's own tool, and, when the server's shell_ or browser_ tools are not loaded yet (Claude Code defers an MCP server's tools until the agent asks for them by name), to load them by name before the first command. Tried on 2026-11-19 with the four real agents in the development build, each at its cheapest model (MCP-35): Claude Code 2.1.328 with Haiku 5.5, Codex 0.169.1 with gpt-5.6-luna (once in two runs) and Antigravity 1.5.10 opened a shell of the server's and ran the commands there; Copilot CLI 1.0.114 called shell_open and waited for the user's leave to use it, as it asks for any tool. Whether an agent follows the words is the model's: Haiku, in a host that refused its server, answered with its own file tools.

What it may reach. A shell it opens is a session like any other, in the agent's folder and at its size, with SessionInfo.openedBy naming the agent's session. Only that agent sees it: it alone lists, reads, types into and closes it, and agentShellResult's shells(_:) lists the asking agent's own (#61). So what runs in an agent's shell is what that agent started, and no agent has to guess from a screen whether a shell is free: one that has none, or whose own is busy, opens another. Any other shell is answered as if it were not there, with words that say to open one; so it is for a shell whose agent's session has ended: it stays open for the user, and nothing takes it over. A session that is resumed or handed off is, to the host, another agent, and does not see the shells it opened before. An agent never reaches the user's sessions or an agent's session. A command whose first word is an agent's is refused. Typing is the same as typing: text, and keys by name turned into the bytes a terminal sends (TerminalKeys). When the agent's session ends, the server it started ends with it. The apps name a shell's agent on its row (SessionInfo.openedByName).

When it cannot reach its host. The server's line to the host (AgentShellsLink in agenttermd) signs in when the server starts. A connection that is refused or closed answers whoever waits at once, with the reason in words: the host is not running on its port, the host refused the sign-in (it answers a wrong token with error("invalid token") and closes), or the connection was lost. Each later call tries the host once more, so it fails as fast while the host is gone and works again once it is back; only a host that is up and silent is waited for, fifteen seconds. The host notes a sign-in it refused from a client on this Mac named MCP, and tells every client agentShellsFaults: an AgentShellsFault per cause (signIn), none when nothing is wrong. It lasts until an MCP client signs in or the server is set up again. Both apps show it in their top banner until it is over or it is closed there, and a closed one comes back only after it went away. A host that is not running cannot say so itself: that one is the agent's to tell.

In the agent's own configuration (#129). What AgentTerm needs of an agent is in the agent's own configuration, at the user's scope, once the user asked: Install in Settings > Hooks & MCP, which the host runs (runAgentSetup, from this Mac's own app or a paired device, #155: the host runs AgentTerm's own commands only, never one a client names), or the commands the pane shows, in a terminal. Each part is added with the agent's own command when the agent has one, and that command is what the user is shown; AgentTerm's own (agenttermd setup <agent>) is for what an agent has no command for (decided by the owner on 2026-11-18: the user sees a standard command of the agent's, knows what it adds, and takes it out the same way). As tried with the real agents on 2026-11-18, each in a configuration folder of the trial's own (docs/AGENT-CLIS.md):

Agent The MCP server, its own command What it has no command for, AgentTerm's (agenttermd setup <agent>)
Claude Code 2.1.327 claude mcp add --scope user <name> -- <agenttermd> mcp its hooks, in a plugin of a marketplace in AgentTerm's folder, which it is had to install (claude plugin marketplace add <folder> --scope user, claude plugin install <name>@<name> --scope user); its status line. Its server's instructions reach the model
Codex 0.169.1 codex mcp add <name> -- <agenttermd> mcp; and for its shared server codex features disable daemon_auto_start (below) its hooks, in config.toml (above), read back with codex features list and put back as they were when it cannot; the session's variable, env_vars in the table its command wrote, which has no option for it and without which Codex gives a server nothing of its session
Copilot CLI 1.0.113 copilot mcp add <name> -- <agenttermd> mcp its hooks, in a plugin (copilot plugin marketplace add <folder>, copilot plugin install <name>@<name>), read from the folder at each session. It does not give a server's instructions: what it is told is in a folder of instructions its environment names (COPILOT_CUSTOM_INSTRUCTIONS_DIRS), in every session
Antigravity 1.5.10 agy mcp add <name> <agenttermd> mcp its hooks and a rule with what it is told, in a plugin (agy plugin install <folder>, a copy)

AgentSetupState.steps and removeSteps (protocol 28) are those commands as typed, each with what it is for, the agent's own first; Install and Remove run them in that order (AgentSetup.install, .all), a server of before taken out first, as Claude Code and Copilot CLI refuse a name they have. agenttermd setup <agent> runs AgentTerm's part only (.own), and says the agent's command for what is still missing. AgentSetup writes the plugins into the build's state folder (agent-setup/<agent>), with this build's names (AppChannel.mcpServerName) and program; the server is in none of them. A plugin that held Codex's server, of a build before, is taken out.

--remove takes out this build's only, with the same commands. What each has is asked of the agent (mcp get or mcp list for the server, which has to run this build's program; plugin list, Codex's hooks, Claude Code's statusLine), off the host's queue; a command that fails is kept as the agent's problem, in its own words.

Codex's hooks, by their own lines (#142). Each hook is three lines in config.toml: a comment that names the build (# AgentTerm's hook (agentterm), added by …), its table ([[hooks.Stop]]) and its command. A build's hooks are taken out by those lines, wherever Codex has them by then, and nothing else is. They were between two marks before: Codex keeps the comments a file ends with at its end and writes a table it adds above them, so the closing mark took in what Codex added after, a folder the user trusted or a server they added, and Install Again and Remove took that out with the hooks. Hooks a build before wrote between marks are taken out by their lines too, and what Codex put between the marks stays.

Codex's shared server (#140). What a principle asks of an agent is arranged with the agent's own command when it has one, and by AgentTerm's own writing only when it has none (above). Install turns off the feature that has Codex start the app server its sessions share (codex features disable daemon_auto_start), keeps that it did (agent-setup/codex/shared-server-was-on), and Remove turns it on again (codex features enable), unless the user had it off, or another build of AgentTerm is still set up in Codex and needs it off as much. The row says so before Install is pressed (AgentSetupWords.sharedServerNote): the setting is all of Codex's, outside AgentTerm too. A server that runs is used whatever the feature says, and stopping it leaves the sessions that use it waiting, so it is not stopped: AgentSetupState.sharedServerOff (protocol 27) is false while Codex starts one by itself or one runs (codex app-server daemon version), the agent then counts as not set up, and its problem says what to do (AgentSetupWords.sharedServerRunning). A Codex that has no such feature is asked nothing of it. Being Codex's own command, it is one of the steps shown, and agenttermd setup codex leaves it to the user who runs the steps by hand. AgentTerm still puts nothing on the command line it starts Codex with (--no-daemon would do the same for the sessions it starts, and not for one typed by hand). The server finds what to say in the prompt files the host writes for every agent (HostServer.promptFile). Every session has its key in its environment (AGENTTERM_MCP, which names the build), a shell's too; outside a session of this build the server offers no tools. A host with a state folder of its own (a test) sets up only its stand-in agents, in its own home, and never the user's. What builds before 0.8.0 put in the agents' configuration (agent-shells.json) is no longer taken out (principle 6).

The browser

The Mac app's browser (#76) is Chromium, embedded with the Chromium Embedded Framework (CEF 156.0.30, Chromium 156.0.8078.96, tried on 2026-11-15). Nothing of CEF is in the repository: scripts/fetch-cef.sh fetches the minimal binary distribution, pinned with its SHA-1, into .build/cef/<name> and points .build/cef/current at it.

The right-click menu (#131). The client's context menu handler sets the items from what was clicked (on_before_context_menu: the type flags, the media type, the edit state's flags), each labelled by the app; CEF shows them in its own menu, and does the ones that are its own (Back, Forward, Reload, Cut, Copy, Paste, Select All). The app's own, from MENU_ID_USER_FIRST (ATC_MENU_*), are told to Swift as an event, ATC_EVENT_MENU_COMMAND with the link's and the image's address: BrowserTab.menuCommand opens them as a page (as a page that asked for a new window is), copies them, or shows the DevTools. A page is laid out for accessibility only for the UI tests (AGENTTERM_WEB_ACCESSIBILITY, set when a browser is made): Chromium does it for a reader at a cost.

A button's label is of one shape (#134). The Show As button on a page's bar shows a picture, and a device's name beside it when the page is shown as one. With the name there only for a device (if let), SwiftUI made the button anew when the first device was picked: its accessibility element was another, so that a press on the one found before did nothing and was still reported as done, and a list open under it was closed with the state it is shown by left as it was, so that the next press closed what was not there. The name is always in the label, empty and of no height for this Mac, so that the button is as large as it was. A button drawn by AppKit, the bordered ones of the Git panel, keeps its element through such a change: its Push, found before a commit, pushes after it, as tried.

Windows of Chrome's own (#125). Chrome's own interface opens windows of its own kind, an extension's page say, outside the app's views; CEF gives them no client of the app's (get_default_client would, but a window made through it is not the one an extension opens, and hiding those that are broke an install, as tried on 2026-11-17). So the app watches its windows instead (BrowserModel.watchChromeWindows, on didUpdate and the windows' key, main and occlusion changes): one of Chromium's (NativeWidgetMacNSWindow, looked up once the framework is loaded), with a title bar, resizable, and with no parent (not a bubble or a dialog), that the app did not ask for, is ordered out and held, and kept out of sight when Chrome shows it again; held, not closed, so that what made it goes on. Open in Chrome Window shows them (atc_open_chrome_window makes one for a page, in the page's request context, marked agentterm.chrome-window); they are closed before Chromium stops, which they would keep from stopping.

The bridge. CAgentTermCEF is C and Objective-C on CEF's C API, its headers read from .build/cef/current (headerSearchPath) with CEF_API_VERSION 15600 pinned, so that a later build of the same API is taken without a change. Built without the headers (__has_include), it compiles to stubs and the browser says it is not in the build. Each function of the header has its stub, and a build with the headers never compiles them: one that is missing stops only the linker of a build without them, which CodeQL's is (#133), so BROWSER-39 compiles the file as such a build does and looks for each. The framework is never linked: it is loaded with dlopen the first time a browser is wanted, and the dozen functions used are looked up by name. Reference counting follows the C API: a struct a callback receives carries a reference the callback releases, and a struct of ours given to CEF carries one CEF releases. CEF runs on the main thread with an external message pump: on_schedule_message_pump_work sets a run loop timer in the common modes, at most a thirtieth of a second away, as cefclient does. A turn of CEF's work is not done from inside another, except under a right-click menu (#139): CEF runs the menu from inside the turn that opened it, which then lasts until the menu closes, and with every other turn put off nothing of Chromium went on (a page asked to reload was not read, its title stood still). Between on_before_context_menu and on_context_menu_dismissed one level more is let in. Chromium wants its application to say whether it is sending an event: isHandlingSendEvent, setHandlingSendEvent: and a wrapped sendEvent: are added to NSApplication itself. Changing the running application's class instead, as first done, crashed the app the first time Chromium added a key-value observer to it: by then the application's class was the one observing had made for it. do_close answers that it is handled; answered otherwise, CEF sends performClose: to the window the page is in, the app's own.

The processes. The pages, the GPU and the network run in the helper apps of the bundle's Frameworks folder, " Browser (Chromium).app" and its four variants, named so for Activity Monitor, where the pages' memory is then seen to be the browser's, all one program (AgentTermBrowserHelper), which enters Chromium's sandbox (libcef_sandbox.dylib, cef_sandbox_initialize) before it loads the framework, then runs cef_execute_process. The browser runs in the app bundle only: scripts/bundle-mac.sh puts the framework in, in the versioned layout codesign wants, and the helpers, each signed with the entitlements scripts/browser-helpers.sh names. No DevTools port is opened (remote_debugging_port 0).

Settings and profiles. CEF's root folder is the state folder's browser, so the two builds and every test keep their own; its keychain item is " Safe Storage" (keychain_service_name, new in CEF 156). A test, which runs with a state folder of its own, and the development build use a key of Chromium's own (use-mock-keychain) and never the user's keychain: the development build is signed ad hoc, anew with each build, and macOS asked each time whether it may read its item (decided by the owner on 2026-11-15). Its cookies are then only as safe as its folder. A profile (BrowserProfiles) is a request context with cache_path browser/profile-<id>, right in the root folder, where Chromium's profiles have to be: one a level further down is refused ("Cannot create profile at path"), and its pages fall back silently to a profile of Chromium's own, which every profile then shares (found on 2026-11-15, BROWSER-10). It is opened in the background: a browser is made in it once on_request_context_initialized says it is open, and atc_create answers with ATC_EVENT_CREATED and the token it was given. The profiles, their names and the default are the app's preferences. Data Chromium has open is wiped at the next start, before Chromium opens anything (browserProfilesToWipe). A request context is named by a key (atc_create's key), the profile's id, so that tabs of one profile share it. An agent's profile is the one it names, then the one it was given (BrowserModel.agentProfiles), then the only one; with several and none named, browser_open is refused at once with their names (BrowserWords.whichProfile), for the agent to ask the user in its conversation. A private tab's profile is private-user or private-agent-<session>, a request context with no cache_path, which Chromium keeps in memory; atc_forget_profile lets it go when the last of its tabs closes, and the next private tab gets a new one. A popup is opened in its opener's profile, made by Chromium itself so that it keeps its opener (#162): on_before_popup asks the app (atc_popup_fn, on the UI thread) for a new tab's view and a token, puts the popup's window_info in it and lets Chromium go on; on_after_created knows the browser by its view's superview and sends ATC_EVENT_CREATED with the token, as for a browser the app made. Without a view it opens the address in a tab, without its opener, as before. A page that closes itself (ATC_EVENT_CLOSED with the tab not closed by the app) closes its tab.

Tabs. A BrowserTab holds Chromium's browser for one page, the view it draws in (BrowserContainerView, moved to whichever pane shows it), and its DevToolsSession. A page no pane shows waits in a one-point view in the window's corner (BrowserParking): Chromium draws, and takes pictures of, a page in a window only. Its tab id in a TabLayout is b:<id>; a tab an agent opened is its companion and shows in its area (see Panes). The tabs are not kept: the app opens with none, and what an earlier build kept in the app's preferences (browserTabs) is forgotten. An agent's tab whose agent has ended is the user's.

The devices. A device asks with browserAsk, for what the user does (BrowserRequest.isTheDevices: a picture, take over and give back, watch, tap, text, press, scroll, history, navigate, stop, emulate, close, profiles, and newTab, a tab of the user's in a project, in a profile or private, which the Mac does not bring to the front). A tap is answered with whether a field of the page took the keyboard (touched, from the element that has it, through shadow roots and frames of the same site; a frame of another site counts as a field), and the device's keyboard comes up for it; a newTab with the new tab's id (opened). What a device does to a page is done on the Mac in the order it was sent (BrowserTab.deviceInput chains them), since each answer is awaited in a task of its own; so is what reads what that input made, a copy and a contextAt, which are not refused while the user has the tab as what acts is (BrowserRequest.followsTheDevicesInput, #191). A page no pane shows that takes the keyboard while it loads is not brought to the front, and the keyboard goes back where it was. The host keeps which devices watch which tab (browserWatchers), and asks the app for a tab's pictures when its first watcher comes and stops it when its last goes, a device that goes included. The app sends each picture as a JPEG no wider than the device asked, with the size in CSS pixels of what the page shows (browserFrame); the host passes it to the watchers. A Mac showing another Mac's page (#147, RemotePageView) draws those pictures and sends its mouse as pointer events in the page's CSS pixels: moved (a hover, and with the button held a drag, which selects text), pressed and released, each sent once the one before it is answered so that they keep their order, the moves made meanwhile kept to the latest; ⌘C and a right click wait in the same queue, never kept to the latest, so that they read what the drag before them selected (#191); so do the keys, text typed and pasted, the wheel, a press by accessibility and the menu's Back, Forward and Reload, everything that follows the device's input on the Mac whose page it is (followsTheDevicesInput), so that text typed right after a click goes where the click's release put the caret and a scroll comes after the drag before it (#199). The queue is PageInputQueue (AgentTermProtocol): while one waits for its answer, moves are kept to the latest, scrolls added up and text typed joined, none dropped; a watch and a new tab, which follow no input, go at once. The Mac the browser runs on gives them to Chromium as Input.dispatchMouseEvent; a press takes an agent's page over, as a tap does, a move does not. A right click is not sent to Chromium, whose menu would open on that Mac: contextAt asks what is at the point (the link there, read with document.elementFromPoint, and the selection), and the viewing Mac shows its own menu with Chromium's words (BrowserWords.PageMenu): Copy, Open Link in New Tab, Copy Link Address, Back, Forward, Reload. ⌘C asks copy, the page's selection, or a field's, as text, and puts it on the viewing Mac's pasteboard. A page's own right-click menu, made by its script, is not shown from another Mac. What the viewing Mac asked and was not answered when the connection to that Mac closes is answered at once, refused, and said (BrowserWords.otherMacClosed: it may not have been done there); when the user switches to another Mac it is answered so without being said, and a page's view sends nothing more once its Mac is not the one on show (#196). While the Mac draws the page (BrowserTab.isDrawn: in a pane of a window on screen and not covered) the pictures are streamed (Page.startScreencast), about ten a second, each acknowledged a tenth of a second after it comes. While it does not, Chromium draws nothing to stream, and a picture is taken about five times a second (Page.captureScreenshot, made smaller with ImageIO) and sent only when it differs from the last. Not taken while the Mac draws it: for a page shown as a device whose pixels are not the screen's, Chromium lays the page out again for each picture, a clip or a scale given or not, and the Mac shows it in between, the page shaking (#100). What is streamed has a pixel to the page's point at most, whatever maxWidth asks and whatever the screen has, which a device draws two or three times larger, blurred. So a page that is streamed and has stood still for 0.7 seconds, longer than a caret's blink, has one picture taken of it, with all the pixels it is drawn with, sent in place of the last streamed one and not taken again until the page changes (PageStills): only where a picture taken has more pixels than a streamed one, and where taking it leaves the Mac's page as it is, the page shown as itself or as a device with the screen's pixels. A page shown as a device whose pixels are not the screen's (a phone of three on a screen of two) stays as streamed, soft: sharpening it costs the Mac's page a shake each time it comes to rest, which the owner decided against (2026-11-21). Measured that day on a screen of two pixels to a point, with AGENTTERM_LOG_FRAMES: the stream had two pixels to a point there, 814 × 1094 for a page of 407 × 547, and the picture taken of the page at rest had the same; one pixel to a point is what was measured earlier (#107) on another screen. Taking a picture has Chromium draw the page once more, streamed the same as the last: a streamed picture the same as the last is not sent and is not a change, or pictures would be taken without end. A device asks its pictures as wide as the room it draws them in has pixels (PagePicture.width, asked again when the room's width changes by more than 80), which bounds a picture taken, made smaller with ImageIO; one streamed has fewer anyway. JPEGs are of quality 80 (PagePicture.quality; 55 before, whose losses were what was seen first once drawn larger), and one that weighs more than 2.5 MB is made narrower until it does not (DevToolsSession.fitted): in base64 it must stay under the 4 MB a message may be. A device lays a picture into its room whole, in the picture's own shape counted from its pixels, as large as the room lets it be, and places a touch by the size sent with it (PageFit). With AGENTTERM_LOG_FRAMES set the Mac app writes a line for each picture it sends, one a second at most for each tab and path (screencast, still, capture): its pixels, the size sent with it, whether the two are of one shape, what the page is shown as, its pane and the screen's pixels, and what Chromium says the streamed picture shows; to stderr, or to the file the variable names (FrameLog). A page shown as a device whose screen is taller than its pane has the pane's height (Emulation.setDeviceMetricsOverride's height, set again when the pane changes size; screenWidth and screenHeight stay the device's), on a dark ground beside it: it is as wide as the device's screen, never drawn smaller, and what is below is reached by scrolling it. What the Mac draws, and so what is streamed, is then the page as it is shown, a pixel to its point (what Chromium's screencast gives, whatever the Mac's screen has), and the size sent with it is its own; the devices draw a picture in the picture's shape (#107, the owner's decision of 2026-11-16. Before, the Mac drew the screen's top only, and the devices drew that part squeezed into the screen's shape; then the screen was drawn smaller to fit, scale, which Chromium streams as the whole surface with the page small in a corner, and too few pixels for a device). Streamed, a picture has a pixel to the page's point; taken, as many as the page is drawn with, up to what the device asks for. A touch is placed in CSS pixels by that size and clicked with Input.dispatchMouseEvent; text is Input.insertText. Acting on an agent's tab from a device makes it the user's, as a click on the Mac does.

The agents. An agent's browser_* tool is a BrowserRequest, which agenttermd mcp sends as agentBrowser(id:key:request:). The host finds the agent's session by its key and passes the request to the app that said browserProvider(true), the Mac app on this Mac signed in with the Mac's own token, as browserCall(id:agent:request:); the app answers browserReply(id:result:), passed back as agentBrowserResult. With no such app, or when it goes, whoever waits is answered at once (BrowserWords.noApp). An agent sees and reaches only the tabs it opened (BrowserTabInfo.reachable): browser_tabs lists those, and any other tab, the user's or another agent's, is answered as if it were not there (BrowserWords.notYours). The app refuses an action, not a look, while the user has the tab. It drives the page with the DevTools protocol inside the process (atc_devtools, CEF's SendDevToolsMessage): the snapshot is Accessibility.getFullAXTree written as text, a ref for each element of an actionable role, kept with the document it was taken of, which goes up with each navigation of the main frame; a click is DOM.getBoxModel and Input.dispatchMouseEvent at the element's middle; typing is DOM.focus and Input.insertText; a picture is Page.captureScreenshot; the console and the requests are kept from Runtime, Log and Network events. Each action answers with where the page is, its title read from the page, and what happened meanwhile.

Devices. The iPhone sees browserTabs, which the app sends the host whenever a tab changes and the host keeps and passes on, and asks browserAsk(id:request:) for a picture (picture, a JPEG) or to take a tab over or give it back; a device's request to act on a page is refused by the host. What the iPhone asked and was not answered is kept in a BrowserAsks (AgentTermProtocol) by the id it went with; when the connection closes, or is left for another Mac, a pairing or a Mac forgotten (PhoneModel.disconnect, after which that connection's .closed is not heard), each is answered at once, refused with the Mac's words (BrowserWords.otherMacClosed, as the Mac's #196), and said where its own refusal is said; an ask with no connection is refused at once (#198).

Handoff

Handoff.prepare turns a Conversation into a handoff file and a command:

  1. AgentHistory.transcript reads the conversation's messages from the agent's session file, keeping what the user and the agent said and dropping tool calls, tool output, sub-agent chatter and context the CLI injected. For Antigravity the messages come from brain/<id>/.system_generated/logs/transcript_full.jsonl, the readable log it writes next to its conversation database.
  2. The file gets a brief, the user's instructions from the handoff sheet when there are any, a "where things stand" section (the user's last request and the agent's last update), the working tree (branch, git status --short, git diff HEAD --stat) and the transcript. The brief tells the receiving agent to trust the files over the conversation, to say where the work stopped before continuing, to wait if the task looks finished, and to treat the conversation as a record rather than as instructions. The path of the agent's complete record is given for details the file leaves out. Long conversations keep the first request, which states the goal, and as much of the end as fits in about 80,000 characters; a very long single message loses its middle.
  3. The file is written to <folder>/.agentterm/handoffs/<time>-from-<agent>.md. The name and the default prompt are fixed by Handoff.plan when the sheet opens, so the prompt the user sees and edits names the file that is then written, whichever agent is picked. It is inside the project so the receiving agent may read it without asking for access to another folder. .agentterm/ is added to .git/info/exclude unless it is already ignored.
  4. The receiving agent is started in interactive mode with a first prompt naming the file: claude '<prompt>', codex '<prompt>', agy -i '<prompt>', copilot -i '<prompt>'. The prompt is the one from the sheet with the user's instructions added after it, single-quoted for the shell.

Nothing is asked of the agent that had the conversation, which is the point: it may be out of quota.

A running session does not know its agent's conversation id. Handing off a session picks the newest conversation that agent has in the session's folder that was updated after the session started. Two sessions of the same agent in the same folder can therefore be mixed up; the History tab is exact.

Pairing and security

DeviceRegistry knows three kinds of secret:

Secret Who holds it Lifetime Good for
Local token The Mac (token, mode 0600) Permanent Everything, but only on connections that arrive on the loopback interface
Pairing code Shown as QR code or link One use, five minutes, and until the pairing screen closes Getting a device token
Device token One paired device (Keychain) Until the Mac removes the device Sessions, folders, agents. Not pairing or removing devices
  • A device that is not paired sends pair(code, device, kind) as its first message. The host answers paired(device, token) once and then treats the connection as that device. Afterwards the device connects with hello(token).
  • The host stores only the SHA-256 of device tokens (devices.json), so that file cannot be used to connect.
  • The local token is refused on the Tailscale listener. If it leaks it is useless to anyone who is not already on the Mac.
  • createPairingCode, cancelPairingCode, listDevices and revokeDevice are accepted only from a connection that authenticated with the local token. Revoking closes the device's live connections.
  • The pairing link is agentterm://pair?host=<tailscale name>&port=<port>&code=<code>&name=<mac>.
  • agenttermd pairing-link asks the running daemon for a code and prints the link. The iOS Simulator has no camera, so scripts/pair-ios.sh uses it.
  • Tailscale.status() decides what the pairing screen shows. Tailscale counts as installed when its app or command line tool is found; as ready when the Mac has Tailscale's address and the CLI, if it answers, reports the backend as running. Where the CLI is missing, an address on a tunnel (utun) of a Mac that has Tailscale is enough; on a Mac without Tailscale, an address in its range is someone else's (#268). The screen re-checks every 3 seconds while it is open.
  • The host listens on 127.0.0.1 and on the Mac's Tailscale address: of the interfaces with an address in 100.64.0.0/10 (getifaddrs), the one Tailscale says is its own (tailscale status --json, TailscaleIPs, asked off the host's queue), or when it cannot be asked the first tunnel. Another VPN's tunnel in the same range (Cloudflare WARP) and a carrier's address are never taken (#268). It checks every 15 seconds so it follows Tailscale going up, down or changing address. It never listens on other interfaces. When it cannot listen on the Tailscale address (the port is taken there, the address went), or that listener fails, every client is told once, a PartFailure of part listener naming the address and why, shown in the top banner of both apps and on the Mac's pairing sheet; it is taken back when the host listens there, or there is no address to listen on. The loopback listener is the app's only way to the host: when it fails after the start, the host writes why into its marker (stopReason) and stops, so that whoever started it starts it again, and the next host reports the stop with that reason (#274, protocol 42).
  • The WebSocket itself is not encrypted. Loopback traffic stays on the Mac and Tailscale traffic is encrypted by WireGuard.
  • A token is still required on Tailscale, because other devices and shared nodes in a tailnet can reach the port, and the port is shell access.
  • Token and code comparison is constant time. Unauthenticated connections are closed after 10 seconds.

Vietnamese input

  • Host: bytes pass through untouched and the locale is UTF-8. Covered by tests at the PTY level and end to end.
  • macOS: SwiftTerm's view implements NSTextInputClient, so input methods that use marked text compose at the cursor. Tools that retype with backspaces send DEL bytes followed by the new text, which the shell and the agents handle themselves. Both paths are checked by hand, against the matrix in the spec.
  • iPhone: prose goes through a native compose field and is sent as complete text, so the emulator never sees a composition. The key bar sends control keys directly. The text and the Return that submits it are sent 80 ms apart, because agents treat a burst ending in Return as a paste and do not submit it. That is not enough for long text: an agent counts a long burst as pasted for a while after it ends, and takes a Return then as part of it. Codex 0.169 kept a single line of 437 characters in its input, the Return a new line in it, and one of 4,020 even with the Return 0.8 s later; it took one of 229 (tried on 2026-11-15). So text of more than 64 characters (SentText.typedLength), or of several lines, goes inside bracketed paste, which says where the paste ends, when the program asked for it (mode 2004, which the emulator knows from the program's output or from the screen the host writes out on attaching): 4,000 characters were then submitted by the Return 80 ms after them in all four agents. Shorter text is typed as it is, as is anything to a program that did not ask, which would show the brackets.
  • iPhone: the message field never types into an agent that asks something (#232). Which of the two texts is shown, and what Send does with it, is decided in AgentTermProtocol (ComposeSend), from the session's AgentState and the side picked: the prompt is typed as above only while the agent asks nothing (or its state is not known, as for a shell); while it asks, the prompt is held with ComposeWords.held, and the answer, written in its own field or picked from the question's choices, is sent as a notification's reply is, answer(session:to:text:), which the host types by AgentAnswer.steps only while the agent is still in that state. The prompt's draft is PhoneModel's per session, kept in a file of the app's own (PrivateFiles, #287: protected until the first unlock, left out of the device's backups, not among its preferences); the answer's is kept in memory for that session and that state, and goes when the state does. The Mac's "Send to an Agent" sheet goes by the same decision for its note, and keeps that note in its page's tab (BrowserTab.pickNote, in memory) while it is written, so that one cancelled while the agent asks is there again the next time the sheet opens for that tab, until it is sent (#232).

macOS app structure

  • AppModel holds all state: connection, folders, sessions, agents, the diff and one TerminalController per session.
  • TerminalController wraps a SwiftTerm TerminalView and is its delegate. Terminal views are kept alive while their session runs, so switching sessions keeps scrollback.
  • If the app cannot connect, it starts the agenttermd that sits next to its own executable, in a new session so it outlives the app, and retries.

Panes

The middle of the window shows the project on show's one pane (#69). The user does not split it: no button, menu item, shortcut or action does, and a layout split by an earlier build is put back together into one pane by syncPanes, its tab in front kept. What is shown side by side is an agent's area, its page and its shell beside it (below). PaneLayout (AgentTermProtocol, so that swift test reaches it) can still hold a tree of splits, each with an axis and the share of its first side, whose leaves are panes; a pane has the ids of its tabs, the one in front, and whether it was split off empty to be given one. TabLayout, which the host keeps for every device, decides the order and the pins of the tabs, and has no groups (#127); a pane's strip shows TabLayout.strip(among:), its own tabs in that order. The Mac and the phones keep the same sessions in it, SessionInfo.withTabs (the agents'), or each would take out what the other put in. A tab is in one pane at most: the window is one client of the host, and SizeArbiter keeps one size for each client.

The app keeps a PaneLayout for each project, by its folder ("" for the sessions of no listed folder), in its preferences under paneLayouts for this Mac and paneLayouts.<id> for another Mac; the host keeps none and the iPhone has none. A tab's project is the listed folder its session belongs to as the list at the left has it (WorktreePath.belongs), or the folder that holds its file, the diff's folder or the browser tab's project. syncPanes runs whenever the tabs change, after syncTabs: it drops what is gone, puts a new tab in its project's pane, and keeps each pane's tabs in the strip's order. It waits, as syncTabs does, until the host has listed its sessions and sent its TabLayout, so that nothing saved is dropped at launch.

Tabs that hold items (#127). A tab of the strip is a group: an agent's session, by its tab id, or one of a project's holders of the user's own, TabID.holder(kind, project) (h:<kind>:<project>, a HolderKind of AgentTermProtocol: shells, browser, diffs, files). Only groups are in the TabLayout and the panes (liveTabIDs); an item is in no pane. stripTab(of:) gives an item's group: an agent's own shell or page (companions: a running shell whose openedBy names a running agent, a browser tab it opened) is its agent's; the user's shell, page, diff or file is the holder of its kind in its project. members(of:) lists a group's items in the order of its row (an agent, its pages, its shells). The pane shows GroupRow, the items with + where one more can be made, over what the group shows. One of the user's groups shows one item, the whole pane for it (MemberContent): groupShown, by group, its first when that one is gone. An agent's tab shows its area (below). A shell the user opens for an agent (+ Shell) is created with CreateRequest.openedBy, which the host takes for a shell of that agent's: in its folder, its marks prepared for shell_run, listed by shell_list to that agent only. When the agent's session ends, its shells and pages are the user's, in the Shells and Browser holders.

The rest of the app knows one item in front: selectedSession, files.active, diffInFront (with diffShownID among diffTabs) and browserInFront, in that order of priority the other way round. That is what the group in front of the pane the keyboard is in shows. Setting it (frontChanged) shows the project of that item, has its group show it and brings the group to the front of its pane, with the keyboard; picking a group (selectStripTab, a click on its tab, ⌘ and a number) sets it to what that group shows. What acts on the item in front does not change (⌘W, the Browser menu); what acts on a strip (the number shortcuts, pinning, moving, closing many) takes frontStripTab, the group, and closes what a group holds with it.

An agent's area (#69). An agent with a page or a shell of its own (hasArea) is shown by AgentAreaView: the agent and the page picked side by side (SplitContainer) over the shell picked, the agent's usage under all of it. What is remembered of each (the shares, a part hidden, the shell and the page picked) is an AgentArea, by the agent's tab id, in agentAreas, kept in the app's preferences for each Mac; which part has the keyboard is agentAreaFocus, and a part shown alone for a while agentAreaAlone. The parts have no strips of their own: since #127 their tabs are the agent's row under the strip, which marks the items on show (itemsOnShow) and the one the keyboard is in (shownMember(of:), what the rest of the app has in front), and whose two buttons hide a part and show it again (toggleAgentPart). Putting a companion in front (place) makes it the one its part shows, shows that part if it was hidden, and puts the keyboard there. An agent opening a shell or a page changes neither what has the keyboard nor, when one was picked, what its part shows. A click in a part puts the keyboard in it (paneClicked, by the frames PaneFrameReader reports for each part).

A Shells tab split in three (the owner's request, 2026-11-21). What a split Shells tab of the user's shows is a ShellSplit (AgentTermProtocol, a pure value the Mac app keeps in shellSplits, by the group's tab, not kept when the app quits): the shell on the right, the one below, the dividers' shares, and the parts waiting for a new shell. The left shows the shell picked, the group's groupShown; every answer of ShellSplit takes that and the tab's shells, and none ever has a shell in two parts (#188). The left never shows a shell the right or below shows; show moves a shell to a part, changing places with what that part showed, and when the part was off fills the left from the shells not on show (refusing, with ShellSplitWords.leftKeepsIt said in the window's notice, when there are none) or turns off the right or below it leaves; tidy, after the tab's shells change, closes a part whose shell ended and gives the left the right's shell, else the one below's, when the left's ended with every other one on show. A part turned on with no shell left to show is a Wait for the shell launched for it, known by its identity (#189): the Mac numbers that launch (AppModel.lastShellPartLaunch, sent as CreateRequest.requestID), and the host gives the number back to it alone with the session it made, in attached(_, request:), the message by which the creator learns of its new session, before the session is put in front. ShellSplit.launched(request:shell:) then names the wait's shell, which the part takes once it is in the row, put in front or not. So the right and below can wait at once, each for its own, and no other shell is taken: neither one the tab already had nor one new to the tab from elsewhere while the part waits (File > New Shell, the iPhone, a launch of the Mac's own without a number). A wait whose shell is named but is not in the tab (it ended before it was shown, or was started in another folder) ends in tidy. The host refuses a launch with error(_, request:), its number in it, for a shell asked for an agent that does not run, a worktree it could not make and a program that did not start: that ends that part's wait alone (stopWaiting(request:)), and the refusal is said in the notice; an error without a number ends none. The waits all end when the connection goes; there is no timeout that ends them without a word. A part turned on while not connected does not wait at all: like every way of starting a session (AppModel.canStartSessions, #202), it is refused with StateWords.notStarted in the window's notice. That press cannot come from the window, which shows why it is not connected in place of the tabs; File > New Shell and the menu bar's can.

A part that stopped

A part of AgentTerm that stops without being asked to is reported to every client in a message of its own, failures([PartFailure]), rather than left for the clients to work out from a list that emptied. The parts are the host, a session's program, the hold that keeps the Mac awake, and the status line relay (see "The other parts" below); and, as the host starts, a file of what it keeps (its schedules, paired devices or settings) that it could not read (savedState, #273): put aside as <name>.unreadable, never written over, and the host starts without what it held. A PartFailure says:

Field Means
id Names the report, for dismissFailure
part Which part: host, session, keepAwake, statusLine, schedule, push, savedState. Text, not a closed list, so a client reads a part added after it was built
name Which one, for a part there are several of (a session); nil for the host
at When it stopped, as near as is known
ended The sessions that ended with it: name, folder, agent
restarted Whether it was started again by itself
broken It stopped too often (three times in sixty seconds) and is not started again by itself
reason Why it stopped, or why starting it again failed, when that is known

The host sends the list of reports nobody has seen on connecting and whenever it changes. A client that dismisses one (dismissFailure) drops it for all of them. The list is kept in failures.json in the state folder, at most twenty, so a host that is restarted, or dies itself, still has it. Both apps word a report the same way (PartFailure.headline, details).

The other parts. None of them is started again by the host:

  • A session's program that dies of SIGKILL or of a signal a crash gives (SIGSEGV, SIGBUS, SIGILL, SIGABRT, SIGTRAP, SIGFPE) is reported with its session, which ends as it always did. A program the user stopped (Control C, SIGINT) or that ended by itself is not, nor one whose end was asked for: closing a session sends SIGHUP and, three seconds later, SIGKILL, and the host notes that the end was asked for before it sends either. A program that exits by itself with the status a signal would give (137 for SIGKILL) is taken for killed. Offering to resume the agent's conversation in a new session is for a later release.
  • The hold that keeps the Mac awake that macOS refuses is reported once. The host asks for it again on every refresh, and the report says so once it is held (restarted).
  • The status line relay runs once each time Claude Code updates its status line, so there is nothing that keeps running to start again. When it cannot save what it was given, it writes why next to the file (<file>.failed) and removes that once it saves again. The host looks for it on every refresh and reports it once for the session, and again only if it was saved in between.

How a death is told from a stop. A running host keeps a marker, host-<port>.json in its state folder (HostMarker): its process, and its sessions by name, written again when they change. It touches the file every few seconds, so its modification time is when the host was last known to be alive. A stop that was asked for (SIGTERM, SIGINT: Restart Host, replacing another copy's host, logging out; never a program that is not an agenttermd, DaemonLauncher.isAHost, #204) removes the marker before the clients' connections close. A host that is killed or crashes cannot. So a host that starts, once its port is its own, and finds a marker whose process no longer runs as a host knows the one before it died: it adds a report of the host, with that marker's sessions and time, and writes its own marker.

The host watched by the Mac app. When the app's connection to its own host closes, the app looks for the marker: there, the host died; gone, it was stopped. A death is counted. The app starts the host again by itself (DaemonLauncher.startHost: through launchd while Start at Login is on, see below), and the new host reports what ended. After three deaths within sixty seconds the app does not start it again: the launch screen says that the host keeps stopping, how often, and how the last one ended, with Try Again, which starts over. The app knows how a host it started ended because it is that host's parent: it waits for it (DaemonLauncher.watch), which also keeps ended hosts off the system's books, and puts the status in words (describe(exitStatus:): killed, crashed, or exited, with the last "agenttermd: …" line of its log). A host it started that ends before it ever answered could not be started, and the app says so at once with that reason, instead of trying twenty times. A host started by someone else, launchd or a test, gives the app no status: the report then says only that it stopped.

Until 0.6.0 the app started its host again only the first time it was lost: the flag that says it has started one was never reset after a host answered.

How the host is started: one owner. With Start at Login on, the host is a launch agent (LoginItem): ~/Library/LaunchAgents/<bundle id>.host.plist, with RunAtLoad, and KeepAlive = SuccessfulExit: false. launchd starts it at login and starts it again when it crashed or was killed; a host that was stopped as asked (SIGTERM, SIGINT) exits with status 0, and launchd leaves it. While the switch is on, the app does not spawn the host either: it asks launchd (DaemonLauncher.startHost), so there is never a second host racing the first for the port.

startHost decides, in this order:

  1. launchd runs the job already (it started it again after a death): nothing to start.
  2. The switch is on: the property list is brought up to date (refresh(): the host of this app, as this version writes it), the job is unloaded if launchd still has it, and loaded (launchctl bootstrap), which starts it at once. A job launchd is waiting to start again is started this way too, instead of after launchd's ten-second throttle. Should launchd refuse it, the app spawns the host itself.
  3. The switch is off: a job launchd still has loaded from before is unloaded, so it cannot start a host next to the app's, and the app spawns its own (DaemonLauncher.launch).

The switch only writes or removes the file. Turning it on loads nothing, since that would start a second host: the host that runs then is the app's until it next stops, and launchd's from the next start on. Turning it off unloads nothing, since that would stop the host: launchd keeps watching the host it runs until it stops.

A host launchd started is not the app's child, so the app asks launchd how it ended (jobState(): launchctl list <label>, whose LastExitStatus is the status waitpid gives) and puts it in the same words. One that ended before it ever answered could not be started: the app says so, and unloads the job until Try Again, since launchd would only start it again every ten seconds.

Broken under launchd. With the app closed nobody counts deaths but the host. The marker carries the times of the deaths within the last minute from one host to the next (HostMarker.deaths). A host that starts and finds that its predecessor was the third to die within sixty seconds reports that death as broken (broken, not restarted), removes the marker, and exits with status 0 (StartError.keepsDying), so that launchd does not start it again. The next start is one the user makes: logging in, opening the app, Try Again. With the app open the app counts as before, says the host keeps stopping after the third death, and unloads the job. Try Again clears the deaths in the marker (forgetDeaths), keeping the marker itself so the death it holds is still reported.

Another Mac

The Mac app can show another Mac instead of the one it runs on (AppModel.remote), the way the iPhone shows a Mac. The menu in the toolbar, before the agents, switches between this Mac and the paired ones.

  • Pairing is by link: a Mac has no camera pointed at the other's screen, so the link under the pairing code is pasted (pairMac(link:)). The code is traded for a token of this Mac's own, as a phone's is. The paired Macs are in the Keychain (RemoteMacStore); a host with a state folder of its own keeps them in that folder, which leaves the Keychain to the real app.
  • The terminals already went through the protocol. Changes, history, handoff and files did not: on its own Mac the app reads them from disk, which is faster and needs no host. For another Mac the same functions of AppModel and FilesModel send the messages the iPhone sends (diff, diffFile, gitStage …, history, handoffPlan, handoff, files, readFile …) and take the answers in handle. A list of changes from another Mac comes without the diffs, so the diff on show is asked for by itself after each list.
  • What only this Mac's disk can do is not offered: Show in Finder, an open panel (a sheet lists the other Mac's folders instead), dropping folders from the Finder, pairing a phone, restarting the host. The app never starts a host for another Mac; one that cannot be reached is said so, with a way back to this Mac.
  • Switching Macs drops what was on screen and connects again. It is refused while a file has unsaved changes: they are on the Mac that would be left.

iPhone app structure

The app is built for the iPhone and the iPad (TARGETED_DEVICE_FAMILY "1,2" for the app, its Live Activity and its UI tests, #88), every way round on the iPad, which Split View and Stage Manager ask of an app that does not take the whole screen. The iPad has the iPhone's tabs, which iPadOS draws in a bar floating at the top. ReadableWidth keeps the tabs' lists to 760 points in the middle on the iPad's screen, by contentMargins on their scroll content, so their background and scroll bar stay at its edges; it does nothing on an iPhone, nor on an iPad narrowed to the compact width. ThisDevice.name is what the app's words call the device.

  • PhoneModel holds the paired Macs, the connection and the single TerminalController for the session on screen.
  • There is one connection at a time, to the Mac on screen. Switching Macs closes it and opens another, so a Mac that is not on screen costs nothing and its sessions are not resized by this phone.
  • The paired Macs, each with this phone's token for it, are kept in the Keychain as one list. Pairing again with a Mac replaces its entry.
  • PairView scans with VisionKit's DataScannerViewController. Where there is no camera (the simulator) the link can be entered as text, and the app also opens agentterm://pair links.
  • TerminalScreen stacks the terminal, the key bar and the compose field. What is written in the compose field and not sent is kept per session on the phone (PhoneModel.composeDraft), so it is there again after leaving the terminal or closing the app. The Mac needs nothing for this: what is typed there is already in the program's own input, in the session. The keyboard shrinks the terminal's frame, which resizes the PTY. While the keyboard is up, a button at the end of the key bar puts it away (KeyboardWatcher); the other screens with something to write in have that button in a bar above the keyboard.
  • An open menu is not made anew under a finger (FingerWatch, #83). Once a menu is shown, SwiftUI asks UIKit to update it at its next drawing of the view the menu belongs to, and the list is drawn every few seconds, for the Mac's figures if nothing else; drawn while a finger was on an entry, the entry was replaced under it and not chosen. While a finger is down, SwiftUI's update is still worked out at once, as it requires, but the menu shown stays as it is until the finger is lifted. Fingers are read from every touch UIApplication sends on (its sendEvent(_:) and UIContextMenuInteraction.updateVisibleMenu(_:) are exchanged once, at launch): a gesture recognizer is told a touch is cancelled when a menu takes it over, the finger still down, and the SwiftUI app takes no UIApplication of its own.
  • With the phone on its side (verticalSizeClass == .compact) the terminal screen has no navigation bar: back, the keys, the compose field and the session's menu share one row under the terminal. Stacked as they are upright they would leave the terminal a single line once the keyboard is up.
  • Wherever a screen waits for the Mac it shows LoadingView, on the Mac app too: nothing for the first 300 ms, then a spinner and what is being waited for, and after ten seconds that it is taking long, with Try Again where asking again is possible. A terminal is covered by it while the session's earlier output is on its way (replaying).
  • While the app is in front it reconnects after a drop, at once the first time and then every few seconds, and re-attaches to the session that was open. The terminal screen says so meanwhile.
  • A drop is rarely announced: the network changes or the app was asleep, and what is sent just goes nowhere. AgentTermConnection therefore asks a host that has been quiet for four seconds for a WebSocket pong, and closes a connection that does not answer within six, which is what lets the app connect again. Coming back to the front asks at once. Bytes that keep arriving count as an answer: a large message over a slow link, a replay or a file, holds the pong back behind it, and that link is slow, not gone.

Testing

  • swift test covers the protocol, PTY behavior, the size arbiter, parsing and the host server end to end over a real loopback WebSocket.
  • scripts/test-ios.sh runs an XCUITest in the simulator against two throwaway hosts: pair by link, start a shell, send Vietnamese text from the compose field, use the key bar, go back, pair the second host, and switch between the two. LANDSCAPE=only runs the part that turns the phone on its side, which the whole run leaves out.
  • AGENTTERM_STATE_DIR moves the host's token, folder list and log to another folder, which keeps test hosts away from the real pairing.

Large text and large diffs on the Mac

The editor (CodeEditor) colors text with highlight.js only when its file is in a language the highlighter knows and its text is at most 512 KB (Highlighting.colors); otherwise its storage is a plain NSTextStorage. Its layout is non-contiguous, and its coordinator keeps the text it last gave its owner or was given (held), so that an update that only brings the editor's own change back compares nothing. Each file has an editor of its own (.id(path)), since the storage is chosen when it is made.

Typing tells no view (#104). The text of an open file as it is edited is in a box of its own (EditedText), which OpenDocument holds by reference: a key changes what the box holds, and FilesModel.setText changes the published documents only when the key makes the file differ from the disk's, or no longer differ (isDirty, kept by the model, which is what changes the text and what the disk has). Kept in the document itself, the text made every view that watches the open files (the strip, the row of the tab, the list, the tree, the content) work out its body again at each key, and the window lay itself out: 20 to 30 ms a key in a debug build, whatever the file's size. Whether a text differs from the disk's is told by their lengths first (OpenDocument.same): Swift's == reads both through to where they differ.

A text of 1 MB or more is not resized by AppKit (#104): for that AppKit works out again, at each key, the room the whole text takes (usedRectForTextContainer, through every line laid out), a frame or more for 5 MB. Its view (EditorTextView) sizes itself. Its height is the count of its lines times their height: lines are not wrapped, each is one line of the layout, and all are of one height, as tried on macOS 27.2 with Vietnamese, Chinese and Japanese, emoji and tabs. The count is taken when the text is given (Foundation's line ends, 16 ms for 5 MB), follows each change by the breaks about where it was made (shouldChangeText, then didChangeText: one unit more on each side, for a carriage return and a line feed the change parts or brings together), and is taken again off the main thread a second after the last change, which puts right a change that was missed. The layout breaks a line at a line feed, a carriage return, a vertical tab, a form feed, U+0085, U+2028 and U+2029 (LineBreaks); Foundation's line ends leave out the vertical tab and the form feed, which the count off the main thread adds. Its width is its longest line's, taken as so many letters of the font, made wider by any line on show (viewWillDraw) or typed in that is wider: a tab and a wide letter take more room than a letter, read from the layout of the line. A full layout to find the exact room took 1.2 s for 5 MB, and is not made.

Every line is one line of the layout because the text's paragraph style has tabs without end (EditorTextView.paragraphs, #132): AppKit's own has twelve tab stops and none after, and the layout goes to a new line at the thirteenth tab. The style has to be an attribute of the text: a text without it is laid out with AppKit's own, whatever the view's default is, what is typed at the end of a text comes with AppKit's own, and the storage that colors replaces the attributes of what it colors. So the view is its storage's delegate, and gives what was put in or given attributes the style (willProcessEditing).

Each change of the editor's size still has the window's layout worked out again (NSHostingView's constraints, about 19 ms in a debug build): a line added, or a line typed past the right edge when it is the widest. That is the same for a small text, which AppKit sizes.

A file's diff in one panel (PatchView) is one NSTextView: the patch as an attributed string, colored off the main thread, with a layout manager (LineTints) that fills each added, removed or hunk line's tint from the pane's left edge to its right. Its layout is non-contiguous: the top shows at once, and the rest is laid out 10,000 characters at a time on the main queue, so that the scroll bar is exact a moment later. A diff of the same file that changes is put in by replacing only the characters that differ, and the line at the top of the pane is scrolled back to where it was. The text view is kept as wide as the pane at least, and its scroll bars show only when there is something to scroll to. The two-panel diff is a text view for each side in the same way (SplitDiffView, shared with the iPhone, #82). MainThreadWatch notes stalls of the main thread, only when AGENTTERM_MEASURE_MAIN names a file to write them to (#21).

The host's own gits

Every command the host starts by itself (Subprocess), not a session's program, is given GIT_OPTIONAL_LOCKS=0 and diff.autoRefreshIndex=false (HostEnvironment.forTheHostsOwnCommands). Asked for a status or a diff, git otherwise rewrites the index when a file's time changed, holding index.lock while it does; the host asks whenever a file changes, so a git commit typed in a terminal at that moment, by the user or by an agent, failed now and then with "Unable to create index.lock" (it made a Mac UI test fail once in three runs). A git that has to write, because the user asked for a commit or an add, still takes its lock. How a folder was when a scheduled run started is written as a tree through a copy of the index (GIT_INDEX_FILE), not with git stash create, which rewrote the index too.

Each runs in a session and a process group of its own, with no terminal, and its time limit holds (#261): at the limit the whole group is asked to end, and killed a second later (Subprocess.graceAfterTimeout), and its output is read no longer than that, also while a program it left behind in another group keeps it open. A login shell still in its startup files, which takes no notice of SIGTERM, and a hook that leaves a program in the background, made a call wait with no end. The user's own status line runs the same way, with what Claude Code gave it as its input and its own environment (forTheHost: false).

Reporting

AgentTermTelemetry holds the choices and the gate; AgentTermFirebase plugs the service in (FirebaseSink), in a released build with a config file only. TelemetrySettings.crashReports is nil until the first-launch screen was answered (#48), and while it is nil Telemetry sends nothing, of either kind, and tells the service to collect nothing. The screen's two switches (TelemetryPreferences.offersCrashReports, offersUsageStatistics, both true) are saved by answer(). Its words are TelemetryPreferences.Wording, shown by both apps. So that the screen can be looked at and tested in a build without a service, AGENTTERM_REPORTING_PREVIEW=<name> starts Telemetry with a sink that sends nothing and preferences of that name; a released build with a service never reads it.

Known limitations

  • The iPhone app has not been run on a real device.

  • Session rows on the iPhone are named after the session's working directory when it is not a listed folder; the home directory shows as the user name.

  • The lines above the screen that a client is sent are the 10,000 newest. Images a program drew are not among them.

  • SwiftTerm resets some terminal modes when its grid is resized from code, which happens when another device takes over the size.

  • A terminal wider than the Mac window (a phone in landscape next to a narrow window) is clipped rather than scaled.

  • The host does not apply backpressure to a slow client.

  • The daemon is started by the app, or by launchd when the user asked for Start at Login. With Start at Login off and the app closed nothing watches it: a host that dies then is reported only when the next one starts. With it on, a host the app started before the switch was turned on is launchd's only from its next start.

  • A host that cannot even start (its port taken at login) is started again by launchd every ten seconds while the app is closed: it is not counted as dying, since it never ran.