Files
ai-agent/CLAUDE.md

486 KiB
Raw Permalink Blame History

CLAUDE.md — ai-agent

Guidance for Claude Code when working in this repo. It was extracted from the homelab monorepo (formerly services/ai-agent/, full history preserved); the homelab keeps a deployment shim at ~/homelab/services/ai-agent/ (compose with build.context pointing here, traefik.yml, deploy.sh, the live data/ volume), and the homelab root CLAUDE.md conventions (worktrees, Traefik copy step, commit/notify) still apply when deploying there.

North star

This service is headed somewhere bigger than a homelab dashboard: the open-source, intuitive, private and secure agent layer of any computer, to build and host websites and interact with data — Lovable, but open source and self-hosted. Zipgo under the hood for hosting, shipped as a single Docker container, with self-update handled inside the container (not by host scripts). See GOAL.md for the full vision and the gap list. When making changes here, prefer container-internal solutions, generic config over homelab-hardcoded paths, and zipgo over bespoke hosting.

What this is

A viewer/editor + analytics dashboard for the homelab's Claude context, served as an installable PWA at https://ai-agent.lab.gabvdl.xyz (behind Authelia). It:

  • exposes every CLAUDE.md and the .claude/ tree (skills, hooks, settings) as a flat, editable file list with real Claude token counts + dollar costs (the context-editor live plugin's page since 2026-11-28), plus the repo's root data/ tree (plans, logs, notes, kanban) surfaced read-only;
  • browses the archived Claude Code conversation transcripts (thread view with per-turn usage/cost, skill-usage analytics, spawn/resume/interrupt live runs);
  • catalogs ~/projects (mounted at /workspace/projects; gallery + detail); the repo's services/ (static parse of compose + Traefik configs — never Docker itself) are the services live plugin's catalogue, under Projects;
  • surfaces the scaffolding templates (the assistant's memories are the memories live plugin's since 2026-11-26);
  • streams updates over SSE so the UI refreshes without a manual reload.

It is a viewer: it reads the repo context (mostly read-only mounts) and does static parsing. It never drives Docker or mutates infrastructure. The only writes are file edits into the mounted .claude/ + ~/projects trees and its own SQLite store / metadata sidecar.

Layout

  • backend/ — FastAPI app (main:app, port 8080). Serves /api/* and the built PWA from STATIC_DIR (SPA catch-all mounted last by main.create_app). One package per domain (see "Backend modules").
  • frontend/ — Vite + React + TS + Tailwind PWA. Built in the Dockerfile's first stage into /app/static.
  • sidecar/ — a host-side FastAPI process (NOT in the container) that launches claude -p sessions. See below.
  • Dockerfile — 2 stages: build the React PWA, then a python:3.12-slim image running uvicorn.
  • docker-compose.standalone.yml — the generic, no-host-mounts shape (see "Standalone mode" below). The homelab's compose service (profile dev, container ai-agent, host-only port 127.0.0.1:8096:8080, network main), its Traefik router (ai-agent.lab.gabvdl.xyz, auth-chain) and the blue-green deploy.sh + deploy.override.yml live in the homelab repo's services/ai-agent/ shim.
  • PROJECT_CLAUDE.md — the generic, host-agnostic project working conventions (worktree workflow, artefacts, plans, committing, the closing notification), split out of the homelab root CLAUDE.md so the ai-agent can ship it as the starting CLAUDE.md for a new project. Not this service's own guidance (that's this file) — it's a shippable template with {{…}} placeholders.
  • data/ — SQLite DB, transcript archive, metadata sidecar, ui-state.json (bind-mounted, gitignored).

Backend modules

  • main.py — the assembly only: create_app() installs the trusted-caller gate, builds the shared state, mounts every domain router (ROUTERS, in the old declaration order) and the SPA fallback; _startup starts the background threads. No route lives here.
  • One package per domain, each with a routes.py exposing an APIRouter (and service.py / catalog.py / store.py modules behind it): core/ (config, auth gate, _r/_json_in_worker in http.py, the memo, app-level routes: events / gen-progress / health), files/ (the context catalog + file read/write the context-editor's bridges call, asset serving, uploads, the files a message names — hostfiles.py, and browse.py's raw route; the bridges themselves are plugins/hubfiles.py), settings/ (ui-state, hooks), dashboards/ (a guest's Stats, the skills catalog — the owner's Context & skills dashboard is a plugin's), conversations/ (parser, pricing, cards, subagent tree, catalog, routes, scaffold), diff/, notifications/ (feed, pushes, asks), forms/, drafts/ (composer drafts per user), runs/ (sidecar client, the send path, spawn/resume/fork/interrupt), accounts/, profiles/, workers/, models/, agents/, projects/, services/, goals/, templates/, schemas/, authz/ (permissions: catalog, roles, scopes, the route table — docs/permissions.md), telemetry/ (the hub's own metrics, the browser beacon, feature usage — "Telemetry" below). A package whose flat module moved inside keeps its old spelling through a barrel __init__.py (import conversations, import projects, import accounts… still work; the private names other modules used are re-exported explicitly). Infrastructure shared by every domain stays flat: db.py, events.py, meta.py, indexer.py, fsscan.py, fswatch.py, tailcopy.py, githist.py.
  • Shared state is injected, not imported. core/state.py builds every store, hub, watcher and mirror once (build_state() → AppState, a dataclass attached to app.state.ai). A route declares deps: State (a FastAPI dependency, excluded from OpenAPI) and a helper takes deps: AppState as its first parameter; deps.store, deps.hub, deps.meta_store… replace what used to be module globals. Module-level caches (_Memo, the _*_cache tuples) stay where they are — they are keyed on the store/meta versions, not on the state object. A test builds the app the normal way and reads main.app.state.ai (see test_worker_routing.py).
  • Keep a file under ~500 lines; the parser's conversations/parse/state.py (ParserState) is the deliberate exception — one concern, being cut down.
  • db.py — SQLite store (WAL): files (content hash + real token count + cost + word/char stats, computed lazily only when a file's hash changes), skills, transcripts bookkeeping (each row's parser_version; the sweep and the upgrade queue read path/mtime/size/version off the covering index transcripts_book, never the blobs). Decoded transcript summaries are cached in-process (all_summaries()/get_summary() return read-only dicts — copy before mutating) and summaries_version bumps on change so request-level memoizers (e.g. the project cost rollup) know when to recompute.
  • indexer.py — background daemon: token/cost accounting (via the count_tokens endpoint, debounced) + skill-usage mining from transcripts. Pricing consts here. PARSER_VERSION is per row (transcripts.parser_version, an integer): a bump wipes nothing — every row keeps serving its summary while upgrade_rows, between two sweeps, re-parses the older rows most recently active first at REPARSE_DUTY (env, default 0.5) of a core (aiagent_index_rows_stale / aiagent_index_rows_upgraded_total on /api/metrics); a changed file is re-parsed at once as always. A container only upgrades rows older than its own version and writes them compare-and-set, so the old and new containers of a blue-green deploy never undo each other. Every field a version adds must stay optional (an old row lacks it) and a rename needs a read-side fold (the frontend's normBucket for bash→shell); a change whose old summaries would render wrong raises MIN_SERVABLE_VERSION instead — rows below it are hidden and re-parsed by the next sweep, the old wipe for those rows only. The meta table's parser_version row is no longer written (it stays at the last global version, 46): a pre-per-row image still running beside a new one wipes the store when it reads another value. The first start of per-row code stamps the existing rows with that value (the column's DEFAULT: no re-parse, no row rewritten).
  • conversations/parse/ — parse *.jsonl transcripts. Readers → events → fold: a reader (parse/readers/: claude.py + claudetext.py for Claude Code's records and text conventions, legacy.py for the pi / opencode / agy transcripts written in Claude Code's format before v1 (and a file that switches to v1 at a v1 header line), v1.py for v1 files — what the converters write since step 1c; the lab's past ones are rewritten by scripts/transcripts-v1.py (parse/rewrite_v1.py), the workers' copies stay —, hubtext.py for the hub's inbox / relay / cancel / author envelopes; reader_for picks one from the first record) turns each record into the neutral events of parse/events.py (plain dicts with a t key — prompt, inject, call, usage, text, tool_call, tool_result, turn_end, meta…; the v1 contract for converter authors is docs/transcript-format.md, kept in sync with events.FIELDS by test_parse_fixtures), and ParserState.apply folds them — the fold never reads a record shape or a harness's wording; a new record type or text convention goes in its reader. Tools are known by neutral names (parser v45, parse/readers/toolnames.py): shell, read, write, edit, grep, glob, list_dir, web_fetch, web_search, agent, skill, todo, ask_user…, <harness>:<Name> for one harness's own tool (claude:CronCreate), MCP names as they are; a card's native keeps the harness's name, buckets are shell / todo (not bash / task). Table and rules: docs/transcript-format.md "Tool names". The other modules: records JSONL + timestamps, usertext the DONE markers (+ re-exports), tools tool buckets + evidence, errors API-error kinds, usage, turns, state = ParserState, cut = find_cut_line (reads the native file); every name stays importable from conversations.parse; ParserState owns a UsageMeter (state.usage: totals, by model, plan units, hour bins, EVOX2 energy, context, compactions, by activity) and a TurnState (state.turn_state: turn end, input queue); their old fields still read off the state). ParserState is a resumable parser (feed(record) + summary(); the live state is byte offset + reader + fold, a model step is folded at the end of its record's batch); parse_conversation(path, full=…) is the one-shot wrapper (cheap rollup vs. full thread). Real per-turn usage/cost from usage blocks, plus the per-item metadata the viewer shows on each row: durationMs (a tool call's run time — call → its result record; on a message, the assistant API call's latency), model, toolUseId, resultChars/resultLines.
  • conversations/resources.py (the transcript miner), resource_view.py (the plugin-scoped pills + title), related.py, plugins/resources.py (the resource registry) — see "Conversation resources".
  • fsscan.py — os.scandir-based directory walking. The poll loops re-walk thousands of files every couple of seconds; pathlib.rglob allocates a Path per entry and was a large chunk of idle CPU. Use this, not rglob, in any loop.
  • fswatch.py — inotify over a directory tree (TreeWatch: ctypes onto libc, nothing to install; new dirs watched as they appear, pruned names skipped, overflow reported). What the transcript watcher and the workspace watch run on instead of re-walking; open() returns None where inotify can't work (WATCH_INOTIFY=0, not Linux) and a watch that hits the per-user limit turns ok off — callers fall back to polling. See "Performance" rule 1.
  • tailcopy.py — sync(src, dst): the archive import's copy. Appends only the bytes past the archive copy's end when the source grew (every transcript writer appends), a full copy otherwise; flock'd on the destination so the watcher, the indexer's sweep and a blue-green standby never duplicate a tail.
  • githist.py — cached git history. BucketedHistory walks a repo's log once (git log --name-only -- <prefix>) and buckets commits per directory, keyed on the repo HEAD; RepoLogCache TTL-caches standalone project repos. Before this, the old /api/services forked two git logs per service per request (11 s). The services one lives in servicesdir.py (with SERVICES_DIR and safe_entry, the plumbing the core kept when the catalogue left — see "Services: the plugin's whole catalogue").
  • events.py — Hub (SSE pub/sub) + Watcher (stats meta, takes the live transcripts that moved from inotify — a full re-walk every WATCH_RESCAN_SECS behind it, or each tick without inotify —, re-indexes, publishes meta/transcript events).
  • meta.py — per-conversation action metadata JSON sidecar (projects, state, committed/pushed/merged/deployed/notified timestamps), keyed by session id.
  • conversations/deploycmd.py — "is this Bash call a deploy?", answered by the program it runs (shell-split; quotes, heredocs and comments dropped; cd/timeout/setsid nohup/flock/rtk/bash <script> peeled), never by deploy*.sh merely appearing in the text (cat/grep/bash -n of a deploy script were ~40% of the old regex's hits). The shapes — deploy*.sh, npm run deploy*, zipgo deploy, make deploy*, deploy-html, docker compose up --build|--force-recreate (or up after a compose build), rsync into zipgo's domains/ — were read off what ran before past notify-done --type deploy pushes (see the module docstring). That one answer is the tool card's deploy field (the thread's deploy widget — the frontend doesn't re-match commands), the deployed lifecycle stamp and the "Deploying…" chip.
  • The blue-green deploy's floating banner is the blue-green-deploy live plugin's app.banner (~/projects/ai-agent-plugins; deploy.sh posts each phase to its internalOnly webhook) — no core deploy-status route or file watcher any more. GET /api/app-banner resolves the banner's conversation title and in-app conversationId from the snapshot's sessionId (plugins/routes._attach_conversation; the plugin only sees the sidecar's custom title, which most conversations never set).
  • Cron jobs are the cron-jobs live plugin's (since 2026-11-28 — ~/projects/ai-agent-plugins/plugins/cron-jobs; backend/cron/, /api/cron*, /api/me/cron*, Settings → Cron and the guests' « Tâches planifiées » pages, ai-agent cron and the MCP run_cron_job / set_cron_job / browse cron are gone). The core keeps: core/cronexpr.py (the 5-field matcher the plugin scheduler and the manifest validator use), agents/runconfig.py (an agent file's frontmatter run config — the agents page's Run now), runs/guestjob.py (a guest's job run as that guest, confined by the core: the runs.guest bridge, the result's delivery, « Discuter »), plugins/cron_bridge.py (the runs.cron provider's readers) and the meta.cron stamp — see "Cron jobs: the plugin, and what the core keeps".
  • diff/gitdiff.py / diff/worktreediff.py / diff/editsdiff.py — the diff view (/diff/*), in three layers. gitdiff does committed history: recent commits per repo token (project:<slug> | service:<slug> | super:_), one commit's hunk model, the net diff across a conversation's commits, and the discovery of which commits a conversation produced (its active time window, plus main..<worktree branch>; cached in the DB by a fingerprint of the repo HEADs). The other two answer "what isn't committed yet":
    • worktreediff — a real git diff HEAD (+ untracked files) read from the conversation's still-live worktree. A worktree's .git file points at a host path, so it maps the host repo root onto the mounted one and drives git with an explicit --git-dir/--work-tree pair. Needs the worktrees root mounted (WORKTREES_DIR, /worktrees in the homelab compose); without it every lookup misses and the replay below takes over.
    • convcommits — a conversation's own commits (the parser's commitsAuto, see "Reviewing a conversation's commits" below) and their diffs: lab git → the transcript's patch → the worker it ran on.
    • editsdiff — the fallback for a torn-down worktree: the same view replayed from the transcript's structuredPatch/originalFile payloads, hence approx: true. Paths from the homelab checkout, a ~/projects/<slug> repo and either flavour of worktree all normalise onto the repo-relative paths that repo token's git commands use.
  • conversations/scaffold.py — the completion scaffold (GET /api/conversations/{id}/scaffold): a conversation reduced to markdown — metadata, its prompts, merged bash/tool/subagent summaries, and one squashed diff across every commit it produced (via gitdiff) — with ## Summary and ## Analysis left blank for the model. PUT …/summary publishes the filled version onto meta.summary. The CLI wrapper is scripts/conv-scaffold.sh.
  • accounts/profiles.py — the Claude account profiles (personal, work), hard-coded, and the resolution order that gives every conversation a meta.account. See "Claude accounts" below.
  • models/catalog.py — the models a session can run on (GET /api/models). Fetched from the Anthropic API (/v1/models, same key the token counter uses) and cached in-process for 6h, then reduced to the newest of each family (opus, sonnet, haiku, fable — older snapshots are dropped, so the tag row stays four chips) with the CLI alias attached. A newly released model appears in the composer with no code change. Falls back to a small static list when the key is missing or the call fails. The pi and opencode lists are static: the opencode one is the ChatGPT seat's GPT models (default first: OPENCODE_DEFAULT_MODEL, gpt-6-sol), each with its reasoning efforts, -fast variants flagged fast.
  • the OpenRouter catalogue (GET /api/models/openrouter, plugins/providers.appe_catalogue — the provider-openrouter plugin's openrouter_appe discovery; models/openrouter.py was deleted on 2026-11-26): every model a pi.dev session can run on, with its $/Mtok (input / output / cache-read), context window, parameter size and capability tags. The data is APPE's (appe.dev.gabvdl.xyz/api/models/openrouter.json, a daily models.dev sync), cached 6h by the registry's discovery with a disk copy under PLUGINS_DIR/discovery/ (the old /data/openrouter-models.json still read once) so a restart with no network still lists models. Deliberately separate from /api/models: that endpoint is the composer's short chip list, this is the few hundred rows the model browser searches. It also prices pi sessions — conversations.rates_for() reads a model's real rates from here instead of the flat qwen estimate, and only an id the catalogue doesn't know falls back.
  • POST /api/notifications/audio — the sound a notification made, replayable in the browser (a WAV behind the ▶ button on an expanded notification card). Since 2026-11-26 core only routes it: notifications/channels.render_audio runs the owner's provides: {"notify.audio": "<action>"} plugin (the desk-phone live plugin, which asks the phone bridge's /render and keeps an on-disk WAV cache) and decodes its wavBase64; 503 without one. The card hides the button when usePluginProvides("notify.audio") is false. The spoken field, GET /api/notifications/unread and the phone API scope stay core.
  • settings/ui_state.py — server-side store (/data/ui-state.json) for the PWA's small client state (Settings config + notification feed seen/new bookkeeping), moved off browser localStorage so it follows the user across devices. Dumb key→string map: the key is a Zustand persist store name, the value its opaque serialized blob. Served by GET/PUT/DELETE /api/ui-state/{key}; the frontend points its persist stores at it via frontend/src/lib/serverStorage.ts.
  • projects/catalog.py — the projects gallery (static parsing); the homelab services are the services live plugin's whole catalogue since 2026-11-28 (see "Services: the plugin's whole catalogue" below — no backend/services/ any more); projects/costs.py the per-project spend rollup (its per-token-type split takes the shares from pricing.usage_type_costs and rescales them to each model's recorded cost, as the frontend's splitByType does); projects/worker_projects.py the projects deduced on the workers and the one attribution rule the cards and the rollups share (conversation_projects); projects/merges.py lab projects folded into a worker one.
  • dashboards/skills.py — the skills catalog behind /api/skills (the skills-agents plugin's Skills page since 2026-11-26 — see plugins/hubcatalog.py below): a disk scan of every .claude/skills/<name>/SKILL.md (repo + each project's) joined with the transcript-mined usage. /api/skills returns the union of disk skills and invoked-skill names, so a built-in/plugin skill with no SKILL.md here still shows up (sourceKind: "builtin", no editor link). Per skill: calls, distinct conversations, last-used, context tokens/cost (loading its dir once), estSpend = context × calls, and the coarser sessionCost (whole spend of every conversation that invoked it). Usage is keyed by bare skill name — the identity Skill(name) itself uses — so a project-local skill sharing a repo skill's name shares its counts. A call is a Skill tool call or a /name the user typed that injected a prompt.
    • Skill prompts in the thread (ClaudeReader._skill_injection → an inject of kind skill, folded by ParserState._inject_skill): Claude Code injects a skill's prompt as a user record. It is found by the record's sourceToolUseID naming the Skill call (a built-in/plugin skill has no "Base directory for this skill:" line, so the text can't identify it), or as the isMeta record right after a typed <command-name>/name (the parser then makes a user-role Skill card, rendered "typed by you"). Either way it folds into the card's skillBody — never a "You" bubble or a user turn. "Re-invocation" / "already loaded" notes fold in silently.
    • A built-in's prompt in the catalog: it has no file, so the indexer keeps the newest injected prompt per skill in the skill_prompts table (summary-mode skillPrompts, popped before the summary is stored; written newest-wins as each transcript is indexed, cleared on a parser bump — never a rescan per request). /api/skills gives a no-file skill promptAt; GET /api/skills/{name}/prompt returns the text + the conversation it came from, which the page opens read-only from the card.
  • agents/catalog.py — the agents catalog behind /api/agents (the plugin's Agents page), the same page shape as skills for .claude/agents/**/*.md: a disk scan (frontmatter name/description/tools + the harness/model/effort run-config keys) unioned with the agent types the transcripts saw run, so a built-in type (Explore, general-purpose) shows up as sourceKind: "builtin". The money here is measured, not estimated: an agent run is a whole conversation, so agents.runs._build_agent_runs joins two origins into one run list — a subagent run (a sidechain transcript whose agent-*.meta.json names the agentType, credited to its parent conversation) and a session run (the cron-jobs plugin fires a definition as a top-level run; the agent page's "Run now" does the same and stamps agentRun into the metadata sidecar). POST /api/agents/{name}/run is that button; scheduling creates a job in the cron-jobs plugin (plugins/cron_bridge.create) with the definition as the prompt file.
  • plugins/hubcatalog.py — Files → Skills and Files → Agents are the skills-agents live plugin's pages (~/projects/ai-agent-plugins/plugins/skills-agents, since 2026-11-26; business/skills + business/agents are gone). Its owner-only bridges: catalog.read (GET …/hub/skills|agents[?account=], …/hub/skills/{name}/prompt, …/hub/agents/{name} — the /api answers plus the scope switch's profiles), skills.share (POST …/hub/skills/share {ref, on} — the guests' sharedSkills), agents.run (handler only: POST …/hub/agents/{name}/run, …/schedule {schedule}). /skills[?skill=], /agents and /agents/<name> redirect to /plugins/skills-agents/… (the skill: / agent: pills keep their links); the Files drawer's files/skills / files/agents keys and the Files lists' saved slots follow them. /api/skills and /api/agents stay core: the composer's mentions, the tag pills, ai-agent skills / agents, the MCP tools and cli/tag_looks.py read them.
  • plugins/activitydata.py — the Activity rollup behind the activity.read bridge, read by the activity live plugin (since 2026-11-26 it replaced core's /api/activity + /dashboards/activity page; that address is gone since 2026-11-27): when the agents ran, as opposed to what they cost. Three rollups in one pass over the stored summaries — per local day (the contribution graph), per 5-minute slot per model (the day histogram, as positional [slot, modelIndex, agents] triples), and per model (runs / working time / tokens / cost). The per-turn half is already done by the parser: each summary carries activeBins (model id → the 5-minute bins that run produced a turn in), so a rollup never re-reads a transcript. Bins are epoch-absolute UTC; every entry point takes a tzOffset (minutes east of UTC, straight from the browser) and buckets local days against it — the one representation that survives a DST change. An agent run is one transcript, conversation or subagent alike; the heatmap's intensity is deliberately conversations only, while the histogram and per-model stats count every run.
  • goals/goalmd.py — a dir's GOAL.md (the north star the goal-keeper cron agent pushes forward), shared by both catalogs: goal_summary() returns the {done, total} checklist rollup that tags a card, goal_detail() adds the markdown for the detail page. Counting skips fenced code blocks, so a - [ ] inside a snippet isn't mistaken for a real task. No GOAL.md ⇒ goal: null (a valid state). The Goals board is the goals live plugin's (ai-agent-plugins, /plugins/goals/board, since 2026-11-25). The core page (frontend/src/business/goals, useGoals, spawnGoalWork) left on 2026-11-26; since 2026-11-27 the board is a nav: "files" page and the core names it nowhere (no /goals address, no files/goals link): like every plugin page it sits where its manifest's ui.pages[].nav says (files: Goals, Forms, Plans, Memories, Templates, Skills, Agents), else in Dashboards — docs/plugins.md → "The core names no plugin page". goals/routes.py stays, with no route of its own (/api/goals and /api/goal-work are gone): the plugin's goals.read / goals.work bridges call goals_list and goal_work.
  • usage/ — plan usage: poller.py records each account's official /usage % (rate-limits.json) into usage_limits, store.py also keeps the side-call ledger (side_calls: every one-shot completion the hub makes for itself — the host sidecar's /complete, asked by the conversation-labels plugin through the complete.run bridge — has no transcript for the parser to price, so plugins/hubcomplete.py book() prices its reported usage with the same book and records list $ + plan units per account; calibrate.meters adds them to the plan meter like any run's meterBins), calibrate.py fits plan units per 1 % of the 5h / week windows (daily, service.py) and computes planPct, the per-day untracked %, and the --final notification suffix; routes.py is /api/usage/{limits,history,calibration,calibrate,import} (owner only). Guests' own logins are polled too (the lab sidecar's /claude/usage) but are no plan of the owner's: service.metered() skips them for fits and the plan tracker, limits lists them as a bare reading, and the guest reads theirs at /api/me/usage (accounts/guest.py). An opencode seat's reading comes from the worker hosting it when it isn't mounted (UsagePoller.remote → service.remote_snapshots), its plan has a week only (accounts.plan_windows), and limitAlerts push once per crossing (service.limit_alert). An account's weekTarget (the personal Max: {goal: 100, behindAlert: 20}, target.py) is the week to max out — a straight line from 0 % when the window opens to goal % at the reset; the home week gauge draws it, and the poller pushes once each time the week falls more than behindAlert points under it (service.behind_alert, checked between two stored points, so a restart never re-pushes).
  • perf/ — the data behind the Performance dashboard: CPU and memory of every agent run and of the processes it starts, from each runner's /procs, and what sessions keep on disk. The dashboards and the conversation's consumption cards are the performance live plugin's (since 2026-11-26, over perf.read / perf.act). See "Performance: what agents and their processes cost" below.
  • schemas/ — Pydantic response models mirroring frontend/src/types.ts. They drive the OpenAPI schema (and thus the generated frontend types) but are documentation-only: attached to routes via responses={200: {"model": …}} (helper _r() in core/http.py), never response_model, so FastAPI serves them in /openapi.json without validating or filtering the handlers' actual dicts. One module per API area (conversations, projects, agents, notifications, misc, …) on a shared base.Schema; __init__.py re-exports every model, so handlers keep writing schemas.ConversationDetail. Modules import across each other with relative imports and must stay cycle-free.

API types are generated (orval)

The frontend's API DTOs are generated from the backend's OpenAPI spec, not hand-maintained. Flow: backend/schemas/ → frontend/openapi.json (a dumped spec, committed) → orval → frontend/src/generated/ (committed) → re-exported by frontend/src/types.ts under their original names. types.ts keeps only the non-API helpers (TreeNode, FileKind, ServiceAuth).

  • After changing a backend response shape, update the matching model in schemas/, re-dump frontend/openapi.json from the app's app.openapi(), then cd frontend && npm run gen:api to regenerate, and npx tsc --noEmit to surface fallout. Generated optionals are T | null (Pydantic Optional), so widen consumers to accept null — the app runs unchanged; only tsc cares.

  • The Docker build doesn't regenerate (no backend at build time) — it relies on the committed src/generated/ tree, so commit regenerated output.

  • There's no venv on the host, so re-dump the spec with the service's own image:

    docker run --rm --entrypoint python -v "$PWD:/svc" -w /svc/backend \
      -e DB_PATH=/tmp/x.db -e TRANSCRIPTS_DIR=/tmp -e WORKSPACE=/tmp -e REPO_DIR=/tmp \
      homelab-ai-agent -c \
      "import json, os, main; json.dump(main.app.openapi(), open('/svc/frontend/openapi.json','w'), indent=2); os._exit(0)"
    

    Both odd-looking bits are load-bearing: --entrypoint python because the image's entrypoint (docker-entrypoint.sh) otherwise ignores the command and boots the server, and os._exit(0) because importing main starts the indexer/watcher threads, so a normal exit hangs waiting on them.

    It runs as root, so delete the backend/__pycache__ it leaves behind (a root-owned dir will otherwise block git worktree remove).

The mock backend (frontend/src/mock/) — demo + test without the API

The frontend ships an in-browser mock backend that sits behind those same generated DTOs, so the PWA can be demoed and automatically tested with no FastAPI, no sidecar and no transcripts on disk. Turn it on with ?mock=1 on any URL (sticky until ?mock=0 — works against the deployed app too) or build/serve with VITE_MOCK=1 (npm run dev:mock); a MOCK API badge marks the mode.

It swaps window.fetch (every /api/* route) and window.EventSource (/api/events, same meta/transcript events as backend/events.py) for versions served from an in-memory, localStorage-persisted database. Writes really mutate it, and spawn/resume/interrupt actually run: a scripted turn streams into the conversation item by item over SSE, then stamps the notification + the sign-off message that mark it finished.

The seed is combinatorial — the cross-product of every field the UI branches on (conversation harness × state × lifecycle × archived, every ThreadItemKind and tool card, every FileEntryKind, every service auth, every plan status, every FileDiffStatus/DiffLineType) — so every visual state is reachable from a cold load, and it is deterministic (fixed clock, no RNG). Test hooks live on window.__mock (db(), reset(), speed(), flush()).

Two rules keep it useful: install it before the app tree is imported (main.tsx → dynamic ./mock, then dynamic ./root; the server-backed Zustand stores fetch at import time), and type the seed rows with the generated models — a backend schema change then breaks the seed at tsc time instead of letting the mock drift. Details in frontend/src/mock/README.md.

Every new piece of conversation data gets a visibility toggle

The conversation page has an eye-icon visibility popover (components/ VisibilityPopover.tsx, switches + store in lib/visibility.ts) — a scrollable, grouped list of switches for everything the page renders: per-item metadata (price, tokens, duration, timestamp, model, tool id, result size, diff stat), content (thinking blocks, tool cards, run-command cards, tool output, rich widgets, error states) and gizmos (task panel, fast-forward, animations). State persists server-side via ui-state under the key ai-agent-visibility, so a reading setup follows the user across devices.

When you add anything to a message, a tool card or the conversation chrome, add its switch too — a new metadata field, a new inline widget, a new floating gizmo, a new animation. It is not optional: the thread is dense, and every addition has to be something the user can turn back off.

To add one: append a VisItem to the right group in VIS_GROUPS (lib/visibility.ts) — the VisKey union, the popover list and the persisted state all derive from that array — then gate the render on useVis() (or useVisible(key) for a single switch). The store records only what's hidden, so a newly added switch starts ON for everyone with no migration. A switch that should start OFF (e.g. Command behind a diff) sets defaultOff: true; the store keeps those in a second list, shown — the ones switched on — and isOn() reads both.

The closing push: a ```notify block ending the final message (since 2026-11-23)

A run's closing push is no longer a notify-done --final call: over 382 conversations (14 days to 2026-11-23) that call reached the phone a median 11 s (p90 24 s) before the final message it announced, its card sat above that message, and it cost one more full-context request (median 182k tokens, ≈ $0.04 on Opus 5.5). The run now ends its final message with a fenced block — the last thing in the message, one JSON object:

Shipped: the retry limit is 5.

```notify
{"title": "Retry limit raised", "message": "tests pass", "type": "code", "url": "https://…"}
```
  • Parser (conversations/closing_notify.py → parse/state.py's assistant-text branch): split() cuts a block that ends a text block out of it — a block quoted mid-message, another fence or JSON that doesn't parse stays text (the reader sees it raw: the hint it went nowhere). The cut text is what the thread, search, last_assistant_text and every "final answer" (ai-agent wait, leftovers, conv refs, guests' cron) read; the fields (title message type url image spoken; body read as message) ride on the item as notify (ClosingNotify in schemas/conversations.py) and on the summary as closingNotify (+ the record's uuid / at; only a main-thread message — a sidechain's never counts).
  • Push (indexer.scan_transcripts pops closingNotify before storing the summary and calls on_closing_notify → core/state._closing_push → notifications/closing.maybe_push): on every re-parse, so the push leaves the moment the message is in the transcript (the watcher's ~2 s tick; workers' mirrored transcripts the same way) — as soon as it is written, not at turn end (Gabriel's choice: the complete pass keeps working after it). Once: the id is ntf_ + sha1(at, title, message)[:12] — a fork or a resumed copy carries the same record, so the same id — skipped when already in the notification log or older than MAX_AGE_S (15 min: a re-index after a deploy or a new worker's history never replays). It goes through _create_notify with final: true and the CLI's cost line rebuilt from the summary (Claude Code · $1.57 · 78k tokens · 8m 38s, re-priced and given its week share by restate_cost), off the indexer thread. No block, no push — no default push either (his choice).
  • Viewer (ThreadRowImpl's text branch): an assistant text item with notify renders the bubble (the cut text; nothing if the block was the whole message), then NotifyWidget (closingNotifyArgs) as its own card under it; hasClosingPush keeps it out of the summary's folds even when the complete pass wrote more after it. ThreadNotifs.isNew matches the hub's copy, whose body carries the cost line under the message.
  • Prompts: NOTIFY_GUIDELINE (lib/shortcuts.tsx) asks for the block; isNotifyGuideline hides it — and the older notify-done line — from the prompt pills. The hub's own prompts (guests' runs and cron discussions, New project's hand-over, goals) say the same; a no-shell guest can push now. notify-done stays for mid-task pushes and for --action-cmd / --channel / --importance / --vibration; --final still works. The homelab cron agents (.claude/agents/*.md) moved to the block too.

Notification channels: the phone is a plugin (notifications/channels.py, since 2026-11-25)

The hub records every push, ask and form and reaches each person in the app (feed, SSE) and on their browsers (web push — core, Gabriel's call). Anything past that is a channel: a live plugin whose manifest says "provides": {"notify.channel": "<action>"}. For each event the host runs that action of every enabled, approved install of the person it is for (the owner's Home Assistant, a guest's own ntfy) with {"event": "notify" | "ask" | "clear", "push": {…}} — push is exactly the payload the old Home Assistant webhook got (id, title, message / question + options, url, image, type, importance, channel, actions, tag, account, spoken…; a clear {"tags"}; a guest's own channel gets their wording and guest-host link, no account). It answers {ok, status?, error?}; the delivery record is {channel: <plugin id>, ok, status, error, user} beside {target: in_app | webpush}. Decided in forms ha-push-as-a-plugin_yjj2n0 / browser-push-as-a-plugin_7id9we:

  • Tried once, on the request thread (notify / ask); a failure is recorded, never retried. Clears go off-thread.
  • No channel = still OK: the owner always gets an in_app record, so ok stays true and the CLI notes "in the app only".
  • Buttons answer the hub, whichever channel they were tapped on (/api/ask/{id}/answer, /api/notify/{id}/action); first answer wins and the hub clears the rest (deliver.clear → every audience member's channels).
  • Home Assistant is the home-assistant-push plugin (~/projects/ai-agent-plugins/plugins/home-assistant-push/): it POSTs the push unchanged + pwaPackage to the ai_agent integration's webhook (its settings: webhook URL, Android app package, questions on/off, daily budget), counts what HA accepted per UTC day against the companion relay's 500 pushes a day (clears included; its status), and carries the HA integration's source (integration/, install.sh --restart). Settings → Webhooks and /api/webhooks* are gone (/settings/webhooks redirects to the plugin); the old webhook's URL + package were carried over once into the plugin's data (plugins/carryover.ha_webhook → legacy-webhook.json, read while its settings are empty). The desk phone is HA's fan-out — untouched.

Notification read state

Each id of the owner's feed is unread (implicit: not in the ledger), read (its card expanded — it stays on the home New list) or dismissed (swiped — off New), kept per id on the server: notifications/read_ledger.py (/data/notif-read.json, each change with its time and source, capped at 5000 — dismissed dropped first, and floor remembers the newest push time the cap dropped, so an evicted id still reads dismissed). A state never goes backwards. GET /api/notifications/state → {enabled, seeded, migrated, floor, baseline, states: {id: "read"|"dismissed"}}; POST /api/notifications/state {ids, state, by} moves ids forward, clears their pushes off the owner's other devices and the phone (_clear_read), and publishes SSE {"type": "notif-state", "ids", "state", "by"} with only the ids that moved ({"type": "notif-state", "reload": true, "by"} after an import or a seed: refetch the whole state). The phone's GET /api/notifications/unread reads the same ledger: seen = read or dismissed.

Archiving dismisses (Gabriel, 2026-11-06). dismiss_archived (notifications/routes.py) moves every push of an archived conversation on the owner's feed — service.conversation_feed_ids: each transcript's <conv>#<at>#<i> plus the session's hub-only log#… (an ask still pending is left: archiving isn't answering) — to dismissed, publishes notif-state by: "archive" and clears them off his devices. Called by the owner's POST /api/conversation-meta {archived: true} (drawer menu, ai-agent archive, MCP archive_conversation) and archive-old; the auto-archive sweep only for a test run, ledger only (by: "auto-archive") — a cron run's push is the job's report and stays on New. Never backwards, so unarchiving brings nothing back; a guest archiving their own conversation leaves the owner's ledger alone. On home the stack leaves like any dismissal from elsewhere — slides out right, then the gap closes (PresenceRow); the archiving tab doesn't wait for the event (dropConversationNotifs).

useStore (store.ts) keeps the public names — notifNew, notifUnread, syncNotifs, dismissNotif / dismissNotifs (a whole stack in one POST), markNotifRead, notifsSeenElsewhere — but for the owner (notifMode: "server") the two lists are derived: the ids useSyncNotifs (lib/notifications.ts) has seen in the feed, by their server state. It hydrates once (loadNotifState), writes through optimistically (an outbox retried until the POST lands; actions taken before the state loaded are queued) and patches from notif-state (sseBus.ts), skipping its own echo by by (NOTIF_TAB_ID, one per tab); an SSE resync reloads it. The lists are then left out of the ui-state blob (partialize) and ignored in it (merge), so a stale tab can no longer bring a swiped card back.

The baseline: the server seeds itself from its whole feed (all dismissed) the first time, so history never floods New. The move from the old ui-state lists was a one-time import: the first owner tab to load after the deploy posts its blob's notifNew / notifUnread / notifKnown to POST /api/notifications/state/migrate (on New and read → read, on New and unread → unread, known but off New → dismissed), authoritative over the old seen-only ledger (whose ids loaded as dismissed) but never over a state set since through the live API; later calls are no-ops that answer the state. An old build's POST /api/notifications/seen still works (ids → read; its all is ignored once imported) and /seed only ever seeds once.

The feed is paged, and the baseline keeps old ids off New. GET /api/notifications?limit=60&before=<cursor> answers {conversations, count, total, nextBefore}: conversations newest-push first (then by id — a total order), nextBefore = <at>|<convId> of the page's last one (a bare <at> works as a cursor too), null on the last page; no limit is still the whole feed (count = this page, total = every page). Every push newer than a page's cursor is on that page or an earlier one, which is what useNotificationPages (lib/queries.ts, an infinite query under the QK.notifications prefix, so the SSE refreshes it; trimmed back to its first page once no view shows it) exposes as loadedSince: the history page (NotificationsHome) shows only what's at or after it, so the next page lands below, never in the middle. new=1 (the home) keeps the conversations with a push still on the owner's New list per the ledger — 229 of ~1 300 on 2026-11-02 — and is ignored for a guest. Both pages put a sentinel after the list (an IntersectionObserver on the page's scroll container, rootMargin 600 px, rebuilt whenever the list or the pages move, so a list too short to scroll keeps loading); the home first reveals its loaded stacks 20 at a time (useReveal in ConversationHome.tsx: pinned by push time so a new push doesn't push the last stack out, rows it reveals mount without the arrival animation) and only then fetches a page, while the owner's pages remain or a guest's notifNew names an id not loaded yet. Paging back syncs ids no screen ever showed, and "not in the ledger" means unread — so the ledger keeps a baseline (a push time; read_ledger.py): an unlisted id pushed before it is dismissed, on the server (the new filter, the phone's /unread) and in stateOf (store.ts). A seed or a fresh ledger's first write takes its own second. The one-time import takes the oldest push the old home could show (service.old_home_edge: the 60 conversations that ended last, from before then) — not the import's second, because the import records an unread id by leaving it out: 906 of them on 2026-11-01, the 77 waiting on the home among them. A ledger imported before the baseline existed gets that edge as of its import (imported_at, its earliest change) on first use (routes._ledger): 2026-10-30T13:51:32Z live, which keeps those 77 and turns 687 never-shown ids dismissed. Local mode (guests, the mock) has the same guard in the ui-state blob (notifBaseline): the first sync's newest push, or — for lists kept before paging — the oldest push of the first page synced since, pruning older ids from notifNew / notifUnread then.

Guests keep the old lists in their ui-state (notifMode: "local": the state routes aren't on their surface, the 403 is the cue), as does the mock backend: notifKnown (the baseline), notifNew, notifUnread, seeded by the first sync, reads posted to /api/notifications/seen (which only clears their own devices). An unread card wears its type colour, a primary border and a pinging dot; a read one goes grey (icon + type pill) and dims while collapsed — expanding is what reads it, so it stays bright while open. Hub-only log entries (log#…) are never tracked, so they always render read.

Home page: conversations or notifications (Settings → Display)

Guests read the New feed's stacks — one per conversation, wearing its tile and title — as more conversations. So since 2026-11-17 the home lists conversations by default, for everyone (settings.homeMode, null = DEFAULT_HOME_MODE in lib/homeMode.ts; Settings → Display → Home page switches back to the feed, per user):

  • Running, then Finished (UnreadConversations): the conversations that aren't running and have notifications not read yet, newest push first — the 20 newest (at most 20 card fetches for the ones past the loaded list; the rest are "N more with something new"; this mode reads only the newest page of New, never pages a backlog in) — then See all conversations. A read conversation leaves the list; a swipe marks it read without opening it; Mark all as read clears the section.
  • The dot (UnreadDot) on a conversation's tile — every card, the drawer and the cards page too — counts its unread ids (notifUnread, the read state above; a feed id is <convId>#<at>#<index>, convOfNotif). On the home a card also says its newest notification (notifLine): orange while unread, grey once read (so a running card shows its last push).
  • Inside the conversation (ThreadNotifs.tsx): opening it marks its unread notifications read (markNotifsRead, the ledger — the phone's push clears), and any that land while it's open. A closing push is drawn after the message whose ```notify block sent it (see "The closing push" above). A mid-task notify-done call stands on its own in the thread (groupThread's standalone, the summary's keepAlso), drawn open as the push (NotifyWidget via ThreadRowImpl, not a "Notified …" row); one that was unread on opening wears the dot + New for as long as the page stays on it, and NotifJumpPill ("↑ 1 new notification above") scrolls to one that's off-screen. A guest's widget reads "Notification · sent to your phone" — no device id, no DONE/action buttons.
  • The feed still loads in this mode (useNotificationPages({ onlyNew }) + useSyncNotifs): it is what flags a push unread. Hub-only log entries are never flagged, so nothing here needs a "no conversation" row.

Mockups and the decisions behind it: docs/mockups/guest-home.html (form guest-home-conversations-vs-notifications_fjb5v4).

The home usage strip (ProfileUsageCard)

Since 2026-11-26 the owner's tiles below are plugin tiles — plan-usage (gauges, burn rate, renewal) and activity (sparkline, $ today / 7 days, conversations, tokens) through provides: home.tiles, drawn by PluginTile under the old tile ids (docs/plugins.md → "The core widgets this retired"). Each tile links to its plugin's own page (its to: /plugins/plan-usage/board, /plugins/activity/activity; no to, no link — the core names no plugin page), and is named on the bench by its stashLabel ("$ today"). The core draws only a guest's own Claude gauges + budget and the Guests profile's budget bars (lib/profileUsage.ts). What follows describes the tiles as the plugins keep them.

Under the home banners, chrome-less (no background or border): the scoped profile's ★ Claude logins' 5-hour + weekly windows and its ★ opencode (OpenAI) login's reported windows (a week only) as ArcGauges (the Plan usage page's, compact), a 7-day spend sparkline, today, 7 days, conversations — and tokens, benched by default. A login with a weekTarget (the personal Max, maxed out every week — lib/weekTarget.ts mirrors usage/target.py) gets a tick on its week gauge where the week should be by now (ArcGauge target) and a "target N%" line under the reset countdown, re-read every minute. Beside it (since 2026-11-15) that login's Burn rate speedometer (BurnGauge, owner-only, plain English): list $ per hour over the last 60 min (the current hourly meter bin whole + the covered share of the previous one — usage/burn.py over calibrate.meters), the needle against the pace that brings the week to its goal at the reset ((goal − pct) / hours left, the tick at the top of the dial; the dial runs to twice it), amber + snail behind, green + flame on pace, then "need $X/h" and "→ N% at reset". GET /api/usage/burn (useUsageBurn, polled every minute — run spend fires no usage ping). Only archived runs count (no claude.ai). Asked by Gabriel to catch up a late week. Data in lib/profileUsage.ts (useUsageLimits + the profile-scoped useDailyUsage; every profile's ★ in the All view). Each reading is a tile of one HoldEditable wrapping flex row, justify-between so the tiles span the width (gauges/sparkline fixed-width, figures their text's; three a row on a phone). The arrangement is per profile — listOrders/listStashes["home-usage:<profile|all>"]; useListLayout's defaultStash — the tiles' own defaultBench (the activity plugin's tokens) — is what benches them until dragged in. A guest with their own Claude connected (since 2026-11-07) gets the strip too, same places and toggle: that login's 5-hour + week gauges and their month on the host's account against their budget (guestUsage in lib/profileUsage.ts; no spend figures — the activity plugin's daily rollup is the owner's), each linking to their Settings → My logins → Claude. The figures come from /api/me/usage (useMyUsage), which the host sidecar feeds — see "Guests' own Claude logins" → Usage %. A guest without one sees nothing new. On the owner's Guests profile each guest's budget bar adds own week N%. Where it sits depends on the screen: on a phone it heads the feed and the gauge button beside the profile switch flips settings.homeUsage (server-side, so it follows across devices); on desktop the tiles stand one under the other in a column at the page's top right (ProfileUsageCard column), in the right track of a 3-column grid that keeps the feed centred, sticky so they stay in view as the feed scrolls — and head the feed like a phone's when the page is narrower than feed + two columns (useRoomBeside in ConversationHome.tsx, 960 px). The same button shows/hides them — usePanel("usage") (lib/panels.ts), per device in localStorage, not the synced setting. (Until 2026-11-05 this was a resizable right panel, UsagePanel.)

Panels are per device, the same for every profile (lib/panels.ts, localStorage ai-agent-panels): the left drawer's open/closed (store.sidebarOpen, no longer in the server-side ui-state blob — a phone closing it on load used to close a desktop's on its next refresh, and the blob's late hydration drew it, then took it away), the conversation's Details panel (usePanel("info"), was reset on every load) and the home usage column. Only a desktop's state is remembered; on a phone each starts closed, the drawer too (initialDrawerOpen; until 2026-11-27 it opened on a load of home and covered the feed). Widths are the ResizableLayout's own (autoSaveId, also localStorage).

The drawer's way back is a floating round button (2026-11-25, Gabriel's picks in form reopening-the-left-drawer_qbujxa — guests never found the old chevron mid-divider): @gabvdl/ui ≥ 0.50 ResizableLayout's left.reopenButton draws it top-left over the page whenever the drawer is closed, phone and desktop, entering from the edge once the drawer has slid out. Every page header starts with <DrawerSlot /> (technical/DrawerSlot.tsx, the room the button sits in — always on a phone, on a desktop while the drawer is closed, gliding with the slide); a new page's header needs one too, never its own drawer toggle. Desktop closes from the drawer header's PanelLeftClose button, ⌘B or a drag; open/close slides (animate follows the Animations switch), and the conversation's Details divider lost its chevron as well (showCollapseButtons={false} — its header button toggles it). ai-agent-panels v1 reopened every drawer saved closed, once.

The drawer's list is per profile (business/conversations/filterStore.ts): each profile scope keeps its own filters — interval, message role, project / runner / owner / guest chips, archived, fuzzy, list ↔ scheduled mode and the typed search (this load only) — in ai-agent-conv-filters (byScope; the pre-profile single set, v0, seeds every profile until it is changed there). useConvFilters() reads the scope with useProfileScope, so under the drawer's DeferredScope it follows the late scope. The chips offered are the profile's own (its projects, its runners, plus whatever its conversations ran on); the scheduled list and its badge show the items whose runner sits in the profile (useProfileScheduled). A switch slides the drawer's list out and the other profile's in (usePageSwap, like home).

Stale = grey and empty. While a source has no reading fetched during this page load (limitsStale / activityStale in lib/profileUsage.ts — data restored from the persisted cache is older than PAGE_START, so it stays hidden, and the hook refetches it on mount), its tiles show labels, an empty gauge track (ArcGauge stale), flat grey bars and no figures, every line keeping its height. When the reading lands the colour comes back, each figure types in (TypeIn) while its gauge sweeps up from 0 and the bars grow.

The desktop home composer floats over the feed like the phone's (SpawnDrawer overlay, absolute at the page column's foot): the feed scrolls on under it, padded at the bottom by --spawn-drawer-h (the drawer publishes its height on <html>). SpawnBox's .spawn-lifted (index.css) gives it a deep drop-shadow filter and a lighter edge — a filter, because the card's focus ring is a box-shadow.

Card tags are exactly two rows (TagRows, on the list cards — drawer + home Running — and the /conversations grid): the box always reserves two pill rows, so cards line up tagged or not; what doesn't fit folds behind a +N more pill (in place: less folds back). Every pill is one 18 px line ([data-tag-rows] > * in index.css: fixed height, no vertical padding, nowrap, clipped at the row's width unless it has its own cap) — the pills come from everywhere with their own line-heights and borders, and a taller second row used to be cut by the box's overflow-hidden, a wrapping label to make its card taller (2026-11-27). The box reserves two rows of the tallest pill of the two rows shown, as a fallback. Measured after layout — rows by each pill's middle (items-center pills of different heights share a row), folded pills marked data-tag-fold on the DOM (the pills are the callers' components, some render nothing). A pill that shows up after the card is on screen (a task, a deploy, a worktree) pops in (popIn, 90 ms after the one before it); the ones a card mounts with are just there.

Home motion — make room, then enter

Nothing on the home page jumps (Gabriel's ask, 2026-11-01; the animated mockups are docs/mockups/home-motion.html). There is no loading screen: each section shows up when its data lands, and anything new arrives in two beats — room first (its slot opens from 0, everything below glides down), then it enters from its own edge. Leaving reverses it: out by an edge, then the gap closes. The vocabulary is technical/motion.tsx:

  • Smooth wraps each home section (ConversationHome): its height glides between whatever its child renders, and a child that renders null collapses it. Spacing is the inner box's [&:not(:empty)]:pb-6, so it goes with the section. Banners (SignedOutBanner, WorkerOfflineBanner) are enter="drawer" exit: they come down from the top of the screen and slide back up (an exit animates a DOM snapshot, the React child is already gone). glide={false} for a section whose rows animate themselves (Running, New).
  • usePresence + PresenceRow + useFlip: a keyed list that keeps a removed item rendered while it leaves. The leaving row is derived during the render that drops the item (adjust-state-while-rendering), never in an effect after it: one commit without the row would unmount it and remount a fresh copy — the swiped card snapped back and slid out a second time (motion.test.tsx pins the DOM node). Running (RunningConversations, newest first and stable — no more live re-sort by cost): a run that starts makes room at the top, slides in from the left (spring) and types its title; one that stops shows the state it ended in with a ring pulse (ending on ConversationListElement), holds, slides out right. New: one stack per conversation (groupByConversation → NotificationStack), no count badge (Gabriel: removed). Every card of a stack is always rendered and absolutely placed in the stack's own clipped box by one imperative layout (place): piled (the top card, the others shrunk into two blank sheets) or fanned out under a header with Collapse — opening, closing, a dismissal or a push only move the same elements (CSS transitions, staggered), so nothing remounts and nothing slides over the stacks above (the old fold measured offsetTop against the whole section). A card expanding resizes live (a ResizeObserver re-places without transitions). A tap fans the pile out; a swipe on the closed pile dismisses all of it (dismissNotifs), on a fanned card just that one. A long New list is revealed 20 stacks at a time as its end nears, then paged (see "Notification read state"); stacks rise in (useRiseIn): the first screenful in a cascade, the rest as they're scrolled to.
  • Swipe: the home feed's one swipe — follows the finger and fades; past a third of the width or a flick it flies off and stays gone (the row gets data-swiped, so PresenceRow / the stack only close the gap — no second slide, no snap-back); otherwise it springs back. (Not useSwipeDismiss from @gabvdl/ui, which resets the element to 0 right after onDismiss.)
  • useHeightGlide: a notification card opens and closes by gliding its height.
  • Text that appears types (ProgressiveText): a card's title when it arrives live or is retitled (CardTitle, which reserves the final height with an invisible copy), the usage figures (TypeIn), the sent card's status line (LiveText; the card itself pops from the send button, SentPreview).
  • It all skips itself when the Animations switch is off (the eye menu's animations key, also a row in Settings → Display — one switch for all motion, typed text included: useMotionOn()), under prefers-reduced-motion, in a hidden tab, without Web Animations (jsdom), and for the first 350 ms after mount — what the cache paints is simply there; only what lands later animates (the New stacks' rise-in aside).
  • A profile switch is a page swap, not arrivals (Gabriel's pick, 2026-11-02: "slide like tabs"). Animated row by row, the Personal ↔ Work toggle slid ~40 stacks out while ~15 made room and dropped in — ~60 animations, 20 of them height animations re-laying the page every frame — and froze a Pixel for ~270 ms plus ~200 ms of dropped frames (measured at 4× CPU throttle, data/log/2026-11-02-profile-switch-lag.md in the homelab). Now useSwitchProfile → swapPage: the tapped segment lights in the tap's own frame (the toggle's local picked); the page (usePageSwap on the home's content box) starts sliding out on the compositor; one frame later the scope, the colour and the lists change under holdMotion() — skipMotion() is true until that commit has painted, so presence lists swap without exits/entrances, Smooth snaps, nothing types — and the new page slides in from the picked side (transform + opacity only, so it keeps moving while the phone builds it). It starts at the top with its own first reveal batch; the phone's usage strip remounts per profile (key), its figures just there. The History drawer's panels read the scope through DeferredScope (useDeferredValue): shut on a phone, they re-render in a background render after the swap, not inside it. A new --primary restyles every element (~40 ms at 4×), so applyPalette (lib/palette.ts) skips an identical rewrite.

Conversation motion — the thread makes room, then rows come in from their side

The conversation page follows the home page's rules (Gabriel's picks, 2026-11-03, form conversation-page-motion-your-picks_psxe46; the 41 animated mockups are docs/mockups/conversation-motion.html, generated by docs/mockups/conversation-motion/build.py). The pieces, all in technical/motion.tsx and all off with the Animations switch / reduced motion / a hidden tab:

  • RowGlide wraps every thread row (history, the live ProgressiveList, summary rows, echoes). A live one (enter, the list's isNew) makes room — its box opens from 0, the pinned thread glides up — then comes in from its side (rowFrom in Conversation.tsx: Claude's rows, tools and widgets from the left, yours from the right, a tag pops, a compaction fades). After that every height change of the row glides (a message typing its next line, a widget swapping its body, an output landing): widgets don't animate their own heights. The thread's spacing is the row's inner pt-2 (inside the animated box — a space-y margin would snap), and the row must stay the same element when its content changes kind (a lone call turning into a group), so the RowGlide is the ProgressiveList child, around renderGroup. Content growing during the room re-targets it instead of cancelling it. Inside a row: useLivePop / <LivePop> pop what mounts after the row was on screen (useRowLive), useRowEntering times a divider on the row's entrance (drawRule: the label pops, the rules draw out), useRowTakeOver glides from another row's height.

  • Your message is one card from send to landed. The echo rises out of the composer (from="lift", only for one sent after the page opened), its pill retypes (LiveText), no whole-card pulse. landedPairs (lib/outbox.ts) matches it to its turn during the render; the landed turn is stamped 0 for the ProgressiveList (the lag limit lands it at once, no entrance) and gets landing — it glides from the echo's height (data-echo-mi), the echo's pill shrinks away (LandingPill), its time types in — and calls markShown(mi) from its layout effect. The outbox entry is only dropped once its row is shown (or after 10 s): dropping it in the effect raced the store's re-render against the hand-off and the echo vanished first.

  • Folds: every <details> in the thread glides (index.css, [data-motion] details — ::details-content + interpolate-size, Chrome 131+, snaps elsewhere); RowGlide only follows during a toggle. A summary fold opens with Unfold (height + a 70 ms cascade). The jump flash is .conv-flash (fade in, hold, breathe out) on message cards, widgets and forms.

  • Page swaps: Summary ↔ Full (the toggle, a run finishing under the reader in useSummaryMode, a send unfolding it) and Thread ↔ Changes slide like tabs — swapView(dir, change, channel) on channels summary / changes, usePageSwap(…, dim): they leave dimmed (35 %), not gone, because a long thread takes a while to build and a blank showed between the two.

  • Around the thread: the waiting card above the composer drops into its slot (Smooth enter="drop" exit); the published summary and the local-model strip make room and rise, "Cache expired" pops (Smooth enter="pop"), the cache countdown fades in and rolls; Appear brings in 3× from the left and the waiting strip from behind the composer, and pops Interrupt and the Thread | Changes switch (room: their neighbours glide aside); the title retypes (LiveText, keyed by conversation), the lead tile ends a run with one ring pulse.

  • Widgets use technical/motionBits.tsx, whose one rule is only a live change moves: useLiveRef / isLive (the row's flag inside a RowGlide, the component's own first 350 ms outside one), ShrinkAway (children that shrink out when show turns false — a call's running dot, a form's action row, notify-ask's other options), ArriveText / TypeLines (text and answers typing in when they show up live — in a timeline slot of their own: a ProgressiveText in a row that is no longer the reveal's head ignores a text change), LiveEnter, usePopWhen, growFrom / shrinkTo (a preview or menu growing from where it was tapped), useTransitions (CSS colour cross-fades only once live). A running call breathes an amber dot (ThreadRunningContext), its figures pop in left to right when the result lands; a lone call turning into a group gets morphFrom and retypes from its label; the subagent card cross-fades amber → done; the task panel slides in from the right, strikes its done tasks across and collapses into its pill; the deploy gizmo makes room, then pops.

  • Catching up (business/conversations/catchUp.ts, Gabriel's picks 2026-11-06, form conversation-loading-indicator_mrhf8z): from opening / switching to a conversation, or the app coming back after ≥ 15 s hidden, until the first fresh read lands (dataUpdatedAt / errorUpdatedAt past the mark; gives up after 30 s), a thin indeterminate sliver (technical/LoadingSliver, .sliver-bar) sits under the header — shown only past 150 ms, never for a streaming run's live refetches. An uncached conversation shows an empty thread and its title typing in (a cached list's title first, cachedTitle). What the read brought — the rows past the count the thread had when it began, the last 8 — rises in from the bottom (.conv-arrive, staggered d0…d7) instead of landing at once; such a row skips its RowGlide entrance (one motion, not two).

Probing it: the mock build streams a real resume (npm run build:mock, served with an SPA fallback), and a browser-gateway /function script that sends a reply and samples the DOM every frame (cards with the text, the thread's running animations) shows the hand-off in numbers — echo → row in one frame. Bypass the PWA's service worker (page.setBypassServiceWorker) or it serves the previous build.

"Waiting for feedback" — the home page's answer queue

The home page opens with the one list that is waiting on the user: every open ask-form form (askform/, the standalone ask-form tool the ask-form skill and the clarifier use — answered on its own page, so the card's Answer opens the link), every pending hub form (forms/, the New project dialog and a plan's questions) and every pending ask (notify.py, the notify-done skill's tappable choice), above the Running rail and the notification feed. lib/waiting.ts merges the three sources and joins each question to its conversation by sessionId; the section (conversations/components/WaitingForFeedback.tsx) renders it amber with a spinner while that session is still running and red once it isn't, and reports the conversation ids it showed so the Running rail below skips them.

Three things make that work, and each is easy to break:

  • Both skills must stamp sessionId. It is the only link back to a conversation — a question with no session still renders, but as an orphan card. ask.sh resolves it the same way notify.sh and ask-form.sh do ($CLAUDE_SESSION_ID, else conv-meta's resolve-session.sh).
  • A question can be older than the loaded page. The home list is the first ~50 conversations, so GET /api/conversations?sessions=a,b,c resolves exactly the ids a first pass missed (archived included, no paging). Never reach for limit=0 here — the full lite list is ~1.5 MB for one title.
  • Both kinds are answerable in place. A form flips ?form=<id> and the page's own <FormModal/> opens it full-screen (no navigation); an ask POSTs to /api/ask/{id}/answer — the very endpoint the phone's tapped button uses, so the agent's long-poll wakes either way.

An ask the backend still calls pending past its expiresAt is filtered out client-side: notify.py only flips a lapsed ask to expired when that ask is read, so the list would otherwise keep showing dead questions.

The bell — every profile's questions (since 2026-11-20). The section shows only the profile on screen, so a form a Work run posted went unseen while Personal was up. FeedbackBell (conversations/components/FeedbackBell.tsx) sits left of the profile toggle wherever it is (home's top bar, the conversation drawer's header; owner only, once there are two profiles): its badge counts every pending question of every profile, it wobbles once when the count goes up (.bell-ring), muted when nothing waits; its panel (portaled, fixed — the drawer clips) lists them newest first with a profile pill, and answers in place without a profile switch (a hub form → ?form= on the page on screen, an ask-form → the app-wide frame with no conversationId, an ask's buttons inline; only the conversation title navigates). The toggle's unlit segment gets a rose dot with that profile's question count (useQuestionsByProfile, outranks the orange running dot); a question with no profile (an approval: no session) is on every home, so on no dot. The section and the bell share lib/pendingQuestions.ts (usePendingQuestions, the by-session lookup, the dismissed-ids store — a dismiss on home leaves the bell too). On a phone the home bar drops its title while the bell is there (PageHeader textOffPhone). Gabriel's picks: forms ask-bell-next-to-profile-toggle_jendaq, bell-drawer-final-check_urknbq.

Dismissals follow you; Revoke ends a form (2026-11-26, forms storage-moves-gabriel-s-decisions_jtewhl / storage-plan-confirmation_5p8nuc). Dismiss only hides a card — the question stays pending — and the hidden list is server-side (useDismissedQuestions, ui-state ai-agent-dismissed-questions, {at: {id: ms}}, the 1 000 newest), so an old conversation's form dismissed on the phone stays dismissed at the desk and in a fresh browser. Each browser's old local list (waitingForFeedback.dismissed) is merged in on its first load, then deleted. Every ask-form card has Revoke beside it (second tap confirms, endAskForm) — on home too. Home's section and the stack above a conversation's composer show the 4 newest; Show N more opens the rest in place, Show less folds them (useShowMore in WaitingForFeedback.tsx).

Answering questions inside the conversation thread

Every question kind an agent can ask has an in-thread widget, so it is answerable from the conversation itself, not only from the home queue or the phone. Conversation.tsx's groupThread pulls each one out of the collapsed tool group (gated by the Form cards visibility switch):

how the agent asks parser → widget answer goes to
`ask-form create wait get
notify-ask … / ask.sh (2–3-button choice) parseAsk → notifications/components/AskWidget.tsx POST /api/ask/{id}/answer
a plan's ## Questions json fence the Plans live plugin's plan page → Answer questions opens it as an ask-form (askFormId in the plan) the ask-form; the plugin writes ## Answers
a clarifier subagent's ask-form (in its own transcript — any depth) SubagentRef.formRefs → hoisted by hoistAgentForms into its own kind: "form" row where it opened → AgentFormCard (AskFormCard tagged via clarifier); the Agent card keeps a "📋 1 form ↓" chip the form's page

The hub's own form engine is gone (2026-11-25). backend/forms/ (frm_…, /api/forms, FormStore, SecretStore), the FormWidget / FormModal / FormPager / formDraft front end and notify form | wait frm_ | cancel | secret were retired once Approvals, New project and Plans moved onto the ask-form live plugin (requires: ["ask-form"]; Gabriel's call: "retire completely", no read-only viewer). Every form is an ask-form now — its paging, catch-all and secret fields are the standalone tool's (ask-form secret). An old conversation's notify form / FORM_ID=frm_… calls render as plain shell output; /forms redirects to the ask-form plugin's Forms page. forms/components/SandboxedHtml.tsx and the dock (FormDock, formDock.ts, ask-form frames only) stay.

AskWidget resolves the ask record from the ASK_ID= stdout (a --background ask) or the id on a notify-ask wait <id> call (Bash or Monitor); a blocking ask with no id is matched in the notify log by question text + nearest time. Its query key sits under QK.notifyLog, so the SSE notification event refreshes the card the instant any surface answers. AskUserQuestion stays a read-only card: it is disabled in spawns, and a Claude Code process has no channel to take its answer from the viewer.

Long blocks: clipped at 8,000 chars, Show more unfolds the rest (since 2026-11-25)

The parser ships at most MAX_BLOCK (8,000) chars of any text block — a message, a thinking block, a compaction summary, a skill body, a tool output, a Code Mode result — so the thread payload stays bounded. records._clip cuts on a clean boundary so the part shown still renders: a blank line outside any code fence (a table or list kept whole), else between two lines outside a fence (never between a table's header and its rule), else inside the fence with the fence closed again; tool output (markdown=False) at the last line end. No marker goes into the text: the item carries clipped ({field: full length}) and a clipId, and ParserState._set_clipped keeps the full text (clip_fields, full_field, last_answer). Clip ids follow the transcript's order, so a fresh parse gives the same ones.

  • The viewer: fullText.ts (useClipped, wholeField) + components/ShowMore.tsx — a fade over the last lines and Show N more characters, which fetches GET /api/conversation-full-text?id=&clip= once (conversations.read) and re-renders the item whole; Show less folds it. Wired into message and thinking rows (Conversation.tsx), the compaction divider, every tool card (ToolBody in ToolUse.tsx, the orphan ToolResult), and the message menu's Copy / Edit & fork (they use the whole text).
  • Answers are whole too: the CLI's detail() (so wait, show, the MCP tools) fetches a clipped message's rest, and the backend's runs/guestjob.final_answer (a child's report back, guest deliveries) and the plugin hub route read ParserState.full_field / last_answer.
  • Mock: conv-long-report (a clipped tool output and a clipped message ending on a table) and MOCK_FULL_TEXT in mock/seed.ts.

Deep-linking a prompt into the composer (?q= / ?qt=)

Any page URL can arrive with a prompt already written for it:

https://ai-agent.lab.gabvdl.xyz/?q=Deploy%20the%20lab&qt=project:homelab,skill:open-pr
https://ai-agent.lab.gabvdl.xyz/files?q=Summarise%20today&qt=radar

q is the prompt text, qt a CSV of tags to switch on — a full chip id (project:homelab, service:gitea, skill:open-pr, a guideline's id) or the bare slug (homelab, open-pr), matched case-insensitively, because a link written by hand shouldn't have to know which namespace a name lives in. Either param works alone. A selector that matches nothing is ignored, so a link naming a since-renamed project still delivers its prompt.

Nothing is sent: the draft sits in the composer for a read-over and a tap on send. A URL that spawned outright would be a GET that starts an agent run — one stale bookmark or link preview away from a session nobody asked for.

Three things make it work, in business/composer/useSpawnUrlPrompt.ts:

  • It is read in GlobalSpawn, not in the composer. The composer is unmounted on half the pages a link can point at (desktop-docked shows only a launcher button off the home feed); GlobalSpawn is the one always-mounted host. It calls openWith, which surfaces the composer as well as filling it.
  • The params are stripped afterwards (setSearchParams(…, {replace: true}), the same one-shot treatment ?form= gets), so a refresh or a Back/Forward can't re-stomp what has since been typed.
  • A deep link overwrites a draft in progress; the in-app buttons don't. That is the replace flag on SpawnPrefill (lib/spawnDock.ts) — the Goals checklist's Work button and the Plan page's Implement button still stand down when something is already typed. Following a link with a prompt in it is a deliberate act, and silently dropping it is the worse surprise.

The tag half is the fiddly part. RichInput owns its selection — there is no setTags on RichInputHandle — so a preselection can only get in as defaultOn flags on the tags themselves (withPreselect, lib/richComposer.tsx). Hence the two-step consume in SpawnComposer: one commit to put the flags on composerTags, the next to clear() the composer onto them. That clear() is load-bearing twice over — it re-seeds the selection from the fresh defaultOn flags, and it drops the cacheKey="spawn" draft, whose own remembered tag ids RichInput otherwise re-applies over the selection every time the tag list grows (and it grows: locations arrive from /api/projects after the first paint). useSpawnUrlPrompt.test.tsx pins all three cases — preselected on, un-named tag left off, cached draft overwritten.

Sharing to the app from another app (the share target)

The installed PWA is in Android's share sheet (2026-11-03): sharing a link, a text, a screenshot or any file to it opens the new-session composer on it, the text in the box and the files attached. Nothing is sent. It works for the owner and for guests. iOS has no share targets for web apps, so there it doesn't appear. Four pieces:

  • The manifest's share_target (frontend/vite.config.ts): a multipart POST /share with title / text / url / files (accept: */*). Android reads an installed app's manifest on its own schedule, so a change there can take about a day to reach a phone; reinstalling forces it.
  • The service worker answers that POST itself (frontend/public/share-sw.js, in sw.js through workbox importScripts, like push-sw.js). It stashes the files plus a meta entry in Cache Storage (ai-agent-share, /__share/<id>/…), then 303s to /?share=<id>, which the precached shell serves without the network. Shares never picked up are pruned after a day. Stashing, rather than uploading from the worker, is what lets a share survive an expired Authelia session.
  • useShareTarget (business/composer/, read in GlobalSpawn like ?q=) uploads the files through /api/upload, then calls openWith(text, …, {replace: true, files}). It shows ShareNotice (top of the screen, clear of the drawer) while the upload runs, and Retry / Dismiss if it fails; Dismiss still puts the text in. ?share= leaves the URL only once the share is in the composer or dropped, because the re-auth round trip comes back to the same URL and must find it there. Like a deep link, a share replaces the draft in progress: RichInputHandle has setFiles but no getter, so there is no way to add to the draft's files. SpawnPrefill.files is how the files reach setFiles.
  • POST /share on the backend (main.py, next to the SPA fallback) handles a client that has no worker yet. It 303s the text to /?q= and drops the files, instead of answering 405. _share_text mirrors shareText(): each field once, and a title or link the text already contains isn't repeated (Chrome puts the page URL in text).

Tests: useShareTarget.test.tsx (text, files, failed upload → retry/dismiss, stale id) and backend/test_share_target.py.

The reply box folds while away (ResumeBox + lib/foldWhenAway.ts)

Unfocused, the conversation's reply box is just its text field (placeholder, or the draft): every row RichInput renders under the textarea — tag chips, toolbar with the run pickers and send — folds away, and comes back on focus or a tap. Two parts:

  • When — useFoldWhenAway judges "inside" on the React tree: the root's onPointerDown / onFocus tag the native event, and document pointerdown / focusin listeners (which run after React's) fold only on an untagged one. A DOM focus-within would fold the row the moment a picker's popover (portaled to <body>) opens, and on a browser that doesn't focus clicked buttons, before the click on a picker lands. A blocked send (log in / connect) never folds — its way out is in the row.
  • How — plain CSS in index.css (.resume-fold[data-folded] div:has(> textarea) ~ *): height 0, unfocusable, animated to and from auto via interpolate-size (Chrome 129+; snaps elsewhere, prefers-reduced-motion off). It relies on RichInput's markup — the rows are the textarea wrapper's later siblings; recheck after a @gabvdl/ui bump. The placeholders stay one line at 360 px (the textarea is monospace, ≈ 35 characters).

The composers' send button is pinned (ComposerFrame)

Both composers (spawn, resume) keep RichInput's hold-to-rearrange toolbar (toolbarReorder) for every control except send. The arrangement is per profile and server-side (lib/toolbarLayouts.ts, ui-state ai-agent-toolbars, keys spawn:<profile> / resume:<profile>): RichInput keeps it in localStorage (rich-input:toolbar:<key>) and fires gabvdl-ui:storage on each write, which the bridge mirrors up; on hydration it writes the server's back and fires the same event so a mounted toolbar takes it. A profile's first key is seeded from the old shared spawn / resume arrangement. toolbarLayouts.test.tsx runs the library's real hook — recheck after a @gabvdl/ui bump. Send is always visible, always the row's right-most element, and can't be picked up, moved or benched. (Benched controls stay a tap away: while the stash holds any, @gabvdl/ui ≥ 0.43 adds a movable + control — first just before send — whose menu holds the benched controls themselves.) RichInput has no slot outside its HoldEditable group (send is always one of its entries), so business/composer/components/ComposerFrame.tsx wraps the RichInput and its renderSendButton (pinSend(render)): the button is portaled into the frame's own .composer-send-slot, a zero-width anchor stays in the group's send entry. The slot is data-hold-editable-ignore (React bubbles the portal's presses through the entry) and the button runs its own long-press (SendMenuButton uncontrolled — the reorderable toolbar's menuOpen pair is dropped). Layout is CSS in index.css (.composer-frame): the slot is pinned over the row's right end, the row stops short of it by its live width (--composer-send-w, measured — Log in to send is wider), the anchor's entry gives its gap back. It mirrors RichInput's card geometry (1px border + p-2, the row's px-1, h-8 controls) — recheck after a @gabvdl/ui bump. A toolbarTrailing-style slot in RichInput would retire it.

The rest of the row scrolls sideways, never wraps (same CSS block): items don't shrink, no scrollbar, and since a scroller clips both axes the row pads room for what hangs over its controls (drafts count, status dots, edit mode's jump); the drafts dropdown, which would be clipped, hangs off the card instead. A content-sized ancestor would still let the row's min-content push the composer past a phone's edge — the spawn drawer's grid item carries min-w-0 for that.

Resources row and composer motion (@gabvdl/ui ≥ 0.44)

Both composers pass tagList="link": the ~60 projects, services, skills and agents (group: "list" tags) are not on screen as a scrollable box. One row under the guidelines holds a 🔍 pill (Link resources — it opens the filter, the whole list unfolding under the row; Enter links the first match, Escape folds it), the linked resources (solid) and what auto-tag matched in the text (dashed — a tap links it, in place). Auto-tag reads the text after a 600 ms pause (AUTO_TAG in lib/richComposer.tsx) and keeps that reading while the typing goes on, so the row only changes at a pause. Picked in form composer-feel-guidelines-resources-motion_3wcw9m (2026-11-02).

The motion lives in RichInput (rich-input/motion.ts), switched by motion={useMotionOn()} — the app's Animations switch: waking the spawn box (collapseWhenIdle) opens the rows' room and pops the pills in left to right, idling folds them; guideline children and the resources pop in and shrink out while their neighbours glide; the toolbar's controls rise in when the composer mounts (expanding the collapsed strip too), and a harness switch pops/shrinks the controls that come and go. The toolbar's leaving controls are ghosts — inert copies of the removed node, laid back in its old place for the 180 ms exit — so HoldEditable's item list never holds a stale entry.

The un-send window (lib/undoWindow.ts + RichInput's held)

A new session's send, and every reply in a conversation (idle or running — a running one it would interrupt), are held 3 s (each user's own length, 1–5 s — Settings → Composer, unsendMs) before anything goes out: the composer locks on what was sent — RichInput's held prop shows the text, chips and attachments read-only under an overlay whose wash sweeps left → right while "Sending… tap to cancel · Ns" counts down; a tap on it (or Escape) takes it back. The sweep is drawn from useUndoWindow's startedAt, so a composer remounting mid-window (the dock ↔ float switch) resumes it where it was; the textarea is read-only, not disabled, so it keeps focus (and the phone keyboard). The spawn holds through useUndoWindow in SpawnProvider (app-level, so it still fires if the composer unmounts); a reply holds in the outbox (lib/outbox.ts, below) — the window keeps running while you are in another conversation and fires to its own. cancel() refuses once fired, so a tap racing the timer can't leave a send behind and hand the draft back. The resume reply is only echoed into the thread once it fires.

Length and curve (Settings → Composer, business/settings/components/ComposerSettings.tsx): the window's length is per user (settings.unsendMs, clamped by clampUndoMs; guests set theirs too); the outbox stamps it on each entry (holdMs), so a reload re-arms for what is left of that send's window, and useUndoWindow keeps a held spawn's own length if the setting moves mid-window. The sweep's timing is an @gabvdl/ui AnimationCurve edited with its CurveEditor (lazy chunk UnsendCurveEditor.tsx: presets, reset, a replica composer under the real UnsendOverlay playing in sync) — the owner's, for everyone: settings.unsendCurve (null = the library default); guests read it live from /api/me → unsendCurve (backend settings/unsend.py, validated; an owner save that changes it pings their clients like a shortcut change). lib/unsend.ts (useUnsendMs, useUnsendCurve) is what the composers read.

Through the un-send window the composer stays locked on the send as sent: its account / Runs on / Chrome / Code / New project picks clear only once it fires (or is dropped) — pinsHeld in SpawnComposer; resetting them at queue time showed auto's runner (the MacBook) under a devbox send. An un-send keeps them for the restored draft.

Once a new session's send has fired, the composer empties and the sent card (business/composer/components/SentPreview.tsx — status line, text, the guideline/tag chips that went with it, attachments) takes over above it: "starting session…" → "waiting for it to sync…" → "session ready — tap to open" (no auto-redirect); a swipe dismisses it. The reply box has no card.

Whatever hands a draft back — un-send, a cancelled Send later or model switch, a failed resume — restores it as it was sent, tag selection included (spawn: the account/runner pins too), not the defaults a send resets RichInput to. RichInput has no selection setter, so business/composer/useComposerRestore.ts goes through the one door it has: for one commit the composer's tags carry defaultOn = exactly the saved ids, then clear() re-seeds onto them (the ?qt= prefill's trick). The selection is snapshotted in onSubmit from the composer's selected mirror (still pre-reset there), master-muted chips included.

The reply box is its conversation's (lib/outbox.ts)

The conversation page is one React instance for every /conversation/:id — a switch (a link, the drawer, the profile toggle, which jumps to that profile's open conversation) only changes the id. Anything kept in the page or in its ResumeBox used to ride into the next conversation: a reply held in its un-send window locked the next conversation's composer, its echo was drawn in the next thread (one page-level slot, wiped on every switch, so coming back showed nothing), and that echo's Stop & send now resent it to the session on screen. So:

  • <ResumeBox key={sessionId}> — a fresh box per conversation; its run picks (harness / model / thinking / effort) live per session in lib/replyPicks.ts (server-side ui-state ai-agent-reply-picks since 2026-11-26 — a pick made at the desk is the phone's too; the old local ai-agent:reply-picks is merged in once per browser), so they survive a visit without leaking.
  • The outbox (zustand, localStorage) holds every reply from send until its user turn lands, keyed by session: the 3 s timer, the request (always to the entry's sessionId) and the status — holding → sending → started (plain resume) | queued (live run's inbox) | now (Stop & send now); waiting (the window ran out while the lab was unreachable — parked, never sent, goes out by itself once it answers; Edit / Dismiss — see "Off the tailnet" below); failed (Retry / Edit / Dismiss — a send that fails also puts its text back in its own box, on return if you were away); takeover (a terminal holds the worker session — Continue here); returned (taken by the box on mount). landedIds drops an entry once its user turn is in the thread: by text (the typed text heads the turn) for every status that may have left the browser — sending and failed too, since a request whose answer never came back may have arrived (a worker's resume takes seconds; that is how a work conversation's replies sat "not sent" after landing and got sent twice) — then by position (first free user turn past where it went out) for one known to be on its way; oldest first, one turn each, tool cards alone never land a queued one. A transport error (no HTTP answer) is not failed: the entry waits as started and goes stale only if nothing lands. A failed one whose copy went back to the box and then lands clears that copy (landedDrafts). The status pill's tooltip shows status · sent time · item.
  • Reload: a window still running re-arms for what's left; one that ran out while the page was gone still sends within 30 s (RELOAD_GRACE_MS), later it comes back as a draft ("Not sent — …") instead of going out stale. Entries are per tab (TAB_ID in sessionStorage): only the sending tab fires, shows and writes one, so two tabs never double-send; a closed tab's held reply is adopted as a draft by the next one.
  • Server truth for queued follow-ups: the parser keeps the run's input queue from the transcript's queue-operation records (enqueue → dequeue / remove absorbed_mid_turn, FIFO; an enqueue+dequeue back to back means a new process, so anything older died with the last one) and the conversation carries queued: [{text, at}] — the inbox follow-ups not read yet. Shown while the run is live, deduped against this tab's entries by prompt, so a queued message sent from the phone shows at the desk (queued · another device) and survives a reload or a cleared cache.
  • Cancel a queued message. Nothing pulls a message back out of the CLI's queue, so the echo's Cancel sends a note after it (cancelNote: <ai-agent-cancel/> + the prompt quoted verbatim between <<</>>>) with /api/resume inboxOnly — the inbox or nothing, never a new run (no run left ⇒ the message died with it, the entry is dropped). The model reads both at the same tool boundary and drops the first. The parser hides the note (it starts with <), marks the quoted message cancelled (a pill on the user row) and removes both from queued. A message the model already read can't be un-read — the note then tells it to stop.
  • In the thread: one OutboxEchoRow per pending message (OutboxEchoes.tsx), each with its status pill; scrolled up, a strip over the thread's foot says "N waiting · …" (red when one failed). A card in a list shows only a failure (NotSentBadge, useSendFailed) — Gabriel's call: normal sends stay in the thread.
  • Drafts: @gabvdl/ui ≥ 0.40.2 writes the debounced draft at once on a cacheKey change, unmount and pagehide; since 0.47 the reply box's draft is kept on the server (next section).

Drafts follow you across devices (lib/drafts.ts, backend/drafts/, /drafts)

Every composer's draft lives on the server (2026-11-06), per user — the owner's and each guest's — so a prompt started on the phone is waiting at the desk. @gabvdl/ui ≥ 0.47 takes a draftStore (RichDraftStore: get / set / remove + subscribe) and a draftKey (the draft's namespace; cacheKey keeps only the history):

  • Keys: draft:<draftKey> = the live draft (text, tags, master switch and the uploaded files — never a browser File/object URL) and drafts:<draftKey> = the Save as draft shelf; draftKey = spawn:<profileId> for the home composer (one per profile — the Perso / Work switch swaps the draft; a guest's is spawn:<default>) and resume:<sessionId> for a reply box.
  • Backend (drafts/store.py, /data/drafts.json, one record per user + key {value, updatedAt, device}, value ≤ 512 KB and JSON, 400 keys per user, the stalest dropped): GET /api/drafts, GET|PUT|DELETE /api/drafts/{key} (guests allowed — keyed by caller, nobody else's). Each change publishes SSE {"type": "drafts", user, key, updatedAt, device, deleted?}; a guest's stream carries only their own (core/routes.py), the owner's tabs skip another user's.
  • Client (lib/drafts.ts): get answers from an in-memory map mirrored to localStorage (a cold start paints the last known drafts); set / remove mark the key dirty and send a per-key debounced PUT / DELETE (800 ms; on pagehide / hidden with keepalive; a failed one retries every 15 s). A dirty key is never overwritten from the server — this device's next write wins. useDraftSync (App shell) starts it once /api/me answers (another user's cached drafts dropped first), reads the list, and imports the old localStorage drafts once per device (rich-input:draft*:*; the old single spawn key goes to the default profile's). SSE drafts from another tab (DRAFTS_DEVICE, per tab) refetches that key; resync re-reads all.
  • The Up-arrow history stays per browser (rich-input:history:<cacheKey>, ≤ 100 prompts): one key per reply box (resume:<sessionId>), so lib/storageSweep.ts keeps the 100 most recent conversations' — past 100 keys, at most once a day, one ?limit=100&archived=all list read (an empty or failed list deletes nothing). It also drops the dead ai-agent:floating-composer:* keys. Both run 5 s after boot (main.tsx).
  • Two devices at once (Gabriel's call): RichInput takes a change made elsewhere only while it isn't being typed in — not focused, nothing sending/held, no write owed by its debounce; otherwise it waits for the blur (useDraft's canReplace / refresh). The shelf is last-write-wins as a whole.
  • The Drafts page (business/drafts/, /drafts; owner: Files → Drafts with the Perso / Work / All ProfileSwitch; a guest: Me → Drafts): New prompts (each profile's home composer: what is in it + its shelf) and Replies (per conversation, resolved with ?sessions=, filtered by profileOfConv; one not resolved is listed under All only). Open puts a saved draft back into its composer with the shelf's swap (what the composer held becomes a saved draft — restoreFromShelf) and goes there (home on that profile, or the conversation); Copy; Delete with an Undo toast.

Off the tailnet: the app greys (lib/reachability.ts)

ai-agent.lab only answers over Tailscale, and navigator.onLine stays true on Wi-Fi/4G with Tailscale off — while the service worker answers every /api GET from its NetworkFirst cache, so nothing errors and the page just freezes. useReach says whether the lab answers: ok | offline (no network) | tailnet (the private host is silent but the public guest host ai-agent.gabvdl.xyz answers a no-cors probe — the lab is up, this device is off the tailnet) | down (nothing answers, or a 5xx). It looks when the SSE stream drops, when the app returns to the foreground, every 30 s on screen with a quiet stream (Tailscale switched off under an open page leaves the stream "open" on a dead connection — the server's : ping comments never surface), and every 5 s while bad. /api/health is kept out of the worker's cache (vite.config.ts) or the probe would be answered from it. A bad state shows after GRACE_MS (5 s); the stream opening, or a probe answering, clears it at once — a probe revives a stream that closed for good or is a zombie and catches up in full (a fresh EventSource has no Last-Event-ID).

Shown = grey only (Gabriel's pick, form off-tailnet-cue 2026-11-02 — no banner, pill, status-bar colour or "back" toast): ReachStatus puts .reach-stale on <html> and every data-stale-surface goes grayscale(1) at 42 % — the page (App's Outlet wrapper), the drawer, and in a conversation only the thread (its header and composer keep working; the nav and the spawn composer are never grey). A screen reader gets one role=status line. Replies sent meanwhile wait in the outbox (waiting, pill "waiting for the lab") and go out, oldest first, when the lab answers again; a reload re-checks before sending them. New-conversation spawns are not queued.

Fresh context: compact instead of replaying (lib/freshContext.ts)

A reply resumes the session, which replays the whole thread. Claude Code writes the prompt cache with the 1-hour TTL, so within the hour a resume reads ~99 % of the context from cache (a new process included). Past it, the whole context is written again at 2× input: a median $1.22 on Opus for the first call alone. The reply box nudges then:

  • a pill closing the thread ("Cache expired 2 h ago ⓘ", after the last message and any summary card), with no figures and no dismiss; tapping it opens the estimate as a read-only sheet;
  • a confirm on send over the same estimate: Cancel / Send anyway / Fresh & send;
  • a "cache warm · N min" chip in the cache's last half hour;
  • Send with fresh context in the send button's long-press menu, for any other time.

Auto fresh skips the confirm: a send the nudge applies to compacts first, and the pill reads "… · next reply starts fresh". It is per person — the owner's in Settings → Fresh context (autoFresh in fresh-context.json, off by default), a guest's on their users.json record (autoFresh, on unless they turn it off in their Settings → Composer or the owner on their Users page; users/store.py auto_fresh, served as Me.autoFresh). The reply box reads the caller's through useAutoFresh (FreshContext.tsx). Off, the confirm opens as before.

The estimate prices the context cost of the rest of the conversation, continue vs fresh, for three follow-up sizes measured on the lab's transcripts: a quick question (< 5 API calls, 7 %), a fixes follow-up (5–89, 75 %) and a big feature (90+, 18 %). The nudge fires when the expectation, each size weighted by its share, saves at least the Settings → Fresh context thresholds (≥ $0.50 and ≥ 25 % by default).

Fresh = the CLI's own /compact, run headless on Haiku with our instructions (backend runs/fresh.py), then the reply on the conversation's model. The sidecar chains the two as one run (harness-claude's sidecar/claude_launch.py _chain). It stays the same session, so tags, worktree and links don't move. The thread shows a kind: "compact" divider, with what it dropped, its cost (read off the CLI's cost-state records) and the summary folded. The measurements, the formula and the sample compactions are in docs/fresh-context.md; scripts/fresh-context-calibration.py re-measures them.

Outside the hub: cache-score (its own public repo, ~/projects/cache-score, since 2026-11-17) is the same idea packaged as a Claude Code plugin for people who only use a terminal: a report scoring how much re-sent context came from cache, with cold returns in list $ and plan %, a status line on the CLI's prompt_cache field, and a nudge before the first message into an expired cache. Its plan rates are seeded from usage/calibrate.py's fits. Two things carry over here. A terminal /compact is not the hub's Haiku compaction: on a cold cache it re-processes the whole history uncached. And its nudge goes by CLAUDE_CODE_ENTRYPOINT, so the sidecar's resumes are never held.

Keyboard shortcuts (lib/keyboard/, business/keyboard/; the keymap is the keyboard-shortcuts plugin's)

Since 2026-11-19 the app works keyboard-only, Linear-style (Gabriel's picks in form keyboard-only-ai-agent_eh0l4w): single keys and g sequences fire while no text field has the focus (Esc leaves one — only when nobody else claimed the Esc), and bindings with ⌘/Ctrl or Alt fire while typing too.

Since 2026-11-27 (form keyboard-shortcuts-as-a-plugin_2aqd47) which keys run what is a live plugin's: keyboard-shortcuts (~/projects/ai-agent-plugins/plugins/keyboard-shortcuts) owns the defaults, each person's own bindings, the on/off switch, Settings → Keyboard (its nav: "settings" page; /settings/keyboard redirects there) and the cheat sheet (its app.modal slot). No plugin, no shortcuts — the composers keep their own ⌘↵, ↑, Ctrl+R and Esc. The core keeps what a sandboxed frame can't do: the listener, the commands and their handlers. Platform points: docs/plugins.md → "Keyboard shortcuts".

  • Commands — lib/keyboard/actions.ts: every command the app answers (id, group, label, context, repeat, owner; no keys). sidebar, search, settings.search, conv.new / reply / nextActive / prevActive / nextUnread, list.next / prev, composer.guidelines, composer.chip.1…9 (the Nth guideline chip in a composer), go.*, profile.cycle / profile.1…9 (owner). Two families on top: composer.shortcut:<chip id> (a named guideline chip — the person gives a prompt shortcut its own key on the plugin's page; useComposerKeys registers one per chip) and modal:<pluginId>:<slotId> (opens that plugin's app.modal slot, or closes it when it is the one open — KeyboardHost). A composer command wins over a global one on the same key inside a composer, so Alt+N is the chip there and the profile elsewhere.
  • The keymap — business/keyboard/keymap.ts (useKeymap, useKeymapIndex, useCommandKeys): GET /api/plugins/keymap (backend/plugins/keymap.py, the app.keymap provider run as the caller, sanitized, cached; the last answer kept in localStorage so the first key after a load works). Refetched on SSE keymap (the plugin's page saved, any device) and on any plugin change (a peer turning on changes it).
  • Keys — lib/keyboard/keys.ts: chords are mod+ctrl+alt+shift+key (mod = ⌘ on a Mac, Ctrl elsewhere), a binding is one chord or two (g h). Digits come off the physical top row and Alt combos off the physical key (a Mac's Alt mangles e.key; AZERTY's 1 is &); a symbol that needs Shift keeps it in the character (?). The plugin's recorder goes through the same chordFromEvent (the frames' keyChord bridge), so a recorded binding matches on the layout it was recorded on.
  • Handlers — lib/keyboard/registry.ts: useShortcut(s) registers a handler where the state lives (composers: business/keyboard/useComposerKeys, the drawer's j/k, the app-wide ones in KeyboardHost). Dispatch order: the handler whose root holds the focus, then priority (reply box 2 > new composer 1 > app-wide fallback −1), then the newest; returning false passes the key on. A composer's root carries data-kb-composer.
  • The listener — business/keyboard/components/KeyboardHost.tsx, once in App.tsx. Leaves alone: a defaultPrevented key, IME composition, a canvas (the lab browser's take-over), [data-kb-ignore], and any aria-modal dialog — but over a plugin modal that modal's own command still acts (⌘K closes the palette, ? the cheat sheet). It also publishes what the frames' commands() / places() / conversations() bridges answer (business/keyboard/commands.ts, appIndex.ts).
  • Plugin frames pass their unused keys on: the bridge's keydown listener hands the host every key the frame didn't preventDefault() (not plain typing in a field, never Esc); the host takes it only while that frame has the focus (aia-plugin-key in PluginSandboxFrame) — so g h works on a plugin page too.
  • Queues — business/keyboard/queue.ts computes ] / u's lists on the key press from the caches (conversation list, forms, asks, notify log, the unread store), in the home page's order and the profile scope — nothing is kept live on every page for it.
  • Prompt shortcuts are an optional peer (optionalRequires): while the prompt-shortcuts plugin is on, the keymap has the Composer group (⌘G, Alt+1…9) and the named-chip keys; without it Alt+N only switches profiles.
  • The command palette (⌘K) is the command-palette plugin's (since 2026-11-27, form command-palette-as-a-plugin_pwa0w9), the keyboard plugin's second optional peer: its app.modal slot is preloaded (loaded hidden once the app is idle, so ⌘K opens at once — PluginWarmModals), bound to ⌘K only while it is on (modal:command-palette:palette). It lists what the bridges give: the available commands with their keys, the places (sections, Settings pages and rows, plugin pages), the loaded conversations of the profile on screen; it runs one with runCommand / navigate. No palette without both plugins.
  • Carry-over carryover.keyboard: each person's old state.keyboard ({enabled, bindings} in their ai-agent-settings blob, left there unread) → the plugin's per-user keymap.json, once.
  • The composer half needs @gabvdl/ui ≥ 0.48 (RichInputHandle.toggleTag / toggleMasterSwitch). Tooltips show the key (the Guidelines switch, the profile toggle) through useBindingHint / withHint, from the keymap.

Fixed lists are rearrangeable: HoldEditable + useListOrder

Small lists of links, chips or cards are user-arrangeable by holding one for 1.4s: it lifts out of the flow and follows the pointer, the rest of the group starts jumping (iOS-springboard style), dragging into a neighbour's slot hands it over, and releasing drops it there and ends edit mode. All of it lives in technical/ui/HoldEditable.tsx — pointer-events only (one code path for mouse and touch) and a body-level portal for the lifted item so nothing clips it. It's layout-agnostic: the group's flex/grid classes come from the caller, so the same component drives a horizontal navbar and a vertical panel (one row or column — not a wrapping grid).

The DOM order never changes during a drag. Slots are measured once at pickup and the rearrangement is expressed purely as transforms; only the drop commits a real reorder, once the pointer is gone. This is load-bearing, not tidiness: reordering live means React moves the pressed node — and re-renders whichever item now sits in a position-dependent slot, like the navbar's raised centre tab — and a browser cancels the touch whose target left the document, so the drag died on the first hand-over. For the same reason the held item's (invisible) in-slot copy keeps rendering with the props it had before the pickup: its node must not be replaced. Freezing the DOM also fixes the geometry, so hit-testing needs no re-measuring and no animation lock, and a fast drag can't outrun the shuffle.

const [tabs, setTabs] = useListOrder("nav", TABS, tabKey);   // lib/listOrder.ts
<HoldEditable items={tabs} getKey={tabKey} onReorder={setTabs} className="flex …">
  {(tab, { index, held, editing }) => <Tab …/>}
</HoldEditable>

For a list that is the data, pass the array and write it back. For a list hard-coded in the app, useListOrder(name, items, getKey) persists only the order, as ids, under settings.listOrders[name], and reconciles it against the code list on read — so adding, renaming or removing an entry in a later release can never strand or duplicate an item. An entry the saved order has never seen lands right after its code-order predecessor (reconcileOrder), not at the end: a card added at the top of the code list shows up at the top for someone who already rearranged. Already wired: the bottom navbar (nav), the dashboards / settings / files drawer panels, and the conversation's Details drawer (DETAIL_CARDS in Conversation.tsx — every part of it is a card, the name and tag row included, so nothing in the drawer is pinned; the lifecycle checks are the lifecycle plugin's conv-checks slot since 2026-11-27). Renaming or splitting an entry: pass useListLayout a renamed map (old id → the ids that replace it) and a saved layout expands the old id in place, slot or stash — that's how the drawer's one subagents card became subagentsRunning + subagentsDone (stopped agents sit in the finished card with a rose stopped badge) without dropping anyone's arrangement, and how the built-in plans card became pluginSlots — every live plugin's conversation.details slot (the Plans plugin's list of the conversation's plans, since 2026-11-25), and the built-in memories card too (the Memories plugin's read / created lists, since 2026-11-26).

A list inside one of those cards (commits, subagents, memories, the Graph plugin's related conversations) shows five entries and a "Show 5 more · N left" button: useShowMore(items) + <ShowMoreButton list={…} /> from technical/ShowMore.tsx (a plugin frame draws the same button itself). A new list in a card uses the same pair. A strip that scrolls sideways (the artefacts thumbnails) has no button: it loads the next batch as its end scrolls into view — useShowMoreOnScroll(list) puts an IntersectionObserver on a sentinel after the last entry (wheel, drag and touch alike).

A hold ends in a click, so HoldEditable swallows the click that closes a drag — otherwise rearranging the navbar would also navigate. Presses that start inside an input/textarea/select/[contenteditable] (or anything marked data-hold-editable-ignore) never pick up.

Travel during the hold cancels it only for a finger (>12px), where it means "I'm scrolling, not holding". A mouse is deliberately exempt: it can't scroll with the button down, and a hand resting on one drifts far more than that over 1.4s — cancelling on drift made hold-to-drag impossible on desktop. The pickup then happens wherever the cursor ended up, not where it went down.

Settings lists share one card: technical/ItemCard.tsx

Every settings list — Users (each a page of its own under /settings/<name>, routed in root.tsx and listed once in business/settings/registry.ts) — renders its items with the same ItemCard: a collapsed header row (chevron · icon · title · chips · optional aside · optional toggle) that expands on tap into a body holding the editable fields, the actions and the item's detail. The conventions, so a new list looks like the others without re-deriving them:

  • The toggle is in the header and applies immediately (optimistic cache flip + rollback on error), independent of any unsaved edits in the body. What it means is per list: mail sender = allowed or not (kept in a disabled list the mail service never reads). Accounts have none.
  • Edits are explicit: fields in the body hold a draft and a SaveButton appears only while dirty — no autosave on blur.
  • Delete lives at the bottom of the open body (BTN_DANGER, pushed right) behind useConfirm, never in the collapsed row.
  • Add is the dashed AddButton under the list, which swaps for a NewItemFrame form; EmptyNotice / ListLoading / ListError / PageIntro / ListPageBody are the page-level pieces.
  • Inputs and buttons use the exported class strings (INPUT, INPUT_MONO, SELECT, BTN_PRIMARY, BTN_ACTION, BTN_GHOST, BTN_DANGER) and Field for a labelled control, so the bodies match without copy-pasting Tailwind. SettingRow is the title + help + control row the plain Settings page (display) and the account cards share.

/settings is one page per topic (since 2026-11-23): Display, Notifications, Extras (composer, the clarifier — the pets moved to the pets plugin's page), Fresh context and Claude Code hooks (the last two owner-only), plus Profile, Projects and Budget — the old guest /me, folded in (business/settings/pages/*.tsx, business/users/pages/Profile.tsx; shared pieces in components/SettingsBits.tsx). /settings, /me and every old anchor (#display, #composer, #push, #pet, #misc, #clarifier, #fresh-context, #hooks, #webhooks, #mail-trigger, #subscription, #claude; /me#profile|projects|notifications|budget) forward through business/settings/redirects.tsx (keeping ?login=). Each row carries a data-setting="<page>.<row>" anchor (SettingRow setting=…) listed in business/settings/rows.ts (SETTING_ROWS, plain data for the settings search); <page>?row=<id> scrolls to the row and rings it (useFlashRow, still with animations off). A new row on these pages gets an anchor and a SETTING_ROWS entry — rows.test.ts fails otherwise.

Every Settings destination is one entry of business/settings/registry.ts (since 2026-11-23; read docs/settings.md before adding or moving a settings page): five groups (You · Your logins & tools · Workspace · People & security · This machine), each entry with the permission its page needs. The left panel (SettingsPanel, one for everyone, with a search box over pages and SETTING_ROWS — / focuses it), the bottom bar's drawers, nav.ts's SUB_SECTIONS.settings, the command palette's Settings section and the routes' guard (RequiresSettings in business/users/guards.tsx) all read it, filtered by me.perms (useAccess / useCan in business/users/api.ts; everything allowed while /api/me loads or fails). What a role lacks is hidden; an empty group disappears.

Settings → Machines (was Profiles) is the exception: not a card list but a list of machines grouped by profile whose rows open a profile page and a machine page in tabs — see "Profiles → Workers, and Accounts". It replaced the Profiles, Workers and Accounts card lists on 2026-10-19, and the tree on 2026-11-23.

The palette: accent, surfaces, dark depth (lib/palette.ts, since 2026-11-05)

index.css holds the neutral greys and the orange; lib/palette.ts paints over them with one <style id="account-theme"> (html:root + html:root.dark: they outrank the stylesheet's :root / .dark whatever the order — the boot script's copy sits before the stylesheet link, and a plain :root lost to it in the light scheme), written by useAppPalette in App.tsx:

  • Accent (--primary, --ring, --primary-foreground, the caret, the code selection, the theme-color status bar). The owner's is the scoped profile's colour (Settings → Machines → the profile; the profile switch repaints at the tap with applyAccent). A guest's is their own (Settings → Display, the settings store's accent): one of the 11 presets of lib/accountTheme.ts, or any #rrggbb from @gabvdl/ui's ColorPicker — its light shade is clamped to 30–60 % lightness and its dark one to 52–74 % so a pale or a near-black pick still draws a visible button, and the text on it is black or white by WCAG contrast. "" = orange.
  • Surfaces (surfaceTint: neutral · warm · cool · accent) — background, card, popover, secondary, muted, accent, border, input take a hue (stone, slate, or the accent's own); text keeps 40 % of the tint's saturation, muted text 60 %. A tinted light page sits at 98 % so white cards read.
  • Dark depth (darkDepth: dark · black) — pure black for OLED: page 0 %, card 4 %, popover 6 %, borders 14 %.

Everyone's surfaces and depth are their own Display rows (the owner's included); all three fields live in the user's server-side ui-state, so they follow them across devices. Nothing is painted until /api/me and the settings have landed; till then the CSS the last visit cached in localStorage (aia.palette) — painted by index.html's boot script — holds, so a guest's violet app never flashes orange. The light / dark / system theme gets the same treatment (aia.theme, THEME_CACHE_KEY in settings.ts, written once the server's settings are in): the boot script used to read it from a local ai-agent-settings that serverStorage had long deleted, so a forced Dark painted the OS's scheme first. Tests: lib/palette.test.ts.

Performance: what the hot paths cost, and the rules that keep them cheap

This service polls the filesystem continuously and serves lists built from ~900 transcripts, so the naive version of almost anything here is quadratic. Seven rules, each of which was once a real regression:

  1. Never walk the workspace (or the transcript dirs) per request or per tick — let inotify say what moved. The file catalog comes from the files table; the discovery walk (~8 000 dirs / 120 000 files for ~300 context files) is cached in the indexer (_exposed_files) and redone when the workspace watch (files.discovery.WorkspaceWatch, inotify on every walked dir, drained by its own thread) reports a context file appearing or going — forced on save, every WALK_SAFETY_SECS (30 min) regardless. The transcript watcher drains its own inotify watch each 2 s tick and stats only the paths it reports, with a full re-walk every WATCH_RESCAN_SECS (60 s) and after a queue overflow. Without inotify (WATCH_INOTIFY=0, not Linux, the per-user watch limit — the two watches take ~9 000 of fs.inotify.max_user_watches) both fall back to the old cadence: a walk each tick / every WALK_INTERVAL_SECS. The watcher tells the indexer which transcripts changed (scan_transcripts(only=…)), so a live turn re-parses one file. Walk with fsscan.walk_files, never rglob, and in a walk over many files don't build a Path per file — _iter_files filters on strings and only makes paths for candidates (a Path + relative_to per file was most of the walk). Before inotify the two poll loops were ~15 % of a core at idle.
  2. Never re-parse a whole transcript to see what was appended. A live session writes every couple of seconds; the indexer keeps a ParserState per growing transcript and feeds it only the new lines (byte offset in Indexer._live), and the detail route does the same for full threads (_detail_cache in conversations/routes.py, through the shared conversations.feed_lines) — a running conversation's (mtime, size) changes every second, so a cache keyed on it never hit while anyone watched the thread, and every ping cost a whole re-parse (~1 s on 8 MB) per open tab. A transcript rewritten in place (a converter, a hand fix, the archive's full re-copy) restarts both from byte 0: each state keeps a conversations/rewrite.py Mark — the (mtime, size) and the hashes of the first 4 KB and of the 4 KB before its offset — and resumes only while the file grew and both match (shrunk, or same size with a new mtime, also restarts). Re-parsing from byte 0 each tick is O(n²) over a session. The same goes for the archive import: a grown transcript gets only its new bytes (tailcopy.sync) — a whole-file copy2 rewrote 100 MB for one line on the biggest.
  3. Never shell out to git per item. Both catalogs share one HEAD-keyed history walk (githist).
  4. Never send content you don't need. The context catalog (the context-editor plugin's context.read bridge, was /api/bundle) is metadata-only (content loads per file through …/hub/context/file); /api/conversations is paginated + lite (usage/byToolSub only under full=1, which no page asks for since the Environment and Analytics dashboards became plugins — their bridges read the cards server-side); an SSE transcript ping carries the list cards of the conversations it moved (conversations/card.py, built by the watcher right after it re-indexed them) so a tab patches its rows with no request at all (/api/conversation-summary is the fallback for an id without one); the open thread refetches as a delta — GET /api/conversation?since=<rev> answers with thread from threadFrom on, the client splices it onto what it holds (spliceThread in lib/queries.ts). The rev is the detail cache's snapshot counter; each snapshot records where the thread changed (an equality walk against the previous one — the parser mutates items in place) and which cards had an agent running (their rolled-up cost keeps moving); the window starts at the earliest change since the client's rev, and the running cards before it travel as threadPatch (index → item), not by widening the window to the first of them. A response's rev and window are its own snapshot's (_parse_full_snapshot reads the rev under the entry's lock; _delta_from(ent, since, upto, length)): the endpoint decorates for a few hundred ms after the snapshot, and reading ent.rev then — after an overlapping request moved it on — labelled a thread with a later rev, so the next delta started past the end of what the client held. The client never takes such a delta for a whole thread either (canSplice → readConversation reads it whole): it used to, and the page showed the latest message alone, every later delta the same (2026-11-20, conv 01a1fa0f). /api/notifications is paged (limit + before cursor, new=1 for the home's New list — see "Notification read state").
  5. Make the stream resumable, not the reconnect expensive. Every SSE event has an id (<epoch>-<seq>, the hub keeps a ring of the last 1 024) and the backend closes each stream itself after 9 min — under Traefik's writeTimeout — so the browser reconnects with Last-Event-ID and gets a replay instead of a gap; only an id the hub can't honour (another process, fell off the ring) opens with a resync event, the one case the client does a catch-up refetch. Before: every 10 min, every tab, two list fetches and a full invalidation.

The frontend side (lib/sseBus.ts) has lanes: a ping naming the open conversation (lib/openConversation.ts) refetches its delta at once — through refreshConversation (lib/queries.ts), never a plain invalidateQueries, whose default cancels the read in flight: a busy run pings every ~0.5 s and a long thread takes 0.3–0.8 s to read, so no read ever landed and the open thread froze while the cancelled reads piled up on the hub. One read in flight per conversation plus one trailing; only one stuck past 20 s is cancelled and restarted. The rest of the burst (row patches, diff stats — throttled to one per 30 s per running conversation —, list heads at most every 20 s, catalogs stale-only unless a meta change) waits for that fetch to land. A hidden tab accumulates and flushes once on return; heavy queries don't refetch on window focus.

The thread goes first; what isn't on screen asks nothing (2026-11-24 — "opening a conversation takes 5 s+": a dozen widget requests queued with the thread's on a saturated hub, data/log/2026-11-24-ai-agent-conversation-load-perf.md in the homelab). The pane sets paintedId one frame after the thread's first paint; the Details drawer's cards, the Bash cards' call costs (CallCostProvider ready), the Changes tab's commit / diff-stat counts and the header's perf + disk chips wait for it. The drawer's cards mount the first time it's shown for that conversation — a desktop's (open by default) after the paint, a phone's (an off-screen sheet ResizableLayout keeps mounted) when opened — and stay mounted. The desktop panel itself is in the layout from the first render but waits closed for the conversation's first read, then slides open like the left drawer (2026-11-27 — added only once the read landed, it flashed at ~95 % of the width and shrank: the panel group laid out afresh with the thread at a flex-grow of 1); once a page has shown one it stays open across conversation switches, and that waiting collapse is never remembered as the person's choice; DrawerOpenContext (lib/drawerOpen.ts) tells them it's closed, and then nothing of theirs polls or refetches (perf, CPU/RAM series, disk, a shell's output tail; the plugin slots read update.drawerOpen, as the Graph plugin's Related card does). A new drawer card that polls reads useDrawerOpen(). The meta line (with the chips) renders once, for the current breakpoint — mounted twice under CSS it ran every chip's poll twice, out of phase. A phone opening the app on a conversation starts the spawn drawer auto-hidden (spawnDock merge), so the composer's catalog queries never fire just to unmount it.

Reload paints from a per-conversation cache (lib/threadCache.ts): the last 10 threads read, each its own IndexedDB entry (store ai-agent-threads), written at most every 15 s per conversation and on hide, busted per deploy like the query blob, cleared with it on sign-out. readConversation seeds the query from it when memory has nothing, then asks ?since=<rev>. Threads stay out of the persisted query blob, and so do the call-probe records (["perf","calls",sid], 2–12 MB): the blob is restored before any query runs and re-serialised on every change. The calls themselves travel as deltas: /api/perf/conversation/{sid}/calls?since=<cursor − 30 s> (the overlap covers two runners committing out of order), merged by toolUseId (mergeCalls in perfQuery.ts); the backend caches each call's view on (tool_use_id, updated, len(data)).

  1. Memoize whole-catalog builds on the version key, through _Memo. Every SSE-driven refetch lands right after a transcript write, i.e. right after a summaries_version bump — so a hand-rolled check-then-build cache misses in every concurrent request at once and each one rebuilds the same thing (N open clients = N× the CPU, all on one GIL). _Memo.get(key) is single-flight: the rest wait for the first build. Cards, agent runs and agents-by-conversation go through it; a card's state also depends on the clock, so the cards key carries a 15 s time bucket. The memoized list is shared — copy before sorting it. Behind that memo the cards are cached one by one (_card_cache in conversations/catalog.py — the comment there lists every input): a rebuild remakes only the cards whose inputs moved, so one write costs one card plus the O(n) bookkeeping, not ~2 000 cards. A card's own summary, its subagents' and its meta entry are compared by identity — which holds only because the summary store and MetaStore replace a changed entry and never mutate one (MetaStore._load even keeps an unchanged entry's object across a reload): never mutate either in place, or cards go stale. A card read from a new shared source needs that source in its key. The 15 s bucket only remakes cards inside the recency window; a staggered 5 min expiry covers what has no version. A rollup that may lag a minute takes max_stale (_Memo(build, max_stale=60, slots=n) + get(key, …, soft=summaries_version)): the soft part only ages the value, and while one caller rebuilds a stale one the others get the stale value instead of waiting on the lock. Project costs (projects/routes.py, ~10 s a build under load, 151 builds in 40 min before) and the related index (conversations/related.py) use it; meta / profile / worker versions stay hard, so ownership changes show at once. PerfStore reads never queue behind its writes: query() / proc_state() use a read-only connection per thread (WAL readers don't wait on the writer); writes keep the one locked connection. Before, one slow ingest on the 689 MB perf.db parked 14 pool threads in query and conversation reads waited 60–90 s for a free thread (2026-11-24).
  2. Keep per-summary helpers O(1). Anything called once per summary per build runs ~2 000× a request: pathlib.relative_to was 0.24 ms a call and alone made _conv_id half the list's cost — the path helpers are lru_cached. MetaStore.peek is lock-free (entries are replaced, never mutated) and .items() is the no-copy sweep; .all() deep-copies 1.4 MB.
  3. Don't let FastAPI encode big bodies on the event loop. A handler returning a dict is serialized by pure-Python jsonable_encoder on the loop thread (5–10× slower than json.dumps), and while it runs nothing is served, /api/health included. Heavy GETs wear @_json_in_worker, which returns a ready JSONResponse from the worker thread. When the loop is starved the symptom is /api/health taking seconds.

Re-measure with scripts/bench-lists.sh [backend-dir] (a data snapshot in a throwaway --network none container; pass a worktree's backend/ to compare against the deployed image). On 2 210 transcripts, one transcript write then cost the list 526 ms → 111 ms, the per-row summary 312 ms → 47 ms, eight clients refetching together 7.1 s → 0.18 s, and an unchanged re-request 214 ms → 1 ms. Before that fix the live box sat at a pinned core with /api/health at 43 s and the list at 80 s: requests queued past the client's patience and every refetch added more. On 3 501 transcripts / 2 064 cards (2026-10-26, per-card cache + inotify + tail copy), one write cost the list ~600–800 ms → ~50–100 ms on one core, and side by side on the live mounts — background threads running, a client polling the list every 5 s — the backend went from 28–40 % to ~4 % of a core, list p90 1.3–2.6 s → ~150–180 ms, worst request 5–9 s → 0.34 s.

Measured on the real archive (898 transcripts / 458 MB): /api/bundle 12.5 s → 26 ms, /api/services 11.2 s → <1 s cold / 0.5 s warm, /api/projects 3.4 s → 0.35 s, the conversation list 1.3 MB → 89 KB, and idle CPU ~58% → ~7% while a session streams. If you add a feature here, check it against the four rules — and re-measure, don't assume.

Security: the trusted-caller gate

The backend has no auth of its own — Authelia guards it at Traefik. But the container also sits on the shared main docker network, where a write into .claude/ (hooks! — the context-editor's context.write bridge, was PUT /api/file) or a POST /api/spawn is host-level code execution. So core/auth.py installs a middleware that answers /api/* only for: Traefik (resolved from TRAEFIK_HOST), the docker gateway (how host-originated connections to the published 127.0.0.1:8096 port appear), localhost, or a caller presenting INTERNAL_API_TOKEN. Everything else gets 403; /api/health stays open for the deploy probe. /proxy/claude/… and /proxy/opencode/… (the workers' Claude and opencode proxies, claudeproxy/) are outside /api on purpose: Traefik serves it without Authelia, and its own check — a worker's proxy token, an account that worker may bill, a v1/ path — is the whole gate.

Through Traefik, the owner is whoever Authelia vouched for, never "came from Traefik". The admin router's forward-auth sets Remote-User, overwriting anything a client sent, and every other router strips it. A request from Traefik without one is anonymous, whatever its Host says (public routes only — signing in; logged as edge_anonymous).

The owner's internet address (OWNER_HOSTS, homelab hub.gabvdl.xyz, since 2026-11-24 — docs/remote-access.md, backend/remoteaccess/): the one host where the owner is reached without Authelia. There the gate takes only the owner's __Host-aia_owner session (7 days, opened with a passkey the hub verifies itself) — no Remote-User, host token or guest cookie is anyone. Passkeys are added only through a one-time link made on the admin host; Switch internet access off sits beside Lock guests. Not Pocket ID: a mailed code there can enrol a passkey.

Who may do what is one table (since 2026-11-23, docs/permissions.md, backend/authz/): after deciding who the caller is, the gate asks one question for every kind of caller — caller.allows(authz.routes.TABLE[route], method) — against their permissions: a person's role (Operator = the owner, Admin, Member, Guest, Viewer, custom clones; Settings → Roles) plus their allow / deny overrides, narrowed by the scope of the credential acting for them (cli, worker.read|run, bot, phone — authz/scopes.py; a scope only removes). Permissions sit in tiers: person, admin (nobody but the owner until team mode), host (code on the machine — the operator only). Adding a route = a TABLE entry with the narrowest permission (else only the operator passes), relation filtering inside the handler, and UPDATE_GOLDEN=1 python -m unittest test_authz_matrix — the diff of authz/matrix.golden.txt is who now reaches it. A refusal is a perm_denied line in the Security log.

Until 2026-11-01 the owner was decided by the host. Host: claude.lab.gabvdl.xyz. (trailing dot) matched the guest router but not GUEST_HOSTS, and came out the owner, from the internet (docs/security.md). request_host now strips trailing dots too. A new router to this backend must never need the Host check to be right.

Loopback and the docker gateway are still the owner: every uid-1000 process and every host-network container (Home Assistant, glances…). Moving to tokens was left for later (docs/security.md → Left).

Since the 2026-11-15 pass (docs/security.md → "Second pass", test_gate.py) the gate also holds four rules a new route gets for free — don't work around them:

  • Cross-site requests are refused for every caller, the owner included (cross_site): a state-changing request whose Origin isn't this host, or whose Sec-Fetch-Site isn't same-origin / none, is a 403 and a cross_site line in the Security log (pushed by default). Every *.gabvdl.xyz page — a guest's site — is same-site with the admin host, so Authelia's Lax cookie rides its POSTs; this check is what stops them. A browser's body through Traefik also needs a Content-Type (415). Host callers send neither header and are unchanged. A websocket never passes the HTTP middleware: check auth.cross_site(ws) and auth.edge_role(ws) yourself, as chrome/routes.py does.
  • Which Authelia user: OWNER_USERS are the owner, READONLY_USERS (the password-only claude bot the skills log in with) may only use safe methods, and only what the Admin role reads minus people, security and the machine (the bot scope), anyone else Authelia lets through is anonymous. Both unset ⇒ any Authelia user is the owner (standalone). So a screenshot of the live admin app works — but not of Settings → Users / Security / Accounts; a flow that writes through the bot's session doesn't — use the mock recipe or a host call.
  • The path is request.scope["path"], never request.url.path (Starlette rebuilt that from the Host header: Host: x? emptied it and skipped the gate). Owner-only routes should still declare OwnerDep.
  • Bodies are declared and bounded for whoever isn't the owner: 64 KB anonymous, 4 MB a guest (500 MB on /api/upload); a chunked body ⇒ 413.

There is no served /openapi.json (it sat outside the gate, on the public host); app.openapi() still builds the spec for the orval dump. The app shell carries a Content-Security-Policy (script-src 'self' + the hash of index.html's inline bootstrap): no new inline <script>, no eval, no script from a CDN in the app itself — and HTML an agent wrote goes through /sandbox-frame.html, never srcdoc or a blob: page, which would inherit the shell's policy.

Read-only API keys (READONLY_API_KEY, comma-separated) are the one credential that is checked before the trusted-IP path: a caller presenting a matching X-API-Key is allowed safe methods only (GET/HEAD/OPTIONS) and only the phone scope (notifications.ledger: the unread list) — any mutating method or other route is 403, even from an otherwise-trusted source IP. That downgrade is the point: the desk phone reaches the backend over the trusted host loopback but must only ever read (it fetches GET /api/notifications/unread to read notifications aloud), never spawn a session or PUT into .claude/. The unread endpoint is a pure read — it never advances the read ledger (notifications/read_ledger.py / /data/notif-read.json); only the PWA opening/dismissing a card (POST /api/notifications/state, or the older /seen) marks notifications read. Assets served from repo/user bytes (/api/data-asset, /api/upload-file, …) go out nosniff and, unless they're an allow-listed raster image or video, Content-Disposition: attachment — an uploaded .html/.svg must never execute on the app's origin.

Conversation ids: a UUIDv7 each (conversations/ids.py)

A conversation — a root transcript, and every subagent's — is addressed by an opaque UUIDv7, never by its transcript's path (the old id, -home-gabrielvidal-projects-x/<sid>.jsonl, put the owner's home dir, project and branch names into every URL a guest saw). Since 2026-11-04.

  • The id: the 48-bit timestamp is the transcript's first timestamped record (so ids sort by start, past conversations' included; none in its head → the moment it was first seen), and the other 74 bits are a sha256 of the archive-relative path — not random, so a lost registry re-derives the same ids. Forks and resumes share their source's first timestamp but not its path, so they get their own ids.
  • The registry is the conv_uids table in ai-agent.db (rel path ↔ uid, loaded into memory by core/state.build_state → ids.bind). It is the source of truth once an id is handed out; uid_for_path / uid_for_rel mint on first sight (tree._conv_id is the one door every response goes through).
  • Internally the path stays the key: summaries, the watcher, the indexer and tree.py's subagent walk all work on paths. Turn an id into a path with ids.rel_for / ids.path_of (lookups) or catalog._resolve_transcript (opening a file from a request — it validates). Never build TRANSCRIPTS_DIR / <id> or split an id on / — and never derive the session id from an id (access.session_of and catalog._meta_key resolve a uid through the registry first).
  • Every spelling still opens it: conversations/routes._public_id maps a legacy path id (old pushes, docs, PR bodies) and a bare session id (what a script knows — deploy.sh, the mail trigger, a worker's terminal link: …/conversation/<sid>) to the uid; the thread page then swaps the uid into the address bar. Endpoints that echo or compare the id canonicalize first.
  • SSE: the transcript event's ids are uids, plus roots (subagent uid → its root's uid) since the client can't read the parent off an opaque id (card.transcript_event; lib/sseBus.ts keeps the map). The guest filter trims roots with ids.
  • The owner's transcript path: the thread detail's transcript (the archived copy's host path, ARCHIVE_HOST_DIR, default the uploads dir's sibling) — owner only, shown under the id in the details drawer (under the branch line: the ID card is id → branch → transcript path, each line copies itself; the branch was a Cost-card cell until 2026-11-27, where long names ran out of the card).
  • The migration (conversations/id_migration.py, run in build_state before any JSON store loads): mints every archived transcript's uid, swaps every known path id in the top-level /data/*.json stores for its uid (raw-text, so ids nested in the synced PWA stores' JSON strings are caught; absolute file paths are left alone; a .bak-uids-<stamp> copy is kept beside each file it changes), and re-keys short_titles + the short-title side-call ledger. ~2 s the first time on the 2026-11 archive. It re-runs at every start (a walk + a ~12 MB read when nothing is left): a blue-green deploy's old container keeps writing path ids after the standby's start swept, so the canonical container's start sweeps again. Two processes on one DB agree on every uid: a mint adopts what the table already holds, and a uid the memory doesn't know is looked up in it (v7 only — a bare session id costs nothing).

Guests: multi-user (backend/users/)

People other than the owner can use the app — guests — each scoped to the projects they were granted. Design + decisions: docs/multi-user.md.

  • Who is calling is resolved by the gate (core/auth.py) into a users.caller.Caller on request.state.caller; routes take it as caller: CallerDep (or _: OwnerDep for owner-only). Every pre-existing path is the owner, unchanged: Traefik (Authelia), loopback / docker gateway, INTERNAL_API_TOKEN; the read-only key is the owner, read-only.

  • Guests are users.json records (per-project grant view|chat|ship, allowed model families, monthly budget, notification channels). They log in with the built-in login: a one-time link (/api/auth/request-link mails it over SMTP_*; the owner can also copy one from Settings → Users) → /api/auth/login sets the aia_session cookie. Tokens are stored hashed (auth.json). The sign-in mail also carries a 6-digit code (in its subject, so the phone's notification shows it and iOS offers to fill it): /api/auth/login {email, code}, typed on the login page's Check your inbox step. It is what an app on a phone's home screen needs — the mailed link opens in the browser, whose cookies the home-screen app doesn't share. The code is hashed with the user id, spent with its link, and stops after 5 wrong tries (code_failed in the security log). The link lands on the guest host the request came in on.

  • Or one login through an identity provider (round 9, 2026-11-16 — Pocket ID in the homelab, one account for the ai-agent and Jellyfin): users/oidc.py is an OIDC client (code flow + PKCE S256, state/nonce kept server-side 10 min and bound to the browser by the aia_oidc cookie, RS256 ID token checked against the JWKS with cryptography — no new dependency). /api/auth/methods tells the login page which it is (Continue with …); /api/auth/oidc/start?next= → the provider → /api/auth/oidc/callback opens the same session /api/auth/login would (users/session.py). A provider account is a guest by idpId (the sub), else once by email. While it is configured, /api/auth/request-link and /api/auth/login answer 410 (kind: oidc); sessions opened before stay valid. users/idp.py mirrors every guest into Pocket ID from Settings → Users (create / save / disable / delete; POST /api/users/idp-sync for all): username = their id, the IDP_GUEST_GROUP group, plus one group per app switched on (apps in users.json, the Apps panel; groups the hub doesn't manage are left alone); the result is idpSync on the record, never an error on the save. With it on, Copy invite link / Mail invite mint a Pocket ID one-time login code (/api/auth/oidc/start?lc=: the hub opens the authorize request itself and sends the browser to the provider's /lc/<code>?redirect=/interaction?interaction=<id> — its code page only redirects to its own pages; without an interaction, the code page alone), and Mail new sign-in (mail: "sso") sends the migration note. Env: OIDC_ISSUER (public), OIDC_INTERNAL_URL (back-channel, e.g. http://pocket-id:1411), OIDC_CLIENT_ID, OIDC_CLIENT_SECRET, optional OIDC_REDIRECT_URI (default {GUEST_PUBLIC_URL}/api/auth/oidc/callback), OIDC_PROVIDER_NAME (the button), POCKET_ID_API_KEY (its STATIC_API_KEY), IDP_GUEST_GROUP (ai-agent), IDP_APPS (group|label|url,…). The login switches on with issuer + client id + secret; the mirror with the API key. A refused callback logs oidc_refused. Tests: test_oidc.py (a fake Pocket ID).

  • On a phone's home screen the guest host is its own install: the backend rewrites manifest.webmanifest and index.html there (users/branding.py: GUEST_APP_NAME / GUEST_APP_SHORT_NAME, default APP_NAME / ai-agent, description and lang per browser) — the owner build's « Claude Agent » name never reaches a guest. iOS takes only apple-touch-icon.png (no SVG, no manifest icons); Android takes the 192/512 PNGs and the full-bleed icon-maskable-512.png (frontend/public/, rendered from icon.svg).

  • A session cookie decides the request outright (before the IP checks): a guest reaches only the routes their permissions allow (role + overrides, authz/) — default deny — and a mutating request must be same-origin. On GUEST_HOSTS (the guest host, no Authelia) nothing is ever the owner: without a session only /api/auth/* answers (401 login_required, which the PWA turns into /login).

  • Inside allowed routes, handlers filter: a guest sees the conversations whose meta says owner: <them> or lists them in participants (users/access.py; 404, never 403, for the rest), their forms/asks/pushes, their granted projects; their ui-state keys live under u.<id>.; the SSE hub filters per subscriber. Adding a route a guest needs = a person-tier permission for it in authz/routes.py and filtering inside it. A route on an admin- or host-tier permission is the owner's by construction.

  • A guest's spawn is pinned server-side (runs/routes.py → users/runs.py): one project they hold chat on as cwd, the host sidecar, the harness of the picked model's preset (Settings → Models — claude unless the guest pool gives them a pi / agy model; see "Settings → Models"), never the composer's — on their own Claude login when they connected one (any model, no budget), else on the default account with an allowed model, under budget (see "Guests' own Claude logins" below) — and it carries a sidecar scope: --permission-mode dontAsk, Edit allowed only under the project + /tmp, credential reads and the hub's uploads store denied, their own attachments folder readable (readDirs, see "Attached files"), an appended system prompt naming the guest and their level, no remote control (harness-claude's sidecar/claude_launch.py "per-run scope"; the scope's check is the core's launch.valid_scope). Bash is not confined unless GUEST_SANDBOX=1 (Claude Code's bubblewrap sandbox; needs bwrap + socat on the host): beyond the guard hook's rules it is a shell on the host as uid 1000 (see "A guest's run is contained" below).

  • Guest commits are authored as the guest (scope gitAuthor → settings env GIT_AUTHOR_NAME/GIT_AUTHOR_EMAIL, from their name and account email — the address their Gitea account carries, so Gitea links the commits); the committer stays the host's git identity, so git log --author=<guest> separates their work. Pushing: plain git push works because the host's ~/.gitconfig has tea-cli credential as the helper for git.gabvdl.xyz (homelab tea-cli credential install). A new scope key like this needs the host sidecar restarted before the backend deploy (valid_scope 400s unknown keys).

  • What every guest gets — their prompt shortcuts are the prompt-shortcuts plugin's (see "Prompt shortcuts are a plugin" below): one library, the owner's, where a shortcut ticked Guests reaches every guest live (the plugin's composer.shortcuts answer for a guest is the owner's guest slice, their preferences applied, then their own); their skills are chosen in Settings → Skills & agents (/settings/setup, beside what each worker gets). A line naming lab things gets its own guests-only shortcut (guests, runners: []), not a second wording. sharedSkills (users.json guestDefaults, name = the repo's .claude/skills, <project>/<name> = a project's; toggled in Settings → Skills & agents or per skill in the catalog) ride in the run's scope as skills; the host sidecar symlinks them into a generated plugin (sidecar/shared_skills.py, cache ~/.cache/ai-agent/shared-skills/<hash>) and adds --plugin-dir — they load as shared:<name>. A guest's composer lists them (+ their projects' own skills) from /api/guest-skills. A guest's bottom bar has five tabs (2026-11-01): Stats (/stats), Projects, Conversation, Settings (/settings) and Me (/settings/profile). Both drawers come from the settings registry (docs/settings.md), filtered by their permissions: Me = the You group (Profile, Display, Notifications, Prompt shortcuts, Extras, What's new) + their Drafts, Settings = the rest (Budget with their Claude login, Scheduled jobs, My computers, AI apps, Projects). Their left drawer is the same SettingsPanel as the owner's; the Stats tab's is GuestStatsPanel (business/dashboards/components/).

  • A guest's Stats (/stats, business/dashboards/pages/Stats.tsx → components/GuestStatsView.tsx; backend dashboards/guest.py): their own, simplified dashboard — only the conversations they started (meta.owner, as the budget counts; ?shared=true would add the ones shared with them) over a 7 days / 30 days / All switch: This month vs their budget (their own Claude's ≈ estimate apart), conversations, the time Claude worked (distinct 5-minute activeBins, subagents included), a calendar heatmap of the days anything ran (all time), spend per day (per week past 62 days), per project, per model, and the footprint — carbon, water, energy, estimated client-side by lib/footprint.ts from the footprint.tokens the rollup sums under each conversation's busiest model (the estimate is linear, so the sum is the per-conversation convFootprints') plus the EVOX2's measured Wh. GET /api/me/stats?days=&tzOffset= (guest route; 404 for the owner) and GET /api/users/{id}/stats (owner) answer the same payload from the memoized cards + the summaries — never a transcript; the query sits under the conversations key, so SSE bursts mark it stale. The owner sees exactly that view on Settings → Users → → Activity (above the recent conversations list). Gabriel's calls (form guest-dashboard-a-few-choices_p3wnvv): dollars, own-Claude apart, no recent-conversations list on theirs, no token totals, no time-of-day histogram. Its last two sections, Performance and Storage (2026-11-06; drawer anchors #performance, #storage), are the owner's perf dashboards narrowed to their sessions: GET /api/me/stats/perf?days=&shared= (guest route) / /api/users/{id}/stats/perf (owner) → dashboards/guest_perf.py, which calls perf/views.py conversations / commands with a sids filter (only_sessions: one json_each parameter) and perf/storage.py of_sessions — CPU time + peak RAM, the top 10 commands and conversations of the period (one row per conversation, runners merged and dropped), and what their sessions keep on disk now (of the period's conversations). An item is theirs when one of their sessions owns it, or nobody owns it and only their sessions worked in it — never another's rows, never disks or host totals; git state without the repo path. Read-only: no Remove / Measure now / kill. The UI (components/GuestPerfSections.tsx) is its own lazy chunk.

  • Guest composer: a mandatory project pill above the text area (GuestProjectSelect; sticky as settings.spawnGuestProject, auto-picked for a single-project guest) — the run's cwd; a send without one is refused in place. Their other project chips stay, as extras: the spawn sends projects: [pick, ...chips], users/runs.check_projects needs chat on each and adds them to the write scope (kept on resume/fork). A chip turned on with nothing picked becomes the pick. Their bottom bar and drawer panels are hold-editable like the owner's, saved as their own guest-bar (the five tabs; the three-tab bar's guest-nav is ignored) / guest-you (both the Me and Settings drawers, filtered per tab) list orders; their Settings panel shares the owner's settings-panel order (docs/settings.md).

  • Their scheduled jobs (2026-11-04; the cron-jobs plugin's since 2026-11-28): every guest may schedule prompts of their own — Settings → Tâches planifiées, or ai-agent plugin cron-jobs add from a run (the CLI is on by default for a new guest since then; the plugin's shared:cron-jobs skill). See "Cron jobs: the plugin, and what the core keeps".

  • Their projects' files: read-only, through the file-explorer plugin (managed, on for every guest) — a path in a message becomes a chip that opens it, and the Project page has a Files card (see "Files a message names" below).

  • Shared threads: in a conversation with a guest owner or participants, every turn is prefixed <ai-agent-from user=… name=… role=…/>; the parser lifts it into the thread item's author (the viewer's author chip).

  • Notifications are per user: a push / ask / form reaches its conversation's audience (users/access.audience) — whoever started it (meta.owner, else the owner) and its participants, plus the owner once they follow a guest's conversation, minus whoever muted it (meta.follow: {uid: bool} — the bell in the conversation header, PUT /api/conversation-follow; the owner writing in a guest's conversation follows it). Each person on their channels (users/deliver.py): the owner through their channel plugins (+ their web push browsers), a guest in-app + web push (no per-push mail since 2026-11-01 — a stored email channel is dropped on load; Gabriel plans a weekly recap instead). The feeds (/api/notifications, /api/notify-log, the phone's /unread) list only what the caller hears — the owner included — with links rebased to the reader's host; forms carry forYou so waiting for feedback is per user too. A push with no session is the owner's; the owner also gets one push per guest start on the lab — none for a start on the guest's own computer (2026-11-07: their machine, their business; it's still in the Security log as guest_run).

  • Language (2026-11-01; a plugin since 2026-11-28): the core speaks English only; every other language is a kind: "translation" plugin (translation-fr in ai-agent-plugins, seeded at start, operator-only — docs/plugins.md → "Translations"). users.json lang = auto | en | an installed code (the guest's Settings → Display, or the owner on their page → Account; auto = the browser's, whose primary Accept-Language is recorded as browserLang on sign-in and GET /api/me — any base code, so it counts the day its translation arrives). The owner picks too (users.json ownerLang, PUT /api/me {lang}; English by default) — it sets their UI only: their pushes and runs stay English. A pick whose translation is gone reads English and is kept. /api/me returns it, Caller.lang is the resolved one. The backend's half is core/i18n.py: tr(lang, "English text", **vars) reads the enabled translation's backend dictionary (plugins/translations.py); test_i18n.py keeps the key list core/i18n_keys/backend.json in step (the frontend's i18n.test.tsx keeps ui.json) — a missing translation never fails the core, the plugin's page counts it and the plugins repo's test flags it. It words the sign-in / invitation mails, the app's own pushes (a shared notice carries i18n variants, one per installed language, picked per recipient by users/deliver.py and by the feeds), guest-facing API error messages (kind unchanged) and the New project form. A guest reading another language gets its translation's promptLine in their run's system prompt (users/runs.language_line). Text for Claude stays English. The frontend's half (the dictionary from GET /api/i18n/{lang}, cached on the device): frontend/src/i18n/README.md.

  • Web Push (users/webpush.py, 2026-11-01): guests and the owner turn push on per browser — the guest's /me#notifications, the owner's Settings → Push notifications (PushSettings, lazy) — which asks the browser, subscribes with the app's VAPID key (made on first use into VAPID_KEY_PATH, default /data/webpush-vapid.pem; replacing it orphans every device) and POST /api/me/pushes the subscription; devices live in WEBPUSH_PATH (/data/webpush.json, id = sha256(endpoint)[:16], so the page knows which one it runs on). A guest's subscribe also switches their webpush channel on; the owner's devices ride beside the channel plugins, never instead. Every notify / ask / form push (_deliver's kind: forms pass pushKind: "form" to _create_notify) and the login-refresh alert go out through pywebpush off the request thread; a 404/410 drops the device. The service worker's half is frontend/public/push-sw.js, pulled into the generated sw.js by workbox importScripts: it draws the notification (push-icon-192.png / push-badge-96.png; asks and forms requireInteraction), an ask's options become buttons that POST /api/ask/{id}/answer straight from the notification (none on iOS — a tap opens the conversation), and a tap focuses an open window and routes it in place (push-open message → src/pwa.ts). iPhone/iPad only deliver to the Home Screen app — the card says so in a Safari tab. Not while impersonating (the owner's browser would keep the guest's pushes). Owner side: the guest's page → Account → Notifications lists their devices with Send test push (POST /api/users/{id}/push-test); /api/me/push/test is everyone's own Send a test. Env: VAPID_SUBJECT (default the guest surface's URL), WEBPUSH_TTL_S (24 h).

  • Web Push ↔ Home Assistant parity (2026-11-01, form pwa-pushes-home-assistant-parity_7tmbmq; HA stays the owner's phone channel). users/push_style.py is the twin of the HA integration's TYPE_STYLES: a push's type → a style → its large icon + status-bar badge (frontend/public/push/<style>.png / -badge.png, rendered in the HA colours by frontend/scripts/push-icons.mjs — re-run it after adding a style). A site gets one Android channel, so HA's per-type channels are groups each user sets to Buzz / Silent / Off (PUT /api/me/push/prefs, kept per user in webpush.json prefs, same on all their devices; defaults = HA importance: high/max buzz, default silent; off sends nothing). A push's image is served from the app — GET /api/notify/{id}/image (notifications/image_proxy.py): the hub's own paths redirect onto the caller's host, public hosts are fetched and passed on (image/*, ≤ 5 MB, each redirect re-checked), a lab/private host only redirects the owner and 404s a guest (the hub never fetches its own network for one). Chromium sends the session cookie with notification image loads, so this works on the Authelia host too. tag (forms: their id) + renotify + timestamp ride along; an ask answered or a form submitted / cancelled / closed anywhere sends a silent {kind: clear, tag} push (deliver.clear) and the worker closes it on every device — not to users who have questions off. Not built (his call): --action-cmd buttons, the work-account split.

  • Clearing pushes everywhere (2026-11-01, form clearing-phone-notifications_txsep5): a push leaves every screen it reached once it is dealt with — users/deliver.clear(deps, sid, tag, style, only=, phone=) sends a web push clear to the audience's devices and {"event": "clear", "tags"} to the owner's channel plugins (notifications/service. clear_phone → the HA integration's clear_notification; every HA push is now tagged with its form id or hub id, the entry records tag). Triggers: an ask answered anywhere (/api/ask/{id}/answer), an ask expiring (the ask-sweeper thread, every 5 min — asks used to expire only when read), a form submitted / cancelled / closed, and a card read in the app — POST /api/notifications/state (expanded or swiped; only the ids that moved), or the older /seen with ids (not all/seed), clears the reader's own devices, plus the phone for the owner (entries_for_feed_ids: log#<id> or a conversation's <conv>#<at>#<i>, whose at is the log entry's). The other way: the HA integration reports a phone swipe (mobile_app_notification_cleared → POST /api/notifications/dismissed {tag}, owner only) → dismissed in the ledger, SSE notif-state (+ the older notif-seen; owner-only) drops it from the open PWAs' New/unread, owner's web push devices cleared — never echoed to the phone. Integration changes need the home-assistant-push plugin's integration/install.sh --restart (ai-agent-plugins repo).

  • Spend + impersonation (Settings → Users): /api/users carries each guest's spentUsd (this month — what the budget is checked against), totalSpentUsd and conversations (users/runs.spend_by_user), shown as a meter on every row of the list plus a month summary. Each guest has a page, /settings/users/<id> (users/pages/User.tsx; the old #user-<id> anchor redirects there): a hero, three KPI tiles, and tabs in ?tab= — Access (grants with a View/Chat/Ship toggle, models, new projects), Budget, Activity, Account. Field edits share one draft (users/userDraft.ts: draftOf / patchOf / rebase) behind a save bar that tucks the phone's new-session drawer away while dirty; the enable switch (top bar), sign-in actions and delete apply at once. The charts and the recent conversations come from GET /api/users/{id}/activity (users/runs.activity_of, from the memoized cards — never the transcripts): spend per UTC day over 30 days and per project this month, a conversation's whole cost on the day it last ran (as the month's sum does), split owner account / their own Claude. Delete (DELETE /api/users/{id}; disable is the reversible one) drops the record, their sessions + links, their u.<id>.* ui-state, their place in shared conversations (participants / follow, access.forget_user) and logs their own Claude login out on the host (best effort, off-thread). Their conversations, transcripts and projects stay, still owner: <id> — and the id is retired (users.json deleted), so a new user with the same name gets <id>-2 instead of inheriting them, the ~/.claude-guests/<id> dir or the Gitea account named after it. Impersonate (POST /api/users/{id}/impersonate) opens a short-lived guest session (IMPERSONATE_TTL_S, 4 h, never extended, not counted in their sessions, imp on the record) as a host-only cookie on the admin host — the browser then is that guest (/api/me → impersonating, the amber Viewing as bar); Back to admin is /api/auth/logout. It only narrows what that browser can do. A spawn while impersonating skips the "guest started" ping.

  • New projects — the new-project live plugin (ai-agent-plugins plugins/new-project/, since 2026-11-25; backend/newproject/ and notify new-project are gone). The owner, and guests granted the managed plugin (Managed plugin grants — it replaced the createProjects switch; grant fields override quota / templates / approve), start a project from one of TEMPLATES_DIR's templates at <label>.<bucket>.<domain>; the policy is the plugin's settings. The run follows the plugin's new-frontend-project skill (open_new_project.py → actions/open_form, runAs: owner), which opens an ask-form form and records it in the plugin's shared requests.json; plugin:ask-form:form.submitted → shape/policy checks → hub/scaffold/check (problems ⇒ a fresh pre-filled form) → an approvals decision for an approve template (plugin:approvals:decision.resolved) → hub/scaffold/run → hub/scaffold/grant-project → hub/scaffold/relocate (the sidecar's /relocate + /resume there with an app-authored turn, plugins/hubbridge.py). The core keeps only the spawn: the plugin's provides.composer.mode (plugins/waiting.composer_modes_for) is the source of truth for /api/me.newProjects (None without it), the composer's toggle / + New project entry, /api/spawn's newProject check and the mode's stagingNote (users/runs.new_project_mode / new_project_line / staging_note). A guest's + New project spawn starts in ~/projects/.new-project/<uid> (users/runs.staging_cwd) with users/runs.staging_scope (writes /tmp only; it carries their tool proxy so the plugin's skill can reach the hub). plugins/carryover.new_project moved /data/new-projects.json, guestDefaults.newProjects and the projects.create guests over once (the permission itself is gone since; the carry-over reads it off the raw allow list). A guest's resume always passes the session's own cwd (runs/reply.session_cwd).

  • The guests' New project policy is the plugin's settings only (since 2026-11-27): quota, templates, approve, visibility, visibilityDefault, level, domain. The core's copy (users/store.DEFAULT_NEW_PROJECTS / clean_new_projects, schemas.NewProjectPolicy, guestDefaults.newProjects in GET/PUT /api/guest-defaults) is gone; a stored guestDefaults.newProjects is only read raw by UsersStore.legacy_new_projects() (the carry-over and a fallback). The guests' root domain (<name>.<bucket>.<domain>: ship hosts, Matomo, users.read's address, the Users page) is users/domains.default_domain: the owner's new-project Shared domain setting (installed, enabled or not) → the legacy guestDefaults.newProjects.domain → gabvdl.xyz. /api/guest-defaults reports it read-only as domain; change it in the plugin's settings.

  • A guest with no project (no chat grant on any — view-only ones don't count; since 2026-11-15) still chats: their composer's project pill reads No project (the default, + New project one pick away when allowed), the spawn sends projects: [] and runs/routes._spawn_scratch starts it in ~/projects/.guest-scratch/<uid> with users/runs.scratch_scope (writes that folder + /tmp, no pushes), stamped meta.scratch — which keeps that scope on resume (_guest_scope) and lets them keep writing in it (access.can_send). The composer and the reply box drop the Changes chip there and always send its "no changes" line (lib/guidelineDag.withoutChangesChip, richComposePrompt's fixed). No owner push on start (Security log only). A guest holding a chat project who sends none still gets the 400. Its shell is a per-guest switch (users.json scratchBash, Settings → Users → → Access → No-project chats; on by default — Gabriel's call, 2026-11-15): off, the scope carries noBash and the sidecar launches the run without Bash and Monitor. On, a guest with no project at all has a shell on the lab until GUEST_SANDBOX is.

  • A guest's own root domain (their card's domain, Settings → Users → → Web address): their projects go to <label>.<domain> instead (<label>.<bucket>.<domain> only if the owner also set a bucket), and the form offers the bare domain too (apex checkbox / open_new_project.py --apex). users/domains.address_of → (bucket, domain), opts["base"] = what follows the label; the scaffold vars carry DOMAIN + HOST (the lab's generator and templates deploy to @@HOST@@). Saving a new domain runs users/edge.setup_later: the sidecar's POST /edge-domain runs the lab's edge-domain add <domain> --json (raspy2's Traefik passthrough rules; once the DNS points at the lab, the zipgo folder + a zipgo restart) and retries every 10 min until ready (48 h max; lost on a backend restart). The card shows DNS / Edge / HTTPS from GET /api/users/{id}/domain (?cached=true = the last answer) and Check again = POST /api/users/{id}/domain/setup. The DNS itself is not set by the app.

  • Approvals — a live plugin since 2026-11-25 (plugins/approvals/ in the ai-agent-plugins repo; core backend/approvals/, notify approval, cli/skills/ask-approval and Settings → Approvals are gone). A run stuck on a step only the owner can take sends him a request through the plugin's ask-approval skill (POST …/plugins/approvals/actions/request, runAs: owner); his owner-only ask-form answers it, an owner run carries a guest's plan out and its report goes back into the requesting conversation (conversations.reply). Its decision export is a plain owner yes/no for other plugins (emits decision.resolved). Guests get the skill as a managed plugin skill (users/runs.APPROVAL_LINE when it is on for them). The old /data/approvals.json (requests + always allow rules) is carried over once into the plugin's hub-scoped approvals.json (plugins/carryover.approvals). /settings/approvals redirects to /settings/plugin/approvals. The exit watcher (runs/sidecar_client._mark_run_exited) now dispatches conversation.finished ({sessionId, state, exitedAt}) to the owner's live plugins.

  • A guest's run is contained (docs/security.md):

    • Live runs (runs/service.py): every launch stamps meta.runAs, the guest it was scoped for or owner. A guest's turn into a live run that isn't theirs is a 409 run_busy: never the inbox, which would hand it the owner's permissions, and never a stop.
    • Spend: on the owner's account each run is capped at the month's remainder (scope maxBudgetUsd → --max-budget-usd), with GUEST_MAX_LIVE_RUNS (3) at once.
    • Run env: no SSH agent, D-Bus or XDG_RUNTIME_DIR, plus AIA_GUEST=<id>; the shared screenshot / page-scrape refuse Authelia and lab/internal hosts when they see it.
    • Git: the run never gets the owner's credentials (sidecar guest_git.py, scope git {user, email, push}): its GIT_CONFIG_GLOBAL is a sidecar-written file with the committer identity only, so none of ~/.gitconfig's helpers (git.gabvdl.xyz, gitea.lab, gh for github.com) is in reach. A ship run pushes to Gitea with the guest's own token; a chat run can't push at all; nobody's run pushes to a github.com remote.
    • The project's own Claude configuration is ignored on the lab (--setting-sources user --strict-mcp-config, hooks under python -I, Edit denied on .claude/settings*.json and .mcp.json): its hooks, env, permissions and MCP servers would run outside any sandbox. The sidecar appends the project's CLAUDE.md as plain text instead (60 KB, no @ imports); project-level skills and agents don't load. Not on a guest's own computer.
    • git on a guest's repo — the Bash diff hook, the Changes tab, the gallery — goes through safegit.py (one in sidecar/, one in backend/): fsmonitor, hooks, external diff and textconv off, work-tree commands against a private git dir so the repo's .git/config (a clean filter) is never read. Use it for any new git call on a repo a guest can write.
    • Guard: the guard hook blocks their docker, sudo, ssh, hub-port and /proc environ calls, and any ai-agent call but the plain one its broker runs (below) — from Bash and from Monitor, which runs shell commands too. It fails closed: an exception, an unreadable input or a guard that can't start is a deny. The CLI itself refuses under AIA_GUEST.
    • Deploys go through the ship live plugin's ship-deploy skill (since 2026-11-26; ship.run bridge + sidecar ship.py), to the owner's per-project host list (the plugin's deploy-hosts.json, edited on the project's page) or one label under the guest's own namespace; any other host asks the owner through Approvals.
    • GUEST_SANDBOX=1 (bwrap) is the real boundary and is still off.
  • A guest's ai-agent CLI (users/cli.py, 2026-11-02; Gabriel's calls in form guests-and-the-ai-agent-cli_a601cw): their runs may drive the hub as them once the owner switches it on (users.json cli, Settings → Users → → Access → ai-agent CLI, default off).

    • The broker: a scoped run's guard runs a plain ai-agent … Bash command itself, outside the session (and its sandbox), from its argv — never a shell — with a clean env, cwd / and AIA_AS_SESSION=<the run's session id>, and hands back the output as the deny reason (≤ 12k chars, cut in the middle). Pipes, &&, redirects, $VAR, $(…) are refused; env X=1 ai-agent, sh -c 'ai-agent …' and ai_agent.py hit the guard's guest.ai-agent rule.
    • The gate: the CLI sends X-AIA-As-Session; on a call that is already the owner (trusted peer — the header alone grants nothing) it becomes the guest of that session's meta.runAs: active, guests not locked, cli.use held, else 403 (guest_cli). It holds the cli scope (authz/scopes.py) — narrower than their browser (no settings, devices, computers, sharing, uploads, never answering a form) — and the handlers filter as for their browser. An owner run's session stays the owner. The response carries X-AIA-View-Url (GUEST_PUBLIC_URL) so the CLI's links open their app.
    • Commands (cli/ai_agent.py GUEST_COMMANDS): new / send / fork / wait / show / ls / search / stop, title / archive (their own conversations, title/archived only, as an agent rename — conversations/routes.GUEST_META_KEYS), inbox (their forms and asks; no owner unread ledger), projects / models / budget (/api/me: their month, models, own login). Anything else exits 2. A wait is one AIA_GUEST_MAX_WAIT_S (240 s) slice — the hook times out at 300.
    • Children: new is always a child of the calling run (Caller.via_session, whatever the body says), in its project unless --project names another they hold chat on; the owner's limits (depth 2, 4 running) inside GUEST_MAX_LIVE_RUNS; billed like their composer runs; no "guest started" push for a child.
    • The skill: their runs get shared:ai-agent — the guest edition at cli/skills/ai-agent/SKILL.md, the sidecar's built-in @ai-agent ref (shared_skills.BUILTIN_SKILLS), first in the plugin so it wins over an owner skill of the same name — plus a system-prompt line (users/runs.CLI_LINE). Without the switch, neither.
  • The guard (sidecar guard.py): a PreToolUse hook on every sidecar run (Bash / Edit / Write / MultiEdit / NotebookEdit).

    • Rule families: persistence, destructive, exfil, docker escapes, plus the guest family.
    • A scoped run's hit is denied; an owner run's goes through.
    • Both are POSTed to /api/security/events. SIDECAR_GUARD=0 disables it.
    • Tune the rules against real history before widening them: the replay script and its numbers are in docs/security.md. A false hit pushes Gabriel or blocks a guest.
  • Settings → Security (backend/security/, business/security/):

    • /data/security-log.jsonl holds sign-ins, new devices, link requests, guest runs, guard hits, sandbox denials, edge probes and ship deploys;
    • the push picks live in /data/security.json;
    • Lock guests drops every guest session, refuses sign-in (403 guests_locked) and interrupts their runs;
    • Stop every run covers the lab and online workers;
    • all owner-only, and the SSE type security never reaches a guest.

Guests' own Claude logins (accounts/guest.py)

A guest can connect their own Claude Pro/Max (their /me → Budget → Claude account, the same headless sign-in as the owner's accounts): account guest-<uid> = the host sidecar's ~/.claude-guests/<uid> (SIDECAR_GUEST_ACCOUNTS_DIR; made on the first sign-in by claude_accounts.provision_guest, 0700). Its projects/, CLAUDE.md, RTK.md, settings.json and skills are links into the host user's ~/.claude — only the login is theirs — so transcripts land where they always did (ingest unchanged) and a session resumes on either login.

  • Routing (users/runs.run_as_guest): their own login first while it is connected and healthy; a launch refused as auth / rate_limit — or a login the health monitor holds as signed out / limited (a usage-limit error in the last 5 h) — falls back to the default account, where the budget and allowed models apply. The owner writing in such a conversation (resume / fork) always bills the owner's account. meta.account is the latest run's account (a mid-thread fallback moves the whole conversation).
  • Their pick (since 2026-11-04; on their own computers since 2026-11-06 — there Your Claude is the computer's own login, the chip shown whenever that computer is signed in, see "Guests' own computers" → Runs): the composers' account chip (GuestAccountChip, new conversation and reply alike) is a select — Your Claude (the routing above, the default) or Host's account (straight to the default account, budget + allowed models, the model list narrowed to match). PUT /api/me/claude/bill (own|host) keeps it on their login record (users.claude.bill, kept across a re-login); run_as_guest reads it (prefers_host), so CLI-started children and their cron jobs follow it too.
  • Costs: guest-* accounts are excludeFromTotals (an estimate on a plan the owner doesn't pay); ?account=guests still selects them all, but the dashboards' Guests segment is now the Guests profile (profile:guests — every guest's conversation, on any seat; see "Profiles → … → The Guests profile"), whose figures count their own logins too. spend_by_user splits on the owner's account (budget) from own*; Settings → Users shows both, the guest sees their own in /me → Budget.
  • Usage % (since 2026-11-07): the status line that feeds the owner's accounts never renders on a guest login, so the host sidecar (the provider-anthropic plugin's sidecar/usage.py reader, every SIDECAR_CLAUDE_USAGE_POLL_S = 300 s) reads each logged-in guest dir's 5-hour / week / per-model week through Anthropic's GET api.anthropic.com/api/oauth/usage (what /usage reads — no tokens spent) and writes <guest dir>/usage-state/rate-limits.json; a fresh sign-in reads at once. The token never leaves the sidecar (its /access-token still refuses guests); one about to expire is skipped, never refreshed (the refresh token rotates and their runs share it — every run refreshes it). The hub pulls GET /claude/usage on the usage poller's tick (usage/service.remote_snapshots) and records guest-<uid> points like any account's, but service.metered() keeps them out of calibration, plan tracking and their pushes. Served to the guest as GET /api/me/usage (the /api/usage/limits shape, their login only, empty unless connected; the SSE usage ping now reaches guests) — their home strip and their composers' rings (GuestUsageRings: only while the prompt bills their own Claude on the lab, not the host's account nor their computer's login) — and to the owner as a reading-only row in /api/usage/limits (the Guests strip's own week).
  • /api/me → claude (with bill); /api/me/claude/login[/code], /logout, /bill, GET /api/me/usage (guest routes). ~/.claude-guests/** is in every guest run's DENY_READ.

Guests' own computers (users/computers.py, workers/link.py)

A guest can pair a computer of their own (a Mac mini…) and drive Claude Code there from their portal — runs that never touch this host. Decisions (homelab data/log/2026-11-02-guest-workers.md, forms guest-workers-guests-own-computers_q9ztmc, guests-own-computers-screens-and-flows_9twu29, guest-computers-security-hardening_0n6okr): self-serve once the owner switches it on for that guest (users.json computers: {enabled, max}, default off / 3), every Claude call on the owner's default account within their limits — unless the computer is signed in to the guest's own Claude, which their app runs there bill first (since 2026-11-06, see Runs) — no lab projects there (runs start in the machine's start folder, or — since 2026-11-11 — in one of its projects the guest picks), a reverse HTTPS tunnel — no Tailscale for guests.

  • The worker link (workers/link.py, sidecar/link.py): the computer listens on 127.0.0.1 and long-polls POST /worker-link/poll on the guest host (≤ 25 s, Bearer its link token), runs each request against its own sidecar and answers POST /worker-link/reply/<id> (status + headers in x-link-status / x-link-headers; a body over 512 KB is fetched from /worker-link/body/<id>). The hub's callers don't change: a linked record's url is the backend's own http://127.0.0.1:8080/_tunnel/<id> (loopback only, no X-Forwarded-For), which relays — the monitor, both mirrors, spawn/resume, uploads, lab sync, the proxy push all work as on the tailnet. Not linked (no poll parked, none in 40 s) ⇒ 502 worker_offline at once. Feed and outbox polls of a linked worker run every 4 s (LINK_EVERY_S). Long-poll, not a WebSocket: Traefik's readTimeout: 600s, and a stdlib-only worker. Since 2026-11-19 the owner's own machines off the tailnet ride the same link (Add machine → It dials out, see "Workers" → "A machine off the tailnet"): a linked record is a guest's computer only when it has an owner — test that, never link.
  • Enrolling: Add a computer (POST /api/me/computers) mints a one-time code (16 chars, 1 h, WORKER_ENROLL_PATH) and the installer line (WORKER_HUB=<GUEST_PUBLIC_URL> WORKER_ENROLL=<code>). The installer's link mode binds 127.0.0.1, skips Tailscale and the Claude login check, prints the disclosure, and runs link.py enroll: POST /worker-link/enroll {code, pairCode, hostname…} → the hub mints the record — its own id (g…), never the machine's, owner, link, pending + the sidecar's pairing code — and the first poll runs the ordinary POST /pair through the link (complete_pairing), then pushes the owner. A computer is in no profile (ProfileStore filters owner); Settings → Machines lists them apart with Revoke (DELETE /api/workers/{id} → computers.remove).
  • Codes don't revoke each other (since 2026-11-03 — a re-opened dialog minted a second code, which killed the line Akira had already pasted, and the install failed at its very end): every code shown stays good for its hour (≤ ENROLL_LIVE_MAX = 5 live per guest, the oldest beyond it go), the first one used retires the guest's others, and a may_add refusal leaves the code unused. The dialog re-shows the line it showed last (module state, while it has 5 min left and enrolling holds). The installer asks POST /worker-link/enroll/check {code} (not consumed) before its minutes-long build, so a dead code fails in a second; link.py enroll exits 3 on enroll_code and the installer prints what to do (a new line — the install is reused).
  • Trust (workers/guests.py): the mirror writes only sessions the hub started there (meta.worker) or the guest shared from its terminal (see "Their terminal claude" below — the others stay on their machine) and nothing the meta store places on another runner or person; outbox items must name one of its sessions (a push with no session would be the owner's); lab sync = guestDefaults.sharedSkills (repo skills) only; no owner agents ride its runs; nothing goes into its ~/.claude/settings.json (desired() → default: None, proxy URL = GUEST_PUBLIC_URL/proxy/claude). Tokens (proxy + link) rotate every rotateDays (maybe_rotate on the probe; the link one handed over by POST /link/token first; the old ones work for ROTATE_GRACE_S). Mirror quota mirrorMb per computer a month (MirrorQuota). 20 bad tokens or codes from one address in 10 min lock it for an hour (BadTokens, Security ip_locked).
  • Runs: a guest's spawn with worker = one of their computers (runs/routes._spawn_on_computer) — any other runner they name is ignored (the lab, pinned, as before). Project pill (2026-11-11, form guest-project-pill-and-plan-peaks_8bd65j): on a computer the composer's project pill lists that machine's deduced projects (projects/worker_projects.py, <folder>@<computer id>, newest first) under a Start folder row (the default), remembered per computer (spawnGuestComputerProjects); a pick sends projects: [slug] and users/runs.computer_project checks it is that computer's (else 400 guest_project), the run starting in its folder (cwd), stamped with it, and its folder added to writeDirs — on later turns too (session_computer_project). No Other folder… typing (later, maybe). Scope = writeDirs: [its start folder, /tmp], remoteControl: false, a system-prompt line saying whose machine it is (+ their language). Which login (users/runs.run_on_computer, 2026-11-06 — Akira's fedora billed $218 of the owner's plan while signed in to his own Pro; forms akira-his-own-claude-on-his-computer_oqhpb2, akira-s-computer-what-those-runs-billed-doing_dgwh3o): their own Claude = the computer's own login — the one claude in its terminal uses — first: account guest-<uid>, which a linked worker's sidecar runs on ~/.claude with no proxy pair (sidecar/claude_accounts.machine_login; guest-<uid> on the host stays the config dir), any model, no budget, billed as their own (excludeFromTotals, own* in spend_by_user). The computer says whether it is signed in on /health → ownLogin ({signedIn, subscriptionType, credentialsAt} — credentials file or the Keychain), kept in the worker status. The owner's default account (budget, their models — a disallowed pick swapped by fallback_model, maxBudgetUsd = the month's remainder) when: they picked Host's account on the chip (prefers_host — PUT /api/me/claude/bill takes a pick from a guest with a computer even with no Claude connected here; a logout keeps it), the computer isn't signed in (or its sidecar predates ownLogin), the launch is refused auth / rate_limit (machine_signed_in checks before launching), or a run of theirs there ended on a usage limit (held 5 h) or a dead login (held until credentialsAt moves) — computer_hold scans their sessions there and keeps what it finds in the worker status (ownHold), since a host turn that answers clears the transcript's error, not the plan's limit. The Claude connected in the app is not used there (Gabriel: "computer's login only for now" — both are usually the same plan). GET /api/me/computers → ownClaude per computer drives the chip (below). Hub-started runs are registered before launch (workers/terminal.expect_run): their first proxied call used to beat the spawn's meta.worker stamp and get claimed as a terminal session ("Terminal · the host's Claude" on 13 of Akira's app runs, relabelled). The account must reach the computer (2026-11-12): after the fix above, 23 of Akira's runs stamped guest-akira still billed personal through the proxy ($274.86) because the hub's runs/sidecar_client._sidecar_call dropped every account a worker doesn't proxy — guest-<owner> included — so the computer took its default, the proxied personal. It now keeps a guest's own account on their own computer (_own_login). The 11-07 tests stubbed _send_message/_launch and never saw it; test_their_own_account_reaches_the_computer stubs only the HTTP call. Homelab data/log/2026-11-10-akira-budget-proxy-leak.md. Defence in depth, the proxy pair never rides an own-login run (2026-11-10, first blamed for the leak — wrongly): sidecar/proxy_pair.py finds the hub's pair (a base URL on the hub's /proxy/claude path, the token beside it, the proxy token anywhere) in the process env and in any settings file the run can read (user, the run's folder and those above, managed). An own-login run drops it from its env (_account_env) and unsets it in --settings (claude_proxy.with_settings_env(…, cwd); settings env outranks the process env, the flag outranks the files, an empty value unsets — checked on the CLI). The terminal launcher's My own Claude does the same. /health → ownLogin.override says where it sits (source, path, keys; for the env startedBy = the parent process and serviceManager = held by systemctl --user show-environment), never values. Managed settings can't be beaten, only reported. Safety net (claudeproxy/routes._own_login_leak): a proxied call from a session whose meta says the hub launched it on the guest's own Claude restamps it account: <proxied account>, ownLoginLeak: true (spend, budget and card follow), logs guest_own_login_leak and pushes the owner once a day per guest; the flag sticks, so a later turn's stamp back to guest-<uid> (its calls can beat it) still counts as the host's (users/runs._billed_own). It isn't refused: the guest may resume that conversation in the terminal on ai-agent Claude. Budget credit: PUT /api/users/{uid} {budgetCredit: {month, usd, note}} stores budgetCredits[<YYYY-MM>], which users/runs.month_credit takes off that month's spend everywhere the budget is read (with_computers, month_spend_all; creditUsd on the user). usd: 0 takes it back. route_new_run refuses anyone else pinning a guest computer (worker_guest); the owner can't continue or fork those conversations; the guest stops / continues them without a project grant (access.can_send). Pause (PATCH /api/me/computers/{id} {paused}) refuses new runs (409 computer_paused) and every proxy call.
  • The proxy holds it (claudeproxy/limits.py) — its token sits on the guest's disk, an API key in all but name: every proxied reply (any worker) streams through a UsageTap (SSE message_start / message_delta usage, upstream asked for identity encoding) into the ledger (PROXY_LEDGER_DIR/<YYYY-MM>.jsonl, sums per guest / worker / account). A guest computer's call is refused (API-shaped error, Claude Code shows it in the thread) when: the guest is disabled or locked, the computer paused, a path other than v1/messages / count_tokens, the 1M-context beta, fast mode, a model outside their families, the month spent (the lab's cards — spend_by_user now leaves a computer's conversations out, machine* — plus the ledger: with_computers / month_spend_all), the owner's plan past fiveHourPct / sevenDayPct (freshest of the poll and the proxied replies' headers), inFlight calls running on it, perMinute calls in the last minute. Limits live in guestDefaults.computerLimits (Users → Every guest). Refusals → Security guest_proxy_refused (once per computer+kind per 10 min); budget/plan ones push the owner once a day. On the public guest host /proxy/ takes guest computers' tokens only.
  • Their terminal claude (2026-11-03, form choose-claude-at-terminal-start-sync-to-the-app_n789ku; worker/claude_launcher.py, worker/claude-mod/, sidecar/terminal.py, workers/terminal.py): the installer wraps the shell's claude in a picker — ai-agent Claude (the proxy pair; synced) or My own Claude (the machine's login; not synced unless the guest syncs it), Remember per folder tree — see worker/README.md → "claude in a terminal there". The hub claims such a session (workers/terminal.claim): on its first proxied call (the CLI sends X-Claude-Code-Session-Id — measured on 2.1.317; the proxy also writes it into the ledger row as session) with terminal: "proxy", or when the computer's /feed lists it under synced with terminal: "local" (accountSource = guest-<uid>: their own plan, out of the totals). A claim stamps workerSource + owner, so guests.session_belongs takes it from then on — refused for an id the hub knows from anywhere else (meta elsewhere, or a transcript in another source: a computer can't name an id it saw and get it stamped as the guest's). A local one keeps coming only while /feed still lists it (still_synced) — Stop syncing keeps the copy, takes no more; a local one the guest resumes on ai-agent Claude turns proxy. The card's meta.terminal draws TerminalBadge ("Terminal · your own Claude" / "· the host's Claude"); continuing a local one from the app confirms it moves to the host's Claude and sends with fresh (Haiku compaction). The probe pushes the picker's and the mod's figures (PUT /terminal/status: budget left, paused, waiting, the guest host, the owner's name) when /health's terminal.statusHash differs. Routes: GET /api/me/computers/{id}/sessions (read from the computer when opened, never kept), POST|DELETE …/sessions/{sid}/sync, PATCH /api/me/computers/{id} {launcher}; My computers shows them folded under each computer (TerminalSessions.tsx). It reaches a computer by auto-update (worker/ changed ⇒ install.sh update lays the shell hook) — on by default, the portal's Ask at start switch turns it off.
  • Edge: the homelab router ai-agent-guest-link (Host(ai-agent.gabvdl.xyz) && (/worker-link/ || /proxy/claude/ || /proxy/tools/), websecure + public, its own per-IP rate limit, no compress).
  • Routes: GET/POST /api/me/computers, PATCH/DELETE /api/me/computers/{id} (guest), GET /api/users/{id}/computers, DELETE /api/users/{id}/computers/{wid} (owner). GET /api/me/computers carries waiting (budget | plan) for the banner on Me.
  • Frontend (frontend/src/business/computers/ + business/machines/): a person's Settings → My computers — since 2026-11-23 the Machines page's person variant (/settings/machines, registry entry profiles, scope mine; /settings/computers redirects): the same list row and machine page as the operator's (pages/MyMachines.tsx, pages/Computer.tsx at /settings/machines/computers/<id>, the two API shapes behind machines/computer.ts) — state, last seen, running, this month's $, ⋯ Pause / Remove, rename in place, Setup, terminal sessions, the limits in a fold, an off-state when enabled is false — and the Add a computer wizard (the owner's Add machine steps, technical/Wizard.tsx, with step 1 fixed — it dials out — and no profile: step 2 mints the code and shows the line + Copy and the disclosure, step 3 waits and flips to Connected ✓ when a computer that wasn't there shows up online). A guest gets no workers SSE event (core/routes._GUEST_PASS), so useMyComputers polls: 30 s, 2.5 s while the dialog waits. The guest composer's Runs on pill (GuestRunnerSelect, sticky settings.spawnGuestRunner; shown once they have a computer, offline / paused / connecting ones greyed): a computer hides the project pill and its chips and sends worker: <id>, projects: []; a send to one that can't take it is refused in place. On a computer the account chip stays (GuestAccountChip computer=…, the reply box's too): Your Claude · pro is that computer's login (lib/loginHealth.guestOwnOn — shown when it is signed in or a Claude is connected here; the hint says why it can't take a run: not signed in there, at its limit, login dead), and the model list and the send block follow it. ComputersWaitingBanner on Profile, Budget and My computers; a computer that is down gets a row of the home WorkerOfflineBanner. Owner side: the guest's page → Access → Own computers (switch + max in the page's draft, their computers with Remove), Users → Every guest → Guests' computers (the six limits), and Settings → Machines → the Guests group's People's computers (each a row opening the same computer page: Check now, Revoke). lib/workers.useWorkers() is the owner's runners only (no owner) — the composer's Runs on, profiles, cron, the shortcut audiences and the home banners never offer a guest's computer; useAllWorkers() (badges, labels) and useGuestComputerWorkers() (the Guests profile's node) see them. Mock: mock/computers.ts (Dom has two, a pairing completes in 8 s, ?mockWaiting=plan|budget for the banner).

Guests' tools: the tool plugins, through the tool proxy door (backend/toolproxy/)

The lab's Nano Banana, video, 3D, Matomo, Movies and Meta Business tools for guests (their lab runs and their own computers) and for the owner's Macs, with every key kept in the hub. Since 2026-11-26 (form ai-agent-moves-to-ai-agent-plugins_o2qxmd) each is a live plugin in ai-agent-plugins — nanobanana, video-extract, video-dl, 3d-gen, 3d-render, matomo, movies, meta — and the core's own per-tool brokers (toolproxy/meta.py, metaroutes.py, snapshots.py, matomo.py, media.py, webroutes.py, owned.py, catalog.py, the Nano Banana / 3d-gen / 3d-render / video-extract / matomo / meta / movies routes and the movies webhook), the guests' tool groups (users.json tools, Settings → Users → Paid tools and Tools budget), Settings → Meta Business (/settings/meta now redirects to /settings/plugin/meta) and the seven hub editions (cli/skills/{nanobanana,3d-gen,3d-render,video-extract,matomo,movies,meta}) are gone. Each tool's own rules (Seerr's quota, Matomo's "a site is theirs when every URL is on their address", Meta's read-only key, the price book…) live in its plugin (plugins/<id>/README.md, skill/SKILL.md, handlers/). What the core keeps:

  • The door (toolproxy/routes.py, /proxy/tools/…, outside /api): the plugins' proxies and actions answer under /proxy/tools/plugins/<pid>/… (plugins/proxyroutes.py); GET /proxy/tools/whoami says who the bearer is, the live plugins whose skills its runs get, and this month's tool spend. The bearer (toolproxy/access.py): a run token (aiat1.<uid>.<exp>.<hmac>, access.mint, key TOOLS_TOKEN_KEY = /data/tools-token.key, 3 days), a worker's proxy token (a guest computer = its guest; an owner's worker = the owner; out on the guest host only guest computers' tokens count), the lab's internal token (the owner, never on the guest host) or a plugin handler token (aiah1.…, the plugin routes only). Who may call what is the plugin side's (plugins/metering.py: grants, limits, per-grant monthly budgets, key health).
  • The tool ledger (toolproxy/ledger.py, PROXY_LEDGER_DIR/tools/), apart from the Claude proxy's, so nothing reaches month_spend_all; every metered plugin call writes it. A call carrying X-Claude-Code-Session-Id of the caller's own conversation stamps meta.tools {usd, calls, tools} — the card's tools chip (ToolsCostChip, visibility toolsCost), included in its headline price and the detail's Total cost.
  • Who gets which tool: a managed plugin's grant (Settings → Users → → Managed plugins: on/off, grant fields — Nano Banana's Allow Pro —, a monthly budget for a metered one, this month's use), or a plain plugin the guest installed (video-dl, meta — each guest pastes their own Meta key on the plugin's settings page). Movies is defaultForGuests. The guest's Me → Budget shows a Tools card from /api/plugins' managed rows (business/users/components/PaidTools.tsx).
  • A guest's lab run gets their live plugins' skills (users/runs.tool_scope → scope skills + scope tools → the run's AIA_TOOLS_URL / AIA_TOOLS_TOKEN) and the TOOLS_LINE of its system prompt — on spawn, resume, reply, fork and in a No project run alike (deps is passed to scope_for / scratch_scope everywhere). The owner's lab runs get the owner's plugin skills and toolsEnv (runs/service.py).
  • The workers' lab sync (workers/labsync.items_for): a guest computer gets the guests' shared lab skills plus its guest's plugin skills; an owner's worker the lab's skills and agents (minus its unticks) plus the owner's plugin skills. A plugin skill wins over a lab skill of the same name — the lab's ~/homelab/.claude/skills/{movies,meta,3d-gen,…} are shims for the lab's own sessions. A plugin skill with a proxy gets hub.json (with_hub: that machine's tool-proxy URL + proxy token, 0600 on the worker; a rotated token re-syncs).
  • Matomo's extra sites: a site is a guest's when every URL of it is on their address, plus the site ids the owner grants them — the matomo grant's extraSites field (a list grantField, Settings → Users → → Managed plugins → Matomo → Extra sites; since 2026-11-27 for Cel's calamite.net, site 11, a project's own domain that isn't her address). It replaced users.json tools.matomoSites, which the carry-over copies into it (below).
  • Movies brings Jellyfin: the movies grant coming on (a new guest it is on for by default, or the owner's switch — plugins/routes._granted) switches their Jellyfin app on (users/routes.movies_bring_jellyfin → their Pocket ID group). Turning Jellyfin off by hand afterwards sticks.
  • Seerr's webhook goes to the movies plugin, http://ai-agent:8080/proxy/tools/plugins/movies/webhook/seerr?token=<the plugin's webhook token> (lab-internal; homelab/services/media/README.md).
  • The carry-over (plugins/carryover_tools.py, run at start and when one of these plugins is installed or put in the catalog): each guest's old groups → grants / installs (images → nanobanana with Pro and the tools budget, video → video-extract + video-dl, 3d → 3d-gen + 3d-render, analytics → matomo, media → movies, meta → meta; never over an explicit grant; a guest who had Movies off gets an explicit off), each guest's tools.matomoSites → their matomo grant's extraSites and the grant on with analytics (matomo_sites, once per guest — not per plugin, so Cel, switched to analytics after the groups moved, still gets it; an explicit grant only gets extraSites when it has none; it waits for a matomo whose manifest has the field), the Meta keys + saved days (/data/tools-meta.json, /data/meta-snapshots/), the Matomo viewers (/data/tools-matomo.json), the Seerr users and pending requests (/data/tools-media.json) and the 3d-gen ownership (/data/tools-owned.json) → the plugins' own data; each legacy file is renamed ….migrated once carried. Tests: test_carryover_tools.py, test_tool_proxy.py.
  • The scope key tools: a lab guest run reaches the proxy on the guest host (GUEST_PUBLIC_URL/proxy/tools, homelab router ai-agent-guest-link), never loopback — loopback is the owner. Under GUEST_SANDBOX=1 the sandbox refuses this host, so the tools don't work there yet.

The hub key of a plugin: Settings → Plugins → Nano Banana (was Settings → API keys)

The paid keys the hub holds (2026-11-06, form nano-banana-key-and-api-keys-page_bwcoae; folded into the plugin's page on 2026-11-26 — backend/apikeys/, sidecar/homelab_env.py and the core page are gone, /settings/api-keys redirects to /settings/plugin/nanobanana). Today the Gemini key Nano Banana runs on. Gabriel's picks still hold: the hub's own log (no Cloud Monitoring), a monthly limit that is an alert (€20, push at 80 % and 100 %), a push when the key breaks and when it works again.

  • The key is the nanobanana plugin's hub secret (api_key, /data/plugins/secrets/_hub/nanobanana.json, 0600) — no longer the root .env's GEMINI_API_KEY. The Google side: project nanobanana-lab-gabvdl on a Prepay billing account — at $0 every key on that account answers 402 prepayment credits are depleted.
  • Every caller goes through the hub: the plugin's generate action (guests, the owner's Macs, the lab's own nanobanana skill with the internal token — via: "lab"). The older /proxy/tools/nanobanana/<model> route and its cli/skills/nanobanana hub edition left on 2026-11-26; this month's rows they wrote (ledger tool nanobanana) still count toward the key's spend through managed.keyHealth.legacyLedgerTool. image-gen is retired.
  • Generic: any managed plugin with managed.keyHealth gets the same section — docs/plugins.md → "The hub key": plugins/metering.py (observe_key_health, check_spend), plugins/keyspend.py (the view), plugins/store.py (secretHints, keySettings, keyHealth), GET /api/plugins/{id}/spend, PUT …/key-settings, Test recording the health, Replace checked with the plugin's testAction before saving (invalid / denied refused, no-credit / capped kept).
  • The page: frontend/src/business/plugins/components/PluginKeyHealthSection.tsx on PluginSettingsPage (owner only; the watched secret's card moves out of Credentials into it).

Files a message names: the file chip and the file explorer (files/hostfiles.py)

Claude writes the full path of a file it made or changed (/home/gabrielvidal/projects/calamite/marketing/meta-ads/bout-de-fi.md — the rule is in the lab's global ~/.claude/CLAUDE.md, which every lab run, guests' included, loads), and the viewer turns it into a chip (📄 bout-de-fi.md · calamite/marketing/meta-ads, full path on hover) that opens the file in the file-explorer live plugin (since 2026-11-28 — ~/projects/ai-agent-plugins/plugins/file-explorer; form migrate-files-context-dashboard-to-plugins_imhucu). Built for guests, who had no way to read the reports their conversations keep (Gabriel's calls, form open-project-files-from-messages_124rv3, 2026-11-02: compact chip, no attachment card, a page not a side sheet, guests read-only on their projects, always the current version, owner roots ~/projects ~/homelab ~/worktrees).

  • What becomes a chip (lib/hostPaths.ts → technical/Markdown.tsx): a path in backticks, bare in the text (a remark plugin turns it into a link node — never inside code blocks or an existing link) or as a markdown link target ([the report](/home/…/x.md) keeps its text, gains the icon). The prefixes are /home/<u>/, ~/, $HOME/ followed by projects/<slug>, homelab or worktrees/<dir>; a :42 line suffix is shown, not followed. Markdown knows nothing about users: PathLinkProvider (a context) hands it a renderer, and business/files/components/FileChip.tsx → FileLinksProvider (around the <Outlet/> in App.tsx) supplies one that returns null for a path the caller can't open — a guest's other projects, every non-project root for a guest — and for everyone while no active page opens: ["host-file"] (usePluginOpener("host-file")): those stay plain text. The chip's link is that page's (/plugins/file-explorer/files?path=~/…). Switch: File links in the conversation's eye popover (fileLinks).
  • The data is a bridge, hostfiles.read (plugins/hubfiles.py, operator-approved — a guest-installed plugin can't hold it; the guests reach it through the owner's managed file-explorer, defaultForGuests): GET …/hub/host-file?path= (card + text ≤ 512 KB for markdown/csv/text — a binary that sniffs as UTF-8 is text), …/hub/host-files?path= (one folder level, folders first), …/hub/host-files/recent?project=&limit= (documents — md, csv, pdf, txt, office files; not html — newest first, ≤ 20 000 files scanned) and …/hub/host-files/roots (where the caller may start: their projects; the owner every project, ~/homelab, each worktree). Each answers as the person the token names (_caller_for_who), handler or run token alike. Paths go in as written and come back spelled ~/…. The JSON routes /api/host-file, /api/host-files, /api/host-files/recent are gone; GET /api/host-file/raw?path= stays core (images/videos inline, the rest an attachment, via _safe_file_response): a sandboxed frame shows an image or video through aiAgentPlugin.mediaUrl and downloads through aiAgentPlugin.download(url, name) (both same-origin in the host, with the reader's cookies).
  • Who reads what (hostfiles.resolve): ~/projects/<slug>/… for anyone with view on the slug; the owner also gets ~/homelab/… (the whole repo, mounted read-only at HOMELAB_DIR=/homelab by the homelab compose; without the mount, the parts already mounted — services/, data/, .claude/, CLAUDE.md, GOAL.md, docs/screenshots/) and ~/worktrees/<dir>/…. Never served, to anyone — they 404 and are left out of listings: .env* (not .env.example/.sample/.template), keys and keystores, credentials*/secret* files, acme*.json, users_database.yml, *.db/*.sqlite*, .storage, the noise dirs (.git, node_modules, .venv, pb_data, caches), the lab's runtime state (services/*/data, data/tmp), and any symlink that leaves its root. A 404 never says which. test_hostfiles.py asserts every one of these over HTTP through the bridge.
  • The plugin's page (files, nav: "projects", fill, opens: ["host-file"]): no path = the roots; a name with an extension is asked as a file first, else as a folder, then the other on a 404. Markdown rendered (a Source toggle; relative and host-path links stay in the explorer), CSV/TSV as a table (,/; sniffed, 500 rows), text with line numbers, images/videos (a video over the 25 MB mediaUrl cap opens in the app's media viewer), the rest a download card. Header: Copy the path, Download; back (to where the chip was tapped), breadcrumb. It re-reads every 15 s while open. A project's root lists Recent documents above All files. It routes itself (aiAgentPlugin.setRoute / onRoute, docs/plugins.md → "Pages that route themselves"): a folder or file is an address, Back works, the frame never reloads. Its project-files slot (project.detail) is the Project page's Files card: the six newest documents, the key files, Browse all files (none for a worker's project). French for guests (init.lang).
  • CLI / MCP: ai-agent plugin file-explorer ls [PATH] | read PATH | recent PROJECT (MCP plugin_file-explorer_ls|read|recent), as the caller.
  • /file/<path below ~> (old links, pushes, PR bodies) redirects to the page that opens host-file (LegacyFileRedirect, legacyFileTarget); none active: a note naming the plugin with a link to the catalogue.
  • Mock: mock/hostFiles.ts serves one small tree per project, answered by the mock plugin's actions (mock/filesPlugins.ts; ?mockFiles=0 turns both plugins off); the kitchen-sink thread names a file.

The context tree and editor: the context-editor plugin (since 2026-11-28)

CLAUDE.md, the .claude/ tree and the read-only data/ tree — what the indexer counts (files/discovery.py, real token counts and cost in the files table) — are edited in the context-editor live plugin (~/projects/ai-agent-plugins/plugins/context-editor, seeded, the owner's only), master–detail on one fill page under Files (editor, nav: "files", opens: ["context-file"] {path} = a workspace-relative path such as .claude/skills/x/SKILL.md): the searchable tree (folder sums, a dot on an unsaved file, the context total) beside the editor (Save on ⌘S or leaving the field, Revert, a markdown Preview, read-only data/, the live ~ estimate while dirty); on a phone, the tree then the file. Unsaved drafts are kept per person in the plugin's data (drafts.json) so they follow you across devices, as the core editor's did in the ui-state blob.

  • Bridges (plugins/hubfiles.py, owner-only, operator-approved): context.read — GET …/hub/context/bundle (the old /api/bundle, memoized on files_version), GET …/hub/context/file?path=; context.write — PUT …/hub/context/file {path, content} (the plugin's own handlers only; _is_editable refuses data/; re-indexes at once). /api/bundle and GET|PUT /api/file are gone (files/routes.py keeps bundle_data, read_context_file, write_context_file for the bridges).
  • The core Files drawer and the /files landing keep shortcuts only (Notifications + every nav: "files" plugin page); the tree is the plugin's.
  • /_/<path> redirects to the page that opens context-file; a skill card's SKILL.md link and the Context & skills dashboard's rows use the same opener.
  • CLI / MCP: ai-agent plugin context-editor ls | show PATH.

Guests get a carousel of the features that shipped when they open the app: one slide per entry — an HTML mockup, a title, short markdown bullets — with Skip on the left, Previous / Next on the right (Done on the last), progress dots and a native swipe on phones. Gabriel's calls (form guests-what-s-new-carousel_lcrfjx, 2026-11-01): HTML mockups, live on deploy, only entries published after the guest joined, on by default, Skip marks the whole run seen, a replay page, nothing for the owner.

Since 2026-11-26 it is the whats-new live plugin (ai-agent-plugins, form ai-agent-moves-to-ai-agent-plugins_o2qxmd): backend/whatsnew/, /api/whats-new*, frontend/src/business/whatsNew/, cli/whats_new.py and ai-agent whats-new are gone. What the core keeps is generic:

  • provides: {"app.launch": …} (plugins/launch.py, GET /api/plugins/app-launch, business/plugins/components/PluginLaunchHost.tsx in App.tsx): asked once per opening — a load, or the app back in the foreground, never mid-use — it opens the plugin's app.modal slot (carousel) in the app's modal, which shows on an iPhone (plugin overlays don't); its closeAction (seen) marks the run seen however it closes. See docs/plugins.md → "App launch".
  • impersonatedBy in an action's AIA_USER_CONTEXT while the owner looks through a guest's eyes: the plugin records nothing then (a preview never eats the guest's carousel). users.read rows carry createdAt (who joined when). Every frame's init carries lang; a plugin page's label goes through t() (so "What's new" reads "Nouveautés").
  • provides: {"whatsnew.index": …} (plugins/whatsnew_bridge.py): App usage's announcement → adoption (telemetry/views.py whatsNew).
  • Pages (the plugin's own Settings pages since 2026-11-27, the core's /whats-new and /settings/whats-new are gone): /settings/p/whats-new/news (You, after Extras — a guest's Settings drawer → What's new) and /settings/p/whats-new/editor (Workspace, perm: users.manage — owner: write, preview phone / wide, publish, unpublish, delete, and per guest Show again).
  • Per guest: the plugin is managed with defaultForGuests: true; its grant field autoOpen (Settings → Users → → Managed plugins → Show What's new when they open the app) replaced users.json whatsNew.
  • Storage: the plugin's shared dir — entries.json and seen.json. carryover.whats_new copied the core's whats_new / whats_new_seen tables there once (the tables stay in ai-agent.db, unread) and turned each whatsNew: false into autoOpen: false.
  • Language: French. Entries are written in French — the title, the bullets and any text in the mockup, with tutoiement (« tu »), as the guest UI (the translation-fr plugin's README → Style). Every guest is French (Gabriel's call, 2026-11-01); the owner's editor around them stays English.
  • Mockups: one script-free HTML snippet, fluid (≤ ~440 px, centred), coloured only with the theme tokens — hsl(var(--primary)), --card, --border, --muted, --foreground, --muted-foreground, --primary-foreground, with / alpha where needed — so it follows light and dark both in the carousel and in an ask-form (same token names). A sketch of the feature's UI, not a page. The plugin draws it in a shadow root, on* attributes and scripts stripped.

Shipping a major feature? Offer it to What's new

When you build a major, guest-visible ai-agent feature and ask Gabriel a form about it (clarifying questions or the final review), end the form with the What's new entry block, pre-filled for that feature — in French (title, bullets, the mockup's text; « tu ») — so he can keep, edit or decline it in the same form:

ai-agent plugin whats-new fields --title "…" --body "$(cat bullets.md)" \
  --mockup "$(cat mockup.html)" > /tmp/whatsnew-fields.json

…and tell the clarifier to append that file verbatim at the end of its spec (its prompt knows ready-made blocks; without the clarifier, concatenate it into your own --fields-file). The block is a checkbox (Add this feature…, on), the title, the bullets and a live mockup editor (an ask-form widget: preview

  • editable HTML), plus a free-text changes to the mockup. Once the feature is deployed, publish what he answered:
ai-agent plugin whats-new add --form <form id> --session "$CLAUDE_CODE_SESSION_ID"

It reads the answers from the hub's copy of the form (askform.bridge, never the clarifier's report, which may escape the HTML; --answers JSON when the hub has no copy), refuses while changes to the mockup are pending — redraw it, then add --mockup "$(cat mockup.html)" — and records the session that shipped it. ai-agent plugin whats-new ls lists the entries, rm ID deletes one, --draft keeps one back. Skip the block for internal, owner-only or lab plumbing work: guests never see those.

The ai-agent CLI (cli/ai_agent.py) — sessions driving the hub

ai-agent is what an agent session (or a terminal) uses to work the hub the way the composers do: new / send / fork / stop a conversation, wait for a run to stop and print its final answer, show / ls / search / archive / title, agents, workers / usage / budget (what is left of the week once the crons and scheduled runs due before its reset are paid for, in %, units, $ and tokens per model, the pace and the nonstop runs it takes — GET /api/usage/budget, backend/usage/budget.py) / models, projects / skills, and inbox (what waits on the owner: the Waiting for feedback sources + unread pushes), plugin (manage live plugins — and a plugin's own commands, ai-agent plugin <id> <command> …, declared in its plugin.json commands: ai-agent plugin commands lists them, e.g. ai-agent plugin plans ls, ai-agent plugin memories show SLUG; docs/plugins.md → "Commands". Core names no plugin: plans / memories / goals left the core CLI on 2026-11-26, and ai-agent plans now says where its commands are — whats-new too: ai-agent plugin whats-new …, see "What's new" below; services on 2026-11-28: ai-agent services prints that it is ai-agent plugin services ls|show and exits 2; cron the same day: ai-agent cron points at ai-agent plugin cron-jobs … and exits 2), tags (a tag's colour / icon / description / auto-tag triggers, its real icon found on disk — see "The tag registry" below), and worktrees (the git worktrees under ~/worktrees — see below). Every command takes --json. The homelab skill .claude/skills/ai-agent/ is the playbook (conversation vs subagent, writing a child's prompt, waiting in slices).

  • Stdlib python like notify.py (it imports its session resolution); cli/ai-agent is the shim, so a sidecar run has it on PATH; the homelab alias goes through services/ai-agent/cli/ai-agent.sh. It calls the hub at AI_AGENT_URL as the owner (the trusted loopback). In a guest's run it is the guard that runs it, as the guest (AIA_AS_SESSION): see "A guest's ai-agent CLI" under Guests. On a worker see the next point.
  • On a worker (AI_AGENT_OUTBOX_URL set) the Mac never calls the hub, so the CLI exits 2 there — except ai-agent past KEY… (WORKER_COMMANDS), a one-shot lookup outbox item the hub answers in its ack, within the worker's own profile (conversations/past.py outbox_lookup → workers/bound.py). The refusal points to the MCP server instead: a Claude Code on the Mac drives the hub with the MCP tools through a connection bound to that worker (docs/mcp.md → "On a worker"). From 2026-11-16 to 11-18 the whole CLI went through the outbox (a cli item the hub ran as a subprocess, a per-worker ai-agent CLI switch, an ai-agent shim in ~/.local/bin); Gabriel swapped it for the MCP on 2026-11-18 — the narrowing it introduced lives on in workers/bound.py, the rest was removed (the installer deletes its old ai-agent shim).
  • An id is a session id, a ≥ 6-char prefix (the recent page first, then the whole list), a conversation's UUIDv7 (no session has it → the hub's conversation-summary answers), an old <dir>/<sid>.jsonl or a viewer link.
  • search (search_hits, shared with the MCP's search_conversations): every word in the title or messages, newest first. Before 2026-11-22 the most message hits came first, so long conversations won and runs reworded a search 3.2 times on average. When no conversation has every word, it falls back to the ones with at least half of them, most words first, and says so on stderr. --project P (a project or service tag) and --since 7d|2w|DATE narrow it. Each row names the machine it ran on (/api/search-index carries worker + projects). show adds the transcript's path when it's on this machine, and a more: line. past also takes a conversation (its id, a prefix or a viewer link): the Linear issues and PRs it is about, primary ones first (past._conversation_of).
  • The conv-ref prompt hook (cli/conv_ref.py, installed by the sidecar in every account's settings.json, harness-claude's sidecar/conv_ref_hook.py): a UserPromptSubmit hook. When a prompt talks about past conversations ("check past conv", "previous convs", "this conv 01a1…", a viewer link), it adds one block of context. That block says a conv is a hub conversation, not a file under ~/.claude/projects, and how to read one on this machine: the CLI on the lab; the MCP tools, else ai-agent past, on a worker. It also holds a card per conversation the prompt names, resolved by the hub: title, state, machine, opening prompt, last answer, and the transcript when it's on this machine. On the lab the card comes from GET /api/conversation-refs; on a worker, from a lookup outbox item with ids, within that worker's profile (past.outbox_lookup → conversations/refs.py). Its command is set per machine: the host asks the hub; an owner's worker passes --outbox + --token-file, so a terminal claude there resolves ids too; a guest's computer gets none. The command is rewritten when it changes; SIDECAR_CONV_REF_HOOK=0 removes it. It is silent on every other prompt and in a guest's run, a bare UUID that is no conversation (an Orus contract id) says nothing, and a hub error never blocks the prompt. Why: in Nov 2026, runs on the workers reached the hub for 3 of 15 "check past conv" prompts. The rest grepped the Mac's own transcripts, or ran find and ssh homelab find / for an 01a1… id (20–29 tool calls each). On the lab, 22 out of 22 reached it. The phrase list was measured on 1,406 November prompts: it catches 128 of the 130 that point at a past conversation, and adds context to about 9 % of all prompts (~/homelab/data/log/2026-11-22-check-conv-analysis.md).
  • The composer's conversation pill (frontend/src/lib/convRefs.tsx): a conversation the draft names (same detection as the hook) and the hub resolves (GET /api/conversation-refs, guests included, access.visible) becomes a pill in the resources row: state dot, title · age · machine, on by default. A tap turns it off like any pill there. Hovering it shows the last answer (RichTag.title, @gabvdl/ui 0.49.0). While on, it adds a Conversations referenced: block to the prompt (composePrompt), with plain titles for a harness the hook doesn't reach (pi, opencode); the hook ignores that block. The sent message shows the same conversations as chips under its text, each opening the conversation in place. Unknown or hidden ids show nothing. The composer reads the draft per pause (usePausedText), not per keystroke. Gabriel's calls (form conversation-links-in-the-composer_mygtqm): the resources row and not an inline chip, the same tab, nothing for an unknown id.
  • wait polls GET /api/conversations?sessions=<sid> every 3 s until the resolved meta.state isn't running (the exit watcher stamps finished the moment the run's process dies); after a send it also needs endedAt past the send, so the previous turn's finished isn't read as this one's. The answer is the thread's last assistant text. The id is resolved first (wait_session, shared with the MCP's wait_for_conversation): a conversation's UUIDv7 looks like a session id, and polling it as one never finds a card. Only a full session id the hub hasn't indexed yet (new just printed it) is polled as is.
  • Children (runs/children.py): new sends parent = $CLAUDE_SESSION_ID (--detach doesn't). The spawn route stamps meta.spawnedBy = {sessionId, depth, at} — refused with a 409 past AIA_MAX_DEPTH (2) levels or AIA_MAX_CHILDREN (4) running children of one parent (a running stamp older than 6 h no longer counts), and with a 403 when an owner call names a guest's conversation as the parent (a guest's Bash reaches the same loopback) — a guest's own children come through the broker, as them. The thread view resolves both ends (conversations/spawned.py → spawnedByConversation, spawnedChildren): the Started by banner on the child and the Started conversations Details card on the parent, each behind its visibility switch.
  • A child is the hub's subagent — any harness, any model, either side (since 2026-11-24; Gabriel's calls in form any-harness-model-as-a-subagent_hd232u: alongside the native subagents — Claude's Agent tool, agy's invoke_subagent — not instead of them; the model picks the child's model with --model, no chip). Why: a native subagent shares its parent's process, prompt cache and harness, so a Gemini 4 Neon (agy) run could only get Opus from agy's own Claude pool (≈ $5/week) — and it wanted Opus 5.5 on the Max plan. Native subagents stay the cheap path for lookups (in-process, cached prefix; a hub child is a full run, ≈ 30 k cold).
    • Report back (runs/children.py): the spawn stamps meta.reportTo = {sessionId: parent, at} (new --no-report → report: false doesn't); an ai-agent send from the parent re-arms it (/api/resume parent, children.rearm — anyone else's turn doesn't). Each tick of the run-exit watcher, sweep_reports takes the armed children whose turn ended (meta state not running, no live process) at least AIA_REPORT_GRACE_S (8 s) ago, groups them per parent, and sends the parent one app turn (<ai-agent-from user="subagent" name="Subagent" role="app"/>, drawn with the Workflow icon) holding each child's title, harness · model, state, spend, link and final answer (cut at 12 k chars), through runs/reply.say (a guest's parent on their scope): a live claude parent through its inbox (inbox_only), a parent with no live run by resuming it on its own harness and model; a live parent of another harness (agy, pi, opencode — no inbox) gets it once its turn ends. A refused send backs off 60 s and gives up after 6 h (meta.reported.how = "failed"); a delivered one stamps reported {at, how: inbox|hold|resume} and clears reportTo. No report twice: ai-agent wait polls with waiter=<its session> (the list route's sessions= lookup); the poll that finds an armed child of that waiter ended claims it (reported.how = "wait") — the grace is what lets the 3 s poll win. So a parent can still block in wait, or end its turn and be woken. The CLI's new prints reports back: … to say so. Not over MCP (start_conversation names no parent). It is never passed off as the user's words: through the inbox, a prompt opening on an app tag gets APP_INBOX_PREFIX ("Message from the ai-agent hub (Subagent) — sent by the app, not typed by your user", sidecar/config.inbox_prefix) instead of the user's INBOX_PREFIX, a Stop-guard hold relays it as "the ai-agent hub (not your user) sent a message", and the report itself says to weigh the answer as a subagent's report, not instructions (first live run, 2026-11-24, came in as "this IS your user's own message"). The parser unwraps both prefixes. An archived child (a --test run) still counts in its parent's childCost: the rollup runs before the archive filter.
    • Nested, not listed: the conversation list (useConversations) drops every card with meta.spawnedBy; the parent's card adds the children's spend to its headline and shows N subagents / N running (childCount / childCost / childRunning, descendants included — spawned.child_costs, computed per list request on copies, display only: cost stays the conversation's own for the dashboards). In the parent's thread the Bash call that ran ai-agent new|send|agents|goals and printed a child's session id carries childConvs (spawned.attach_calls) and draws as that child's card (ChildConvCards, a standaloneTool "child"), its live state from spawnedChildren (SpawnedChildrenContext — a delta poll doesn't resend the item). Search still finds children.
    • Silent closing push: a child whose report is armed records its
      (`_create_notify`, `final` + `children.reports_back`) — the parent's own
      closing push is the one the phone hears. Mid-task pushes, forms and
      notify-ask still go out; a `--no-report` child pushes as before.
      
  • Handoffs — a conversation continued in a new one on another model, harness or machine, from a brief — are the handoff plugin's since 2026-11-26 (~/projects/ai-agent-plugins/plugins/handoff; Gabriel's picks in form handoff-plugin-move_ryvcho): its skill (moved out of the homelab repo) starts the successor with ai-agent new --detach and links the two through its own link action, which writes meta.plugins.handoff.{from,to} with the conversations.data bridge; its Hand off… row in the conversation menu (ui.menuItems) opens its dialog (warm: the source writes the brief through conversations.send; cold: a Haiku test writer through runs.start); its Continued from / Continued in banners are its conversation.threadHeader / threadEnd slots, behind its own Handoffs switch. The core knows none of it — runs/handoff.py, POST /api/handoff, SpawnBody.handoffFrom, meta.handoffFrom / handoffTo, handoff*Conversation and Handoff.tsx are gone; carryover.handoffs moved the old stamps into the plugin's key once. The platform points are generic (docs/plugins.md → "Menu items, thread places and conversation data"). Its CLI / MCP surface is its manifest's commands (docs/plugins.md → "Commands"): ai-agent plugin handoff start ID --model M [--mode warm|cold], link FROM TO, links ID, models; MCP plugin_handoff_start / _link / _links. ai-agent new --handoff-from and MCP start_conversation.handoff_from are gone.
    • new - reads the prompt from stdin (a brief outgrows a command line).
  • new --test (MCP start_conversation test): a throwaway run started to try something out — stamped meta.test and archived once its turn ends, whatever the outcome (see "Auto-archive" below); wait / show still read it. A nested claude -p run from a session's scratchpad needs no flag: its temp-dir cwd is the tell.
  • worktrees (cli/worktrees.py, stdlib, runs git on the host — the container only mounts ~/worktrees read-only) is what "clean old worktrees" is answered with. ls prints each one under ~/worktrees (WORKTREES_ROOT): branch, idle days (its own reflog / HEAD commit time — read before any git status, which touches the index), merged or +N commits ahead of main (local or origin/), uncommitted paths (gitignored ones like the hardlinked node_modules don't count), and the conversations that recorded it (GET /api/conversation-meta → worktrees[].dir, their live state from ?sessions=), then stale or keep: why. Stale = merged, clean, no running conversation, idle ≥ --days (default 3); --unmerged-days N adds unmerged ones idle that long (their branch survives). clean is a dry run until --yes; rm DIR… refuses a dirty / unmerged / running one (or the one the shell is in) without --force. Removing = git worktree remove + prune on the owning repo, git branch -d of a merged branch (never a remote one), and a removedAt stamp on every conversation that recorded it (POST /api/conversation-meta {worktree}), so their pills strike it through.

The hub as an MCP server (backend/mcpserver/, Settings → AI apps)

The ai-agent CLI's commands are also MCP tools an AI app plugs in as a custom connector: Claude.ai (and its phone/desktop apps), ChatGPT, Le Chat, Cursor, VS Code… at https://ai-agent.gabvdl.xyz/mcp (internet-facing: those apps call it from their own clouds). Design + flow: docs/mcp.md.

  • One tool layer: cli/mcp_tools.py (stdlib, built on ai_agent.Hub and its helpers) + cli/mcp_server.py (the JSON-RPC dispatcher). The backend loads them from cli/ (mcpserver/tools.py, cli/ appended to sys.path) and runs each tool against its own API over loopback — the owner to the gate — so a tool is exactly the CLI command it mirrors. Tools sit in groups (read · run · agents, Settings → AI apps switches them — the schedule group went with its tools on 2026-11-28, Send later is the scheduled-conversations plugin's plugin_scheduled-conversations_*); live plugins add plugin_<id>_<command> tools — the commands their plugin.json marks "mcp": true, listed from GET /api/plugins/commands as the connection's caller (mcp_tools.plugin_tools; none on a worker-bound connection); a read-scoped connection gets only the readOnlyHint tools and a hub that refuses non-GET calls. A wait is capped (maxWaitS, 50 s — clients give a call ~60 s); the result tells the model to call wait_for_conversation again.
  • Transport: POST /mcp, Streamable HTTP, stateless (no Mcp-Session-Id; a deploy strands nothing), JSON responses, tools only. GET/DELETE /mcp → 405. Tool calls run on a pool of their own (8), off the event loop and anyio's limiter.
  • OAuth 2.1 (mcpserver/routes.py, store.py → /data/mcp.json, every secret sha256-hashed): RFC 9728/8414 metadata built from MCP_PUBLIC_URL (never the Host header), open dynamic registration (≤ 200 apps, unapproved ones pruned after a day; redirect URIs https, loopback http or an app scheme), /oauth/authorize (PKCE S256 required, redirect URI exact) parks the request (≤ 3 per address, 20 at once) and sends the browser to the PWA's /connect/<id> (outside the shell, like /login). Codes 5 min, single use; access 1 h; refresh 90 days, rolled on every use (the old one lives 60 s). A 401 invalid_client from /oauth/token makes Claude.ai register again.
  • Who approves: the owner on the admin host (/connect/<id> → POST /api/mcp/pending/<id>, OwnerDep + same-origin) or by a push (Approve on my phone on the public page, the access picked there first → number matching: the page shows a two-digit number, the notify-ask offers three, only that one approves and any other answer closes the request; 2 pushes per address and 6 overall per 10 min, 20 a day; the page polls and redirects) — never by anything on the guest host itself. Before 2026-11-15 the push had Allow / Read only / Deny and whoever had parked the request collected the code: an unsolicited push, one tap, an owner token (docs/security.md → "Second pass"). Approving and collecting is one step (store.decide), so a poller holding the request id never sees a code another browser's approval minted. Redirect URIs must survive a parse round trip (no backslash, userinfo, upper case). A guest the owner switched AI apps on for (users.json mcp, Settings → Users → Access) approves for themselves, signed in on the guest host. An unknown redirect host gets a warning on the page and in the push. Every approval logs mcp_connected (pushable), every revoke mcp_revoked.
  • A guest's connection is them: /mcp resolves the grant's user (mcpserver/caller.py — gone, disabled, locked or switched off ⇒ 403 at once) and the tools' loopback calls carry X-AIA-MCP-User, a downgrade the gate (core/auth.py) honours from a trusted peer only, to the cli scope — the same reach as their ai-agent CLI. Their tools are the guest_ok ones (no schedule/agents/past/plans), browse only projects / models / budget, and their links open the guest host.
  • A connection bound to a worker (since 2026-11-18 — Claude Code on the Orus MacBook, in place of the CLI through the outbox): Settings → AI apps → the connection → Acts as sets grant.worker (owner connections only, one of his workers; logged mcp_bound). Its loopback calls carry X-AIA-As-Worker + X-AIA-As-Worker-Mode (run for a full connection, read otherwise) and the gate answers them as workers/bound.py worker_caller: the owner narrowed to that worker's profile, its routes, runs on that machine only. Its tools are WORKER_TOOLS (conversations, wait, past, schedule, browse of scheduled / models / workers / usage / budget). Setup on the Mac and the why: docs/mcp.md → "On a worker".
  • What it leaves: a conversation an app started carries meta.via = {kind: "mcp", app, connection} → the via Claude.ai pill (ViaBadge, visibility switch viaApp) on cards and the header. Settings → AI apps (/settings/ai-apps, business/aiApps/) is the owner's every connection (rename-free; read-only switch, Acts as, Disconnect), the requests waiting, the tool groups; a guest's same page shows the URL, the how-to and their own connections (/api/me/ai-apps).
  • Routing: the homelab's ai-agent-mcp router (services/ai-agent/traefik.yml) serves /mcp, /oauth/* and the OAuth .well-known files on the guest host without the browser chain (no compress, its own per-IP limit). The PWA's service worker must not answer those navigations (navigateFallbackDenylist).
  • No stdio transport and no personal tokens: Gabriel's call (2026-11-03) — every app goes through OAuth and an approval.

The lab browser — Claude in Chrome (the lab-chrome plugin)

A run can drive a real Chrome with Claude Code's Claude in Chrome tools (mcp__claude-in-chrome__*). The composer's Chrome chip (or chrome: true on /api/spawn / /api/resume, the chrome skill tag — its trigger words light the chip up) makes the sidecar launch the run with --chrome (harness-claude's sidecar/claude_launch.py _claude_args); it is stamped as meta.chrome so a continue keeps it (never through the inbox — a flag, like the model). On the first browser call Claude Code pairs, through Anthropic's bridge (wss://bridge.claudeusercontent.com), with the Chrome whose extension is signed into the same claude.ai account the run bills — nothing is shared between the run's machine and the browser's:

  • a lab run gets the homelab's own browser: services/chrome (a windowed Google Chrome in a container, Xvnc + noVNC, persistent profile, extension force-installed by policy). Everything around it is the lab-chrome live plugin (~/projects/ai-agent-plugins/plugins/lab-chrome, since 2026-11-26 — the core's backend/chrome/, business/chrome/'s dock and page, /api/chrome*, the SSE chrome event, the lab.integrations permission and the @novnc/novnc dependency are gone):

    • the conversation's pill (a conversation.gizmos slot: a thumbnail and who drives it, on a --chrome lab run) opens the live view (an app.modal slot, size: "full"): noVNC — vendored in the plugin — over aiAgentPlugin.openSocket("vnc"), which the host relays to the container's websockify (plugins/sockets.py, owner only). Read-only while Claude drives; Take over flips viewOnly, Hand back releases;
    • on demand: before a lab claude run launches with --chrome, runs/service.py asks the chrome.lab provider to bring it up (plugins/chrome_bridge.ensure: the plugin starts the container through the host sidecar's /chrome routes — sidecar/routes_chrome.py, its own proxy, the sidecar_token hub secret — and waits for noVNC); its every-minute idle job stops it once no --chrome lab run is live and no live view has moved for Stop it after minutes (keep: "always" never);
    • Settings → Plugins → Lab Chrome (/settings/browser redirects there): the chip's default (the composer reads it through the provider's {op: "status"}), Guests' runs may use it (runs/routes.py _guest_chrome asks chrome_bridge.guests_allowed), the container's state and actions. carryover.chrome moved /data/chrome.json into the plugin's config.

    No plugin: the chip still launches --chrome (the harness capability), but nothing starts the lab Chrome, no guest keeps --chrome, and there is no live view.

  • a worker run gets that Mac's own Chrome (the profile whose extension is signed in); nothing to show on the lab side. An API-key session can't use it at all (the CLI needs a claude.ai OAuth login).

The rules a run follows with the shared browser (own tab group, never type a password, notify-ask and wait on a login / 2FA / captcha, re-observe after Hand back) are the homelab's chrome skill (.claude/skills/chrome/, portable to workers).

The runner: same sidecar, two places it can run

sidecar/sidecar.py is the only thing that launches claude -p. It runs in one of two places, and the backend doesn't know the difference — it just POSTs to SIDECAR_URL:

  • On the homelab host (the default, below): a run then has the host user's own auth, hooks, skills and CLAUDE.md — i.e. it is exactly a session started from a terminal. This is why the homelab keeps it.
  • Inside the container (RUNNER_IN_CONTAINER=1, the standalone default): the image bakes in the Claude Code CLI (a self-contained native binary — see the Dockerfile) and docker-entrypoint.sh starts the same sidecar module on 127.0.0.1:8790, mints a SIDECAR_TOKEN if none was given, and overrides SIDECAR_URL to point at it. The CLI's $HOME is RUNNER_HOME (/data/home, on the data volume), so its config, credentials and the transcripts it writes survive a restart; RUNNER_TRANSCRIPTS_DIR (defaulted from it) is added to the backend's live SOURCE_DIRS, which is what makes an in-container session stream into the viewer like any other. Auth is ANTHROPIC_API_KEY, or an already-logged-in Claude home mounted at RUNNER_HOME (-v ~/.claude:/data/home/.claude). Remote control is off by default there (it needs an interactive login).

That's GOAL.md's "single Docker container": a standalone image spawns sessions with no host process. Keep it that way — a new runner feature belongs in sidecar.py, not in a host script.

The host sidecar (what the homelab runs)

sidecar/sidecar.py runs natively on the host as the repo owner and the backend proxies to it over host.docker.internal:8790 (Bearer SIDECAR_TOKEN):

  • POST /api/spawn → sidecar /spawn: claude -p <prompt> --session-id <uuid> --model <model> --remote-control (detached). Transcript lands in the watched projects dir and the new conversation shows up in the viewer within ~2s.
  • POST /api/resume / POST /api/interrupt → continue / SIGINT an existing run.

model is the claude --model argument the composer's model tag carries — a family alias (opus) for a family's newest model, or a pinned id (claude-opus-4-5-20251101) for an older one. Unset on spawn ⇒ SIDECAR_MODEL (default opus); unset on resume ⇒ no --model flag, so the session keeps its own. The sidecar only shape-checks the value (it goes on a command line) — the pickable set is whatever /api/models returned.

Code Mode runs (beta): an interactive claude on a pty (sidecar/ptyrun.py)

Claude Code's Code Mode (CLAUDE_CODE_EXPERIMENTAL_CODE_MODE=1, CLI ≥ 2.1.323, Opus / Sonnet / Haiku 5.5, Fable 5.2: the model writes JavaScript its REPL tool runs; the thread folds each script into a Ran code card) only starts in an interactive session — claude -p silently runs without it, and can't resume a session started in it at all ("can't be resumed here") — and only with CLAUDE_CODE_ENTRYPOINT=cli (ours, ai-agent-sidecar, reads as a background job). Analysis and tests: homelab data/log/2026-11-18-code-mode-analysis.md.

  • Launch (harness-claude's claude_launch.py "Code Mode"): /spawn codeMode: true, and any /resume or /fork of a session whose transcript carries {"type":"repl-mode","replMode":true} (is_code_mode_session — also a terminal session started in it), builds the usual argv and code_mode_args turns it interactive: no -p / --output-format / --chrome / --remote-control, the prompt last behind --, wrapped in python3 -I ptyrun.py --sid … --state LOG_DIR -- claude …; env + the two variables above. A fresh compaction is dropped (-p /compact can't open the session; the reply box doesn't offer it). The Bash diff hooks get onFailure: continue (Code Mode refuses a call whose PreToolUse hook fails); the guard keeps deciding itself.
  • The wrapper (ptyrun.py, stdlib, Linux + macOS): pty.fork at 200 × 50; answers the folder-trust, Code Mode consent (each login asks once — accepting restarts the CLI as versions/<v>, a child on the same pty, prompt kept), bypass-permissions and first-run dialogs by moving the highlight (❯) to the option, then Enter; declines an unknown dialog after 20 s. Reads the banner into <sid>.codemode.json ({on, reason} — /spawn waits ≤ 4 s for it, /sessions reports it). Ends the session when its turn is over: stop_guard.py (every run's Stop hook; --mark-only when the guard is off) writes <sid>.turnend with the still-running background_tasks when it lets a stop through in a run with AIA_PTYRUN=1; none left and the CLI's registry (sessions/*.json, found by session id) idle ⇒ it types /exit. So a Code Mode run lives exactly as long as a -p one — running state, Stop, the exit watcher, the inbox (/message works into it) are unchanged. SIGINT/TERM/HUP: Esc, /exit, then SIGTERM/SIGKILL inside STOP_WAIT_S. Its log: the first 64 KB of the screen (ANSI stripped), [code-mode] lines, the last screen.
  • Where it can't: a run billed through the hub's Claude proxy (the CLI refuses Code Mode behind a custom ANTHROPIC_BASE_URL: a proxied worker — the personal Mac by default — and every guest computer) or an older CLI. A new run then goes as a normal -p one and the answer says why (codeMode: {on: false, reason}); a Code Mode session there is a 409 code_mode_unavailable. /health codeMode = {ok, cli, reason}.
  • Hub (runs/codemode.py, runs/service.py): GET /api/code-mode — per runner (the lab's /health, each worker's — claudeMode: proxy can't) and whether the caller may (a guest's Access switch, users codeMode, on by default). The spawn sends codeMode and drops Chrome; the banner's answer is stamped meta.codeMode (true / false + codeModeOff = why) at launch or, when it hadn't shown, by the exit watcher from /sessions (code_mode_seen). The card's codeMode is that or the transcript's (summary.codeMode, PARSER_VERSION 44).
  • UI: the composer's Code β chip (CodeModeToggle.tsx, rules in lib/codeMode.ts), off by default and per conversation, greyed with the reason; it and the Chrome chip turn each other off. The reply box: a CODE · BETA badge, only Code Mode models, no fresh context. The thread: Code Mode didn't start: … (CodeModeOffNotice, switch codeModeNotice).
  • Not yet: Send later doesn't carry the chip; lean (cron) runs never use it.

Background work in a headless run (stop guard, wait ceiling, inbox)

A claude -p process ends when the model ends its turn — and the model routinely ends it with "I'll pick this up when the build / subagent reports back". What happens to that background work then (measured on CLI 2.1.280, harness-claude's sidecar/stop_guard.py has the details):

background task the CLI on exit the sidecar's answer
Bash run_in_background (shell) killed at once — local_bash tasks are excluded from the exit wait stop_guard.py, a Stop hook injected via --settings on every run (spawn / resume / fork): while a running plain shell is left, it holds the stop — polling, no API call, until the task has ended: the CLI's end marker in tasks/<id>.output ([exited with code N], or [killed] when the CLI stopped it — its background time limit, TaskStop, memory pressure) or the CLI's queued <task-notification> for it (a queue-operation record in the transcript, read incrementally) — then returns block with how each task ended and where its output is. The first end releases the hold (since 2026-11-25): one held shell ending, or any other task's notice queued meanwhile (a subagent, a Monitor), hands that over with what is still running, and the model's next turn-end re-arms the guard for the rest — holding until every shell had ended kept a finished result from the model until the last one did: 67 results in a month waited over a minute, 988 min in all, up to the whole budget (scripts/step-lag.py). (Until 2026-11-06 only [exited with code N] counted, so a killed shell held the turn the whole 55 min — 42 times since Oct 10, e.g. a deploy wait loop that hit its time limit.) While it holds, <sid>.hold is reported as held on /sessions, and the hub keeps the live run running — meta.held {since, tasks}, the card's Waiting on a background shell · N min chip — instead of letting the recency window flip it to finished. Monitors are excluded (the CLI waits for those). Budget STOP_GUARD_MAX_WAIT_S (55 min) per hold, then the model is told what's still running and asked to TaskStop it or end its turn again. Hook timeout SIDECAR_STOP_GUARD_TIMEOUT_S (3600); SIDECAR_STOP_GUARD=0 disables. Its lines: sidecar/logs/<sid>.guard.log (hook stderr never reaches the run log); the hold renders as a compact held tag (kind: "held").
background subagent, Monitor waited for, but only CLAUDE_CODE_PRINT_BG_WAIT_CEILING_MS (CLI default 600000 = 10 min — "Background tasks still running after 600s; terminating" in the run log) exported into every run from SIDECAR_BG_WAIT_CEILING_MS (default 7200000, 2 h; 0 = indefinitely, "" = the CLI default)

This is what made a conversation "stuck": the run had exited, nothing could report, and the next --resume opened with a didn't finish before the previous session ended notification. 44 such events in 26 conversations (Sep–Oct 2026), every one a clean exit.

Follow-ups into a live run (/message). Now that runs legitimately stay alive for an hour, a "Up?" must not kill them. _send_message first POSTs the prompt to the sidecar's /message, which writes it into the run's cross-session inbox socket (the CLI's <config dir>/sessions/<pid>.json → messagingSocketPath; runs are launched with crossSessionInbound: accept in the same --settings). The model reads it between tool calls, or at once when idle-waiting, and the background work survives. The CLI records it as a peer message ("Another Claude session sent a message … not typed by your user"), so the sidecar prefixes the text (INBOX_PREFIX) and conversations._unwrap_inbox shows the plain user turn. A busy run absorbs it mid-turn instead (queue-operation remove, reason: absorbed_mid_turn) and writes no user record — only an attachment of type queued_command (origin.kind: "peer", the raw prefixed prompt) — so the parser turns that attachment into the user turn (_absorbed_followup); before that, most follow-ups vanished from the viewer while the model answered them ("Noted: …"). The composer's echo (its outbox entry — see "The reply box is its conversation's") knows the delivery (/api/resume → delivered: "inbox" | "hold") and stays, queued, until a user turn lands — not just the next tool card — and goes stale only if the run ends without reading it. Until then the transcript's open queue-operation enqueue makes it the conversation's queued, on every device. The model reads it only between two steps: one long response (a 56 KB Write streams for minutes) keeps it — and any finished task's notice — queued, so the detail's stepSince (the streaming step's api-request time) lets the echo say Claude is mid-response · 2m 3s, and Stop & send now warns that the response is lost. A run stopped that way loses the task notices the CLI had queued; the sidecar's /resume appends <ai-agent-tasks-done> for each (sidecar/undelivered.py), and the parser marks those cards read (taskUnreadAt → taskReadAt). Only a 404 (nothing live ⇒ plain resume) or a 409 inbox_unavailable (a pi run, an older CLI ⇒ the old stop-then---resume) falls back. A model / thinking / effort switch does not apply through the inbox; the Stop button then a resume does.

Stop & send now. The queued echo (OutboxEchoRow) has a Stop & send now footer button: it resends what the reply box sent (the outbox entry's composed prompt + options, to the entry's own session) with /api/resume now: true, which makes _send_message(restart=True) skip the inbox and go straight to the force-resume (stop the run, --resume on the turn). When the run has live background work (liveBackgroundWork: background shells, watching Monitors, running subagents) it confirms inline first, listing what dies. The sidecar's _stop_run also drops the run's hold mailbox (<sid>.hold, <sid>.inbox/), so a message left for a Stop-guard hold is never relayed twice.

One more hole the tests found: the socket accepts and drops a message while the session sits in a Stop hook — i.e. exactly during a guard hold. So the hook writes logs/<sid>.hold for the hold's duration, /message checks it first and, when present, leaves the text in logs/<sid>.inbox/ (delivered: "hold"); the hook polls that mailbox every poll, ends the hold at once and relays the text in its block reason between <<<USER MESSAGE>>> / <<<END USER MESSAGE>>> fences (conversations._relayed_message shows it as the user's turn), telling the model what is still running and to end its turn again afterwards so the hold resumes.

Background shells: moved to the background-shells live plugin (since 2026-11-27)

The Details drawer's Background shells card, the header's amber N shells running chip (now a conversation.header slot beside the Performance chips, calling aiAgentPlugin.openDetails("conv-shells")), and the thread's background-work tool cards (Monitor, ScheduleWakeup, TaskOutput, TaskStop, and the background Bash state strip) live in the background-shells live plugin (~/projects/ai-agent-plugins/plugins/background-shells, seed: true, managed.defaultForGuests: true).

Core keeps the transcript parser (conversations/taskevents.py), ConvMeta.taskStops, liveBackgroundWork (business/conversations/liveWork.ts, for the Stop & send now confirm), and the hub bridge plugins/hubtasks.py (conversations.tasks capability):

  • GET …/hub/conversations/{cid}/tasks — lists every run_in_background shell and claude:Monitor of the conversation, with its state, events, unread/read stamps, meta.taskStops, and canStop;
  • GET …/hub/conversations/{cid}/tasks/{task_id}/output?lines=20 → runner POST /tasks/output (harness-claude's sidecar/bgtasks.py);
  • POST …/hub/conversations/{cid}/tasks/{task_id}/stop (handler-only; checks ensure_runs_here + can_send(stop=True)) → runner POST /tasks/stop, stamps meta.taskStops, publishes SSE meta.

Core's runs/bgtasks.py (/api/conversation-task-output / /api/conversation-task-stop), BackgroundShellsCard.tsx, BackgroundToolWidgets.tsx, mock/bgtasks.ts, and the bgShellsCard / bgShellsChip / bgWidgets switches are retired (replaced by the plugin's own vis switches and DETAIL_CARD_RENAMES.backgroundShells).

What a Bash call changed: the Bash diff hook (sidecar/bash_diff.py)

Bash is how these sessions mostly edit files — 23 % of 46.8k Bash calls in 60 days wrote files (python heredocs, cat > f <<EOF, sed -i…) against 3.4k Edit/Write calls — and a Bash result carries no diff. So every run (spawn / resume / fork, lab and Mac workers alike — not terminal claude sessions) gets a PreToolUse + PostToolUse hook pair on Bash through --settings, like the Stop guard:

  • pre snapshots the repo the command runs in — its leading cd target, else the session cwd, plus any later cd target and any absolute path it names (a heredoc's open('/home/…') included) — and post snapshots it again and diffs the two trees. Not the session cwd when the command cds elsewhere: the lab's sessions sit in ~/homelab and work in a worktree, and diffing ~/homelab too would credit the call with other agents' edits (exactly what Claude Code's own bashEditDiff does).
  • A snapshot is git add + write-tree through a private index (a copy of the repo's, kept per session so its stat cache stays warm) and a private object store with the repo's objects as an alternate: nothing is written into the repo's .git. Both live in ~/.cache/ai-agent/bash-diff/<sid>/, swept after 3 days. Untracked files over 2 MB are never hashed. Cost: ~80 ms before + ~80 ms after a writing command on ~/homelab; read-only commands (ls, grep, cat, git status/log/diff… — read_only()) and background calls skip both and cost ~35 ms of interpreter start, in parallel with rtk's.
  • post prints {"bashDiff": {…}} — stats per file + the unified patch, capped at 48 KB per call (BASH_DIFF_MAX_PATCH_BYTES; past it files keep their +/− but lose their hunks; lockfiles / minified files never carry hunks). Claude Code keeps a hook's stdout in the transcript as a hook_success attachment keyed by toolUseID and never adds it to the model's context (verified: identical token counts; no output = no record), so the diff costs no tokens and travels with the transcript — archive, a worker's feed, subagent transcripts.
  • A call that overlapped another one in the same repo (any session's pending pre snapshot) is flagged shared — the card says concurrent. A scoped (guest) run's hooks get --within <writeDir>: only repos under its write dirs are diffed, so naming a lab path can't pull other agents' edits into a guest's transcript. SIDECAR_BASH_DIFF=0 turns it all off.
  • Commits are not this hook's any more (2026-11-27): until then post also printed {"gitCommits": {…}} (the commits a call created, their patches, the refs a push moved). Capture is the commits plugin's now — a git path shim on every harness (see "Reviewing a conversation's commits"). Older transcripts' gitCommits are still read by conversations/commits.py.
  • Hub side: conversations/bashdiff.py turns the attachment into the Bash item's bashDiff (FileDiffs, the /diff page's model); without one it falls back to Claude Code's own toolUseResult.bashEditDiff (v2.1.278+: fires on ~2 % of calls, session cwd only, ≤ 5 files with hunks, never in subagents) unless that's shared — flagged built-in, the only record older conversations have. The hook's files (never the built-in's) also count as edits for the project/service auto-tags and for editsdiff's replay of a torn-down worktree (hunks applied onto a known content, verbatim otherwise). The card (BashDiffBox) shows N files +A −D on the row; opened, the diff is the card — file chips + a scrollable DiffCode — and the command + its output only come back with the Command behind a diff switch (off by default) or when the call failed. A tool group's row sums what its calls changed (groupEditStat): distinct files by absolute path across Edit / Write / MultiEdit / patches and Bash diffs (bashDiff.paths), lines summed, failed edit tools left out. Switch: Bash diffs. Every Bash card dropped the repeated description (the row's tooltip has it) and the cwd: line (the command's tooltip).

Split view: up to three conversations side by side

The /conversation/* route is pages/ConversationPage.tsx; each conversation on it is a ConversationPane (pages/Conversation.tsx, the old page, now taking id + a PaneCtl). Gabriel's picks (2026-11-19, form split-view-decisions):

  • URL: /conversation/<left>?with=<second>,<third> — reload, Back and a shared link keep the split; business/conversations/split.ts reads and writes it (splitIds, splitPath, withPane, movePane, replacePane, useSplitNav().go). MAX_PANES = 3.
  • Opening one: the left list's card menu → Open in split screen (desktop, on a conversation page), or drag a list card onto a pane — left or right half = before / after it; with three open, the pane under it is replaced. A plain click in the list while split replaces the focused pane (the one last clicked or typed in — useSplitFocus, per tab; an accent line on its header). A modified click keeps the browser's meaning.
  • Each pane has the full thread, its own composer and a compact header (components/PaneHeader.tsx, lazy): grip (drag to reorder), title, Thread / Changes, Summary / Full, Share, ⋯ (Move left / right, Open alone, the notifications bell via useFollowToggle, Browser) and × close. No visibility popover and no Details drawer while ≥ 2 are open — closing back to one gives the page its drawer as it was (usePanel("info") is untouched). Labels drop under 560 px of pane width (data-compact → group-data-[compact]/pane: on the shared switches).
  • Per-pane state: a plugin tab (Changes) lives in usePaneViews (not ?view=) while split, carried into / out of the URL when the split starts / ends; swapView channels are per pane (summary:<index>, changes:<index>) so a toggle never slides the neighbour; ?m= deep links and the ?form= modal belong to the single page / the left pane; only the focused pane remembers itself per profile (useRememberOpenConversation), so two panes of two profiles don't flip the scope.
  • SSE: lib/openConversation.ts holds every on-screen id (ref-counted), and the bus refetches each of them first.
  • Panes keep their DOM node: a pane's React key is a slot (useSlotKeys) — a pane that switches conversation is the same component, as the single page always was — and the panes are laid out with CSS order in a stable DOM order, since moving a node resets its thread's scroll.
  • Phone: no side by side — the focused pane with its full header, and a tab strip of the open ones above it.

Reviewing a conversation's commits (the commits / diff-viewer plugins)

What a conversation committed is recorded, not guessed (the old way — a git log --since/--until window over its repos — attributed every sibling agent's merge to it, and found nothing at all for a worker's conversation, whose repos aren't the lab's):

  • Capture (since 2026-11-27): the commits plugin's git path shim (manifest pathShims[], plugins/path_shims.py, operator approval, delivered with the harness hooks — live-hooks/index.json shims, a worker's /sync hooks.shims). sidecar/path_shims.py, called by launch._launch for every harness, writes a POSIX-sh wrapper per shim (~/.cache/ai-agent/shims/bin[-guest]/git) first on the run's PATH: an argument equal to a trigger word (commit, merge, push…) → python -I the plugin's script (env AIA_SHIM_REAL, AIA_SHIM_PLUGIN, AIA_SESSION_ID, AIA_REPORT_PY), else exec the real git — read-only git never starts a python. The script reports out of band with core's sidecar/aia_report.py (report(event, summary ≤ 8 KB, blob ≤ 160 KB)): on the lab POST /api/plugin-reports (the run's AIA_REPORT_TOKEN, an HMAC of its session id under SIDECAR_TOKEN), on a worker a one-shot report outbox item (rpt_); a failed send spools (AIA_REPORT_SPOOL), drained by the sidecar every 20 s. The hub stores them per conversation and plugin (plugins/reports.py, /data/plugin-reports/<sid>/<pid>.jsonl + blobs; 2 000 reports / 16 MB), publishes SSE transcript, and /api/conversation joins each report's summary onto the shell item whose run window holds its ts (ThreadItem.reports[<pid>], re-sent in delta threadPatches). The plugin reads them back with conversations.reports.
  • Parser (conversations/commits.py → summary commitsAuto, thread item commits): the Bash hook's gitCommits (exact, patch included — older transcripts, kept), else git's own [branch sha] subject line in a Bash result (terminal sessions, older transcripts; rtk rewrites git commit on the lab, so there it rarely fires) — plus a lone sha subject when the command committed then ran a one-commit git log. Pushes mark commits pushed (a merge's second parent carries its branch). commitCalls counts the Bash calls that could commit.
  • API (diff/convcommits.py): /api/conversation-commits lists them (newest first, exact, worker); a lab conversation with none recorded but commitCalls > 0 falls back to the time window (exact: false, labelled in the UI); a worker one never does. /api/conversation-commit-diff?id&sha reads one commit from the lab's git (its root → a repo token: a project, a worktree of one, the homelab checkout), else the transcript's patch, else the worker's sidecar POST /git/commit (sidecar/routes_git.py, read-only git in a checkout under the worker's ~ holding the sha — a torn-down worktree resolves through its main checkout), cached for good in /data/commit-cache/<worker>/. A sleeping Mac answers 503 worker_offline (the transcript's partial patch is returned instead when there is one). A root (/api/conversation-commit-diff?…&root=, and the diff.read bridge's) names the repo of a commit only a shim report knows — read from the lab repo at that root or the conversation's worker (a guest: their project / their own computer only). The plugins reach all of this through the diff.read bridges (plugins/hubdiff.py, the very route functions as the caller — a guest held exactly as _viewed_by / _repo_allowed hold them). /api/conversation-diff is the net diff per run of consecutive commits (same repo + branch, each one's first parent the previous) — merges left out, so nothing landing in between leaks in; a worker's runs go through POST /git/range.
  • Uncommitted replay (editsdiff): a Bash call that moved HEAD (its gitCommits, or a git merge|pull|rebase|… command in older transcripts) rewrote files that are history — no longer counted as uncommitted edits (that was the "Uncommitted changes" row lingering after every merge).
  • Frontend: plugins, not core (2026-11-27). The commit cards, the Changes tab, the Details Commits card and every diff view are the commits and diff-viewer plugins' (ai-agent-plugins); core's frontend has no diff code but components/DiffCode.tsx (a Bash card's changed files) and components/Diff.tsx (Edit cards). What core gives them (docs/plugins.md, contract A1/A2/A5):
    • conversation.tab slots (plugins/components/ConversationPluginTabs.tsx, plugins/tabs.ts): the header's Thread | switch, same place and swapView slide as the old Thread | Changes. Each tab's frame is mounted hidden once the thread painted and never reloads (init frozen); its button shows after aiAgentPlugin.setTab({hidden: false, badge, label}). Address ?view=<pid>:<slot>&tp=<JSON params>; a slot's legacyView: "changes" answers the old ?view=changes&c=. Active, it fills the pane; split panes keep {view, tp} in usePaneViews. Bridges for any frame on the page: openTab({plugin?, slot, params?}), closeTab(), reply({text, send?}) (→ replyRequests.ts → this conversation's ResumeBox: appended, focused, sent when asked).
    • Stacked in-chat cards: a stackable card's consecutive calls are one frame (PluginToolCardStack: init.stack, update.stack; groupThread's joinable returns the stack key); pullOut keeps it out of the Summary folds (summarizeThread's pullOut, the old CommitStack placement) and standing when the tool switches hide calls. A card's init/update carry commits and its own reports (ThreadItem.reports[<pid>], match.hasReport).
    • Links by kind: plugins/opener.ts pluginOpenHref / usePluginOpener from ui.pages[].opens (Project / Service Recent commits → commit; no page: a plain row). /diff/* redirects (LegacyDiffRedirect). The old Details card id commits → plugin:commits:conv-commits.

Model tags

Models are a first-class tag on both sides of the app (frontend/src/lib/models.tsx): picking one in a composer (a mutually-exclusive chip per model — RichInput's exclusive key, added in @gabvdl/ui ≥0.11) runs that session on it and the toolbar echoes the choice; the pick is sticky per profile, server-side (spawnByProfile in Settings, business/composer/spawnPrefs.ts: model, thinking and each harness's effort; a profile that never picked falls back to the shared spawnModel / spawnThinking / spawn*Effort). Runner and account pins, the Chrome and Code β chips stay per send. Reading back, a conversation is tagged with every model that actually produced a turn — conversations/parse/state.py collects them (models, busiest first; a session can switch mid-thread), so past conversations are tagged too (bump PARSER_VERSION: the indexer's upgrade pass back-fills a new summary field on every past row in the background). Subagent models are appended after the thread's own (_with_child_models in conversations/tree.py), so models[0] stays the main thread's busiest.

Switching mid-thread. model is the first model a thread ran on; the one it is on now is contextModel (the last turn's) — that is what the resume composer, header and fork menu seed from. A switch is sticky (an untouched resume sends no --model and the CLI keeps the session's last one). Sending a switch goes through a confirm (lib/modelSwitch.ts → useConfirm, which needs the ModalProvider in root.tsx): a new model re-reads the whole context uncached (priced as a cache write on it), and claude ⇄ pi starts blank — the two harnesses keep separate session stores. The thread draws a "switched a → b" divider above the message whose answer came from a new model.

Settings → Models: the model decides the harness (since 2026-11-22)

The composer has no harness select: one Model chip (ModelPicker, lib/models.tsx) lists every model — the owner's ★ favorites first, then vendor by vendor (Anthropic, Google, OpenAI, EVOX2 · local, OpenRouter + the Browse OpenRouter… row) — and the picked model's preset decides the harness. The owner's picker ends on Manage models… → /settings/models.

  • Keys (backend/models/presets.py key_of, mirrored by lib/modelCatalog.ts): /api/models still lists (model, harness) pairs, each tagged key + vendor (+ fastMode). A Claude model's key is its family (opus, stable across releases — the word guests' lists always held); an opencode EVOX2 twin's is the pi id (ggml-org/qwen3.8-27b, inkling-2-mini — catalog.local_twin_base); a GPT tier's is its base id (gpt-6-sol); else the id. catalogModels() folds the pairs into one CatalogModel per key, whose entry is the pair its preset launches; routeOf(key) → {harness, model}. Sticky spawnModel holds a key now (an old alias / id still resolves through keyForArg).
  • Presets (/data/model-presets.json, MODEL_PRESETS_PATH; PATCH /api/model-presets {key, patch}, owner, SSE model-presets): harness (one that lists it), effort, thinking (pi), fast (GPT tier), favorite, guests. Unset ⇒ defaults(): claude › pi › agy › opencode, i.e. today's routing; guests: opus / sonnet / haiku. /api/models returns them resolved as presets (a guest's without guests). A pick seeds the composer's effort / thinking chip from the preset; the chip still changes it per run. The page (business/models/pages/Models.tsx) is ItemCards per vendor, ★ in the header (ItemCard.trailing), the preset in the body; OpenRouter's models aren't on it (the browser is their catalogue).
  • The guest pool = keys with guests on. Switching one on adds it to every guest's models list (Settings → Users unticks it per guest — the chips there are the pool, out-of-pool leftovers struck through); off gates it for all. users/runs.allowed_models = their list ∩ the pool; check_model takes a key, an id or a Claude family id. A guest's /api/models = every Claude entry (their own login may run any) + the pool ∩ their list, the preset harness's entry only.
  • A guest on another harness (users/runs.model_route → run_other_harness): their spawn / scratch / turn runs on the model's preset harness, on the lab, under the live-run cap and the month budget (no login of theirs). pi is confined: the sidecar's _runner_scope_args → the runner's --scoped (--no-skills --no-extensions --no-prompt-templates), the scope's system prompt as --append-system-prompt, reads narrowed by --read, writes in the cwd (folder-permissions), Bash off on noBash. agy: the scope's system prompt rides each prompt as <session-rules>, and the run drops --dangerously-skip-permissions for --settings with agy's own allow-rules (agy_cli.guest_settings, plain paths — /** breaks agy's shell sandbox): read_file / write_file / edit_file / list_dir in the cwd + writeDirs, reads of the readDirs and the CLAUDE.md files, command(*) unless noBash. Headless, agy auto-denies anything else and ends the turn (the rules tell the model so). Without it a guest's Gemini wrote outside its project when asked (gabtest test, 2026-11-22). The shell isn't path-confined — no more than a guest's claude Bash without GUEST_SANDBOX; --sandbox is useless headless (it errored and the model reran outside it). opencode and forks stay claude-only for guests; a guest's own computer runs claude only.
  • CLI: ai-agent new --model X without --harness takes the preset's harness (and GPT tier) of the model the words hit.

Services: the plugin's whole catalogue (since 2026-11-28)

The homelab services catalogue left the core (Gabriel's picks in form move-services-fully-to-plugin_j2oy8p): backend/services/ (index, the service.cards merge), schemas/services.py, /api/services + /api/service, the core /services and /services/:slug pages (Service.tsx, the Projects | Services tabs), ai-agent services and MCP browse services are gone. The services live plugin (~/projects/ ai-agent-plugins/plugins/services, 2.0) owns the list, the cards, the detail page (containers, Traefik routers, env keys, files, GOAL.md + Work, commits, linked conversations, memories, README / CLAUDE.md), and ai-agent plugin services ls|show / MCP plugin_services_ls|show. What the core keeps:

  • The plumbing — servicesdir.py: SERVICES_DIR, safe_entry, the bucketed git history. Used by services.read (AIA_SERVICES_DIR), the file chips (files/hostfiles.py), the artefacts strip, a goal-keeper's services/<dir> (goals/routes.py), the parser's servicesAuto and the diff view's service:<slug> token.
  • provides: {"services.index": …} read through plugins/services_bridge.py (30 s stale-while-revalidate): the Goals board's service goals, the Graph's service nodes and GET /api/plugins/services-index (owner) — the tag registry, the composer's service chips and ai-agent tags (the frontend asks only while usePluginProvides("services.index")). No plugin, no services anywhere.
  • Bridges for the plugin: hub/services/commits (services.read) and hub/conversations?service=<dir> (+ a services field on every row) — docs/plugins.md → "Host data and slots".
  • Navigation: ui.pages[].nav: "projects" puts its page at the top of the Projects panel and the Projects bottom-bar drawer; /projects is Projects only. service: pills are a plugin tag (tag: "service", subpath): tagHref resolves them through usePluginTagPages, a plain pill when the plugin is off — _CORE_TAG_KINDS is project alone.
  • Frames link without naming plugins: init.tagPages / init.openers and aiAgentPlugin.openTag(kind, slug) / aiAgentPlugin.open(kind, params) (docs/plugins.md → "Pages").

Context & skills: the context-skills plugin (since 2026-11-28)

The core's last dashboard — what the Claude context costs to load: six stat cards, the skills' usage table (calls, last use, context cost, estimated spend) and the most expensive files — left for the context-skills live plugin (~/projects/ai-agent-plugins/plugins/context-skills, nav: "dashboards", feature dash.overview; Gabriel's picks in form migrate-files-context-dashboard-to-plugins_imhucu: a standalone plugin, toggleable like activity). GET /api/dashboard, business/dashboards/pages/ Dashboard.tsx and useDashboard are gone. What the core keeps:

  • The bridge — plugins/hubcontextcost.py: GET …/plugins/{pid}/hub/ context-cost (contextcost.read, owner only, operator approval) answers the old /api/dashboard body, each skill with path (its SKILL.md when the file index has it). _context_by_skill stays in dashboards/routes.py, shared with /api/skills. A guest gets a 403.
  • /dashboards is a grid (business/dashboards/pages/DashboardsHome.tsx, the Files landing's twin): a card per active nav: "dashboards" (or tools / main) plugin page, hold-to-rearrange (listOrders["dashboards-home"]), an empty state pointing at Settings → Plugins → Available. The Dashboards panel (DashboardsPanel.tsx) heads its list with All dashboards and has no core page any more; dashboardPages.tsx is the one list both read, and its DASHBOARDS_RENAMED keeps a saved /dashboards slot for the plugin page.
  • The carry-over — plugins/carryover_context.py: the owner's saved stat-card order and bench (listOrders / listStashes["dashboard-stats"]) become the plugin's layout.json, once. The plugin's Arrange header button replaces hold-to-drag (drag on a desktop, arrows on a phone, − to bench).
  • The page's links go through openers (context-file for a file or a skill's SKILL.md, else the skill tag page): plain text when nothing claims them.
  • CLI / MCP: ai-agent plugin context-skills summary | skills | files.

Settings → Plugins: one catalog with categories (since 2026-11-28)

The page (business/plugins/pages/PluginsPage.tsx) is Orca's layout in the app's own look (form plugins-page-rework_rhce3j): a category sidebar with counts (a chip row under lg), search, All / Installed / Available and a sort (Installed first by default, Name, Recently updated — settings.pluginsSort), then cover cards or compact rows (pluginsView). Every plugin shows once: an install (or, for a guest, a managed plugin provided to them) opens its settings, a catalog entry its info and Install. The shelf is the manifest's category (backend/plugins/categories.py, strict: an app picks dev data agents chat scheduling media or other — the default —, a provider / harness / translation is under its kind's shelf), resolved on every row of GET /api/plugins (an older record reads its source's plugin.json). Labels and icons: business/plugins/categories.ts (keep in step). Addresses ?cat= / ?show=; the old ?tab= / ?kind= links still land (filtersOf). An empty shelf is hidden, so Translations appears with the first translation plugin. docs/plugins.md → "Categories and the Plugins page".

The public plugin catalog: a site and the plugin-catalog plugin (since 2026-11-28)

What isn't installed is browsed on ai-agent.plugins.gabvdl.xyz (a static site + catalog.json, built by the plugins repo's scripts/build-catalog.py from catalog/public.json only) and, in the app, on the seeded plugin-catalog plugin's Settings page (after Plugins; operator only): the same cards with Install / Update / Uninstall. A frame only asks (aiAgentPlugin.plugins.list|install|uninstall, the operator-only plugins.manage capability); the host checks the source is <PLUGIN_CATALOG_REPO>#plugins/<id>, shows what the hub validated and does the install itself, and asks keep-or-delete on every uninstall (business/plugins/catalogBridge.tsx, plugins/catalog_repo.py). The operator's Settings → Plugins drops Available for a Browse the catalog link (old ?show=available links redirect there); guests keep theirs. docs/plugins.md → "The public catalog and the plugin-catalog plugin".

The tag registry (Settings → Tags)

Tags are derived, never authored (frontend/src/lib/tags.ts): useTags() aggregates the projects on disk, the services the services plugin indexes (/api/plugins/services-index, only while it provides services.index), the stack + package.json keywords a project declares, the skills/agents catalogs, and every mention carried by a conversation, memory, plan or project-local skill into one list of <kind>:<slug> tags with per-source counts. Nothing creates, renames or deletes a tag — rename a directory and the tag follows; a tag that is referenced but has no directory is flagged exists: false rather than hidden, since that is usually a rename something still points at.

Two axes: where work happened (project/service/stack) and what it was done with (skill/agent). The tool axis is mined from the transcripts, not declared — a conversation card carries skillsUsed (the Skill(…) calls, its subagents' included, since a child transcript is never listed on its own) and agentsUsed (built in conversations.catalog._agents_by_conversation from the same run list the agents catalog counts, so a card can't disagree with the agent page: a subagent run keys to its parent conversation, a cron/manual agent session to the conversation it is). Population is "everything on disk + the built-ins that actually ran", straight off the two catalogs, so a built-in skill/agent is a tag with exists: false and no file to open. Those pills render on the conversation detail only (SkillTags/AgentTags in ConvMetaBits, capped at 5 with an expanding +N) — the list cards stay about location.

What a human does own is a tag's presentation: colour (a key into TAG_COLORS, lib/tagStyles.ts, or #rrggbb), icon (a glyph key — curated / lucide name, sh:<ref> selfh.st mono, svg:<id> an uploaded icon), description, auto-tag triggers (added words) and mutedTriggers (derived ones switched off), plus iconSource (where a real icon came from). Unset fields fall back to the tag kind's shipped look — projects primary/Tag, services sky/Server, stacks violet/Blocks, skills amber/Wrench, agents emerald/Bot — which is why an untouched homelab looks exactly as it did before the page existed.

The hub owns them (backend/tags/, /data/tag-meta.json, since 2026-11-05): GET /api/tag-meta → {tags, icons}, PATCH /api/tag-meta/tag {id, patch} (null clears a field), DELETE /api/tag-meta/tag?id=, POST /api/tag-meta/icons {name, svg | data(base64)} → {icon, color}, PATCH|DELETE /api/tag-meta/icons/<id>; every write publishes SSE tag-meta. Owner only. They used to sit in the settings blob (tagMeta / customIcons), which a CLI can't edit — an open tab rewrites the whole blob on its next save — so the store imported them from there once, and the blob no longer carries them (partialize/merge in settings.ts). The settings store still holds an in-memory copy every pill reads synchronously: useTagMetaSync() (App shell) fills it, its actions write through lib/tagMetaApi.ts. A guest keeps the old behaviour (their own blob, no hub calls — hubOwnsTags() is false).

Icons (tags/icons.py): an SVG is cleaned server-side like lib/svgSanitize (no scripts/handlers/foreign objects/external links, a viewBox, ≤ 48 KB); a raster favicon (PNG, ICO → its largest frame, WebP, JPEG) is shrunk by Pillow to a ≤ 96 px PNG data: URL (icon.image). Either is drawn in its own colours or tinted (masked by its alpha, tint). The upload answers the colour a tag wearing it would take — its most used saturated colour, so a logo's brand colour beats its white ground; null for an all-grey icon. The glyph picker uploads PNG/ICO/WebP too (owner).

ai-agent tags (cli/tag_looks.py) is the CLI side: ls / show / set (--color, --icon, --icon-file PATH|URL, --selfhst REF, --real-icon, --tint, --keep-color, --description) / triggers (--add/--remove own words, --mute/--unmute derived ones) / reset / icons / find-icon. find-icon looks for a project's real icon on the host: the <link rel=icon> of its index.html (root or one or two levels down, Vite public/ resolution), its web manifest, favicon / logo / app-icon files (Android launcher icons included), skipping every file of ~/projects/templates/*/public/ (the placeholder a new project starts with) and Vite's default; and a service's selfh.st logo (its homepage tile, or the shipped sh: default). An icon file gives the tag its colour unless --keep-color; a selfh.st logo with no colour of its own (penpot, ollama) is set as the tinted sh: glyph instead, since black-on-transparent vanishes in dark mode. The homelab tag-triggers skill tunes the triggers from past conversations, and the monthly tag-tuner cron agent gives new projects / services their real icon and proposes triggers for new tags.

useTagPresentation() is the queryless resolver every surface uses, so a tag looks the same on a conversation card (ConvMetaBits), in a memory/plan list, and as a composer chip (lib/richComposer.tsx). The description matters most in the composer: it's the text that goes out in the prompt's Work in the following homelab location(s): bullet, so editing it here changes what a spawned agent actually reads — the Tags editor previews that exact line.

Skill/agent tags are composer chips too (toolMentions/toolTags, offered in both the spawn and resume composers, recently-used first). They deliberately do not join the location block: selecting one adds a Use the following in this task: bullet naming the skill/subagent and its description — the difference between a session invoking open-pr and one hand-rolling a PR body.

The icon set is curated rather than lucide's full icons barrel on purpose: tag glyphs render synchronously all over the app, so they can't come from a lazy chunk, and pulling ~1500 icons into the main bundle to serve one settings page is a bad trade.

Picking a pi model: the OpenRouter browser

The model select lists the curated entries per harness, but on pi the real catalogue is a modal: Browse OpenRouter… opens OpenRouterBrowser — a FuzzyList over every OpenRouter model, each row stating the three rates that bill an agent run (in / out / cache-read, $ per million tokens), the model's parameter size and its context window, with capability chips (tools, reasoning, vision, open weights, free) to narrow the list. Cheapest first, so an unfiltered open lands on what costs least to try.

Picking one sends its full id (openai/gpt-oss-20b) as --model; the runner already routes any vendor-prefixed id to OpenRouter and bare ids to the local EVOX2 provider, so no allow-list has to be kept in step. The frontend reads the same shape: isOpenRouterId() (a slash — Claude ids never have one) is what makes an arbitrary pick resolve to the pi harness on resume, without the catalogue being loaded.

Untouched, a continuation keeps the model the session last answered on — the harness-pi driver reads it off pi's session file (session_model), since pi itself always runs whatever the runner names. Never a default: until 2026-11-06 an untouched follow-up of a local (EVOX2) conversation went to OpenRouter's twin id and died on its expired key with nothing on screen. The EVOX2's chips come first (PI_MODELS_DEFAULT), so a new pi run with nothing picked is local — on Inkling 2 Mini since 2026-11-23 (the runner's and the sidecar's default too; Qwen 3.8 27B before) — and ai-agent new --model qwen the local Qwen. While the host's OpenRouter key is refused, /api/models marks the OpenRouter chips unavailable (GET /pi/openrouter on the sidecar) and the select greys them and the browser out with the reason. A failed pi call is the red error card (API key refused, Context full, Connection lost…) — see harness-pi's runner/README.md (ai-agent-plugins) → "Errors become the error card".

pi's runner lives in the harness-pi plugin (since 2026-11-27)

The core runner/ (pi's cli.mjs, extensions/folder-permissions.ts, its node --test) and the sidecar's RUNNER_BIN are gone: they were a byte-for-byte duplicate of the harness-pi plugin's runner/, which its driver had been falling back from. harness-pi ≥ 1.1.0 launches its own runner and installs the pi it drives itself (PI_BIN, else runner/node_modules, else its own npm ci --ignore-scripts of the runner's lockfile into ~/.pi-runner/runtime, else pi on PATH; none = a 503 "pi isn't installed", never a silent fallback). The runner has no hardcoded Wake-on-LAN MAC: the driver hands it provider-evox2's localInfra.wolMac / wolBroadcast (EVOX2_MAC / EVOX2_BCAST). An older harness-pi (1.0.x) still reads config.RUNNER_BIN and fails every pi run on this core — install harness-pi 1.1.0 first. sidecar/local-model.md stays in core: harness-opencode reads it (config.LOCAL_MODEL_GUIDE); harness-pi ships its own copy.

Effort (claude) vs. thinking (pi)

How hard a run works a turn is one knob shown two ways, per harness — never both at once:

  • claude gets an EffortSelect (--effort low|medium|high|xhigh|max), the CLI's own scale. Sticky as spawnEffort; "" means "send no flag" and let the CLI default. The sidecar validates against an allow-list (EFFORT_LEVELS), unlike --model, because the scale is a closed set.
  • pi keeps the binary ThinkingToggle — it has no --effort. _effort_args emits nothing for it, so a stale pick can't leak onto a pi command line.
  • opencode gets the EffortSelect too, with the picked model's own levels (ModelInfo.efforts, from models.dev: none…xhigh or low…max), sent as the model ref's #variant. Its own sticky pick (spawnOpencodeEffort — none/minimal don't exist on claude); unset ⇒ the sidecar's default (SIDECAR_OPENCODE_EFFORT, high).

The composers send only the active harness's control (the other goes out unset). Reading back, conversations/parse/state.py mines the effort field the CLI stamps on each assistant record (it rides on the record, not the message) into efforts, busiest first — same shape as models, rendered by EffortTags on conversation rows and in the detail header. Empty for pi runs and for transcripts predating the flag, which is a valid state, not a blank chip.

The opencode harness: GPT models on the ChatGPT seat

A third harness, opencode V2 (@opencode/cli, a single native binary), running OpenAI models on a ChatGPT subscription (the Orus Enterprise seat, account chatgpt-work — "OpenAI · Work", Work profile, out of totals). It lives on the Orus MacBook worker today (worker/install.sh installs and declares it); the lab sidecar runs it the same way once SIDECAR_OPENCODE_ACCOUNTS is set there. Same idea as pi: the run writes opencode's own store, and a mirror turns it into a v1 transcript (docs/transcript-format.md) so the whole viewer — parser, costs, tool cards, SSE, the turn's end — needs no harness branch.

  • Runs (sidecar/opencode_cli.py, routes_runs._opencode_launch): opencode run --standalone --format json --auto -s ses_<conversation uuid> -m openai/<model>#<effort>, the prompt on stdin (opencode quotes a positional prompt holding spaces), PWD = the cwd (it wins over cwd()), the account's database in OPENCODE_DB (default = opencode's own ~/.local/share/opencode, shared with a terminal opencode). -s creates an unknown id, so spawn and resume are one call and the session id is the conversation's UUID. --standalone = a private server per run, so the run's env (CLAUDE_SESSION_ID, the notify CLI on PATH) reaches its tools. Per-run config (OPENCODE_CONFIG_CONTENT): the question tool denied, and the CLAUDE.md files as instructions — opencode V2 reads AGENTS.md only (SIDECAR_OPENCODE_INSTRUCTIONS); it loads .claude/skills natively. Interrupt = SIGINT (opencode aborts the turn, writes idle{interrupted}). No inbox: a follow-up into a live run is the stop + resume path, like pi. Fork = opencode's own (POST /api/session/<id>/fork {before} through opencode api --standalone), whose new id it mints — ids.json maps the hub's UUID to it, for the mirror and for later resumes.
  • The lab's keyless account (opencode-lab, "Lab · opencode", since 2026-11-01): the lab sidecar declares it (SIDECAR_OPENCODE_ACCOUNTS= opencode-lab=default — opencode's own store, shared with a terminal opencode — plus SIDECAR_OPENCODE_KEYLESS=opencode-lab). It has no ChatGPT login: it runs pi's EVOX2-local models — the sidecar mirrors the evox2* providers of ~/.pi/agent/models.json into every run's config under their own names (opencode_cli.local_providers), and catalog._opencode_local_list() twins pi's local chips as <server>/<pi id> — evox2/… for llm-server's, evox2-inkling/inkling-2-mini for Inkling (the chip's server). A Qwen twin (efforts: ["think"]) thinks off by default (chat_template_kwargs), the think variant turns it on — not high, which a sticky GPT pick would match. A model whose template takes a reasoning_effort (Inkling: pi's chatTemplateKwargs.reasoning_effort) gets none|low|medium|high variants (twinEfforts) and its pi defaultThinking (medium) as the default. A keyless account reads as signed in (_status), its probe is a no-op, no usage is polled, a GPT model on it is a 400, and it never gets the default GPT effort. The composer couples model and account: an opencode chip's provider decides which accounts can take it (serves in SpawnComposer), so a local chip routes to the lab's account and a GPT one to the ChatGPT seat. Runs cost $0 (models.is_local).
  • The mirror (sidecar/opencode_mirror.py, a sidecar thread, 2 s): reads each opencode account's SQLite (session_v2 / session_message, read-only, PRAGMA data_version + event_sequence to find what changed) and appends v1 events to ~/.opencode-runner/transcripts/<account>/<slug>/<uuid>.jsonl (subagents — opencode's subagent tool, child sessions — as sidechains with their meta.json, linked to the call). One opencode assistant row is one model step, its tools' results inside it, and opencode writes its tokens only when the step ends — after its tools ran: the mirror writes the step whole then (call, blocks, usage), its results right after (since step 1c; before, the content went out mid-stream and the usage as a later content-less record, which folded differently). A step whose turn ends first (idle, a new turn, the next step) goes out as it stands; a step that failed or was aborted with nothing in it is not written (its API error, or the interrupt, says it). Each group of events carries ocKey on its first event (dedup survives restarts, rebuilt from the file) and the header harness: "opencode" (a terminal session resumes on opencode). Tools are shaped as Claude's (sidecar/opencode_tools.py) under neutral names, the opencode name in native; GPT's patch splits per file into write / edit (+ delete_file), so diffs, edit buckets and project tags light up. A file from before v1 that a resume appends to gets a v1 header line first. An opencode→another-harness switch in one conversation is refused (409 harness_switch): the two transcripts would be one archive file.
  • Ingest. The lab mounts ~/.opencode-runner/transcripts at OPENCODE_TRANSCRIPTS_DIR: one source dir per opencode account, stamped with it at import. A worker serves its mirror on the feed as @opencode/<account>/…; the hub's FeedMirror strips the prefix into the usual layout and stamps that account (_record_worker_files).
  • Accounts. ACCOUNTS entries carry harness (claude|opencode), provider, planWindows, homeProfile, limitAlerts. A run bills an account of its own harness (accounts.valid_for / for_harness; ProfileStore.default_account(profile, harness); the composer's AccountSelect harness= / profileAccountFor). An opencode account lives in one machine's database: a worker declares it in /health (opencodeAccounts, persisted on the worker record), and its runs, login, logout and status go there (runs.service._pick_opencode_runner, accounts.routes._account_runner, HealthMonitor._worker_opencode) — an offline host is a 409, never the lab.
  • Login = OpenAI's Codex device code (opencode auth login openai --method chatgpt-headless): Settings → Logins shows the code and auth.openai.com/codex/device, and polls GET /api/accounts/{id}/login until opencode has stored the credential (table credential in its db — the sidecar reads it for status, never refreshes it: the refresh token rotates). Health: its sessions' API-error turns, refused launches, the credential row's time_updated; Check again = a usage read.
  • Analytics. opencode records $0 for a subscription step, so the backend prices the tokens at OpenAI list price (pricing.OPENAI_PRICES, models.dev 2026-10-18: the >272K long-context tier, -fast 2× / -ultrafast 6×, cache writes 1.25× input) — input excludes cached tokens and output carries reasoning, as the mirror writes them. plan_units = list $ for a GPT model. Frontend mirror: lib/pricing.ts openaiRates.
  • Plan (week). opencode never reads its limits; the sidecar does (the harness-opencode plugin's sidecar/usage.py, every 5 min): GET chatgpt.com/backend-api/wham/usage with the Codex token → ~/.opencode-runner/usage/<account>/rate-limits.json in the status line's shape. The hub reads it from a mount, or from the hosting worker's GET /opencode/usage (UsagePoller.remote), records it like the Claude seats, calibrates the week only (calibrate.windows), and pushes once per crossing of limitAlerts (95 %). When the token is about to expire it asks opencode to refresh it (opencode auth list --standalone boots the OpenAI plugin) — never while a run on that account is live.

The agy harness: Gemini on the Google AI Pro plan (since 2026-11-22)

A fourth harness, agy — Google's Antigravity CLI (~/.local/bin/agy, a closed-source Go binary that updates itself), running Gemini 4 on Gabriel's Google AI Pro login: account google-personal ("Google · Personal", Personal profile, out of totals). It runs on the lab and, once set up there, the personal Mac (WORKER_AGY=1 ai-agent-worker update); a guest only when Settings → Models puts a Gemini model in the guest pool (on the lab, held to its project by agy's allow-rules — see "Settings → Models"). Same idea as opencode: the run writes agy's own store, and a mirror turns it into a v1 transcript (header harness: "agy"), so the viewer needs no harness branch.

Google's terms. The Antigravity FAQ says headless agy -p is meant for scripting and CI and that wrapping it in third-party apps "is not supported under consumer plans" (third-party access with the login "can result in suspension or termination of your account"). Gabriel chose the plan login anyway (form of 2026-11-22), knowing it; a Gemini API key ("modelProvider":"gemini" + GEMINI_API_KEY) is the sanctioned fallback if Google ever objects — agy_cli.run_env is where it would go.

  • Runs (sidecar/agy_cli.py, routes_runs._agy_launch): agy --print <prompt> --output-format stream-json --model <base> --effort <level> --dangerously-skip-permissions [--conversation <agy id>], env without DBUS_SESSION_BUS_ADDRESS (no Secret Service on the lab: the keyring only times out; without D-Bus agy keeps its token in ~/.gemini/antigravity-cli/antigravity-oauth-token, 0600). agy picks its own conversation id, so the launch records the hub's UUID as pending in ~/.agy-runner/ids.json and the mirror binds it to the run log's first init event; a resume passes --conversation. Untouched, a resume keeps the conversation's own model + effort (read off its last step: agy would fall back to Neon high). Models = agy's base slugs (gemini-4-neon, gemini-4-hydrogen, gemini-4-argon, gemini-3.8-flash); the effort is agy's suffix (gemini-4-neon-high) — low…xhigh per model, Neon high by default. Carbon is Ultra-only; the Claude 5.5 / GPT-OSS models agy offers on Pro are not listed (Gabriel's call). No inbox (stop + resume, like pi and opencode), no fork (agy forks only in its TUI: /fork is 409 fork_unavailable, the menu greys it), a guest's scope as prompt text (<session-rules>) plus allow-rules instead of --dangerously-skip-permissions (agy_cli.guest_settings). Interrupt = SIGINT, and the commands agy started — in process groups of their own — are killed once it has exited (agy_cli.reap_later; agy-cli#1458).
  • The mirror (sidecar/agy_mirror.py, a sidecar thread, 2 s): reads brain/<conversation>/.system_generated/logs/transcript_full.jsonl (one line per step: USER_INPUT wrapped in <USER_REQUEST>, PLANNER_RESPONSE = one model call with model, tokens, thinking, content, tool_calls with full args, GENERIC = the tool results in call order, SYSTEM_MESSAGE, ERROR_MESSAGE) and appends v1 events to ~/.agy-runner/transcripts/<account>/<cwd slug>/<uuid>.jsonl, each group keyed by agyKey on its first event; a PLANNER_RESPONSE is one whole step (call, blocks, usage). The transcript never says a turn ended (an interrupted step isn't written at all): the run log's result event does — SUCCESS → turn_end, interrupted → turn_end: interrupted, another error → an API-error call; a dead run without one is closed once its process is gone; a terminal conversation once its last step is an answer and it has been quiet 20 s. What closes a turn carries the latest time agy recorded in it (the result has none), never the mirror's clock (since step 1c). Tokens: agy's input_tokens excludes cache reads, output_tokens includes thinking, no cache writes. Subagents run asynchronously (invoke_subagent returns at once, the child reports back with send_message, which lands in the parent as a SYSTEM_MESSAGE): each child (subagents/<child>.json in the parent's brain dir) becomes a sidechain agent-<child>.jsonl linked to its spawning call. Tools are shaped as Claude's (sidecar/agy_tools.py — both spellings agy uses: read_file/view_file, edit_file/replace_file_content…) under neutral names, agy's own in native. agy deletes all but its newest 500 conversations; the mirror's copy is what stays.
  • CLAUDE.md and skills. agy reads AGENTS.md / GEMINI.md and .agents/skills, never CLAUDE.md or .claude/skills: the sidecar keeps a managed global rule (~/.gemini/config/rules/ai-agent-claude-md.md, trigger: always_on: read the CLAUDE.md files first) and a skills manifest (~/.gemini/config/skills.json → ~/.claude/skills, ~/homelab/.claude/skills, SIDECAR_AGY_SKILL_DIRS) — same SKILL.md format. A rule file is capped at 24 KB, which is why the CLAUDE.md files are pointed at, not inlined.
  • Login = agy acp --login on a pty: a Google sign-in URL, then the code (or the landing URL) pasted back — the Claude paste-code flow's shape, so Settings → Logins reuses it. Status = the token file's id_token_email / auth_method (macOS: the Keychain entry gemini/antigravity). Logout deletes the token (agy has no logout subcommand).
  • Quota (the harness-agy plugin's sidecar/usage.py, every 5 min): agy -p /usage --output-format json — answered by the CLI itself, no turn, no quota spent — gives each model group's buckets (remaining_fraction, reset_time). The Gemini Models group (Neon, Hydrogen, 3.8 Flash share it, drawn down at each model's API price) becomes the five_hour / seven_day windows of ~/.agy-runner/usage/<account>/rate-limits.json (opencode's shape); the Claude+GPT group and Argon's own weekly bucket ride along raw in groups. Pro: a 5-hour window that refills until the weekly limit is hit; no published absolute numbers. A worker serves it on GET /agy/usage.
  • Config: SIDECAR_AGY_ACCOUNTS (google-personal, or id=/home/dir — agy has no config-dir switch, an extra account is an extra HOME), AGY_BIN, SIDECAR_AGY_DIR (~/.agy-runner), SIDECAR_AGY_MODEL, SIDECAR_AGY_EFFORT, SIDECAR_AGY_USAGE_POLL_S. /health says agy + agyAccounts; the feed serves the mirror as @agy/<account>/….
  • A broken RDRAND kills agy at start (since the homelab became the G11, 2026-11-25): agy's crypto is a BoringSSL FIPS build that seeds from RDRAND and aborts with CRNGT failed. when two seed blocks match — and the G11's Ryzen Embedded R2514 (Zen+, microcode 0x0810810e) returns all ones from RDRAND and RDSEED. account_env therefore sets OPENSSL_ia32cap=~0x4000000000000000:~0x40000 (mask both CPUID bits → seed from getrandom) for runs, /usage and the login; the host's hide-broken-rng unit (~/homelab/hosts/homelab/rng/) hides them from every program. A Go crash dump ends on register lines, so run_failure reports its reason (agy crashed: CRNGT failed.), not the last line (gs 0x0).
  • Research behind it (CLI mechanics, quota model, the terms): ~/homelab/data/log/2026-11-22-antigravity-cli-harness.md.

Local-model runs: live progress, the stall push, the guide

The EVOX2 serves local models from two llama-server routers, both pi providers: llm-server (evox2, :8090 — the Qwens, kyuz0's image) and llm-inkling (evox2-inkling, :8091 — Inkling 2 Mini, the default local model since 2026-11-23, on a llama.cpp build of unmerged upstream branches; ~/projects/brain/llm/compose.yml, inkling.ini, inkling-setup.sh). A catalogue chip says provider: "evox2" for either (free, the "EVOX2 · local" group, the lab's keyless opencode account) and names the serving one in server when it isn't evox2. Thinking: the runner sends --thinking off for a local run that names no level — or the model's models.json defaultThinking (a key pi ignores; Inkling: medium, its reasoning_effort none still reasons a little).

A run on the EVOX2's llm-server (pi, or opencode on an evox2* provider) is silent in its transcript while the model streams — a step lands once its stream ends, and at ~17 tok/s one 10k-token write is ten minutes of nothing (the 2026-11-01 "stuck" zipgo run). So:

  • Live reading (provider-evox2's sidecar/gen_progress.py): a thread polls llm-server every second (SIDECAR_GEN_PROGRESS_POLL_S) for every live local run — the router's /models first (a /slots?model= on an unloaded model would load it), then the slot: prefill (prompt read vs cached), decode (tokens vs the request's cap, smoothed tok/s), loading, idle, unreachable; plus, for opencode, the tool call being streamed (its database row holds name + empty input from the first token). /sessions carries it per run as progress, with a trail of the previous 6 readings, and a phase's since back-dated from the run's last known rate for it (the step began count / rate ago).
  • Relay (backend/runs/genprogress.py): the exit watcher hands each runner's rows over — every GEN_RELAY_S (1 s) while a local run is live, its 2 s otherwise; the map is GET /api/gen-progress and a gen-progress SSE event whenever it moved, clocks aside (guests: their conversations only). It is a tick event — subscribeEvents drops it unless the caller passes {ticks: true} (only sseBus does), so the pages that reload on any event don't reload per token.
  • Viewer (the provider-evox2 plugin's conversation.threadFooter slot since 2026-11-26 — the core GenProgress.tsx / lib/genPlayback.ts went): a strip under the last message (label, numbers, a bar against the cap) that plays the readings on the thread's clock, not live: the playhead runs as late as the thread reveals its rows (RevealMark in each row / tool-group call revealed live reports reveal time − row ts), never earlier than the readings can be interpolated (delivery lag + the gap between relays), never backwards. Being late, it interpolates: the bar glides every frame, the numbers roll (CharRoll) 4×/s; a phase change switches at the new phase's back-dated since; past the newest reading the count carries on at its rate for 2 s, then holds. No card pill (removed 2026-11-24).
  • Stall push: idleSince = the last sign of life (server busy, transcript growth); a transcript ending on a running tool call (an ask-form wait, a build) is busy, not idle. After GEN_STALL_PUSH_S (1200 s) with neither, one push per idle stretch, claimed in /data/gen-progress.json.
  • Make room (provider-evox2's sidecar/local_room.py): the two routers each keep a model loaded for an hour and know nothing of each other, so _launch (pi and opencode) and /local-ready unload the other servers' idle models first (/models → /slots?model=…&autoload=false → POST /models/unload); a model mid-request (another live run) stays. Threaded, retried while the box wakes. Always autoload=false on a router /slots read (here and in gen_progress): a request naming a model that just unloaded reloads it.
  • Guide (sidecar/local-model.md): small tool calls, big files in sections, narrow reads — an extra opencode instructions entry and the pi runner's --append-system-prompt, on local models only.

Claude accounts: which subscription a run bills

The host runs Claude Code under two logins — personal (the CLI's default ~/.claude) and work (the Orus seat, ~/.claude-work). An account is a config dir: CLAUDE_CONFIG_DIR moves the login, .claude.json, settings and the projects/ transcripts together. The accounts are hard-coded in backend/accounts/ (the backend must decide an account for its own server-side totals, so it can't be a client preference); Settings → Claude accounts owns only the presentation — plan, monthly price, start date, and an in-totals toggle (settings.accounts[id], settings v2). Which projects, runner, start directory and colour go with an account is its profile's (see "Profiles" below) — the accounts used to hard-code orus-monorepo for the work seat.

  • Launch (sidecar/routes_runs.py): account on /spawn, /resume, /fork. A non-default account's dir (from SIDECAR_ACCOUNTS=work=~/.claude-work, written into the unit by install.sh) is exported as CLAUDE_CONFIG_DIR; the default account gets the variable removed — pointing it at ~/.claude would move .claude.json into the dir and log the account out. With accounts declared, ANTHROPIC_API_KEY is stripped from every run (it would silently bill the API key instead of either seat), a work run whose dir has no .credentials.json is a 409, never a fallback, and --remote-control is default-account only (a work run would list itself in the employer's claude.ai sessions). GET /accounts = claude auth status per account (cached 60s).
  • Log in / out (sidecar/claude_cli.py, Settings → Logins → a login's page → SignIn): a headless claude auth login --claudeai under the account's env prints an OAuth URL (redirect = Anthropic's manual-code page) and waits on stdin; the UI shows Open sign-in page + a paste box, the code#state goes to POST /api/accounts/{id}/login/code and is piped to the CLI (the sidecar checks #state first). …/logout runs claude auth logout — the default account asks you to type its id first (it signs every lab run out). Changes publish an accounts SSE event. /settings/logins?login=<id>[&start=1] opens that login's page (the target of every "Log in" button).
  • Typed errors: sidecar errors are {detail: {message, kind, hint?, account?}} and _sidecar_call passes them through with the sidecar's status (401/403 → 502: the viewer reads a 401 as an Authelia logout). A launch that dies is read from the CLI's JSON result line. The frontend's ApiError (api.ts) + lib/runErrors.tsx (RunErrorFix) show the hint and a Log in button under composer/resume/fork errors; a transcript's API-error turn (isApiErrorMessage) is tagged ThreadItem.apiError by the parser and drawn as an error card instead of a Claude bubble.
  • Resume a stopped run (components/StopResume.tsx): the latest error card of a stopped run — rate_limit, overloaded or network, with nothing real after it — gets buttons instead of the hint. A usage limit's reset is parsed from the CLI's "resets 2:20pm (Europe/Paris)" (parse.limit_resets_at → ThreadItem.resetsAt, also on lastApiError): before it, Resume at 2:20 pm (a Send-later follow-up one minute after the reset — then Resumes at … · Cancel) and Resume now; after it, Resume; the transient errors get Retry. All send "Continue where you left off." The list card carries the same as a red limit pill + chip (ResumeChip), from the card field stoppedOn (cards._stopped_on, which re-reads an older summary's reset off its stored message — no re-parse).
  • Route (route_new_run): a new run bills the account the composer pins — when its runner holds it — else that runner's ★ login in its profile (the Homelab holds both Claude seats; Personal's ★ there is personal). A tagged project routes nothing. It starts in its runner's start dir. The account no longer decides the profile — the runner does. Resume and fork always keep the session's own account — its transcript only exists in that account's projects/. Stamped as meta.account. Cron/agent frontmatter takes account:. pi runs aren't a Claude login and bill personal.
  • Ingest: WORK_TRANSCRIPTS_DIR (/transcripts-work) joins SOURCE_DIRS; the archive merges every source into one tree, so the indexer stamps meta.accountSource at import — the last moment the origin is known.
  • Attribute: _conv_meta always emits account — explicit stamp → import source → default (the old cwd rule is gone: on 2026-10-14 every conversation that ran in orus-monorepo already carried a work stamp). A subagent shares its parent's sessionId. A project-less conversation is filed under its profile's first project (Work → orus-monorepo), not the lab root.
  • Totals: work spend is list price × tokens on a seat the owner doesn't pay for, so it is excluded from aggregated totals by default. The rollups (the activity bridge, /api/projects, /api/skills, /api/agents) take ?account= — unset = the totals (no excludeFromTotals accounts), all, or an id — and byAccount splits activity, project costs and plan actuals. The API's conversation list is unfiltered (the PWA scopes it client-side, see below). An account-owned project card shows its own account's spend flagged excludeFromTotals, rather than $0. /api/notifications carries each conversation's account, and /api/notify-log stamps an entry's account when its session's sidecar records one (account / accountSource) — never guessed, so an unattributed hub-only entry stays account-less.
  • Frontend (lib/accounts.tsx): the global scope is a profile (see "Profiles"); useAccountScope() hands it down as the accounts it covers — "all" or a comma list ("work", "a,b") — which inScope tests and the server-side rollups take as ?account= (accounts.selector accepts the list), so client-side and server-side figures always agree. Also: AccountBadge (non-default accounts only, like the harness badge), the composer's AccountSelect chip (auto = the profile's account, pinnable per send — never sticky) and the account tag kind. planValue prices each account against its own seat.
  • Plan usage (backend/usage/, docs/usage-calibration.md): the backend records each account's official /usage % (its rate-limits.json, mounted read-only; USAGE_STATE_DIRS) into usage_limits, and fits it daily against the runs' hourly meterBins → plan units per 1 % of the 5h / week window (usage_calibration; only trusted fits replace the rate, a >20 % shift notifies). Per plan: usage/plans.py records the login's tier (sidecar /accounts → plan) and the windows its rate-limits.json reports into usage_plans segments; each segment is fitted on its own hours, seeded from the previous one × the tiers' multipliers, a change pushes, and Settings' plan follows the tier (lib/planFollow) — see the doc's One calibration per plan. The personal Max has had no 5h window since 2026-10-31. Cards carry planUnits / planPct / byModel (per effort); the hub prices the notify CLI's Claude Code · N tokens · 8m line with the exact list price (an older CLI's own $x estimate is replaced), and a --final push adds · ≈Y% wk. Prices come from the provider plugins' books (provider-*, read through ProviderRegistry; conversations/pricing.py is the facade, plugins/seed_registry.py the seed-dir fallback for a process with no plugin store — PRICE_BOOK = the newest bookDate), and the parser prices each API call once (the per-content-block records repeat its usage) through ProviderRegistry.price_call — the list cost and the plan units apart. Frontend: lib/pricing.ts mirrors that book (keep the two in sync), lib/planUsage.tsx holds the hooks/formatters (one ["usage"] query key, refreshed by the usage SSE event), the card chip sits behind the Plan % visibility switch, the Details drawer's Plan usage card is the plan-usage plugin's slot, and the owner-only Plan usage dashboard is the plan-usage live plugin since 2026-11-26 (/plugins/plan-usage/board, through the usage.read / usage.calibrate bridges — plugins/usagedata.py; /dashboards/plan redirects there, every old link and push still points at it). The spawn / floating / resume composers carry a usage toolbar item (composer/components/UsageRings.tsx): context-gizmo rings for the provider the prompt bills only — the Claude login's 5h + week (the Account chip's pick), or the OpenAI week on opencode; hover = that meter's popover (reset, pace-to-100 %, last read), mouse click → /dashboards/plan, tap pins the popover; stale meters dim.
  • Local runs cost the box's time (docs/local-energy.md): an EVOX2 model's tokens are free, so the parser prices each local call from its duration — calibrated wall power × time at the dated electricity tariff, plus the box's amortisation per busy hour (pricing.local_call, over the runner's costUSD: 0). Cards carry local (seconds, wh, electricity, hardware): a ⚡ Wh chip, the Details drawer's EVOX2 time card, and a footprint from the measured kWh (French mix) instead of the Claude token factors. Re-fit the watts and busy hours with scripts/local-energy-calibration.py; add a tariff line each 1 Feb / 1 Aug.

Login health: a signed-out account (accounts/health.py)

claude auth status keeps saying logged in after the OAuth session dies ("OAuth session expired and could not be refreshed" — 2026-09-19, 10-10, 10-13, 10-15, the last one stopping every guest run), so the backend works an account's health out from the newest of its signals: bad = a lab conversation on it ended on an auth API error (parser lastApiError), a launch the sidecar refused (runs.service._launch → report), auth status saying logged out; good = its .credentials.json rewritten (any sign-in, app or terminal, or a token refresh — the sidecar's /accounts reports credentialsAt + the refresh token's expiry), a passing probe. Replies are not a good signal (an in-flight run keeps its in-memory token). Detection is passive and free; Check again (Settings, POST /api/accounts/{id}/check) is the only probe — a one-turn Haiku claude -p --no-session-persistence.

  • GET /api/accounts/health (guests: the default account's status only), accounts SSE on change (also refreshes /api/me).
  • UI (lib/loginHealth.tsx): a red home banner per signed-out account the hub watches on the scoped profile's runners (the Homelab's logins, any opencode one) → Log in = /settings/logins?login=<id>&start=1 (which redirects to that login's page, which starts the sign-in on arrival); a composer that would bill it keeps the draft but its send button becomes Log in to send (a worker run through the Claude proxy is on the lab login too; one on the worker's own login and pi runs aren't); a guest's composer locks with Connect your own Claude.
  • Pushes (owner, through the hub → HA → phone, deep-linked like the banner): signed out, still signed out every 2 h (ACCOUNT_HEALTH_REMIND_S), and 24 h before the refresh token's expiry (ACCOUNT_HEALTH_EXPIRY_WARN_S); a back in push exists behind ACCOUNT_HEALTH_NOTIFY_BACK=1. Once each — the claim is the flocked /data/account-health.json, so restarts and the deploy cutover's second backend don't repeat it. A guest's own login going out mails them once.
  • A worker on its own login (own mode — the Orus Mac, its macOS Keychain login) is watched per worker, never against the account: its runs (and mirrored terminal sessions) that end on an auth error mark that worker (HealthMonitor._compute_workers → /api/accounts/health's workers, owner only). Its sidecar reports the machine's login in /health ownLogin on every worker now, not only guest computers (sidecar/claude_accounts.own_credentials: the credentials file on Linux, the Keychain item on a Mac — its mdat for credentialsAt, the stored JSON for refreshTokenExpiresAt and the plan, read through security, which made the item, so nobody is prompted; never the tokens). Newer credentials, or a sign-in through the hub, clear it. Pushes: one per outage (no reminders) and one 24 h before its refresh token ends, both opening /settings/workers/<id>?login=1. Fix = sign in on the machine: the worker's page (Settings → Machines → → Logins) runs the same headless claude auth login on its sidecar (POST /api/accounts/{id}/login?worker=<id>, /login/code?worker=; refused for a proxied worker, a guest's computer or another account); the home banner, the run's error card (Sign in on , RunErrorFix's worker) and the push all go there. Why: 2026-11-17 the Orus Mac's login hit its 30-day limit, the card's Log in to Work re-signed the lab's ~/.claude-work (which those runs never use), and runs kept failing while the hub showed Work as fine.

Profiles → Workers, and Accounts (backend/profiles/)

A profile (Personal, Work — Settings → Machines, /settings/machines/<id>) is the machines you work on together, and is the app's one scope. (The built-in Guests profile is the exception — the conversations guests started; see "The Guests profile" below.) Since 2026-10-19 it is runner-first: a profile is an ordered list of runners (workers: "local" = the Homelab, else a paired worker's id), each in exactly one profile, the first being its default runner; a runner holds the logins it can bill, per harness. Plan + decisions: ~/homelab/data/log/2026-10-19-profiles-workers-accounts.md (form frm_850c1fc75efd). Live: Personal = Homelab (Claude Personal ★, Claude Work)

  • Mac perso; Work = Orus MacBook (Claude Work ★, OpenAI Work ★).
  • A conversation's profile is its runner's (ProfileStore.resolve: meta.profile stamp → the profile holding meta.worker/workerSource, or "local" → for an unknown runner, where its account is a ★ → default), emitted as meta.profile on every card, notification and notify-log entry. A personal task run on the Homelab on the Claude work seat is Personal. An unpaired worker stays in its profile's retired list so its history keeps its profile. The 8 Orus tasks run on the lab before the Mac was paired (Sep 11–26) carry a profile: work stamp (POST /api/conversation-meta {id, profile}).
  • Entries ({id, accounts, cwd}): accounts = the ★ login per harness ({"claude": "personal"} — what a new prompt there bills), cwd = where a run there starts (None = the runner's own: the lab sidecar's, a Mac's install dir). Which logins a runner holds (profiles/runners.py): the lab = every Claude account (each is a config dir) + the opencode ones its sidecar declares; a worker = its Claude accounts (claudeproxy.claude_accounts: the hub accounts ticked for it when it runs through the hub, else its own login's) + its opencodeAccounts. /api/profiles adds them to each entry as logins. A ★ the machine no longer holds falls back to its first.
  • Routing a new run (runs.service.route_new_run, mirrored by lib/profiles.routePrompt): the composer's worker pin, else the default runner of the profile it was sent from (the spawn/schedule body's profile; unset — cron, the API — the profile where the pinned account is a ★, else the default), or that profile's first runner that can run the harness / pinned account. Falls back inside the profile only (since 2026-11-19): an offline default runner hands an unpinned prompt to the profile's next runner, in its order, that can take it and is up (_first_up — the Work MacBook shut in a bag → the Orus devbox, on the devbox's ★); the Runs on chip's auto simply shows the devbox, no hint. Only when every one of them is down is it a 409 worker_offline (worker = the default's id; the message names the others: "… — and so is Orus devbox") — the chip turns red and Send later is the way out. Never the lab (outside the profile), and never for a pin: a Runs on pick that is down is refused, not moved. A continue goes where its session lives (an offline Mac's conversation stays refused — a session can't move machines). Account = the pin, which the runner must hold (else 400 worker_harness), else the runner's ★. pi → the lab only.
  • Writes: PATCH /api/profiles/{id} (label, colour, icon, projects, resources, workers = the whole ordered list — a runner claimed here leaves its old profile; one dropped without a new home is a 400), PATCH /api/profiles/runners/{runner} (accounts ★ merge, cwd, default, profile = move). Pairing (POST /api/workers) takes profile + default; a worker store change re-runs assign_worker; unpair → forget_worker (into retired). An account-first profiles.json (accounts / defaultWorker / cwd) migrates on load (_migrate): workers logged in on a profile's accounts join it, the lab joins the default profile.
  • Projects (exclusive): preselected in the composer while the profile is on, owned for project costs (account_for_project = the first runner's ★), and the home of a project-less conversation (home_project(profile)). On a worker run the composer leaves the profile's own projects out of the prompt's location block (their ~/projects/<slug> path is the lab's), but still tags the conversation with them.
  • Totals / scope on the wire: ?account=profile:<id> (ProfileStore.selector) = the profile's conversations billed to its own seats (its runners' ★) or to a seat counted in the totals — the lab's work-seat runs list under Personal but stay out of Personal's figures (not the owner's money). The conversation list endpoint with profile:<id> keeps all of them. Client side: inScope(scope, meta) for lists, countsInScope for sums (dashboards), scopeSeats for the subscription maths.
  • Colour + icon: the app's accent while it is the scope (useAppPalette → lib/palette.ts) and its chips' (an account's colour = the profile it is a ★ in). A guest's accent is their own, not a profile's.
  • Scope (lib/profiles.tsx): a profile id or "all", per device (lib/accountScope.ts, localStorage, key kept from the account era; unpicked = the default profile; a guest is always "all"). Set by the home top bar's ProfileToggle, by the same toggle (icons only) in the History drawer's header on any non-home conversation page, and by the dashboards' Personal / Work / All ProfileSwitch. An unlit segment carries a dot counting what runs there.
  • Each profile keeps its own selected page (lib/openPages.ts, per device, localStorage ai-agent-open-pages): home or /conversation/<id>. The conversation page records itself under the conversation's profile (useRememberOpenConversation) and the scope follows it there (a Work conversation opened from a push flips the toggle to Work); home records itself under the scope on arrival. The toggle (useSwitchProfile) on home or a conversation goes to the other profile's page (home when it has none; a 404'd conversation is forgotten) — so a Personal and a Work conversation stay open side by side. Elsewhere (the card grid, dashboards) it only changes the scope.
  • Cards (useCardHides, ProfilePills meta=): a card drops the account pill when it is its runner's ★, the worker pill when it is its profile's default runner, and the profile's own projects; in an "All" view one profile pill (non-default profiles only) is added. So a Personal task on the work seat keeps a Work account pill. The conversation page's own meta row keeps everything. Waiting-for-feedback cards filter projects the same way.
  • Settings → Machines (since 2026-11-23, was Settings → Profiles; business/machines/, plan ~/homelab/data/plans/2026-11-23-settings-machines-logins.md; one registry entry drawn per caller — the operator's Machines, a person's My computers: docs/settings.md → "Machines and Logins"): /settings/machines = every machine grouped under its profile (a row: up/down, default, login chips with ★, one "N to fix" badge; a pencil to the profile); /settings/machines/<p> = the profile in Profile (name / icon / colour, its machines — radio = default, Add machine, Move a machine here — projects) and Tracking (the resources rule) tabs; /settings/machines/<p>/<runner> = a header (name edited in place, up/down, profile, default, ⋯ Check now / Unpair), the Needs you strip (needsYou() in needsYou.ts, pure and tested — the list's badge counts the same) and Logins / Tools / Details tabs (?tab=; #mcp or ?mcp= open Tools, ?login=1 starts a worker's own sign-in on Logins). The breadcrumb's last crumb switches between siblings (no tree column). Text rule: no intro paragraph — How it works (technical/HowItWorks.tsx), ⓘ InfoHint, terminal commands behind a From a terminal instead Fold. /settings/profiles[…], /settings/workers[#id|/<id>] redirect there, query string and hash kept (pages/Redirects.tsx).
  • Settings → Logins (since 2026-11-23, was Settings → Accounts; business/logins/, same plan; a person with self.claude gets My logins there instead — their own Claude row and page, pages/MyLogins.tsx): /settings/logins = every login per harness — chip, state (signed in / signed out / no login / checking), the machines that bill it as small chips (★ = their default), one to fix mark when signed out (pages/Logins.tsx); /settings/logins/<id> = state first — signed in as / the hub's signed-out verdict + Check again (components/LoginState.tsx), Re-login / Log out (an agy login: one row per machine, then its Gemini quota; opencode: its plan-usage read), Used by as chips to the machine pages (· own login when a worker bills its own), then Plan & cost (components/PlanCost.tsx: plan, monthly cost, start date, count in totals, each note behind an ⓘ) in a Fold, closed, its header keeping the savings line. The breadcrumb's last crumb switches between logins (no second column); the account's description and the long notes are behind How it works. One sign-in block: components/SignIn.tsx (was AccountLogin) with the calls of the login it signs — hubLoginApi(id[, machine]) (a hub login; an agy machine's own), workerOwnLoginApi (a worker's own Claude login, the machine page's Logins tab; no log-out) and guestClaudeApi (/api/me/claude*, the guest's GuestClaudeCard, connect wording). ?login=<id>[&start=1][&worker=] on the list (every signed-out push, Log in button, signInHref) opens the login's page, sign-in started; /settings/accounts[/<id>] redirect there with query string and hash (pages/Redirects.tsx), and the old /settings/profiles/<p>/<runner>/<account> too.

The Guests profile (since 2026-11-04)

Guests' conversations used to land in Personal (they run on the Homelab, whose profile is Personal). A built-in Guests profile now holds them — form guests-profile_2hfpbx.

  • Membership = who started it, not the runner: ProfileStore.of_meta(meta, account) → meta.profile stamp → Guests when meta.owner names a guest (or the run billed a guest-<uid> login — guest_owner) → the runner rule. Every resolution goes through of_meta (cards, the notification feed, the notify log, the rollups' _summaries_for). A conversation the owner started and shared with a guest stays in its runner's profile.
  • Store (profiles/store.py): {id: "guests", kind: "guests", label, icon ("users"), color ("emerald"), enabled} — seeded on load, always last, never default, with no runners, projects, retired or resources (_clean_guests). PATCH /api/profiles/guests takes only label / icon / color / enabled (anything else is a 400); a runner can't move into it (patch_runner, assign_worker), a prompt sent with profile: "guests" routes like one with none (runs.service._profiles_for_run). Off (enabled: false) = the old behaviour: guests' conversations follow their runner, a meta.profile: guests stamp is ignored. /api/profiles adds members (the guests' ids) to it (runners.with_computed); a users event refetches profiles.
  • Figures (Gabriel's pick: both): selector("profile:guests") = every guest conversation on a seat counted in the totals or their own login (an estimate); profile:personal still counts a guest's spend on one of Personal's ★ seats (it is that seat's money) though the conversation lists under Guests only. guest:<uid> items narrow the Guests view to those guests (the predicate's third argument). Client twin: countsInScope.
  • Switches (switchProfiles): the home toggle and the dashboards' switch get a Guests segment once it is on and has a member (or while it is the scope). The old dashboards-only "guests" scope id is the profile id now (profile:guests on the wire), so a device left on it lands there.
  • Guests home (ConversationHome): no composer (desktop dock and the phone's drawer — guests start their own conversations; a floating composer opened there sends as the default profile, useSpawnProfile), one chip per guest at the top instead (GuestChips: All guests + avatar, running dot; most recently active first). The pick (useConvFilters.selectedGuests, per device) is one for the home page, the drawer list (ConversationsPanel, which drops its Mine / Guests chips on this profile) and the usage strip: it filters New (the feed's owner), Running, Waiting for feedback and the list.
  • Usage strip on Guests (lib/profileUsage): the default profile's plan gauges always (what guest runs bill), one budget bar per guest (month spend on the owner's account vs their budget, ≈ own-login estimate; the picked guests only), and the activity tiles from ?account=profile:guests[,guest:<uid>…].
  • Settings → Machines: a built in Guests group (its members, then People's computers, each opening the computer page); /settings/machines/guests = GuestsProfilePage (the on/off switch, name / icon / colour, members with month spend). Runner pickers (runnerProfiles) leave it out.
  • Not done: no backfill needed (membership is derived at read time); a guest never sees profiles (their scope stays "all").

Conversation resources: what a work conversation is about

A work conversation is almost always about one issue, one PR, one branch or one thread. Those are resources — typed links keyed kind:id (pr:orus-tech/orus-monorepo#13722, slack:C02…/1791878511.818179) — shown as pills on cards, the drawer list, the Details header and notification cards (ResourceTags), searchable by id / label / title, and named into the title once: INS-2229 · <issue title> · #13722. Plan + decisions: ~/homelab/data/plans/2026-10-15-conv-resources.md; the move to plugins: ~/homelab/data/log/2026-11-26-ai-agent-plugins-round4-analysis.md §9b.

Since 2026-11-26 the core knows two kinds only — branch and url. Everything vendor-specific is a plugin's resources[] (pure data in its plugin.json, docs/plugins.md → "Resources"): the github plugin's pr, the linear plugin's linear, the slack plugin's slack (three separate plugins, none importing another — backend/fixtures/resource_plugins/ holds their reference manifests and the test kit). No GitHub polling any more (the old pr_state.py + sidecar /gh/pr-states are gone); Notion links are plain url pills; Profile.resources and the Orus defaults are gone (a stored block is dropped on load).

  • Registry (backend/plugins/resources.py): the owner's active plugins' resources[] + each one's settings, compiled once into an immutable PluginResourceRegistry (cached on PluginStore.version, the same object — and version — while nothing it reads changed; the cards' memo keys on it). Matching: urlRegex / idRegex / bareKeyRegex (team-gated) / branchKeyPattern (cross-links: linear reads github's head branch) / toolExtractors[] (declarative rules over tool calls and results — never a subprocess, never plugin code). Shape: idTemplate / urlTemplate / labelTemplate / titleToken ({num}, {repo|config.githubRepo}, {{config.linearWorkspace}}, {team:upper}). Look: icon, color, stateTones, clickAction, priority, hueRole. Scope per plugin (its settings): workers (runner ids, local = the lab) + cwdGlobs (empty = every conversation), notifPills, channelMap; any other text setting is {config.<key>}. GET /api/plugins → ui.resources = the display descriptors (no regexes; pluginId for the owner only); a plugin write that changes the registry publishes meta.
  • Model — cli/resource_urls.py, stdlib only, shared by the conv CLI and the backend (the image ships cli/ as /app/cli; conversations/resources.py loads it by path): links → url records (junk stripped: , . ), zsh \#, fragments, </command-args>; skip hosts, bare domains), branches, key / merge.
  • Source 1, the parser (conversations/resources.py, ResourceMiner fed by ParserState): every link in the user's turns raw (url — the view matches it, so a plugin installed later lights up the whole archive with no re-parse), typed <key>-<n>-<slug> branches, the session's own branch (checkout -b / switch / worktree add / branch -m, and gitBranch of records in a worktree cwd — never a shared checkout's first gitBranch; scratch repos ignored), pr-link records (as their link), and — with the registry of the day (plugins.resources.current()) — plugin bare keys and toolExtractors (gh pr view title/state/head, get_issue title/labels/project/team, slack_read_thread, channel names). Ids are shaped without the settings (the transcript's own repo beats the default); resourceInfo (title, state, xref, metadata) + resourceNames are what the archive learns. Legacy summaries (kinds pr/linear/slack/notion, resourceTeams, slackChannels) still read. Subagents lend their lookups' titles to the parent (merge_children).
  • Source 2, the run — conv add <url|key> [--kind] [--title] [--label] [--state] [--primary] [--repo], conv title, conv rm, conv show (cli/notify.py conv). The CLI can't know plugin kinds: a link goes as a url record, a key / id as {ref} — read hub-side by the registry (resource_view.clean_recorded / clean_remove, also on a worker's met_ outbox item through apply_recorded). meta.resources merges by key (primary exclusive); titleSource: user › agent › resources.
  • The view (conversations/resource_view.py): every record normalized by the registry (url → plugin kind, ids completed from the settings, a kind no active plugin declares → a plain link); a plugin's kinds only where its own scope matches, branch/url where any plugin's does, recorded ones always; bare keys for teams seen in a real link; branchKeyPattern cross-links over branch ids and PR heads / bodies (xref, archive-wide); names = the plugin's channelMap › learned › conv add --label; repeated threads get their date (dateGroup); the primary = the lowest priority first-turn resource; the title = <lead token> · <title> · <shade token>. One Context per (summaries, meta, registry) version, kept by identity while its content holds (per-transcript _derive cached on the summary object). _conv_title = meta.title › resource title › ai-title.
  • The work-context subagent is not the hub's any more (since 2026-11-05). From Oct 15 to Nov 5 the hub injected a Haiku work-context agent (claude --agents) plus a "delegate first" system-prompt snippet into every run a profile's rule matched (runs/work_context.py, the work-context subagent / Past conversations in the brief switches). The Orus team asked for it to be opt-in (orus-tech/orus-monorepo#14642), so the hub code and both switches are gone (a stored contextAgent / pastConversations is dropped on load) and the agent ships as a Claude Code plugin of the Orus repo — a repo-local marketplace orus (.claude-plugin/marketplace.json → .claude/plugins/work-context/), which nobody gets until they install it. It runs on the Orus MacBook only: work-context@orus installed at user scope (claude plugin marketplace add <checkout> + claude plugin install work-context@orus --scope user; claude plugin disable|enable toggles it), so every session there — hub-launched or not — sees work-context:work-context. The plugin reads the agent in place from that checkout. The repo's agent never mentions the hub, so it doesn't conv add what it fetched or run ai-agent past: a work conversation's pills come from the miner (the prompt's links, the session's branch, pr-link, its own lookups) and from whatever the run records itself. A subagent's lookups still lend titles to the parent (merge_children). Measured while the hub ran it (Oct 16 → Nov 3): 102 runs, $2.64 of Haiku, ≈ $37 saved at list price.
  • The clarifier subagent (the clarifier live plugin's agents[], added to every claude run by runs/extras.py through plugins/agents.py; runs/clarifier.py and /api/clarifier are gone): asks the run's ask-forms so the main thread carries a brief + a digest instead of the spec, mockups, skill text and Monitor schema. The test form promised $0.35 → $0.03; measured over Oct 21 → Nov 1 it saves nothing: the brief (3.3k tokens, its thinking included) + the report (1.2k) weigh what they replace (5.0k), so only the main-thread calls drop (3.3 → 1.6). Per form: inline $0.35 / 0.68 plan units, clarifier on Sonnet $0.54 / 0.79, on Haiku $0.29 / 0.66 (docs/clarifier.md → "Measured", scripts/clarifier-gains.py). Since Nov 1 its description asks for a short brief (paths and URLs, not pasted content; ≤ 1,200 characters since Nov 4), the clarifier reads/screenshots what it needs itself, and its report carries only the answers object. Since Nov 4 it runs without CLAUDE.md (omitClaudeMd: true): the instruction files and memory index were 25k of the 33k tokens each spawn wrote cold. With that, a Sonnet form costs ≈ 0.52 plan units vs 0.68 inline (docs/clarifier.md → "Nov 4"). The sidecar lists the definition keys it takes in /health (agentKeys), and runs/extras.py strips omitClaudeMd/effort for one that predates them, since an unknown key is a 400 for the whole run. Haiku by default; the plugin's prefs (ui.prefs: enabled, model — optionsFrom: user.modelFamilies, effort — Medium by default, Inherit = the run's) turn it off or pick Sonnet / Opus, read at each launch. They are scope: default+override: the operator's value is everyone's default, a person's own fields override it (pluginPrefs.clarifier in their ai-agent-settings blob; a guest may pick only models their list allows). A run gets its runAs person's value; cron runs and the operator's get the default. The old /data/clarifier.json and users.json clarifier overrides were carried over once (plugins/carryover.py clarifier). A guest's runs on their own computer get no lab agents at all, the clarifier included. Since 2026-10-28 it drives the standalone ask-form tool (ask-form create … --open, ask-form wait <id> --timeout 270s: a subagent caches at the 5-minute TTL, a longer poll re-writes its ~31k context) and gives up at ~1h45, inside the 2 h background-agent ceiling. Its forms are hoisted to the root conversation (2026-10-31): tree._scan_forms scans every agent transcript (incrementally — offsets per file) for the create output's /f/<id>?token= links (the legacy FORM_ID=frm_… no longer, 2026-11-25) with the timestamp of the line each opened on; _subtree_forms gives every Agent card its whole subtree's forms (a clarifier three agents down included) as SubagentRef.forms + formRefs ({id, at, agentId, agentType}), teaching the ask-form mirror each link on the way (askform_store.learn). On a root page the viewer's hoistAgentForms (business/conversations/hoistForms.ts) turns each into a client-side kind: "form" row placed where it opened (never above its card) — the backend can't insert rows: its thread deltas are index-based — drawn by AgentFormCard (via clarifier, live while the agent waits); the Agent card keeps a "📋 1 form ↓" chip. Both stay on with the Form cards visibility switch off (it only folds the thread's own form widgets back to their Bash rows — a subagent's form has no row to fall back to). An agent page in between shows neither (the root and the asking agent's own page do). The summary view keeps pending forms (the thread's own and hoisted) out of its folds; answered ones fold away. Above the composer, ConversationWaiting draws each pending form as a slim bar (title, wait, Answer, ↓ to its card — jumpToForm, the FormJumpContext, mounts a folded/unmounted card first); asks keep their button card. Push and Waiting for feedback need nothing: a subagent shares its parent's CLAUDE_SESSION_ID, which the CLI stamps as meta.session. The Details drawer's Forms card (the ask-form plugin's conversation.details slot since 2026-11-26; the core FormsCard.tsx went) lists every form of the conversation — the hub's (useForms()) and the ask-form tool's (useAskForms()), subagents' too, matched on sessionId — as two-line rows (title; status · fields · age; pending ringed amber with an Answer chip, cancelled/revoked dimmed). A hub row sets ?form=<id>, so submitted forms reopen read-only in the full-screen dialog; a pending ask-form row opens its answer page, an answered one scrolls to its card.
  • Related conversations (conversations/related.py): an inverted kind:id index over the cards. The Details drawer card that lists them is the graph plugin's conv-related slot since 2026-11-27 (owner only, over graph.read's GET …/hub/graph/related?id=, plugins/graphdata.related); the core card, GET /api/conversations/{id}/related and the Related conversations switch went.
  • Past conversations (conversations/past.py, GET /api/past-conversations, ai-agent past INS-2229): the same index read for a subject — the hue resource (hueRole: hue, the linear issue; a shade — a PR — counts as the hue its head branch names, else its conversations' primary hue; a branch only names one the hub knows) — the asking session left out: the ones running now apart, then the ended ones of the last 30 days, primary-on-it first, newest first, 3; each with its last assistant message that names the subject (whole words, from searchMsgs) — a conversation's last message is about another issue a third of the time. Measured before it existed (Nov 2026, ~/homelab/data/log/2026-11-03-work-context-past-conversations.md): 177 of 326 work conversations followed one on the same issue (median 4 earlier, 15 h apart), 63 % of their early fetches repeated one, 5 / 192 prompts said so. (The hub's old work-context agent asked it once per brief; the Orus Mac's opt-in copy doesn't.) Notifications: a push carries its conversation's main resources (≤3, when an in-scope plugin has notifPills), the feed falls back to the conversation's current ones.
  • Switches: Resource pills, Resource state (key resourcePrState) (lib/visibility.ts). Frontend: lib/resources.tsx (descriptor-driven glyph / tone / action, useResourceKinds(); historical kinds keep a fallback glyph), ResourceTags.tsx; the mock seeds three variants on the work conversations and lists the three plugins' kinds (mock/plugins.ts).
  • A worker picks up the run side (sidecar extras, the outbox meta kind, conv) with its next auto-update (see "Workers" → Auto-update); until then its conversations still get the parser's pills and titles.

Conversation look: a colour and two icons per card

Every conversation card (the drawer list, Home → Running, /conversations, the conversation header, notification cards) leads with a tile: the project icon in a tile tinted with the conversation's colour (the border runs while the session runs), and under it two small bare icons, what it does (the action) and, once it stops, its state. Off switch: Settings → Display → Conversation look (settings.convLook). Decided over two ask-forms on 2026-10-20 (layout L2 + the rules below).

  • Colour (backend/conversations/look.py). For a work conversation it comes from its hue + shade resources — the kinds whose plugin declares hueRole (linear: hue, github's pr: shade): subject() → linear:INS-2171+pr:o/r#13497. The hue is the primary one, else the first (the view already cross-linked the one a PR's or branch's name carries). LookColors (/data/look-colors.json) gives each issue a hue that no other issue active within 7 days wears, walked in a spread order. Each of the issue's PRs gets a shade of that hue (violet-300, -700, -400, -600). A conversation keeps the colour it got first, even after it opens a PR. Without a subject, the card takes its project's tag colour. Projects and services now get a hashed default colour (defaultTagColor), so their pills stopped being all orange.

  • Icon (frontend/src/lib/look.tsx). Tried in this order:

    1. a set override (look.icon);
    2. the issue's first Linear label that has an icon (area labels beat the Linear project, by Gabriel's choice; type labels such as is : bug have no icon);
    3. the Linear project;
    4. the team;
    5. the project tag, else the service tag, else homelab.

    Labels, project and team are mined from get_issue results (resourceInfo.labels/project/team, the linear plugin's metaFields) and aggregated in resource_view.Context.metas (keyed by the hue resource). They appear in Settings → Tags as the linear kind (label/<name>, project/<name>, team/<name>). Shipped defaults for every project, service and the known labels live in lib/tagDefaults.ts. An sh:<ref> icon is a selfh.st logo drawn in monochrome: its -light SVG used as a CSS mask, so it follows the colour (selfhstIcon in lib/tagIcons.tsx). The tag editor has a selfh.st field.

  • Action. One of 16 keys (look.ACTIONS; the CLI, the conv-meta skill and lib/look.tsx carry copies). In order of precedence:

    1. set — by conv look <action> (cli/notify.py, which also works through a worker's outbox, since look is in _RECORD_KEYS), by conv-meta look, or from the card menu;
    2. the conversation-labels plugin (since 2026-11-26; it replaced the core's Haiku-only look_labeler.py thread and the sidecar's /look). On conversation.started and every 2 minutes it reads what has no badge (hub/labels/pending → conversations/look_pending.py: the title, the first prompt, the issue's labels, the Claude login it bills), asks the model picked on its page (default Haiku, any model through the sidecar's /complete, a fallback) with the hub's prompt (look.SYSTEM_PROMPT) and writes meta.lookAuto (hub/labels/look); spend booked as side call look. Work isolation (on by default) keeps a Work conversation on the Work seat. No plugin, no new badges. scripts/look-backfill.py (Batch API) → GET /api/look/pending → POST /api/look/auto still works.

    There is no keyword guess while the label is pending (Gabriel's call).

  • Card menu (right-click, or a 500 ms long-press on a phone): Copy ID first (the conversation's UUIDv7, toast on copy), then pin, rename, Colour… → POST /api/look/color. On a conversation with a subject this re-colours every card on that subject; otherwise it sets the conversation's own look.color. Action… → look.action. One component, useConversationMenu() (components/ConversationMenu.tsx, 2026-11-25): triggers(c) goes on a card (right-click, long-press, and the long-press's trailing tap swallowed), node renders once — the menu is portalled to <body>, with its Rename / Colour dialogs and the plugins' rows (ui.menuItems, the dialog each opens — the Handoff plugin's). The drawer list, the /conversations full cards and the home page's Waiting for feedback (once its conversation is known), Running and Finished cards all carry it; the home's passes { bulk: false }, which drops the list-wide Archive all older than yesterday. One handler set per conversation id is kept across renders, so the memoized cards don't re-render on every update.

  • Sidecar change — /look and /title are gone, /complete is new (sidecar/complete.py); restart claude-sidecar after deploying, or the plugin's calls 404 (no badges, scheduled titles fall back to first words).

Pets: a live plugin over the overlay point (since 2026-11-25)

The pet-pet hamsters (Akkibi's lib, our fork @gabvdl/pet-pet) left the core for the hub plugin pets (~/projects/ai-agent-plugins/plugins/pets/), drawn through a new plugin point, overlays (ui.overlays + ui.prefs, docs/plugins.md → "Overlays"; host in frontend/src/business/plugins/overlay/): a transparent sandboxed frame over [data-overlay-world] (App.tsx, the whole screen but the navbar). The conversation page wraps an OverlayHost where="conversation" around its OverlayMember; home wraps its content in OverlayHost where="home" root="[data-overlay-root]", and each Running card (ConversationListElement overlay) is a member whose card carries data-overlay-anchor. The frame sees the page's box outlines, the members' colour / state / mood, stamps and new-message events — never text. The plugin lays invisible platforms at the outlines and pet-pet climbs them as before; clicks reach the frame only on a pet's own box (pointer: "hits"). Behaviour is the old one (mood map, colony, homesick rail pets) plus a hop on each new Claude message (Gabriel's picks, forms pets-as-an-overlay-plugin_wl2w72, how-the-pet-moves-on-the-page_6k4gry). Switches: the plugin's page → Your preferences (on / size / your hamster's colour — settings.pluginPrefs.pets, the v6 migration moved settings.pet there), the eye menu's Plugin overlays, the Animations switch. A managed plugin, on for every guest.

Workers: the runner on another machine (workers.py, remotefeed.py)

A worker is sidecar/sidecar.py running somewhere other than the lab — a Mac as a launchd user agent, or a Linux box as a systemd user unit (worker/install.sh, see worker/README.md; install-macos.sh is its old name, kept as a shim). Any Mac qualifies: Gabriel's personal MacBook (account personal) as much as the Orus work seat (work), the one it was built for — the org disables Claude Code's Remote Control there, and the lab's own work seat can't do what a terminal on that Mac can (its secrets are stubs). Sessions on a worker run natively under the Mac user: its Keychain login and whatever its shell has (mise, gcloud, op, gh…). The installer asks for the default cwd (the directory it is run from, confirmed with y), labels the worker with the sidecar's default account unless WORKER_ACCOUNT says otherwise, and keeps Remote Control off. Every question has a WORKER_* answer, so Add machine (machines/components/PairWizard.tsx, machines/pairing.ts installCommand) hands out one line with them baked in; the installer also writes ai-agent-worker (status / logs / pair / update / uninstall) into ~/.local/bin.

The hub pulls; the worker calls the hub for one thing only — its runs' model calls, through the Claude proxy (below), with a token that can do nothing else. (A guest's computer is the exception: it reaches the hub through the worker link — see "Guests' own computers".) That is the security shape: the worker binds its Tailscale address only, holds one bearer (minted at pairing) and, once it runs through the hub, the proxy's URL and its own proxy token. Notifications, asks and forms work there through the outbox (below); the other lab skills that call back (conv-meta, complete) are not on workers yet — a worker session's closing push is its final message's ```notify block (the hub reads the mirrored transcript), and it finishes on its turn's end, else the exit watcher and the recency window.

The lab's own routers are not mounted on a worker (sidecar.py _host_only): /scaffold, /tools/video-extract/… + /tools/3d-render, /homelab-env, /ship/deploy, /chrome, /local-ready, /pi/openrouter. The hub calls them on the host sidecar only (_sidecar_call with no worker); the in-container runner has a token, so it is a host and keeps them. test_host_only_routes.py pins both route lists — a new lab-only router goes through _host_only too.

  • Pairing (workers.pair, sidecar/pairing.py): the installer writes a one-time code and prints 100.80.162.92:8790/<code>[/<claude login email>]. Settings → Machines → Add machine (the list's button, a profile's Add machine, or ⌘K — all open the modal through ?pair=[<profile>], handled by MachinesFrame) is a 3-step wizard (since 2026-11-23): Where is it? (on my tailnet / it dials out) → Run this on it (the line + copy, an Options fold: start dir, opencode) → Paste what it printed. What it sends is built by the pure pairing.ts (installCommand, tailnetPairRequest, dialOutEnrollRequest), pinned against the old one-screen dialog's code in pairing.test.ts. Step 3 takes that one string, the profile it joins (default or not) and how its Claude Code runs: through the hub (the default — no login on the machine; tick the accounts) or on its own login, which is then matched against the hub's accounts (the host sidecar's claude auth status per account) before the code is spent — no match ⇒ 400 kind: "account" and the wizard shows an account picker, code still good. POST /pair consumes the code and answers the bearer + identity; wrong codes burn it after 10. Store: /data/workers.json (0600; the token never leaves the backend). Re-pairing needs ai-agent-worker pair and rotates the token.
  • A machine off the tailnet: It dials out (since 2026-11-19, for an Orus devbox — on the company's tailnet only, the hub can't call it; decided in form devbox-as-ai-agent-worker_4edssv). The dialog's other way in: POST /api/workers/enroll {account, cwd, opencode, name, profile, default} mints an owner code on the guests' worker link (link.ENROLL.mint( link.OWNER, opts)) and answers the install line (WORKER_HUB = the public guest host, WORKER_ENROLL, WORKER_ACCOUNT, WORKER_CWD, WORKER_OPENCODE). /worker-link/enroll/check tells the installer it's the owner's (owner: true → link.json), so it gets the owner's setup (notify shims, no Which Claude? launcher); /worker-link/enroll makes an ordinary owner record (no owner, id w…, link, claudeMode: own, account), and link.on_paired puts it in enrollProfile (first = default runner when enrollDefault) once the pairing ran through the link. Own login only: the proxy is on the tailnet host and the public host takes no owner token, so PATCH refuses claudeMode: proxy / claudeAccounts / opencodeProxyAccounts on a linked owner worker (kind: "worker_link"). Its login is watched like any own-mode worker's (accounts/health.py, sign-in through ?worker=), its link token rotates weekly like a guest's (guests.maybe_rotate), and the security log records worker_linked. The dialog waits on the SSE-fed workers list and shows Connected ✓. Recipe for a devbox: worker/README.md → "A machine off your tailnet".
  • Auto-update (workers/updates.py, sidecar/selfupdate.py, install.sh auto-update): a worker follows the hub's deployed commit — the homelab deploy.sh writes it to /data/deployed-commit (DEPLOYED_COMMIT_FILE). /health carries the worker's commit, updatable (only the installer's own clone — WORKER_UPDATER — never a dev checkout or the host sidecar) and update (its update.json). Each probe computes updateStatus (current / outdated / ahead / updating / failed / unsupported / unknown — ahead via git merge-base --is-ancestor on the source mount AI_AGENT_SRC) and maybe_update POSTs /update {commit} to an outdated one (30 min between attempts at one target, 6 h after it failed; autoUpdate: false on the record stops it). The worker runs the installer detached: fetch that full sha from Gitea, restart only if sidecar/ cli/ worker/ or the notify skill changed, wait for /health to report it, else check the old commit out again and restart it (rolledback). "Report it" means a new process: /health's commit is the checkout's HEAD, which a process that never restarted reports too (the Orus Mac did exactly that on 2026-10-21 — done, old code still serving), so the installer notes the port's listener pid first (/health's pid, else lsof/ss) and, if that same sidecar still answers after the restart, stops it so the new job can bind (runs are detached daemons — they survive). POST /api/workers/{id}/update is Update now. An install from before this has no /update — unsupported, one manual install-macos.sh --update fixes it.
  • Lab sync (workers/labsync.py, sidecar/labsync.py): the homelab's .claude/skills/<name>/ and .claude/agents/<name>.md whose frontmatter says portable: true (they need neither the homelab checkout nor lab-only infra) reach every worker — portable: <account> (work, personal, since 2026-11-23) only the workers whose record's account is that one (default_on; overrides, clean_overrides and view's default compare against that per-worker default, and Settings shows the account as a badge); Settings → Skills & agents ticks or unticks any of them per worker (the worker's own page keeps the sync state and Sync now) (labSyncOverrides on the record, {"skill:<name>"|"agent:<name>": bool}, GET/PUT /api/workers/{id}/labsync, POST …/labsync/push = Sync now). The homelab repo is private, so the hub ships the files: it bundles them from /workspace/.claude (never .env*, node_modules, venvs, caches, tests/; 512 KiB a file, 4 MiB a bundle — the rest is listed as skipped), and each probe compares the bundle's hash with /health's labSync.hash and POSTs /sync to a worker that differs (10 min between attempts at one hash). The worker writes v-<hash>/ under ~/.local/share/ai-agent-worker/lab-sync, swaps current to it, and symlinks each item into every config dir it knows (~/.claude + its declared accounts) as skills/<name> / agents/<name>.md — plain names, terminal sessions see them too, /skills lists them. A skill or agent of the machine's own under the same name wins (conflicts), and only links into lab-sync are ever removed (ai-agent-worker uninstall drops them all). /sync is a 409 on the host sidecar. A sidecar from before has no labSync in /health ⇒ unsupported until its next update. Harness / provider plugin maps ride the same bundle (harnesses / providers, typed-plugins §3.1) and are checked apart from its hash (2026-11-26 outage: an older sidecar took a bundle's hash, dropped the maps it didn't know, then updated onto the strict plugin-only code with no harness — invalid harness: 'claude' on every worker): /health's pluginSync ({kind: {version, loaded}}, sidecar/labsync.plugin_sync) says which map version a worker holds and runs, labsync.plugins_drift makes a worker that holds the hash without them outdated, and the worker's /sync re-applies maps it lacks even under a hash it already has. No bundle goes out in the probe that asks a worker to update, nor while it is updating. A plugin path the worker would refuse (a hidden part, like runner/.gitignore) is never shipped — it would fail the whole /sync. Portable agents (portable: true only — not an account-scoped one) also ride every lab run (not a guest's) through claude --agents (runs/extras.py), whatever its cwd — after the clarifier, within the runner's agentsMax from /health (12 agents / 60 000 chars; an older sidecar 5 / 16 000); a worker gets them as files instead.
  • Setup checklist (sidecar/tools_check.py, 2026-11-23): a worker's /health carries tools — claude, gh, ask-form, each {installed, path, version, signedIn, …} (claude: its auth status or the Claude proxy; gh: gh auth status's exit code + login name; ask-form: admin token
    • serve answering) — and toolsCheckedAt. Checked in a background thread every 10 min (/health never waits; None until the first check), never a token. The hub keeps it in the worker's status (Worker.tools) and the worker page's Setup section shows ✓ / ✗ + a fix hint per tool (WorkerSetup.tsx); an older sidecar has no tools ⇒ no section. The installer also sets ask-form up on every owner worker (WORKER_ASKFORM=0 opts out; worker/README.md → Forms). Since 2026-11-23 the checklist also covers opencode, agy (harness: declared in the service, account) and pi (managed: tools.sh's wrapper; gh's managed = in ~/.local/bin or Homebrew), and installs what's missing (see Tools from the Setup checklist below).
  • Tools from the Setup checklist (backend/workers/tools.py, sidecar/tools_install.py, worker/tools.sh, 2026-11-23, form install-tools-on-workers_jg0hk3): Install / Install all missing / Update / Sign in per row. The hub sends only tool names from a list — owner workers claude, gh, opencode, agy, pi, ask-form; a guest's computer claude, gh (never the owner's harnesses nor ask-form; pi left it on 2026-11-26: harness-pi never reaches a guest's computer) — and update only for gh and pi (the rest update themselves). Since 2026-11-26 core keeps gh and ask-form only: each harness CLI's row, recipe and check is its harness plugin's (harness.workerSetup + the driver's setup_check, docs/plugins.md → "The sidecar hooks of a typed plugin"). The recipes live in the worker's checkout (worker/tools.sh install|update <tool>…: user space only, never sudo — ~/.local/bin, brew on a Mac; gh's release build checksum-checked; pi's CLI on the machine's Node ≥ 22.19 or a private Node LTS; pi runs stay Homelab-only, runs/service.py). opencode / agy / ask-form go through one install.sh update with WORKER_<TOOL>=1 (installs, declares the harness, restarts the worker once, runs survive), last in a batch, holding update.lock so it never races an auto-update. The sidecar starts the script detached (own session: it outlives that restart), answers once every tool reads queued, and /health carries toolInstall {tools, update} (absent on an older sidecar ⇒ hints only, 409 tools_unsupported) and toolJobs {tool: {action, state queued|running|done|failed|interrupted, startedAt, finishedAt, error, tail}} read off ~/.config/ai-agent-worker/tools/<tool>.json|log; tools_check re-checks once a job ends. The hub probes a worker with a job queued/running every 3 s (WorkerMonitor.check_hot, 30 min cap) so the page follows it live. gh's Sign in is GitHub's device code (gh auth login --web on the worker, opencode's _Login pump with GitHub's patterns, POST|GET|DELETE /gh/login); claude (own mode) / opencode / agy link to their account's sign-in (signInHref(account, worker)). Routes: owner POST /api/workers/{id}/tools {tools, action} + /gh-login (409 guest_computer on a guest's machine — they install from their portal); guest POST /api/me/computers/{wid}/tools + /gh-login (gate: users/caller.py), the Setup block of each computer in My computers (ComputerSetup.tsx, French in the translation-fr plugin).
  • Repo plugins (workers/repoplugins.py, sidecar/repo_plugins.py, 2026-11-23): Claude Code plugins a repo ships in its own marketplace (<cwd>/.claude-plugin/marketplace.json — orus-monorepo: marketplace orus, plugin work-context), on per account. A worker's /health carries repoPlugins — {checkedAt, configDir, marketplace: {name, path, repo, plugins: [{name, description}]} | None, known, plugins: {"<plugin>@<marketplace>": {installed, enabled}}} for its default cwd and default account's config dir, read off files (settings.json's enabledPlugins / extraKnownMarketplaces, plugins/installed_plugins.json, plugins/known_marketplaces.json), cached 30 s, never the CLI or a token. The hub keeps account picks in /data/repo-plugins.json ({"accounts": {"work": ["work-context@orus"]}} — the seed when the file is missing; REPO_PLUGINS_PATH) and per-worker overrides (repoPluginOverrides on the record, {id: bool}, not served; a tick the account already picks is dropped). Desired = the override, else on when the worker's account picks it, else left alone — the hub never turns off a plugin nobody unticked (a hand-enabled one stays; un-picking an account default stops turning it on, it doesn't disable). After each probe maybe_push POSTs /repo-plugins {enable, disable} when that differs from the report (10 min between attempts at one change; a Settings tick forces it): the sidecar runs claude plugin marketplace add <cwd>/ when the marketplace isn't known (. alone is refused, ./ works), claude plugin install <id> --scope user (enable when installed but off) / claude plugin disable <id> --scope user, with the default account's env (_account_env) — only the cwd marketplace's ids, never an uninstall, 409 on the host sidecar. A guest's computer is never touched. The worker serves repoPlugins / repoPluginsStatus (current | outdated | failed | unsupported — a sidecar from before | none — no marketplace | unknown) / repoPluginsError; GET /api/repo-plugins is the matrix, PUT /api/repo-plugins/accounts/{account} {plugins} an account's picks, PUT /api/workers/{id}/repo-plugins {overrides} a worker's ticks. UI: the Repo plugins section under Skills & agents (RepoPlugins.tsx: an account chip per account, a ✓/✗ cell per worker, "—" when its repo has no such plugin, "update needed" for an old sidecar) and the worker page's Setup rows.
  • MCP servers — the MCP servers the owner sets up for his harnesses (Linear, Sentry, Notion…; first for the Orus devbox, form mcp-servers-on-ai-agent-machines_j8rac9) are the mcp-servers live plugin since 2026-11-26 (~/projects/ai-agent-plugins/plugins/mcp-servers; homelab spec data/log/2026-11-26-ai-agent-mcp-plugin-spec.md, form mcp-servers-as-a-live-plugin_dd5yeg): any harness with an MCP adapter (Claude, OpenCode, agy), per harness:account, owner only. The core's Claude-only half — workers/mcpservers.py, /api/mcp-servers*, LabMcp, Worker.mcpSetup, the old Shortcuts & setup page's MCP servers tab and the machine page's section — is gone. What the core keeps is generic (docs/plugins.md → "Machines, relays and attention"): the sidecar's harness-agnostic /mcp-servers routes (each harness plugin ships its mcp_adapter()), the machines.mcp bridge that reaches them, the relay.serve hub gateway (/proxy/tools/relay/<plugin>/<name>: sign in once on the hub, every machine goes through it), the machine page's machine.detail slot and the machine.attention Needs-you rows. carryover.mcp_servers copies an old /data/mcp-servers.json (and the workers' mcpServerOverrides) into the plugin once it is installed. Not to be confused with the hub's own MCP server (backend/mcpserver/, Settings → AI apps), which is unchanged.
  • Plugin harness hooks (harnessHooks[], since 2026-11-26 — docs/plugins.md → "Harness hooks"): a live plugin's hooks into Claude Code's own hook points. Declarative rules (a tool call's command / output regex → a hint as additionalContext, evaluated by the stdlib sidecar/plugin_hooks.py) or operator-approved .py script hooks, placed by the plugin's where / profiles / workers settings: the lab reads /data/plugins/live-hooks/ (plugins/harness_hooks.py materializes it), a worker gets its filtered copy in the /sync bundle's hooks map (~/.ai-agent-worker/hooks). A guest's computer and a guest's scoped run get only guestAllowed ones. The old core gcloud expiry hook (gcloud_reauth.py) is now the gcloud-reauth plugin (Work workers). SIDECAR_PLUGIN_HOOKS=0 disables — the plugins' pathShims (command wrappers on every run's PATH, since 2026-11-27) ride the same index, bundle, scope settings and switch.
  • The Claude proxy (claudeproxy/, sidecar/claude_proxy.py, decided 2026-11-02 — form claude-proxy-for-workers_rfmh1q): a worker needs no Claude login. Its record's claudeMode is proxy (bills the Homelab's logins — the default for a new pairing) or own (its machine's login — a record from before, and the Orus MacBook by choice); claudeAccounts are the hub accounts a proxied worker may bill (its page's checkboxes; the profile entry's ★ among them is what a new prompt there bills). Each probe compares /health's claudeProxy.hash with what the hub would send (fingerprint(url, sha256(token), accounts, default), computed the same on both sides) and POSTs /claude-proxy {url, token, accounts, default} — or DELETEs it for an own worker. The worker keeps it in ~/.config/ai-agent-worker/claude-proxy.json (0600); a run on one of those accounts launches with ANTHROPIC_BASE_URL=<CLAUDE_PROXY_URL>/<account> and the worker's proxyToken as CLAUDE_CODE_OAUTH_TOKEN (the CLI then talks as a subscription client: the oauth beta, the plan's models). The ★ account's pair also goes into the machine's ~/.claude/settings.json env — a terminal claude there needs no login — and since settings env outranks the process environment (measured on 2.1.312), a hub run repeats its own pair in its --settings flag (with_settings_env; the flag outranks the file). Only the keys it wrote are ever removed, and a value the user had comes back. The hub's route /proxy/claude/<account>/v1/… (outside /api: no trusted-caller gate; Traefik routes /proxy/ on the admin host without Authelia — the homelab traefik.yml) names the worker by its token (worker_for_token), refuses an account it may not bill (403 permission_error) and any path but v1/…, swaps in the account's real access token and streams the reply (httpx, aiter_raw, encoding kept). The token comes from the host sidecar (GET /accounts/{id}/access-token, host only, declared accounts only — never a guest's), cached ≤ 5 min (TokenCache); a stale one is refreshed by the CLI (the one-turn probe), never by us — the refresh token rotates and the lab's own runs share it. A 401 upstream refetches once with ?refresh=1; still refused or signed out ⇒ the login-health monitor hears it (report) and the worker's CLI shows sign it in again from Settings → Logins. Every reply's anthropic-ratelimit-unified-<5h|7d>-utilization/-reset headers feed the account's live usage (usage_poller.observe — the freshest of file / worker / proxy wins). _sidecar_call keeps a claude run's account only when the worker's sidecar says it proxies it (an older sidecar takes its own default), the composer's Log in to send applies to proxied worker runs (workerProxies), and meta.accountSource of a mirrored terminal session is the worker's ★ (terminal_account). A worker whose sidecar predates the proxy reads unsupported until its auto-update.
  • The opencode proxy (claudeproxy/opencode.py, sidecar/opencode_proxy.py, same day, same form): its twin for ChatGPT seats. A worker ticks the Homelab's opencode accounts with a real login (declared in the lab sidecar's SIDECAR_OPENCODE_ACCOUNTS, signed in from Settings → Logins — none yet on 2026-11-02: the ChatGPT seat lives on the Orus MacBook) as opencodeProxyAccounts; its own declared logins are untouched. The hub POSTs /opencode-proxy {url, token, accounts} (same proxyToken). The worker gives each such account a database of its own (~/.local/share/ai-agent-worker/opencode/<account> — never the machine's login) holding a placeholder ChatGPT credential written through opencode's own API (opencode api POST /api/credential --standalone: the proxy token as access, expiry 2100 so opencode never refreshes it), mirrors it like a declared account, and runs it with provider.openai.options = {baseURL: <hub>/proxy/opencode/<account>, transport: "http"} — opencode 2.x keeps its Codex request shape behind a custom base URL (measured on 2.0.32: every call lands on <baseURL>/responses), and http skips its WebSocket attempt. The hub route takes responses[/compact] only, swaps Authorization and chatgpt-account-id for the account's (host sidecar GET /opencode/accounts/{id}/access-token; a token within 4 min of expiry is refreshed by opencode's own auth list boot, never in Python) and streams chatgpt.com/backend-api/codex's reply. Terminal opencode on a worker keeps the machine's database; the lab-held seat's usage comes from the lab sidecar's /opencode/usage (usage.service.remote_snapshots).
  • Liveness (WorkerMonitor, 15 s): /health + an authenticated /sessions ⇒ online / offline / unauthorized (token refused), live in memory only, published as a workers SSE event.
  • Transcripts (FeedMirror, 2 s): GET /feed?since= lists the worker's projects/ (.jsonl + subagent .meta.json), GET /feed/file?rel=&offset= serves byte ranges. The mirror appends what grew, re-downloads what shrank, and keeps the remote mtime (a backfilled old session mustn't read as running), into WORKERS_TRANSCRIPTS_DIR (/data/workers/transcripts) — which is just one more SOURCE_DIRS entry, so indexer/Watcher/parser/costs/ SSE are untouched. It stamps meta.workerSource + meta.accountSource (the worker's account) in one meta save per pass (MetaStore.stamp_many) — the first sync backfills every session the Mac ever had.
  • Routing (route_new_run — see "Profiles → Workers → Accounts"): a new run goes to the composer's worker pick ("local" = the lab; an offline pick is a 409, never a silent reroute), else the default runner of the profile it was sent from — offline, a 409 too, never the lab. (The worker record's autoRoute flag is legacy: it only seeded the profiles.) It bills the pinned login when the worker holds it, else the worker's ★ (a Mac holds one Claude login: the one it was paired on). Continue / fork / interrupt follow meta.worker (stamped by the hub) or meta.workerSource (mirror) — _session_worker; a session can't move runners. pi never runs on a worker.
  • Takeover guard: resuming a worker session whose mirror copy grew in the last TERMINAL_LIVE_S (60 s) with no worker run behind it is a 409 kind: "terminal_live" — a terminal on the Mac probably still holds it, and two writers garble the transcript. The ResumeBox turns it into a confirm and resends with takeover: true.
  • Attached files (runs/attachments.py, sidecar/uploads.py): the composer names an upload services/ai-agent/data/uploads/<batch>/<name>, a path relative to the lab's homelab checkout. Every send (spawn, resume, a live run's inbox, fork) renames each stored file it names to an absolute path: on the lab, its host path (UPLOADS_HOST_DIR — the homelab compose sets ${PWD}/services/ai-agent/data/uploads; unset ⇒ the relative path stays), so a run whose cwd isn't the checkout finds it too. A guest's lab run (a scope naming them in git.user) can't read that store — dontAsk refuses Read outside its project + /tmp, and its scope denies the store outright — so the file is hard-linked into the guest's own folder, services/ai-agent/data/guest-uploads/<guest>/<batch>/<name> (GUEST_UPLOADS_DIR / GUEST_UPLOADS_HOST_DIR, the store's sibling), and named by that host path; attachments.grant gives every guest lab scope a read-only readDirs: [<that folder>] (sidecar → Read(//…/**) allow + sandbox allowRead; pi's --read), so a follow-up into a live run — whose scope was fixed at launch — reads it too (fixed 2026-11-06, Dom's refused image). Never a symlink: read rules follow it back into the denied store. On a worker, which has no such file, the hub first PUTs it to the worker's /uploads/<batch>/<name> (raw bytes, 50 MB cap) and uses the absolute path the worker answers — ~/.local/share/ai-agent-worker/uploads/<batch>/<name> (WORKER_UPLOADS_DIR), outside every repo; batches older than WORKER_UPLOADS_KEEP_DAYS (30) are pruned on the next upload. A worker that can't take the file refuses the send (409 worker_outdated for a sidecar without /uploads, 502 worker_upload) rather than handing the agent a path it can't open. On screen nothing changes: lib/attachments reads a worker-path bullet inside the Attached files block as the same upload (its last two segments are <batch>/<name>), so the thread shows the gallery, never the path.
  • Images a run read (conversations/toolimage.py, sidecar/media.py, technical/ImageWidget.tsx): an image Read stores the bitmap the model saw (base64, often downscaled to ≤ 2000 px) in the tool_result, so GET /api/conversation-image?id=&toolUseId= serves it from the transcript — the mirror's copy for a worker run, a subagent's call through its parent's id, a cleared scratchpad's long after /tmp was wiped. The card previews the lab's own file when it serves one (artefacts, data/, scratchpad) and falls through to that copy; a worker run's paths are never mapped onto the lab's disk (a Mac's /private/tmp/claude-501/… once read as an expired lab scratchpad). Its header opens the shown image in a browser tab, copies the path, and — while the run's worker is online — links Original ↗: &original=1, where the hub reads the path off the tool call (never one the browser names) and fetches it from the worker's GET /media?path= (raster images only, judged by the symlink's target, WORKER_MEDIA_MAX_BYTES 50 MB, refused on the host sidecar). A lab file outside the served roots links its /api/host-file/raw instead, for whoever may open it.
  • Outbox (sidecar/outbox.py, backend/outbox_mirror.py, cli/notify.py): the notify CLI — the one entry point behind notify-done, notify-ask and ask-form — is stdlib Python shipped in cli/ and appended to every run's PATH by the sidecar, which also exports CLAUDE_SESSION_ID. On the lab it POSTs to the hub. On a worker the sidecar exports AI_AGENT_OUTBOX_URL + a per-worker run token, and the CLI drops the same payload into the worker's POST /outbox; the OutboxMirror thread polls GET /outbox on every online worker (2 s), creates the record through the very functions /api/notify and /api/ask run (_create_notify / _create_ask), acks it, and pushes the terminal state (answered / submitted / acted / expired / cancelled) to POST /outbox/{id}/answer, which wakes the CLI's notify wait long-poll on the worker. Ids are minted by the CLI (ntf_/ask_ + 12 hex; the form kind and its frm_ ids went with the hub's form engine, 2026-11-25) so the viewer, the phone and the worker agree. The hub owns what the CLI used to compute: the default url (_conversation_url — worker transcripts included), the notified meta stamp, and final → state: finished (read as running until the turn it is part of ends — see "Conversation "finished" state"). A fourth kind, meta (met_, the conv CLI — see "Conversation resources"), is applied once and ended by its ack (applied); a fifth, askform (afe_), carries an ask-form serve event from the worker's webhook receiver (below) the same way; a sixth, lookup (lkp_, the worker's ai-agent past), is answered in the ack itself (hub.result, conversations/past.py outbox_lookup) — the CLI's long-poll reads it, so a lookup takes one mirror pass (≈ 2 s; 4 s on the worker link). A guest's computer is refused: the answer is the owner's conversations, and one of the owner's workers gets its own profile's only (workers/bound.py).
  • The ask-form mirror (backend/askform/, sidecar/askform.py, frontend/src/business/askform/): the standalone ask-form tool (github.com/GabrielVidal1/ask-form) is the form engine for agents — notify form is gone (2026-10-28), and the hub's own forms/ engine too (2026-11-25: New project, Approvals and Plans are live plugins on the ask-form plugin). Each machine's ask-form serve keeps its forms; the hub mirrors them (askform/store.py, /data/askform.json, one record per form with the machine, meta.session → sessionId, the status/answers, and the link — which only the events webhook or a transcript ever carries, the admin API never returns it). Fed by: the events webhook (serve --events-url; lab → POST /api/ask-form/events on the hub's host port, owner callers only; a Mac → its sidecar's POST /ask-form/events, loopback or the bind address only, queued as an outbox askform item) — created (with the link) → the "📋 title" push, once per form and only for a fresh one (claim_push, 15 min); and the sidecar proxy /ask-form/health|forms[/{id}]|revoke|close (one loopback admin-API call each, ids regex-checked, never a shell) polled by askform/mirror.py (5 s while a machine has an open form, 60 s idle, 5 min when ask-form isn't installed — askform_missing, logged once). Routes /api/ask-form/forms[?session=&status=], /api/ask-form/forms/{id} (the spec fetched on first read, for the recap's labels), …/revoke|close, /api/ask-form/health; guests see their conversations' forms (404 for the rest); SSE askform invalidates QK.askformBase. On a worker, ask-form is installed by hand (install.sh) and told where to post with ask-form setup --events-url http://<bind>:8790/ask-form/events; the cli/ask-form shim only prints that hint when the binary is missing. A push's extra button (--action-cmd) answers on POST /api/notify/{id}/action like an ask does. A pending form always has a link (2026-11-04 — Akira, a guest on her own computer, could not open her form: the home card said "Open its card", the Forms card's Answer did nothing, and she asked the agent to resend it). The link only ever comes from the webhook or from what the agent printed, so three things cover every machine: (1) askform/links.py recover, run by the mirror after each read, files the link of every link-less form from its conversation's own transcripts (thread + subagents; tree.form_links, AskFormStore.adopt_link — fills a form that exists, never creates one, never moves it to another session, never replaces a webhook's link); (2) a guest computer's sidecar (sidecar/askform.py wire_events, from a startup thread, link workers only) points its ask-form serve at its own /ask-form/events by editing serve.env (never ask-form setup, which re-picks relay/mode) and restarts it once no form is open (a restart would cut an agent's ask-form wait; marker ai-agent-events next to serve.env); (3) in the thread, a create whose output named no id (the agent sent it to a file) is joined to its mirrored form by session + title + time (matchCreatedForms, Conversation.tsx createdFormIds), so its card has the link and Revoke. The Forms card's Answer pill opens the form's page in a new tab (the card jump is the row). In the app (2026-11-05): a form whose machine lets the app frame its pages opens over its conversation instead of in a new tab — the push (push_new → /conversation/<cid>?form=<id>, a guest's on their host) and every Answer (thread card, Forms card, Waiting rows; from home the conversation opens behind it — askform/useOpenAskForm.ts). ?form=<ask-form id> → forms/components/FormDock.tsx (mounted once in the Layout, so on any page) → askform/components/AskFormFrame.tsx (lazy chunk): the form's page in a sandboxed iframe, full screen on a phone, a 760 px panel wider; bar = title, copy link, open in a new tab, close; the page's own brand line hides. The page and the app talk over postMessage (askform/frame.ts; ask-form docs/how-it-works.md → "In another app's frame"): ask-form:page {page, id, status} from the frame (checked: our iframe, the link's origin), ask-form:theme {scheme, tokens} back — the app's live palette (profile accent, a guest's own, tint, dark/black), so the form wears it; mockups keep the machine's brand. The first closed after a form, or the mirror seeing the form leave pending, closes the panel and scrolls to the form's card. No word in 4 s (a browser that refuses even partitioned third-party cookies) → an Open in a new tab line. Who may frame is the machine's call (ask-form serve --embed-origins, v0.16.0+): the mirror reads each machine's /ask-form/health every 10 min (check_embed, embedOrigins → the records' embedOrigins, which the viewer checks against its own origin) and asks a machine that doesn't list the hub's two hosts (hub_origins: AI_AGENT_VIEW_URL, GUEST_PUBLIC_URL) to add them — POST /ask-form/embed → the sidecar's wire_embed (its serve.env, the owner's own entries kept, a restart once no form is open; old for a serve before v0.16.0, which upgrades itself). Minimize (2026-11-06 — answer, go check something in the thread, come back): both form kinds' top bar has a chevron (pending forms only) that tucks the form into a floating pill (icon, title, a breathing amber dot, a × that only hides the pill) — forms/formDock.ts (one form at a time, zustand, the pill persisted for a reload) + FormDock. ?form= still opens a form; the dock adopts the URL's id, minimizing drops the param, and the pill follows every page until the form leaves pending (the same mirror signal that closes the frame), its × or another form opening; its tap goes back to the form's conversation (conversationId, else the page it was opened on) with ?form=. An ask-form frame lives in the dock, not the page: minimized it stays mounted, hidden (FrameShell — its own portal, CSS states .form-dock-* in index.css, because the ui Modal unmounts on close and a moved/remounted iframe reloads), so nothing typed in it is lost. The answered-while-up jump to the card goes through the page (useDockJump, which has the thread's useFormJump). The pill sits above whatever is docked at the bottom — any .composer-frame (never over send) and any data-form-pill-floor="<px>" box (the conversation thread: clear of its 3× / context / Interrupt corner row) — inside the box above the navbar.
  • Who gets which prompt shortcut (the prompt-shortcuts plugin's page; the composer's side is lib/shortcutRunners.ts): each shortcut of the owner's library carries its audience — shared (shared: true, every runner, workers paired later included) or a set of runners ("local" = the lab, worker ids; [] = none, a guests-only one), plus guests. The plugin's page is the audience matrix (a cell per runner and one for guests, a Preview as strip); the skills' matrix with the same columns is core, Settings → Skills & agents (/settings/setup, pages/SkillsSetup.tsx): a worker cell is the lab sync (labSyncOverrides, see "Lab sync"), the guests cell is guestDefaults.sharedSkills — and below it Repo plugins (a repo's own Claude Code plugins per account and per worker, see "Repo plugins"). Users → Every guest and the worker page link there. The composer resolves the runner its prompt will land on (the "Runs on" pick, else the account's online worker, else the lab) and offers the shared chips first, then that runner's (shortcutsForRunner; a chip that doesn't say is shared, a non-shared one without runners the lab's); switching runner seeds the newly revealed chips' default-on cascade. The resume box uses the session's own runner.
  • Two built-in chips, and an always-on notify line (since 2026-11-06): Changes ⇄ No changes (worktree, commit + push, ship the repo's way: a deploy on the lab, a PR elsewhere — the prompt-shortcuts plugin's built-in; its id changes and off line are lib/guidelineDag's CHANGES_SHORTCUT_ID / NO_CHANGES_GUIDELINE, which a guest's No project run keys on) and Form (clarifying questions in an ask-form through the clarifier, mockups for UX/UI — the ask-form plugin's chip), both shared and on by default. They replaced Worktree / Commit & push / Deploy / Open PR / Notify / ask / form, which were on together in almost every prompt (homelab data/log/2026-11-06-guidelines-usage.md). There is no Notify chip: every composed prompt (owner and guests, any runner, spawn and follow-up, even with the guidelines master switch off; not a slash command) ends with NOTIFY_GUIDELINE (lib/shortcuts.tsx → withNotify, applied in richComposePrompt), and the thread's prompt pills leave that line out. Since 2026-11-23 it asks for the closing ```notify block (see "The closing push" above) instead of a notify-done call. The Macs only notify when told (their repos' CLAUDE.md say nothing about it), which is why it is in the prompt rather than left to CLAUDE.md.
  • A worker's skills in the composer (sidecar/skills_list.py, GET /api/workers/{id}/skills, useWorkerSkills): when "Runs on" resolves to a worker, the mention list is that machine's skills — its sidecar lists the default cwd's .claude/skills/ then the user-level <config>/skills/ (where the installer links notify), the hub proxies it with a 60 s cache (empty for an offline or pre-/skills worker), and the lab's catalog and cron agents are not offered there because they don't exist on the Mac.
  • Exit watcher: one /sessions baseline per runner (lab + each worker); an unreachable runner keeps its baseline, so a Mac falling asleep never reads as "all its runs exited".
  • Frontend (lib/workers.tsx): WorkerSelect composer chip (only once a worker is paired; auto shows the runner it lands on — the next one up while the default is down; red only when every runner the profile could use is down — the send is refused, Send later is the way out), WorkerBadge on cards / meta row / resume toolbar, the worker's page under Settings → Machines (/settings/machines/<p>/<worker>; /settings/workers redirects there), and the home WorkerOfflineBanner (the scoped profile's workers only). A swipe or its × dismisses a row for that outage on every device (server-side ui-state ai-agent-dismissed-outages, keyed id:status:lastSeen — lastSeen only moves while the worker is reachable, so back online then down again is a new key and the row returns). A guest gets the same banner for their own computers (/api/me/computers, offline or disconnected, never paused or still connecting; tap → My computers): " is offline (seen …) — conversations can't start on it." — no fallback, a send there is refused (since 2026-11-06).

Projects on a worker (projects/worker_projects.py, projects/merges.py)

A lab conversation is filed under ~/projects/<slug> when it edits a file there. A worker has no such layout — Akira keeps games in ~/PROJETS/wall-e game/far-waste, the Orus repo is ~/WORK/ORUS/orus with worktrees beside it (orus-ins-2308) and inside it (.claude/worktrees/…) — and the hub can't look at its disk. So since 2026-11-06 a worker conversation's project is deduced from where it wrote, per worker, over all its conversations (Gabriel's form worker-projects_g1atn9):

  • The parser keeps writtenDirsAuto (dirs of Edit/Write files and of the Bash hook's changed files), gitRootsAuto (the hook's repos[].root, plus main — the hook names a linked worktree's main checkout since this change) and worktreeAddsAuto (git worktree add commands → path + repo; conversations/written.py). PARSER_VERSION 42.
  • WorkerIndex: git roots are exact; a worktree folds into its repo (inside .claude/worktrees/, a worktree add, the hook's main, or a sibling <repo>-<x> of a known root — not one whose sessions sat on main/master); a written dir outside every root gives the folder above its shallowest source-like segment (src, docs, apps, packages…), else the session cwd. A candidate holding others is a container (~/PROJETS, ~/WORK/ORUS), never a project; home, ~/Downloads, ~/Desktop, ~/Library, dot-folders and temp/scratch never are.
  • A conversation that wrote nothing is filed under its cwd's project; a worker conversation with no project at all gets its profile's home project, else none (never the homelab root).
  • Slug <folder>@<worker id> (orus@a8ed565255ed); an owner worker's root named like a lab project is that lab project (~/projects/bffr on the Mac); a guest's computer never maps onto the owner's projects. /api/projects lists them beside the lab's (worker, path, mergedFrom); a guest sees their own computers'. /api/project?slug= serves a synthetic detail (path, worker, costs, the commits its conversations made — no files: the disk isn't ours).
  • merges.py (/data/project-merges.json, GET/PUT /api/project-merges, owner only): {lab slug: worker slug} folds a lab project into a worker one — applied last, so the profile home project and meta stamps follow. orus-monorepo (the lab clone, stale since the Mac took over) → orus on the Orus MacBook. A merged lab slug opens its worker project and leaves the gallery.
  • Frontend: lib/workerProjects.ts — pills and filter chips read name · worker (useProjectLabel, a child component so only project pills read the list), the Projects card swaps the version chip for a laptop chip with the worker and the URL line for the folder (~/…), the project page shows Worker / Folder / Also and hides Files and .env.
  • Cost: the registry rebuilds on a transcript change, but each worker's index is kept while its inputs' fingerprint holds (~10 ms warm; ~150 ms when the Orus Mac's inputs change).
  • The card — read off the transcripts (projects/worker_meta.py, since 2026-11-06; Gabriel's form project-metadata-on-guests-computers_2l6bxi: transcripts only — no call to the computer, no AI summary, every worker). A background thread (ScanThread, started in main.py) follows every worker transcript by byte offset and keeps, per transcript: the last whole copy of each package.json / README.md / CLAUDE.md / index.html (a Read's toolUseResult.file, a Write's content, an Edit's originalFile with the edit applied, a cat package.json in a Bash command), the npm packages the touched source files import, the file kinds and marker files touched, and the URLs mentioned. project_meta folds a project's scans onto its root (worktrees through WorkerIndex.rewrite, latest copy wins) into the lab card's fields — description (package → README → CLAUDE.md → index.html), stack (catalog.stack_tags, shared), version, scripts, keywords, and the site: homepage, else a mentioned URL whose host's first label (the repo on *.github.io) holds every word of the name, seen twice, a domain of its own beating a SaaS tenant (orus.eu over orus.sentry.io) and the shortest label beating a Vercel preview, else og:url. The name stays the folder's (a template's vite-project would rename it). The detail adds README, CLAUDE.md, indexMeta, an absolute ogImage and seenAt (file → when the copy was seen; the page dates the README / CLAUDE.md with it). A request only reads the scans; the first pass after a start reads every worker transcript (~10 s for 801 transcripts / 1.2 GB on 2026-11-06), later passes only what grew.

Cron jobs: the plugin, and what the core keeps (since 2026-11-28)

Every cron job — the owner's and each guest's own — is the cron-jobs live plugin's (~/projects/ai-agent-plugins/plugins/cron-jobs, seeded, managed with defaultForGuests; Gabriel's forms move-ai-agent-cron-jobs-into-a-plugin_u0wa6b and cron-scheduled-in-the-cli-and-mcp_x4nk83). It owns the store (jobs.json in its shared dir — the core's /data/cron-jobs.json, carried over once by plugins/carryover.cron_jobs, history unchanged), the every-minute tick (each job's minute claimed in that store under flock, so the blue-green cutover's two backends never both fire a job; a job that waits on the EVOX2 fires from a detached jobs/fire.py), the owner's page (Settings → Cron jobs, /settings/p/cron-jobs/jobs — /settings/cron redirects, ?runner= / ?job= kept) and the guests' (Settings → Scheduled jobs, « Tâches planifiées », /settings/p/cron-jobs/mine — /settings/jobs redirects; the page's unless: automation.manage hides it from the owner), and the CLI / MCP: ai-agent plugin cron-jobs ls|show|prompt|add|edit|pause|resume|run|rm and the plugin_cron-jobs_* tools (every command mcp: true). /api/cron*, /api/me/cron*, ai-agent cron (it now only says where it went), run_cron_job, set_cron_job, browse kind=cron and the scheduled-jobs core skill are gone; the plugin's cron-jobs skill replaces the latter. A connection bound to a worker gets none of it (its scopes have no plugins.use). A guest's limits (maxJobs, the model a new job starts on) are their grant's fields, else the plugin's settings, else the carried guestDefaults.cronLimits (limits.json), else 5 / sonnet.

What the core keeps — contracts, no routes:

  • meta.cron — {id, name, guest?, fallback?, firedAt, project?, email?, mailHtml?, plugin?, delivered?}: the card's pill (ConvMetaBits, linking to the plugin page with ?job=), auto-archive, telemetry's cron origin, the analytics / left-to-do filters. runs.start takes a cron: {id, name} and stamps it (+ fallback).
  • runs.guest (POST …/hub/runs/guest, owner-only, operator approval, runs/guestjob.py): a guest's job run as that guest. The plugin names only the guest, the prompt, the model word, the job ({id, name}), its project, email / mailHtml and the owner's extra programs; the scope, the lean allowlist, the budget and the EVOX2 probe are built by the core from the guest's record (below).
  • Delivery (runs/guestjob.deliver_sweep, a 20 s thread): it reads only the run's stamp — and mailing a page of a guest's project is a power no plugin bridge gives — so it stays core.
  • « Discuter » (POST /api/cron-runs/discuss {sessionId, prompt}, cron.own, guests only — was /api/me/cron/{job}/discuss), from the run's page (business/conversations/components/DiscussBar.tsx).
  • runs.cron (plugins/cron_bridge.py): the readers that need jobs ask the plugin's provider — index (auto-archive's archiveOnSuccess, the agents catalog's cron runs, an agent page's "its cron job"), list (the week's budget: firings × the median of its runs), get, create (the agents page's Schedule, through agents.run). Cached 30 s and refreshed off-thread; no plugin ⇒ an empty list.
  • core/cronexpr.py (the matcher: the plugin scheduler, the manifest validator, the budget) and agents/runconfig.py (an agent file's frontmatter, below — Run now on the agents page, runs.start's lean).
  • The context.write bridge's create: true makes a missing .claude/agents/<name>.md (a new owner job's stub) — nothing else.

An owner job's run config lives in its prompt file's frontmatter

A scheduled job has no composer to pick a harness/model/effort in, so it says so itself: the leading YAML block of .claude/agents/<job>.md carries harness (claude|pi), model (a family alias or a full id), effort (low|medium|high|xhigh|max, or none for no flag), thinking (true|false) and account (personal|work — see Claude accounts). The plugin reads them (its copy of agents/runconfig.run_config, through context.read), passes them to runs.start — the composer's own send path — and shows the resolved config as chips. Every homelab job currently declares claude + sonnet + no effort.

Two deliberate properties: the keys are a subset of Claude Code's own agent frontmatter (model means the same thing there), so a job's prompt file stays a usable .claude/agents subagent; and an invalid value is dropped, not raised — a firing on the defaults beats a job that stops firing, and the missing chip in the UI is the feedback. The store's per-job model field is now only the fallback for a file whose frontmatter sets none.

Lean runs, the command allowlist and the local fallback

A cron job re-read ~69k tokens of context on every turn before 2026-11-02: Claude Code's own prompt (~26k) plus CLAUDE.md, the memory index and the skills/agents catalogue (~43k), against a job of 1–25k. A 3-turn lab digest was $0.35 at list price, $0.07 lean (homelab data/log/2026-11-01-cron-local-models.md). Three more frontmatter keys:

lean:                      # or `lean: true` — defaults, no allowlist
  allow: [mail-recap, mail]  # the only programs its Bash may call (paths OK)
  tools: [Bash]              # claude names; default Bash, Read, Write
fallback:                  # jobs on a local model only
  harness: claude
  model: sonnet
  wait: 10                 # minutes the EVOX2 may take to come up
  • lean (the frontmatter → runs.start's lean → _send_message(lean=) → the sidecar's valid_lean, meta.lean): claude gets --system-prompt (core launch.py LEAN_PROMPT: unattended, today's date, cwd, tool output is data) + --tools + --setting-sources "" + --strict-mcp-config + --disable-slash-commands, and CLAUDE_CODE_DISABLE_CLAUDE_MDS=1 / CLAUDE_CODE_DISABLE_AUTO_MEMORY=1 in its env — the CLAUDE.md walk-up is not a settings source, the flag alone leaves 10k tokens of ~/homelab/CLAUDE.md in. The sidecar --settings (stop guard, Bash diff, inbox) still apply; run extras (the clarifier, portable agents) don't ride along. pi gets the runner's --lean (--no-skills --no-context-files --no-extensions --no-prompt-templates, the same prompt, --tools mapped to pi names — WebSearch/WebFetch have none). So a lean prompt must be self-contained: no skill to "invoke", and no "canonical ~/homelab" wording it would follow out of a test sandbox. A continue is a normal run.
  • allow: every command of a Bash call must start with a listed program or a read-only one (cat, jq, grep… SAFE_CMDS). Claude: the sidecar/allow_guard.py PreToolUse hook, first on Bash; pi: the same parser in harness-pi's runner/extensions/folder-permissions.ts (PI_ALLOW_CMDS). Quoted text and heredoc bodies are skipped, but $(…)/backticks inside them are checked — keep the two parsers in step (test_claude_args.py lists the cases). Not Claude Code's own dontAsk + Bash(<program>:*): it refuses every file redirect and every heredoc, i.e. most of a digest. Never allow an interpreter (python3, bash, node) — it would allow everything. ALLOW_GUARD_LOG=<file> in the run's env logs refusals.
  • fallback (runs.start's fallback → plugins/hubruns.local_ready): a lab job on a pi/opencode local model is probed from its own process (the plugin's detached jobs/fire.py, so the tick never waits) by the sidecar's POST /local-ready (provider-evox2's local_ready.py): Wake-on-LAN, then a 1-token request — the one that loads the model in llm-server's router mode — retried every 20 s up to wait. A box that never answers, or a model that won't load because another GPU job holds the VRAM, fires the job on the fallback harness/model instead (lean kept), lastStatus ok (fallback: …) (amber "ran on fallback" chip), meta.cron.fallback. Run now skips the probe.

Where an owner job runs: the store's worker field

Unlike the run config, the runner is a store field (worker, the page's "Runs on" select, ai-agent plugin cron-jobs edit ID --worker W), because it is machine pairing, not prompt content. null = the lab's own sidecar; a worker id pins every firing to that paired machine (e.g. a PR-watch job on the Orus MacBook, where gh and the work login live). The plugin passes it to runs.start as an explicit runner pick ("local" when unset), so a job never auto-routes, even with account: work in its frontmatter. Workers run claude only. The prompt file is always read on the hub and sent as text. The run uses the worker's own login and default cwd, and notify-done from there goes through its outbox. A firing while the worker is offline is refused (worker_offline) and recorded as the job's lastStatus. It never falls back to the lab. Unknown ids are rejected when saved (workers.read). The page shows one tab per runner (Homelab + each paired worker, plus Guests); ?runner=<id> selects one.

A guest's own scheduled jobs (runs/guestjob.py + the plugin)

Since 2026-11-04 every guest may schedule prompts of their own (Settings → Tâches planifiées — the plugin's mine page; or by asking a conversation — ai-agent plugin cron-jobs … through their CLI broker and the plugin's shared:cron-jobs skill). Gabriel's calls: forms guest-scheduled-jobs_2lxwmr and guest-scheduled-jobs-round-2_xupa7m.

  • Same store, different shape. A guest job is a record with owner: <uid> and the prompt in the record (prompt), no promptFile — a guest can't write the lab repo. Its id is <uid>-<slug>. The plugin's actions all run runAs: owner and tell a guest from the owner by AIA_USER_CONTEXT.requester: a guest reaches only their own jobs (404 for the rest), never allow / effort / worker; the owner sees and edits every one (the page's Guests tab), and goes past a guest's limit.
  • One word of run config, model: sonnet (the default since 2026-11-27 — Inkling looped on one command until its runs were stopped; the carry-over moved every guest job still on qwen to Sonnet, PR #23's decision) = claude; qwen = pi + the EVOX2's local model (GUEST_JOB_QWEN_MODEL: Inkling 2 Mini since 2026-11-23, Qwen 3.8 before — the stored word stayed qwen; the UI says "Inkling 2 Mini"), $0, probed with /local-ready and run on Sonnet when the box can't take it within 10 min (that run counts toward their budget). Both always lean (guestjob.run_config): Bash allowlist web, notify-done, mkdir, mktemp (+ the read-only tools) plus allow, programs only the owner adds per job (shown locked to the guest — veille pharma's veille-pharma); Sonnet also gets WebSearch / WebFetch. effort is the owner's too. pi has no web tools, hence cli/web (web search = DuckDuckGo lite, web news = Google News RSS, web fetch = Jina Reader, else the raw page) on every run's PATH.
  • Runs as the guest (runs.guest → guestjob.fire): meta.owner = them, meta.cron.guest, their scope (guestjob.scope_for_job: writes in the job's project when they hold chat there, else ~/.local/share/ai-agent/guest-jobs/<uid> — the sidecar makes it on the first run, SIDECAR_GUEST_JOBS_DIR), a Sonnet run through run_as_guest (their own login first, else under their budget). A scoped pi run is now possible (lean only): the sidecar appends the scope's prompt to the lean one and passes --read <cwd>:/tmp → PI_PERM_READ, and the permissions extension also catches ~/…, $HOME/… and .. paths. Every scoped run's env carries AIA_GUEST.
  • Limits (the grant's maxJobs / defaultModel, else the plugin's settings, else the carried guestDefaults.cronLimits): maxJobs (5); a schedule fires at most once an hour (one minute value). The owner gets a push for every job a guest creates.
  • The result is the final reply: guestjob.deliver_sweep (a 20 s thread) finds ended runs not yet meta.cron.delivered, pushes the first ~280 characters to the guest (_create_notify on the session — their feed and devices) and, with email, mails the whole reply as light HTML over SMTP_*.
  • A designed mail: mailHtml (since 2026-11-27, Gabriel's ask for Cel's Meta recap — charts, rich HTML): a .html file of the job's project, a relative path (clean_mail_html: no / start, no .., no backslash; guest and owner may set it — ai-agent plugin cron-jobs add|edit --mail-html PATH, the owner's edit works on a guest's job; the firing carries it on meta.cron). guestjob.mail_html mails it as the HTML part when it resolves (realpath, re-checked on the open fd via /proc/self/fd) inside PROJECTS_DIR/<project>, the guest still holds chat there, it's a regular file ≤ 1 MB and its mtime ≥ the run's meta.cron.firedAt (stamped by guestjob.fire) — else the light render. <!--reply--> → the reply rendered (_markdown_body), <!--url--> → the conversation link; no <!--reply--> ⇒ reply + link before </body>. The text part stays the reply. Charts as images (Cel reads on Proton: remote images blocked, embedded ones shown): each <img src="cid:NAME"> (a plain file name) is the file NAME next to the page, attached inline (mailer.send(images=…) → multipart/related, Content-ID <NAME>) — png/jpg/gif, ≤ 2 MB, ≤ 12, same containment + freshness rules; one bad image drops the whole page (light render instead).
  • A run is read-only to its guest (access.can_send → only stop); the conversation page swaps the reply box for DiscussBar — « Discuter » (POST /api/cron-runs/discuss) starts a normal (not lean) Claude conversation quoting the result, in the job's folder with its scope (meta.cronChat — {id, from, name, project?}), which they continue as usual — read off the stamps, the job itself isn't needed.

Performance: what agents and their processes cost (backend/perf/, sidecar/procstats.py)

The Performance dashboard answers "which agent — and which command it ran — is eating the box", on the lab and every paired worker. Owner only — a guest gets their own sessions' slice of it (and of Storage) on their Stats page: see "A guest's Stats" under Guests.

The pages are a live plugin (since 2026-11-26): the performance plugin (ai-agent-plugins/plugins/performance) draws the Performance and Storage dashboards (/plugins/performance/performance, /plugins/performance/storage — /dashboards/performance and /dashboards/storage redirect there, else to the Dashboards overview) and the conversation's two Details cards, CPU & RAM (conv-perf: now, totals, its life with the prompts as ticks, heaviest commands, left running) and On disk (conv-storage), through plugins/hubperf.py: perf.read (GET …/hub/perf/live, history, conversations, commands, conversation/{sid}?series=10m,life, conversation/{sid}/storage, storage, storage/history, storage/writers, storage/config, settings — the /api/perf/* answers, live and storage plus profiles and guestNames) and perf.act (POST …/hub/perf/kill, keep, settings, storage/rm, storage/scan, storage/config; the plugin's own handlers only), both owner-only and operator-approved; the Hub section reads …/hub/telemetry/hub (telemetry.read). The retired core Details card ids (perfLive, perfTotals, perfLife, perfCommands, perfLeftovers, storage) map onto the two slots (DETAIL_CARD_RENAMES). Since 2026-11-27 the header's two chips are the plugin's too: its conv-chips slot in conversation.header (HeaderPluginSlots, inline at the end of the meta line, hidden until the frame first sizes itself) draws the CPU chip (live CPU · RAM, else peak RAM · CPU time) and the On-disk chip (from 50 MB, amber from 1 GB), each opening the plugin's page; it polls while the conversation runs (CPU 5 s, disk 30 s) and reads a finished one once. Core's PerfChip / StorageChip, their useConversationPerf / useConversationStorage hooks and the Performance eye switch are gone (the plugin's Performance chips switch replaces it). Everything else stays core: backend/perf/ (poller, store, storage records, every /api/perf/* route), the Bash cards' cost strip and playback (CallCost, CommandPlayback) and the guest Stats' perf sections. The details slots' update carries drawerOpen (a closed drawer's slots stop polling) and prompts (each prompt's epoch s).

Where the numbers come from. sidecar/procstats.py (GET /procs) scans the process table when asked (/proc/<pid>/stat, one read each, ~50–90 ms for ~800 processes; psutil on a Mac — slower, so the hub polls a worker every 15 s, the lab every 5 s). It sorts processes three ways:

  • agent roots: the sidecar's own pidfiles (logs/<sid>.pid) and every Claude config dir's live-session registry (<dir>/sessions/<pid>.json — terminal sessions too, entrypoint tells hub from terminal), pinned to their start-time;
  • a run's tree: every process whose nearest agent-root ancestor is that root (another root starts its own tree);
  • by environment: everything a session starts inherits CLAUDE_SESSION_ID (the sidecar's) or CLAUDE_CODE_SESSION_ID (the CLI's), so a process that left its tree (setsid nohup, a dev server whose shell exited) still names its conversation — detached while that run lives, a leftover once it ended. Read once per process (cached on pid + start-time).

CPU is the tree's cumulative time (each live process's own + the cutime/cstime of children it already reaped), so a tsc that ran and exited between two scans still counts; memory is RSS (over-counts pages shared between processes — fine for "which is heavy"). Claude's Bash-tool shells (bash -c "… eval '<cmd>' …") are labelled by the command they run (command_label: first real command, past cd/export/VAR=/until…), with their whole subtree's CPU and RSS — those kind: "tool" rows are what the Heaviest commands ranking groups.

Storage (perf/store.py, its own perf.db beside ai-agent.db so the 5-s writes never queue behind the indexer): perf_samples per poll (48 h), perf_minutes rollups (30 d), perf_runs one row per agent process (cumulative CPU + peaks, forever — a conversation's totals are its rows summed), perf_procs one row per process seen (Bash-tool rows forever, the small rest pruned after 30 d). perf/poller.py is the clock (poll, roll up each minute, prune hourly, auto-kill every 5 min); perf/views.py the dashboard reads, perf/conversation.py one conversation's (the plugin's header chip + drawer card, /series for its timeline).

Leftovers and the auto-kill. /api/perf/kill → the runner's /procs/kill, which re-scans and signals (SIGTERM, then SIGKILL after 3 s) only processes it still attributes to that ended conversation — never a live run's tree, never a recycled pid. The auto-kill (/data/perf-settings.json, default on, 24 h) counts from the first poll that saw the process as a leftover, not from when its conversation ended, so a fresh install never kills on sight. Exempt: a row's Keep (perf_procs.kept) and keepLabels (opencode, ask-form-relay, ask-form serve by default) — shared daemons that merely inherited a session's environment: opencode serve --service is started by whichever opencode run comes first and serves every later one; killing it would break a live run. Add a label there for any other daemon an agent starts on purpose.

Split by profile (since 2026-11-06, perf/scope.py): the Performance and Storage pages carry the Personal / Work / Guests / All switch the other dashboards share; every perf read takes the same ?account=profile:<id> (unset / all = everything, so the conversation views are untouched). A run — its tree, leftovers, history band, commands, the disk items and writes it made — is its conversation's profile (ProfileStore.resolve like of_meta: a guest's run on the Homelab is Guests', a pinned meta.profile wins); a session with no metadata (a terminal claude on a Mac) and a disk item no session claims are their machine's. A machine (card, whole-box line, filesystems) shows under the profile that lists it; a guest's own computer under Guests, and Guests also shows the Homelab (where the hub runs their conversations). A machine card's agents add up only the scope's runs; its host stays the whole box. A machine hosting a run of the scope shows too (a Work run pinned on the lab), and history?runner= keeps a machine picked by name. It is the conversation's profile, not the seat it billed — CPU and RAM aren't money, so countsInScope's totals rule doesn't apply. Leftover settings stay global.

Guest pills (since 2026-11-06, form guest-pills-on-dashboards_aynehp): every perf row says whose it is — guest on a run, leftover, band, command example / top entry, conversation row, writer and storage conversation (Scope.guest: guest_owner(meta), else the guest whose computer it ran on), guests on a command (heaviest first) and a disk item, owner on a guest's computer (machine card, storage runner). The plugin's pages put a guest pill (avatar + name, from the bridge's guestNames) on each — they show in Guests and in All, since only those views hold guests' rows; the Homelab card and a command row stack avatars. Tapping one narrows the page to that guest: its own Guests scope with that guest picked (the page's guest chips; since the plugin move the pick is the page's own, no longer shared with the Guests home), sent as guest:<uid> items (Scope.only: it narrows Guests only — the Homelab stays, other guests' computers go).

In the conversation: the header's CPU and On-disk chips and the Details drawer's CPU & RAM card (now, totals, its life, heaviest commands — a run with its toolUseId is a tap from its Bash card — and what it left running) are the performance plugin's slots (above). The Bash cards' cost strip imports only perfFormat.ts / perfQuery.ts: a module shared between the root chunk and a lazy one lands whole in the root chunk, which must stay under the PWA precache's 2 MiB.

A worker reports once its sidecar has /procs (it auto-updates to the deployed commit); before that its card says so (unsupported, a 404).

The call probe: what each Bash call cost, exactly (agent-probe, sidecar/callprobe.py, backend/perf/calls.py)

The 5-s /procs samples (above) see a process only if it lives through a scan and can't say which card a shell was. The call probe records, per tool call, every process it started and what each cost, and each turn boundary — none of which the agents keep. It is the standalone agent-probe binary (GabrielVidal1/agent-probe, ~/projects/agent-probe, public, Go, MIT) — claude-probe's successor, generalised from Claude Code to opencode, Codex and pi too: anyone can run it (report, top, a status-line segment); the ai-agent only reads what it recorded.

  • Records: the same call / mark / storage shapes as claude-probe's, plus agent (claude-code | opencode | codex | pi) on each. A shell no hook announced (an agent without hooks, a missed one) is still recorded, adopted: true, under the session id <agent>:<pid>@<start> when the agent process has no hook session. Marks no longer carry the plan / usage reading: calls.fill_marks derives both from the hub's usage history (as derived_marks does for conversations from before the probe).
  • How it attributes: its hook (agent-probe hook, on PreToolUse / PostToolUse Bash, UserPromptSubmit, Stop, SubagentStart/Stop; prints nothing — opencode gets a plugin, Codex hooks.json, pi an extension) hands the daemon the ids Claude Code gives every hook — tool_use_id, prompt_id, and agent_id / agent_type inside a subagent — and its PID chain; the daemon takes the session's claude's new bash -c "… eval '<cmd>' …" child whose command matches (rtk's rewrite stripped — the post hook sees the command after rtk, the pre hook before), else first in, first out.
  • Sources (a record says source: kernel | sampled): Linux — a CO-RE eBPF program embedded in the binary (task_newtask, sched_process_exec/exit, an fentry on acct_collect for the image's own peak RSS), loaded by the user's daemon under the file capabilities sudo agent-probe setup-kernel puts on the root-owned /usr/local/bin/agent-probe (CAP_BPF + CAP_PERFMON, dropped right after loading; only the user's own agents traced). Not a kprobe: Debian's perf_event_paranoid=3 refuses perf events to anything below CAP_SYS_ADMIN. macOS — no setup: kqueue EVFILT_PROC gives fork / exec / exit with the exit status for any same-user process (undocumented, self-tested at start), proc_pid_rusage read on the zombie gives exact CPU, lifetime peak footprint and disk I/O — unless the parent reaps first (then the last 40-ms sample, the process flagged not exact). Research: conversation db57e5eb on the personal Mac. Fallback — /proc sampling of the call's subtree.
  • Daemon: one per user, started on demand by the first hook (exits after 30 idle minutes) or kept up by the sidecar (daemon --idle 0); store ~/.local/state/agent-probe/probe.db (macOS ~/Library/Application Support/agent-probe), socket ~/.cache/agent-probe/probe.sock (macOS ~/Library/Caches/agent-probe/probe.sock) — fixed paths, never $XDG_*, so every session's hook finds the same daemon (AGENT_PROBE_SOCK / AGENT_PROBE_STATE_DIR override them).
  • The runner's side (sidecar/callprobe.py): finds the binary (SIDECAR_AGENT_PROBE, /usr/local/bin, ~/.local/bin, PATH; missing, it fetches the latest release from SIDECAR_AGENT_PROBE_RELEASES, checksum-checked — how workers get it; SIDECAR_AGENT_PROBE_FETCH=0 turns that off; the old SIDECAR_CLAUDE_PROBE* names still work). Once, while claude-probe's store exists and agent-probe's doesn't, it stops claude-probe's daemon (SIGTERM to the pid its GET /health names) and runs agent-probe migrate — record ids kept, so the hub's perf_cursors carry on; a failure is only logged. Then agent-probe install --config-dir … for every account (claude-probe's # claude-probe hooks are replaced in place; the hooks / plugins of every other agent on the machine are set too; the Python probe's are taken out), keeps the daemon up, and answers the hub's GET /callmeta from the daemon's socket or agent-probe export.
  • Hub (unchanged contract): perf/poller.py pulls /callmeta with each /procs poll (a runner whose store restarted from id 1 is re-read) into perf.db — perf_calls, perf_call_procs, perf_call_parts, perf_marks; perf/shellsplit.py (agent-probe has the same in Go) puts each process under its part of the command line. The Heaviest commands rankings and the drawer read only these: sampled Bash shells (perf_procs kind = 'tool') never rank and are pruned a day after they're last seen (the leftover auto-kill still reads them); the programs ranking keeps the samples of what runs outside Bash calls (in_tool = 0: claude itself, MCP servers, a browser). Marks are measured only (Gabriel's choice): account-wide, whole percents — claude-probe recorded them live; agent-probe's marks, and conversations from before the probe (start/end only), get the reading and plan derived from the usage history.
  • UI (switch Call cost, owner only): components/CallCost.tsx — the Bash row's strip (CPU · peak, GPU, red exit N, a pulse while running, ~ when sampled) and What it ran (CallParts.tsx, its own chunk). Looked up by tool_use id, so a subagent's cards find theirs.
  • Command playback (switch Command playback, Content, on by default — Gabriel's picks, 2026-11-09, form bash-command-playback_30tavz): components/CommandPlayback.tsx types a plain Bash call's parts out under its row, one line each ($ part, | part after a pipe, || part for a fallback), terminal-style, then ✓ + wall time, or ✗ exit N + wall time and the output's last 3 lines under the part that failed; a part that never ran gets —. Builtins are left out, and a command with fewer than two parts keeps its row alone. The parts are the record's components (the query also runs with Call cost off — useCallRecord vs useCallCost) and, before it lands or for a guest, lib/shellSplit.ts (a port of perf/shellsplit.py split(); its test mirrors SplitTests). Pace = the call's own, compressed (hold(s) = 250·log10(1+10 s) ms, capped at 1 s): a part types once it started, after the line above finished typing. Live it never runs ahead of the probe's last poll: a part that hasn't started waits, a running one shows its elapsed time. A row the thread renders whole shows its end state; Animations off = no typing. It sits in the row's <summary> (flex-wrap), so clicking it opens the card's raw command, output and What it ran.
  • Aliases and exec'd scripts (components, both copies): a process no part names by its program that isn't a fork of the shell (its argv differs from the shell's) takes the next part with a program, unless a later process is that program by name. Without that, cd x && dev-up … put dev-up's uv run … dev_env.py on the cd and showed dev-up as never run.
  • Daemonized processes (_parents, both copies): git fetch leaves git maintenance run --auto --detach behind, launchd / init / a subreaper reaps it, and agent-probe 0.1.0 recorded that reaper as its ppid (its depth stays right). A process whose ppid isn't in the call, deeper than the shell's children, goes back under the process one level up that was running when it started. Without that, its git gc (23 s, 29 s CPU, 1 GB) showed on the next git log part. agent-probe after 0.1.0 records the fork parent as ppid and the reaper as reaper.
  • Not attributed: work another daemon does for the call (a docker run's container is containerd's child; a brain job on the EVOX2 is remote).
  • Claude Code's Code Mode (CLAUDE_CODE_EXPERIMENTAL_CODE_MODE=1, since 2026-11-18): the model writes JavaScript its REPL tool runs, and each $`…` / edit(…) in it is a Bash / Edit call of its own (hooks fire, ids repl_<uuid>), so the probe measures it as usual. The transcript writes those calls later, as virtual records (isVirtual, zero usage) after the delivery that settles the script's eval; conversations/codemode.py tags each with script (the REPL call's toolUseId) and gives the REPL card codeResult / codeMs. The viewer folds them into one Ran code card per script (components/CodeCard.tsx: programs, ×N parallel and the summed cost from the probe, the code, the calls, what it returned). A call still running when its script returned never reaches the transcript: agent-probe 0.1.2's records carry script too (by time — no hook names the script), and the card lists it as outlived its script. 0.1.2 also measures the Claude Code that Code Mode's restart re-runs as …/claude/versions/<v> and sets onFailure: continue on its hooks (Code Mode refuses a call from code whose PreToolUse hook fails). Tested on 2.1.325 / 2.1.327. Hub runs start in it with the composer's Code β chip — see "Code Mode runs (beta)".

Storage: what sessions keep on disk (agent-probe, backend/perf/storage.py, /dashboards/storage)

agent-probe's daemon also measures what agent sessions leave on disk, on one background-priority thread (nice 15 + idle I/O class): each session's scratch dir (/tmp/claude-<uid>/<cwd>/<session>/ — scratchpad + background task output; a RAM tmpfs on the lab, never cleaned but by a reboot), the git worktrees of every repo a session's cwd, a git worktree add argv or a --worktree-root (the sidecar names ~/worktrees) leads to, transcripts per session (Claude Code's, and codex / opencode / pi's), opencode's snapshot and command output dirs, and extra roots. Each item carries its agent (none: a worktree or a root — anyone's; the hub serves it on the item). Why: data/log/2026-11-05-claude-storage-analysis.md in the homelab (every real ENOSPC in five months was /tmp; 31 stale worktrees held 22 GB).

  • Records (pulled with /callmeta): storage (key = path; a version only when it changed or every 6 h), disk (key = mount: size, avail, ram, the items' share per kind — agents, claude-probe's claude, which the hub reads as a fallback and serves as agents — the empty session-dir count), grow (key = tool_use_id: what a call added to its session's scratchpad / worktrees), wtorigin (ignored by the hub). Owned vs bytes: a file is owned only when all its hard links are inside the item — a cp -al node_modules is ~0 owned.
  • When: after every finished Bash call (the session's scratchpad if < 50 k files; its worktrees when the call wrote ≥ 32 MB or ran git worktree add/remove), at Stop, every 6 h for the idle rest; a full pass ~40–90 s on the lab. POST /storage/scan (Measure now) runs one.
  • Attribution: a worktree's createdBy = the call whose process exec'd git worktree add; sessions = every session whose cwd or command text named its path (Claude Code resets the cwd, so cd ~/worktrees/x && … is how most sessions work in one); the hub falls back to conv-meta's worktrees records for older ones.
  • Remove (POST /api/perf/storage/rm → sidecar /storage/rm → daemon): agent-probe re-checks there — refused (unsafe + why) when the worktree has uncommitted changes or commits its main lacks, or a session using it was active < 30 min ago / a process has its cwd inside; force only after the UI's second confirm. A merged branch is deleted with its worktree. Transcripts and roots are never removed from here.
  • Auto-clean (Storage page switch → agent-probe storage config --auto-clean N): the daemon removes scratch dirs (and empty session dirs) of sessions quiet N days. Nudge: the UserPromptSubmit hook prints one line into the prompt's context when the fs under the session's scratchpad or cwd is ≥ 90 % full — the only time the hook prints.
  • Hub: perf_storage (+ perf_storage_sessions), perf_disks, perf_disk_history (10-min samples, 30 d), perf_storage_grow, perf_storage_alerts. A RAM filesystem past 85 % pushes once per crossing (re-armed under 80 %; INSERT OR IGNORE so the blue-green pair can't both push), url /dashboards/storage.
  • UI (owner): the Storage dashboard and the drawer's On disk card (the performance plugin's, since 2026-11-26) and, since 2026-11-27, its header chip (what the conversation still keeps, ≥ 50 MB, amber ≥ 1 GB; the plugin's Performance chips switch); +1.9 GB on a Bash row's cost strip (Call cost switch).
  • Exact writes (agent-probe, Linux kernel mode; claude-probe ≥ 0.3 before it): the eBPF program follows every regular file a call's processes open for writing (security_file_open: allocated size + bpf_d_path) to its last reference (security_file_release, ≥ 6.8; filp_close before), and every last link they unlink or rename over. The call record's files = written / freed / net (allocated bytes), created / deleted, top files (merged per inode) and dirs (cut at node_modules, target, dist…). Write / Edit / MultiEdit / NotebookEdit: the hook stats the file before and after → a call record of its own (tool: "Write", source: "hook"). Not counted: directories' blocks, the agent's own writes (its transcript), another daemon's writes (Docker layers), Claude Code's per-call /tmp/claude-<hex>-cwd. Hub: perf_calls.disk_net (+ files in view()), the conversation's writes totals, GET /api/perf/storage/writers (Storage page → Biggest writers), the Bash row's +20 MB (exact files win over the remeasure; Write / Edit rows get the disk delta alone), On disk in the call's What it ran box. macOS has no file layer: only the remeasures.
  • Rollout: workers re-fetch a fetched (~/.local/bin) agent-probe older than MIN_VERSION (0.1.1 since 2026-11-18: the fork parent as ppid) at sidecar start, stopping the old daemon (a worker with only claude-probe fetches agent-probe, migrates its store and swaps the hooks on its first start); the lab's capable /usr/local/bin copy is upgraded by hand (setup-kernel, then restart the daemon).

Telemetry: how the hub itself performs, and which features get used (backend/telemetry/, lib/telemetry/, since 2026-11-24)

The Performance dashboard measures the agents; this measures the hub (every lag incident in "Performance: what the hot paths cost" was found by hand with py-spy) and which of its features people use. Everything stays on the machine (GOAL.md → Private); nothing is sent to a third party.

  • Backend metrics — telemetry/metrics.py names every metric in its own prometheus_client registry, served at GET /api/metrics (owner, or Prometheus with Authorization: Bearer $METRICS_TOKEN — scope metrics, that route only; docs/permissions.md). telemetry/middleware.py (pure ASGI, installed outside the gate so it reads the gate's caller) times every request by route template × method × caller kind × status class; SSE responses and /worker-link/poll count as open streams, not latency. telemetry/loop.py measures event-loop lag every 0.5 s (the /api/health-takes-43-s symptom) and samples the thread pool and the SSE subscribers. Internals: watcher tick + transcript publish lag (events.py), _Memo builds by builder (core/memo.py), delta vs full thread reads (conversations/routes.py), SSE events by type and replay/resync resumes, runs started by origin.
  • Browser — lib/telemetry/index.ts (startTelemetry() in root.tsx) batches web vitals (web-vitals: LCP, INP, CLS, FCP, TTFB), JS errors, long tasks, the stream's reconnects / resyncs / whole-thread reads and the update lag (a transcript ping naming the open conversation → its delta painted: markUpdate in sseBus.ts, updateShown in refreshConversation) and sends them with sendBeacon every 30 s and on hide to POST /api/telemetry (telemetry/ingest.py: bounded, shape-checked, silently dropping the rest). Off in the mock backend and in tests; a batch from an owner impersonating a guest is dropped.
  • Feature usage — page views (TelemetryRoute → pageView) and named events (track(id, props?)) are ids from lib/telemetry/features.ts, the registry; track only takes registered ids. Server-side use needs no entry: the middleware counts each /api route per person per day. To add a feature: append it to VIEWS/EVENTS (with whatsNew: <entry id> when an entry announced it), fire track, done — the App usage plugin lists it and flags it once unused for 30 days. The registry reaches the hub as backend/telemetry/features.json, generated from it and kept in step by lib/telemetry/features.test.ts (UPDATE_FEATURES=1 npx vitest run src/lib/telemetry/features.test.ts after an edit). Props are a few scalars (ids, counts, booleans) — never what someone typed.
  • Storage — telemetry.db beside ai-agent.db (telemetry/store.py, flushed once a minute by Flusher): hub_minutes (30 d), hub_routes hourly (90 d), web_vitals + web_errors (30 d), raw usage_events (90 d) and usage_daily per day × person × device (forever).
  • Pages — The hub itself on the performance plugin's Performance page (GET /api/telemetry/hub?range=24h|7d|30d, read through telemetry.read's …/hub/telemetry/hub) and the app-usage live plugin (since 2026-11-25; /dashboards/usage redirects to /plugins/app-usage/usage), which reads …/hub/telemetry/usage?range=7d|30d|90d&who=all|owner|guests|guest:<uid> (views.usage; no core /api/telemetry/usage route) + the registry through the owner-only telemetry.read capability: most used, unused in 30 days, phone vs desktop, adoption after What's new, where runs start (views.run_origin reads the meta; /api/spawn stamps meta.origin = app | script | child | mcp | newProject (handoff from 2026-11-24 to 26, before the Handoff plugin) since telemetry began — older and terminal-started ones are unknown). Owner-only (perf.read). Guests are told in Settings → Profile.
  • The homelab scrapes ai-agent:8080/api/metrics (Prometheus job ai-agent), draws Grafana's ai-agent dashboard and mails two alerts (loop lag p95 > 1 s, a 5xx burst) — ~/homelab/services/logs.

Labels stay bounded: a route template, never a path; a page pattern (/conversation/*), never an id — metrics.page_label checks the shape and folds past 80 distinct pages into other. Never add a label that can take a conversation id, a user id or free text.

The mail trigger is a live plugin: Mail agents (since 2026-11-25)

The core's Settings → Mail trigger (settings/mail_trigger.py, /api/mail-trigger-senders, the page) is gone: mail now starts conversations through the hub plugin mail-agents (~/projects/ai-agent-plugins/plugins/mail-agents/, spec ~/projects/mail/docs/mail-agents-spec.md, Gabriel's picks in form mail-agents-plugin_qzqpe1). One address per hand-made agent — <name>@hub.gabvdl.xyz; the default agent is default@, and claude@gabvdl.xyz (+ claude@hub) are its aliases — each with a model (harness / effort / thinking from Settings → Models unless set), a machine, a lean run, an EVOX2 fallback, its senders (the owner always) and answer-by-mail.

  • mail-ui keeps the proof (~/projects/mail/ui/backend/mailtrigger.py): it watches gabvdl.xyz/claude/ and every hub.gabvdl.xyz/<name>/ folder, runs the unchanged DKIM verify(), keeps the (Message-ID, address) replay index, groups a mail's copies (30 s) and POSTs the group to the plugin's receive action (/api/plugins/mail-agents/actions/receive, internal token). Signed In-Reply-To / References ride along (refs).
  • The plugin owns the agents, the allowlist (senders.json in its hub-scoped dir, /data/plugins/data/_hub/mail-agents/ — mail-ui reads it as MAIL_TRIGGER_SENDERS_FILE; emails = the enabled ones, as the old file), the routing (owner to an unknown agent → a push listing them; anyone else → silence), the prompt (its core.md first, then the agent's text, then the mail with the quoted part fenced as untrusted), the thread index (a signed reply continues its conversation; the mail CLI reports what it sends from an agent's address through the sent action) and answer-by-mail (a one-minute schedule mails the final answer to the owner via mail-ui's /api/send, behind the plugin proxy). The page is its settings page; /settings/mail-trigger redirects there. Owner only.
  • Run bridges it introduced (plugins/hubruns.py, owner-only, operator-approved, docs/plugins.md): runs.start (lean + local-model fallback + machine + meta.plugins.<id>), conversations.send, models.read, workers.read.
  • /data/mail-trigger-senders.json was carried into the plugin once at start (plugins/carryover.py). ~/homelab/.claude/agents/mail-agent.md is gone: the core is the plugin's core.md, its claude-specific rest seeded the default agent's text. No plugin installed ⇒ no mail trigger (mail-ui retries three times, then pushes a failure).

"Left to do" is a live plugin (since 2026-11-25)

The nightly "what did my finished conversations leave undone" list moved out of the core (backend/leftovers/, /dashboards/left-to-do, both gone) into the hub plugin left-to-do (~/projects/ai-agent-plugins/plugins/left-to-do/): a schedule (nightly 06:30, continue every 15 min until noon when a pass ran out of its 900 s), actions report / scan (Scan now detaches a pass), the Dashboards page /plugins/left-to-do/board (the old URL redirects there), the brain's systemone through its proxy (hub secret brain_key). It reads conversations through the conversations.read bridge, whose rows carry the conversation's id, userTurns, turnEnded and the cron / agentRun / test / spawnedBy flags; one conversation's finalAnswer is its newest transcript's last assistant text. The core's /data/leftovers.json is carried into the owner's plugin data once at start (plugins/carryover.py, renamed .migrated). Eval and method: the plugin's lib/ltd.py docstring.

Prompt shortcuts are a plugin (prompt-shortcuts, since 2026-11-27)

Gabriel's form prompt-shortcuts-into-a-plugin_dkhipt: everything moved — the owner's library, its editor and audience matrix, the guest sharing, guests' own shortcuts and preferences, the built-in Changes chip — into the prompt-shortcuts plugin (ai-agent-plugins plugins/prompt-shortcuts). What the core keeps is the composer's side: the chips engine (RichInput chips, the DAG in lib/guidelineDag, auto-tag triggers, the runner filter, the default-on seeding), the always-on notify line and the thread's prompt pills.

  • Where the chips come from: only composer.shortcuts providers (GET /api/plugins/composer-shortcuts, plugins/shortcuts.py; the frontend's business/settings/shortcuts.ts). The plugin's answer says "position": "first" (its chips before ask-form's Form), keeps runners: [] (a guests-only chip) and, for a guest, flags a chip they hid hidden (out of their composer, still named by the prompt pills). Up to 64 chips per provider. Any POSTed action of a plugin that provides composer.shortcuts (its page saved) drops its cached chips and publishes composer-shortcuts (guests too, _GUEST_PASS): every composer refetches its own at once.
  • Its data: the owner's library in the plugin's hub-scoped library.json (missing ⇒ the built-in Changes chip), each guest's own in their personal.json ({shortcuts, prefs}). The carry-over (carryover.prompt_shortcuts, once, marker .carried-over) wrote them from the settings store — the owner's promptShortcuts with each audience spelled out (a pre-v4 blob first folds in guestDefaults.promptShortcuts, read only by UsersStore.legacy_guest_shortcuts now), each guest's promptShortcuts + shortcutPrefs. The settings store's v7 migration drops both keys; /api/me no longer carries sharedShortcuts, /api/guest-defaults no promptShortcuts, and settings/shortcuts.py (upgrade on read) is gone.
  • Seeded: "seed": true in its manifest makes seed_typed_plugins install it once from the seed dir like the provider/harness plugins (an uninstall sticks); managed.defaultForGuests gives it to every guest.
  • Its page is a Settings entry: ui.pages[].nav: "settings" (+ group, after) routes at /settings/p/<id>/<page> and lists it in the panel, the drawers and the search (business/settings/pluginEntries.tsx → visibleEntries(a, extra)); /settings/shortcuts forwards there, its old #skills tab to /settings/setup. Saved drawer / panel layouts expand the old shortcuts key in place (RENAMED, SUB_RENAMED, GUEST_RENAMED).
  • Its icons come from the host: aiAgentPlugin.pickIcon opens the app's glyph picker in a dialog, aiAgentPlugin.iconSvg(keys) renders glyphs as markup (business/plugins/iconBridge.tsx); a page's init.lang says the app's language, so its strings follow it.

Scheduled conversations: "Send later" (the scheduled-conversations plugin)

Since 2026-11-26 a live plugin (~/projects/ai-agent-plugins/plugins/scheduled-conversations, form move-scheduled-conversations-to-a-plugin_ofuwjr): the core's backend/scheduled/ (store, ScheduledRunner, service) and frontend/src/business/scheduled/ are gone. Hold (or right-click) send in either composer → Send later… (the plugin's composer.send slot, in the app's plugin modal): quick picks (next night 02:00, next morning 09:00, tonight 22:00, next Monday 09:00 — each the next occurrence still ahead), native date + time inputs, and a title. Owner only.

  • What is frozen. onSubmit is intercepted (the button's submit() runs with a flag set), so the frozen payload is exactly what Send would have spawned — guidelines, tags, attachments folded in — plus model / harness / effort / account / projects; the host hands it to the slot as init.send (useSendSlots). The runner: an explicit "Runs on" pick is frozen; an unpinned prompt is stored auto (+ the profile it was sent from, the account only when pinned) and routed when it fires, like a send then. Its card shows where it would start right now (hub/runs/resolve mode: "now"), once started where it went. From the reply box it is a follow-up (targetSessionId): it resumes that session on its own runner.
  • Firing. The plugin's tick job (* * * * * — the plugin scheduler wakes a second past each half minute, so it fires at :01) claims each due entry in its store ($AIA_PLUGIN_SHARED_DIR/scheduled.json, flock'd compare-and-set — the blue-green cutover's two backends can't both start one), then sends it through hub/runs (runs.start: the composer's _send_message, with worker: "auto" + profile, account, projects, cwd, scheduled) or hub/conversations/<sid>/send. A new conversation gets meta.scheduled ({id, scheduledAt, shouldStartAt} → the violet scheduled · 02:00 pill, still core: cards._scheduled_ref, ConvMetaBits) and the scheduled title as meta.title. A start by hand (Start now, Retry) adds manual: true: no pill.
  • Failures. Any refusal — a pinned worker offline, every runner of an auto one's profile down ("no Work worker was up at 09:00"), the sidecar down — marks it failed and pushes a notification (hub/notify with actions: ["Retry"]); the tap (/api/notify/{id}/action) reaches the plugin as the notify.action event. A start missed by more than 120 s (the hub was down) is never run late: failed / missed + the same push. The push opens /?modal=scheduled-conversations:edit&id=<id> (the old /?scheduled=<id> still does).
  • Naming before it runs. The plugin's title action → hub/title (conversations.title) → the plugin that provides: {"conversation.title": …} (plugins/labels_bridge.py — conversation-labels); no provider or any failure falls back to the prompt's first words.
  • The core's readers (plugins/schedule_bridge.py, the plugin's provides: {"runs.schedule": "schedule"}, ops list / get / create / edit / cancel / start / title / upcoming): the week's budget (op: upcoming, cached 30 s) and the stopped-run card's Resume at… (usePluginProvider("runs.schedule")). No plugin: nothing in the budget, Resume now only.
  • The CLI and the MCP are the plugin's commands (since 2026-11-28, form cron-scheduled-in-the-cli-and-mcp_x4nk83): ai-agent plugin scheduled-conversations ls | show | add "…" --in 2h|--at 09:00 [--to ID|.] [--model M] | cancel | start, each also an MCP tool (plugin_scheduled-conversations_add…, "mcp": true). The core's /api/scheduled* door, ai-agent later / scheduled / unschedule (they now only print where they went, exit 2), the MCP schedule_conversation / cancel_scheduled / browse scheduled, the schedule tool group and the runs.schedule permission are gone. --to is a conversation argument (plugins/commands.py): the CLI and the MCP resolve any spelling (id, prefix, viewer link) to a session id, and the CLI takes . for the run it is called from ($CLAUDE_SESSION_ID). --model words are matched by the plugin against hub/models (models.read): --model qwen is a pi run. A connection bound to a worker can't schedule (Gabriel's call: Full only — it holds no plugins.use; the plugin also refuses any call naming viaWorker): the owner's own CLI, or a full AI-app connection, does.
  • Long titles get a short header title the same way (conversations/short_title.py). Any conversation whose displayed title runs past MIN_LEN (48) — a subagent's (its prompt's first 90 characters), a top-level one's (a first prompt Claude never named, a ⑂ fork, a resource title, an agent / resources stamp) — except a title the owner typed: meta.title with titleSource: user, or with no source at all (a rename from before the field, indistinguishable from conv-meta.sh title and scheduled titles, which send none either). On the conversation page only, the detail route hands the title + a subagent's card description + the first prompt to the same conversation.title provider (none installed: no short titles at all), on a 2-thread pool, one in-flight ask per conversation — the response never waits (it carries shortTitle: null, the header shows the long title) and a short-title SSE event ({id, title}, guest-filtered — a guest's view asks on the lab's login like any other) patches the open page's query cache. Cached in SQLite short_titles (conv id → title, or NULL for a failed ask, retried after RETRY_S = 6 h) with the long title it stands for (source): a changed auto title misses the cache and is asked again (one row per conversation; NULL source = a subagent row from before the column, its title can't change). A title that leads with an issue key or a PR number keeps it (INS-2229 · <Haiku's words>). Spend booked as short-title in the ledger. The full title stays on hover. The parent's page names its direct subagents (for_subagents, from _attach_subagents): one batched cache lookup for SubagentRef.shortTitle (the Subagents card, and the Task card's View subagent link, which shares the dict), and the same background ask for each child never named for its title — it used to wait for the child's own page, so almost every subagent card sat on its prompt's first 90 characters (often identical across siblings). The short-title event patches the child's header and any cached parent page listing it (withSubagentShortTitle). Lists never ask: the graph (/api/subagents), the Conversation name card and the left list's cards keep the full title — the list would need the lookup per row plus a list refetch per event. A rename clears the open header's short title optimistically (optimisticRename). A subagent is always named by its own task: its meta is the parent's (shared sessionId), so _conv_title returns a sidechain summary's parsed title before looking at the meta — it used to hand the root's rename to a subagent's own page and to every agent in a nested agent's parent chain.
  • UI (all the plugin's sandboxed documents): the drawer's calendar toggle with the count still to come (a conversations.drawer slot: icon, badge → the count action) flips the drawer to the plugin's list; a card opens the app.modal slot edit (title, message — the typed text, its composed blocks kept — time, Start now, Delete); Tools → Scheduled is the whole list (/plugins/scheduled-conversations/board). Live: every write calls hub/changed → SSE plugin-data → the plugin's reads refetch. /data/scheduled.json was carried over once (carryover.scheduled).

The complete skill replaced the conversation hooks (and the CTAs)

There used to be a hook scheduler here: ten seconds after any run ended, it resumed that same conversation with a follow-up prompt. It worked, and it was the wrong shape. Two reasons, both structural:

  • It cost a full transcript per firing. --resume is a fresh claude -p process, and Claude Code rebuilds that process's environment preamble (cwd, git status, date, …) from scratch; any byte of drift there — near-guaranteed on a checkout other agents are also committing to — invalidates every cache breakpoint after it. Sampled real transcripts confirmed it: cache_read_input_tokens collapsed to the cross-session baseline and cache_creation_input_tokens re-created the entire prior conversation, every firing, regardless of the delay. A tidy-up pass routinely cost as much as the feature work it followed. The maxContextK cap was a bandage.
  • Half the work didn't need a model. "Summarise what happened" is mostly aggregation — which prompts were given, which tools ran, what net change landed in git — and the backend already parses transcripts and buckets commits. Asking a model to re-read a transcript to derive that was paying premium rates for a GROUP BY.

The first replacement was a CTA: the same prompt file, offered as a button under the last message of a finished run. It fixed the "unasked-for" half but not the cost — pressing the button still resumed the session in a new process, so the tidy-up still paid for the whole transcript as fresh input tokens.

The current answer avoids the resume entirely: completion is a skill the session runs on itself, before it ends. A spawn guideline tells the session to finish with the complete skill, so the pass happens inside the still-warm process, on the prompt cache it already built — the same work for a fraction of the tokens. The skill waits 30 s first, so there is a window to read the finished conversation and steer it before the pass starts.

What that leaves in this backend:

  • conversations/scaffold.py — the algorithmic half (conv-scaffold), unchanged: metadata, the squashed diff, the merged tool/bash/subagent summaries, two blank sections for the model. The filled document is published onto meta.summary and rendered under the thread by ConversationSummary.
  • meta.completedAt — derived, not stamped. The completion pass signs off with COMPLETED, the parser already flags that (completedMarker), and _conv_meta turns it into a timestamp. Nothing has to write a ledger, and there is no button state to keep in sync. It is what puts the spinning COMPLETED seal on a conversation card.

Native Claude Code hooks (.claude/settings.json) are read-only here (GET /api/claude-hooks, listed under Settings → Claude Code hooks): writing that file from the container would be host-level code execution — see the trusted-caller gate above. They are now the only hooks the viewer knows about.

Install/manage the sidecar with sidecar/install.sh (systemd user unit claude-sidecar); config comes from the repo .env (SIDECAR_TOKEN, SIDECAR_PORT). See sidecar/README.md.

Schema drift: the transcript format is not ours

backend/conversations/parse/ parses Claude Code's internal, undocumented JSONL transcript format, so a CLI update can silently change what it emits. The early-warning tool is scripts/schema-drift.py:

scripts/schema-drift.py            # newest transcripts vs committed baseline
scripts/schema-drift.py --update   # add reviewed drift to the baseline

It does two things: diffs a structural footprint (key paths + content-block types, never values — scripts/schema-baseline.json is safe in git) of recent ~/.claude/projects transcripts against the baseline, and runs a parser canary (the real parse_conversation cross-checked against raw record counts: assistant turns with usage, token totals, models, timestamps). Exit 1 on drift or a failed invariant. Run it after a Claude Code update or whenever conversations render oddly; on drift, decide whether the parser needs to handle the new shape, then --update. Every transcript record carries the CC version stamp — a new version alone is INFO, not failure (releases are ~daily and almost never drift).

Subagents nest: the subagents/ dir is a tree, not a list

Claude Code writes every agent a conversation spawns — at any depth — into the one flat <convId>/subagents/ dir, as agent-<id>.jsonl + an agent-<id>.meta.json sidecar. A subagent's own Agent/Task calls spawn grandchildren whose meta names the spawner in parentAgentId (absent on a depth-1 agent) and the level in spawnDepth. conversations/tree.py keeps two parent notions apart, and everything subagent-related goes through its helpers rather than globbing the dir:

  • root (_root_path_of): the <convId>.jsonl the dir belongs to. Usage rolls up there (_subagent_descendants — the list card and the detail totals count the whole tree, each transcript once), agentsUsed and the agents catalog key runs there, and the graph's rootId is it.
  • direct parent (_parent_path_of, via parentAgentId): the transcript holding the Task card that spawned it. _subagent_children lists a node's direct children (a root's are the metas with no parentAgentId, so archives from before nesting keep their one-level reading); _attach_subagents links each card to its child on every page, a subagent's included, and sends parentConversation (direct parent + toolUseId) plus parentChain (every ancestor, root first — the breadcrumb). _sidechain_state resolves running state up the chain: a nested agent runs while its parent's Task call is open, and that parent's own state comes from its parent, not from the metadata sidecar (a sidechain's sessionId is the root's, so _conv_meta would answer for the root).

An agent page reports its own spend (subagents = direct children, each ref carrying subagentCount for what it spawned in turn); only the root rolls the tree up. The Task card that spawned a child is still credited with the child's whole subtree (turnCost), so the cost-growth chart stays whole on the root page where the grandchildren have no card. The graph (/api/subagents) orbits a nested agent around its parent agent's node (parentId is a sidechain id there; rootId is the fallback when that node isn't drawn). _parent_path_of is deliberately not memoised on the path: the meta sidecar can be unwritten on the first look, and a nested agent must never get pinned to the root.

Deploying

Never compose up --force-recreate this service — use the blue-green script, which validates a fresh build on a standby container before touching the live one:

~/homelab/services/ai-agent/deploy.sh   # the homelab shim's copy (runs from anywhere)

# from an agent session — one foreground Bash call (timeout 600000):
~/homelab/services/ai-agent/deploy.sh --detach && ~/homelab/services/ai-agent/deploy.sh --watch

It builds a new image, brings up a second ai-agent-deploy standby on homelab_main, health-gates it on /api/health, cuts Traefik over to it (file-provider hot-reload), recreates the canonical ai-agent on the new image, then restores routing and removes the standby — zero downtime, and if the standby never goes healthy the live container is left untouched. An flock on /tmp/ai-agent-deploy.lock serializes deploys; a second run waits for the first (DEPLOY_WAIT, 600 s; --no-wait aborts). From a session, --detach starts it in its own session (it outlives the caller) with a per-run log, and --watch [<run>] waits for that run and prints one result line, exiting with the deploy's code — never a hand-rolled pgrep loop (it matches its own shell and never ends; the homelab CLAUDE.md → "Deploying the ai-agent service"). deploy.override.yml is only for the standby slot (renames the container, drops the host port, joins the external homelab_main network).

The public face: landing/ → tokunia.dev.gabvdl.xyz

The project's public name is Tokunia (Tokun·IA, from 徳用 tokuyō, "good value for the money"). landing/ is its marketing page — a dependency-free static site (hand-written HTML/CSS, one small JS file), not a Vite app — and landing/deploy.sh publishes both public hosts through zipgo on raspy2:

./landing/deploy.sh          # landing only → tokunia.dev.gabvdl.xyz
./landing/deploy.sh --demo   # rebuild + publish the demo too

Two things about that script are load-bearing:

  • The demo is this frontend built with VITE_MOCK=1 — the in-browser mock backend (see above) is what makes a public demo possible with no API exposed. Branding comes from VITE_APP_TITLE / VITE_APP_SHORT_NAME / VITE_APP_DESCRIPTION, read in vite.config.ts; unset, they keep the homelab's own title and manifest exactly as they were.
  • The landing rsync excludes demo./. The two hosts are nested in zipgo's trailing-dot tree (…/dev./tokunia./ and …/dev./tokunia./demo./), and zipgo deploy mirrors by default — an unfiltered landing deploy would delete the demo sitting underneath it.

Numbers quoted on the page (the receipt's itemised run, the archive stats) are real figures pulled from the live instance, and the carbon line uses the app's own frontend/src/lib/footprint.ts factors. Keep them honest if you edit them.

Standalone mode: a missing catalog is a valid state

The homelab docker-compose.yml mounts ~8 host paths (transcripts, memories, screenshots, services/, plans, …), but the image must also run with none of them — that's the GOAL's "generic first-run setup" / one-liner docker run. docker-compose.standalone.yml is that shape: a workspace + a data volume, and nothing else required.

So every catalog degrades to an empty list when its dir is absent — never a 500. (/api/templates used to raise; it doesn't now.) A named item that isn't there is still a 404 — it's only the missing-mount case that's benign. When you add a catalog backed by a mount, follow that rule.

The guard is a smoke test — run it after touching mounts, env wiring or a catalog route:

scripts/standalone-smoke.sh            # boot the current image on a bare workspace
scripts/standalone-smoke.sh --build    # build first, then smoke

It boots the image with only a throwaway workspace + data dir (and RUNNER_IN_CONTAINER=1), asserts every catalog endpoint and the PWA shell answer 200, that the bundled claude CLI is on PATH and its runner answers /health, and greps the log for tracebacks (a background indexer/watcher crash won't fail a request). Exit 1 = regressed.

Standalone spawns sessions now (the in-image runner, above). The one thing it still can't do is build off-homelab: frontend/.npmrc pulls @gabvdl/ui from the host-bound verdaccio, so a standalone build needs that registry — a prebuilt image runs anywhere. Tracked in GOAL.md.

Local development

Tests: scripts/test.py runs every suite and gives one verdict — each backend module in its own container of the deployed image (the repo mounted read-only at /repo, run with pytest so the plain def test_* modules count too), the sidecar and cli/ with pytest under uv, vitest and tsc (pi's runner and its node --test moved to the harness-pi plugin, 2026-11-27: run them in ai-agent-plugins). scripts/test.py backend -k parse narrows it; scripts/test-known-failures.txt holds what already fails on main (reported as known, it doesn't fail the run; a known one that passes again is listed for removal; a flaky … line, failing only under load, is tolerated either way). A full run takes 18–27 min on the lab. Don't use the old recipe of backend/ mounted alone at /app: tests that read ../cli, ../frontend or ../sidecar fail there (it made ~40 tests look broken on main).

There is no CI. Frontend and backend are built into the image; to iterate:

  • Frontend only: cd frontend && npm install && npm run dev (Vite on :5180). It needs the backend API — point it at a running container or backend.
  • Full stack: rebuild + redeploy via the homelab shim's deploy.sh, or hit the running container directly on the host at http://127.0.0.1:8096 (plain HTTP, bypasses Authelia — handy since new *.lab domains can't get an LE cert here).
  • Health: curl -s http://127.0.0.1:8096/api/health → {"ok":true}.

After changing the homelab shim's traefik.yml, run make link-traefik-configs from the homelab repo root (the file provider watches config/dynamic/, not the shim's file).

Gotchas

  • Read-only mounts: most of the repo context is mounted :ro (services/, .git, transcripts, memories, screenshots, and the root data/ tree). Only .claude/, ~/projects (host-side; /workspace/projects in-container), CLAUDE.md and the service's own data/ (SQLite store) are writable. The container runs as 1000:1000 so edits keep repo ownership.
  • Root data/ tree: mounted ${PWD}/data:/workspace/data:ro and surfaced in the file tab for visibility only. The indexer exposes just text files (see DATA_TEXT_EXTS in core/config.py — md/json/py/log/…; binaries like the PNG thumbnails are skipped) and marks them non-editable. data/tmp/ is in IGNORE_DIRS, so scratch files and secrets (e.g. *-creds.env) never appear.
  • Summaries carry no searchMsgs: since 2026-11-22 db.py keeps a transcript's text blocks apart (search_json), so all_summaries() / get_summary() never have them. Read them with deps.store.search_msgs(paths) (or all_search_msgs() for the whole corpus); a test fake store must do the same (test_conv_refs, test_past and test_short_title use the real db.Store).
  • Token counts cost API calls: they hit the count_tokens endpoint (ANTHROPIC_API_KEY from .env) and are recomputed only when a file's content hash changes, after a debounce — don't add code that recounts on every request.
  • Conversation "finished" state: a conversation is finished when its turn ends — no DONE needed. The parser's turnEnded (conversations/parse/turns.py) is true when the transcript ends on a turn-end record with no turn activity (user / assistant / attachment / api-request / an enqueued prompt) after it; bookkeeping records (last-prompt, cost-state, ai-title, …) don't reopen it. The records: system/stop_hook_summary — Claude Code writes it once a turn's Stop hooks ran, and only when there is one: every hub run has the stop guard, and the sidecar adds a no-op Stop hook (harness-claude's sidecar/turn_hook.py, marker ai-agent turn-end) to every account's settings.json at start, so a scripted claude -p or SDK run outside the hub writes it too; system/turn_duration — an interactive session's own, hook or not; and a v1 turn_end event — what the harness converters write (harness-pi's runner/cli.mjs on pi's agent_settled, or the pi process's exit; sidecar/opencode_mirror.py on opencode's idle row; sidecar/agy_mirror.py on the run's result) — or, in a transcript from before v1, their system/turn_end record. A Stop hook that blocked (the stop guard holding for a background shell) writes its "Stop hook feedback" user record right before its summary — that summary doesn't end the turn. An API error the CLI gave up on (isApiErrorMessage, no Stop hook runs then) ends it too. A turn that ends with a background agent still at work (its call open in runningAgents, flagged background) hasn't ended: the CLI waits on the agent, and its <task-notification> starts the next turn. While a hub-launched run's process is alive (core/liveruns.py, fed by the exit watcher's polls) that conversation stays running however quiet the agent is — a long command, a form wait; a terminal session has only the subagents' writes and the recency window. A SendMessage whose result says resumedAgentId reopens the stopped agent's call until it notifies again; a blocking agent's report (which ends on an agentId: line too) closes its call. _resolve_state reads an ended turn as finished after the subagent, interrupt, paused and trigger-wait checks. Two older signals stay for what has no turn-end record (an older CLI, a run killed mid-turn): the exit watcher — a background thread in runs/sidecar_client.py (_watch_sidecar_runs) polls every runner's /sessions every ~2s and stamps finished (+exitedAt) the moment a run's process dies (distrusted if the transcript later grows past exitedAt, _outlived_exit; in-flight resume/interrupt swaps are shielded via _sidecar_busy; a run shorter than one poll is never seen live — the turn-end record covers it) — and the recency fallback (RUNNING_WINDOW_SECS, 600s). The legacy DONE / COMPLETED sign-off + a notification still ends a conversation. The closing push's own finished stamp (notify --final, or the ```notify block's push) can land before the turn ends (the complete pass works on), so it is only trusted once exitedAt backs it; until then the run reads running and the turn's end flips it — the viewer never folds into the summary over a thread still missing its last message.
  • Auto-archive (conversations/autoarchive.py, a thread every AUTO_ARCHIVE_SWEEP_S = 30 s; AUTO_ARCHIVE=0 disables): the clutter folds into the archive by itself, stamped meta.autoArchived = {kind, at} (the card's auto · cron / auto · test chip). cron — a run with meta.cron once it finished successfully: turnEnded (the CLI's own turn-end record — an exit-watcher or recency finished isn't enough), no lastApiError, not interrupted / paused, no question left open on its session (a pending ask-form form, hub form or ask) and no error / warn push in meta.notifications; a job opts out with archiveOnSuccess: false (the cron-jobs plugin's page). test — meta.test (ai-agent new --test, the spawn body's test, POST /api/conversation-meta {test}) or a cwd in a temp dir (/tmp, /var/folders, a Claude scratchpad — where a nested claude -p runs): archived once finished or stopped, any outcome — its pushes leave the owner's New list with it ("Notification read state" → Archiving dismisses; a cron run's stay). Both wait SETTLE_S (60 s) past endedAt, skip a guest's conversations (meta.owner), and apply to what started after the sweep first ran (auto_archive_since in the store's meta table) — meta.test whenever it ran; POST /api/conversations/auto-archive {backfill, dryRun} runs the rules over the whole archive (and, for a transcript from before the turn-end record, takes exitedAt or a DONE / COMPLETED sign-off as its clean end). A manual unarchive wins: the meta route adds autoArchiveOff and the sweep never touches it again. A new turn sent to an archived conversation unarchives it (on_resume in both resume paths of runs/service.py); a cron one continued by hand opts out for good, a test one is swept again when that turn ends.
  • Conversation "paused" state: a run whose last act was parking itself on a trigger — a trailing ScheduleWakeup (non-stop) or a pending Monitor — is shown paused instead of running (waiting_trailing in conversations/parse/state.py, resolved in conversations/cards.py:_resolve_state). The flag clears on any later tool call, real user turn, or interrupt — not on the same turn's closing text.
  • Running subagents keep a conversation running. The main transcript goes quiet as soon as its turn ends — an orchestrator waiting on background agents, a blocking Task, a headless run the CLI keeps alive for them — while the agents keep writing <conv>/subagents/agent-*.jsonl. So _resolve_state answers running while the parser still has an open Task/Agent call (runningAgents) and a subagent wrote after the main thread's last record (and after exitedAt; >10 s slack each) within RUNNING_WINDOW_SECS (_subagents_live). That outranks the recency fallback, the trailing markers (interrupted / paused / waiting / the turn's end) and the exit stamp; other explicit states (review, the Stop button's interrupted) still win. An agent that died mid-call leaves its call open forever: its going quiet for the window is what flips the conversation back. The subagents' last write comes from _subagent_activity — a sessionId → newest sidechain endedAt map memoized on the summaries version (one pass, ~5 ms over ~3 000 summaries), looked up only for a root with an open call — never from a transcript read. The in-flight agent chips, the subagent refs and /api/subagents follow, since they are gated on the parent's state.
  • Two containers briefly share data/ during a deploy cutover (SQLite); this is a short window and intentional — don't "fix" it by locking the DB.
  • A resume must never answer 200 without a live run behind it. The composer echoes the typed turn optimistically and only drops the echo once the transcript grows, so any resume that reports success but starts nothing leaves the UI on "sending…" forever. Two guards keep that honest and must stay: sidecar/launch.py watches a freshly launched claude for LAUNCH_PROBE_S and 502s with its log tail if it dies on the spot (a --resume whose transcript isn't found exits 1 in ~2.5s), and /resume only reports reused for a process that is genuinely still running — a finished-but-unreaped child is a zombie, and a zombie answers os.kill(pid, 0) (hence _reap() + the Z check in _alive). reused means the turn was dropped, so the backend returns 409, not 200. The backend always resumes with force: true: a genuinely-live run is stopped first (_stop_run — SIGINT the group, wait up to STOP_WAIT_S, escalate to SIGKILL) and the resume then launches, so sending a message into a running or paused conversation restarts it on the new turn instead of 409ing. reused can now only come from a sidecar predating the flag.