Files
cobble/AGENTS.md
T
tben f8a7b0f2e7
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
Keep every connector account a second sign-in adds
2026-11-22 09:32:54 +01:00

155 KiB

Agent Instructions

Cobble (cobble.moduletrace.org): an open-source crew of small AI worker bots. The unit noun is bot, never "agent" or "expert".

This file is a map: it names the rules, the invariants and where things live. For detail, read the code it points to. When this file, the handoff, the code and the user disagree, the code and the user win.

The handoff is outdated

assets/handoff/ (gitignored) is the project's foundation, not its design. Never use its layouts, assets/screens/*.png, right-hand "working on" panel or PRODUCT/IMPLEMENTATION briefs as reference for the UI, docs, screenshots or marketing. Still authoritative:

  • Brand assets (never change): stone icons (public/brand/icons/*.svg, mirrored in src/data/stone-geometry.ts), coordinator (public/brand/coordinator/), app icon (public/brand/app-icon/), wordmark (public/brand/wordmark/, mirrored in src/data/wordmark-paths.ts). The mark is a stone with exactly one flat cut; a bot's colour is its identity (never status); the coordinator is hue-less. The one sanctioned override is an install's own app icon (Settings > General): another brand stone, or an uploaded image with a brand stone as its top-left corner mark.
  • Tokens: src/styles/main.css is now the source of truth (the handoff tokens.css is history).

For the current UI read src/layouts/bots/ (rail, workspace rail, user popover), src/pages/admin/bots/[bot_id]/ (header, thread, composer, modals) and src/pages/admin/workspaces/ (dashboard).

Stack

  • Runtime: Bun, not Node. Use bun, never npm/npx.
  • Framework: @moduletrace/bunext, not Next.js. Filesystem routing under src/pages/, served by Bun.serve in src/server.ts.
  • Database: @moduletrace/bun-sqlite (SQLite). Schema db/schema.ts, generated types db/types/db.ts, config bun-sqlite.config.ts.
  • UI: Tailwind v4 + @moduletrace/twui (the only component system: no shadcn, no tailwind.config, no components.json) + src/components/general/. The library lives in its own repo at /home/archben/Projects/Git/moduletrace/libraries/tailwind-ui-library (playground bun run dev on 7010, tests bun test src). CSS chain: src/pages/__root.tsx -> src/styles/main.css -> @moduletrace/twui/base.css. Theme tokens in the @theme inline block of main.css.
  • Icons: lucide-react. Never render a lucide icon by name (twui LucideIcon, a string beforeIcon): it ships every icon. Import the icon.
  • Validation: zod v4 ([email protected]).
  • Branding: site name/slug only in src/data/site-data.ts. Logo source public/logos/logo.svg (the ember stone, rendered via BotStone in logo-icon.tsx).

Commands

Purpose Command
Dev server bun run dev
Production bun run start (serves whatever .bunext/ holds; build first with NODE_ENV=production bunx bunext build)
Type-check bun run typecheck
Tests bun run test (one file: bun test <file>; tests are colocated .test.ts(x))
Bundle budget (after a production build, CI) bun run check:bundle (fails if the conversation page's initial JS passes budget or the full Lucide set returns)
Favicon/brand/PWA assets bun run gen:favicon
DB schema sync / admin UI / backup bun run db:schema / db:admin / db:backup
Seed super admin / sample crew bun run seed (needs SEED_SUPER_ADMIN_PASSWORD) / bun run seed:bots [email] (idempotent)
Query DB (read-only, JSON envelope) bun llm-code-assistant/query-db.ts "<sql>"
CI status, before deploying anything gh run list --limit 5, gh run watch <id> --exit-status, gh run view <id> --log-failed for a red one
Publish a release bun run publish:github / publish:gitea; bun run mirror:gitea afterwards (gh run watch in between until the image build ends)

No linter or formatter. bun run typecheck and bun run test are the verification steps. Use query-db.ts to see what is actually in the database instead of reading ORM code.

Path alias @/* resolves from the repo root (@moduletrace/twui/layout/Button, @/src/data/site-data, @/db/types/db).

Entrypoint (src/server.ts)

Enables SQLite foreign keys (enableForeignKeys), bunextInit(), ensureDockerNetwork() (exits without docker: computers are containers), Bun.serve, then cron(), botsQueue(), the file-ingest worker and liveRelay() (cron and the queue are gated to MAIN_SERVER in production; the relay runs everywhere).

  • /media/* -> media server; /computers/<id>/ -> computer proxy; /ws upgrades only after userAuth; /sw.js and PWA files via handlePwaFile; precache gate before bunext; everything else -> bunextRequestHandler.
  • Responses go through compressResponse (src/functions/server/compress-response.ts): hashed assets cached immutable and compressed once (in-memory, bounded); pages/JSON gzipped as they stream; media and streams untouched.
  • Keep page props small: every page is a full server render. Anything only a modal needs loads when the modal opens (e.g. the models modal fetches api/admin/harness/catalog and api/admin/bots/harness-overview, cached in localStorage by src/utils/harness-cache.ts).

Architecture

Auth

  • Guard: src/pages/__root.server.ts on every request. No public pages: anything outside AdminSections (src/dict/admin-sections-dict.ts) and /auth redirects to /admin/bots. No users -> /auth/signup (first-run super admin only, which then opens the skippable guided setup /admin/settings/setup: app name, provider, models, where to go next; it stays under Settings; or Restore from a backup: another install's database file or data archive, told apart by their bytes, through public api/auth/bootstrap-restore, refused once any user exists or for a database with no users, restored like Settings > Backups and then the app restarts, the page polling bootstrap-status and going to the login); unauthenticated /admin/* -> /auth/login; authenticated /auth/* (not logout) -> /admin/bots; unknown /admin/settings/* -> /admin/settings/general.
  • Session: AES-256-GCM cookie (key from ENCRYPTION_KEY/ENCRYPTION_SALT) plus CSRF cookie, Secure only over HTTPS (isSecureRequest, honours X-Forwarded-Proto). userAuth (src/functions/backend/auth/user-auth.ts) checks expiry (60 days), CSRF (constant-time) and re-reads user_types every request.
  • Login: email/username + password (api/auth/password-login.ts, rate limited). No emailed codes or resets. Google login only for existing accounts, when GOOGLE_CLIENT_ID is set. Sessions issued by login-user.ts.
  • Passwords: bcrypt in user_passwords (never in users; blocked from CRUD via src/dict/private-tables.ts).
  • User types (src/dict/user-types-dict.ts, the only definition): super_admin (user #1), admin (only the super admin grants it), member (default), read_only (non-GET CRUD blocked), revoked. A user needs at least one type to sign in.
  • RBAC: src/utils/check-user-access.ts plus the matrix engine in src/utils/rbac/ (userTypeAssignment over UserTypeAssignmentMatrix/UserTypeDeletionMatrix).
  • Audit: src/functions/backend/logger.ts (logEvent/logError -> logs). Auth events, cron runs, every unexpected API error (safeErrorMessage -> logUnexpectedError, not for AppError), every failed or lost bot job, every failed model call (category llm, logCandidateFailure; older system rows moved at boot by migrateLlmLogs). WebSocket connects are not logged. Kept for the app setting logs_keep_days (default AppData.LogsKeepDays), deleted by the daily prune-logs.

WebSocket

/ws, session frozen at upgrade (src/websocket/types.ts). Rooms in src/dict/websocket-rooms.ts, store in src/websocket/(data)/rooms.ts. Dispatch in handle-message.ts; client handlers are folder-per-event in src/websocket/client-requests/<event>/. Non-JSON messages (twui's "twui::ping") are ignored. Server pushes: sendToUser; clients listen with useServerEvent.

Cron

src/cron/index.ts registers everything via registerCronJob (src/cron/register-cron-job.ts); one folder per task. In-process Bun.cron, UTC, never overlapping. Notable: heartbeat, sync-harness-models (hourly), run-cron-jobs (every minute, fires schedules), sync-computers, sync-mcp-servers, clear-job-steps, prune-bots-queue, prune-bot-traces (the debug view's runs, app setting bot_trace_keep_days), prune-asks, prune-orphan-media (unreferenced uploads, AppData.MediaOrphanKeepDays), prune-computer-caches (pip/npm/bun caches, __pycache__ and Chrome profile caches, skipped while a task runs there), prune-computer-homes (a computer's moved-aside old home, AppData.ComputerOldHomeKeepDays), warn-computer-workspaces (logs a computer whose workspace passed AppData.ComputerWorkspaceWarnShare of its quota, daily, reports only), prune-logs.

Admin CRUD API

api/admin/crud/[[...paths]].ts: userAuth -> read-only gate -> per-table handler in src/pages/api/admin/crud/(tables)/<table>/ -> generic fallback (super admin only). Add a table handler folder plus a case in the router.

Crew access (bots, workspaces, computers)

  • Bots, workspaces and computers belong to the install; their user_id is only the creator. Users reach them only through grants: bot_users (a worker's own chat) and workspace_users (every bot in that workspace).
  • crewRole (src/utils/rbac/crew-role.ts): super_admin reaches everything and is the only one who chats with the coordinator; admin reaches every worker and workspace; member only their grants. canManageCrew (super admin + admin) creates/edits/deletes crew and grants access; DB helpers check it themselves (assertCrewManager). A bot changes the crew only on the user's own words: add_bot_to_workspace, remove_bot_from_workspace, assign_computer, set_bot_type, create_bot, create_workspace, delete_bot, delete_workspace, delegate_task, hand_over_task and hand_over_schedule take a required because quote, checked against the human messages in the conversation (assertUserAsked, userAskedQuote, at least 24 normalised characters, crew briefs and install answers excluded); a missing session refuses the call, and a quote the user didn't write is refused (update_bot's role is a description, not permissions, so it isn't gated).
  • Access SQL lives in src/utils/crew-access/ (tested against SQLite) and backs grabChatBot, grabUserBot, grabUserWorkspace(s), grabWorkspaceBot, grabBots, grabUserComputer(s).
  • Conversations, faces and status lines are per user (bot_sessions.user_id, bot_user_faces). A job runs for its session's user, with that user's memory and reach. Page reads overlay the viewer's face (botFaceSql). Status lines never name a task. The rail row marks work with a spinner (WorkingSpinner) in the time's slot, from the face alone (working, so work anywhere for that user), and the time returns when it ends; the unread dot stays beside it. Nothing goes on the stone: no ring, badge or corner mark.

Bot types

bot_types extends bots.kind (worker | coordinator) the way user_types extends users (src/dict/bot-types-dict.ts): today only workspace_admin, each row naming its workspace (no row = just the kind; the coordinator is its kind, written only by ensureCoordinatorBot). A bot's role where it works is its kind plus the types it holds there (botTypesIn). BotTypePermissionMatrix, BotTypeTargetMatrix (keyed by role), BotTypeAssignmentMatrix/DeletionMatrix (types only) are read by the generic interpreter src/utils/rbac/type-assignment.ts. Every run reads grabBotRunPowers once and gates tools on its is_coordinator, admin_workspace_ids and can(permission), never on its own check of kind. A run's powers are its role's AND its user's. Rows from v0.2.8 and earlier (admin, coordinator) are fixed at boot by migrateBotTypes. A workspace admin gets grabWorkspaceAdminTools (delegate to members, set their workspace instructions, edit that workspace, and read its context). A plain worker gets no work to hand out, but may pass on an open task of its own to a bot it could ask (hand_over_task, hand-over-task-tool.ts): its one permission, its own list only, and BotTypeTargetMatrix is left alone so it still directs no one, the targets coming from askableBots. Set via api/admin/bots/set-bot-type. Admins are marked with AdminShield (green, beside the name, never on the stone).

Bots, sessions, chat

  • Tables: bots (kind, color #rrggbb, stone, role, system_prompt; hue is a legacy fallback), bot_user_faces, bot_sessions, bot_messages, bot_tasks, bot_task_steps (unused yet), bot_plans (a plan a bot wrote for work in pieces, its steps and their state), bot_job_traces (a run's debug view, 7 days by default). Enums in src/dict/bot-dict.ts and src/dict/bot-plan-dict.ts.
  • Sessions: one thread per user per bot in its own chat plus one per workspace; split into bot_sessions (rollover at the app setting bot_session_max_messages, default AppData.BotSessionMaxMessages, via grabBotSessionMaxMessages; titled and summarised by name-bot-session.ts from the session's opening after a reply or a task (a session with no user message, work handed to the bot, is named from the bot's own messages; grabSessionOpening; grabBotMessages reads the latest; each opening message is cut to AppData.BotSessionNameMessageChars, so a pasted brief of tens of thousands of characters costs one naming call, not a second copy of itself), summary carried into the next session only when they're linked by previous_session_id, which only a carry-over sets; older implicit links are cleared at boot by clearImplicitSessionLinks). New session (startBotSession) and a conversation with no active session always start fresh. The rollover carries over like the bot does (rollOverBotSession -> continueBotSession, falling back to the stored summary; kept for the next message while a job is open in the full session or there's nothing to carry), inside send-message, so the user's message lands under the summary. A routine and a hook each keep a thread of their own, never the chat that happens to be active: bot_sessions.routine_id and hook_id mark it, ensureRoutineSession/ensureHookSession open it closed (so it takes nothing over) with the routine's or hook's title, roll it over at the same session max into a new linked session (rollOverLinkedSession, previous_session_id, the summary opening the new one), and it is read and chatted in with ?session_id= like any session. A deleted routine or hook detaches its thread (routine_id/hook_id set to null) and keeps the messages; a silent hook's thread is the one exception to being followed (followedSessionSql: no rail row, no unread, no push, no face change) until the user writes in it: a human message takes the thread from the hook (adoptHookSession, from insertUserMessage, so a chat message and a question's answer alike), so the thread is theirs from then on and the hook opens a new one next time, while a hook that isn't silent makes its thread the conversation's active session for its run. Helpers in src/functions/backend/db/bot-sessions/. Job results land in the job's own session, even after it closes, except a reply that called continue_in_new_session (carryOverBotSession; the menu's and sessions modal's Continue in new session does the same through continueBotSession, the model writing title and summary, refused while a job is open in the session): its summary is kept on the closed session and opens the new one as a bot message (carried_from_session_id), the job's session_id moves so the answer follows, the new session is titled by the bot then (it has no first exchange to be named from), and the old one can never be reopened (reopenBotSession refuses; a thread showing it swaps its composer for a link to the new one). Session lists (rail, sessions modal) reopen a session on click, as before; a carried-over one can't be, so it opens to read (?session_id=, conversationHref). The page tells them which session it shows (announceShownSession -> useShownSession): they reload, mark it Current (greyed out; without ?session_id= the active one is), list it even when it's older than the rail's latest, and the active row then leads back. From half the session length the reply prompt suggests moving on (longSessionNote). Earlier sessions never enter the prompt (only the last one's summary): the thread can open them above a session (useOlderMessages.loadPrevious, a divider per session, quote and reply as usual), and replies get search_past_sessions/read_past_session (scoped to that user, bot and place, never the current session) when the conversation has any.
  • Coordinator: exactly one, the super admin's alone, created idempotently by ensureCoordinatorBot. Default prompt src/data/coordinator-system-prompt.ts, backfilled only when empty.
  • Routes: /admin/bots reopens the last visited bot's own chat (cookie cobble_last_visited_bot_id, <bot> or <bot>:<workspace>; the landing uses only the bot) if still reachable, else coordinator (super admin) / latest bot / first workspace / empty. Workspace and conversation pages record the visit per user (recordWorkspaceVisit/workspace_user_visits, recordBotVisit/bot_user_visits) and the rail lists both latest visited first (last_visited_at, orderByLastVisit; recorded before the crew is read, so the conversation opened is already on top in that render, and its bot leads whatever the visits say (pinned_id); a workspace nobody visited yet ranks by its creation, so a new one leads); it never decides the landing. Settings and the rail pages get the cookie's conversation, workspace included, as root prop last_conversation (grabLastConversation, access-checked, only on those paths: isPagesRailPath), shown above their rail list as the way back (RailLastConversation). /admin/bots/[bot_id] conversation (header, thread and composer at 760px, the bot panel (BotPanel) sliding in from the right when its avatar or its name is tapped, or a phone swipes that way, over the conversation rather than taking width; ?session_id= opens another of the user's sessions there: a closed one is reopened, except a carried-over one, which shows with SessionMovedBar instead of the composer, pointing where the conversation went on); /admin/bots/[bot_id]/models; /admin/workspaces/[id] dashboard; /admin/workspaces/[id]/bots/[bot_id] same conversation scoped to the workspace.
  • No model: while the bot has no text model there (bot_text_model null, kept live by the models modal), the thread shows NoModelNotice (centred when empty): super admins get Connect a provider / Guided setup, others are told the super admin sets it up.
  • Conversation loading: pages render everything server-side (grabConversationProps) except the history, which the client loads (api/admin/bots/conversation-history, merged with what's already shown, refetched on bfcache restore) and pages older messages on scroll. Rail lists go through railBots/railWorkspaces (no prompts/memory, previews cut). Every return to the page (window focus, a hidden tab visible, back online: use-refocus, AppData.RefocusGapMs) reads the crew again (use-live-crew-refresh -> api/admin/bots/live-crew -> cobble:live-crew-refreshed, taken by useLiveBots/useLiveWorkspaces) and the session's latest messages plus its bot's face, task and the step its reply is on (session-messages, use-reply-catch-up; the history's own step seeds that row on load, use-reply-progress, and a row only ever moves forward in bots_queue_updates ids), and the page polls the same while a reply is due (read with the live face, never the page's): pushes missed while the phone slept left threads thinking and faces stale until a reload. The thread follows new messages while it sits at its bottom and offers "Jump to latest" (ScrollToBottomButton) when scrolled up; End does what that button does and Home goes back to the top of the messages loaded so far, both keeping away from a field being typed in, an open menu and an open modal (typingInField, scrollThreadToTop). On a phone, pulling the thread up past its bottom lifts the newest message off the edge, opening just enough room for a lone refresh icon (a ghost button, no label; no deeper, however far the drag goes), and letting go only reloads once that full room has been held for half a second, which lights the icon (AppData.PullToRefreshHoldMs: an exhausted thread reaches the limit by accident too easily) and then turns it into its spinner for at least a second (AppData.PullToRefreshMinLoadingMs) while the conversation and the rail are read again (use-pull-to-refresh writes that room straight onto the content as the finger moves, never through a render, and owns the gesture until release; the gesture is a plain state machine in (utils)/pull-to-refresh-gesture.ts, its steps tested without a browser, which takes the pull's anchor the moment the thread reaches its end, so one swipe that runs out of conversation hands over instead of stopping dead, and reads the end with AppData.PullToRefreshEndSlackPx of slack through atThreadEnd, since a phone's fractional device pixel ratio leaves the content a hair short and demanding an exact zero made the whole gesture do nothing; PullToRefreshIndicator; dragged back down before the release, the icon hides at the travel that showed it).
  • Sending: api/admin/bots/send-message.ts -> enqueueBotReply -> wakeBotsQueue. Never import src/bots-queue/index.ts from a page or API route (pulls the bunext runtime into page bundles). Optimistic bubble in pending_messages until the saved message replaces it. A message is capped at the app setting bot_message_max_chars (Settings > General, default AppData.BotMessageMaxChars, counted on the trimmed markdown, up to BotMessageMaxCharsMax), checked by the composer before it sends (the reason shows under the input) and again by the route (messageTooLongMessage says how far over it is and to attach the text as a file). Once stored, a message is never cut: it goes into every turn whole. A message sent in Plan mode (bot_messages.plan_mode, turned on by Tab anywhere on the conversation page or the composer's Plan button, remembered per conversation in localStorage) is answered by a planning run: run-bot-reply gates every tool outside PlanModeToolNames (gatePlanModeTools: the write tools stay listed with their own name, description and schema, and calling one throws the Plan mode reason, never "there is no tool called ...", since only run is replaced; load_tools is gated too, so a deferred MCP or browser tool can't be pulled in), send_reply refuses work and working, and the computer and browser notes are left out; Retry and Run again copy the flag from the message they answer. Answering or skipping an ask_user card is not a way out: the card carries bot_questions.plan_mode from the run that asked, and postBotQuestionAnswers runs the answer as a Plan mode reply too (only Tab, or approving a plan, turns the mode off). A reply that ran in it carries bot_messages.plan_mode (jobPlanMode over the job's params) and shows PlanModeOffButton under it while the mode is still on: one click turns it off and puts "Plan mode is off, go ahead." in the composer (turnOffPlanMode, never sends), which is the click the bot's answer asks for. A Plan mode reply whose result belongs in a file or another place outside the chat may not paste it or say a write tool is missing: it says the mode stops the save and either writes a plan they approve or tells them to turn Plan mode off, and planModeFileEscape sends a reply back when it hands the save to the user instead.
  • Composer: Tiptap editor reading/writing markdown, drafts in localStorage, @ bots / # workspaces written as [bot:ID]/[workspace:ID]. Enter sends (Mod+Enter in lists/code). Up/Down walk the user's own earlier messages (use-composer-history, from composerHistoryTexts over the thread's user messages, never a crew message): Up recalls the newest from an empty input and older ones from there, Down comes forward again and back to what was being typed, a keystroke takes the input back, an open mention menu or a selection keeps the arrows. A clear button (X, disabled while the input is empty) empties the text without sending, keeping the quote and the picked files. Ordered lists are read back from digit markers only (composer-ordered-list): Tiptap also takes a./i., so a recalled "Ok. Do that." came back as item 401 with "Ok." eaten. @tiptap/react needs use-sync-external-store; the app ships an ESM stand-in in packages/use-sync-external-store-esm (file dependency + override; the Dockerfile copies packages/ before bun install).
  • Rendering: markdown via react-markdown + remark-gfm, raw HTML never rendered, component map in [bot_id]/(data)/message-markdown-components.tsx. Inline refs, all linked by link-computer-refs.ts and rendered by chips in (partials)/: [bot:ID], [workspace:ID], [computer:ID], [file:ID] (a saved file), [folder:<volume>:<owner>:<path>] (opens FolderPreviewModal, the files browser's listing over the chat, files opening their own preview; a modified click or its Open in Files goes to /admin/files), [take-over:ID:mode], [secret:ID] (masked env, Reveal/Copy), [suggestion:ID] (its suggested next steps, buttons that fill the composer), [plan:ID] (a plan, as its card: steps, the one being worked, and the buttons to approve or change them), [graphic:ID] (a bot graphic, framed inline), [task:ID] (a tracker task, opening TaskDetailModal), [setting:<section>:<field>] (SettingRefChip: the exact Settings > General page and field to change, from src/dict/general-settings-dict.ts; every group of that page also has its own page under /admin/settings/general/<section>, and its fields are anchors). A plan, questions, a proposal, a hook proposal and a secret request show in full under the message, as the card the user acts on, never behind a chip: they are blocks, so MarkdownParagraph ((partials)/markdown-paragraph.tsx) lifts those refs out of the paragraph they were written in (isCardRefHref in (utils)/card-ref-href.ts), which React would otherwise refuse inside a p. Parsers in src/utils/*-ref.ts. A chip reads its own row through (utils)/ref-view-loader.ts, which keeps only what it read: a read that failed or hung is retried (AppData.BotRefViewRetryDelaysMs, each after BotRefViewTimeoutMs), so a chip pushed with a run shows its steps or card without a reload, and a chip whose card the user just decided (primeRefView) tells every other chip naming the same ref, since a thread can carry the same card twice and the others otherwise went on saying "Waiting for you" until a reload (subscribeRefView; useBotPlan instead re-reads on server:bot-plan). Anywhere else that renders bot-written markdown with MessageMarkdownComponents (a workspace's context on its dashboard, a task's description and notes through TaskMarkdown) runs it through linkComputerRefs and provides CrewBotsContext/CrewWorkspacesContext too. A ref quoted alone in a code span still links; one inside longer code stays literal (linkComputerRefs splits out code first). A file chip opens a file from another bot's folder for a user who reaches that folder (userReachesFileScope, the same rule as its bytes), so answers another bot passed on keep working.
  • Message images: a bot message shows the images it's about under its text (MessageImages in (partials)/, on BotMessageLine and CrewMessageLine): its image attachments plus every image [file:ID] it names (liveFileRefIds, which keeps the renderer's code rules), deduped when a named file is also attached (file_id). Each is a MessageAttachment thumbnail opening the shared FilePreviewModal; in a thread its gallery is the whole conversation (sessionImageGallery + SessionGalleryContext from MessageThread): every image in the session, bot and user, in message order, deduped by URL, falling back to the message's own images outside a thread. Non-image files and unreachable refs show nothing. Named files resolve through useBotFile/useReferencedFiles (page props first, then the cached api/admin/bots/files read shared with FileRefChip). A thumbnail URL serves the original when no smaller copy was made (mediaServeWritePath), since bot files keep no thumbnail.
  • Task chips: which tracker tasks a bot message is about is the app's record, not the bot's word: a run's task tools report each task they touch (onTask: list_tasks with task_id, create_task, update_task, delete_task, delegate_task's hand-over), plus a handed-over job's tracker_task_id, into bot_messages.task_ids (also on its failure notice and its report relayed to the requester). The thread shows them under the message (MessageTaskChips) with title and status, read per viewer and only for tasks they reach (grabMessagesTasks; pushes carry them through withMessageTasks).
  • File preview: every file link (chips, attachments, files modal, task files, /admin/files) is a FilePreviewLink: a plain click opens FilePreviewModal (its header shows the size and the file's full path on the data volume, full_path, e.g. bots/3/reports/q3.md, absolute when outside it; every opener passes it; markdown rendered with the message elements, CSV/TSV as a table via parseCsv, images in ImageViewer (zoom buttons and keys, Ctrl/Cmd+wheel or pinch at the pointer, Fit, Fit width (a full-page screenshot opens that way and scrolls down), Actual size, double click, drag to pan; sized by the width attribute and centred with auto margins, never flex centring, which cuts off a tall picture's top), PDF/audio/video in place, HTML in a frame with sandbox="" (plus the media server's sandbox CSP), other text as code, the kind from filePreviewKind; Download and Open in a new tab), a modified click still opens a tab. Text is read up to AppData.FilePreviewMaxTextBytes. Never render a file's HTML on the app's origin or with scripts. Opened from a list (a folder, the files modal, a conversation's images), an image gets that list's images as its gallery (imagePreviewGallery): Previous/Next (side arrows at the far middle left/right, the header's stepper, and the arrow keys) step through them in the same modal, neighbours preloaded. Escape closes only the top modal of a stack (useTopModalEscape; twui closes every open one). The message elements and the preview import each other (through the file chips), so the preview merges MessageMarkdownComponents when it renders, never at module load.
  • Copy chat (header menu): the active session (the one on screen) as one markdown document (api/admin/bots/conversation-export -> conversationMarkdown, refs as names, message headings demoted). The clipboard write starts on the click with a pending ClipboardItem (copyPendingText), since Safari drops the gesture after a fetch. A message's Details modal has its own Copy report (messageDetailsMarkdown, the same pending write): that message's whole details, listing up to AppData.MessageDetailsCopyMaxCalls calls and failures (the route's full=1) instead of the modal's first MessageDetailsMaxCalls.
  • Asking before acting: ask_user (QuestionsNote) puts up to AppData.BotQuestionMaxQuestions multiple-choice questions (single = radios, multiple = checkboxes, optional typed "Other") on one card, once per run (a second call returns the card already up instead of throwing: a refused re-ask read as a failed closing turn and the whole answer was thrown away) -> bot_questions -> [question:ID] (its card in the message, not a chip); the message needs the user. Answers are checked against the questions (checkBotQuestionAnswers) and stored, then sent as the user's chat message (botQuestionAnswersText); Skip says so. The card belongs to the conversation it was asked in: the answer and skip routes post that message into the question's own session (postBotQuestionAnswers), never the page's bot (a card answered on the requester's page woke the wrong bot), and stripQuestionRefs takes [question:ID] out of text copied into another bot's conversation (relayJobToRequester, a crew request's outcome, an install request's answer), which would otherwise show the same card in two sessions, answered in one and left waiting in the other. Replies and user-started tasks only: never routines, hook calls or a crew request's run (no one sees those). The reply's ask_user/suggest_next_steps and QuestionsNote are gated on attended (isHiddenSession), and a task run's on can_ask (isHiddenSession checked there too): a question in a hidden session has no card the user would see (one reached the coordinator as a bare [question:22], its answer never getting back).
  • Suggested next steps: suggest_next_steps puts up to AppData.BotSuggestionMaxSteps follow-ups under the answer, once per run (a second call returns the steps already attached instead of throwing) -> bot_suggestions -> [suggestion:ID] rendered inline as buttons (BotSuggestionsRef); clicking one inserts it into the composer (ComposerHandle.insertText, never sends) and nothing waits on it, so it's shown in withTakeOverRefs, never refs, and never sets needs_you. For when the work is done and the bot offers follow-ups; when the answer decides what it does next, it's ask_user. Same runs as ask_user. Both are closing tools (ClosingToolNames, src/harness/tools/closing-tool-names.ts): the turn that writes the answer and puts the card up ends the run, after the usual review, because a reply is only the run's last message. Without that, a bot answered with the PR links the user asked for, then called list_tasks (which TaskReminderNote told it to do after answering), and the user was sent the short "still open" line alone.
  • Plans: work with several pieces that build on each other is written down before it starts, and worked one step per reply, since a bot answering such a request in one message is how a reply turns into a wall of text. create_plan (title, goal, 3 to AppData.BotPlanMaxSteps steps) -> bot_plans (one open plan per conversation, BotPlanOpenStates) -> [plan:ID] (BotPlanCard); nothing of it runs until the user approves it there, and they change the steps first (BotPlanEditModal -> save-plan), though a step already worked stays at the top with its note (planStepsRewriteProblem). Approving or picking a paused plan back up ends Plan mode in that conversation (announcePlanModeOff): the user asked for the work to start, and its steps write, which the toggle otherwise promises nothing of. Approving queues the first step as an ordinary reply job with params.plan_id, in the same conversation, so it has the bot's tools, computers, memory and files; the run gets PlanStepNote and works that step alone, complete_plan_step marks it done with what it produced (the card checks it off, pushBotPlan -> server:bot-plan), and continueBotPlan (from process-bot-job, after the notice) queues the next one. A step's reply is held to the step (planStepReviewNote): one that neither finished it, asked the user, changed the plan nor handed work on is sent back, and a blocked step or a send_reply that queued work stops the plan instead of advancing over it (started_work). It stops on its own when the user is needed (needs_you), when the reply handed work to a run (WorkStartingTools), or when an unanswered reply already waits in the session, and never counts an approval as a step: done is the app's call once no step is pending. A run that is a plan's step can't write or cancel a plan, only work it, change it (update_plan) or finish its step. An ordinary reply in a conversation whose plan is open gets PlanWaitingNote/PlanActiveNote/PlanPausedNote instead of plan tools, so a plan is only ever advanced by the app. A routine writes its plan with approve: true (ScheduledPlanNote): nobody is there to approve it, so it starts itself and the run works every step, reporting at the end. Plan tools are not closing tools: the card and one sentence about it are the reply. When a plan is one the work comes back to, the bot saves its steps with update_memory (PlansNote); a repeating job is a routine instead. A plan stays one click away however far the thread moves on: while it is open a bar sits under the conversation header (SessionPlanBar: title, status, step x of y) and opens it in a modal (BotPlanModal), and every message that belongs to it (the one that wrote it, each step report) carries a Plan chip that opens the same card. The link is bot_messages.plan_id, the app's record written when the message is saved (the plan it wrote, or the step it worked), since the job that made it is pruned; a finished plan's bar goes, its chips stay. The history read carries the open plan (history.plan), and server:bot-plan keeps it current (useSessionPlan), so the bar never waits on another read. bot_plans is deleted with its session (deleteBotPlanRows, from deleteSessionRows).
  • Quoting: selected text quotes into the composer through quotableText, which reads each ref chip as one inline label (MarkdownLink wraps chips with QuoteInlineAttribute; Selection.toString() broke a quote into a paragraph per chip).
  • A user's own long message is cut: the bubble shows the first twenty lines (max-h-[25rem], the bubble's leading-5) with Read more under it, and Show less puts it back (use-bubble-clamp.ts measures the cut text in the browser: bubbleOverflows); a pasted prompt should not fill the screen. Only what's shown is cut, so the bot, Copy chat and the export still get every character.
  • Replies/reactions: reply_to_message_id (not an FK); reactions from the fixed BotMessageReactions, toggled by react-message.ts and the react_to_message tool, pushed as server:bot-reaction. A reply's history shows the user's own reactions on each bot message in its app record (botMessagesToHarness, so run-bot-reply loads history with user_id), and the chat reply note tells the bot to save lasting preferences they show in its memory of that user; 👎 is in the set for that.
  • Attachments: uploaded on pick (upload-attachment.ts, private media, no text kept: a reply reads a document's text from the file), linked via bot_message_media. Replies read files of the last BotReplyAttachmentMessages messages that have any, and only while they're within BotReplyAttachmentMaxAgeMessages of the latest (liveAttachmentMessages: one old screenshot, being the last message with files, was re-attached and re-read on every reply for the rest of a long session); older files are only named. An upload's bytes go with its message: whatever deletes messages that carry them (deleteAskRows) unlinks them and deletes a media row nothing else points at (deleteUnlinkedAttachmentMedia), and prune-orphan-media takes what is left after AppData.MediaOrphanKeepDays (both share UnreferencedMediaSql). Tasks don't get files yet.
  • Thinking row / stop: bot-busy-state.ts decides the row's line and whether Stop shows. A plan step is a reply job the app queues with no user message before it, so the bot has the last word: ConversationHistory.open_jobs and useOpenReplyJobs (server:bot-job-update) keep awaitsReply true, and the row stays up thinking until the step's answer lands. Stop (api/admin/bots/stop.ts, stop-bot-jobs) fails every open job of that bot for the user, aborts the running handler (job-abort-registry) and drops late face updates.
  • Running a reply again: the bot's last word in a conversation (MessageThread reads its own last bot message, crew messages aside) offers Run again (retry-reply-button.tsx -> api/admin/bots/retry-reply, eligibility in rerunReplyProblem), whatever it was: an answer that went out, a stopped run's notice, a task run's failure. A failed reply's notice carries bot_messages.failed_job_id (set by notifyBotJobFailed, not an FK); while it still needs_you, its actions show Retry instead (the same action, worded for a failure, eligibility in retryReplyProblem), which clears the notice's needs_you. Either way the route queues a reply to the newest user message with params.retry_of, so run-bot-reply bypasses the silent finish gate (a reply run again doesn't look unanswered) and gets RerunReplyNote; a retry whose message carries failed_job_id also reads that job's last_error (grabRetryFailure -> RetryFailureNote), so it knows what the failed attempt claimed and never did instead of setting off on the same premise; the thread leaves that message out (only a bot message is hidden, threadMessages) and shows its thinking row until a newer bot message lands (rerun_after_id in conversation.tsx: the message it runs again is the last one and looks answered, and a stopped run's notice would say it stopped right above the row). A run that was stopped, or ended without a word, leaves the user's own message last with nothing on its way: the thread says so there and offers the same Run again on it (unanswered-reply-row.tsx; the route answers it when rerunReplyProblem sees it is the session's last message), instead of a thinking row that would never move (awaits-reply.ts, which holds the row back once the open replies are read as none). Failure notices are the app's record, never the bot's words, so botMessagesToHarness skips them.
  • Debug view: what a run did in order: each turn with what the model reasoned (stripThinkTags's reasoning, or the provider's reasoning/reasoning_content) and answered, each tool call with the arguments it was sent and the answer it got (and its duration), and the loop's own events (wrap_up, redraft, review, incoming, steps_low). runTextLoop emits them through Params.trace into bot_job_traces (never bots_queue_updates, which the clear-job-steps cron deletes a minute after a job ends). While a run works, the thinking row's bug button, beside Stop (BotThinkingRow), toggles a 250px strip under it ((partials)/trace-panel.tsx, (partials)/trace-log-line.tsx: one line per step, following its newest line while scrolled to the bottom), read live through (hooks)/use-bot-trace.ts and api/admin/bots/trace; that toggle stays as the user left it in every conversation (on this device, per user: useDebugOpen over readDebugOpen/rememberDebugOpen, AppData.DebugViewStorageKey). When the run ends its logs are tied to the message it answered (attachJobTracesToMessage, from the job helpers) and read in that message's Details modal, under a Debug logs tab beside Details ((partials)/message-debug-logs.tsx, (hooks)/use-message-trace.ts, api/admin/bots/message-trace), which copies itself as one markdown document (CopyDebugLogsButton over messageDebugLogsMarkdown), which checks the message's session for the user or a super admin). Every entry is redacted before storage (insertBotJobTrace with the run's reachable envs, plus the task run's computer redaction for what the bot captured), cut to AppData.BotTraceTextMaxChars/BotTraceArgumentsMaxChars/BotTraceResultMaxChars (an argument's path survives whole, toolArgumentPath: a write's path is what a reader needs), at most BotTraceRowsPerJob entries per run and BotTraceJobsPerSession runs shown, kept for the app setting bot_trace_keep_days (default AppData.BotTraceKeepDays, daily prune-bot-traces). Pushes carry only BotTraceData (job_id, session_id): an open view reads the entries it doesn't have.
  • Voice: mic -> api/admin/bots/transcribe.ts; play -> GET speak-message streamed into <audio>. Nothing recorded is stored. Both disabled with a note when the harness has no model.
  • Pictures: image_media_id (private media, bot-image/workspace-image), via set-profile-image.ts, the set_picture tool or update_workspace. Bytes are copied, never moved; only picture-paradigm rows are deleted on replace. Format kept by imageOutputFormat.
  • Colour: only src/utils/bot-color.ts resolves/validates colours and stones (resolveBotColor, resolveBotStone, botColorNeedsPaperFace); new bots get pick-free-color.ts.
  • Avatars: BotStone draws the stone inline with the colour as SVG fill and the face as eyes. Coordinator: ink body, paper eyes. Each face moves the stone and its eyes (keyframes stone-* in main.css; body in BotStone, transforms only from its base, never redrawing the outline or cut; eyes in BotStoneFace: idle blinks at a per-bot pace, working glances, done hops once, asleep breathes, needs-you nudges; off under reduced motion; still for the logo). Never put a stone in a circle/badge or add outline/shadow. The wordmark is vector (Wordmark), never live text.
  • Copy helpers: src/utils/crew-status.ts, src/utils/relative-time.ts (relative timestamps only).

Prompt and memory

composeBotPrompt (src/utils/compose-bot-prompt.ts, via grab-bot-prompt): core system_prompt, install-wide append (bot_system_prompt_append), then in a workspace its context, the bot's instructions there and the run's user's role there (workspace_user_roles), then core memory, per-user memory (bot_user_memories), workspace memory (workspace_bots.memory). Core memory is never about one user. update_memory defaults to user (workspace in a workspace); core only for what holds for everyone. Whole-text replace, capped at AppData.PromptMaxLength. Each whole-text replace (update_workspace's context, set_bot_workspace_instructions, update_memory) refuses once a save that would drop a section (markdownHeadings) or cut the text below AppData.SharedTextShrinkShare of its length (sharedTextProblem, src/utils/shared-text-guard.ts), until the caller passes replace: true; the context is read before it is rewritten with find_workspace include_context (coordinator wherever it works, and a workspace admin), and each of them reads its save back before reporting it. Each memory section says it shapes how the bot does the work, never what it does beyond the request.

Every run also gets RequestScopeNote (src/data/harness-prompts.ts): the user's request sets the scope, and crew changes (create, place, remove, assign a computer, change a role) and handing work out (delegating, handing over a task or routine) happen only once the user asked for them, through one ask_user card in a reply or task, or as a proposal in a run nobody watches (routine, hook call, crew request). The way they named is part of the request too: a tool, app, service, provider or path they asked for is the one to use, a blocked one is reported and asked about, never swapped for another way that reaches the same result, and a probe is not a deliverable. Memory, habits and the bot's own initiative never widen a request.

Queue (bots_queue)

  • Kinds (BotJobKinds): reply (chat answer, no task row) and task (long work, usually on a computer). bun-sqlite isQueue table. Helpers in src/functions/backend/db/bots-queue/: enqueueBotJob, claimBotJobs (kind-filtered atomic claim), updateBotJob (false once lost/cancelled), completeBotJob, failBotJob (backoff or fatal), deferBotJob (all models resting: attempt refunded, face asleep), cancelBotJob, stop-bot-jobs.
  • Handler src/bots-queue/index.ts: separate reply/task slots, heartbeat, a per-attempt deadline for replies (AppData.BotJobAttemptTimeoutMs; a task run has none, since its script may run for hours, and Stop ends it), one task per computer and one reply per session (createKeyLock). Work in run-bot-job.ts -> run-bot-reply.ts / run-bot-task.ts. Throw BotJobFatalError for failures retrying can't fix. A computer that's down (isComputerDown: failed, dead, exited) is one: queueBotTask (a reply's send_reply work, or start_task) refuses it and a task run on it fails at once.
  • Every model turn is a step in bots_queue_updates (tool names, never arguments; describe-job-step.ts, labels in JobStepToolLabels), pushed as server:bot-job-update by the live relay only. Steps feed the live working row alone: the clear-job-steps cron deletes them AppData.BotJobStepsKeepMs after the job ends, however it ended, keeping their count on bots_queue.steps. Never delete them the moment a job ends (the relay would miss the last ones). A job queued by a tool (enqueueBotJob, the queueBotTask path) wakes the queue and pushes server:bot-updated itself, so a run queued behind another on the same computer shows and starts at once instead of waiting for the poll; a failed run closes its own bot_tasks row (notifyBotJobFailed), since a row left active kept a conversation's progress on a run that had failed months before (a queued run creates it active; only complete, cancel and stop closed it before).
  • A task run plans before it starts: planBotTask (from run-bot-task) spends one turn, no tools, on the very system prompt the run then sends, so the provider's cache serves it and it costs little more than the plan. The answer is a bounded JSON plan (BotTaskPlanSchema, caps in AppData.BotTaskPlan*) that opens the run as taskPlanNote and shows as its first step line; shouldPlanBotTask keeps it off short runs (AppData.BotTaskPlanMinSteps). A plan that can't be written or read starts the run unplanned, never blocks it. The wrap up is told what is on disk: a task run passes Params.wrap_up_note, which runs worktreeSummary over the run's folders (git status --porcelain and git diff --stat per repository, nested ones included, at most 5) and puts the machine's own account in front of the wrap-up prompt, so the report is written from the tree and not from the run's memory of writing it. The files the brief names are checked once, before the run starts (namedFilesNote, over namedFiles): a path that isn't on the computer but is still in the bot's files is handed over as its [file:ID] with export_file, and one with no copy anywhere says plainly not to go looking through the machine or the user's accounts. It is the app's answer, not the run's guess: a source a rebuild took off the computer once cost a run thirty turns probing the container and then the user's own accounts for a copy the app was holding the whole time.
  • A reply ends with send_reply: a reply run's answer is not its prose. The last turn must be send_reply({status:"done"|"working"|"blocked", work?, message?}) with the message beside it or in its message/text argument (replyTextFromCall: a model that wrote the message into the call instead of the turn lost six production answers to "doesn't take text"), and assistant text with no tool call is a draft the loop returns to the model (replyDraftNote, up to AppData.HarnessReplyDraftsMax) rather than a message the user sees. A bare send_reply does not ship that draft on the first pass (replyNoTextNote): the model writes the whole message again in that turn, which is also the only turn that may call suggest_next_steps or ask_user beside it (any other tool is replyClosingMixedNote and unsent). A message written in the turn that put a card up (ask_user/suggest_next_steps with no send_reply) is kept as card_text and goes out with the call that closes it: that sentence is what the card belongs under, and asking for it again left the model with nothing to say (session 146). A review send-back clears draft_text and card_text and the reminder flag, so a refused answer is never carried again (the same faulted text went out on every bare send_reply and used up the rewrite budget). A draft that stops in a table, a fence or a bare marker (unfinishedAnswerText) is sent back once and never carried. A run that still ends with no message fails saying so rather than that its answer was wrong (unsentAnswerMessage). status:"working" must queue work ({title,instructions,computer_id?,separate?,max_steps?}, through queueBotTask, the same guards and brief as start_task) or follow a run already started from this reply, so a message that says work is running can only exist when the job does; done and blocked carry no work, and work beside either is refused. start_task is not a reply tool (it stays in task runs for a hand-off), send_reply is a closing tool beside ask_user/suggest_next_steps, and a task report ends the same way. If the run never closes, the job fails honestly and the thread offers Retry; work queued earlier in the run is cancelled with the unsent message. The review reads the status: a done/blocked message that says work is under way is faulted even when some unrelated run is open, and hasOpenWork takes the current job_id (exclude_job_id) so a task report can't count its own job as open work.
  • A bot can't vouch for itself: a run's tool calls (tool_uses, names and ok, never arguments) go to the wrap-up turn when steps run out and onto the result message as bot_messages.tool_log; history follows each recorded bot message with an [App record: ...] line (botMessagesToHarness), and copies of that line in an answer are stripped (stripAppRecords, which shares the line shape with appRecordLines). Before a reply or a task report goes out, reviewBotReply (the loop's review, wired for both by reviewRunAnswer) sends it back when it names a [file:ID]/[task:ID]/[graphic:ID] that doesn't exist for the user, a task named in plain prose (task #16, mentionedTaskIds) whose row is gone (a row the user cannot open is left alone), a [setting:...] ref the app can't resolve (unresolvedSettingRefs), a [suggestion:ID]/[question:ID]/[plan:ID] ref it wrote itself (AppCardRefTools: the app adds those from the tool that made the card, so a written one is made up or copied from an earlier message and the user reads "not available"; stripCardRefs keeps them out of the answer and out of the model's own history, since the stored text carries the ref the app appended under it, which is how one began writing [question:24] at a card it never made), a [proposal:]/[hook-proposal:] ref no row backs (the model guessed [proposal:19] 85 s before that row existed, and the user was told three times a proposal had gone out when none had), asks the user to choose in the text (a question, or an offer ending in ":" such as "Want me to:", with a numbered or bulleted list of options under it, proseChoiceQuestion) without an ask_user call in the run, so they would retype an option instead of clicking one (session 133 shipped two), or says work is under way, that a report will follow, or that it is about to do the work ("Let me check", "I'll connect and inspect", "next I'll", "Starting the conversion run now") (claimsWorkUnderWay, which reads a promise only when its own sentence is the commitment, so an offer waiting on the user is left alone) with no run this reply started and nothing open from the session: bots wrote "I'm scanning now" plus made-up results in one answer, and a reply promising to check the articles and then starting nothing left the user waiting for a report nobody would send. It also faults the app's own state described from nothing (replyAppStateClaims, skipped when read_message_usage/read_settings answered): how the model "routing" resolves or which model the tool sends, a run "killed" or "stopped" (Stop is the user's), and the model rest called unlimited or restart-only, each written by a bot that had only an HTTP 404 to go on and told the user a model and a mechanism nobody had configured. Review runs on every answer it writes, up to AppData.HarnessReviewRewrites rewrites (a repeat of the faulted message is told so, repeatedAnswerNote); past that the answer is never sent and the job fails instead (review_note -> BotJobFatalError, a reply and a task report alike; a rewrite that lands on the wrap up is reviewed there and refused, not sent on), since a model that kept writing the same thing sends the claim anyway. A fault must be something the bot can stop making: only a whole line in the app's own record shape naming tools this reply didn't call is a forgery (unsupportedAppRecordLines) - the same text quoted inside a sentence is the bot naming its mistake, and job #468 faulted three rewrites in a row for that quote alone, so the lie stayed and the correction never reached the user. No fault note may itself contain the shape it faults or a claimsWorkUnderWay phrase. Tool names copied into a list (WorkStartingTools, AppCardRefToolNames, WritingToolNames, WrapUp*ToolNames) are pinned to the tools the harness declares by src/harness/tools/tool-name-lists.test.ts (ask_crew outlived its rename to ask_bot, so a reply that really had asked the crew was faulted for saying so). A long bot message whose run called no tools shows "No tools used" (MessageNoToolsChip).
  • A reply's send_reply work and start_task/delegate_task jobs are runs, not tasks: their results say Run #<job id> and that list_tasks doesn't show them (bots sent users to the tracker for them). queueBotTask refuses a second open run in its session on the same computer unless separate (it would only wait behind it) and says how many runs are ahead on that computer. Its max_steps (params.max_steps) caps the run below the install's limit; the brief alone never did. Nothing wakes a bot when a run ends, so different follow-up work is queued at once with separate, never promised for later (send_reply's work, start_task, chatReplyNote).
  • Replies take in messages sent mid-run (incoming, IncomingMessagesNote, redraft); separate requests are acknowledged with send_message (interim). A queued reply finishes silently only when a finished reply already read every user message (hasUnansweredMessage), never by who wrote last; a retry (params.retry_of) always runs. Task runs take them in too (taskIncoming, only runs the user follows: no routines, hook calls or rooms): everything the user wrote since the run was queued, at the start, between steps, past a report not yet out and by the wrap up (incoming_notes, TaskIncomingNote); a correction changes the work, anything else is left to the chat, and crew messages to the reply they wake. A reply is told which runs open in its session hear the user (openRunsNote), so a correction never starts a second run.

Live updates

Server push only. pushBotNotice (server:bot-message, server:bot-updated), pushBotUpdated (to the bot's whole audience), server:bot-created|removed, server:workspace-created|updated|removed, server:computer-updated, the debug view's server:bot-trace (just the job and its session), and a plan's card server:bot-plan (just its id and conversation). Deletions push to the audience read before the delete. liveRelay (src/live-relay/) polls the DB every AppData.LiveRelayPollMs so work from other processes shows; clients dedupe by id. useLiveBots keeps rail and header current. A push's task is a list of every active task that user has on the bot (grabActiveBotTasks), and the conversation picks its own session's (ownTask), since sending only the newest one blanked the row whenever another conversation of the same bot had a run open; a page also keeps polling (use-reply-catch-up running) while its session has open jobs or an active task, not only until a reply lands, since a run queued behind another on the same computer starts much later (queueBotTask refuses a second one there, and the face then says which wait it is: botWaitsOnComputer picks BotComputerBusyStatusLine over BotWaitingStatusLine).

Crew requests (bot_asks)

A worker reaches another bot only through the coordinator's gate: ask_bot (every worker run with a session except hook calls; never the coordinator) queues a request (createAsk) for the run's user and place. Who can be asked is the app's call (askableBots): in a workspace its members, else every worker the user reaches. Whether the request should be passed on is the coordinator's judgement, in its instructions (AskGateNote); reach, membership, depth and the open cap are the app's. The gate is one turn of the coordinator with no tools (runAskReview, queued by enqueueAskReview, dispatched from run-bot-job on params.stage == "review") answering bounded JSON (AskDecisionSchema: approve, redirect or refuse, the bot, and a one-sentence reason) which applyAskDecision carries out. A refusal ends the request (refused) with its reason; an approval or a redirect sends the brief to the target (enqueueAskAnswer) as one reply job in a new session of the target's conversation with that user for the request's workspace (startBotSession with workspace_id, so the run keeps its workspace context and the conversation they were in closes; never a hidden session), titled from the request, where the brief lands as a crew message naming that workspace (from_ask_id, askRequestMessage, pushed live) and the answer as the bot's reply. The answer can start runs of its own (send_reply's work, start_task, delegate_task): the request stays working while any run in its answer session is open (onAskJobEnded checks hasOpenWork), the acknowledgement is never relayed as the outcome, and each run's result comes back to the asking bot's conversation as it lands (askUpdateMessage while more is open, the last one closing the request answered); a child run carries params.ask_id so its result is routed, and update_requester sends the asking bot a short interim word, never the final result. An answer that only promises work without starting any still fails the request (claimsWorkUnderWay, exempt when a WorkStartingTools call really ran). The target's own chat (and any other place it is read from) shows the request's row, whose Open link appears only outside the request's own thread (answer_ask.session_id != session_id), while the session carries AskSessionBar, built from previous_session_id (recorded when the request took its session, null when the bot had no conversation there before it, an empty active session counted as the request's own, askPreviousSessionId: with nothing to go back to, the bar is not shown at all), back to the conversation the user was in; an outcome message carries the [ask:ID] pill (askRef, AskRefChip, api/admin/bots/ask) which opens the session it ran in, in the bot that answered it; only the gate's own review run uses a throwaway session (ensureAskSession, status ask, deleted when empty). Stopping the target's run ends the request too (stopBotJobs reads params.ask_id and the answer-session link, then stopAsk; cancelAskJobs matches the review session, the answer session and any job carrying params.ask_id), and the bot that asked is told why and woken for it (stopAsk's reason into askOutcomeMessage); stopping the asking run still ends it silently, since that bot is the one that was stopped. The outcome goes back to the bot that asked as a crew message in the conversation it asked from, which wakes it (finishAsk), except when the user stopped it. Every session query that lists or picks a conversation must run through them (visibleSessionSql drops a crew request's session; followedSessionSql also drops a silent hook's thread); an answer run is a normal conversation on purpose. The gate fails closed: a decision that can't be written or read, or a run that can't happen, ends the request as failed (onAskJobEnded, from complete/fail) rather than leaving it open. Files the answer cites that the asker can't reach but the target can are copied into the asker's folder (crew/ask-<id>/) and the refs repointed (shareAskFiles). Caps: AppData.AskMaxDepth (nested requests, parent_ask_id; a bot waiting up the chain can't be asked), AskMaxOpenPerBot, AskBriefMaxChars. A request's run shows on the target bot's face and in its thread (the thinking row says SEO Expert is answering Software Engineer's request in Moduletrace LTD… with Stop, from grabConversationAsk; answer_ask in the page props, answering_ask in botBusyState) and pushes no message or notification of its own (the brief is an ordinary conversation message), and counts like any reply when a face is put back after another job (grabRunningBotJobFace leaves out a silent hook's and a crew request's run; answeringAskFace keeps an answer run's face while it works, since a sibling job's completion would otherwise put the bot to sleep mid-answer). A bot reads its own requests with list_asks (ids and statuses from the app, never its memory), so it stops guessing what it sent. A task run opens with the user's own words that asked for it (taskRequestNote, from bots_queue.message_id; empty for routines, hook calls and crew requests) and then the bot's brief, which is only a summary, and gets its bot's open and recent requests (grabCrewRequests, crewRequestsNote), so it doesn't ask twice. The user sees an outcome only in the asking bot's conversation (there is no page for requests) and can Stop the run that asked (stopAsk, stopAsks). Retention: ended requests go after the app setting ask_keep_days (daily prune-asks) and past ask_max_per_place per place, oldest first (pruneAsksSql; pending and working requests, and ones a pending request was asked from, are never pruned; deletion through deleteAskRows -> deleteSessionRows, which clears each session's job steps, traces, jobs, billed token_usages and messages first, so no child row is left behind for the next db:schema). Sessions from before this feature (bot_sessions.status = 'chatroom') are deleted at boot by migrateChatroomsToAsks.

Workspaces

workspaces (description, shared system_prompt, default computer_id (not an FK), archived), workspace_bots (per-bot instructions and memory there; coordinator is an implicit member), workspace_computers. First computer linked becomes the default. A workspace's models are what its bots use without models of their own, then the defaults. A user's role in a workspace (workspace_user_roles, plain text, one per user and workspace) tells every bot there who it's working for; it's not their bio, the user never sees or sets it, and only crew managers set it, an admin never a super admin's (canSetWorkspaceUserRole, checked in setWorkspaceUserRole). Set from the workspace's settings (People, everyone who works there: workspacePeopleSql), the user's settings (Roles in workspaces) and by the coordinator (list_workspace_people/set_user_workspace_role, replies and tasks, saved as the run's user so the same rule holds). It stays when access is taken away, shown and used only while they work there. A bot's instructions and memory there (WorkspaceBotModal/WorkspaceBotForm, crew managers) open from the workspace's settings, the bot's settings and the conversation menu's "Instructions here" (loaded on open). Helpers in src/functions/backend/db/workspaces/ are access-checked; structural ones are crew-manager only.

Computers

  • Our own image (computer/, Debian 13, AppData.ComputerImage, or the app setting COMPUTER_IMAGE), one docker container per computer on AppData.DockerNetworkName, managed over the docker socket (src/functions/backend/docker/). Google Chrome on amd64, Debian's Chromium on arm64 (Google ships no arm64 Linux Chrome), headful on Xvnc (an X server that is also a VNC server, on loopback), never launched by automation (no automation flags), so it's as close to a real browser as possible. Inside, one agent (computer/agent/, Node, no dependencies, bundled by Bun at image build) supervises Xvnc, the session bus, Chrome, Playwright MCP and ttyd and serves one port: /health (open), /api/exec, /api/files/* (shell and files, as gem or, with run_as, a worker's own account), /mcp (proxied to Playwright MCP on loopback, --shared-browser-context --codegen none --no-webmcp), /desktop/ (the screen: noVNC, its websockify socket bridged to Xvnc by the agent), /terminal/ (ttyd). Every request but /health needs the computer's token (computerToken: HMAC of the id with ENCRYPTION_KEY, given as COBBLE_COMPUTER_TOKEN), so another computer's bot can't drive it; the app's client is src/functions/backend/computers/. Any change under computer/ bumps the tag in AppData.ComputerImage (the release workflow builds a tag only once; bun run build:computer builds it locally); bump ComputerWorkspaceLayout too when existing computers must move to it. containers records every container except the app's own. createComputer + background provisionComputer (status creating until the health check passes; while setting up or restarting it touches the row every ComputerSetupHeartbeatMs, keepComputerSetupAlive, so one the app lost to a restart (computerSetupInterrupted) shows as failed with Retry and sync-computers starts it again). A setup that fails while the old container still runs (a new image that couldn't be pulled) keeps it running on its old layout (setup_failed_at, migration retried after AppData.ComputerMigrateRetryMs), and a failed row whose container docker runs anyway is revived (reviveFailedComputer, from sync-computers and grabComputerMcpUrl). Resource changes recreate the container.
  • Only /home/gem/workspace is mounted, from DATA_DIR/computers/<id> (with bots/, workspaces/, marker AppData.ComputerWorkspaceMarker), plus the browser profile and any host directory; the rest of home lives in the container.
  • Browser profile: DATA_DIR/computer-browsers/<id> mounted at ~/.cobble-browser, which the agent starts Chrome with (--user-data-dir, --password-store=basic so the cookies' key is the same in every container), so logins, extensions and site permissions survive restarts and recreates. Seed prefs (computer-browser-preferences.ts) are written only when missing; stale Singleton* links are removed before each provision and before each Chrome start. The agent stops Chrome with TERM on docker stop, so the profile is saved. Its regenerable cache is cleared at every start (pruneProfileCache: HTTP and code caches, shader/GPU caches, extension assets, the component updater's CRX cache, only while no browser runs) and the HTTP cache is capped at DiskCacheMaxBytes (--disk-cache-size), so the mounted profile holds logins rather than gigabytes. It keeps no saved passwords: pruneProfileSecrets deletes Login Data*, Account Web Data and Web Data in every profile at each start, and the managed policy turns the password manager, card and address autofill and Chrome sign-in off (SyncDisabled, BrowserSignin: 0), so no page a bot reads is filled from a vault (site cookies stay, so the user's own sites stay signed in). An idle browser is parked: the virtual screen has no GPU or window manager, so the tab in front is always on show and drawn in software at full rate (one animated site took a core or two); after COBBLE_BROWSER_PARK_AFTER_SECONDS (default 180) without a /mcp call or screen view the agent puts a blank tab in front of each site on show (createBrowserParking, over its own CDP client), and the next /mcp call or view brings them back first. Pages are composited in software (--disable-gpu-compositing, WebGL unchanged) and the policy sets TabDiscardingExceptions: ["*"] so a parked tab never reloads. Bumping AppData.ComputerWorkspaceLayout recreates every computer once (migrateComputerLayout, skipped while a job runs on it). Default extensions (ComputerBrowserExtensions: Cookie-Editor, normal_installed: can be turned off, not removed) come from a managed policy written as root into the running container (syncComputerBrowserPolicy, on provision and every sync-computers run), not a mount, so existing computers get new ones without a recreate; Chrome installs them live. Deleting a computer keeps its directory. Outside docker (dev) containers are reached by IP (pickReachableAddress).
  • Settings per computer (super admin, its settings page): resources, and its browser (browser_settings, ComputerBrowserSettingsSchema: timezone, languages, screen, scale (Chrome's device scale factor, 125% by default: larger text in bots' screenshots), sandbox, lightweight (for small hosts: --disable-gpu, so the GPU process loads no Mesa and WebGL is off, reduced motion, no smooth scrolling or component downloads, Xvnc at LightweightFrameRate fps), extra Chrome and Playwright MCP flags), passed as env (computerBrowserEnv); saving either recreates the container. Chrome reads only one --disable-features=/--enable-features=, so browserArgs merges the agent's with the extra flags' (mergeFeatureFlags). Flags that would open DevTools or MCP around the token are refused (ComputerBlockedBrowserArgs/ComputerBlockedMcpArgs) and dropped again by the agent (computer/agent/blocked-args.ts; keep both alike). Rebuild (api/admin/computers/rebuild-computer) pulls the image again (keeping the local one when the registry has none) and recreates the container; files and logins stay.
  • The workspace has a limit (computer_workspace_quota_mb, Settings > General, default AppData.ComputerWorkspaceQuotaMb, 0 = none): it is the one folder on a computer mounted from the data volume, so it is what can fill the host. The agent measures it (GET /api/usage -> grabComputerUsage, du -x (so a mounted host folder neither counts nor gets walked) cached 10s, per-folder figures with it: bots/<id> and workspaces/<id>, highest first); the app refuses a write that would pass it (computerWorkspaceRoomError in computer_write_file/computer_edit_file), reports it after computer_bash and after a browser call that wrote a file (computerWorkspaceFullWarning, screenshots and downloads included) and bash still works, since it is how a bot cleans up. A refusal names the folder holding the space and whether the run can clear it (computerWorkspaceSpace: its own folder or its workspace's, else another bot's, which it can only report); nothing prunes that folder, so the daily warn-computer-workspaces cron logs an install past the quota rather than letting it fill quietly. A run's caches go to the account's own home inside the container, never its folder (computerCacheEnv).
  • One main computer (ensureMainComputer), whose coordinator grant is locked (isLockedComputerAccess). With MAIN_COMPUTER_URL set (dev) it isn't provisioned. Only super admins create/delete/retry/restart computers. Restart (ComputerRestartButton, in the shared viewer modal, so every computer modal has it) restarts the same container, so what's installed stays, even with a job on it (restartComputer, clearing Chrome's Singleton* links while stopped; a container docker lost is provisioned instead).
  • A bot's effective computers (grab-bot-computers): the workspace's in a workspace; otherwise direct grants plus its workspaces' (coordinator: all); bots.computer_id first. Only a running (healthy) computer is reached (grabComputerMcpUrl ready, computerNotReadyMessage).
  • Folders: a run works only in its user's folder (cwd, HOME), its bot's and its workspace's (computerRunDirs, withComputerDirs, resolveComputerPath). A worker sees them through its home: /home/cb-<bot>/workspace (a link the agent keeps to bots/<bot>, checked every request by ensureRunUser; the rest of the home stays in the container and is never kept), with users/<user> and, in a workspace, workspaces/<id> (a link to the shared workspaces/<id>) inside it; the coordinator works in bots/<bot>/users/<user> and reaches the whole workspace. Paths are checked on their real place (computerWorkspacePath) and shown to a worker its way (computerRunPath); computer folder refs take either spelling. Linux enforces it between bots: every worker works as its own account cb-<bot> (uid 100000 + id, no sudo, ComputerRunDirs.run_as -> the agent's run_as, made by ensureRunUser, commands through setpriv --init-groups), owning bots/<bot> (2770); a workspace's folder (root's) belongs to group cw-<id> its bots join. gem, and so Chrome, has no way into either (a page could show another bot's files): a worker's downloads (collectComputerDownloads), uploads and files saved by name (withWorkerBrowserFiles) pass through a folder of the call's own and are copied by the worker's account (sudo -u), never written by gem into its folder, and a worker opens no file: URLs (it serves its pages on localhost). Its env files are in its own home. A worker can't reach the computer's services: the agent's nftables rule (guardServicePorts, container CapAdd: NET_ADMIN) resets its connections to the agent, CDP, Playwright MCP, VNC and ttyd, and the X display needs gem's cookie; without the rule the agent refuses everything for a worker (never falls back to gem). The agent reads files for a worker only inside its folders and home, checked on the open descriptor (openRunFile), and writes as the worker (writeFileAs). Only the coordinator works as gem (sudo). Users within one bot's folder aren't separated by Linux (same account). Keep computerWorkerAccount and runUserFor alike.
  • Installs: workers install pip/npm packages into ~/.local of their folder themselves; anything needing root goes through request_install (worker task runs the user follows) -> install_requests -> a coordinator task on that computer in the super admin's coordinator conversation (createInstallRequest, fenced installRequestBlock, InstallRequestNote, answer_install_request); when that job ends however it ends (settleInstallRequest, from the job helpers) the answer lands in the worker's session as a crew message (from_install_request_id, isCrewMessage) and wakes it. Stop also ends a worker's leftover processes on its computers (endWorkerProcesses).
  • Tools: the app's own computer_bash, computer_read_file, computer_write_file, computer_edit_file (src/harness/tools/computer/, paths through resolveComputerPath), plus export_file, which copies one of the bot's own files onto the computer (the inverse of import_file, AppData.BotFileExportMaxBytes), and Playwright MCP's browser_* (minus ComputerMcpExcludedTools: close, resize, config, browser_run_code_unsafe; withComputerDirs checks file: URLs, paths and filename). Playwright MCP returns only browser_snapshot inline: actions save their snapshot and console log in its own folder (ComputerBrowserOutputDir, outside every run's folders), so withBrowserOutputs turns those links into the tool that reads them, and moves what Chrome finished downloading (ComputerBrowserDownloadsDir; Playwright over CDP never sees downloads) into the run's downloads/ after each browser call. An action Playwright killed waiting for its element to settle (5s, --timeout-action's default; a page that animates never settles) is answered with browserSettleTimeoutNote (browserRecoveryHint): retrying it only buys the same timeout, browser_evaluate drives it. Each command is its own bash -c in its own process group, stdin /dev/null, and has no time limit of its own: computer_bash asks for none unless the bot names timeout (an install can cap what a bot names with AppData.ComputerCommandMaxSeconds, 0 = no cap), so a long script runs for hours, and the command is killed with its children only when the call is aborted (Stop), so nothing blocks the computer; the agent keeps that answer's connection alive with a space every CommandHeartbeatMs while it runs, since the app's fetch drops a connection that stays silent for about six minutes. Background work (nohup ... &) doesn't hold the call. A command that would throw uncommitted work away (isDestructiveGit: git checkout -- <path>, restore, reset --hard, clean, stash, switch -f, git rm, worktree remove) is snapshotted first (gitSnapshotScript -> <bot folder>/.cobble/pre-destructive/, tracked diff, index and untracked files - ignored ones too for clean -x - across every repo the command touches (git -C, cd), newest 40 patches kept) and the result says where the patch is and how to apply it: the command reports success either way.
  • Viewing: /computers/<id>/ proxy (handleComputerProxy, strips app cookies, adds the token, bridges websockets) passes only the view paths (computerProxyPathAllowed), never the agent's API or /mcp (those are the app's tools, with the folder rules). Modes (ComputerViewModes, computerViewModesFor): Browser, the computer's screen (noVNC, scaled to the frame; its size is the computer's setting, a viewer can't resize it), so Chrome shows whole: tab strip, address bar, menu, extensions, drop-downs and prompts (no window manager, Chrome's window fills the screen), and Shell (ttyd as gem, for crew managers only, crew_only: it reads every folder there). Never draw a stand-in browser UI around a page: the user wants Chrome itself. computer/novnc/cobble-clipboard.js (added to noVNC's page) makes Ctrl/Cmd+V paste the user's clipboard and copies the computer's back; browsers allow that only over HTTPS or localhost (otherwise noVNC's side panel). Chrome's --window-size is in scaled units, so the agent divides it by the scale. No code editor in the image; a mode can be added to ComputerViewModes. Old [take-over:ID:code|desktop] refs open the first mode; take-overs ask only for modes every user can open. Take-over: ask_user_to_take_over writes [take-over:ID:mode]; "Hand back" sends a chat message; tasks stop and report rather than wait.

Host directories (host_directories)

A folder on the host machine shared with bots (super admin, Settings > Host directories). host_directories (name, source as the docker daemon sees it, slug, created_by), linked to computers (host_directory_computers) or workspaces (host_directory_workspaces), each link read-write (default) or read-only. Where it shows: a computer link is mounted for every bot reaching that computer at bots/<bot>/hosts/<slug> (the worker sees /home/cb-<bot>/workspace/hosts/<slug>), a workspace link at workspaces/<wid>/<slug> (in the workspace's shared folder). Both sit inside computerRunDirs' roots, so no agent path rule had to change; the mount points are made by prepareHostDirectoryMounts and docker's CreateMountpoint: false (HostConfig.Mounts, never Binds), so a missing source fails the setup instead of docker making a root-owned folder (the folders belong to the run accounts, so a dev app running as a plain user gets EACCES and makes them with a throwaway root container over the computer's folder instead). Mounts only exist at container creation, so reconcileComputerHostDirectories (after every link change, and from sync-computers) reprovisions a computer whose metadata.host_mounts (hostDirectoryMountEntry entries) differ, skipping a busy one (isComputerBusy; the cron retries) and MAIN_COMPUTER_URL ones. A link is all it takes: Cobble gives every bot that sees the folder access to it itself. applyHostDirectoryGrant computes the uids the live crew implies, runs grantHostDirectory (a throwaway container of the computer's image as root, setfacl -R -m u:<uid>:rwX on the folder and default entries on its folders) and records them in host_directory_grants (uids, granted_at, error). It is ACL entries only: ownership, group and mode are never touched, so the folder stays the host owner's exactly as it was. It runs on link and unlink, on a source change, when a bot joins a computer or a workspace, from sync-computers (retry: false, so a folder the user hasn't fixed doesn't start a container every five minutes), and from Give access (api/admin/host-directories/grant-host-directory) when it failed; a check refreshes after it. Unlinking a place takes the entries back from the uids no remaining link needs (removing the last link removes them all, so deleting a directory leaves the folder as it was). Check (probeHostDirectory: one throwaway container, each account through setpriv --reuid/--regid/--groups, test -r/test -w; mounted read and write, since a read-only mount answers no to every write test) stores host_directory_checks per computer, and the page shows hostDirectoryPermissionCommand only when the grant couldn't run (a host without ACLs, a folder the daemon can't reach), for the user to run by hand. Every bot that sees the folder must be able to read and write it, so the command names the uid of each of them, from the live crew and not from the stored check: hostDirectoryLinkUids over bots/bot_computers/workspace_bots (a computer link: every bot reaching it; a workspace link: its bots plus the coordinator), hostDirectoryAccount mapping a bot to its uid (coordinator 1000, a worker 100000 + bot_id). A check that misses a uid now seeing the folder is flagged hostDirectoryCheckStale, so the page says to check again rather than showing an old result. A delete inside a mounted folder asks the user first: gate_deletes on each link (on by default, toggled per link in the page) holds a computer_bash command that would remove something in it (host-directory-delete-guard.ts, called before the command runs) until the newest user message approves it. hostDirectoryDeletePaths reads the plain spellings (rm/rmdir/unlink/shred, find -delete, >/tee/dd of=, mv, rsync --delete, git clean/git rm), gatedMountFor matches them against the read-write, gated mounts the run reaches (computerWorkspacePath, so either spelling; a rename inside the folder is not a delete), and grabDeleteApproval wants one of the exact paths plus an agreeing word in the newest user message, which is how an ask_user answer counts. Not approved, approvalNote comes back as the whole result and nothing runs; approved, keepCopies keeps a copy of each named path in <bot folder>/recovered/<stamp>/ (AppData.HostDirectoryRecoverMaxBytes; past it no copy is kept and the result says so, and a path already gone is skipped) before the command runs. It is a heuristic at the tool's edge: a script the bot writes and runs still deletes what its account may. The agent's shareFolder walk prunes every mount point found in /proc/self/mountinfo (computer/agent/mount-points.ts) and runs find -xdev, so setting up a bot never chowns or chmods through a mount into the host. The app container itself does not mount a source, so Files shows the mount point empty and sizes are not counted.

Schedules (routines in the UI)

cron_jobs per user and bot (schedule is a Bun.cron expression in UTC, max_runs, next_run_at, last_error). Helpers in src/functions/backend/db/cron-jobs/ (ownership-checked). nextCronRun validates and enforces AppData.CronJobMinIntervalMs; max AppData.CronJobMaxPerBot per bot. fireCronJob claims a run atomically, skips while the last job is open, queues a task in the routine's own thread (bot_sessions.routine_id, ensureRoutineSession: created closed, rolled over at the session max, never the chat that happens to be open, linked from /admin/routines and chattable there). A deleted routine detaches its thread instead of deleting it. A missed run runs once. Runs act on their own (ScheduledRunNote); report_run_failed retries with doubling backoff. handOverCronJob (tool hand_over_schedule, UI Hand over) moves a routine to another bot: a workspace routine stays in its workspace (handOverPlace), its computer is kept only if the new bot reaches it, refused while a run is open. Whose routines a run sees: a worker's list_schedules/update_schedule/delete_schedule reach only its own, and the tool says so, so a partial list is never read as a census of the install; the coordinator's reach the whole crew's (the user's routines on every bot, grabCronJobs without bot_id, each line naming the bot that runs it) and it may change, delete or hand over any of them, matching /admin/routines. UI: /admin/routines and each conversation's Schedules modal (shared RoutineForm/RoutineRow/RoutineEditModal, HandOverForm).

Hooks (bot_hooks)

A secret URL, POST /api/hooks/<token> (src/pages/api/hooks/[token].ts, public, no session), that queues a hook's brief plus the raw body as a task, per user and bot like a routine (runs act as the owner, who must still reach the bot and not be read-only). Only the token's prefix and SHA-256 are stored (shown once; "New URL" rotates it); an optional HMAC-SHA256 signing secret is stored encrypted (verifyHookSignature). Order in the route: rate limit per IP, lookup (same 404 for every miss), rate limit per hook, signature, then fireBotHook. Calls are recorded in bot_hook_events with idempotency on the sender's delivery header; when a run ends (completed, failed, lost, stopped, cancelled) every call it took in gets its response and turns done/failed (recordHookCallResponse, called from the job helpers, not the handler). Calls are searchable by payload/response (searchHookCallsSql; Calls view, bot tools search_hook_calls/read_hook_call) and pruned daily after the app setting hook_events_keep_days (default AppData.BotHookEventsKeepDays). The caller only ever gets 202 Queued. A call while the last run is still pending and untried joins its brief (mergeHookCallSql) instead of queueing another. The payload is fenced data (hookPayloadBlock), and HookRunNote tells the bot never to take instructions from it. Failed runs retry like routines and keep why in last_error. Users make hooks in the conversation's Hooks modal and manage all of theirs on /admin/routines. A hook keeps its runs in a thread of its own (bot_sessions.hook_id, ensureHookSession: one per place, created closed, rolled over at the session max, linked from its card and chattable with ?session_id=). bot_hooks.silent decides whether it takes the conversation over: silent (the form's "Run silently"; every hook made before this setting existed is made silent at boot by migrateHookSilence) leaves the thread out of the rail, unread and pushes, changes no face and names nothing (isUnattendedHookSession, followedSessionSql), so its runs show only in the thread and last_error; the thread stops being the hook's the moment the user writes in it (adoptHookSession: it becomes an ordinary conversation, pushed and counted, and the next call opens a fresh thread; adoptChattedHookSessions does the same at boot for threads earlier versions left that way, one holding a human's message or left active by them); a hook that isn't silent makes its thread the conversation's active session for its run, and its report is pushed and notified like any message. Calls stay in bot_hook_events (HookDetailModal, opened from a hook's title; live through server:hook-call-updated from the relay) and are pruned daily, while the thread's messages stay. bot_hooks.session_id is unused. Deleting a hook detaches its thread (detachHookSessions: hook_id null, status closed) and keeps the messages. Moving a hook is refused while a run is open; the computer is kept only if reachable there. A hook can keep the process that calls it running (runner_command, runner_dir inside the bot's folder, runner_computer_id, crew managers only: it is a command the app starts, never a bot's own run): syncHookRunners runs at the end of the sync-computers cron (*/5, and unawaited after a hook changes, with a restart_hook_id for the Restart button) and reconciles desired.json in the bot folder's .cobble/hook-runners through a small Python keeper (src/data/hook-runner-script.ts, protocol checked) that starts bash -lc with the run's envs and its own session, keeps the ones that are up, stops the ones a paused, deleted or changed hook no longer wants (with the env file it wrote, since those hold secrets), and reports one JSON line (state on the hook: runner_pid, runner_started_at, runner_last_error). It runs as the hook bot's own account (cb-<bot>, the coordinator gem), so its files must be inside that bot's folder (the computer defaults to the bot's own); a changed command, folder, computer or env restarts it. Nothing runs it instantly: a dead runner is back within five minutes, or at once with Restart in its modal or in HookRow's state. A bot never makes or changes a hook on its own: list_hooks, search_hook_calls, read_hook_call, pause_hook and delete_hook act directly (they only read or take away); a new hook, or a new name, brief or filter, switching one back on, or its runner, goes through propose_hook -> hook_proposals -> [hook-proposal:ID] card, described from the data and confirmed by that user (checkHookProposal runs again on confirm). What calls a hook, its computers and its signing are never proposed, and a runner proposal is refused unless that user is a crew manager (assertHookRunner at propose and at confirm), since the card would start a command on their computer. A new hook's URL shows on the card only, never in the outcome the bot is told. Only chat replies propose; a hook call's own run gets no hook tools. Whose hooks a run sees: a worker reads and stops only its own (list_hooks, search_hook_calls, read_hook_call, pause_hook, delete_hook all carry its bot_id, except propose_hook, which makes or changes its own); the coordinator's reach the whole crew's the same way its schedules do, so it can pause or delete any of the user's, and a partial list is never read as a census.

Browser notifications: a hook with source = browser_notifications is called by a watcher on watch_computer_id instead of an outside service. The watcher (src/data/notify-watch-script.ts, Python + GLib, run as gem from ~/.cobble/) owns org.freedesktop.Notifications on the computer's session bus (started by the agent; Chrome's pid and bus are in /run/cobble/browser.pid|json), so Chrome hands it every notification, push ones included, instead of its silent built-in message center, and it posts each as JSON (origin, title, body) to the URLs in ~/.cobble/notify-hooks. Chrome only looks for that service when it starts, so syncComputerNotifyWatch restarts Chrome once after starting the watcher (the agent brings it back), never while a task works on that computer. The hook's token is kept encrypted (watch_token) to rewrite that list after a container is recreated; sync-notify-watchers (every 5 minutes) and every change to such a hook resync it. watch_filter keeps only matching notifications (others are recorded as ignored). Computers reach the app at COMPUTER_APP_URL (an app setting; needed for a dev server outside docker), else the app container's name on the docker network. Sites still need notification permission in that computer's browser (on the computer's screen: chrome://settings/content/notifications; a Browser.grantPermissions over CDP lasts only for that CDP session). Anything on the computer can read the list and call those hooks, which is one more reason payloads are only data.

Tasks (the to-do tracker)

tasks (a task belongs to a bot by default, the coordinator included: a bot's own list is bot_id alone, a workspace's task has workspace_id plus the bot_id that has it there; the one exception is a workspace-wide task (workspace_id, bot_id null), only when asked for (workspace_wide, enforced by taskScopeValues), which every bot working there sees and works on; a worker reaches its own plus the workspace-wide ones in its workspaces, a workspace admin all of that workspace's, the coordinator all, botTaskScopesSql; on a workspace-wide task update_task logs each call's status move and filed files as a note under the bot (task_notes.bot_id), and list_tasks with task_id reads the whole log with who and when; the coordinator and a workspace's admin bot (update_task workspace_wide) or a crew manager (Make workspace-wide, api/admin/tasks/make-workspace-wide) turn a bot's open workspace task workspace-wide (makeTaskWorkspaceWide, noted in its log; never a bot's own list), and hand-over gives one back to a single bot; it can be split into subtasks (parent_task_id, one level, subtaskLinkProblem): each one an ordinary task of one bot in that workspace (create_task/save-task parent_task_id, cap AppData.TaskSubtaskMaxPerParent, listed under the parent in TaskDetailModal and marked Subtask of #N in lists), and a task a bot already has joins one the same way (linkSubtask, api/admin/tasks/link-subtask from the panel's "Make it a subtask of..." picker, subtaskAttachProblem refusing a closed task, another subtask, or a task with subtasks of its own; the parent logs who took which piece), loose again with detach-subtask/update_task unlink_parent; the parent stays open until someone verifies it, and its subtasks never close it. Only a task with no subtasks and no parent moves (subtaskMoveProblem, so making it workspace-wide or handing it on is refused until the subtasks are unlinked) and a parent with subtasks is never handed its own work back on deletion (subtaskDeleteProblem: all subtasks finished first, then they go with it, children deleted explicitly since foreign keys are off outside the server); a bot removed from a workspace or deleted passes its own tasks there to the workspace's admin bot, else the coordinator (passOnBotTasks), workspace-wide ones stay), task_notes, task_media (deliverable|reference). Not the same as bot_tasks/bots_queue (those record jobs). Visibility SQL in src/utils/task-access/. Helpers in src/functions/backend/db/tasks/; tools list_tasks/create_task/update_task (which also renames a task and rewrites its brief, refusing an open twin's title, and unlinks bot files with unlink_file_ids: a task holds AppData.TaskMediaMaxPerTask files; list_tasks with task_id lists them) and, in chat replies the user follows only (never routines, hook calls or rooms), delete_task; API api/admin/tasks/ (userAuth -> isReadOnlyUser -> assertUserReachesTask -> safeErrorMessage). UI in the workspace dashboard and the header's Tasks modal (shared components in src/components/general/), the dashboard's list ordered by workspaceTaskSections (workspace-wide first, then one section per bot by name) and capped at AppData.TaskSectionShown, its View all opening WorkspaceTasksModal with the same sections uncut, and a workspace-wide row wearing the workspace's picture (WorkspaceAvatar, its icon when it has none) since it is nobody's; a card's title opens TaskDetailModal with everything about the task and its status moves (a modal over the list, never swapped in place), a wide task's panel listing the first AppData.TaskSubtasksShown subtasks with TaskSubtasksModal behind its View all, and a subtask's own modal walking up to it through its Parent task fact (Escape closes only the modal on top, TopModalEscape). Hand-over: handOverTask (bot: delegate_task with task_id when it directs work, else hand_over_task for a task of its own; UI: Hand over, crew managers) moves an open task to the new bot (a workspace's stays in the workspace, now the new bot's, and is worked there) as to do, with no job: a hand-over never starts the work. Only start: true (the UI's "Start it now" toggle, or a bot passing it after the user said so) sets it doing and queues a job with params.tracker_task_id; when the user asked for the move but not for the work to start, bots ask first with one ask_user card for every task they named, since a worker can't start a task once it has left its list; noteTrackerTask notes the job's end on it, blocks it on failure, and blocks it too when the run used every step it had without finishing (trackerTaskEnding, so a run measured to its last step no longer leaves the task silently open). Not built yet: task steps, server:task-changed pushes, a /admin/tasks page.

Envs

Set in Settings > Environment (super admin), not .env. envs (private; encrypted value; paradigm general|workspace|computer|bot|user; one per key and scope, enforced in saveEnv). Cached per process. App settings (EnvDict in src/dict/env-dict.ts) via grabEnv (general value, else process.env); ProcessOnlyEnvKeys can't be saved. Precedence for runs: user > bot > computer > workspace > general (resolveScopedEnvs, grabRunEnvs; pass the run's user_id). Written to ~/.cobble/env and env.json in the run account's home on the computer each task run (only task tools load them; search_computers doesn't); bots see keys and descriptions, never values (tasks in their prompt, replies through composeEnvsNote from grabReachableEnvs, so they never ask for or test a key that's set); every computer tool result goes through redactSecrets. A custom tool's arguments are filled too (fillEnvArgs, on build-custom-tool, with arg_envs = the computer's envs and the run's, the run's winning): http and script tools get the value, a prompt tool the [KEY] marker, and a key that isn't set throws the same Settings > Environment message as a config template.

Secrets never pass through the model. A user env is one user's secret for one bot (saveUserSecret, reach-checked), set from the chat, listed on Settings > Secrets (own) and Environment (everyone's, remove only). In: request_secret (refused for a key that already reaches the run, unless the user asked to replace it) -> secret_requests -> [secret-request:ID] card (masked input, answer-request), then a chat message naming only the key. Out: capture_secret (task computer tool: a file via the agent's /api/files/download or a command's output, saved straight to a user env and added to the run's redaction list) and show_secret (an env by key) give [secret:ID]; the chip fetches the value only on click (api/admin/secrets/reveal-secret, canRevealEnv: a personal one only its own user, anything else only a super admin). Never put a value in a message, page prop, log or tool result. SecretsNote tells bots never to ask for secrets in chat. A password field never reaches the model: every browser tool result goes through maskPasswordFieldValues (a password-named field's value, and the value inside its container's accessible name, become [hidden]), and a reply's text, an ask_user card, suggested steps and a task report are redacted through it plus redactSecrets before they are stored (redact_reply in run-bot-reply.ts, redact_text in run-bot-task.ts), since a page credential is not an env and nothing knew its value.

PWA and notifications

  • Generated assets (manifest, icons, offline.html, loading.html) come from bun run gen:favicon, which reads main.css; outputs are committed. Shared paths in src/data/pwa-data.ts.
  • Install name: app setting install_name (Settings > General, super admin). handlePwaFile rewrites the manifest's name/short_name per request (namePwaManifest), the root head uses it for iOS tags, the loading page's <title> is the {{name}} placeholder. Devices pick up a new name only on reinstall.
  • Install icon: app setting install_icon (JSON, parseInstallIcon): a stone, or an upload (decoded, cropped to source.png, never stored as sent, no SVG) with the stone at PwaCornerMarkInset/PwaCornerMarkScale, inside a round launcher's crop. saveInstallIcon draws the set (renderInstallIcons, shared with gen:favicon via renderAppIcon) into DATA_DIR/install-icon/<version>/, served publicly and immutable by handleInstallIconFile; the manifest, head links and push payloads point at it. Ember stone = stock icons, no set.
  • Notification badge is icons/badge-96.png (white silhouette; Android masks by alpha, so never the opaque app icon). Brave on Android has no WebAPK, so its notifications always carry Brave's name and icon.
  • public/sw.js is served no-store; navigations network-only (authenticated HTML never cached); /api/, /ws, /media/, /computers/, /build-info.json never intercepted. A new worker takes over by itself (skipWaiting on install; nothing in it is per-version) and never reloads a page; there is no update prompt. In development the worker and caches are actively removed (clear-development-service-worker.ts, stub /sw.js).
  • Precache (production): a navigation without the current build cookie gets loading.html, which downloads all of .bunext/public into cobble-assets-<build_id>, verifies, sets the cookie and reloads (falls back to network on stall). React knows nothing of this.
  • Phone shell: rail is a slide-over below md (the shared src/components/general/side-panel.tsx, always mounted so it slides both ways; the rail passes inertWhenClosed={false} since it is the page's own rail from md up); rail internals use the @rail: container variant, not viewport lg:. Two swipes anywhere on a phone page move between panes: to the right opens the rail's drawer, to the left the conversation's bot panel (cobble:open-bot-panel, src/utils/bot-panel-open-event.ts, answered only by a conversation's header, so a page without one slides nothing). They are flicks, read by src/hooks/use-horizontal-swipe.ts (a field, a data-no-swipe panel, a box that scrolls sideways, a text selection, a finger down longer than AppData.MobileSwipeMaxMs, an open twui modal, a screen from md up and the open drawer all own the touch), with the thresholds and the one-decision state machine in src/utils/swipe-gesture.ts (AppData.MobileSwipeMinPx, MobileSwipeAxisRatio), tested without a browser. LiveSocket is remounted on online/pageshow/visibility since twui stops retrying after three attempts. Nothing is queued offline.
  • Web Push: push_subscriptions, user_presence; VAPID keys generated into envs by ensureVapidKeys. pushBotNotice is the one trigger, skipped while the user is present (AppData.PushPresenceWindowMs, per user not per device). Best effort, no retry. Needs HTTPS.

Bot files and folders

  • Files live on the data volume, not on computers: DATA_DIR/bots/<id> and DATA_DIR/workspaces/<id>. Catalog bot_files, bytes in private media (bot-file) written by recordBotFile. Reach via grabStorageScopes; paths via resolveBotPath (no absolute, .., NUL, symlink escape); quota checked by assertStorageRoom.
  • Tools in src/harness/tools/storage/ (every run). attach puts a file on the reply. grabConversationFiles must list the whole folder tree, or nested [file:ID] refs render dead. A workspace run saves to the bot's own folder unless it picks the workspace's, so a chip in a workspace conversation looks up both (api/admin/bots/files?file_id= with bot_id and workspace_id).
  • import_file copies from a computer through the agent's streaming GET /api/files/download, never through its shell (a shell's output is capped and once silently truncated imports). Size read first, the agent cuts a file that changes mid-send, length checked. A chat reply has it too (grab-bot-chat-tools, its computers to choose from), so what a reply made on a computer comes into its files the same way a task's does.
  • list_files with search matches names and paths in every folder (leaving folder out lists every folder too): scoping a search to the root hid images/summit-hero-pil.png and made a bot believe its file was never saved. write_file refuses a binary extension, since text saved under .png reached the user as a file that would not open.
  • Only knowledgebases store text. Bot files and uploads are never indexed and keep no extracted text (media.text_content only for knowledgebase documents); bots find files by name or path (list_files search) and read them with read_file, and the Files searches match names only. Text that should be searchable goes in a knowledgebase. dropStoredFileText clears what older versions stored, at boot, and vacuums when much of the file is free.
  • Foreign keys are off per connection unless enableForeignKeys ran (only src/server.ts does). Scripts never fire ON DELETE CASCADE, so any helper that deletes a parent row must delete its children explicitly (as deleteBotFile, purgeStorage, deleteSkill do). A leftover child fails the next bun run db:schema with a foreign key violation.

Graphics (bot_graphics)

A bot shows a concept as a visual with create_graphic (plus update_graphic/read_graphic/list_graphics, src/harness/tools/graphics/, on every run, no computer needed): one HTML document stored as text, per user like the conversation (viewerGraphicsSql: only the user it was made for reads it; only its bot edits it), version bumped on each edit (in place, no history), message_id filled when the job completes. The run's message always carries its [graphic:ID] (shown in withTakeOverRefs); the chat renders it as GraphicRefCard (inline frame sized by the graphic's postMessage, open large, own page /admin/bots/<bot>/graphics/<id>). Graphic HTML is hostile (a prompt injection can write it): it's only ever served at /graphics/<id> (handleGraphicsRequest, before the precache gate, bypassed by the service worker) with graphicHeaders: CSP sandbox allow-scripts (never allow-same-origin), default-src 'none', scripts only inline or from /graphics-lib/ (the vendored GraphicsLibs: Chart.js, Mermaid, read from node_modules). Never render graphic HTML on the app's origin (dangerouslySetInnerHTML, srcdoc without sandbox) and never add network to that CSP. A frame that navigates itself away is closed (GraphicFrame); meta refreshes are stripped (graphicDocument), which also sets the theme vars parsed from main.css.

Browsers (browsers, browser_access)

A user's own running browser, reached over a browser MCP server they run beside it (Settings > Browsers). It serves only its owner's runs, since it holds their logins: every helper takes the session's user_id, and nobody sees anyone else's, super admins included. A row in browser_access makes a browser available in a scope (a bot, a workspace, or both null for all the user's bots) and at most one row per scope is the default; browser_id null there means the computer's browser, winning over a wider scope. Adding a browser gives it to no bot. Default order (pickDefaultBrowser): workspace > bot > all bots > computer. The computer's browser stays as the fallback. BrowserDefaultPicker is the one control, on Settings > Browsers, bot and workspace settings and under the composer (only once the user has a browser, has_browsers). Runs get tools through openBotBrowsers (<slug>__<tool>, from tools_cache, connecting on the first call) and composeBrowsersNote, in replies too, so a bot can browse from the chat. browserRunAllowed: routines only with allow_routines, hook calls and crew requests never. Never use openMcpServer or fillTemplate for a browser: its URL and headers are a member's own text, and {{env.KEY}} would send install secrets to their server. The URL goes through assertBrowserUrl on save, test and each connection (refuses the computers' docker network, link-local, and loopback in production; the docker gateway stays allowed, it's the host), and redirects are refused (no_redirects). Headers are encrypted and never reach a page. Playwright MCP needs --allowed-hosts naming exactly the URL's host and port; install.sh adds host.docker.internal. A Flatpak browser takes the same flags through flatpak run <app id>, Playwright MCP staying on the host; it needs the host network and home (Flathub Chromium has both; its /tmp is private). New browsers start without BrowserDefaultExcludedTools. No cron lists tools: a sleeping laptop isn't a fault.

Connectors (connector_connections, connectors, bot_connectors, workspace_connectors, connector_accounts, connector_sessions, connector_requests)

A user's access to an outside app (Gmail, Slack, ...) as themselves, reached through a provider that holds the OAuth app and the connected account (Settings > Connectors). Composio is the first provider: one file under src/harness/connectors/providers/ and the preset in src/dict/connector-dict.ts. A connection is one provider account, not an app: connector_connections has one row per provider account (Composio Personal, Composio Work, ...), each with its own encrypted api_key, added in Settings > Connectors; the form's paradigm (provider, Composio the first) decides how that connection's apps are reached, and more paradigms can be added; that form names the key a paradigm wants and links where to make it (key_help, key_url, key_url_title in the preset: Composio wants a project API key ak_... from its Project Settings > API Keys, not a ck_... key made for connect.composio.dev/mcp, whose router signs everyone in as the key's owner); connectorProviderFor builds the provider from that key, so no install-wide key is read from Environment. syncConnectorConnection({ connection_id }) reads every app the connection offers into connectors (connectors.connection_id; planConnectorSync derives each slug and names a second connection's app after it, gmail-work), so nothing is added or edited app by app; a stored app follows the provider's name, description and logo only, keeping its slug, reach and accounts. A thousand apps cost nothing until one is used: its tools are read when it is first given to a bot or workspace (syncConnector from set-bot-connector/set-connector-access when tools is empty) and by the cron for assigned apps alone. An account is a person's own (connector_accounts.user_id), several per app, and its owner's runs always reach it; its owner or a super admin can also give it out (connector_accounts.all_bots, connector_account_workspaces, connector_account_bots, written by setConnectorAccountAccess), so every run in a workspace or on a bot reaches it too, whoever signed in (and giving an account out brings its app along to that bot or workspace, since botConnectorsSql counts a connected account given there), and the session is built as the account's owner (openBotConnectors passes account.user_id, and a shared line names whose account it is). Its owner or a super admin renames it (saveConnectorAccount, which regenerates the slug, so a namespace follows its label); a member can only give an account to places they reach, and only a super admin sets all_bots. A second account is a new sign-in, never the first one reused: startConnectorConnection always makes a link (an account already connected never stands in for the new one), and a request is settled only by the account it made (connector_requests.provider_account_id, matched in settleRequests and grabConnectorRequestView), so a request the user has not finished cannot show the label of an account that was already there. The sign-in itself must never replace the app's earlier account: Composio's plain connected_accounts/link does exactly that, so the adapter first opens a multi-account tool-router session and takes its link (/tool_router/session/<id>/link), which keeps the other sign-ins; tool sessions stay single-account, pinning one in connected_accounts, since a multi-account session exposes only the router's meta tools and refuses preload. Credentials never reach this app or a model, and a run gets tools from an endpoint the provider builds for one account. Where a connector reaches: all_bots (every bot, every user) and workspace_connectors are the install's and only a super admin sets them; bot_connectors.user_id is NOT NULL, so a bot row is always personal to whoever made it and shows only in their runs (botConnectorsSql). Runs get deferred tools through openBotConnectors (<slug>__<tool>, or <slug>-<account slug>__<tool> when the user has more than one account) and ConnectorsNote, opened beside openBotExtensions/openBotBrowsers in replies and task runs. Tool names and the action cap (connectors_actions_per_run, an app_settings row, 50 by default) come from the app. Transport is the MCP lane; when a provider can't pin an account at a session endpoint (endpoint throws), ensure-connector-endpoint records session_id = "rest" and the tools call provider.execute({tool, args, account}) with the account, so the model's surface never changes. Composio's tool router answers with a URL and no headers and rejects a keyless call (401 "API key is required"), so the adapter sends the connection's project key as x-api-key on every session call; a cached session whose stored headers can't be read is rebuilt, never used keyless. Bots never make or change a connector: a missing account in an attended reply makes the app create connector_requests and show [connect:ID] (ConnectRefCard, the sign-in opened from there, then read by asking the provider's accounts), and a note line says so; a task, routine, hook call or crew request never gets the card. The settings page lists connections only (super admin: add, edit, delete, sync; everyone: their own sign-in); each connection's apps live at /admin/settings/connectors/<connector_id>, ConnectorAppsPageSize (24) a page, searched on the server over name, app and description by grabConnectorApps, so a connection holding 1,842 apps never renders them all; that read puts apps with a connected account the viewer can see first and filters to all / connected / unconnected (ConnectorAppFilters), returning each tab's count with the page. A row's one assignment control is who gets the app; its account chips (ConnectorAccounts) show the label and where each is in force, "New connection" opens the sign-in modal (the app's logo beside its title, Connect the only primary button), an account chip opens its own modal: the name, all_bots and the bots and workspaces it reaches (reach-checked lists), and Disconnect; the row's New connection line leads with how many of the app's accounts are connected (N accounts, in the success colour, and nothing while none is). A conversation's composer tools modal ends with a Connectors section (ComposerConnectorsSection), read by grabBotConnectors when the modal opens (never by the page): each app the bot reaches there (its title tagged with the connection's name, and with the account's label when an account given here is what brings it), where it comes from (every bot, this workspace, only you, or an account given here) and the accounts that reach there (this user's own, whatever their status, and connected ones given here, with their owner), or that none is connected yet, with a Manage link to Settings > Connectors, and Add/remove: Add opens a modal that walks down from the connection, to the app (searched on the server through grabAttachableConnectors with its connection_id, 20 at a time, listing only apps with a connected account of the user's and never one they already attached to this bot), to that app's own accounts (grabConnectorOwnAccounts, which leaves out an account already given here) or All accounts for the app alone, and gives the app to this bot for this user (connectors/set-bot, so every account they have of it reaches the bot, ones connected later included), plus the picked account to this bot (connectors/set-account-access); Remove is the row's X (shown when entry.removable) and calls connectors/detach, taking away this user's own attachment there and their own account given to that bot alone, while a workspace's, the install's or an account given to every bot shows no X. sync-connectors (*/15) refreshes every connection's apps, assigned apps' tools and the accounts a sign-in left waiting (pending requests and any account not yet connected, so an OAuth callback that lands after the poll is picked up); prune-connector-requests takes old requests. A request is only settled as connected once the provider reports an account connected, never on a sync that found none. Deleting a connection removes its apps, sessions, requests, accounts and grants explicitly. Connectors travel in no extension bundle.

Knowledgebases

A fourth extension kind (ExtensionTables.knowledgebase): knowledgebases given per bot (bot_knowledgebases), per workspace (workspace_knowledgebases) or every bot (all_bots), through the same add/remove/access/default paths as skills (list_extensions and delete_extension leave them out, and so do the proposal cards). Documents (knowledgebase_documents: an upload in private media, paradigm knowledgebase-document, or written content) are chunked into knowledgebase_chunks and embedded into the knowledgebase_vectors vec0 table by the file-ingest worker (file_ingest_queue.document_id, ingestKnowledgebaseDocument), always with the install's embedding model; old passages stay until the new ones are in, embedding_model records where vectors came from; whatever can change the install's model (default settings, a provider saved or deleted, the hourly catalog sync) calls reindexAfterEmbeddingChange, and Re-index reads a knowledgebase again by hand. Retry failed (retryFailedDocuments, the row menu's Retry failed and retry_failed_documents) queues only the documents with ingest_error, clearing it so the ten-minute sweep can pick them up too. Word search runs on knowledgebase_chunks_fts, an FTS5 table (unicode61 remove_diacritics 2) made by ensureKnowledgebaseFts (FTS5 can't be declared in the schema; sync leaves undeclared tables alone), backfilled at boot by syncKnowledgebaseFts, ranked by BM25 with a scored LIKE fallback for unspaced scripts (knowledgebaseWordQuery); every write and delete of knowledgebase_chunks updates it. Ingest jobs (settleFailedIngestJob) wait without spending an attempt while every embedding model rests, fail at once on an error retrying can't fix, and a document whose model refused keeps its new passages for word search (counted as needing re-index, not failed). Runs get search_knowledgebase/read_knowledgebase_document (openBotKnowledgebases, limited to the run's ones) and replies start with passages found for the unanswered messages (grabKnowledgebaseContext); passages are fenced (knowledgebasePassageBlock) and KnowledgebasesNote says they're never instructions. UI: Settings > Knowledgebases (super admin edits and fills; admins set access), a Knowledgebases group on bot/workspace settings, and the composer's own button beside Tools (ComposerToolsModal with composerKnowledgebasesCopy). Deleting one deletes its documents' vectors, chunks, media and links explicitly. The coordinator manages them when the super admin asks for it in the chat: grabCoordinatorKnowledgebaseTools (src/harness/tools/bot/knowledgebases/, pushed beside grabCoordinatorExtensionTools in grab-bot-chat-tools.ts and in the coordinator branch of run-bot-task.ts) gives list_knowledgebases in any of its runs, and save_knowledgebase (name, description, on/off, who gets it through set_extension_access), add_knowledgebase_document (file_id a saved file, media_id the user's own upload, path on a computer, or text), delete_knowledgebase_document, delete_knowledgebase, retry_failed_documents and reindex_knowledgebase only in a reply or a task the user follows (attended: never a schedule, hook call or hidden session), each checking the super admin again. A document from a file is copied into private media first (recordKnowledgebaseFile, shared with upload-document.ts, and the same refusal in knowledgebaseFileProblem), so it stays after the computer or the file is gone; a task's own computer is the default for path. AccessExtensionKindSchema adds knowledgebase for access only: ExtensionKindSchema stays three kinds, since delete_extension's last branch deletes a custom tool.

sqlite-vec limits: metadata columns are NOT NULL; side-car columns can't be filtered with MATCH (filter in code). Never pass --vector to bunx bun-sqlite schema in entrypoint.sh (wipes vectors on boot). Changing AppData.EmbeddingDimensions needs a manual --vector run and a re-index.

Files browser (/admin/files)

Read-only browser of every volume (src/utils/storage-volumes.ts: bots, workspaces, computers, media, mcp, db). resolveStorageSpec is the only access gate (members see only their bots' and their own user folders inside a computer, computerPathAllowed); resolveStoragePath applies the path rules. Links built only by storageSpecHref. Deletion stays in the chat's files modal and bot tools.

Harness (the model layer, src/harness/)

  • Harnesses (src/dict/harness-dict.ts): text (always on), vision, transcription, speech, image, image_edit, video, video_edit, embedding. One harness_settings row each (provider, pinned model or automatic, fallback, enabled, options). Transcription, speech, video and embedding have no automatic picks: unavailable until a model is picked.
  • Images: generate_image attaches what it makes to the reply unless attach: false (a coordinator once asked a user to judge three versions they were never sent). It takes reference images (references as [file:ID], reference_media_ids for uploads, checked like a picture source by loadReferenceImages). With references the call goes to image_edit (no automatic picks; only while its fallback is on does HarnessFallbacks hand it to image, both while it is unpicked or off and after its pick fails), and only models that take image input are tried (orderImageCandidates), never one that would drop them. OpenRouter takes references on /images (input_references), other providers as multipart on image_edit_path (/images/edits); DashScope/Model Studio hosts (dashscope*.aliyuncs.com, *.maas.aliyuncs.com) take them as the image extension field on /images/generations instead (they have no multipart edits endpoint) and always answer with URLs, ignoring b64_json (isDashScopeHost in the adapter). The Token Plan host (token-plan.*.maas.aliyuncs.com) has no compatible images route, so its call goes straight to Alibaba's native multimodal-generation on the host root (dashscope-native-image.ts, the documented body: size as width*height, no prompt_extend); a workspace host that answers 404/405 on the compatible route falls back to the same call. xAI takes no size (imageRequestFields maps one onto aspect_ratio).
  • Videos: generate_video (src/harness/video/), offered only while video or video_edit has a model for the bot there (no video model is free). A video is a job at the provider: asked for at video_path, checked every AppData.VideoPollIntervalMs for at most VideoMaxWaitMs (below the tool timeout), downloaded from the provider itself (<video_path>/<id>/content, never a URL it hands back, so the key stays home). Still images go as first/last frames or references; videos to change (inline data: URLs, VideoSourceMaxBytes) go to video_edit's pick, which hands over to the video models that take videos like image_edit does (orderVideoCandidates). OpenRouter takes JSON (frame_images, input_references with video_url); other providers get OpenAI's (Sora) form with one start image and no videos.
  • Transforming images without a model: transform_image (never "edit": that word is the image_edit harness) (src/harness/image/transform-image.ts, sharp) runs ordered steps (crop, resize, rotate, flip, grayscale, blur, sharpen, adjust, trim) on raw pixels, so the order is the bot's, after turning the source upright by EXIF. Source checked like a picture (grabPictureSource), never SVG. Saves a new file and shows the bot a preview so it checks the crop.
  • Providers (src/dict/harness-provider-dict.ts): OpenRouter default plus OpenAI-compatible ones; one adapter today (src/harness/providers/openai-compatible/). Keys encrypted in private harness_providers, falling back to the preset env.
  • Catalog: harness_models, synced hourly. OpenRouter "free" means :free or openrouter/free, never zero prices. Auto picks: rank-auto-models. A custom provider's /models lists ids and nothing else, so its form takes a context window (harness_providers.context_length) and the sync writes it into every model that reports none of its own (modelContextLength); leaving it empty leaves them unknown and a run assumes AppData.HarnessUnknownContextWindow, since a model with no window at all gets 70% of that as its working context no matter what harness_context_budget_tokens says.
  • Calling: resolveHarnessCandidates -> withCandidates with process-wide cooldowns; errors are HarnessError. Order: the pick, the text setting's fallback models (fallback_model_ids in its options, up to AppData.HarnessTextFallbackModelsMax, any provider), then the free automatic picks (when fallback is on). Every failure is logged (logCandidateFailure) and benches its model (or provider, for a key or credits) for the model rest (app setting harness_model_rest_seconds, Settings > General run limits, default AppData.HarnessModelRestMs, or until the setting changes and the app restarts when the rest is unlimited; the bench lives on a globalCache slot (cobble.harnessCooldowns) so a run-limits save clears the copy the queue reads, and that save, like queue startup, wakes the jobs a rest had parked ahead of time (releaseRestingBotJobs)), never longer, even past a Retry-After: one failure once left every reply on a weak free model for an hour. A message answered by a model in place of the one ahead of it shows the fallback on its usage chip (fell_back_from/resting in token_usages.settings). A call that only reaches benched models records a failed-call row for each resting candidate (recordHarnessFailure, no re-log of the outage) so the message shows why nothing was tried, and its error names Settings > Models; a resting call says how long the wait is ("The next try is possible in 27s."), since told only "trying again shortly" a bot told the user the models were benched until a restart. A failure carries the model the candidate ran on, the request's method and address, and a hint when a 404/405 came back with an empty body (no endpoint there), so the tool's message names the pick instead of leaving the bot to guess it: with only "HTTP 404", a production bot invented a model and its routing. Entry points under text/, media/, audio/, image/, embeddings/. run-text-loop.ts sticks to one model (an automatic pick only until the pick or a fallback model has rested), caps steps (grabHarnessMaxToolSteps, grabReplyMaxToolSteps; routines and hook calls grabUnattendedMaxToolSteps, all unlimited by default, so a run's job deadline and its prompt-token budget are what end it; every run limit reads as RunLimit in src/utils/run-limit.ts, number or "unlimited", saved as -1 on the settings form and "unlimited" in app_settings; a run is told once, stepsLowWarningLeft steps before the wrap up, to save its report, and the wrap up keeps WrapUpToolNames (write_file, import_file, and send_reply for a reply's answer or start_task for work a task run can't finish: a 20-step reply used for research otherwise left the writing undone and the next reply had the same budget) for a saving-or-answer turn before the last turn with no tools, since runs measured to their last step with the report unwritten) and the prompt tokens one run may spend (grabRunMaxPromptTokens, 4M by default: at 40M one task run spent 195 turns and 30M tokens re-reading its own notes with the ceiling never in reach; a run is told once, a quarter in and only while it has produced nothing (commitEarlyNote, isWritingTool, AppData.HarnessRunTokensCommitShare), to land one piece of the work, then once at AppData.HarnessRunTokensWarnShare of it to land the rest, tokensLowNote, then the wrap up). Results are cut keeping their start and their end (run-tool-call.ts, capToolOutput), never the start alone: a du/find sweep's totals are its last lines. A read the run already made is answered from that answer (RepeatableToolNames, repeatToolCallKey, alreadyRanToolNote): calling read_file, list_files, search_knowledgebase, list_tasks and the like again with the same arguments returns a pointer to the output above instead of running again, and works. So a run whose brief can be wrong is told the tree wins over the brief, and told that handing the rest on with start_task is following the plan. computer_bash whose command provably only reads (isReadOnlyCommand: an allow-listed program and no redirect, no tee/xargs, no writing git subcommand) is a read here too; any other tool (a write, a bash command that isn't one) clears what was remembered, so a file read, edited and read again is read again. A call that failed is answered from that failure the same way, past one retry (toolCallKey, AppData.HarnessSameFailureRetries, failedToolCallNote): five identical failing commands once cost five turns, each resending the whole transcript. A turn that wrote a message and then called any other tool is told once that the message never went out (answerNotSentNote), since only the last one is sent: a run that doesn't know ends with the tail of an answer it already wrote.
  • Token use: every turn resends the system prompt, tool definitions and whole transcript, so a run's cost grows with its length squared (production lost 39M tokens on one routine run on a 1M-window model that never trimmed). Keep turns small: fitTranscriptToContext trims to the working context (grabContextBudgetTokens, never just the window), cutting in one block down to 60% so the cached prefix holds between cuts, and a trimmed tool result keeps its start and its end (TrimmedKeepChars) instead of being replaced whole: the old note said "call it again if you still need it", so runs did, paying twice for the same output; every AppData.HarnessTrimNoteEvery trimmed turns the run is told its earlier readings were cut (contextTrimmedNote, traced as trimmed), since trimming is otherwise invisible and a run re-reads what it thinks it never saw; the newest messages are never trimmed; the user's own text is never trimmed (a request can't be lost mid-run), so a run whose prompt is still over the working context after everything trimmable was cut is told once (oversizedRequestNote: work in pieces, don't paste more in, say what it could not reach), and fitTranscriptToContext reports it as over_budget; only the newest browser_snapshot and browser_find per browser stay (supersedeToolOutputs); browser results are capped lower (HarnessBrowserResultMaxChars); MCP and user-browser tools are deferred (listed by name in the prompt, loaded with load_tools) once their definitions pass HarnessDeferToolsMinChars, loaded ones appended last. Don't rewrite earlier transcript messages every turn (it breaks providers' prompt caches); token_usages.cached_tokens shows what was served from cache. Models that can't take an image/audio part get it read by vision/transcription first (prepareMessagesForModel, per candidate). Tool images (screenshots, read_file images) are never read by the tool: tools return { text, images }, the loop shows them in a user turn after the results (toolImagesTurn, fenced as tool output), and prepareMessagesForModel decides. A text model looks at images itself (attachments too) only when its text setting has "Use the model's own media reading" on (sees_images in the text harness options, per default/bot/workspace row, textSeesImages) and it takes image input: the catalog's input_modalities decide, so a custom provider's bare model id gets guessModelModalities, which says text-only for anything it doesn't recognise and then sees_images reads nothing (the Models page says so under the checkbox, HarnessSeesImagesNote, since the setting is otherwise silently useless). Otherwise the vision harness reads them (with the tool's focus and redact; pixels a seeing model gets can't be redacted). Readings are kept across runs by MediaReadings (HarnessMediaReadingsCached), keyed by imageReadingKey, so the same image is read once rather than once per reply; a reading made to redact a secret is never kept there. Only the newest AppData.HarnessToolImagesKept stay (dropOldToolImages).
  • Per-bot models: workspace row > bot row > default; the coordinator always uses the defaults. Every entry point takes bot_id and passes it on. Embeddings are install-wide (install_wide in Harnesses, isInstallWideHarness): grabHarnessSetting ignores bot/workspace rows for them, the per-bot/workspace forms don't list them and saving one is refused, so every stored vector comes from one model. Shared form settings/models/(partials)/harness-settings-form.tsx. A provider that embeds a passage and a query differently (NVIDIA's asymmetric models) is told which through input_type, from embedText's purpose; embed.ts finds that out on the first 400 that names the field and remembers it per provider and model for the process. A provider that caps a batch below AppData.EmbeddingBatchSize (Alibaba's Model Studio: "batch size is invalid, it should not be larger than 20") is answered by retrying the refused batch at the size it named, remembered per provider and model (smaller-batch-limit.ts), so one document's large batch no longer fails the whole ingest.
  • Generation settings follow the model: a model takes only the parameters its provider advertises (modelAdvertisesParameter, src/dict/harness-parameter-dict.ts); a custom provider's /models lists ids only, so its models take none and the form hides the Model settings target. The wire sends only advertised parameters (grabChatParams), never a value saved on another model. Switching the model or the provider clears the saved generation settings and voice (nextHarnessModelValue / nextHarnessProviderValue), so a temperature tuned for one model never rides to another that rejects it.
  • Tools: HarnessTool built per run; own tools validate with zod. run-tool-call.ts reports errors back to the model and caps each call at the tool's timeout_ms (its own, else AppData.HarnessToolTimeoutMs; null means no cap, as computer_bash has); a computer_*/browser_* call from a run without them (a reply) is told to use send_reply with work, or start_task in a task run (unknownToolMessage). Bot tools in src/harness/tools/bot/ (memory, instructions, tasks, schedules, read_settings, read_message_usage, send_reply, start_task, hand_over_task, update_requester (an interim word to the bot that asked while a crew request is open), coordinator's crew management, delegate_task and hand_over_schedule, with results relayed back by relayJobToRequester).
  • Extensions: MCP servers (mcp_servers, remote or stdio), custom tools (custom_tools: http, script, prompt) and skills (skills, runbooks loaded with load_skill). Given per bot / per workspace (botExtensionsSql); all_bots only decides what new bots get. Templates {{args.x}}/{{env.KEY}} via fillTemplate; secrets redacted from results. A prompt-kind tool's filled template is the model's own input, so a secret env fills in as its [KEY] marker there, never its value (runPromptTool); http and script tools use secrets server-side, where the value never reaches the model. stdio servers run in a per-process pool. Skill body limits are app settings (grabSkillBodyMaxChars, grabSkillBodyShownChars). A skill proposal says what it changes (skillProposalChanges) to the bot and in the confirm outcome, takes no unknown keys (a misnamed body would re-propose the saved runbook) and is refused when it changes nothing.
  • Bots never add or repoint extensions or set envs. The coordinator may only change what can't alter where data is sent (name, description, on/off, access); knowledgebases are the exception it fills itself, since they live on the install (see Knowledgebases). Its extension tools (grabCoordinatorExtensionTools) come wherever it works, a workspace as much as its own chat. New skills, servers, tools, or changes to a URL, headers, kind, config or a skill's runbook go through propose_* -> extension_proposals -> [proposal:ID] card, which the app describes from the config itself (never from what the bot says) and the super admin confirms (checkProposalData re-checks). A pending proposal for the same thing in the same conversation is replaced when another is made or one is confirmed (replacePendingExtensionProposals: a skill by data.slug, else the extension id, else the normalised name; replacePendingHookProposals by hook_id, then title), so a conversation carried into a new session no longer leaves a second card pending for the same skill (#41 stayed pending for ever while #42 made it, and the same target churned through #60-#63). Stdio servers are never proposed by bots (they run in the app container, which holds the docker socket).
  • Extension bundles: each of the four extension settings pages (MCP servers, tools, skills, knowledgebases) exports the rows picked there as one JSON file (cobble-extensions v1, {format, version, exported_at, app_version, items}, one item per row: {kind, key, config, redacted, env_keys, notes, documents?}) and imports one again beside its "New ..." button. src/functions/backend/db/extension-bundles/ holds the plain-data core (exportExtensions({kind, ids}), previewExtensionImport({bundle, kind}), applyExtensionImport({bundle, kind, decisions, user_id}); the three routes under api/admin/extensions/ are thin wrappers, super admin only, so a chat path can reuse them later). Preview matches by natural identity (mcp and skill slug, tool name, knowledgebase name lowercased) and calls each item new, same, conflict (with the differing fields) or invalid; nothing is written until the super admin picks skip/add/overwrite/copy per item, and one bad item never fails the batch. A bundle carries settings, never keys or reach: {{env.KEY}} templates stay, literal headers/env values are left out and named in redacted (missing keys are listed for Settings > Environment), and no grant or all_bots travels, so every imported row starts unattached. Knowledgebase documents travel as their text (never bytes; ingest re-embeds them), and nothing is synced on import, so a new MCP server says "Not connected yet: Refresh". One item can also be copied from its row's menu into its Add form: Copy MCP server / Copy tool / Copy skill / Copy knowledgebase copies that item's JSON (the export's shape, CopyExtensionMenuItem over the export route), and the Add form's Paste JSON button, beside Cancel and its submit, opens PasteExtensionModal, whose Fill the form button reads one item or a whole export (readExtensionPaste, validated by extensionItemSchema), fills the form and remounts it so its code fields take the new text; a knowledgebase's documents are written by save-knowledgebase when it is saved.
  • Check before and after acting (ActionCheckNote): look for an existing record before creating one, verify every action took effect. Tools enforce it (read-back on memory saves, duplicate checks on bots, schedules, tasks, workspaces).

Token usage

  • Every model call writes a token_usages row via record-harness-usage.ts (never throws) in withCandidates's on_success, with the provider/model that actually answered and the call's settings (HarnessCallSettings, including limits: the steps, run tokens and context the run was held to, so a bot can explain a cost against them with read_message_usage).
  • Attribution through an AsyncLocalStorage scope (src/harness/usage/harness-usage-scope.ts) entered once in run-bot-job.ts; merged, not replaced; null clears a field. withUsageScope / runWithFallbackScope for calls outside a run. No owner, no row.
  • Every failed model call also writes a harness_call_failures row (recordHarnessFailure, beside the log in withCandidates: model, pick, HTTP status, the provider's reason, rest), same attribution, no foreign keys, pruned with the logs' retention by prune-logs.
  • attachJobCallsToMessage back-fills message_id for the job's calls and failures, from complete-bot-job.ts and notify-bot-job-failed.ts (so a failure notice shows why). Messages show MessageUsageChip and a details modal (grabMessageDetails, failed calls listed with their reasons, and the run's calls counted by tool from bot_messages.tool_log in MessageToolsRollup: 242 model calls read differently once it says computer_bash 210, start_task 0).
  • /admin/usage (crew managers). Days are local, not UTC: group with date(created_at / 1000, 'unixepoch', 'localtime'); never name a local day with toISOString().slice(0, 10) (bucket-usage-days.test.ts pins this). Bars use static h-* classes from (data)/usage-bar-heights.ts.

Installer and release

  • install.sh (curl -fsSL https://url.moduletrace.com/cobble | sudo bash) is the only install and update path; idempotent; --uninstall [--purge]. Never regenerates secrets; backs up the DB before replacing the container, and removes every older tag of the app's and the computer's images plus dangling layers (prune_old_images, old_image_tags; docker refuses what a container still runs), since a release per update otherwise fills the host. Everything persistent lives in $COBBLE_HOME/data (default /opt/cobble).
  • Mount specs: source:destination[:options], options (z, ro) comma-separated in the third field. Never append an option to the destination ($DATA_DIR:/data,z mounts a directory literally named /data,z and loses all data on update). install.test.ts runs the marked selinux-detection and mount-specs blocks. /data must stay a bind mount (resolveHostPath maps it to host paths for computers).
  • App networks: extra docker networks for the app's own container (never computers) are the app setting app_extra_networks (Settings > General, super admin, picked from the networks docker lists, listJoinableNetworks), joined by the app itself over the docker socket (syncAppNetworks) at boot, on save and every 5 minutes, so they outlast install.sh recreating the container; the installer's --extra-network still works beside it.
  • Plain HTTP only; TLS is the proxy's job. Container: --network cobble, .env read-only at /app/.env, docker socket, MAIN_SERVER=1, --init, --cpus 1 --memory 2048m by default.
  • Publishing: scripts/publish-github.sh / publish-gitea.sh sharing scripts/lib/publish-*.sh (tested by scripts/publish-tools.test.ts). A GitHub release triggers .github/workflows/release.yml (amd64 + arm64 to ghcr.io/moduletrace/cobble); mirror-gitea.sh copies to git.tben.me/moduletrace/cobble (CI can't reach the VPN). Bump package.json's version with a release. CI (ci.yml) runs typecheck, tests, NODE_ENV=production bunx bunext build and check:bundle; the publish scripts' own gate is only typecheck, tests and bash -n install.sh, so build and run bun run check:bundle before publishing. Dockerfile pins Bun 1.4.3.
  • A release is done when every artifact exists and the CI run on the pushed commit is green, not when the tag is pushed. Publishing (publish/release/ship, any of them) means the whole chain, run by you and watched to the end: publish:github, publish:gitea, the CI run the push starts (gh run list --limit 5, then gh run watch <id> --exit-status; read a red one with gh run view <id> --log-failed), then gh run watch until the image build succeeds, then mirror:gitea (it has nothing to copy until that build finishes). The same CI check comes before updating installs. Report each artifact with its link, and say plainly (with the reason) if one fails or is still building: never hand back a tag and leave the rest as a note for the user. v0.26.0 shipped with check:bundle red (454 KB against a 450 KB budget) because nobody read the CI run after the push.

Admin routes

AdminSections: /admin/bots, /admin/workspaces, /admin/routines, /admin/logs, /admin/help, /admin/settings. /admin -> /admin/bots. Every /admin/* page renders in the bots layout (src/layouts/bots/); there is no separate admin layout.

  • Rail pages (src/dict/rail-pages-dict.ts): Routines, Files, Usage (crew managers), Activity (/admin/logs, super admin), Help ((data)/help-topics.ts). Visibility via canSeeRailItem for both the popover and the aside.
  • Settings (src/dict/settings-pages-dict.ts; add a sub page = folder + dict entry): general (theme per device, plus super-admin app settings: prompt append, run limits, skill limits; crew-manager storage quota; running version), setup (super admin; shares the Models page's server props and useModelsOverview), profile, notifications, change-password, secrets, browsers, models, environment, backups and database (super admin), bots, workspaces, host-directories (super admin), computers, mcps, tools, skills, knowledgebases (crew managers), users (canListUsers).
  • Settings pages use SettingsShell (breadcrumbs via admin-breadcrumbs.tsx), SettingsGroup blocks (no cards) and the sticky SettingsSaveBar. Each group of General also has a page of its own (/admin/settings/general/<section>, keyed in src/dict/general-settings-dict.ts, linked from the group's title): anyone who may read it sees its values (SettingsReadOnlyValues), only its owning role gets the form. A bot points at one with read_settings and a [setting:section:field] ref, so every limit refusal or cost answer names the page and value to change. Saves don't reload. Keep save notices in component state (useFormInit clears status on change). Lists share SettingsList/SettingsListRow/SettingsRowAction. Row actions are icon-only (RowIconButton).
  • Backups: DB snapshots (synchronous) and whole-data archives of DATA_DIR into BACKUP_ARCHIVE_DIR. What an archive leaves out is decided in one place, listArchiveExclusions (--no-wildcards --exclude-from): DATA_DIR/computers (a computer's workspace is the computer's own state, so AppData.DataBackupsKept copies of it never fill the volume and a restore neither empties nor copies that folder), each Chrome profile's caches (the profile is kept for its logins, a few MB against hundreds of MB of HTTP and code caches), db/.backups (that is the database snapshots' own list) and .bun-sqlite. A restore keeps the running install's db/.backups (copied aside and put back), since no archive carries them. Archives and restores outlast a request, so the route only starts the run (startDataBackupRun, which holds with-backup-run-lock.ts) and the page polls data-status. A restore takes a safety archive first, then restarts the process. A database snapshot restore restarts too (also a background run, db_restore): bun-sqlite import swaps in a new file from another process, and this process's handle would stay on the old one, so nothing may be written to the database between a restore and the restart (log entries go through queueBootLog, written by flushBootLogs at boot).
  • Database browser: strictly read-only; values cut in SQL; state in the address via databaseHref.
  • Add flow ((partials)/add-flow.tsx) from the rail's Add icon: bot, workspace, computer (super admin). Page heroes use AdminHero.

Page directory rules

Route-local code under src/pages goes in non-routed meta folders: (sections), (partials), (data), (functions), (utils), (hooks). Keep route files (index.tsx) thin. Dynamic routes [param], catch-all [[...paths]]. Server functions in index.server.ts beside index.tsx.

Shared code

  • src/hooks/ shared hooks; src/functions/backend/ server-only (auth, db, email, logger); src/functions/frontend/ client-safe handlers; src/functions/server/ server utilities.
  • src/utils/ utilities (most with tests), src/utils/rbac/ the RBAC engine.
  • src/dict/ dictionaries/constants; src/data/ static data (site-data.ts, app-data.ts with every AppData.* constant); src/types/; src/scripts/ CLI scripts; src/schemas/ zod schemas.
  • src/components/general/: shared components built on twui (logo, logo-icon, wordmark, bot-stone, user-avatar, code-editor, computer-view, admin-hero, login-shell, tab-button, ...).

UI and styling rules (MANDATORY)

  • Build UI with twui and src/components/general/. Don't hand-roll HTML for layout, typography or controls. Layout: Section, Container, Stack, Row, Center, Span, P, H1-H5, Button, Divider, Img, Link, ArrowedLink, Main, Header, Footer, Spacer. Elements: Card, Paper, Tag, HeaderNav, LinkList, Tabs, Table, Breadcrumbs, Modal, Dropdown, CheckBulletPoints, EmptyContent, Loading, LoadingBlock, Toggle, Toast. Forms: Form, Input, Select, Textarea, Checkbox, Radios, SearchSelect, FileUpload, ImageUpload.
  • UNCHANGEABLE: twui components always win over raw JSX elements (<h1>, <p>, <span>, <ul>, <li>, <img>, <a>, <button>, <div>-as-card, ...). Never introduce one where a twui equivalent exists; override via className.
  • No new CSS classes, CSS files or inline style={{...}}. Style only with component props, existing twui-* classes, semantic token utilities (bg-paper, text-ink, border-hairline, ...) and utilities already used in the codebase. Extend component code only when the API can't express the need.
  • Chunk classes with twMerge, one chunk per claim: base first, one string per conditional, caller override last. Never concatenate conditional classes with template literals or +, never one long mixed string: className={twMerge("w-full flex-col gap-0! rounded-default py-1", selected && "bg-ink/5")}.
  • twui Checkbox calls changeHandler on mount. Harmless for local state; anything that saves or confirms goes on clickDispatchHandler.
  • Theming: colours, radii and fonts change only in src/styles/main.css (:root/.dark vars exposed as paper, surface, sunken, ink, ink-secondary, ink-disabled, hairline, hairline-strong, on-ink, hue-<name>, shadow-popover, --m-fast/base/slow). Never hardcode hex colours, radii or font stacks. Hues are bot identity only, never state.
    • The one exception: a bot's user-chosen colour reaches BotStone, UnreadDot and WorkingSpinner as an SVG fill/stroke attribute. Nothing else may take a colour that way, and src/utils/bot-color.ts is the only place a colour string is validated.
  • Screenshots: docs/readme/{hero,workspace}-{light,dark}.png are real screenshots (1440px at 2x, downscaled to 1600px). Retake them from a seeded dev instance when the UI changes, same names. Never use handoff screens.
  • Logo: public/logos/logo.svg is the single source; after changing it run bun run gen:favicon.
  • Site name: interpolate SiteData["SiteName"] in titles, emails and copy; never hardcode the brand.

Conventions

  • One function/component per file.
  • Modularization is non-negotiable. Repeated UI blocks become reusable prop-driven components.
  • Every rendered array item is its own component: items.map((item) => <Item {...item} />), never inline JSX in the map.
  • No em dashes (U+2014) anywhere (code, comments, docs, copy). Use - or restructure.
  • Always object parameters ({ foo, bar }), never positional.
  • Prefer existing patterns over new abstractions.
  • Do not patch @moduletrace/twui (shared, publishable; its repo is named in Stack). Fix it there, then publish, and compose app-side changes in src/components/general/ or main.css. Ask the user before publishing a new twui version, every single time: a change that needs a release is not permission to publish one.
  • .env (secrets, gitignored, dockerignored) and secrets/ are never committed. external/ binary dirs are gitignored.
  • Rate limit unauthenticated endpoints that check secrets or send email (src/utils/rate-limit.ts).
  • Validate untrusted bodies with src/schemas/ via parseWithSchema. Throw AppError for safe messages; catch blocks return safeErrorMessage.
  • HTML columns accepting user input: sanitize with sanitizeRichTextHtml (or sanitizeUserBio) before storing or dangerouslySetInnerHTML.
  • Email outside production goes through resolveEmailRecipient (to DEV_EMAIL_RECIPIENT). Never hardcode recipients.
  • Never trust ids from the request body for ownership or sessions. Use the session user.id and the src/utils/rbac/ helpers.
  • Any helper deleting a parent row deletes its children explicitly (foreign keys are off outside the server process).
  • Keep this file current, and short: when you change something it describes, update the line; add new rules and gotchas, not inventories of helper names.