Skip to content

Latest commit

 

History

History
333 lines (240 loc) · 87.8 KB

ipc.md

File metadata and controls

333 lines (240 loc) · 87.8 KB

IPC

Power controls: caffeinate_status, caffeinate_set ({ request }), caffeinate_permission ({ install }) and caffeinate_recover return a revisioned native status snapshot, including the original duration_minutes and the current deadline_ms. mode is off, duration, until, agents or indefinite; the request and status both carry display (Keep display on). caffeinate://status broadcasts changes across profile windows. Configuration, authorization and recovery are async; the manager and timers live outside the webview. See Caffeinate.

Profile customizations use customizations_open and customizations_set_enabled { enabled }, both async commands with blocking filesystem work off the UI thread. They resolve the calling window's profile. The open command initializes the layout and bundled skill, opens the folder in the file manager, and returns its absolute path. The setter changes the profile default and reconciles active tasks whose projects follow it, keeping explicit project overrides. See customizations.md.

Tauri commands

  • Tasks: task_create/task_create_multi (async, spawn_blocking; the frontend never blocks on the returned promise — see "Non-blocking task creation" below) stream the WHOLE creation timeline — worktree add, file copy, port allocation, then the setup script — on one channel, setup-output://<id> ({ line }) + setup-done://<id> ({ code, success }), keyed by the client-generated task id the New Task dialog sends as args.id (so the frontend can subscribe before invoking). task_archive/task_delete (async, spawn_blocking), task_open_repo (multi-repo projects take an optional members root_path filter — absent links every member, the quick paths' shape), task_update_members { taskId, add, remove } (edits a live multi-repo task's composition: remove lists member dir_names torn down per-member best-effort — worktree members via git worktree remove --force, link members by unlinking only Termic's symlink; add takes CreateMultiMember specs materialized exactly like create, with ports claimed from the task's own PORT_BLOCK_BUFFER tail, then the added members' setup scripts stream on the task's setup-output://. Removals run first so same-call adds can reuse freed slots; the auto-derived sandbox cage is re-derived only while it still equals the auto-derived base), task_run_script_stream + task_stop_script (PIDs in RUNNING_SCRIPTS, child has process_group(0) for clean SIGTERM tree-kill), the CLI run verb / MCP task_run (the webview's run_script RPC, runScriptRpc in src/lib/runTabs.ts: start, stop or report the run or setup script in its Run tab through the same launch path as the Run button, leaving a running one alone), task_ensure_extra_ports (GH #196: tops up frozen named ports from the current config, called by the frontend before every tab spawn). Task groups: task_group_join { taskId, targetId, color } (joins the target's group, or founds one led by an ungrouped target, color an accent key), task_group_new { taskId, color } (a group of just this task, the sidebar's Move to group > New group), task_group_leave { taskId } (touches nobody else: a lone member keeps its group), and the CLI group verb / MCP task_group reach the same writes through the webview's set_task_group RPC (absent key = unchanged, name: "" = follow the lead, a task in no group founds one first), task_group_update { groupId, name, color } (a blank name returns the group to following its lead's name), task_group_dissolve { groupId }, task_link_spawn { taskId, parentId, color } (the CLI / MCP new: stamps spawned_by, and joins the parent's group only when both are in one project; task_group_join refuses across projects). All async + spawn_blocking; the rules are pure apply_group_* functions in lib.rs, unit-tested. The CLI / MCP new never calls these from Rust: the server passes parentTaskId to the webview's new_task handler, which links (task_link_spawn) BEFORE its loadAll, so the row first renders already inside its group. See docs/ui.md "Task groups".
  • PTYs: pty_spawn/pty_write/pty_resize/pty_kill. pty_children { id } -> the names of what runs under a PTY's root (descendants only), for "restarting ends these" confirms; capped, and empty off macOS, where the caller confirms generically. ipc.ptyWrite queues per PTY so writes land in call order (two concurrent invokes are not ordered, see gotchas.md "Two invokes in a row"). Emits pty://<id> (PtyChunk { data: Vec<u8> }) and pty-exit://<id> (PtyExit { code: Option<i32> }). SpawnArgs.role ({ task_id, kind: "agent"|"aux", is_default }) is the CLI attach/logs identity and allocates the 256 KiB output ring; it is deliberately separate from task_id, which doubles as the sandbox trigger (the aux shell carries a role but never a task_id). SpawnArgs.owner ({ task_id?, tab_id?, kind: "agent"|"shell"|"aux"|"run"|"setup"|"custom" }) is a THIRD identity and a reporting field only: the Activity monitor groups rows by project → task → tab with it. Every spawn sets it, including the ones the other two must skip — a scratch shell pegging a core is exactly what the monitor exists to find. Nothing may branch on it. SpawnArgs.shell_secrets ({ task_id, tab_id, role }, never with task_id) starts a SHELL with a Secrets role through the broker (sandbox.md "Shells"); absent, the spawn is unchanged. A role that cannot apply (with task_id, off macOS, a gone role or task, a broker that fails to start) fails the spawn with a readable error.
  • Touch ID for sudo offer (sudo_touchid.rs): the reader thread of every HOST PTY (not sandboxed, not Docker) emits pty-sudo-touchid://<id> (SudoOffer { show }) when the PTY reaches a sudo password prompt on a Mac that could use Touch ID for sudo, and show: false once sudo stops being the foreground job. Detection never matches prompt text: echo off with ICANON on (tcgetattr on the master) plus the foreground pgrp leader's proc_name being sudo. Reads over 512 bytes skip the probe, and so does every read once the user opted out (sudo_touchid_set_offer { enabled } mirrors the pref into an atomic). Eligibility (/etc/pam.d/sudo includes sudo_local, sudo_local has no live pam_tid.so, LAContext can evaluate biometrics) is checked once per prompt, not per read. sudo_touchid_script writes the bundled enable-touchid-sudo.sh to <global_dir>/bin/ and returns { path, command }. There is no elevation of our own: the script re-execs itself under sudo in a terminal the user sees. AppleScript with administrator privileges is out because writing under /etc/pam.d/ that way fails with EPERM on macOS 26 (iTerm2 shipped it and pulled it).
  • PTY attach ack: pty_attached { id }, called by the webview the instant listen("pty://<id>") resolves. Tauri events are fire-and-forget, so everything the flusher emits before that listener exists is dropped with no trace, and the child starts writing the moment it is forked. Rust therefore holds a PTY's FIRST flush (and the reader's final drain, for a process that exits immediately) until the ack lands or a 3s grace expires. Every caller of pty_spawn must send it (TerminalPane, AuxTerminal today), or that terminal shows nothing until the grace runs out. The gate itself is wait_for_attach in lib.rs, unit-tested for all three exits.
  • Activity monitor: procmon_open_window creates or re-focuses the procmon window; procmon_start → ProcSnapshot { session, rows, sampleMs, webkitUnavailable }, procmon_sample { session }, procmon_stop { session }, procmon_signal { pid, signal } (TERM/KILL/INT/STOP/CONT only, and only for a pid inside one of OUR PTY subtrees — the webview must not be an arbitrary kill(2) gadget; on Windows the names map to actions on the pid's whole process tree: TERM and KILL end it, STOP and CONT suspend and resume it, INT is refused). Sampling is PULL-based: there is no sampler thread, the Activity window's own interval is the clock, and stop leaves the module holding nothing. session is a guard, not decoration: a mismatched id errors so a reloaded webview restarts cleanly instead of reading another window's deltas. Only ever called from the Activity window (activity.html), never the main one. mod procmon in lib.rs is a 4-way #[cfg(…)] split resolving to procmon.rs (macOS, libproc/mach FFI, ri_phys_footprint for memory), procmon_linux.rs (/proc, plain text, VmRSS for memory — no phys_footprint equivalent, no WebKit-sidecar attribution), procmon_windows.rs (a ToolHelp snapshot, the private working set for memory, WebView2's processes counted as the app's own descendants when this instance owns them), or procmon_other.rs (every other OS: a stub reporting "unsupported"). All four share row shapes + OS-agnostic logic (subtree walk, cpu_ratio, label_for, signal_from_name) from procmon_common.rs. The macOS FFI genuinely fails to LINK if it ends up compiled into a non-macOS build — this split exists because that shipped broken once (the Linux release build failing at link time with undefined libproc/mach symbols).
  • Language servers (GH #174, code intelligence): lsp_start { root, language, channel, options } → a server id, spawning the child at root with the user's login-shell PATH but a NARROW environment (VIRTUAL_ENV, RUSTUP_TOOLCHAIN, GOFLAGS, locale and friends, never the tokens an rc exports: resolution prefers a binary from inside the checkout, so the repo picks the process). options carries the project's own { initializationOptions, settings }, forwarded verbatim; lsp_catalog {} → every server termic knows about per language, with what this machine already has; lsp_send { id, message }; lsp_stop { id } (SIGTERM to the whole process group); lsp_reap_foreign { page } → how many were killed (every server started by an EARLIER page load: a reload throws away the webview map that keeps one server per checkout while the processes keep running, unreachable, so App calls this once at startup); lsp_list → [{ id, root, language, command, pid }]. Installation is separate: lsp_offer { root, language } → { exe, installLabel, installBytes, caveat } (what can be driven, or downloaded, or neither, plus anything about this checkout that will make the answers look broken), lsp_install_zuban {} (a virtualenv termic owns, pinned and wheels-only, because zuban ships as a PyPI package rather than a binary), lsp_install { language } (idempotent; resolves the LATEST release of a hardcoded upstream repo, verifies the bytes against the SHA-256 that release advertises, unpacks into <data dir>/servers/<language>/<version>/ and strips com.apple.quarantine), lsp_check_update { language } → { installed, latest, upgradable } (on demand only, and never reports an upgrade when the API did not answer, which would offer a downgrade), and lsp_update { language } (installs alongside, keeps the newest two versions, takes effect at the next spawn).

lsp_send is a queue push, not a write: a child that has stopped reading would otherwise block a Tauri IPC thread inside a pipe write, holding the server map's mutex, which is the synchronous-IO trap in CLAUDE.md reached through a pipe. Each server owns a writer thread. The bridge is a Tauri Channel, not emit/listen: Tauri's listeners may process events out of order when a listener is async, and out-of-order delivery corrupts JSON-RPC. Three things in the host are load-bearing and fail SILENTLY when wrong, so they have unit tests rather than comments alone: it answers server→client requests itself (workspace/configuration gets one null per requested item — ty panics on a length mismatch and hangs when the reply never comes — everything else gets a null result, because an ERROR reply is what aborts pyright), it merges workspaceFolders/rootPath into the outgoing initialize (the CodeMirror client sends only rootUri; clangd reads only the former, ruby-lsp only the latter), and Content-Length counts BYTES. Servers are registered in cleanup_children and are procmon roots, so they appear in the Activity window with no taskId — one server serves every task on its checkout. Deliberately NOT sandboxed: only the agent CLI PTY is in that threat model, and a language server is the user's own toolchain.

  • Subscription usage (GH #277, the task footer's usage chip): agent_usage_codex { agentId } -> AgentUsage { session, weekly, budget, planType, accountId }. Async + spawn_blocking, because it SPAWNS codex app-server and waits up to 10s for a cold start; a synchronous command doing that blocks the WKWebView event loop. It is one initialize + one account/rateLimits/read over stdio, then the child is killed, deliberately the same shape as codex_trust::hooks_list (worker thread, join timeout, kill first and report second) because it is the same hazard: a long-lived JSON-RPC peer termic wants exactly one answer from. CODEX_HOME comes from agent_dirs::instance_config_dir for the agent ENTRY, so a clone is asked about its own login rather than the base's. Windows arrive as durations and are sorted into session/weekly BY LENGTH, never by primary/secondary position: a free plan sends a single 30-day window as primary, and reading position as meaning paints a session bar that resets next month. Credit-based Codex plans report individualLimit even when both rolling windows are null. It becomes budget { usedPercent, used, limit, resetsAt }, with numeric credit amounts parsed from the protocol's strings and percentage inverted from remainingPercent. The codex entry in rateLimitsByLimitId takes precedence over the legacy rateLimits view; model-specific buckets are excluded. claude has no equivalent command and must not grow one - it reports itself through the status line agent_hooks::statusline_body installs, over the OSC channel the hooks already use. agent_usage_devin { agentId } -> same AgentUsage: a plain async command, no spawn, because the transport is one Connect GetUserStatus POST to the api_server_url in the account's credentials.toml with its windsurf_api_key in metadata. Devin reports daily/weekly quota REMAINING, which parse_devin_result inverts into used percent. An ACU-billed (Enterprise) account has no quota at all (unlimited credits, no daily/weekly fields), only acuConsumed since planStart: that arrives as AgentUsage.consumed { amount, unit: "ACU", periodStart, periodEnd }, set ONLY when there is no window, and the chip shows it as a plain count; a Docker devin answers an error, since its login lives inside the container with no mount. See docs/agent-hooks.md and docs/ideas/usage-footer.md. agent_usage_copilot { agentId, docker, account } -> same AgentUsage, read from the copilot-user-cache.json copilot writes in the platform cache dir on every run (// comment lines stripped, newest retrievedAt entry wins). No spawn, no token: the endpoint behind it needs the OAuth token copilot keeps in the Keychain. The quota is MONTHLY and filed under session; the bucket is premium_interactions where it has a cap, else chat (a Free plan). Docker answers an error.

  • Context window (the chip's ctx gauge): every agent but devin PUSHES it over the OSC channel (docs/agent-hooks.md "The context window, per agent"). agent_context_devin { agentId, account, sessionId } -> { usedTokens, windowTokens } | null is the one pull: devin has no live source, so TerminalPane asks on the turn's 133;D. One sqlite3 -readonly query against cli/sessions.db (the session id is slug-checked before it is interpolated) plus devin models list --format json, cached per launch. null whenever a column is missing, never a guess.

  • Scripts: emit script-output://<wsId>:<kind> ({ line }) + script-done://<wsId>:<kind> ({ code, success }). kind in setup/run.

  • Settings/discovery: settings_load/settings_save/agents_save/discover_repos/detect_clis/list_monospace_fonts/list_font_families (async + spawn_blocking + a OnceLock filled by get_or_init inside the blocking closure, so concurrent callers share one scan). list_font_families is the unfiltered family list (installed-ness checks); list_monospace_fonts is the is_monospace() subset (picker extras) — the latter trusts the post-table isFixedPitch bit, so it misses real monospace fonts with sloppy metadata. On macOS the monospace probe is Core Text directly, NOT font-kit, whose family lookup copies a whole .ttc once per collection index it tries (an hour with an 830 MB SuperTTC installed; see gotchas.md "One big font collection made the font scan run for an hour").

  • Files: workspace_file_read (text, 2 MB cap) / workspace_file_write, workspace_file_read_base64 (async + spawn_blocking; images only by extension whitelist, 10 MB cap, takes known_fp and returns { unchanged, mime?, data?, fp } for the markdown preview's data: URLs — unchanged: true skips the read+encode when known_fp still matches, the fast path for agent-settle revalidation storms), workspace_path_stat ({ exists, is_dir }, tolerates a missing leaf so link-existence checks don't error — also accepts a path that's exactly a composition member's own root, via resolve_workspace_git_path_ex). task_file_fp is the same resolution with no read at all: it returns just the mtime:len fingerprint, so the PDF pane can tell a real rewrite from an agent-settle tick without pulling a 20 MB file through the IPC it doesn't need (the bytes go over the taskpdf: scheme). All of them are member-aware (resolve_workspace_git_path) and worktree-contained (safe_workspace_path for an existing target, check_workspace_path_existence when the target may legitimately be missing); both file reads run through read_capped_file (TOCTOU-safe: fstat on the open handle, not a separate path stat).

  • Linux desktop entry: desktop_integration_status / desktop_integration_add / desktop_integration_remove (all async + spawn_blocking; add/remove shell out to update-desktop-database, gtk-update-icon-cache and xdg-mime). They write ~/.local/share/applications/termic.desktop and a 256px icon under ~/.local/share/icons/hicolor/, which is what gives an AppImage a launcher entry AND a termic:// handler: macOS and Windows get the scheme from the bundle and the installer, an AppImage has no install step, so without this a deep link on Linux has nowhere to go. available is driven by $APPIMAGE (absolute and still on disk), NOT by target_os, so a .deb, a dev build and every other platform answer available: false through the same path rather than the command being absent; src-tauri/src/linux_desktop.rs compiles everywhere on purpose so its desktop-entry format tests run on the machine they are written on. integrated is re-read from the filesystem on every call and never cached: the user can delete the entry and Gear Lever or AppImageLauncher can write one. The entry carries X-AppImage-Integrate=false so those tools do not add a second one. It does NOT move the AppImage: Exec= points wherever the file already is, and moving someone's file (and then having to rewrite the entry to match) is AppImageLauncher's job, not ours.

  • Forge rate ledger (forge_rate.rs, forge::gh_api): forge_rate_status { probe } (async + spawn_blocking) -> RateStatus[], one per GitHub host: buckets (graphql, core), each with GitHub's window (limit/remaining/used/reset_at, account-wide, so it includes agents and the user's terminal; null when unknown or past its reset), termic's own spent / estimated / cap for the last hour and by_feature, plus paused ({ until, kind: "limited" | "floor" | "budget" }, worded by the webview) when background polling on that host is held. probe: true first seeds hosts with no current window from GET /rate_limit, which does not count against the primary limit. Every change also arrives as termic://forge-rate-changed with the same payload, throttled to one per 2s except when any host's pause starts, ends or moves, which always goes out. New GitHub reads go through forge::gh_api / gh_graphql (gh api --hostname H --include), which feed the ledger from the headers and the GraphQL rateLimit object, and refuse without spawning while GitHub's own refusal stands (plus termic's budget for background calls); the older gh pr / gh issue calls report no cost and are charged as 1-point estimates (not when gh failed on auth, since nothing was sent). A lookup GitHub refused answers status rate-limited (PR card, issue and PR pickers, Todos lists) with retry_at (epoch seconds, that host's), which the webview words itself (lookupMessage in forgeRate.ts) rather than showing Rust's English message; retry_at is null on every other status. A pulled forge_rate_status that resolves after a pushed event is dropped. Budget rules: performance.md.

  • Batched forge reads (one GraphQL query per GitHub host instead of one gh subprocess per task or per project; budget in performance.md): task_pr_status_batch { ids } (async + spawn_blocking) -> (PrLookup & { id })[], always background work. A GitHub task whose record has a PR url joins one aliased repository.pullRequest query per host (forge::PR_BATCH_MAX = 50 per query); a closed PR, a task whose live branch is not the PR head (forge::branch_matches_pr, which also accepts the pr-<n> / pr-<n>-<head> fork checkouts), a PR the query cannot see, and every non-GitHub task take the per-task pr_lookup_at. A host whose gate closes (checked per chunk, inside gh_api) is skipped from there on and its tasks left OUT of the answer, so the caller keeps its entry. A missing CLI or signed-out gh answers each task with cli-missing / cli-unauthed; any other failure leaves the chunk out for a pass and, if it fails again, falls back per task within that budget. An open PR whose head is not the task's branch is looked up by branch at most every three minutes per task (else the batch's answer stands). The webview drops a batch answer that lands behind a refresh in flight or one that landed since, and keeps a good lookup over an error / rate-limited answer while still stamping the attempt (batchLanding). Every per-task lookup a pass starts shares one budget of eight, and each task gets one at most every three minutes, so a PR the query cannot see (deleted repo) does not cost a subprocess every pass; an answer whose url is not the PR asked is not trusted. task_pr_status { id, background }, task_member_pr_status { id, background } and task_pr_comments { id, background } take background as REQUIRED, so a new caller has to choose; with it set they answer null without calling anything while the task's (or any member's) GitHub host is paused (forge::background_held). The TS side has taskPrStatusBackground / taskMemberPrStatusBackground / taskPrCommentsBackground for the pollers; the plain wrappers send background: false. The identity is persisted exactly as task_pr_status does (persist_pr_identity). project_forge_lists { queries: { projectId, kind: "issues" | "prs", scope, limit }[] } (async + spawn_blocking) -> (IssueLookup | PrPickList)[] in queries order, each answer shaped for its own kind: GitHub lists on one host go out as queries of up to forge::LISTS_BATCH_MAX = 30 lists (forge::github_lists; repo-wide lists as repository aliases, personal ones as search aliases with repo: qualifiers chunked under GitHub's 256-character limit, split back out by nameWithOwner and capped at each list's limit), the rest (GitLab, Azure, no forge, a limit over 100, an owner or repo outside GitHub's [A-Za-z0-9._-] charset, or a failed GitHub query) take the per-project path on three threads, except a query GitHub refused on a limit, whose lists (and the host's later chunks) each answer rate-limited, and a query past the output cap, which is split in half and asked again (one list still too large answers error). forge::tests::live_github_batch_queries_parse is an ignored test that runs both queries against the signed-in gh.

  • Change summaries: task_diff (async + spawn_blocking) returns the whole unified diff plus its counts, for the compare view. task_diff_stat returns the COUNTS ONLY and is what a list view must use: task_diff also ships the full diff text and spawns one git diff --no-index per untracked file, so a board polling every visible card would fork that many processes on a timer. The lean one runs exactly two git processes per repo (a --numstat against the merge-base, and one ls-files --others) and counts new files' lines by READING them, skipping binaries (a NUL in the first 8KB, git's own probe) and anything over 2MB. That line count is therefore an estimate and is documented as one at every layer: a file with no trailing newline is one short. The file counts are exact. Multi-repo tasks sum the host worktree and every WORKTREE member; a repo_root member is the project's live checkout, shared with every other task and with whatever the user is doing by hand, so counting it would attribute someone else's uncommitted edit to an agent. Consumed through src/store/diffStat.ts, which is demand-driven rather than a poller (see docs/ui.md).

  • Pasted images: clipboard_image_save (async + spawn_blocking) takes the image bytes as the raw request body (invoke(cmd, uint8array) → tauri::ipc::Request / InvokeBody::Raw), not as a JSON array of numbers, which for a 3 MB screenshot is the difference between one copy and several million. It sniffs the format from the MAGIC BYTES (PNG/JPEG/GIF/WebP) rather than trusting a caller-supplied extension, writes pasted-<unix>-<8 hex>.<ext> into $TMPDIR/termic-attachments/clipboard/ (attachments_dir, shared with dropped-file staging, and NOT the data dir, which Seatbelt denies outright), prunes anything there older than 7 days, and returns the absolute path. It exists because an image paste cannot reach an agent any other way: xterm.js sends only text down the PTY, and in Docker mode the agent is a Linux process whose clipboard reader shells out to xclip/wl-paste with no route to the Mac's pasteboard. TerminalPane's capture-phase paste listener PASTES the returned path in the image's place (via term.paste(), so it arrives bracketed and claude reads the file into a real [Image #N] attachment instead of echoing a path), backslash-escaped by the same shellEscapePath a dragged-in file uses. It fires for DOCKER tasks only: everywhere else the agent reads the Mac clipboard itself and already gets the real image. Docker mounts that directory READ-ONLY at the identical absolute path, so the pasted string resolves inside the container.

  • Clipboard image, ctrl+V: clipboard_image_capture (async + spawn_blocking) reads the image off the MAC's pasteboard itself (tauri-plugin-clipboard-manager's read_image, off the main thread per its own deadlock warning), re-encodes the raw RGBA it returns as PNG (encode_rgba_png, refusing a buffer shorter than the advertised dimensions) and stores it through the same save_clipboard_image. It exists because ctrl+V is not a paste event: on macOS it is byte 0x16 travelling down the PTY, and it is the gesture claude binds its own image-attach action to - which inside a container can never work. Called ONLY for Docker tasks, and a clipboard holding no image is an ordinary rejection: TerminalPane forwards the original 0x16 to the agent so a text ctrl+V behaves exactly as before. Reading the pasteboard in Rust rather than via navigator.clipboard needs no webview permission and no user gesture.

  • Scratchpads (GH #244, untitled buffers scoped to one task): scratch_list ({ taskId } → ScratchRecord[], ordered), scratch_read, scratch_write (create-or-overwrite the buffer, stamp updated_at), scratch_set_meta (index-only; every field optional so the debounced title derivation cannot race a syntax pick into a stale value, and syntax: "" clears a manual pick), scratch_delete, scratch_promote, scratch_promote_target_exists. All async + spawn_blocking.

  • Shared scratchpads (GH #385, the project / profile / global trees in data-model.md): every command takes { scope, projectId, rel }, where scope is task | project | profile | global and projectId carries the id that scope needs (the project id, the profile slug, or the task id; unused for global). An unknown scope is an error, never a fallback to the task. scratch_tree_list (one directory level → FileEntry[], symlinks left out), scratch_file_read, scratch_file_write, scratch_file_create, scratch_path_rename, scratch_path_delete, scratch_path_reveal, and the two that cross into the worktree, scratch_copy_to_workspace and scratch_copy_from_workspace. All async + spawn_blocking. rel goes through reject_escaping_segments before it is joined, because on Windows a rooted (/etc/passwd) or drive-relative (C:foo) path is not is_absolute() and join still replaces the base.

    Buffers live under <data_dir>/scratch/<task_id>/, never inside the worktree: a scratch file in the repo shows up in git status, in the diff the agent reviews, and eventually in a commit. The index carries the title and syntax because a pad has no filename to re-derive them from on launch. A SCRATCH_LOCK mutex serializes each index read-modify-write — the buffer write and the title derivation are debounced independently on the typing path, so two writes genuinely can interleave.

    scratch_promote is ONE command on purpose. It reads the buffer, resolves the target through the same resolve_task_git_path + containment pair every other write uses, writes it, and only then deletes the pad (a failed write leaves the pad exactly where it was). Doing it as "read here, write there" from TypeScript would re-implement that containment rule in the one place it must not be re-implemented. It refuses an existing target unless overwrite, which is what scratch_promote_target_exists exists to ask first.

    Containment for a target that does NOT exist yet is safe_task_path_for_create, not safe_task_path: the latter canonicalizes the target itself and so errors on a missing file. The new helper walks up to the nearest existing ancestor, canonicalizes and contains-checks THAT, then rebuilds the target underneath the canonical ancestor — so a member symlink is resolved before the remainder is appended and the write lands where the check looked.

    Ids from the renderer become path segments here, so both the task id and the pad id go through scratch_id_ok ([A-Za-z0-9_-], ≤128). Refused, never sanitized: a silently rewritten id reads a different pad than the caller asked for.

    termic scratchpad list|new|write|read|rm|clear (alias pad) (wire pad_list / pad_new / pad_write / pad_read, protocol v13; pad_remove / pad_clear, v20) let an agent keep notes for the human, and tidy them up. rm deletes one pad and clear every pad list shows for the same target; both close the pad's tab FIRST, wait for any write already on its way to disk, and only then delete, because a mounted editor flushes its buffer on a debounce and on unmount and would write the file straight back (the same trap as GH #244's Discard). The user gets one toast saying what an agent removed. MCP: scratchpad_remove / scratchpad_clear, both destructiveHint. The server only resolves the task (handle_pad, which also refuses an archived one) and forwards the op as ONE webview RPC, pad, handled by lib/scratchCli.ts. The webview owns it because an OPEN pad's truth is its CodeMirror buffer, not the file: EditorPane reads a pad once, and the file lags typing by the flush debounce. Open pads register in lib/scratchLive.ts; a write to one is dispatched INTO the buffer (it shows at once, Cmd+Z undoes it) and flushed immediately, and a read comes out of it. A closed pad is plain scratch IPC. pad new opens its tab with focus: false only when the task's tabs are loaded; otherwise restoreScratchTabs picks it up on the next open. A --title sets customTitle, so the agent's later text does not retitle a pad it named. Selectors are a pad id, or an exact title that must be unique. Pads are EXCLUDED from MCP (mcp_server.rs): they are notes for the human in the window.

  • Scheduled queue messages (GH #300): task_set_tab_scheduled ({ id, tabId, items: ScheduledMessage[] }) overwrites one durable tab's scheduled list, searching persisted_tabs then right_split_tabs; a tab not yet persisted is a silent no-op, and an unchanged list writes nothing. The frontend always sends the full set, from syncScheduledMessages in the app store, after every add, remove, clear and delivery. task_set_tabs / task_set_right_tabs never take scheduled from their payload.

  • Recurring schedules (GH #300, src-tauri/src/schedules.rs): task_set_schedule { id, schedule | null } overwrites Task.schedule with the whole record and writes nothing when it is unchanged (the runner calls it once per slot it acts on, never on an idle pass). It validates at the boundary (slug [a-z0-9-], HH:MM, a weekday for weekly, a real calendar YYYY-MM-DD date for once (2026-02-30 is refused, not rolled into March), 1-20 runs kept, a prompt), refuses a slug change and a slug another schedule in the project owns, and refuses to CREATE a schedule on a Docker task; a parent switched to Docker later keeps its record so the runner can record why its slot failed. The first set creates the report folder and the exclude line (schedules::ensure_report_dir, which resolves the repo root with git rev-parse because a project need not be it, and refuses a symlinked .termic or schedules). schedule_prune_reports { projectId, slug, before } deletes reports dated before before, a LOCAL YYYY-MM-DD the caller computes so local time lives in one place; schedule_delete_reports { projectId, slug } deletes all of them and then the folder if nothing else is in it. Both return the names deleted and share the rules in Rust, not the caller: a canonical folder under <project>/.termic/schedules/, only YYYY-MM-DD_HHMM.(md|html) regular files directly in it, never a symlink, never by mtime. schedule_report_status { projectId, slug, stem } -> { path, title } says whether a run wrote its report (.md wins over .html) and reads its first heading or <title> from the first 64 KiB. All four are async + spawn_blocking, and none takes a path: the folder is derived from the project record. task_archive takes skipScripts, which only the runner passes when it archives a run past keep_runs (or when archiving a deleted schedule's parent and runs): the project's archive script (or a multi-repo member's) would otherwise run in the live checkout every morning. See docs/ui.md "Scheduled tasks".

  • Git history (issue #199, the Graph section of the right panel's Git tab): task_git_log ({ id, dirName, skip, limit, allBranches, firstParent, grep, refs } → GitLogPage { commits, has_more, branch, upstream }) is one git log --topo-order per page; it asks git for limit + 1 rows and drops the extra, which is how has_more is known without a second walk. Commit fields are US (0x1f) separated and RS (0x1e) terminated — a subject can hold anything but a newline, so newline-delimited parsing loses records. task_git_commit_files ({ id, dirName, sha } → GitFile[]) runs diff-tree -m --first-parent --root so merges and the initial commit report files instead of nothing. task_file_diff_sides takes scope: "commit:<sha>" for a historical diff (sha^ vs sha, no working-tree side). Every revision argument goes through is_commit_ish (hex only): the graph never passes a user-typed ref, so anything else is a bug or an injection attempt.

    Scope: allBranches is --all and wins over everything; otherwise refs names what to walk (the picker's multi-select) and an empty list means HEAD alone. refs is an ALLOWLIST check, not a syntax check: allowed_refs keeps only names git_refs actually enumerated, so a caller-supplied string can never reach argv as a flag (--upload-pack=…) however it is spelled. A scope whose refs have all been deleted returns an empty page rather than falling back to HEAD, which would answer a different question under the old scope's label. grep is --grep plus --regexp-ignore-case --fixed-strings: FIXED strings because it is fed by a filter box, where [ is a character someone typed and a half-written regex must not become an error mid-keystroke; it is glued into one --grep=<q> argv element, so the query cannot be read as a flag. It narrows the active scope rather than replacing it. firstParent is a separate axis from the ref list: it adds --first-parent so a merged side branch collapses into its merge commit, and is ignored under allBranches (where seeing every tip is the point, and pruning the topology would draw tips with no path to them). task_git_refs ({ id, dirName } → GitRef[] { name, sha, kind }) is what the picker lists and what that allowlist is built from; origin/HEAD is dropped because it is an alias for another entry.

  • Blame (the editor's cursor-line annotation): task_git_blame ({ id, path } → BlameFile { commits, lines, head, skipped }) is git blame --root --incremental over the WHOLE file, once, async + spawn_blocking (~200 ms on a 15k-line file). Three things about the payload are load-bearing:

    • --incremental, not --porcelain. On this repo's own lib.rs (15,742 lines) --line-porcelain is 7 MB and --porcelain is 1.6 MB, because both echo the file content back; --incremental emits headers only and is 433 KB. It also repeats a commit's header block only on that commit's FIRST group, which is the dedupe already done for us.
    • The wire shape is a commit table + one u32 per line, not a record per line: 169 commits and 63 KB of indices for that same file. This crosses into a WKWebView, so the shape is the difference between instant and janky.
    • It blames the WORKING TREE (no rev argument), so git itself attributes uncommitted lines with the all-zero sha (BlameCommit.uncommitted) and the line numbers already match the file on disk. VS Code instead blames at a sha, which makes its cache immutable, and maps the cursor's line back through a live quick-diff model; we have no such model, and this trade avoids needing one. The cost is that the frontend cache is invalidated by writes (save, external reload, any gitRevision bump) rather than never.

    Files over BLAME_MAX_BYTES (2 MB) come back skipped: true with empty data, which is a distinct signal from "no blame here" (untracked file, or not a repo) so the UI can stay silent rather than look broken. Neither is an error: an untracked file legitimately has no history. That cap deliberately mirrors task_file_read's own text cap instead of inventing a second policy, and it is one metadata call: the index length comes from git's own line numbers, so nothing re-reads the file to count newlines (and a file rewritten between two reads cannot produce an index that disagrees with the blame).

  • One commit's detail: task_git_commit_meta ({ id, path, sha } → GitCommit) is git log --no-walk with GIT_LOG_FORMAT, the SAME format constant and parser task_git_log uses, so the blame popup and a History row cannot describe one commit differently. Async + spawn_blocking. Fetched when a blame hover card opens (cached per sha on the frontend), never as part of the blame payload: a file's blame can name 169 commits and the reader hovers one. sha goes through is_commit_ish, so only hex reaches argv, and path resolves the repo member-aware exactly as blame does.

  • Locating one commit: task_git_commit_offset ({ id, dirName, sha } → usize) is rev-list --count <sha>..HEAD, i.e. how many commits are newer, which is exactly the skip the history page needs to land on it. It exists so "show this commit in History" is one query rather than paging forward until the sha appears: on a monorepo the target is tens of thousands of rows down. is_commit_ish guards the sha, and a commit not reachable from HEAD is an error rather than 0 (which would scroll to the top and look like success).

  • Push: task_git_push ({ id, dirName }) pushes the repo's current branch without committing, for the Push button beside Commit. It shares git_push with task_commit's push flag, so the set-upstream fallback (push -u <remote> <branch> when a plain push fails on a fresh worktree branch) cannot differ between the two. GitRepo.ahead (rev-list --count @{upstream}..HEAD, 0 with no upstream) is the button's badge.

  • Branch compare (issue #208, the Compare sub-tab of the right panel's Git tab): task_git_compare ({ id, dirName, base, mergeBase } → GitCompare) is everything differing between a ref and the WORKING TREE, in one list: git diff --name-status -M -z for the glyphs, --numstat -M -z for the churn, and ls-files --others for untracked paths git's diff cannot see. Both diffs are -z because a path may contain any byte but NUL, and a rename's record carries two paths (the destination is the one kept, being the one git show <sha>:path resolves). mergeBase: true (the default) diffs from merge-base(base, HEAD) rather than the ref's tip, so commits the base gained after the branch point do not render inverted as deletions. Unlike the graph, a user-typed refname DOES reach git here, so base goes through resolve_rev → is_safe_rev (no leading dash, no rev syntax, no glob) plus --end-of-options, and is resolved to a sha ONCE: everything downstream, task_file_diff_sides' scope: "base:<sha>" in particular, stays hex-only under is_commit_ish. That scope reads the base commit against the live file, which is why Compare keeps the review affordances a historical diff has to drop. The base picker lists task_git_refs (above), which already includes remote-tracking refs and tags.

  • Profiles (GH #280, see profiles.md): profiles_list -> { profiles: ProfileView[], current: string | null }, scoped to the CALLING WINDOW (current is this window's slug, and null means no profiles exist, which is what the sidebar keys "show no strip" off). profile_create { args } (creating the FIRST profile also adopts the install that already exists, in the same write), profile_update { slug, name?, accent? } (the SLUG is never touched: it keys both trees and CWD-resume agents key sessions to the working directory), profile_open { slug } (focus the window or build it, one action either way), profile_delete_preview { slug } -> counts (async + spawn_blocking: it runs git status and rev-list per task), profile_delete { slug, deleteWorktrees } (async + spawn_blocking; REFUSED while the profile's window is open), profile_close { slug } (which is why that refusal is actionable: the window may be on another Space, so the dialog offers a button rather than an instruction; refuses to close the CALLING window, which is the red button's job), and profiles_disable (stop using profiles keeping every byte of data, which is a DIFFERENT operation and has to be: a delete is refused while the window is open and the last profile is always the one you are in). Emits termic://profiles-changed as a genuine broadcast: every window's strip has to learn.

    Two commands take window: tauri::Window, and they are the ONLY two that need to: projects_list (which profile does this sidebar show) and project_add (which profile does a new project join). Everything else resolves the profile from the record it is already holding — see profiles.md, "the profile rides the data, not the call". deep_link_take_pending and tray_set_attention also take a window, for routing rather than for data.

    Task-keyed events are emit_to, not emit. pty://, pty-exit://, pty-sudo-touchid://, setup-*://, script-*://, grep-*:// and spotlight:// all route to the window owning the task; a broadcast would hand every profile's webview every other profile's PTY bytes. The three pty*:// topics carry a PTY id and grep-*:// a per-keystroke search id, neither of them a task id, so pty_spawn and task_grep_start resolve the label once from the task they already hold and emit with emit_to_window (the hot path does no disk IO). The rest go through emit_scoped, which parses the task id out of the topic and memoizes the answer, misses included; save_task seeds it. An unresolvable id falls back to a broadcast, deliberately. Why the split matters: performance.md bear trap 12.

  • Agent accounts (GH #278, see agent-accounts.md): agent_accounts { agentId, docker } -> the account list for one agent plus supported (false when nobody has measured how to relocate that agent's login, in which case the UI must not offer a second account) and envIsSharedRoot (opencode and muse ride a GENERIC variable other tools read). account_add, account_remove, account_set_default, account_set_label { agentId, name, label } (display only; the name never changes, "" clears), and task_set_account { id, agentId, name } which is the switch. Each AccountView carries name (identity) and label (what to show). All LOGIN verbs: none takes a path, because where a login lives is derived from the account's NAME and never stored.

    The chosen account is applied in pty_spawn, not by the frontend, so every spawn path gets it (UI, CLI, MCP) and none can forget. A Docker spawn takes the Docker realm, since its container reads a directory termic mounts rather than the host's config dir. A switch lands on the NEXT spawn: a running process cannot have its environment changed underneath it.

  • Config sync (config_sync.rs, phase 1 of ideas/config-sync.md): every command is async + spawn_blocking and every clone-touching one serializes on SYNC_LOCK. The window always passes prefs: PrefsSnapshot ({ shared: {key: value}, scoped: {ns: {key: value}} }, the registry's "sync" keys read from localStorage by src/lib/configSync.ts, ns being a profile's localStorage namespace: "" for the root profile, profile-<slug>: otherwise) because Rust cannot read localStorage. sync_status -> SyncStatus (connected, repo URL, machine name, last sync / error, this window's ns + sync_id + folder name, bound profiles for the snapshot, conflicts, waiting, skipped, removals, safety notices). sync_connect { url } clones into sync/ (or reuses this machine's clone of the same URL) -> { url, empty, folders }. The URL must be https://, http://, ssh://, git://, file:// or scp-like user@host:path (config_sync::check_repo_url, the authority): anything else, ext:: / fd:: remote helpers and a leading - above all, is refused before git runs with an error starting Unsupported repo URL., a prefix SyncSection.tsx matches to show its translated text (a test pins the two). The clone passes -- before the URL. sync_preview { folder, prefs } -> Change[], a dry run of the first connect that writes nothing. sync_bind { folder, prefs } binds this window's profile to an existing folder or a new one (folder: null) and runs its first sync. sync_now { prefs }: export, commit, fetch, rebase, apply, push. sync_launch_pull { prefs }: the same (with push), once per process (the first window to ask after first paint; later calls return skipped). sync_focus_pull { prefs }: the same (with push), when the window regains focus and the later of SyncState.last_pull_at and last_sync_at is at least five minutes old. Rust decides under SYNC_LOCK, so a second window's call returns skipped. An outstanding conflict returns skipped with conflicts set and does not fetch. A failed run still writes last_pull_at (set at the start of run_core), so an offline machine does not fetch on every focus. sync_resolve { path, choice: "local" | "remote", prefs } records a choice per conflicting file and settles them all once each has one. sync_locate { projectId, path }, sync_skip { projectId, skip }, sync_keep { projectId }, sync_dismiss_notices, sync_disconnect. The run commands return SyncRunResult { ok, skipped, pushed, changed_profiles, prefs: { shared, scoped }, themes_changed, changes: Change[], conflicts, error }: prefs is what the window writes to localStorage (only keys whose stored value differs), changed_profiles the namespaces whose projects.json / settings.json changed. They emit termic://sync-changed ({ profiles, themes }) so every window reloads. Network ops (clone, fetch, push) go through config_sync::git_bounded: -c protocol.ext.allow=never -c protocol.fd.allow=never whatever the user's git config says, GIT_TERMINAL_PROMPT=0, batch-mode SSH, and a deadline enforced by a waiter thread plus recv_timeout, never a sleep poll. Profiles follow the repo: a run creates a local profile for each folder nobody here follows and uploads each unlinked local profile (adopt_profiles; the rule is the pure plan_adoption), and SyncRunResult.profiles_changed makes the caller emit termic://profiles-changed and rebuild the tray. SyncStatus adds opted_out, suggested_folder (the same-named folder an unlinked profile is waiting on) and ignored (folders whose profile was deleted here); sync_restore_folder { folder, prefs } takes one off that list and runs a sync, which recreates it. sync_disconnect leaves the profile opted out while others still sync. Change.kind gains profile with actions add, upload and update.

  • Secrets + broker (secrets.rs, broker/; see sandbox.md "Credential broker"): no command returns a secret's value. Secrets and roles save through settings_save, which refuses (errors joined with ; ) anything secrets::validate rejects, e.g. two secrets of one role on the same host, a host that is not a lowercase DNS name, a rule with no method or an empty non-QUERY pattern, or a recipe / kind from a newer build (parsed as unknown rather than failing the whole file). It validates only when secrets or roles differ from disk, so a stale invalid entry cannot block unrelated settings. secret_probe { id } (async + spawn_blocking: the first read of an item can sit on macOS's "Termic wants to access" prompt) -> SecretStatus ({ status: "readable" | "locked" | "missing" | "denied" } or { status: "error", detail }). secret_store { id, name, value } (async + spawn_blocking) -> "protected" | "generic", the KeychainKind it wrote: a pasted value goes in as the Termic-owned generic password termic:<id> / termic, labelled Termic: <name>, in the data protection keychain, or the login keychain on a build without the entitlement (-34018, and only that error), then the other store's copy is deleted; write-only, refuses an empty, over-16 KiB or control-character value and an id outside [A-Za-z0-9_-]{1,64}. The caller saves the secret with the returned kind. secret_forget { id } (async) deletes the owned item for id from both stores only when no saved secret has that id (the add dialog's cleanup when the store worked and settings_save did not); Ok(()) either way, never reads a value. secrets_protected_available (async) -> bool, whether this build can use the data protection keychain (one query for an item that never exists, -34018 means no; cached for the process). settings_save deletes the item of an owned secret it drops, from both stores (off the IPC thread). secrets_gh_accounts (async) -> { host, user, active }[] from gh's hosts.yml (GH_CONFIG_DIR, else $XDG_CONFIG_HOME/gh, else ~/.config/gh, checking the login-shell delta too), both the multi-account users: layout and the old single user:; an --insecure-storage oauth_token in the file is never deserialized, and a parse error does not echo the file. secrets_exposed (async) -> { agent_id, var_name, prefix }[], real-looking tokens (ghp_, gho_, ghu_, ghs_, ghr_, github_pat_, sk-ant-, sk-proj-, sk- plus 20+ token chars) typed into any agent's env / docker_env; prefix is the type prefix only. Termic's OWN environment is the kept-out list's (sandbox.md "Env vars kept out of agents"): env_guard_list (async) -> KeptOut[] ({ name, reason: "builtin" | "detected" | "added", set, all, preset: "github" | "openai" | "anthropic" | null, own_login_of: [agent id] }, names only, never a value), env_guard_save { rules } (async; rules is the whole Settings.env_guard list, refused on a bad or duplicate name; read-modify-write, returns the fresh list), agent_set_pass_env { agentId, names } (async; one agent's pass_env, read-modify-write; the agent card saves it through agents_save instead). task_set_role { id, role } (async; role an id or "" for No secrets; null also reads as No secrets, defaults are never consulted after creation) refuses a role id unless the task's Keychain block applies (Task::keychain_blocked) and the role exists; applies on the next spawn, no PTY kill. Every id a broker_* command takes is a broker key: the task id for its agents, shell:<task_id>:<tab_id> for a shell running a role. broker_counts { id } -> BrokerCounts (foreign_token: the part of suspicious that is gh sending its own token on the socket; roles: the distinct role ids live spawns run; stale: a live spawn's role, as saved now, binds other secrets than the spawn started with, so it needs a restart; one settings read per call while a spawn is live), broker_events { id } -> BrokerEvents (Used and Blocked rows carry role, the spawn's role id), broker_all_events -> [taskId, BrokerEvents][], broker_set_paused { id, paused } (live, no restart; a task's pause also covers its shells' keys) are thin wrappers over broker::. broker_allow { id, scope, secret, host, rule, role } (async; id is the broker key the row came from, and a shell's only takes scope: "role"): the rule must be an allow with a method and a pattern, for a secret bound to host; scope: "task" appends to Task.secret_allows, scope: "role" puts it first in role's rule set for (secret, host) (required: the blocked row's role, so it lands on the role the spawn runs; a missing set is created with the role's default as fallback) and saves settings, so every task on that role gets it. Either way the blocked rows it covers are cleared. broker_unallow (same arguments and checks) is its undo: it drops that exact rule again from the task's allows or the role's set, judged from the next request. secrets_test_request { role, secret, host, method, target } (async + spawn_blocking; reads settings once, only for the secret's recipe) -> { effect: "allow" | "deny", rule_index: number | null, from_fallback: boolean, detail }: the role editor's request tester. It judges the role it is passed (the editor's copy, not the saved one) with rules::trace, the same walk rules::evaluate runs for the broker, with no task allows. method is an HTTP verb (then target is path[?query], normalised and classified as git / GraphQL like a real request for that recipe; a POST /graphql has no body, so it judges as an unparsed mutation) or a pseudo-verb built straight into the op: QUERY, MUTATION <name>, fetch <owner/repo>, push <owner/repo>. rule_index indexes the (secret, host) set's rules; from_fallback means no rule matched and the set's fallback (or, with no set, the role default) decided; neither means TRACE / TRACK / CONNECT (always refused) or an unnamed mutation. Rejects a line it cannot judge (no method, a non-token method, MUTATION or push with no target). The role coupling is enforced in Rust too: task_set_sandbox, task_set_docker and every create path drop a role id once the Keychain block no longer applies, and a create path given no role seeds it from the project's default, else the primary agent's, else "" (seed_task_role).

  • Misc: notify, open_path (handles URLs via macOS open), home_dir, path_exists, log_line.

  • Opening a web link (GH #245): open_external_url ({ url, browser } → { used, reason }) opens a URL in the browser the user configured, where browser is a COMMAND TEMPLATE the frontend has already resolved (resolveBrowserCommand in src/lib/previewBrowser.ts owns the project-overrides-global precedence, and is where its tests live). An empty template takes the OS-default path, byte-identical to open_path, so an unconfigured app behaves exactly as it did before the setting existed. used is "default", "browser" or "fallback", and a fallback carries the reason so the UI can say why instead of leaving a dead link.

    The template is tokenised by split_browser_command and spawned as argv — never through a shell. This is load-bearing, not stylistic: a shell would re-split a preview URL like http://localhost:3000/?a=1&b=2 on the unquoted &, which is the same bug the open_command comment documents for cmd /C start, and the one Debian's eval-based $BROWSER actually has. {url} is substituted if present, otherwise the URL is appended as the final argument.

    Launch failure is detected by watching the child for BROWSER_WATCH_MS (500ms). A launcher that is going to fail does so immediately (open -a "Nonexistent" exits 1 in milliseconds), while a browser that took the URL either exits 0 at once or lives for the whole session — so the bounded watch separates them without ever waiting on a real browser. It runs on spawn_blocking, and is a single wait per user click, NOT the steady-state sleep-poll that docs/performance.md bear trap 9 bans.

  • Opening a folder in another app: open_with_apps (no args -> ExternalAppInfo[], i.e. { key, label, kind } per detected app in menu order) backs the title bar's picker; open_with_app ({ key, taskId }) opens that task's worktree root in it. Both async + spawn_blocking: macOS is a handful of stats, but the Linux branch walks shell_env::resolved_path() and can block for hundreds of ms while the first login-shell probe lands. Not cached, because it is one call behind a user click and a OnceLock would hide an app installed since launch.

    The webview is told a KEY and nothing else. It never sends a path, an app name or an argv: open_with_app takes the TASK ID and resolves the directory itself from the task record, the same discipline task_reveal_path follows and for the same reason (the webview sits outside the sandbox, see sandbox.md "Known gap"). open_with_argv additionally refuses a directory that is not absolute on the TARGET platform (C:\ or a UNC path on Windows, / elsewhere), because open reads a leading - as a flag. That check takes os rather than calling Path::is_absolute, which reads cfg(windows) instead of an argument and so cannot be driven per-OS from a Unix runner: the first version of this guard was starts_with('/'), which rejected every Windows worktree path while every Unix test stayed green. A conformance test pins the hand-rolled form against Path::is_absolute on whichever platform runs the suite. The app table (EXTERNAL_APPS) is the single source of keys, labels and grouping; the frontend substitutes its own FILE_MANAGER constant for the file-manager row's label so "Finder" vs "File Manager" keeps one definition (src/lib/openExternal.ts).

    Detection is Path::exists on candidate .app bundles, which is the only /Applications probe in the tree, and the choice is deliberate: a PATH lookup like detect_clis uses would report most installed editors as missing, since code and cursor are opt-in shell commands the user installs from inside the app and Warp, Terminal, iTerm2 and Ghostty ship no folder-opening CLI at all. Linux has no bundles and so does use the PATH walk. Windows returns the file manager alone (registry work, unmeasured). Launch is open -a <bundle path> <dir> with no -n: reusing the running instance is what "open this folder in Cursor" means. Resolution returns the FULL path to launch, never a bare binary name: Command::new would then search the host process's PATH, which for a GUI-launched app is much shorter than the login shell's, so an editor in ~/.local/bin would be listed in the menu and fail on click.

    A real app's launch goes through run_browser_argv's bounded watch (GH #245's launcher policy, named for its first caller and deliberately shared): a launcher that will fail exits non-zero within milliseconds, while one that took the folder either exits 0 at once or lives on. status() would instead block a spawn_blocking thread for as long as the editor stays open, since not every editor binary detaches. The file-manager entry keeps open_path's policy of ignoring exit status, which is not laziness: explorer exits non-zero on SUCCESS (see open_command) and Windows offers no other entry, so reading it there would report failure on every open. Err when the key is unknown, its app has gone away, or the launcher failed, which is what lets the frontend revert the remembered pick instead of leaving a dead button.

    The path is always the HOST worktree, in every sandbox mode including Docker. The app launched is a host GUI application, so there is no container-realm counterpart to build: a container has no Cursor to open.

    Under --features e2e both halves are stubbed, and they differ: open_with_app records <key>\t<dir> to e2e-open-with.log (its own file, not e2e-opened.log, which the file-tree specs assert line-for-line) and open_with_apps returns a FIXED three-entry list, because the CI runner has no editors and a spec keyed on real detection would assert an empty menu. Real detection is unit-tested with an injected exists predicate instead.

  • Validating a browser command: browser_command_check ({ command }) rejects an unparseable template or a launcher missing from PATH, for the Settings field. It can only vouch for the launcher: open -a "Gogle Chrome" passes (because open exists) and still fails at launch, which is exactly why the runtime fallback above also exists.

  • LAN pairing (peers.md): peer_status (whole page state: sharing on, this machine's id / name / default name, listener port and ip:port addresses, bind and discovery errors, platform, peers, nearby (each with pairing: in pairing mode), pair_mode (this machine's code and deadline while it shows one); answers with sharing off too, for the paired list), peer_set_name { name } ("" = the computer's own name; re-announces), peer_pair_mode { open } (open:

  • peer_pair_request(target) → the other machine's name: asks it to open pairing mode and show its code (/pair/request). The first half of Pair; peer_pair(target, code) is the second. a fresh four-digit code for 5 minutes, and pair=1 in the advert; close: both end), peer_pair { target, code } (async + spawn_blocking: SPAKE2 start and confirm over the network with the code the other machine shows; resolves with the PairingView once both hold the pair, rejects with a readable reason), peer_rename { peer, name }, peer_set_grant { peer, grant } ("reply" / "drive"), peer_set_note { peer, note } (what it is for), peer_unpair { peer } (async: it sends the notice), peer_refresh (an mDNS query now). Events: peer://changed (no payload; re-read peer_status) and peer://pairing (a PairingView once per completed pairing, on both machines; the global dialog asks what the other machine is for). The setting itself, lan_sharing_enabled, rides settings_save, which binds or unbinds before it resolves (peers::apply_enabled).

termic:// deep links (GH #192)

A public integration surface: an external system (ticket tracker, internal dashboard, shell alias) drives Termic from a link. Two actions:

termic://new?project=web&worktree=1&name=fix-login&p=Fix%20the%20login%20bug
termic://open?project=web&task=fix-login

new (pre-fills the New Task dialog):

param meaning
project required. Registered project, by id or by name (case-insensitive).
name task name (max 200 chars)
prompt / p first message, pre-filled into the dialog (max 8000 chars, counted after decoding)
agent / cli agent id to pre-select; ignored if this install doesn't offer it
mode worktree or main. worktree=1 is the shorthand. On a multi project main is the host-level shape: the live host checkout with every member linked in, the same task the sidebar quick menu's Main checkout creates.
base "Branch from" ref

open (selects an existing task):

param meaning
task required. Live task, by id or by name (case-insensitive). Archived tasks don't match.
project optional scope. A bare name matching in two projects is ambiguous, not a coin flip.

The rule that separates them, and that any future action must pick a side of:

Navigation is immediate, state change is a modal, destruction is not a link.

open only selects something that already exists, so it just happens. new never creates anything — it fills the form and a human presses Create. That is the whole security model for accepting a prompt: links are authored in the ticket tracker, so whoever can file or edit an issue (in many orgs that includes external reporters) controls the text. It is also why an unregistered project is a hard error rather than a fallback to "the first project" or a silent project add. Do not add an auto-create or skip-confirmation option. The same reasoning keeps a YOLO default (Settings → Sandbox) from applying to a link that carries a prompt: the dialog starts with YOLO unticked and says why (yoloHeld in NewTaskDialog.tsx, which also steps back when an issue fills the prompt), so text someone else wrote reaches an agent that still asks before it runs anything. The user can tick it.

Percent-encoding the prompt

prompt carries free text (a ticket body, a paragraph, newlines) through a URL query string, so it MUST be percent-encoded by whoever builds the link. Termic decodes it once, with the standard URLSearchParams rules, and never tries to repair a malformed value: there is no way to tell a truncated prompt from a short one.

Four characters decide whether a link survives, and all four are ordinary in ticket titles:

raw encoded if you leave it raw
& %26 everything after it parses as a NEW query param, so the prompt silently truncates
# %23 everything after it becomes the URL fragment and never reaches the app
+ %2B decodes back as a SPACE, so C++ arrives as C
newline %0A usually stripped by whatever hands the URL over

Space may be %20 or +; both decode to a space. % itself must be %25, or a literal %2 in the text will eat the next two characters.

Build the value with a real encoder rather than escaping by hand:

# shell
jq -Rr @uri <<<"$BODY"
python3 -c 'import sys,urllib.parse as u; print(u.quote(sys.stdin.read(), safe=""))'
`termic://new?project=web&p=${encodeURIComponent(body)}`   // NOT encodeURI

encodeURI is the wrong function here: it deliberately leaves &, # and + alone, which are exactly the three that break a query value.

The cap is on the decoded text, not the URL. MAX_PROMPT_CHARS is 8000 characters after decoding, so a fully-encoded 8000-character prompt is a URL of roughly 11000 characters, and that is fine. Over the cap the whole link is REJECTED with a toast and no dialog opens, rather than being truncated, because half a prompt is worse than none: the user would have to notice the missing tail themselves. The value is also trimmed, so leading and trailing whitespace never counts toward the cap.

Templating gotcha. A tracker that expands {{issue.summary}} without a URL-encode filter hits the table above at the first & or #, turning Fix login & signup into Fix login . The confirm step is what catches this: the user sees the mangled text in the textarea instead of an agent acting on half a sentence. Template authors should apply the tracker's encode filter (Jira automation's .urlEncode(), and equivalents elsewhere).

A link that seems to do nothing at all is usually not the link. open still exits 0, nothing is queued, and [deeplink] queued never appears in termic-debug.log. Check that log line first, before suspecting the URL. Two causes:

  • The app updated itself under the running process. LaunchServices resolves the scheme to the bundle on disk, so the old process stops receiving links. Restarting the app fixes it.
  • make beta is installed. Both Termic.app and Termic Beta.app register termic://, deliberately: one link should reach whichever of the two is open, and they are mutually exclusive (shared data dir, shared socket, single instance). LaunchServices picks one bundle, and when it picks the one that is NOT holding the socket, that process raises the owner and hands the URL over rather than opening a second window. See "the macOS handoff" below, and handoff_deep_link_then_exit in lib.rs.

The macOS handoff. On Windows and Linux a link spawns a fresh process with the URL in argv, so deep_link_from_argv reads it before the single-instance check and it rides along with the raise. macOS has neither half of that: the URL arrives as an Apple Event that AppKit only delivers once the run loop turns, i.e. strictly AFTER setup returns, and tauri-plugin-deep-link only records it from RunEvent::Opened. So the non-owning process cannot call std::process::exit(0) inside setup the way the other platforms can, or the link dies with it (which is exactly what "opens the other Termic and does nothing" was). Instead it returns from setup with NO window built, drops to ActivationPolicy::Accessory so it takes no dock slot and steals no focus, polls the plugin's captured URL for a 1.5s grace, forwards it over the socket as open_url, and exits either way. Nothing waits on that process: the raise already landed on the way in.

Explicit non-goals: no project/add (a link must never register a repo — that routes around the gate above), and nothing destructive (archive, quit), where no amount of confirmation justifies exposure to a channel any web page can trigger.

Where the pieces live:

  • Scheme registration: tauri.conf.json → plugins.deep-link.desktop.schemes. The bundler turns this into CFBundleURLTypes; it merges with the hand-written src-tauri/Info.plist rather than replacing it. Deep links only work from a bundled .app — not under npm run tauri:dev, so test with make beta or tauri build.
  • Rust (lib.rs) is a pipe, not a parser: every arriving URL lands in PENDING_DEEP_LINKS and the webview gets a payload-free nudge (termic://deep-link). The queue exists because macOS delivers the launch URL while the webview is still booting; the webview always reads through deep_link_take_pending, which drains atomically, so a link is never handled twice.
  • Parsing + validation is entirely in src/lib/deepLink.ts, because the checks that matter (a registered project, an existing task) need the webview store. initDeepLinks() is chained off loadAll() in App.tsx for the same reason.
  • Raising: queue_deep_link calls leave_windowless when a window already exists. macOS activates the app for a link it routes, but that does not un-hide a window windowless mode put away, and a dialog behind a hidden window is indistinguishable from a link that did nothing. Gated on the window existing so cold-start setup doesn't flip SHOWN_ONCE ahead of normal startup ordering.
  • Second instance: a link that spawns a fresh process is killed by the single-instance preflight, which hands the URL over first via the control socket's unauthenticated open_url verb (proto v11) — that raises and queues in one request. Windows/Linux do this synchronously from argv; macOS cannot, see "the macOS handoff" above. With only one bundle installed macOS never gets here at all, because LaunchServices routes to the running app.

The termic command

One release command, termic, for both the shipped app and make beta. Not a cosmetic choice. The two release flavors share the data dir, therefore the control socket, therefore the single instance that owns it — so a single binary already reaches whichever of them is running, and only one of them ever is. install_name (cli_server.rs) returns termic for every release build and termic-dev only for a debug one, which has a genuinely separate termic_dev data dir and socket.

The beta used to install a termic-beta twin. It was a name and nothing else: the same binary, talking to the same socket, so it drove the shipped app whenever the shipped app was the one up, while its name promised otherwise.

Auto-launch always opens Termic.app (client.rs, open -ga Termic). When neither app is running there is no socket to disambiguate on, and the shipped app is the right default; run make beta yourself to get the other one.

reconcile_link runs on every launch (off the main thread, from cli_server::start) because three things drift silently: the name (a leftover termic-beta), the target (a deleted or moved bundle leaves a dangling link and a "command not found" with no explanation), and the version (a link into the OTHER flavor's older sidecar fails hello's protocol check). It repoints the link at the app you actually launched, in the directory the link is already in.

--help leads with the version (cli_command() in termic-cli/src/lib.rs), on the root, on every subcommand, and through the termic help [command] renderer. One command for two bundles means "which build is this?" is a real question, and the binary's version is the app version it was built with, so one line answers it. clap 3 printed this by default and clap 4 dropped it. It is a literal in the template rather than {version}, because {version} renders empty on a subcommand unless propagate_version is set, and that would add a --version flag to every subcommand — widening the surface machine_help() publishes and the MCP parity test pins, to fix a header. termic help --json already carried version.

It is deliberately narrow, and the narrowness is the contract: reconcile_link only ever REWRITES a link of ours that is already installed, never creates one, and anything that is not our symlink is never touched. An unwritable /usr/local/bin logs and changes nothing; a launch must never raise an admin prompt.

"Install system-wide" asks for the password through the platform's own prompt: osascript ... with administrator privileges on macOS, pkexec (polkit) on Linux, an elevated PowerShell on Windows. Linux used to have none: the macOS call was compiled out, so the button that says "asks for your password" quietly installed into ~/.local/bin instead. pkexec is run with --disable-internal-agent, because without a polkit agent in the session it otherwise prompts on the controlling terminal and waits forever, and it is never run by the e2e build. Declined or unavailable falls back to the user directory, as on macOS.

A Linux AppImage links a COPY, not the bundled sidecar. Inside an AppImage termic-cli lives in the image's mount, /tmp/.mount_TermicXXXXXX/usr/bin/, which exists only while the app runs and has a new name on every launch. Linked there, termic was a dead link the moment the app quit (the shell says "No such file or directory", where the CLI would have said the app is not running), and so was the $TERMIC_CLI an agent had been handed if it outlived the app. bundled_cli_path therefore copies the sidecar to <data dir>/bin/termic-cli once per launch, when the content differs (copy_if_changed: by content, because fs::copy does not keep the modified time on Linux, and replaced by rename, because an agent parked in termic wait is executing the old file), and that stable path is what gets linked and exported. The sidecar links only libc and libgcc, so it runs outside the image. The copy keeps the basename termic-cli, which is how replaceable recognises a link as ours. Everywhere else the bundled path is used as before.

auto_install_user_link is the one thing that CREATES a link, and it runs at most once per profile. cli_enabled defaults to true, and for a long time the only thing that ever created the symlink was the Settings toggle's off-to-on transition, so a fresh Mac rendered a toggle that already said on, above a hint that said "On by default", with no termic command anywhere. Nobody got a CLI unless they happened to switch it off and back on. Every profile the cli_default_migrated flip reached had the same problem, since it sets the flag and installs nothing. Reported from a fresh install, where the system-wide button was the only way to get a working command.

It installs into ~/.local/bin and never /usr/local/bin: writing there needs an admin prompt, and a launch must never raise one, so system-wide stays on the explicit button where the user asked for it and can answer. The tradeoff is real and is not hidden: ~/.local/bin is NOT on a stock macOS PATH (/etc/paths ships /usr/local/bin and not it), so Settings reports whether the command it installed is actually reachable, and offers system-wide when it is not.

The gate is a MARKER (cli_user_link_installed), not "install whenever it is missing", and that distinction is the whole design. On disk the two look identical and mean opposite things: a command that was never installed wants installing, and a command the user DELETED wants leaving alone. The marker is set on the first attempt, success or failure, so a user who removes the link is never re-installed behind their back, and a failing install does not retry on every launch.

Paired machines (wire v22). Request gains peer (the global --peer flag: forward the whole verb to that paired machine) and from_task (the caller's $TERMIC_TASK_ID, sent only with peer, so the other machine may reply into it). Not caller_task: the command is flattened into the request and group already owns that key; the peer_* verbs name their machine target for the same reason. New verbs peer_list, peer_pair { target, code? } (the code the other machine shows in pairing mode; without it, that machine is asked to show one and the reply is peer_code_shown { name, next }), peer_unpair { target }, peer_rename { target, name }, all answered by peers::handle_verb and refused with peer set. ErrorCode::PeerUnreachable maps to exit 12. handle_request skips local --profile resolution when peer is set (the name is the OTHER machine's profile), and dispatch_authenticated forwards before matching a verb. See peers.md.

Critical shapes (fail silently)

  • pty_spawn payload is { args: SpawnArgs }, NOT SpawnArgs at top level. Wrong shape → "invalid length 0, expected struct SpawnArgs".
  • Listener payload is ev.payload.data / ev.payload.line — Rust emits structs, not bare arrays. Wrong unpack → blank terminals, no error.
  • task_run_script takes { id, which }. Forgetting which → silent no-op.

Long-running IPC discipline

Any IPC doing heavy IO MUST be async fn + tauri::async_runtime::spawn_blocking. Synchronous commands run on the IPC handler thread = same thread driving WKWebView event loop in dev. fs::remove_dir_all on a 50k-inode .venv froze the entire Mac. Already applied to task_archive, task_delete, list_monospace_fonts. Pair with useUI.setBusy("…") overlay so the user knows a multi-second op is in flight — UNLESS the operation is scoped to one task rather than the whole app (both sections below), in which case a global overlay is the wrong tool: the other tasks' agents keep working and the user must be able to reach them.

Checking out an existing branch

Reviewing a PR (proto v21, Command::New.pr): termic review <pr> and MCP task_review send a new with pr set and no name. The server names the task review-pr-<n>, refuses pr with from / checkout / a non-git project, and without -P resolves the first enabled prompt labelled "Code review" with a body (default_review_selector; list_prompts reports each prompt's labels, the built-in one as code-review, plus a derived review flag, and termic prompts prints them in a LABELS column), refusing with not_found when none carries it. Labels are the prompt library's (store/prompts.ts): any number per prompt, user-made, and code-review is the only one the app reads. The webview's new_task handler (reviewParams in lib/cliRpc.ts) fetches the PR head (project_forge_prs by number, then project_fetch_pr_branch), turns a worktree request into checkout of that branch or switches the main checkout onto it (refusing on a conflicted switch), and puts the PR's title, link, description and the commands for its diff and thread in front of the prompt (prReviewPrompt, lib/prReview.ts). The Review a PR dialog (ReviewPrDialog.tsx, lib/prReviewTask.ts) does the same from the GUI, with one difference: a PR that already has a review-pr-<n> task gets a new agent tab there instead of a refusal.

task_create with checkout_existing: true checks branch out as it exists instead of cutting it from base_branch, which then only sets the diff baseline. checkout_existing_branch (lib.rs) runs first and turns the request into a local branch (local as is; origin/x or a bare remote-only x fetched and tracked) or an error; it never falls through to the new-branch path. The New Task dialog's "Existing branch" mode and termic new --checkout (proto v14, Command::New.checkout) are the two callers. The flag is saved on the task (Task.checkout_existing), so task_restore brings a branch archive deleted back the same way (ensure_restore_branch) instead of cutting it from the base. See ui.md "Checking out an existing branch".

Multi-repo members from the CLI

termic new --member <name> (proto v24, Command::New.members, MCP task_new members) is how a CLI or MCP create gets member worktrees. The wire carries member NAMES; handle_new resolves them against the disk-read project (resolve_new_members: case-insensitive, project order, repeats collapsed), refuses an unknown one as not_found listing the members, refuses members on a single-repo project (naming the registered multi-repo projects, or saying there are none) and alongside from / checkout / pr / resume, and sends the new_task RPC the member root_paths plus a concrete mode: "main" only when asked for, otherwise "worktree", also on a plain-folder host, which keeps the dialog's canWorktree = isMulti || !hostNonGit instead of the single-repo plain-folder pin. The webview's new_task handler then calls task_create_multi (each member worktree, or repo_root when it is a plain folder; member branch and base left to Rust's fallbacks) or task_open_repo with the members filter. Without members nothing changes: a worktree create is a single-repo task_create of the host with no members, and a main-checkout create (the only kind on a plain-folder host) links every member.

termic project list (MCP project_list) is where a caller finds those names: ProjectInfo carries type ("single" or "multi", the Project.type key) and a multi project's members, each one's name, root_path, non_git and base_branch (ProjectMemberInfo), filled by project_info from the disk read.

Non-blocking task creation (GH #242)

task_create/task_create_multi being spawn_blocking on the Rust side keeps the WKWebView event loop free, but that alone doesn't stop the FRONTEND from blocking: the old New Task dialog (and, separately, the sidebar + quick-create row via QuickCreateProgressDialog) each awaited the call with a dialog locked open, so the whole window was unusable until git worktree add + the file copy finished on a big repo. There were TWO of these blocking implementations (the full dialog and the "quick create" inline path in Sidebar.tsx/quickTask.ts) — both needed the same fix, since a caller with the id ahead of time gets the same treatment regardless of which UI it came from. The fix doesn't use useUI.setBusy (that dims the entire app for one in-flight task, the wrong blast radius) — instead:

  1. The caller generates the task's uuid client-side (crypto.randomUUID()), registers a setup-output://<id> listener, adds a src/store/pendingTasks.ts entry, calls setActiveTask(id), and closes/proceeds — all synchronous with the click, before taskCreate's promise resolves. Both NewTaskDialog.tsx's submit() and Sidebar.tsx's inline worktree-row onCommit do this now; quickTask.ts's createQuickTask takes an optional id so the caller can pre-generate it.
  2. Sidebar.tsx's PendingTaskRow and MainArea.tsx's CreatingTaskPane render for that id (no real Task exists in the store yet) — a spinner-badged row and a full-pane live log, not a blocking overlay. The rest of the app stays fully interactive.
  3. Once taskCreate resolves, loadAll() picks up the real task and the pending entry is dropped — PendingTaskRow/CreatingTaskPane are superseded by the normal TaskRow/TaskView at the same id, so the user's click target never moves. On rejection the pending entry flips to an error state instead (dismissible from the pane), no toast, no reopened dialog.

QuickCreateProgressDialog and useUI().taskCreateProgress are gone (deleted, not just unused) — don't resurrect them for a new quick-create variant; extend the pendingTasks flow instead. Any future task-scoped long-running create/import flow should follow this shape rather than reaching for setBusy.

Non-blocking archive (GH #246)

The same bug at the other end of a task's life, and the same fix. archiveTask.ts's runArchive raised setBusy("Archiving …") and held it until task_archive AND the post-archive loadAll had returned — the project's archive script, then git worktree remove, then fs::remove_dir_all over a node_modules-sized tree, with the whole window under a click-blocker and every other task's agent unreachable. Worst exactly when #242 was worst: archiving several finished tasks in a row.

startArchive(taskId, deleteBranch) (exported, also used by the CLI's archive RPC in cliRpc.ts) does everything visible synchronously with the click and returns a promise the UI does not wait on:

  1. src/store/archivingTasks.ts gets the id (a separate store, not useApp — one transient flag has no business re-running every mounted task's selectors, see performance.md bear trap 8). It also doubles as the double-fire guard, which the modal used to provide for free.
  2. The task is deselected immediately if it was active: its pane is in front of the user with its worktree being deleted underneath it.
  3. Sidebar.tsx's TaskRowSlot swaps that one row for ArchivingTaskRow — struck-through name, spinner, no click, no menu, no tab children — until loadAll drops the task. Nothing else in the window changes.

archiveAndRefresh still swallows the IPC rejection (issue #24: the task is already persisted as archived, so the refresh must run regardless), but it now also toasts the cleanup error. In the background that toast is the ONLY signal: a worktree that failed to remove would otherwise vanish from the sidebar with the directory still on disk. Read the task's name for that toast BEFORE loadAll drops it.

CLI tab launch options

termic tab TASK --agent codex --model MODEL --arg=-c --arg='model_reasoning_effort="xhigh"' opens a fresh agent tab with explicit provider arguments. Each --arg is one argv element, not a shell fragment. --model is appended after these values so it wins for CLIs with last-value-wins parsing. Both options require an explicit agent, conflict with rename/shell/terminal modes, and do not alter global configuration.

The task_tab MCP tool exposes equivalent model and args parameters. Protocol 17 carries composed agent_args through new_tab as agentArgs; opening replies and status --json tab rows expose the explicit overrides. These fields describe configured overrides, not proof of the provider's actual active model. Agents should honor the user's requested model and reasoning; otherwise choose for the assignment and consult the provider's own help for supported options. Termic does not maintain a model catalogue or silently choose a reasoning level.

A model-switch prompt sent after creating a tab cannot make the original launch fresh and is not an equivalent substitute for launch arguments.