The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
CLAUDE.md
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
What this is
Harness Desktop — a Flutter app that lists Harness machines and attaches xterm terminals to the
agents running on them. macOS and Linux (Ubuntu) are both real, released targets — first-run
provisioning (lib/bootstrap/environment_provisioner.dart), self-update
(lib/update/desktop_updater.dart), and packaging (scripts/upload-desktop.sh /
scripts/upload-desktop-linux.sh, see RELEASE.md) all branch per-OS internally rather than being
separate code paths.
Windows is a local desktop too, not a viewer (lib/core/viewer_mode.dart): homeDir()
(lib/core/home_dir.dart) reads USERPROFILE there even when Git Bash set HOME, console
children start through lib/core/hidden_process.dart so no window flashes, and the executable is
harness-desktop.exe (the CLI owns harness.exe). .github/workflows/windows-desktop.yml builds
and runs the whole suite on x64 and arm64 against test/windows_known_failures.txt. Self-update
adds a version folder beside the running one and relaunches through Harness.exe
(lib/update/windows_update_swap.dart).
Package name is harness
(import 'package:harness/...'). It lives under desktop/ in the autonomous-harness repo, beside
the CLI (../cli) and the backend (../backend); a few comments still point at autonomous-code,
the older backend checkout, which is a sibling of this repo rather than part of it.
Grid was removed on 2026-09-11, when the project was killed: no lib/grid/, no lib/share/, no
Settings ▸ Providers or Share Intelligence, no provider pill, model picker, node dashboard or
usage-limit card, and first-run setup no longer installs the Grid CLI. The last commit that still
has all of it is the archive/grid branch — bring anything back from there rather than rewriting
it from memory. The harness CLI (autonomous-harness) still carries its own grid code
(gridLaunch.ts, gridWebMcp.ts, agent_retarget, harness grid login); nothing here calls it.
Toolchain and commands
Choose and time-bound validation using the repository's validation and release guide. The full-suite command below is available for broad changes and suite maintenance; it is not an extra mandatory run after affected checks and equivalent CI have already passed.
pubspec.yaml pins sdk: ^3.13.0, i.e. Flutter ≥ 3.47 / Dart ≥ 3.13. An older Flutter fails at
flutter pub get ("version solving failed") and every command below fails with it — check
flutter --version first.
The macOS project is migrated to Swift Package Manager (macos/Runner.xcodeproj references
FlutterGeneratedPluginSwiftPackage). Run flutter config --enable-swift-package-manager once, then
flutter pub get — the generated macos/Flutter/ephemeral/Packages/FlutterGeneratedPluginSwiftPackage/Package.swift
only lists the plugin dependencies when SPM is on at pub get time. With SPM off, flutter run falls
back to CocoaPods and rewrites tracked files (project.pbxproj, contents.xcworkspacedata, the
Flutter-*.xcconfigs) and adds macos/Podfile; revert those rather than committing them.
flutter pub get
flutter analyze # lints: package:flutter_lints, no custom rules
make -C .. desktop-test # bounded VM suite, workers + receipt
flutter test test/terminal_session_test.dart # one file
flutter test test/ws_conn_test.dart --plain-name "reconnects" # one test by name substring
flutter run -d macos # or: flutter run -d linux
bash scripts/build-macos-debug.sh # pins the host's release renderer
flutter build macos --release
flutter build linux --release # Ubuntu build host only — no cross-compiling
flutter build windows --release # Windows host only
Windows pipe unit tests need the native bridge built first (flutter build windows --release).
In PowerShell, set $env:HARNESS_DESKTOP_PIPE_IO_DLL = (Resolve-Path 'build/windows/<arch>/runner/Release/harness_pipe_io.dll').Path before flutter test --no-pub
(<arch> is x64 or arm64). Unit tests run in the SDK's flutter_tester, outside the app bundle.
For flutter run and native integration, remove that override: each app build loads the DLL beside
its executable, including Debug. The Windows workflow checks both paths.
Native integration fixtures need a device and the test-mode environment:
FLUTTER_TEST=1 flutter test -d macos --no-pub integration_test/native_terminal_e2e_test.dart
FLUTTER_TEST=1 flutter test -d macos --no-pub integration_test/native_workspace_e2e_test.dart
integration_test/flutter_test_config.dart installs the production accessibility guard before
Flutter's launcher initializes its binding. A fixture launched directly for manual review must
call ensureNativeTestBinding() too; an unguarded fixture can reproduce the engine's known
disconnected-semantics crash even though the normal app already protects that boundary.
Pin macOS-only cases with TargetPlatformVariant({TargetPlatform.macOS}): Flutter's debug
FLUTTER_TEST default is Android, which bypasses desktop-specific behavior. Native accessibility
review must also exercise activation after the framework tree exists; retaining a test semantics
handle while AppKit reconnects requires replaying the complete tree and custom actions.
integration_test/sign_in_native_test.dart walks a new computer from the tour to the sign-in page
and on to the workspace, in the real window. AppKit draws the tab row, so no Flutter test can see
or press it: run python3 tool/native_driver.py <dir> <shots> & beside it and pass
HARNESS_NATIVE_DRIVER_DIR=<dir> HARNESS_NATIVE_SHOTS_DIR=<shots>, and the driver reads and
presses the real title-bar controls through accessibility and photographs that one window (the
terminal needs Accessibility and Screen Recording). Without it, or with the screen locked, the
same presses arrive as the row's channel actions. ⚠️ The row is in the window only after
invokeMethod('configure') on harness/swarm_tabs, as configureDesktopWindow does at launch; a
native test that skips it has a plain title bar.
Both use in-memory state and fake terminal traffic; the workspace fixture also simulates agent
creation and machine-link responses. They refuse to run without FLUTTER_TEST=1, which disables
production-only pollers and persistence. The workspace fixture exercises the native macOS titlebar; its injected
Flutter keys do not establish physical AppKit keyboard/IME behavior. A fixture build replaces
Harness.app, so rebuild the normal review artifact afterward with
bash scripts/build-macos-debug.sh --no-pub --target lib/main.dart.
Local macOS renderer: Intel review builds need Skia, just like the Intel release.
Plain flutter build macos --debug leaves Impeller enabled and can produce invisible
bitmap artwork on Intel. The script above pins the built bundle's renderer and re-signs
it so Finder launches work too; Apple Silicon keeps Impeller. For flutter run and
native integration tests on Intel, add --no-enable-impeller. Check companion artwork
on the real renderer with integration_test/companion_art_native_test.dart; headless
image tests alone do not catch this failure.
Local stack / E2E scripts (the CLI comes from this repo's ../cli; the backend from a sibling
autonomous-code checkout next to autonomous-harness — override with AUTONOMOUS_CODE_ROOT /
HARNESS_REPO_ROOT; see README):
make terminal-local-manual # boots backend+CLI locally and runs lib/main_local_manual.dart
make terminal-local-e2e
make terminal-prod-e2e # opt-in, refuses without PROD_TERMINAL_E2E=1 + release evidence vars
Release (make release-desktop from the repo root, which tags vX.Y.Z_desktop and lets CI build; make upload-desktop VERSION=… and
make upload-desktop-linux are the by-hand escape hatches, the latter on an Ubuntu host only) is
documented in RELEASE.md. macOS ships TWO builds of one universal app, differing only in
FLTEnableImpeller: Intel on Skia under the old desktop-macos key (which every older install and the
website download also read), Apple Silicon on Impeller under desktop-macos-arm64, both built by
scripts/publish-macos-variant.sh — RELEASE.md, "Two macOS builds", has the why. An internal
build for testers — both macOS builds, signed and notarized by CI, behind an unlisted link, with
self-update off — is git push origin HEAD:internal/<name> (../.github/workflows/desktop-internal-build.yml,
RELEASE.md "Internal builds"); never cut one by hand. The run prints the links, and this repository
is public, run pages included — so they are unlisted, not private. All platforms
publish to the same GCS metadata.json under different keys and share one version
number by default; pubspec.yaml's version: is a placeholder and is never bumped — Linux instead
gets a version.txt written into the built bundle at package time (see lib/core/app_version.dart,
since flutter build linux has no Info.plist-style stamping). Test the updater against a scratch
manifest with --dart-define=DESKTOP_UPDATE_METADATA_URL=...; HARNESS_RUNTIME_METADATA_URL does
the same for the desktop updater only. The managed Node runtime is still published from this repo with
make upload-node-runtime ARGS=22.23.2 (darwin-arm64, darwin-x64, linux-x64, linux-arm64) — and,
since 2026-09-15, a managed tmux for macOS the same way (release-tmux-runtime.yml /
make upload-tmux-runtime, RELEASE.md "Managed tmux runtime") — but
its consumer is now the harness installer rather than this app.
Architecture
One Flutter UI, native and browser transports
lib/main.dart serves both targets; its signed-in workspace is a conditional import
(desktop_workspace.dart, or web/web_entry.dart when dart.library.js_interop), so the
web build is mouse-first (product decision, 2026-09-29): every action
desktop keeps in native menus or chords must be clickable. Keys keep working but are not
advertised. Browser-only UI lives in lib/web/ and is never imported by desktop code;
it plugs into shared screens through additive seams whose default is today's desktop
behavior (e.g. SwarmScreen.chrome / WorkspaceChrome in state/workspace_chrome.dart,
which runs the same _commands table keys use, gives the picker a clickable Back, and turns off
KeyHints — widgets/key_hints.dart, absent means hints shown). Below
WorkspaceChrome.compactBelow (web: 720px, a phone) the workspace goes compact: a tab
switcher replaces the tab row, WorkspaceChrome.compactFooter replaces the status bar with one
dropdown, Download app, and Share when it is on (hidden while the on-screen keyboard is up), and PaneGrid.soloFocused draws only the focused harness —
without touching zoom or the synced layout, so the same desk keeps its grid on a computer. Solo still records the desk's
arrangement (Swarm.arranged), because that is what a split divides: without it the menu's Split pane could never run on a phone. Do not change desktop behavior for the
web, and do not copy shared screens into lib/web/ — add a seam instead.
A browser downloads the app in parts (lib/web/parts/, DeferredPart/DeferredPartView): the
signed-in workspace (web_entry.dart → workspace_part.dart, fetched once the first frame is up, so a
first visit's sign-in page skips its 4.4 MB), the Finder and its editor (pane_grid.dart), and the chat's
text viewer (attachment_chips.dart). Shared code reaches the last two through a compile-time import
switch (if (dart.library.js_interop), as main.dart picks the web entry), so a computer compiles the
same files as ever (test/pane_grid_finder_test.dart). Importing one of these libraries directly from
shared code puts it back in main.dart.js. Check a real build with tool/web_ux/deferred-parts.mjs.
A browser on a phone or tablet (iOS, Android by defaultTargetPlatform, whatever the window's width) gets a bar over
every screen, sign-in and shared harnesses included, sending it to the Harness app in its store
(web/shell/web_store_banner.dart). It is the app's frame — startHarness(frame:), which main.dart takes from the
same conditional import as the workspace; native builds pass the app through. Closing it is remembered on that
origin, and the on-screen keyboard hides it. It sits above the Navigator, so nothing in it may need an Overlay (no
tooltips), and it keeps one tree shape shown or not so the app below is never remounted.
kViewerMode is true on the web:
the browser owns its OAuth session, peer links, and end-to-end relay encryption.
viewer/browser_login.dart validates the same-tab callback against the backend's
PKCE transaction; conditional adapters handle storage and native-only services.
platform_auth_web.dart serializes shared login/refresh/logout with Web Locks
and reloads other tabs when the account changes. Auth and E2EE keys persist in
origin-local storage; only the OAuth transaction is in session storage.
Each relay connection also negotiates a WebRTC data channel to the machine
(web/p2p/, the phone's ../mobile/lib/p2p on the browser's own
RTCPeerConnection — no flutter_webrtc, so native builds gain no plugin);
terminal frames take it when it is up and fall back to the relay. Those files,
the transport interface and the E2EE session began as copies of the phone's
(mobile stays a standalone package). test/p2p/mobile_parity_test.dart still
holds two of them to the phone's — the link (web/p2p/terminal_p2p_link.dart)
and the transport interface (ws/terminal_transport_plugin.dart) — and fails
until a change is carried to both. The P2P plugin and policy, the relay codec
and the E2EE session differ on purpose since 2026-10-14: the phone starts its
channel on the first terminal with no open wait, redials a dropped one within
seconds, and works the hello, the welcome and large frames on a background
isolate; the browser keeps its own copies, so a fix to one of them is carried
across by hand. The browser's E2EE is pure Dart on the UI thread,
and that is fine: sealing plus opening a 4 KiB frame measured 316 µs under
dart2js -O4, 282 µs on the Dart VM and 479 µs as -O4 WASM (Node 24,
2026-10-06) — flutter test --platform chrome compiles unoptimized and reads
~40× slower, so do not judge it there. WASM is not worth adopting for speed.
System notifications in a browser use its Notification API
(web/notify/browser_system_notifier.dart, picked by notify/browser_notifier.dart):
the same Settings switch, one per agent by tag, a click focuses the tab and
opens the agent. A phone's browser cannot construct one (service workers only),
which reads as unavailable.
Shared sessions use ObserverRelayCodec and /api/observer-ws, verifying the
owner and permitting only observation and authenticated comments. /s/:id#key=…
opens SharedAgentPage without restoring the visitor's workspace. Public links
allow anonymous viewing; private links require an invited account. Preserve the
fragment identity pin through sign-in and reload: startHarness disables Flutter
hash routing, while the sign-in adapter owns the callback and return URL.
The owner daemon stores comments and enforces link/invitation access on every
request. Reuse ShareHarnessDialog and HarnessComments for both app targets.
See README.md for origin setup, browser storage
lifetime, capability limits, and Chrome checks. Browser tests must set
--dart-define=HARNESS_TEST=true so no production pollers run.
Native desktop talks to the local harness CLI
The native desktop target uses the CLI for cloud access and SSO tokens:
- Auth lives in the CLI.
lib/auth/cli_login.dartshells out toharness auth status --jsonand drivesharness login --json(NDJSON event stream);cli_link.dartwrapsharness link create/import/list. The login screen's way in is two buttons, Continue with Google and Continue with Apple (widgets/sign_in_provider_button.dart), on desktop and web alike:AppNotifier.login(provider)hands aSignInProviderto the sign-in client —--google/--appleto the CLI,providerto the backend's authorize routes in a viewer build — and auth-service opens that account's own sign-in. A caller with no button of its own (login()with none) still gets the page's chooser. Each surface signs in as its own auth-service client (backendSSO_CLIENT_IDS): the CLI asharness-cli, orharness-desktopwhen this app runs it (--entry-point=desktop); a viewer build asauth/sso_client.dartsays (harness-webin the browser). ⚠️ A token belongs to the client it was issued to, so the session keeps the client the backend's exchange REPORTS — never the one it asked for, since an older backend exchanges as its configured client and names none — and every refresh names it again (AuthSession.ssoClientId, the CLI'ssession.json). Desktop requires sign-in after setup and before opening the workspace (widgets/sign_in_step.dart,AppNotifier.signInStepShowing; design../docs/research/2026-10-08-onboarding-redesign/index.html1b, owner 2026-10-12). The tour has five slides: machines, agents, persistent sessions, phone and device; the ⌘P and ⌘N slides are removed. The sign-in page keeps its four benefits and standalone Google and Apple buttons, with Continue with email centered underneath; there is no surrounding card or Skip. It applies to existing signed-out installations and relaunches after setup too. A successful explicit sign-out brings it back. A signed-in offline launch opens normally. A server-rejected session requires sign-in again; saved local work and running harnesses survive behind the page. A temporary network outage keeps an already signed-in workspace available. Agent downloads still run during setup; first arrival waits for an account and opens one recent usable conversation, or one configured agent with an editable, unsent starter task. A person with no configured agent gets OpenCode alone. Failed opening offers explicit recovery; it never starts again in a later empty tab. An uncertain start keeps its receipt and checks status. The first-run draft also uses the local pane's composer; it is never sent into an installing agent's terminal automatically. Other agents and tabs remain available through the usual controls. The page does not change while the browser is open: the same option reopens its page, and another option cancels and switches. Failures and cancellation keep the required page visible. The workspace account menu iswidgets/account_menu.dart(design/workspace-status-bar.md). Every native sign-in entry uses this same page; the old fleet-map card and desktop phone-scanning choice are removed. Sign-out owns its CLI process, checks its exit, and terminates it on timeout.AppNotifierjoins repeated sign-out requests and blocks another sign-in until credential and connection cleanup finish; failure offers keyboard-focused Retry sign out. Development fixture disconnects never sign out the real CLI. Viewer builds useviewer/direct_login.dartandviewer/direct_auth.dartinstead: login attempts and token refreshes have session revisions, credential writes are serialized, and cancelled or superseded responses cannot restore or clear another account. Sign-out and runtime expiry clear live panes, inventory, and history without saving an empty layout over the user's desk. Sign-in waits for old transports to close, then restores the saved tabs, focus, pins, zoom, and layouts. Every layout read checks both account and layout revisions. - REST (
lib/api/api_client.dart, Dio) goes toAppConfig.localCliBaseUrl(http://127.0.0.1:18473), and the CLI proxies to the backend with its own session. Responses are{success, data|error}and unwrapped intoApiException. Machine responses carry their own cache freshness (MachineInventory). Sharing fallback is cleared on account changes; only the latest request can publish inventory or clear its error.refreshMachines()returns whether its result was applied, and retry uses that public path.machineInventoryLoadeddistinguishes an initial wait from a completed inventory with no row for a restored pane. Missing, cached, and failed inventories give distinct recovery guidance; Retry stays mounted and joins any pending retry, preserving its keyboard focus and position. Agent discovery and terminal capabilities also belong to a machine's current connection revision. Disconnect/reconnect releases obsolete discovery and recovery futures immediately; late replies and timeouts cannot overwrite the replacement connection. Reconnect releases old terminal stream IDs while retaining their renderer and output until the new keyframe arrives. - WebSocket (
lib/ws/) —WsPoolowns oneWsConnper machine. Every real connection usesWsTransportKind.localPlaintextagainst the CLI daemon's loopback WS (discovered/started byLocalCliDiscovery, which runsharness startwhen needed). The CLI terminates E2EE for relayed machines; the app carries no crypto. Close code4404/NO_PEER_LINKmeans the machine needsharness link import— surfaced asMachineState.needsLinkand polled via_linkRetryTimers. Native link retries wait 5, 10, 20, then 30 seconds between probes, and never close an active connection or password-link handshake. Explicit Connect is immediate; repeated clicks join it. The initial unlinked refusal is measured once; later automatic probes are suppressed until the machine is linked. A browser's link retry backs off the same way (it redialled every 5 s, each refusal reading the device list again). While a machine waits for a link, machine-list reads neither dial nor load it, and only a forced load asks it (a person's reload, a status change); connecting after a link loads its agents (test/unlinked_machine_load_test.dart). A released web build prints nodebugPrinttraces (web/web_console.dart): framework errors and uncaught errors still reach the console, and?debug=tracesbrings the traces back for that browser until?debug=off. A viewer build settles its ownNO_PEER_LINK/E2E_DENIEDfirst (_settleTrust): it joins the device log if it is not in it (ViewerDeviceLog.ensureRegistered), reads it and dials again, showing the machine as connecting; only a refusal that outlasts two rounds (~15s), or a frozen log, asks for the password. The desk frames (app_focus,app_panes,app_swarms,app_unread,agent_seen) are for this computer's daemon and only ride a loopback connection. A viewer with no machine connected hears no push, so it re-reads the machine list itself while that lasts (state/machine_list_watch.dart): after 4 s, 8 s, then every 10 s under the connect page (waitsForFirstComputer), or 15 s then every 30 s under the asleep band, and every 20 s otherwise (a computer still connecting). A push, the tab coming back to the front (which reads at once) and Retry start that pace over, and while recovery retries a failed or stale list it is the only one asking. A hidden tab reads nothing on this pace; the one read it still makes is the 5-minute safety net every window keeps (machineListSafetyNetInterval). The browser's connect page and asleep band keep no timer of their own. - Both REST and the local WS use the daemon's Unix socket (
lib/ws/local_daemon_transport.dart; CLIlib/localSocket.ts):~/.harness/cli/data/daemon-<port>.sock, 0600, named for the port inlocalCliBaseUrl. The loopback port takes any local user's process and any account can bind it once it is free, after a reboot until this user logs in or during a restart (audit H1); the socket is this user's alone. So while a socket can exist the app never asks the port: with the socket gone, the daemon is down. OneLocalDaemonTransport, owned byLocalCliDiscovery, is shared byApiClient(a Dio adapter that only routes the daemon's own address) andWsPool/WsConn. Each WS connect re-checks whether the socket file exists. Windows and paths over 96 bytes have no socket, and only those use the port. Underflutter testLocalDaemonTransport.detectfinds no socket, so tests never reach a real daemon. - On Windows the trusted routes go over the daemon's pipe (
ws/trusted_pipe.dart, B's §2):POST /api/auth/handoff, and this computer's window connection (WsConn.trustedLocal), where the daemon takes itsdaemon_*frames. Everything else stays on loopback TCP, relayed machines' connections included. Reaching a Windows pipe is no trust: the app reads the pipe's name fromdaemon-<port>.jsonand the token fromdaemon-tokenfor every request (ws/daemon_pipe_record.dart), each request carriesx-harness-auth, and an answer counts only when itsx-harness-proofproves the token (ws/windows_pipe_auth.dart, held to the CLI's__fixtures__/pipe-auth-vectors.json). An unproven pipe is no pipe: Add Phone shows its QR without the sign-in code, and the daemon's keys and talk say harnessd's private connection is missing. The pipe client is kernel32 over FFI on two background isolates (ws/windows_pipe.dart); its real-pipe test isintegration_test/windows_pipe_test.dart, on Windows CI. With no socket, the loopback port on Windows is the one the daemon recorded indaemon-<port>.json(LocalDaemonTransport.refreshTcpBase): another user's daemon may hold the configured one. - Besides viewer builds, a direct-to-backend test path is
LocalManualFixture(lib/main_local_manual.dart), a compile-time-gated dev entrypoint fed byscripts/start-terminal-local-manual.sh. It fails closed unless every--dart-defineis present.
lib/core/harness_cli_runner.dart is how the app finds the CLI without a shell: prefer
~/.harness/runtime/current-node + ~/.harness/cli/cli.js, then ~/.local/bin/harness, then PATH.
On Windows it reads B's layout instead (lib/core/windows_layout.dart, the rules of B's own
readers): runtime\current-node + cli\current → cli\<ver>\cli.js, then bin\harness.exe, then a
harness.exe in a PATH folder.
lib/bootstrap/environment_provisioner.dart installs the CLI and tmux (plus, on Linux, the clipboard
helper) on first run (the preparingEnvironment status). On Windows the steps are the CLI and B's
terminal host (EnvironmentStep.tmux stands for it, runtime\pty\<ver>\harness-pty.exe), both from
one hidden install.ps1 -Desktop run (windowsInstallCommand), which fails in install.ps1's own
sentence.
Node is deliberately not the user's: it is a private, sha256-verified runtime under
~/.harness/runtime, never Homebrew, nvm or PATH. The app does not install it — install.sh does,
on its own or on the app's behalf, and records it in current-node; the launcher it writes names that
binary absolutely, so a Finder launch (PATH is launchd's bare /usr/bin:/bin:/usr/sbin:/sbin) and a
Terminal launch behave identically. One implementation, shared with everyone who installs the CLI from
a terminal, instead of a second copy here that had to keep its own pinned checksums in step.
tmux on Linux is the one dependency still taken from the OS package manager, and the only reason
the setup screen ever opens a terminal: apt-get install needs a password prompt on a real tty. On
macOS it is a managed runtime (or the Homebrew one, if Homebrew is already there) and needs neither.
Readiness is the list of commands the app runs, nothing more (EnvironmentStep: tmux — plus ps
on Linux — the Harness CLI, and on a Linux desktop the clipboard helper). Homebrew, the Apple developer
tools, apt and the curl/tar/sed/awk/sha256sum the CLI installer downloads Node with are recipes for a
missing command, kept in EnvironmentReadiness.plan and probed top-down only while the command is
missing: a Mac with tmux is never asked about Homebrew, and a Linux box with a managed runtime never
about curl. The ladder itself is implemented once, in cli/scripts/install.sh (--host runs just
that half): on macOS tmux comes from the Homebrew already present or, failing that, the managed
build downloaded into ~/.harness/runtime — no compiler, no package manager, no password, so the
app runs --host in-app and never opens a Terminal window there. Linux keeps the app's own apt
transaction (its clock-skew repair) and the one Terminal handoff. Gating readiness on the recipes
was what sent a computer whose tmux ran fine into Terminal to reinstall developer tools after a macOS
upgrade — the screen renders plan, it does not infer one.
Installer-log polling reads only the last 64 KiB and keeps at most 200 lines, tolerating partial UTF-8 output. Truncated diagnostics include the full log path; the original file remains intact. A missing, unreadable, or partial Terminal result stays pending until a complete exit code or successful live probes establish the outcome. Copy failures in setup remain visible beside Retry, and only the latest clipboard attempt can update its feedback. The setup render fixture checks both themes and enlarged text at the minimum window size without running an installer.
Read-only dependency probes own their subprocesses and have a ten-second deadline covering startup,
exit, and output-pipe closure. A timeout reports a failed check, not a missing tool; Retry after the
initial check probes read-only first. When every item in the probed plan installs in-app (no
requiresTerminal — always the case on macOS), the app installs it straight after the probe, at
launch and after an automatic-mode Retry, without showing the review or its Install button; a plan
that needs Terminal (Linux apt) waits on that button, and manual mode never installs. Only an
install the app or the person started may continue after a Terminal handoff, and a failed recheck
stops that continuation. Readiness requires the final ready phase and every required step, so old
successful step values cannot flash a ready screen during a new verification. The preflight status
is a live region and uses a static waiting icon when Reduce Motion is enabled.
Boot and state
lib/main.dart: CrashLog.install() → loadPersistedSettings() (theme mode + terminal font, awaited
before the first frame to avoid flicker) → RootShell, which switches on AppStatus
(bootstrapping → preparingEnvironment → unauthenticated → authenticated).
lib/state/app_state.dart (AppNotifier, a ChangeNotifier exposed through the single Riverpod
appStateProvider) is the whole app model: machines, agents, connections, panes, updater, login.
Widgets receive notifier explicitly and rebuild via ListenableBuilder; Riverpod is only the
injection point (main_local_manual.dart overrides it). bootstrap() → _prepareEnvironment() →
cliLogin.checkStatus() → _finishBootstrapSignedIn() (restore pane layout, create WsPool, ensure
the daemon, api.me(), refreshMachines()).
Experimental switches are account state. AppNotifier.experimentalFeatures binds after api.me()
identifies the account, clears on sign-out/account change, and rejects stale responses. It uses
/api/experimental-settings, refreshes on account invalidations and a 30-second fallback poll, and
shows changes only after server acknowledgement. Do not restore the old unscoped local keys at startup.
Agent Messages (docs/design/2026-10-10-agent-messages.md) replaced Swarm collaboration. Whether
agents may message is the account's Experimental switch (agent_messages, off by default; each
daemon keeps a copy for its agents), not a tab's: the tab's own 💬 beside its × was easy to hit by
mistake and turned the tab off, failing a waiting message (owner, 2026-10-12), so the tab, its
menu, File and ⇧⌘P have no on/off. So are the other two things agents may do with Harness,
starting agents (agents_start_agents) and the pull request line (agent_pull_request_line):
they were each computer's Settings ▸ Agents until the owner made all three account experiments,
off for all (2026-10-12). The app reads GET /api/agent-messages through
the CLI like the desk only to learn that the daemon and backend have Agent Messages — once the desk
is joined, from the desk safety-net poll until one has answered, and when the backend comes back;
each tab's enabled in the answer is not read. A 404 (an older CLI or backend) offers no Show
Agent Messages (agentMessagesOffered, which also needs a desk tab). Traffic arrives as
messages_changed — but a daemon sends that only to its own computer's windows, so
AgentMessagesRemoteWatch reads the last messages of each desk tab with two or more harnesses
from its other machines every 15 s while the window is in front. A tab's log is the
agent_messages history request to every daemon with a pane in it, merged by message id. The creature switch opens the account's
ZooController collection; disabling it hides the creature without deleting eggs, individuals or progress.
Window-only preview collections are test/render fixtures, not a user setting.
Per-machine runtime state is MachineState (connection status, transport mode, agents, nodeOnline
from node_status pushes — distinct from our own socket status, pending offline agent, turn activity).
Explicit pane/tab Close uses requestClosePane / requestCloseSwarm and closes the session across
the global workspace. Harness Monitor is the exception: closing its reusable dashboard dismisses
the view immediately, even offline, and keeps its assistant available for the next open.
An owned idle session saves its native conversation and terminal snapshot
before releasing its process, regardless of other viewers. A ready, unused Claude/Codex chat with
an empty composer also closes directly, saving its terminal snapshot without requiring a native
conversation. Missing activity evidence for an existing chat remains unknown. Working,
waiting-for-input, draft, or unknown sessions share one confirmation for the whole tab, with
their names, activity, and the number of sessions that will stop. Its only choices are Cancel
and Stop; Cancel is the default. Stop saves and stops every reviewed session before the tab
closes. Idle-only closes retain the daemon's activity guard; newly active work gets one review
of the remaining sessions. Failures identify confirmed stops separately from uncertain ones
and default to Keep open. Close pane / Close Tab dismisses the captured views through the
normal recently-closed history path without another stop request; unconfirmed sessions may
still be running, and their views in other tabs remain open. A session reviewed before its
engine bound a conversation (Codex's first seconds) that has bound one since is the same session
(Agent.continuesSession): its Stop names the reviewed identity, no conversation, and the daemon
decides (CLI closeAgentService.ts matches); another conversation once one was bound is a
change. Previously queued daemon close plans remain compatible. Layout cleanup, moving panes, switching tabs, and sign-out retain
their view-only behavior. Older daemons retain their existing behavior until updated.
HarnessMonitor supplies the global running-harness count without process sampling
in the footer. Clicking it opens the reusable autonomous/harness-monitor DSH tab
through HarnessMonitorController, with its viewer on the left at 70% and the assistant
terminal on the right at 30%. Only the pane zoom action expands either pane. The DSH table shares the daemon's resource sampler
and adds opt-in activity metadata to agents_list. RAM is process-tree RSS; CPU is
interval use, with 100% representing one core. Unknown readings remain unknown.
Shared Codex servers are listed separately and included once; token counts reuse
existing agent data. The monitor never resumes sessions or scans transcripts.
MachineResourceMonitor always scopes CPU/RAM/GPU to this computer, even when the
focused pane is remote. Hardware is passive text, with no filter or popover. It
samples only the local host every 15 seconds while foreground. Readings expire in
45 seconds and clear on disconnect, replacement or hide. CPU is normalized host
utilization; RAM excludes reclaimable cache where available. GPU is the busiest
reported device. Missing telemetry is -. Additive machine_resources RPC fields
allow mixed old/new CLIs. See design/workspace-status-bar.md for the complete
scope and format contract.
Command dock
For app UI outside terminal panes, follow the desktop design system. The terminal-only presentation rules are retired for desktop forms, pickers, and menus. Preserve workspace boundaries and dialog behavior. Cmd-N and New Tab share their composer.
SwarmSearchController owns search and selection; SwarmSearchResults keeps a bounded cache of
visible/recent row controls. Query-dependent match text listens separately, so typing does not
rebuild unchanged row controls and arrows rebuild only changed highlights. The cache still
invalidates for row metadata, availability, action, geometry, theme, and font changes. Keep focus,
semantics, and traversal on the row; do not replace them with paint-only search results.
Creation and draft precedence are documented in design/new-harness-entry-rules.md and exercised
by its listed tests. Cmd-T/Cmd-O retarget the same draft/search; Store requests own their explicit
product and machine. test/benchmarks/swarm_benchmark.dart measures large synthetic inventories;
its headless debug timings do not establish native display or network latency.
A New Harness box takes files three ways, all into the same HarnessAttachments: 📎, a drop, and a
paste (widgets/new_harness_paste.dart). ⌘V/Ctrl-V in the task asks the clipboard three things, in
this order. Files copied in a file manager come first (NativeClipboard.readFilePaths — the runner's
readFilePaths on harness/clipboard_image, NSPasteboard file URLs on macOS and GTK's
text/uri-list on Linux — read off disk by clipboard/copied_files.dart, which names a file over
the limit without ever reading it): Finder leaves each file's NAME as text and its ICON as a picture
beside them, and neither is what was copied. Then text, which pastes into the task and wins whenever
it is there — except a lone web address, which is what Safari's Copy Image puts beside the picture
(pastedTextWins). Then a picture — a screenshot, Copy Image — attached as pasted-image.png through
the same NativeClipboard the terminal reads. In a browser the page's paste event carries the files
instead (clipboard/pasted_files.dart, a no-op natively), because Flutter leaves ⌘V to the browser
there and PasteTextIntent never fires. Pasted files are numbered, never swapped for one of the same name — every
clipboard picture is called alike. The field's own paste is the fallback and must be captured inside
Action.invoke: callingAction is gone by the time a clipboard read returns. A chip
(widgets/new_harness_attachment_chip.dart) shows a picture as itself and any other file by the mark
of its kind — fileTypeIcon in shared/theme/file_type_icon.dart, one table from extension to icon;
add a kind there, not at the call site.
Terminals
TerminalPane(lib/state/terminal_pane.dart) separates intent (machine + agent id, stableidused as the widget key) from the liveTerminalSession, so a tile can exist before its machine answers and survive the machine going offline.PaneLayoutStorepersists intent only, max 4 panes;PaneGridrenders fixed 1–4 tile shapes (deliberately not a splittable tree).TerminalSession(lib/terminal/terminal_session.dart, protocol v3) owns onextermTerminalfor one agent:terminal_open/terminal_readyhandshake matched by requestId+agentId, seq-tracked output with bounded resync and one auto-reopen, batched input/resize, heartbeat, andonOpenStalledto force a transport redial.engineId == 'grok'scrolls via tmux copy-mode instead of mouse reports (seescrollViaTmuxCopyMode).- Bulk terminal bytes are binary WS frames framed by
lib/terminal/terminal_binary.dart(HTRLmagic, kinds input/output/keyframe/sync, zlib flag).AppNotifier._handleTerminalBinarydecodes once and offers the frame to every session on that machine; each session drops frames whosestreamIdis not its own. The same fan-out applies to JSON events in_handleEvent: all pane sessions gethandleFramefirst (a session returns true for any terminal frame, even one not addressed to it), then the app-level switch handlesnode_status,agent_*,turn_*, and the hardware-dial eventsdial_scroll/dial_focus. - A pane's colours are told to the daemon (
theme_set,AppNotifier._announceTerminalTheme, on every connect and whenevergrid.AppTheme.paletteorterminalThemeStorechanges; CLI sidelib/hostTheme.ts). tmux answers a TUI'sOSC 10;?/OSC 11;?— which is how Codex picks a light or dark diff palette, once, at startup — from whichever client attached to the session FIRST, so a person whotmux attached a light terminal before the daemon's control client made Codex draw pale-green diff rows with dark text inside a dark pane. tmux'swindow-stylewins over every client in that reply and changes nothing a control-mode client receives, so the daemon sets it, window-scoped, on the sessions it created (TmuxBackend.createchains it intonew-session;inventory()restyles existing panes on each scan). ⚠️theme_set/theme_set_resultare in the E2EE type sets incli/src/lib/e2ee/core.ts, which re-pinned the interop keystone; a daemon that predates the type goes silent, which the app treats as "not supported" — never an error. - A Finder tile is a folder, not a terminal (
lib/finder/,PaneKind.finder), modelled on Orca's Explorer, Source Control and editor tabs. New Harness lists Finder beside Terminal (kFinderEngine), and a Finder never opens alone (owner, 2026-10-20): it is chosen as a Store harness is — Harness row "Finder", then "Run Finder with" an agent, its model and approvals (NewHarnessController.isFinder;harnessIdreadsfinderwhile_harnessIdstays the DSH one) — and starts that chat in the folder (no worktree; the first message goes to it).AppNotifier.openFinderBesideputs the tile LEFT of that terminal at 70/30, as a harness's web viewer sits. It is the chat's viewer (ownerAgentId,TerminalPane.viewsAgent): it moves and closes with the terminal, and the two are one group — the Finder has no Close of its own, and closing it (⌘W) closes its chat (requestClosePane). Viewers are never in the saved layout or the desk, so the folder is kept per chat inFinderRoots(finder.rootsin the local store);_syncViewerPanebrings the Finder back whenever that chat's terminal is shown — after a restart too — until it is closed by hand or the agent stops. With no file open the tile is only as wide as its file list, and its header's Collapse (Orca'sPanelLeftClose) folds it to a 44px rail (FinderRail): the panel reports that width (TerminalPane.fixedWidth,AppNotifier.setPaneFixedWidth) andPaneGridgives it to a full-height edge tile, sliding the others into the rest (pinFixedColumn,widgets/pane_fixed_width.dart; no divider drag while pinned). Opening a file takes its share back. Left: Files (a lazy tree with Git colours, ignored entries faint viagit check-ignore, a right-click menu, names typed in place, Trash rather than delete) or Changes (Conflicts / Changes / Staged / Untracked with +/- counts, Stage, Unstage, Discard). Right: tabs — a single click opens a preview tab that the next one replaces, a second click or an edit keeps it. Files open inre_editorwith re_highlight colours, find/replace, ⌘S, the file's own line break and indent; Markdown opens rendered with its source a click away; diffs are whole-file (--unified=1000000), folded, inline or side by side. A watcher (FSEvents on macOS) refreshes the tree, clean tabs and Git, with a 60 s safety read; a tab edited when its file changes on disk gets Reload / Keep My Edits. Closing a tile or tab with unsaved edits asks first (TerminalPane.beforeClose). ⌘S and ⌘F are workspace bindings elsewhere, so the editor'sKeymapRegion(keeps:)takes them back while it has focus. The editor highlights on an isolate that headless tests never let answer — check colours withintegration_test/finder_native_test.dart. OnlyLocalFinderFiles/LocalFinderGitexist, so other machines and the browser offer the row disabled (canOpenFinderOn) until the daemon serves listings, reads, writes and Git. third_party/xtermis a vendored, patched xterm 4.0.0 (atomicreplaceRangefix for scroll regions — see itsREADME.autonomous.md). Do not replace it with the pub package; the regression lives intest/terminal_session_test.dart.
Theming — two files, one source of truth
lib/shared/theme/app_theme.dart(imported asgrid) is the design-system token layer:AppPalette/AppSurface/... members are getters that resolve against the globalgrid.AppTheme.brightness, which_GridTokenScopeinmain.dartsets fromTheme.of(context). Chrome widgets callgrid.AppTheme.watch(context)at the top ofbuildsoconstsubtrees still repaint on a theme flip.- The workspace status bar places system-font tabs and global actions at the top,
with harness, machine and installed local model counts plus subscription allowance remaining at the bottom left and focused machine/repo/branch/PR at the bottom right.
Tabs center their name/status group. Holding Command shows their current shortcut in the status
slot using the original small labels; release or window deactivation restores the status.
Hovering a tab shows only its ×. Agent Messages has nothing on a tab: no 💬 (it was
easy to hit by mistake and turned the tab off, owner 2026-10-12; Settings ▸ Experimental holds
the account's switch) and no traffic, so its status slot keeps its own status (messages arrive when they
arrive). A tab's log is its menu's and File's Show Agent Messages (
lib/agent_messages/,AgentMessagesControlleronAppNotifier.agentMessages, its own notifier so traffic never rebuilds the workspace;SwarmTabButtonmirrors the tab natively). At rest the name has the whole tab; hovered, it moves left only as far as × needs. Tab and pane close marks are small and quiet, with larger click targets. Terminal panes end with matching plain-text agent/model selectors and close at every width. Hovering the right or bottom edge reveals its split icon; zoom stays in commands, menus and keyboard shortcuts. Only distinct domain-harness icons stay on the left. Usage has no dot separators and colors only low/exhausted percentages. Automatic names use the strongest shared harness type, project, or machine, preferring traits that distinguish tabs and excluding dependent viewers. The context follows a viewer's owner and uses the compact project label, never a worktree path or marker. User-renamed tabs always retain their saved name. Appearance → Status selects shell-inspired text or Powerline themes; the focused PR label uses that same theme. The single focused PR reader isstate/workspace_pull_request.dart. lib/theme/app_theme.dart(AppColors,AppTheme.terminalLight/terminalDark) is a set of adapters over those tokens. Nothing here isconston purpose — freezing a colour is how light mode silently breaks. Do not add a parallel palette.- Type is
AppType(lib/shared/theme/app_type.dart): system sans for app headings, labels, fields, navigation, and prose; explicit mono for code, paths, logs, and identifiers. Ordinary UI is independent of terminal zoom and respects accessibility text scaling. The terminal grid, in-pane composer, and in-pane find keep the selected terminal font and size. Compact pane/status bars retain their establishedworkspaceBarTextStyle()and user-selected status themes. Native menus use the system menu font. Do not measure desktop UI in terminal cells. ThemeModeStoreandTerminalFontStoreareValueNotifiersingletons (they must resolve above the provider scope and before sign-in).
Persistence and native integration
- All local state is in
HarnessFileStore(~/.harness/desktop-app/state.json, mode 0600, keyed strings behindLocalKeyValueStore): connection config, skipped update version, theme, font, pane layout.~/.harness/computer-idis the machine identity shared with the CLI. A Swarm's saved view (up to 512 KB of chat) is never in it: each is a private file of its own inswarm-views/beside it (super_tabs/view_store_native.dart), and the first use moves out any that Desktop builds from 1.3.27 on left instate.json. Tests that pass a memory store keep views there. - The window is frameless on macOS via
window_manager(lib/core/desktop_window.dart, same size andTitleBarStyle.hiddenas Grid). On macOS the tabs are native, in the title bar beside the traffic lights (SwarmTitlebar.swift); the pane headers are aDragToMoveArea. A screen that fills the window goes throughFullWindowScreen(lib/widgets/window_chrome.dart) for its drag strip, and a full-width band at the top edge pads bytrafficLightClearance. macos/Runner/MainFlutterWindow.swiftinstalls native menu items and calls into Dart over theharness/app_menuMethodChannel (checkForUpdates,showShortcuts, terminal font size). Keep the menu in Swift; only the handler lives inRootShell.macos/Runner/SurfaceCacheGuard.swiftpatches Flutter's private macOS back-buffer cache, which can hand a frame a surface of another size after an A → B → A resize or a display replug; Impeller then dereferences a null color texture inCanvas::SetupRenderPass(flutter#185394). It checks every private class, selector and type encoding and stays inert if they change. On a Flutter bump, check whetherremoveSurfaceForSize:compares each surface's size; delete it if so.- Agent-account usage is what the native Models menu reads (
lib/usage/,usage/models_menu_controller.dart,SwarmSubscriptionViewinSwarmTitlebar.swift): what the Claude and Codex accounts on this machine — and on the remote machines that answerusage_read— have spent. Each account shows itstightestwindow, the limit that stops the work first. The shared controller reads ahead at startup and every five minutes; opening a menu requests a fresh reading, capped at once per minute. The footer uses these same deduplicated accounts and freshness rules, displaying one provider icon and remaining percentage per account. Values are neutral above 20%, muted amber at 6–20%, and red at 5% or less; tooltips identify the account, machines, limiting window and resets. Models counts distinct installed local model variants across linked owned machines, sharing the picker's cached inventories. Remote machines' accounts arrive throughusage_read(AppNotifier.readRemoteUsage,usage/remote_usage.dart,usage/usage_accounts.dart; CLI sidecli/src/lib/accountUsage.ts). A remote machine may be signed in to a DIFFERENT subscription, and the only honest way to read that one is to ask the machine holding it — so its CLI calls the vendors with ITS OWN token and hands back their HTTP status and body untouched, and this app reads them with the SAMEclaudeUsageFromAnswer/codexUsageFromAnswerit reads its own with. The credential never crosses the relay, and the window-naming rules live in one language. Readings are grouped ONE PER ACCOUNT (groupUsageAccounts): an account key — the first 16 hex of sha256(<provider>:<id>),usageAccountKeyhere andaccountKeythere, both suites pinning one vector — decides whether a remote subscription is this one again (folded in, unlabelled) or another (its own figure, labelled with the machine). Hashed because RPC replies are logged. Subscription headings show the provider login's email when available; older readings without an email show only the provider. Email is display metadata, redacted from structured logs. Account grouping, search identity and model selection continue to use the full hashed key. ⚠️ A null key never matches, itself included, and a remote reading folds into this computer's only when this computer HAS figures — otherwise a token that expired here would swallow a live reading of the same account taken there.readingsstays this computer's alone andaccountsis the grouped view. ⚠️usage_readis in the E2EE type sets (core.ts), which re-pinned the interop keystone the browser client and the paired device share. And a remote CLI that predates it does not refuse the frame — it cannot open the envelope, loses the requestId and goes silent — so this asks with a 10s timeout and treats every failure as nothing to add, never holding up this computer's own figures. This is the one exception to "the app talks only to the local CLI", and a narrow one: nothing here is dialled on the app's own behalf.UsageCredentialsreads the tokens the agent CLIs already wrote — the macOS Keychain itemClaude Code-credentials(falling back to~/.claude/.credentials.json, which is all Linux has) and~/.codex/auth.json— and spends them against the vendors' own usage endpoints. It never writes or refreshes them: one sign-in per machine, owned by the CLI that made it. A rate limit is scoped to an account, not a machine, so reading it here is right even though the agents run elsewhere — provided the remote machines sign in as the same account. ⚠️ Both endpoints are undocumented —api.anthropic.com/api/oauth/usage(needsanthropic-beta: oauth-2025-04-20and the CLI's own user agent, because the OAuth token was minted for the CLI) andchatgpt.com/backend-api/wham/usage. Either can change without notice; both failures land as aProviderUsagestate rather than an exception.signedOutis kept apart fromfailed: retrying a sign-out fails identically forever. Claude's Fable window has been spelled three ways across releases and all three are tried; Codex names its windows fromlimit_window_secondsrather than assuming, because a confident "5h" beside a real percentage reads as measured.loadingis false beforestart()as well as after the first answer — a controller nobody started is not waiting for anything, and a skeleton for it would promise an answer never coming. That is also what keepsflutter testhonest:kUnderTest(core/test_run.dart) stops the poll auto-starting, since aTimer.periodicis apumpAndSettlethat never settles and these sources would otherwise shell out tosecurityand open real sockets. - The token ledger is the OTHER usage feature, and the two must not be merged (
lib/usage/ledger/, Settings ▸ Usage insettings/sections/usage_section.dart+usage_panels.dart). The Models menu's readout above asks the vendors how much of your rate limit is left — a percentage, scoped to an account, true whichever machine burned it. This counts tokens, scoped to this machine, with a history: it reads the logs the agent CLIs already wrote to this disk and calls nobody. Ported from Orca (src/main/{claude,codex,opencode}-usage/); keep the pricing tables in step with itsclaude-model-pricing.ts/codex-model-pricing.ts. Three providers, three unrelated formats. Claude: JSONL under~/.claude/projectsand~/.claude/transcripts(the older layout — reading only the first drops every pre-move session), usage offmessage.usageontype == "assistant"rows. Codex: JSONL under$CODEX_HOME/~/.codex/{sessions,archived_sessions}, usage offevent_msg/token_count. OpenCode: a SQLite database at$XDG_DATA_HOME/opencode/opencode*.db, one aggregate row per session. ⚠️ Codex reports CUMULATIVE totals where Claude reports per-turn figures — summingtotal_token_usagewould bill a 40-turn session forty times over, soresolveCodexDeltatakes the increment and guards the compaction/resume regressions. ⚠️UsageTotals.freshInputis cache-EXCLUSIVE for all three, which costs Codex a subtraction because itsinput_tokensincludescached_input_tokens; Orca deliberately does not normalise, which is right for a scanner that round-trips a file format and wrong here, where one panel adds all three together. Codex'scache_write_input_tokensis dropped on purpose — OpenAI writes its cache free, so a bucket for it would show tokens nobody is billed for.costUsdis nullable and null is never zero. Only OpenCode fills it, from its owncostcolumn; Claude and Codex are priced frommodel_pricing.dart, and a model that matches no row leaveshasUnpricedModelset so the panel calls the figure a floor. A Grid session records a real0.0(Grid inference is free, grid ADR 0039 D-g) and that measurement must not render like an unpriced model. Same rule as account usage:LedgerStatus.unavailableis kept apart fromfailed, because a machine with no OpenCode is never fixed by retrying. Off is the resting state, per provider, persisted throughLocalKeyValueStore: these transcripts hold every prompt, path and branch a session touched and this feature wants only the counts, so nothing is read until somebody switches it on — and switching one off deletes its snapshot from disk as well as from memory. JSONL scans are incremental against a{path, mtime, size}fingerprint cached in~/.harness/desktop-app/usage-ledger-<provider>.json. OpenCode instead queries a committed SQLite snapshot on each scan: the main database's metadata can stay unchanged while its WAL changes. SQLite reads run in a worker isolate.kLedgerStaleAfter(5 min) keeps opening the pane from re-walking the disk; a cold Claude scan is ~3s over 71 transcripts, which is why neither of those is optional. Nothing polls — a ledger only moves when an agent writes here. An unreadable OpenCode source is failed, not missing. If other databases are readable, the result is partial and the UI marks its figures incomplete. Partial results are kept in memory, but never restored as a fresh complete snapshot; reopening or Retry rescans them. Claude/Codex share the same failure rules injsonl_ledger_scan.dart: a failed read is never cached as an empty successful source. Snapshot format 3 discards old snapshots that could contain that mistake. Reads stop at the captured file size and tolerate an unfinished UTF-8 suffix while an agent appends, preserving earlier complete records; completed corrupt text remains an error. Model-name normalization has a small bounded cache, while per-turn token/tier pricing stays dynamic. ⚠️ Local only, by decision. Agents launched onto remote machines write their transcripts there and nothing here reaches them; the pane's subtitle says so, because a total that silently excluded most of a team's work would be worse than no total.UsageSourceinusage/usage_source.dartis where a per-machine source would arrive if that changes.sqlite3is a Dart-only FFI dependency (neversqlite3_flutter_libs): it dlopens the system library, so it registers no native plugin and leaves the macOS SPM package list alone.kUnderTestkeepsUsageSectionfrom auto-loading, for the same reasonUsageController's poll does not start there. ⚠️ The snapshot goes throughSnapshotStore(core/snapshot_store.dart), and a test MUST passMemorySnapshotStore— this is not tidiness. A realFile.writeAsStringnever completes insidetestWidgets' fake-async zone, so a store awaiting one hangs the whole run until the shell is killed rather than failing; that seam is what keepsdart:ioout of a widget test, exactly asLocalKeyValueStoredoes. It is deliberately NOTLocalKeyValueStore: that isstate.json, one small locked document, and a multi-megabyte usage snapshot in it would be rewritten on every theme flip.HarnessStatsuses the same seam. - Settings ▸ Usage has a second half, and it counts the APP rather than the CLIs
(
lib/stats/harness_stats.dart, drawn byStatsSummaryCards). Ported from Orca'ssrc/main/stats/: agents spawned, time agents worked, and a "Tracking since" line. These are this app's own events, so unlike the ledger there is no permission to ask and no switch — an app may count what it did.harnessStatsis a singleton likeappLog, loaded byloadPersistedSettings(not for the first frame — because the counters start moving as soon as an agent does, and a load landing after the firstonAgentSpawnedwould overwrite it) and flushed byStatsLifecycle.didRequestAppExit(stats/stats_lifecycle.dart), which is the ONLY place a turn still running at quit gets its time counted. Three hooks, all inAppNotifier:createAgent(not theagent_createdpush, which also fires for agents another client made on the same machine), theturn_startedcase (notturn_heartbeat, which is a turn already under way), and_cancelTurnActivityplus the turn watchdog for the end. ⚠️ The watchdog end is load-bearing: it is the only close a stalled turn ever gets, and a stats turn left open would sit there until quit and then bank every hour since as work. A start on a live key is ignored rather than restarting the clock, and an end with no start contributes nothing — that is what makes the disconnect sweep safe. ⚠️ Two deliberate departures from Orca. The third card is TURNS, not PRs created: this app opens no pull requests, and a card wired to a number that can only read zero is worse than one showing something true. And no event log is kept — Orca persists 10,000 events beside its aggregates for breakdowns it does not draw, at ~900KB per write;firstEventAtis stored directly, which is the one thing that log was protecting. - The per-provider detail pane is ONE file, not three (
settings/sections/usage_provider_pane.dartwithusage_detail_panels.dart), against Orca's near-identicalClaudeUsagePane/CodexUsagePane/OpenCodeUsagePane. Everything that differs between providers is already inusage/ledger/usage_report.dart; three copies of the layout would be three places to fix a spacing bug. The lens picker at the top of Settings ▸ Usage switches between the overview and one provider, and_Lensis a nullableLedgerProviderso the per-provider cases stay exactly the providers that exist. The overview opens on the last 30 days, the window Orca's default range shows, so a figure here can be compared against one there —_kDefaultOverviewRange. All-time is a click away in the same picker the provider panes carry. Measured on one machine: 30 days reads 3.2B tokens / 20 active days / 80 sessions, where all-time reads 3.8B / 33 / 92 — both true, answering different questions. The intensity grid draws a fixed six weeks whatever the range is, as Orca's does:overview.daysis already clipped, so the days before the window fill in as EMPTY cells rather than as stray data, and shrinking the strip to the range only costs it the context a heatmap exists for. Clipping happens inclipLedgerat draw time, not at scan time: the scan is the expensive half and does not depend on the window being looked at, andledgerFromEntriesis shared withbuildProviderLedgerso a clipped ledger cannot sum its cost differently from the full one. ⚠️ There is a RANGE filter and deliberately no SCOPE filter. Orca offers "Orca worktrees only" against "all local usage" because it owns the worktrees its agents run in. This app owns no such boundary — agents launched through Harness run on OTHER machines and write their transcripts there — so a "Harness only" lens over this computer's logs would filter on a distinction that does not exist here and would answer nearly zero. Everything local is counted and the pane says so. ⚠️ OpenCode'stokens_cache_readis a PEER oftokens_input, not a subset — Orca gets this wrong and this app must not copy it.opencode-usage-row-parsing.tsclamps it withMath.min(cache.read, input)on the assumption it is contained, the way Codex's cached input is. Measured against a live database, three of nine sessions read more from cache than they had input at all (7,680 cached against 72 input), which no subset can do; the clamp threw away 30.2k of 51.0k real cache reads and dropped them from the total besides. OpenCode's schema keepstokens_input,tokens_cache_readandtokens_cache_writeas three columns, the Anthropic shape rather than the OpenAI one. Codex remains the only provider whose input needs the subtraction. ⚠️UsageSessionsTablestates its width instead of stretching. Inside a horizontalSingleChildScrollViewthe incoming width is unbounded, soCrossAxisAlignment.stretchasks for an infinite row and the layout throws;_sessionTableWidthsums the columns, which is the only honest width it has. - Settings is a screen, not a dialog (
lib/settings/):showSettingsScreenpushes a faded route whose rail listssettingsGroupsfromsettings_section.dartand whose pane is one widget perSettingsSection(sections/). Adding a setting means adding an enum value, a group entry and a section widget — nothing else. Panes are framed byshared/widgets/section_scaffold.dart(copied from Grid), and one setting inside a pane is ashared/widgets/setting_row.dart— a raised block with its title and detail on the left and its control, fixed atSettingRow.controlWidth, on the right. Appearance and Terminal both use it; a pane that invents its own row shape is the bug. Controls come fromshared/widgets/too (AppSelectField,AppIconButton) — raw MaterialDropdownButton/IconButtondo not match anything else in the app. Settings holds settings only (owner, 2026-10-11): Account alone at the top, then General (Appearance — thecustomizerow, which opens the Appearance panel over the workspace — Notifications, Keyboard shortcuts), Agents (Connectors, Usage), Labs (Experimental) and Help (About, Debug in dev builds). A thing is managed where it lives: the Autonomous robots — Wi-Fi code pairing, Revoke, Still companion — in the Devices tab (devices/wifi_robots.dart); the account's computers, phones and apps, each device's code, Remove (a computer: sign out AND delete its machine record), History… and Show in this window in the Machines picker (state/machine_devices.dart,widgets/machine_picker_extras.dart). A way in from outside the workspace asks for Machines withAppNotifier.requestMachines(openMachinesinwidgets/new_device_notice.dart). What agents may do with Harness is in Experimental, the account's (owner, 2026-10-12): Settings ▸ Agents, which read and wrote this computer's daemon, is gone. An experiment an older backend does not name is shown off and unavailable, never a failed read (ExperimentalFeaturesStore._apply). - The log is written to files, and Settings ▸ Debug reads them back (
lib/logging/,settings/sections/debug_*.dart).appLog(app-YYYYMMDD.log) is the narrative —app,ws,api,flutter— andcliLog(cli-YYYYMMDD.log) is a transcript of every child process, both ported from Grid and both pruned after 14 days. The CLI chokepoint writes it:HarnessCliRunner.run/startgoes throughlogging/cli_transcript.dart, which logs the command as a person reads it (harness auth status --json, never the managed tier's<node> <cli.js>argv) and never its environment — a secret handed to a child rides there precisely to stay out of argv. The Dio clients carryattachHttpLog, oneapiline per finished request, method and URL only. What a child PRINTS can still be a credential, so CLI output and URLs go throughredactSecretsInText(logging/redact.dart, beside the frame-levelredactValue) before anything is written. The Debug pane is a mirror of those sinks, not a second stream (log_stream.dart+log_stream_sinks.dart): a bounded ring of the last 500 entries thatinstallFileLogstees into. Routine DEBUG records use a one-second flush deadline, 256 entries or 64 Ki characters. INFO/WARN and admitted ERROR records flush their preceding context; export, backgrounding, normal quit and updater handoff also flush. Every flush and immediate record reaches the kernel at once, but only admitted ERROR records (crashes included), normal quit and updater handoff fsync (flushAppLog(durable: true)): on Linux ext4 an fsync on the UI isolate waits for a journal commit (10–500+ ms under I/O), the best fit for the Linux long frames of 2026-10-16. An abrupt process kill can lose the pending DEBUG batch; a power loss can also lose written lines not yet synced. CLI transcripts are still written line by line, without an fsync. No timer runs with an empty buffer. It is developer furniture —kDebugSurfaceEnabled(logging/debug_surface.dart,kDebugModeor--dart-define=HARNESS_DEBUG_SURFACE=true) gates the rail row, the ⌘D shortcut (kDebugShortcut, inappShortcuts()rather thankAppShortcuts) and the ring itself; the log FILES are written either way, because a shipped app with no stderr is exactly the one whose logs matter. - A screen that waits on a call waits in the shape of its answer.
shared/widgets/skeleton.dart(Skeleton,SkeletonText,SkeletonLine,SkeletonList,SkeletonBlock) draws placeholders andshared/widgets/pulse.dartowns the app's one loading rhythm — an opacity breath betweenAppSurface.recessandrecessHover, never a shimmer sweep, frozen at the peak under Reduce Motion because a block held at 40% reads as disabled. A spinner is still right where the shape is genuinely unknown (boot, a button mid-action); a list, table, card, row or figure gets a skeleton. Three rules the call sites keep, guarded bytest/skeleton_test.dart: a placeholder is measured from the real content (SkeletonTextlays out the style with aTextPainterrather than trusting arithmetic — seeAppMenuRowMetricsfor why), it wears the real row's surface and padding, and it is never taller than the answer usually is, since a skeleton that shrinks jumps the page upward. "Loading" and "answered with nothing" must not render the same — henceAppNotifier.machinesLoading, which is set on the first fetch only so a refresh keeps the rows already on screen. lib/shortcuts/app_shortcuts.dartandkeymap_commands.dartsupply the live shortcut catalog.shortcuts/shortcuts_browser.dartshares searchable, grouped rows between the ⌘/ dialog and Settings ▸ Keyboard shortcuts. It reads resolved bindings throughkeyboardLessons(), so remaps appear immediately; clicking a row or pressing Enter opens keyboard practice without dispatching that action. Labels and keycaps use system UI typography and accessibility text scaling, independent of terminal font and zoom. The practice scratch preview retains terminal typography. ⇧⌘P opens commands with the query>; ⌘P opens the unified picker. On Linux these use Ctrl+Shift+P and Alt+Shift+P. Linux, like the web, takes Alt where the Mac takes ⌘ (altWorkspacePrefix) — Hyprland and GNOME keep most Super chords for themselves — and_linuxAltShortcuts/linuxAltCommandKeysmove the few that would land on a key a terminal program answers (Alt+Enter, Alt+T, Alt+F/B/D). The runner rewrites Super to Meta (super_as_meta_cb), so a Super chord a user binds still reads ascmd. Native Windows (ctrlWorkspacePrefix, excluding web) keeps its existing shortcuts everywhere: Ctrl+Shift for workspace letters, Alt+Shift for shifted twins, Alt(+Shift)+arrows for pane focus and moves, Ctrl+Page Down/Up for tabs, and Ctrl+Shift+Z for zoom. Outside the terminal view, eligible Mac ⌘[⇧]key defaults also have Ctrl[+Shift]+key aliases, such as Ctrl+T for New Tab, Ctrl+W for Close Tab, Ctrl+N for New Harness, and Ctrl+R for Reload. Aliases follow each command's existing keys and never replace another default in the same context. Mac chords containing Alt get no alias (Ctrl+Alt can be AltGr), nor do ⌘⌃ chords (⌘⌃S would take ⌘S's Ctrl+S). Arrows, Enter/numpad Enter, Backspace, Delete, Home, End, Tab, digits 1–9, comma, and A/C/V/X/Z/Y are excluded from alias generation; their existing bindings remain. For example, Ctrl+Shift+G stays Find Next, so Find Previous keeps Alt+Shift+G. In the terminal view, plain Ctrl+letter reaches the program except Ctrl+C with a selection (copies, clears the selection, and sends no interrupt) and Ctrl+V (Harness text/image paste). Native Windows local panes read clipboard PNG bytes throughNativeClipboard.readImagePngand the guardedsession.pasteImageroute. When a Windows clipboard writer is unavailable, the existing CLI route saves the PNG and pastes its file path into the prompt. With no selection, Ctrl+C still interrupts. Ctrl+Shift+C/V/A remain available; a pane this window does not control still permits copying but blocks paste. The composer and find bar count as text fields: editing keys win, and other aliases work. The terminal composer also reserves Ctrl+W/U for line editing and routes Ctrl+V through Harness image/text paste; Ctrl+T opens a tab there. IME composition does not dispatch aliases. Menu/tooltips retain the keys that work everywhere; the Shortcuts sheet and command palette also list aliases as “outside a terminal”. Only the Windows Edit menu follows focus: text fields show Cut/Copy/Paste/Select All as Ctrl+X/C/V/A; terminals disable Cut and show Ctrl+C, Ctrl+V, and Ctrl+Shift+A. Composer Edit-menu Paste uses the same image-aware path as Ctrl+V. Holding Ctrl shows tab numbers. User bindings retain their behavior, including in terminals; rebinding a command removes its default aliases, including bindings saved before aliases existed. Windows stores keybindings in%APPDATA%\harness\keybindings.jsoncwhen APPDATA is absolute. If that file is absent, the default store reads the previous configuration location (normally~/.config/harness/keybindings.jsonc, respecting XDG_CONFIG_HOME). Editing/rebinding writes the new path using the legacy content first and leaves the old file intact. With missing or nonabsolute APPDATA, the previous path rule remains. macOS, Linux, and web are unchanged. The Windows shortcut acceptance record identifies the tested source revisions and platform limits. Other workspace shortcuts are ⌘-based — Ctrl otherwise belongs to the shell/tmux, ⌥ is a Meta prefix for the pty (⌥⏎ and ⌥⌫ only —AltAsMetaInputHandlerinlib/terminal/terminal_input.dartturns them intoESC+ Return andESC+\x7f, so the engine's prompt breaks the line instead of submitting and kills the word behind the cursor instead of hearing nothing; ⌥ stays the compose key everywhere else), and ⌘C/⌘V/⌘A are owned by xterm — with two pinned exceptions:⌃⇥/⌃⇧⇥for the panes, which the terminal is made to let past, and ⌘⌫, whichTerminalPanel._onTerminalKeytakes back off the app and sends to the pty as^Ubecause a ⌘ chord never reaches xterm's input handler at all. The composer answers all four line-editing chords too: it writes ⌥⏎'s newline itself, binds^W/^U, and lets Flutter's own macOS text-editing shortcuts serve ⌥⌫ and ⌘⌫.- The app has no flash UI: the dial is flashed with
harness flash.SerialPortLeasesees that flash's lease file and pauses daemon supervision soharness startcannot steal the port mid-write. lib/update/desktop_updater.dartself-updates from the GCS manifest (sha256-verified, strictly newer only, and on macOS and Windows signed by the running app's own publisher:lib/update/update_signature.dart, RELEASE.md "How a running app self-updates"). Its keys must match what writes the manifest —_otaKeyMacOS/_otaKeyMacOSArm64the variant table inscripts/publish-macos-variant.sh,desktop-linux-<arch>theOTA_KEYinscripts/upload-desktop-linux.sh. An Intel Mac reads onlydesktop-macos(the Skia build); Apple Silicon takes the newer ofdesktop-macos-arm64anddesktop-macos, arm64 winning a tie.
Testing conventions
Unit tests build AppNotifier(config: AppConfig.dev, authSession: AuthSession(), configStore: null)
and set status directly, or pass subclass fakes (CliLogin, EnvironmentProvisioner, ConfigStore)
so nothing shells out to a real harness binary. Stores (PaneLayoutStore, ThemeModeStore,
TerminalFontStore) take an in-memory LocalKeyValueStore implementation instead of touching
~/.harness. TerminalSession is exercised with recording send/sendBinary closures and
handleFrame/handleBinary. Use the @visibleForTesting seams on AppNotifier
(handleEventForTest, adoptSessionForTest) rather than reaching into private state.