Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1bf50b717b | ||
|
|
c6697c91cd | ||
|
|
8d7309084f | ||
|
|
6f26222e2c | ||
|
|
343fdb2d25 | ||
|
|
1a0bcb8360 | ||
|
|
181b7f9e30 | ||
|
|
d7e66a5123 | ||
|
|
03e372d38d | ||
|
|
615ba5a9b9 | ||
|
|
6a808d8417 | ||
|
|
585b77eec1 | ||
|
|
74693cccd3 | ||
|
|
115113247f |
@@ -68,7 +68,7 @@ Enables SQLite foreign keys (`enableForeignKeys`), `bunextInit()`, `ensureDocker
|
||||
|
||||
### 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-chatrooms`, `prune-logs`.
|
||||
`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-chatrooms`, `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`), `prune-logs`.
|
||||
|
||||
### Admin CRUD API
|
||||
|
||||
@@ -92,17 +92,17 @@ Enables SQLite foreign keys (`enableForeignKeys`), `bunextInit()`, `ensureDocker
|
||||
- **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`; 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, no right panel; `?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]/chatrooms` that workspace's chatrooms; `/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). While a reply is due (read with the live face, never the page's) the page polls `session-messages` (`use-reply-catch-up`, also at once when the page comes back into view or online) in case a push was missed, replaying the messages and the bot's face and task as their pushes.
|
||||
- **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 and task (`session-messages`, `use-reply-catch-up`), 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. 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; `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), checked by the composer before it sends (the reason shows under the input) and again by the route.
|
||||
- **Composer:** Tiptap editor reading/writing markdown, drafts in `localStorage`, `@` bots / `#` workspaces written as `[bot:ID]`/`[workspace:ID]`. Enter sends (Mod+Enter in lists/code). `@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]`, `[proposal:ID]`, `[hook-proposal:ID]`, `[secret:ID]` (masked env, Reveal/Copy), `[secret-request:ID]` (masked input card), `[question:ID]` (a bot's questions), `[graphic:ID]` (a bot graphic, framed inline), `[room:ID]` (a chatroom), `[task:ID]` (a tracker task, opening `TaskDetailModal`). Parsers in `src/utils/*-ref.ts`. 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 passed on from chatrooms keep working.
|
||||
- **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`, `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 message's images), an image gets that list's images as its `gallery` (`imagePreviewGallery`): Previous/Next 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.
|
||||
- **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 -> `bot_questions` -> `[question:ID]` chip opening `BotQuestionCard`; 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. Replies and user-started tasks only: never routines, hook calls or chatroom sessions (no one sees those).
|
||||
- **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).
|
||||
- **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. Tasks don't get files yet.
|
||||
- **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 (`deleteChatroomRows`, `deleteHookSessionRows`, `prune-bot-hook-events`) 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. 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.
|
||||
- **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`.
|
||||
@@ -112,7 +112,9 @@ Enables SQLite foreign keys (`enableForeignKeys`), `bunextInit()`, `ensureDocker
|
||||
|
||||
### 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`.
|
||||
`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 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, chatroom). Memory, habits and the bot's own initiative never widen a request.
|
||||
|
||||
### Queue (`bots_queue`)
|
||||
|
||||
@@ -139,8 +141,9 @@ A worker reaches another worker **only through the coordinator**: `ask_crew` (ev
|
||||
|
||||
- **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; 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. **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`).
|
||||
- **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. **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 only measures it (`GET /api/usage` -> `grabComputerUsage`, `du` cached 10s); 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 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.
|
||||
@@ -213,12 +216,12 @@ Read-only browser of every volume (`src/utils/storage-volumes.ts`: bots, workspa
|
||||
- **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`.
|
||||
- **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`), 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`). 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`; a long run is told once, `AppData.HarnessStepsLowWarning` steps before the wrap up, to save its report, since the wrap up has no tools) and the prompt tokens one run may spend (`grabRunMaxPromptTokens`, then the wrap up).
|
||||
- **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; only the newest `browser_snapshot` per browser stays (`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; otherwise the vision harness reads them (with the tool's `focus` and `redact`; pixels a seeing model gets can't be redacted). Only the newest `AppData.HarnessToolImagesKept` stay (`dropOldToolImages`).
|
||||
- **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`), 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`). 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`; 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`) for a saving 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`, 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.
|
||||
- **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; only the newest `browser_snapshot` per browser stays (`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`.
|
||||
- **Tools:** `HarnessTool` built per run; own tools validate with zod. `run-tool-call.ts` reports errors back to the model and caps each call (`AppData.HarnessToolTimeoutMs`); a `computer_*`/`browser_*` call from a run without them (a reply) is told to use `start_task` (`unknownToolMessage`). Bot tools in `src/harness/tools/bot/` (memory, instructions, tasks, schedules, `start_task`, 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. 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). 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). Stdio servers are never proposed by bots (they run in the app container, which holds the docker socket).
|
||||
- **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); 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). Stdio servers are never proposed by bots (they run in the app container, which holds the docker socket).
|
||||
- **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
|
||||
@@ -231,7 +234,7 @@ Read-only browser of every volume (`src/utils/storage-volumes.ts`: bots, workspa
|
||||
|
||||
### 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. Everything persistent lives in `$COBBLE_HOME/data` (default `/opt/cobble`).
|
||||
- `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.
|
||||
@@ -244,7 +247,7 @@ Read-only browser of every volume (`src/utils/storage-volumes.ts`: bots, workspa
|
||||
- **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`, `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`. 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`. 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).
|
||||
- **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`.
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import browserArgs from "./browser-args";
|
||||
import browserArgs, { DiskCacheMaxBytes } from "./browser-args";
|
||||
|
||||
const base = {
|
||||
profile_dir: "/p",
|
||||
@@ -24,6 +24,13 @@ describe("browserArgs", () => {
|
||||
expect(browserArgs({ ...base, screen: { width: 1366, height: 768 }, scale: 1.25 })).toContain("--window-size=1092,614");
|
||||
});
|
||||
|
||||
test("caps the disk cache, so a profile can't grow by gigabytes", () => {
|
||||
const args = browserArgs({ ...base, screen: { width: 1920, height: 1080 }, scale: 1 });
|
||||
|
||||
expect(args).toContain(`--disk-cache-size=${DiskCacheMaxBytes}`);
|
||||
expect(DiskCacheMaxBytes).toBe(512 * 1024 * 1024);
|
||||
});
|
||||
|
||||
test("keeps WebGL but composites in software", () => {
|
||||
const args = browserArgs({ ...base, screen: { width: 1920, height: 1080 }, scale: 1 });
|
||||
|
||||
|
||||
@@ -21,6 +21,13 @@ type Params = {
|
||||
extra?: string[];
|
||||
};
|
||||
|
||||
/**
|
||||
* Chrome's on-disk HTTP cache, in bytes. Left to itself Chrome grows it to
|
||||
a few gigabytes inside the profile, which is mounted and never shrinks;
|
||||
what it holds is fetched again on demand.
|
||||
*/
|
||||
export const DiskCacheMaxBytes = 512 * 1024 * 1024;
|
||||
|
||||
/**
|
||||
* Chrome's background work a lightweight browser goes without: on-device
|
||||
* model and hint downloads, casting, translate prompts, autofill lookups.
|
||||
@@ -57,6 +64,7 @@ export default function browserArgs({ profile_dir, cdp_port, screen, scale, lang
|
||||
// Chrome reads the window size in scaled units: divided by the
|
||||
// scale, the window fills the screen exactly.
|
||||
`--window-size=${Math.floor(screen.width / scale)},${Math.floor(screen.height / scale)}`,
|
||||
`--disk-cache-size=${DiskCacheMaxBytes}`,
|
||||
...(scale == 1 ? [] : [`--force-device-scale-factor=${scale}`]),
|
||||
...(lightweight ? lightweightArgs() : desktopGpuArgs()),
|
||||
/**
|
||||
|
||||
@@ -5,6 +5,7 @@ import handleExec from "./handle-exec";
|
||||
import handleFileDownload from "./handle-file-download";
|
||||
import handleFileStat from "./handle-file-stat";
|
||||
import handleFileWrite from "./handle-file-write";
|
||||
import handleUsage from "./handle-usage";
|
||||
import isAuthorized from "./is-authorized";
|
||||
import isPortAnswering from "./is-port-answering";
|
||||
import log from "./log";
|
||||
@@ -22,6 +23,7 @@ import serveStaticFile from "./serve-static-file";
|
||||
* - `GET /api/info`, `POST /api/exec`, `GET /api/files/stat|download`,
|
||||
* `POST /api/files/write`: the app's shell and file access, as gem or
|
||||
* as a worker bot's own account (`run_as`).
|
||||
* - `GET /api/usage`: how much the workspace holds.
|
||||
* - `/mcp`: Playwright MCP, driving the computer's browser.
|
||||
* - `/desktop/` and its `/desktop/websockify` websocket: the screen
|
||||
* (noVNC over Xvnc), Chrome's whole window.
|
||||
@@ -139,6 +141,7 @@ async function route({ req, res, parking }: { req: IncomingMessage; res: ServerR
|
||||
if (pathname == "/api/files/stat" && req.method == "GET") return handleFileStat({ req, res });
|
||||
if (pathname == "/api/files/download" && req.method == "GET") return handleFileDownload({ req, res });
|
||||
if (pathname == "/api/files/write" && req.method == "POST") return handleFileWrite({ req, res });
|
||||
if (pathname == "/api/usage" && req.method == "GET") return handleUsage({ req, res });
|
||||
|
||||
sendJson({ res, status: 404, body: { error: "Not Found" } });
|
||||
}
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
import type { IncomingMessage, ServerResponse } from "node:http";
|
||||
import { AgentConfig } from "./config";
|
||||
import sendJson from "./send-json";
|
||||
import { workspaceUsage } from "./workspace-usage";
|
||||
|
||||
/**
|
||||
* `GET /api/usage`: how much the computer's workspace holds
|
||||
* (`workspaceUsage`). Only the size: what may be written there is the
|
||||
* app's call (`grabComputerWorkspaceQuotaBytes`), so changing the limit
|
||||
* needs no new container.
|
||||
*/
|
||||
export default async function handleUsage({ res }: { req: IncomingMessage; res: ServerResponse }) {
|
||||
sendJson({ res, body: { used_bytes: await workspaceUsage(), workspace_dir: AgentConfig.WorkspaceDir } });
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
import { afterEach, describe, expect, test } from "bun:test";
|
||||
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import pruneProfileCache from "./prune-profile-cache";
|
||||
|
||||
/**
|
||||
* The profile is mounted from the data volume, so whatever this clears is
|
||||
* gone for good. A cache comes back by itself, an extension's own state
|
||||
* never does, so only caches may ever be in these lists.
|
||||
*/
|
||||
const roots: string[] = [];
|
||||
|
||||
function profile() {
|
||||
const root = mkdtempSync(path.join(tmpdir(), "cobble-profile-"));
|
||||
|
||||
roots.push(root);
|
||||
|
||||
return root;
|
||||
}
|
||||
|
||||
function write({ root, relative }: { root: string; relative: string }) {
|
||||
const target = path.join(root, relative);
|
||||
|
||||
mkdirSync(path.dirname(target), { recursive: true });
|
||||
writeFileSync(target, "x".repeat(1024));
|
||||
}
|
||||
|
||||
function exists({ root, relative }: { root: string; relative: string }) {
|
||||
return require("node:fs").existsSync(path.join(root, relative));
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
describe("pruneProfileCache", () => {
|
||||
test("keeps an extension's own state", () => {
|
||||
const root = profile();
|
||||
|
||||
write({ root, relative: "Default/Storage/ext/abc/def" });
|
||||
write({ root, relative: "Default/Local Storage/leveldb/000003.log" });
|
||||
|
||||
pruneProfileCache({ profile_dir: root });
|
||||
|
||||
expect(exists({ root, relative: "Default/Storage/ext/abc/def" })).toBeTrue();
|
||||
expect(exists({ root, relative: "Default/Local Storage/leveldb/000003.log" })).toBeTrue();
|
||||
});
|
||||
|
||||
test("never touches a login, a permission or history", () => {
|
||||
const root = profile();
|
||||
|
||||
write({ root, relative: "Default/Cookies" });
|
||||
write({ root, relative: "Default/Login Data" });
|
||||
write({ root, relative: "Default/Preferences" });
|
||||
write({ root, relative: "Default/History" });
|
||||
write({ root, relative: "Default/Extensions/abc/1.0/manifest.json" });
|
||||
|
||||
pruneProfileCache({ profile_dir: root });
|
||||
|
||||
for (const relative of ["Default/Cookies", "Default/Login Data", "Default/Preferences", "Default/History", "Default/Extensions/abc/1.0/manifest.json"]) {
|
||||
expect(exists({ root, relative })).toBeTrue();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,97 @@
|
||||
import { afterEach, describe, expect, test } from "bun:test";
|
||||
import { existsSync, mkdirSync, mkdtempSync, readdirSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import pruneProfileCache from "./prune-profile-cache";
|
||||
|
||||
/**
|
||||
* The profile is mounted so logins survive a restart, and this runs at
|
||||
* every start: a folder wrongly listed here would log the user out of
|
||||
* every site, and one wrongly left out grows the volume forever.
|
||||
*/
|
||||
const dirs: string[] = [];
|
||||
|
||||
function profile() {
|
||||
const dir = mkdtempSync(path.join(tmpdir(), "cobble-profile-"));
|
||||
|
||||
dirs.push(dir);
|
||||
|
||||
return dir;
|
||||
}
|
||||
|
||||
function write({ root, relative, bytes }: { root: string; relative: string; bytes: number }) {
|
||||
const target = path.join(root, relative);
|
||||
|
||||
mkdirSync(path.dirname(target), { recursive: true });
|
||||
writeFileSync(target, "x".repeat(bytes));
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
describe("pruneProfileCache", () => {
|
||||
test("clears a profile's caches and the ones Chrome keeps beside it", () => {
|
||||
const root = profile();
|
||||
|
||||
write({ root, relative: "Default/Cache/data_0", bytes: 400 });
|
||||
write({ root, relative: "Default/Code Cache/js/index", bytes: 300 });
|
||||
write({ root, relative: "Default/Service Worker/CacheStorage/a/b", bytes: 200 });
|
||||
write({ root, relative: "Profile 1/Cache/data_0", bytes: 100 });
|
||||
write({ root, relative: "ShaderCache/data", bytes: 500 });
|
||||
write({ root, relative: "GPUCache/data", bytes: 50 });
|
||||
|
||||
expect(pruneProfileCache({ profile_dir: root })).toBe(1550);
|
||||
|
||||
for (const gone of [
|
||||
"Default/Cache",
|
||||
"Default/Code Cache",
|
||||
"Default/Service Worker/CacheStorage",
|
||||
"Profile 1/Cache",
|
||||
"ShaderCache",
|
||||
"GPUCache",
|
||||
]) {
|
||||
expect(existsSync(path.join(root, gone))).toBe(false);
|
||||
}
|
||||
});
|
||||
|
||||
test("never touches a login, a permission or an extension", () => {
|
||||
const root = profile();
|
||||
|
||||
write({ root, relative: "Default/Cookies", bytes: 10 });
|
||||
write({ root, relative: "Default/Login Data", bytes: 10 });
|
||||
write({ root, relative: "Default/Preferences", bytes: 10 });
|
||||
write({ root, relative: "Default/Local Storage/leveldb/a.log", bytes: 10 });
|
||||
write({ root, relative: "Default/Extensions/abc/1.0/page.html", bytes: 10 });
|
||||
write({ root, relative: "Local State", bytes: 10 });
|
||||
|
||||
expect(pruneProfileCache({ profile_dir: root })).toBe(0);
|
||||
|
||||
for (const kept of [
|
||||
"Default/Cookies",
|
||||
"Default/Login Data",
|
||||
"Default/Preferences",
|
||||
"Default/Local Storage",
|
||||
"Default/Extensions",
|
||||
"Local State",
|
||||
]) {
|
||||
expect(existsSync(path.join(root, kept))).toBe(true);
|
||||
}
|
||||
});
|
||||
|
||||
test("a folder that isn't a profile is left alone", () => {
|
||||
const root = profile();
|
||||
|
||||
write({ root, relative: "SomeOtherProfile/Cache/data_0", bytes: 400 });
|
||||
|
||||
expect(pruneProfileCache({ profile_dir: root })).toBe(0);
|
||||
expect(readdirSync(root)).toEqual(["SomeOtherProfile"]);
|
||||
});
|
||||
|
||||
test("an empty or missing profile frees nothing and throws nothing", () => {
|
||||
const root = profile();
|
||||
|
||||
expect(pruneProfileCache({ profile_dir: root })).toBe(0);
|
||||
expect(pruneProfileCache({ profile_dir: path.join(root, "missing") })).toBe(0);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,121 @@
|
||||
import { readdirSync, rmSync, statSync } from "node:fs";
|
||||
import path from "node:path";
|
||||
import log from "./log";
|
||||
|
||||
/**
|
||||
* Folders inside a browser profile that only ever hold what Chrome can
|
||||
* download or build again. Cookies, logins, site permissions, history,
|
||||
* local storage and extensions live elsewhere and are never touched: the
|
||||
* profile is mounted so a computer keeps them across restarts.
|
||||
*/
|
||||
const RegenerableProfileDirs = [
|
||||
"ShaderCache",
|
||||
"GrShaderCache",
|
||||
"GPUCache",
|
||||
"GPUPersistentCache",
|
||||
"GraphiteDawnCache",
|
||||
"DawnGraphiteCache",
|
||||
"DawnWebGPUCache",
|
||||
"component_crx_cache",
|
||||
"CertificateRevocation",
|
||||
"optimization_guide_model_store",
|
||||
];
|
||||
|
||||
/**
|
||||
* The same, in each profile's own folder (`Default`, `Profile 1`, ...).
|
||||
* Never `Local Storage`, `IndexedDB` or `Storage/ext`: those are what the
|
||||
* extensions a computer keeps (Cookie-Editor among them) hold their own
|
||||
* state in, which is not rebuilt by downloading anything.
|
||||
*/
|
||||
const RegenerableBrowserDirs = [
|
||||
"Cache",
|
||||
"Code Cache",
|
||||
"GPUCache",
|
||||
"GPUPersistentCache",
|
||||
"GraphiteDawnCache",
|
||||
"DawnGraphiteCache",
|
||||
"DawnWebGPUCache",
|
||||
"Service Worker/CacheStorage",
|
||||
"Service Worker/ScriptCache",
|
||||
];
|
||||
|
||||
/**
|
||||
* Frees what Chrome downloaded or built last time it ran and will build
|
||||
* again: extension assets, the component updater's CRX cache, model files,
|
||||
* certificate revocation lists, HTTP and code caches. A profile otherwise
|
||||
* grows by hundreds of megabytes and never shrinks.
|
||||
*
|
||||
* Only called while no browser runs (a cache cleared under a live Chrome
|
||||
* leaves it writing into a deleted folder). Returns the bytes freed.
|
||||
*/
|
||||
export default function pruneProfileCache({ profile_dir }: { profile_dir: string }) {
|
||||
let freed = 0;
|
||||
|
||||
for (const name of RegenerableProfileDirs) {
|
||||
freed += freeDir({ target: path.join(profile_dir, name) });
|
||||
}
|
||||
|
||||
for (const profile of safeReadDir({ target: profile_dir })) {
|
||||
/**
|
||||
* A profile's own folder: `Default` or `Profile <n>`, and
|
||||
* `System Profile` for Chrome's own pages.
|
||||
*/
|
||||
if (!/^(Default|Profile \d+|System Profile)$/.test(profile)) continue;
|
||||
|
||||
for (const name of RegenerableBrowserDirs) {
|
||||
freed += freeDir({ target: path.join(profile_dir, profile, name) });
|
||||
}
|
||||
}
|
||||
|
||||
if (freed > 0) log({ name: "browser", message: `cleared ${(freed / (1024 * 1024)).toFixed(1)} MB of regenerable profile cache` });
|
||||
|
||||
return freed;
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes one folder with what is under it, returning the bytes.
|
||||
*/
|
||||
function freeDir({ target }: { target: string }) {
|
||||
const size = dirSize({ target });
|
||||
|
||||
if (!size) return 0;
|
||||
|
||||
try {
|
||||
rmSync(target, { recursive: true, force: true });
|
||||
|
||||
return size;
|
||||
} catch {
|
||||
/**
|
||||
* Something that can't be removed is left for the next start; the
|
||||
* browser comes up either way.
|
||||
*/
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Bytes under one folder. Links are counted, never followed: a profile
|
||||
* has none of its own, but a retired one might.
|
||||
*/
|
||||
function dirSize({ target }: { target: string }): number {
|
||||
let stat;
|
||||
|
||||
try {
|
||||
stat = statSync(target);
|
||||
} catch {
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (stat.isFile()) return stat.size;
|
||||
if (!stat.isDirectory()) return 0;
|
||||
|
||||
return safeReadDir({ target }).reduce((total, entry) => total + dirSize({ target: path.join(target, entry) }), 0);
|
||||
}
|
||||
|
||||
function safeReadDir({ target }: { target: string }) {
|
||||
try {
|
||||
return readdirSync(target);
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,7 @@ import { AgentConfig } from "./config";
|
||||
import findBrowserBinary from "./find-browser-binary";
|
||||
import isPortAnswering from "./is-port-answering";
|
||||
import log from "./log";
|
||||
import pruneProfileCache from "./prune-profile-cache";
|
||||
import superviseProcess, { type Supervised } from "./supervise-process";
|
||||
import userEnv from "./user-env";
|
||||
import waitUntil from "./wait-until";
|
||||
@@ -92,6 +93,11 @@ export default async function startServices({ parking }: { parking: BrowserParki
|
||||
command: binary,
|
||||
args: () => {
|
||||
clearProfileLocks({ profile_dir: AgentConfig.ProfileDir });
|
||||
/**
|
||||
* No browser runs now (this is its start): the caches it built
|
||||
* last time are free to go, so the profile stops growing.
|
||||
*/
|
||||
pruneProfileCache({ profile_dir: AgentConfig.ProfileDir });
|
||||
|
||||
return browserArgs({
|
||||
profile_dir: AgentConfig.ProfileDir,
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
import { execFile } from "node:child_process";
|
||||
import { AgentConfig } from "./config";
|
||||
|
||||
/**
|
||||
* When the workspace was last measured, and what it held: the whole
|
||||
* folder, every bot's and user's included, since that is what grows on the
|
||||
* data volume.
|
||||
*/
|
||||
let measured = { bytes: 0, at: 0 };
|
||||
|
||||
/**
|
||||
* Measuring walks the whole workspace, so a run writing several files in a
|
||||
* row asks once. The app's quota is its own decision; this is only how
|
||||
* much is there.
|
||||
*/
|
||||
const CacheMs = 10_000;
|
||||
|
||||
/**
|
||||
* How many bytes the workspace holds, measured with `du` (which reads the
|
||||
* folders in C) and reused for `CacheMs`.
|
||||
*/
|
||||
export async function workspaceUsage() {
|
||||
if (measured.at && Date.now() - measured.at < CacheMs) return measured.bytes;
|
||||
|
||||
measured = { bytes: await measureWorkspace(), at: Date.now() };
|
||||
|
||||
return measured.bytes;
|
||||
}
|
||||
|
||||
/**
|
||||
* The workspace's size through `du` (bytes), 0 when it can't be read: a
|
||||
* missing folder holds nothing.
|
||||
*/
|
||||
function measureWorkspace() {
|
||||
return new Promise<number>((resolve) => {
|
||||
execFile("du", ["-s", "-B1", "--", AgentConfig.WorkspaceDir], { timeout: 30_000 }, (error, stdout) => {
|
||||
if (error) return resolve(0);
|
||||
|
||||
const bytes = Number(String(stdout).trim().split(/\s+/)[0]);
|
||||
|
||||
resolve(Number.isFinite(bytes) && bytes > 0 ? bytes : 0);
|
||||
});
|
||||
});
|
||||
}
|
||||
+55
@@ -565,6 +565,58 @@ wait_for_health() {
|
||||
fail "Cobble did not become healthy within ${HEALTH_TIMEOUT_SECONDS}s"
|
||||
}
|
||||
|
||||
# ---------------------------------------------------------------- images
|
||||
|
||||
# Every release is a new image tag, and a host keeps every one of them
|
||||
# otherwise: over a gigabyte each, so a year of updates can hold tens of
|
||||
# gigabytes that nothing runs. Once the new container is healthy, the image
|
||||
# the previous one ran is removed (the registry still has it) along with the
|
||||
# layers nobody uses any more, and so is every older tag of the app's image
|
||||
# and of the computer's, which the app pulls again when it needs one.
|
||||
|
||||
# MARK:old-image-tags
|
||||
# The tags of one image repository in a `docker image ls --format
|
||||
# '{{.Repository}} {{.Tag}}'` listing, except the tag being installed (an
|
||||
# empty `keep` keeps none) and anything docker couldn't name.
|
||||
old_image_tags() {
|
||||
local listing="$1"
|
||||
local repo="$2"
|
||||
local keep="$3"
|
||||
|
||||
printf '%s\n' "$listing" | awk -v repo="$repo" -v keep="$keep" '
|
||||
$1 == repo && $2 != "" && $2 != "<none>" && $2 != keep { print $2 }
|
||||
'
|
||||
}
|
||||
# END:old-image-tags
|
||||
|
||||
prune_old_images() {
|
||||
local previous="$1"
|
||||
if [ -n "$previous" ] && [ "$previous" != "$IMAGE:$VERSION" ]; then
|
||||
say "Removing the previous image ${previous}"
|
||||
docker rmi "$previous" >/dev/null 2>&1 || true
|
||||
fi
|
||||
|
||||
# Releases keep stacking up: an install updated twice a month holds
|
||||
# every tag it ever ran. Docker refuses any image a container still
|
||||
# uses, stopped ones included, so only what nothing runs goes.
|
||||
local listing repo tag
|
||||
listing="$(docker image ls --format '{{.Repository}} {{.Tag}}' 2>/dev/null || true)"
|
||||
repo="$(printf '%s' "$IMAGE" | sed -E 's|:[^/:]+$||')"
|
||||
|
||||
for name in "$repo" "$repo-computer"; do
|
||||
local keep=""
|
||||
[ "$name" = "$repo" ] && keep="$VERSION"
|
||||
|
||||
while IFS= read -r tag; do
|
||||
[ -z "$tag" ] && continue
|
||||
say "Removing the older image ${name}:${tag}"
|
||||
docker rmi "${name}:${tag}" >/dev/null 2>&1 || true
|
||||
done <<< "$(old_image_tags "$listing" "$name" "$keep")"
|
||||
done
|
||||
|
||||
docker image prune -f >/dev/null 2>&1 || true
|
||||
}
|
||||
|
||||
backup_database() {
|
||||
local data_source="$DATA_DIR"
|
||||
if container_exists; then
|
||||
@@ -909,6 +961,7 @@ if container_exists; then
|
||||
# own layer, so lift it out before anything replaces the container.
|
||||
rescue_container_data
|
||||
backup_database
|
||||
PREVIOUS_IMAGE_TAG="$(docker inspect -f '{{.Config.Image}}' "$CONTAINER" 2>/dev/null || true)"
|
||||
say "Replacing the Cobble container"
|
||||
docker stop -t 30 "$CONTAINER" >/dev/null 2>&1 || true
|
||||
docker rm -f "$CONTAINER" >/dev/null 2>&1 || true
|
||||
@@ -920,6 +973,8 @@ connect_extra_network
|
||||
|
||||
wait_for_health
|
||||
|
||||
prune_old_images "${PREVIOUS_IMAGE_TAG:-}"
|
||||
|
||||
ok "Cobble is running"
|
||||
printf '\n'
|
||||
printf ' %sOpen Cobble%s\n' "$C_BOLD" "$C_RESET"
|
||||
|
||||
@@ -182,6 +182,64 @@ describe("install.sh mount specs", () => {
|
||||
}
|
||||
});
|
||||
|
||||
describe("install.sh image pruning", () => {
|
||||
const LISTING = [
|
||||
"ghcr.io/moduletrace/cobble 0.18.2",
|
||||
"ghcr.io/moduletrace/cobble 0.18.3",
|
||||
"ghcr.io/moduletrace/cobble 0.18.4",
|
||||
"ghcr.io/moduletrace/cobble-computer 1.3.0",
|
||||
"ghcr.io/moduletrace/cobble-computer 1.4.0",
|
||||
"ghcr.io/moduletrace/cobble-tools 9.9.9",
|
||||
"<none> <none>",
|
||||
].join("\n");
|
||||
|
||||
async function oldImageTags({ repo, keep }: { repo: string; keep: string }) {
|
||||
const block = await readMarkedBlock({ name: "old-image-tags" });
|
||||
const script = [block, `old_image_tags "$LISTING" "$repo" "$keep"`].join("\n");
|
||||
const proc = Bun.spawn({
|
||||
cmd: ["bash", "-c", script],
|
||||
env: { ...process.env, LISTING, repo, keep },
|
||||
stdout: "pipe",
|
||||
stderr: "pipe",
|
||||
});
|
||||
const [stdout, , code] = await Promise.all([
|
||||
new Response(proc.stdout).text(),
|
||||
new Response(proc.stderr).text(),
|
||||
proc.exited,
|
||||
]);
|
||||
|
||||
expect(code).toBe(0);
|
||||
|
||||
return stdout.trim().split("\n").filter(Boolean);
|
||||
}
|
||||
|
||||
test("removes every older version of the app, keeping the one installed", async () => {
|
||||
expect(
|
||||
await oldImageTags({ repo: "ghcr.io/moduletrace/cobble", keep: "0.18.4" }),
|
||||
).toEqual(["0.18.2", "0.18.3"]);
|
||||
});
|
||||
|
||||
test("removes every computer image tag, since the app pulls one again", async () => {
|
||||
expect(
|
||||
await oldImageTags({ repo: "ghcr.io/moduletrace/cobble-computer", keep: "" }),
|
||||
).toEqual(["1.3.0", "1.4.0"]);
|
||||
});
|
||||
|
||||
test("never touches another repository's images", async () => {
|
||||
// `cobble-tools` shares the prefix: a prefix match would take a
|
||||
// project the installer knows nothing about.
|
||||
const tags = await oldImageTags({
|
||||
repo: "ghcr.io/moduletrace/cobble-tools",
|
||||
keep: "",
|
||||
});
|
||||
|
||||
expect(tags).toEqual(["9.9.9"]);
|
||||
expect(
|
||||
await oldImageTags({ repo: "ghcr.io/moduletrace/cobble", keep: "" }),
|
||||
).not.toContain("9.9.9");
|
||||
});
|
||||
});
|
||||
|
||||
describe("install.sh data rescue", () => {
|
||||
test("rescues the container's data before replacing it", async () => {
|
||||
const source = await Bun.file(INSTALL_SCRIPT).text();
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "cobble",
|
||||
"version": "0.18.2",
|
||||
"version": "0.18.7",
|
||||
"module": "index.ts",
|
||||
"type": "module",
|
||||
"private": true,
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import type { BotMessageWithAttachments } from "@/src/types";
|
||||
import liveAttachmentMessages from "./live-attachment-messages";
|
||||
|
||||
const message = ({ id, files }: { id: number; files?: number }): BotMessageWithAttachments => ({
|
||||
id,
|
||||
attachments: files
|
||||
? Array.from({ length: files }, (_unused, index) => ({
|
||||
id: index + 1,
|
||||
name: `file-${index + 1}.png`,
|
||||
media_type: "image",
|
||||
url: `/media/${index + 1}.png`,
|
||||
}))
|
||||
: undefined,
|
||||
});
|
||||
|
||||
describe("liveAttachmentMessages", () => {
|
||||
test("hands over the files of the latest messages that have any", () => {
|
||||
const messages = [
|
||||
message({ id: 1 }),
|
||||
message({ id: 2, files: 1 }),
|
||||
message({ id: 3 }),
|
||||
message({ id: 4, files: 2 }),
|
||||
message({ id: 5 }),
|
||||
];
|
||||
|
||||
expect(
|
||||
liveAttachmentMessages({ messages, max_messages: 4, max_age: 8 }),
|
||||
).toEqual([2, 4]);
|
||||
});
|
||||
|
||||
test("only the newest few file-bearing messages", () => {
|
||||
const messages = [
|
||||
message({ id: 1, files: 1 }),
|
||||
message({ id: 2, files: 1 }),
|
||||
message({ id: 3, files: 1 }),
|
||||
message({ id: 4, files: 1 }),
|
||||
];
|
||||
|
||||
expect(
|
||||
liveAttachmentMessages({ messages, max_messages: 2, max_age: 8 }),
|
||||
).toEqual([3, 4]);
|
||||
});
|
||||
|
||||
test("a file far back is named, not re-attached", () => {
|
||||
const messages = [
|
||||
message({ id: 1, files: 1 }),
|
||||
...Array.from({ length: 20 }, (_unused, index) => message({ id: index + 2 })),
|
||||
];
|
||||
|
||||
expect(
|
||||
liveAttachmentMessages({ messages, max_messages: 4, max_age: 8 }),
|
||||
).toEqual([]);
|
||||
});
|
||||
|
||||
test("keeps a file that is still inside the age bound", () => {
|
||||
const messages = [
|
||||
message({ id: 1, files: 1 }),
|
||||
...Array.from({ length: 6 }, (_unused, index) => message({ id: index + 2 })),
|
||||
];
|
||||
|
||||
expect(
|
||||
liveAttachmentMessages({ messages, max_messages: 4, max_age: 8 }),
|
||||
).toEqual([1]);
|
||||
});
|
||||
|
||||
test("no files, nothing to hand over", () => {
|
||||
expect(
|
||||
liveAttachmentMessages({
|
||||
messages: [message({ id: 1 }), message({ id: 2 })],
|
||||
}),
|
||||
).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,45 @@
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
import type { BotMessageWithAttachments } from "@/src/types";
|
||||
|
||||
type Params = {
|
||||
/**
|
||||
* The conversation a reply reads, oldest first.
|
||||
*/
|
||||
messages: BotMessageWithAttachments[];
|
||||
/**
|
||||
* How many messages with files may hand their files over
|
||||
* (`AppData.BotReplyAttachmentMessages`).
|
||||
*/
|
||||
max_messages?: number;
|
||||
/**
|
||||
* How far back a file may be and still be handed over
|
||||
* (`AppData.BotReplyAttachmentMaxAgeMessages`).
|
||||
*/
|
||||
max_age?: number;
|
||||
};
|
||||
|
||||
/**
|
||||
* The messages whose attached files a reply gets as the files themselves,
|
||||
* oldest first. Two limits, both needed: only the latest few messages with
|
||||
* files (`max_messages`), and only while the conversation hasn't moved
|
||||
* far past them (`max_age`).
|
||||
*
|
||||
* The age bound is what keeps one upload from being re-attached, and so
|
||||
* re-read by the media reading harness, on every reply for the rest of a
|
||||
* long session (a screenshot 25 messages back was read once per reply, a
|
||||
* vision call of a minute each time). Past it the file is only named
|
||||
* (`botMessagesToHarness`), so the bot still knows it was sent.
|
||||
*/
|
||||
export default function liveAttachmentMessages({
|
||||
messages,
|
||||
max_messages = AppData.BotReplyAttachmentMessages,
|
||||
max_age = AppData.BotReplyAttachmentMaxAgeMessages,
|
||||
}: Params): number[] {
|
||||
const oldest_allowed = messages.length - Math.max(0, max_age);
|
||||
|
||||
return messages
|
||||
.map((message, index) => ({ message, index }))
|
||||
.filter(({ message, index }) => index >= oldest_allowed && Boolean(message.attachments?.length))
|
||||
.slice(-Math.max(0, max_messages))
|
||||
.map(({ message }) => Number(message.id));
|
||||
}
|
||||
@@ -7,6 +7,7 @@ import type { HarnessContentPart } from "@/src/harness/types";
|
||||
import type { BotMessageWithAttachments } from "@/src/types";
|
||||
import extractBotFileText from "@/src/functions/backend/db/bot-files/extract-bot-file-text";
|
||||
import describeAttachment from "./describe-attachment";
|
||||
import liveAttachmentMessages from "./live-attachment-messages";
|
||||
|
||||
type Params = {
|
||||
/**
|
||||
@@ -17,18 +18,13 @@ type Params = {
|
||||
|
||||
/**
|
||||
* The files of the latest few messages that have any
|
||||
* (`AppData.BotReplyAttachmentMessages`), as model input by message id:
|
||||
* images and audio as themselves (a model that can't take them gets them
|
||||
* read first), documents as their text, videos as a note. Older files are
|
||||
* only named (`botMessagesToHarness`).
|
||||
* (`liveAttachmentMessages`), as model input by message id: images and
|
||||
* audio as themselves (a model that can't take them gets them read
|
||||
* first), documents as their text, videos as a note. Older files are only
|
||||
* named (`botMessagesToHarness`).
|
||||
*/
|
||||
export default async function loadAttachmentParts({ messages }: Params) {
|
||||
const recent = messages
|
||||
.filter((message) => message.attachments?.length)
|
||||
.slice(-AppData.BotReplyAttachmentMessages)
|
||||
.map((message) => Number(message.id));
|
||||
|
||||
const media = await grabMessagesMedia({ message_ids: recent });
|
||||
const media = await grabMessagesMedia({ message_ids: liveAttachmentMessages({ messages }) });
|
||||
const parts = new Map<number, HarnessContentPart[]>();
|
||||
|
||||
for (const [message_id, files] of media) {
|
||||
|
||||
@@ -3,6 +3,7 @@ import { grabSkillBodyShownChars } from "@/src/functions/backend/db/app-settings
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
import {
|
||||
ActionCheckNote,
|
||||
RequestScopeNote,
|
||||
QuestionsNote,
|
||||
AskCrewNote,
|
||||
SecretsNote,
|
||||
@@ -354,6 +355,7 @@ export default async function runBotReply({
|
||||
TasksNote,
|
||||
TaskReminderNote,
|
||||
ActionCheckNote,
|
||||
RequestScopeNote({ can_ask: true }),
|
||||
QuestionsNote,
|
||||
SecretsNote,
|
||||
composeEnvsNote({ ...envs, has_computer: computers.length > 0 }),
|
||||
|
||||
@@ -6,6 +6,7 @@ import workspaceAdminsNote from "./workspace-admins-note";
|
||||
import type { BUN_SQLITE_COBBLE_BOTS } from "@/db/types/db";
|
||||
import {
|
||||
ActionCheckNote,
|
||||
RequestScopeNote,
|
||||
QuestionsNote,
|
||||
SecretsNote,
|
||||
GraphicsNote,
|
||||
@@ -413,6 +414,7 @@ export default async function runBotTask({
|
||||
ComputerFilesNote({ computer_id: job.computer_id || 0, dirs }),
|
||||
TasksNote,
|
||||
ActionCheckNote,
|
||||
RequestScopeNote({ can_ask }),
|
||||
can_ask ? QuestionsNote : "",
|
||||
SecretsNote,
|
||||
GraphicsNote,
|
||||
|
||||
@@ -4,6 +4,9 @@ import pruneBotsQueue from "./prune-bots-queue";
|
||||
import cronClearJobSteps from "./clear-job-steps";
|
||||
import pruneBotHookEvents from "./prune-bot-hook-events";
|
||||
import cronPruneChatrooms from "./prune-chatrooms";
|
||||
import cronPruneComputerCaches from "./prune-computer-caches";
|
||||
import cronPruneComputerHomes from "./prune-computer-homes";
|
||||
import cronPruneOrphanMedia from "./prune-orphan-media";
|
||||
import pruneLogs from "./prune-logs";
|
||||
import syncNotifyWatchers from "./sync-notify-watchers";
|
||||
import cronSyncHarnessModels from "./sync-harness-models";
|
||||
@@ -53,6 +56,24 @@ export default function cron() {
|
||||
task: cronPruneChatrooms,
|
||||
});
|
||||
|
||||
registerCronJob({
|
||||
title: "prune-orphan-media",
|
||||
schedule: "@daily",
|
||||
task: cronPruneOrphanMedia,
|
||||
});
|
||||
|
||||
registerCronJob({
|
||||
title: "prune-computer-caches",
|
||||
schedule: "@daily",
|
||||
task: cronPruneComputerCaches,
|
||||
});
|
||||
|
||||
registerCronJob({
|
||||
title: "prune-computer-homes",
|
||||
schedule: "@daily",
|
||||
task: cronPruneComputerHomes,
|
||||
});
|
||||
|
||||
registerCronJob({
|
||||
title: "prune-logs",
|
||||
schedule: "@daily",
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
import deleteHookSessionRows from "@/src/functions/backend/db/bot-hooks/delete-hook-session-rows";
|
||||
import { grabHookEventsKeepDays } from "@/src/functions/backend/db/app-settings/grab-hook-events-keep-days";
|
||||
import deleteUnlinkedAttachmentMedia from "@/src/functions/backend/db/media/delete-unlinked-attachment-media";
|
||||
|
||||
/**
|
||||
* Deletes hook calls (with their responses) older than the install's
|
||||
@@ -14,7 +15,19 @@ export default async function pruneBotHookEvents() {
|
||||
WHERE s.hook_id IS NOT NULL AND m.id IN (SELECT response_message_id FROM bot_hook_events WHERE created_at < ?)`;
|
||||
|
||||
await BunSQLite.sql({ sql: `DELETE FROM bot_message_reactions WHERE message_id IN (${messages})`, values: [cutoff] });
|
||||
|
||||
/**
|
||||
* The call's uploads go with its messages: their `media` row is what
|
||||
* the deleted link was the only way to reach.
|
||||
*/
|
||||
const uploads = await BunSQLite.sql<{ media_id: number }>({
|
||||
sql: `SELECT media_id FROM bot_message_media WHERE message_id IN (${messages})`,
|
||||
values: [cutoff],
|
||||
});
|
||||
|
||||
await BunSQLite.sql({ sql: `DELETE FROM bot_message_media WHERE message_id IN (${messages})`, values: [cutoff] });
|
||||
|
||||
await deleteUnlinkedAttachmentMedia({ media_ids: (uploads.payload || []).map((row) => Number(row.media_id)) }).catch(() => []);
|
||||
await BunSQLite.sql({ sql: `DELETE FROM bot_messages WHERE id IN (${messages})`, values: [cutoff] });
|
||||
|
||||
await deleteHookSessionRows({});
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
import pruneComputerCaches from "@/src/functions/backend/computers/prune-computer-caches";
|
||||
|
||||
/**
|
||||
* Clears the caches a computer's folders hold (`pruneComputerCaches`):
|
||||
* what pip, npm and bun write beside a run's work, Python's bytecode and
|
||||
* every Chrome profile's caches. Runs now keep their caches inside the
|
||||
* container (`computerCacheEnv`), so this is what an install that grew
|
||||
* before that shrinks back with.
|
||||
*/
|
||||
export default async function cronPruneComputerCaches() {
|
||||
const pruned = await pruneComputerCaches();
|
||||
const bytes = pruned.reduce((total, entry) => total + entry.bytes, 0);
|
||||
|
||||
return { removed: pruned.length, mb: Math.round(bytes / (1024 * 1024)) };
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
import pruneComputerHomes from "@/src/functions/backend/db/computers/prune-computer-homes";
|
||||
|
||||
/**
|
||||
* Deletes the computer folders `prepareComputerDataDir` moved aside
|
||||
* (`pruneComputerHomes`) once their data is past its keep. They are no
|
||||
* longer mounted anywhere, so they only take space on the data volume.
|
||||
*/
|
||||
export default async function cronPruneComputerHomes() {
|
||||
return { deleted: (await pruneComputerHomes()).length };
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
import pruneOrphanMedia from "@/src/functions/backend/db/media/prune-orphan-media";
|
||||
|
||||
/**
|
||||
* Deletes media nothing points at any more (`pruneOrphanMedia`): chat
|
||||
* uploads left behind by a pruned room or hook session, and uploads that
|
||||
* were never saved. It is how their bytes leave the data volume.
|
||||
*/
|
||||
export default async function cronPruneOrphanMedia() {
|
||||
return { deleted: (await pruneOrphanMedia()).length };
|
||||
}
|
||||
+89
-5
@@ -110,7 +110,7 @@ export const AppData = {
|
||||
* `computer/` (the release workflow builds that tag), and bump
|
||||
* `ComputerWorkspaceLayout` too when existing computers must move to it.
|
||||
*/
|
||||
ComputerImage: "ghcr.io/moduletrace/cobble-computer:1.3.0",
|
||||
ComputerImage: "ghcr.io/moduletrace/cobble-computer:1.4.0",
|
||||
ComputerContainerPrefix: `${SiteData["SiteSlug"]}-computer`,
|
||||
/**
|
||||
* Only a computer's workspace (`ComputerWorkspaceDir` in its
|
||||
@@ -157,6 +157,22 @@ export const AppData = {
|
||||
*/
|
||||
ComputerBrowserDownloadsDir: "/home/gem/Downloads",
|
||||
ComputerDownloadsFolder: "downloads",
|
||||
/**
|
||||
* The most a computer's workspace (`DATA_DIR/computers/<id>`) may hold,
|
||||
* when the install saves no `computer_workspace_quota_mb` setting. It
|
||||
* is one folder for every bot and user on that computer, mounted from
|
||||
* the data volume, so a run that fills it takes the host's disk with
|
||||
* it: `computer_write_file`, `computer_edit_file` and every
|
||||
* `computer_bash` command that outgrows it are told to free space
|
||||
* first (`computerWorkspaceRoomError`). 0 sets no limit.
|
||||
*/
|
||||
ComputerWorkspaceQuotaMb: 10240,
|
||||
/**
|
||||
* How long a media row nothing points at stays before
|
||||
* `prune-orphan-media` deletes it. Long enough that an upload in flight,
|
||||
* or one a delete is still tidying, is never taken with it.
|
||||
*/
|
||||
MediaOrphanKeepDays: 30,
|
||||
/**
|
||||
* Written at the root of a computer's workspace once it uses that
|
||||
* layout, so an older computer's whole home is told apart and moved
|
||||
@@ -168,6 +184,14 @@ export const AppData = {
|
||||
* `<id><ComputerOldHomeSuffix><timestamp>` and kept, never archived.
|
||||
*/
|
||||
ComputerOldHomeSuffix: "-home-",
|
||||
/**
|
||||
* How long a computer's old home stays after
|
||||
* `prepareComputerDataDir` moved it aside, before
|
||||
* `prune-computer-homes` deletes it. Nothing mounts it again
|
||||
* (backups leave it out), so its only role is a look at what an
|
||||
* earlier layout held.
|
||||
*/
|
||||
ComputerOldHomeKeepDays: 45,
|
||||
/**
|
||||
* Recorded in a container's `metadata.layout`: the image and mounts it
|
||||
* was created with. A container with another value is recreated
|
||||
@@ -177,9 +201,13 @@ export const AppData = {
|
||||
* container gets `NET_ADMIN` to keep them off its services);
|
||||
* `cobble-computer-homes` has workers work in their own home
|
||||
* (`/home/cb-<bot>/workspace`, a link the agent keeps to their folder),
|
||||
* which an older agent would make a folder that isn't kept.
|
||||
* which an older agent would make a folder that isn't kept;
|
||||
* `cobble-computer-caches` is the image whose agent reports its
|
||||
* workspace (`/api/usage`), keeps run caches out of it and clears its
|
||||
* browser profile's caches at each start, so a computer still running
|
||||
* an older one is recreated onto it once.
|
||||
*/
|
||||
ComputerWorkspaceLayout: "cobble-computer-homes",
|
||||
ComputerWorkspaceLayout: "cobble-computer-caches",
|
||||
ComputerUserUid: 1000,
|
||||
ComputerUserGid: 1000,
|
||||
/**
|
||||
@@ -510,10 +538,22 @@ export const AppData = {
|
||||
* saves its report before the wrap up ends it (two runs in a row once
|
||||
* ran out with the report unwritten). Only in runs of at least
|
||||
* `HarnessStepsLowMinSteps` steps, where the warning still leaves room
|
||||
* to act on it.
|
||||
* to act on it. Long runs are warned earlier, a share of their budget
|
||||
* (`HarnessStepsLowWarnShare`) in, never below this many steps.
|
||||
*/
|
||||
HarnessStepsLowWarning: 5,
|
||||
HarnessStepsLowMinSteps: 15,
|
||||
/**
|
||||
* Share of a run's steps it is warned to save with: a tenth of a 200
|
||||
* step run (20) rather than the 5 a short reply gets, so a long audit
|
||||
* has room to write its report after measuring.
|
||||
*/
|
||||
HarnessStepsLowWarnShare: 0.1,
|
||||
/**
|
||||
* Image readings kept across runs: one upload read once, not once per
|
||||
* reply (`media-readings`).
|
||||
*/
|
||||
HarnessMediaReadingsCached: 100,
|
||||
/**
|
||||
* Upload cap for audio sent to transcription.
|
||||
*/
|
||||
@@ -570,8 +610,11 @@ export const AppData = {
|
||||
* past `ComputerReadFileMaxLineChars`, files up to
|
||||
* `ComputerReadFileMaxBytes`. `computer_write_file` and
|
||||
* `computer_edit_file` take files up to `ComputerWriteFileMaxChars`.
|
||||
* Never above `HarnessToolResultMaxChars`: the harness cuts there too,
|
||||
* and a larger cap only meant the tool's own head-and-tail note was
|
||||
* thrown away by the second cut.
|
||||
*/
|
||||
ComputerCommandMaxOutputChars: 40_000,
|
||||
ComputerCommandMaxOutputChars: 20_000,
|
||||
ComputerReadFileMaxLines: 2000,
|
||||
ComputerReadFileMaxLineChars: 2000,
|
||||
ComputerReadFileMaxBytes: 10 * 1024 * 1024,
|
||||
@@ -657,6 +700,12 @@ export const AppData = {
|
||||
* How many of a session's latest messages that check reads.
|
||||
*/
|
||||
BotReplyCatchUpMessages: 20,
|
||||
/**
|
||||
* A window regaining focus and its tab becoming visible are often one
|
||||
* return, and each may fire more than once: a second signal this soon
|
||||
* after the first (a refocus, a socket remount) is the same return.
|
||||
*/
|
||||
RefocusGapMs: 1000,
|
||||
/**
|
||||
* How much of the conversation a bot sees when it replies.
|
||||
*/
|
||||
@@ -670,11 +719,39 @@ export const AppData = {
|
||||
* How many older messages each scroll to the top of the thread loads.
|
||||
*/
|
||||
ConversationOlderMessages: 30,
|
||||
/**
|
||||
* The phone's pull-to-reload gesture on the thread, in pixels: how far
|
||||
* the finger travels before the gesture counts as a pull rather than a
|
||||
* tap (`PullToRefreshMinPx`), how much of that travel shows
|
||||
* (`PullToRefreshResistance`), and the room it opens under the newest
|
||||
* message (`PullToRefreshRoomPx`), which no drag opens deeper.
|
||||
*/
|
||||
PullToRefreshMinPx: 8,
|
||||
PullToRefreshResistance: 0.6,
|
||||
PullToRefreshRoomPx: 64,
|
||||
/**
|
||||
* How long that room must stay full, in milliseconds, before letting go
|
||||
* reloads: an exhausted thread reaches the limit by accident too easily,
|
||||
* and keeping the finger there says the reload was meant.
|
||||
*/
|
||||
PullToRefreshHoldMs: 500,
|
||||
/**
|
||||
* The shortest the reloading icon stays up, in milliseconds: a reload
|
||||
* the server answers at once still says it happened.
|
||||
*/
|
||||
PullToRefreshMinLoadingMs: 1000,
|
||||
/**
|
||||
* The most model calls a message's details modal lists one by one. A
|
||||
* long task can take hundreds; the totals still count every one.
|
||||
*/
|
||||
MessageDetailsMaxCalls: 200,
|
||||
/**
|
||||
* The most model calls and failed calls a message's details report
|
||||
* lists one by one when it's copied (the Details modal's icon): a
|
||||
* whole report for a bug report, not only the first calls the modal
|
||||
* shows. The totals count every call either way.
|
||||
*/
|
||||
MessageDetailsCopyMaxCalls: 2000,
|
||||
/**
|
||||
* The most characters of a provider's error kept on a failed model
|
||||
* call (`harness_call_failures.error`), shown in the message's details.
|
||||
@@ -812,6 +889,13 @@ export const AppData = {
|
||||
* themselves to a reply; older ones are named.
|
||||
*/
|
||||
BotReplyAttachmentMessages: 4,
|
||||
/**
|
||||
* And only while they're within this many of the conversation's latest
|
||||
* messages: a file from far back is named, not re-attached, so one old
|
||||
* document isn't read from disk and resent in full on every reply of a
|
||||
* long session (images are cheap now: `MediaReadings` reads each once).
|
||||
*/
|
||||
BotReplyAttachmentMaxAgeMessages: 20,
|
||||
/**
|
||||
* Longest HTML document a bot graphic (`bot_graphics`) may be.
|
||||
*/
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
/**
|
||||
* What a bot's folder on a computer holds that is rebuilt on demand, and
|
||||
* so is never worth keeping.
|
||||
*
|
||||
* A computer's workspace is mounted from the data volume, so without this
|
||||
* every cache a run writes beside its work is kept forever: one install's
|
||||
* volume held 368 MB of npm cache, 188 MB of pip and headless-Chromium
|
||||
* caches and 53 MB of bun's install cache, against 178 MB of bot files.
|
||||
* Runs now point their caches at the account's own home inside the
|
||||
* container (`computerCacheEnv`), which a new container starts without;
|
||||
* `pruneComputerCaches` clears what earlier runs left behind.
|
||||
*/
|
||||
|
||||
/**
|
||||
* A run folder's caches, relative to it. `.cache` is where every tool
|
||||
* writes once a run has one (`computerCacheEnv`: pip, Playwright,
|
||||
* Chromium, bun's install cache); the rest is what runs before that wrote
|
||||
* into the folder itself.
|
||||
*/
|
||||
export const ComputerRunCacheEntries = [
|
||||
".cache",
|
||||
".npm/_logs",
|
||||
".npm/_cacache",
|
||||
".bun/install/cache",
|
||||
] as const;
|
||||
|
||||
/**
|
||||
* Python's bytecode folders, anywhere below a run folder: every script a
|
||||
* bot imports makes one.
|
||||
*/
|
||||
export const ComputerBytecodeCacheDir = "__pycache__";
|
||||
|
||||
/**
|
||||
* A browser profile a bot started itself, in its own folder, rather than
|
||||
* the app's (which lives at `AppData.ComputerBrowserProfileDir`). It holds
|
||||
* cookies like any profile, so only its caches go, never the folder.
|
||||
*/
|
||||
export const ComputerRunBrowserProfileDir = ".cobble-browser";
|
||||
|
||||
/**
|
||||
* The folders inside a Chrome profile that only hold what Chrome downloads
|
||||
* or builds again. Two of them alone were 729 MB of one install's 1009 MB
|
||||
* profile, while what a profile is kept for (cookies, logins, site
|
||||
* permissions, history, local storage, extensions) is a few MB.
|
||||
*
|
||||
* Keep alike `computer/agent/prune-profile-cache.ts`, which clears the
|
||||
* same ones from inside the container on each start; this list is for the
|
||||
* app's own daily prune and for a data archive, which both work on the
|
||||
* data volume.
|
||||
*/
|
||||
export const BrowserProfileCacheDirs = [
|
||||
"Cache",
|
||||
"Code Cache",
|
||||
"GPUCache",
|
||||
"GPUPersistentCache",
|
||||
"DawnGraphiteCache",
|
||||
"DawnWebGPUCache",
|
||||
"GraphiteDawnCache",
|
||||
"GrShaderCache",
|
||||
"ShaderCache",
|
||||
"Service Worker",
|
||||
"CertificateRevocation",
|
||||
"component_crx_cache",
|
||||
"WasmTtsEngine",
|
||||
"OnDeviceHeadSuggestModel",
|
||||
"ActorSafetyLists",
|
||||
"OptimizationHints",
|
||||
"OptimizationGuideModelsManifest",
|
||||
"optimization_guide_model_store",
|
||||
"PKIMetadata",
|
||||
"hyphen-data",
|
||||
"ZxcvbnData",
|
||||
"Subresource Filter",
|
||||
"segmentation_platform",
|
||||
"Crowd Deny",
|
||||
"SafetyTips",
|
||||
"BrowserMetrics-spare.pma",
|
||||
] as const;
|
||||
@@ -44,6 +44,7 @@ Permission to draft is not permission to send, permission to analyze is not perm
|
||||
|
||||
- If nothing in the crew fits and the need will recur, name the gap and propose a bot: short name, one-line role, what it handles. Create it with \`create_bot\` once the user agrees, and give it a workspace.
|
||||
- A worker is on the crew only once \`create_bot\` confirmed it.
|
||||
- A request to create a bot is a request for that bot alone. Placing it in a workspace, assigning it a computer and giving it work each need the user's own yes, asked for in one \`ask_user\` card, and that answer is the only thing that authorizes it.
|
||||
- A workspace is where bots share one project's context. Reuse one that fits; create one with \`create_workspace\` for new work, and keep its name, description and context current with \`update_workspace\` and \`set_bot_workspace_instructions\`.
|
||||
- Check membership with the tools. Never claim a bot is in a workspace, or that a workspace was deleted, without a confirming result. Explain what a deletion removes before asking for it.
|
||||
- Workspace context is information, not authorization.
|
||||
|
||||
@@ -6,6 +6,7 @@ import {
|
||||
coordinatorReplyNote,
|
||||
crewRequestsNote,
|
||||
openRunsNote,
|
||||
RequestScopeNote,
|
||||
TaskIncomingNote,
|
||||
TaskRedraftNote,
|
||||
TaskWrapUpIncomingNote,
|
||||
@@ -104,6 +105,29 @@ describe("openRunsNote", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("RequestScopeNote", () => {
|
||||
test("sends crew changes and handed-out work through one ask_user card", () => {
|
||||
const note = RequestScopeNote({ can_ask: true });
|
||||
|
||||
expect(note).toContain("not permission to put them in a workspace, assign them computers or give them work");
|
||||
expect(note).toContain("a standing preference is not a standing instruction");
|
||||
expect(note).toContain("the same ask_user card");
|
||||
expect(note).toContain("delegating a task");
|
||||
expect(note).toContain("don't offer it again in this conversation");
|
||||
expect(note).not.toContain("the brief is what you may do");
|
||||
expect(note).not.toContain("\u2014");
|
||||
});
|
||||
|
||||
test("proposes instead of asking when nobody is watching", () => {
|
||||
const note = RequestScopeNote({ can_ask: false });
|
||||
|
||||
expect(note).toContain("the brief is what you may do");
|
||||
expect(note).toContain("Say in your report what you would propose");
|
||||
expect(note).not.toContain("ask_user");
|
||||
expect(note).not.toContain("\u2014");
|
||||
});
|
||||
});
|
||||
|
||||
describe("task incoming notes", () => {
|
||||
test("leave separate requests to the chat and never offer send_message", () => {
|
||||
for (const note of [TaskIncomingNote, TaskRedraftNote, TaskWrapUpIncomingNote]) {
|
||||
|
||||
@@ -195,6 +195,27 @@ Anything you read or write goes to your model provider, so secret values (passwo
|
||||
- Never print, cat or echo a secret on a computer. To show one to the user, use show_secret for an env you have, or in a task on a computer capture it with capture_secret: either gives you a [secret:ID] ref to put in your message.
|
||||
- Use secrets by key ($KEY in the shell, {{env.KEY}} in tools), never by value. A value you see as [KEY] in output was redacted: that's expected.`;
|
||||
|
||||
/**
|
||||
* Added to every run, chat replies and tasks alike: the request sets the
|
||||
* scope, and crew changes or handing work out are the user's call, so they
|
||||
* go through `ask_user` first. `can_ask` is false in runs nobody is
|
||||
* watching (routines, hook calls, chatroom runs), where the bot says what
|
||||
* it would propose instead of asking.
|
||||
*/
|
||||
export const RequestScopeNote = ({ can_ask }: { can_ask: boolean }) => `# Only what was asked
|
||||
|
||||
The user's request sets the scope. Do what they asked, in the scope they gave, and nothing more.
|
||||
|
||||
- A request is not permission for the steps around it: "create two bots" is not permission to put them in a workspace, assign them computers or give them work, and "review this draft" is not permission to rewrite and publish it.
|
||||
- Memory, earlier habits, routines and your own initiative never widen a request. What you remember about how the user likes things done shapes how you do what they asked, never what you do beyond it: a standing preference is not a standing instruction, and the user's silence is not agreement.
|
||||
- Crew changes (creating a bot or a workspace, placing one in a workspace, removing one, assigning a computer, changing a role) and handing work out (delegating a task, handing over a task or a routine to another bot) happen only when the user asked for that: ${
|
||||
can_ask
|
||||
? `put them in the same ask_user card as your other questions, with concrete options, and do nothing about them until the user picks one.`
|
||||
: `the brief is what you may do. Say in your report what you would propose, and why.`
|
||||
}
|
||||
- When you can't tell whether something was asked for, it wasn't: ask. Once the user has chosen, do exactly that, nothing bundled with it.
|
||||
- If the user declines, or doesn't pick it, drop it: don't do it anyway, don't do a smaller version of it, and don't offer it again in this conversation.`;
|
||||
|
||||
/**
|
||||
* Added to chat replies and to tasks the user started: before acting on
|
||||
* something unclear, a bot asks (`ask_user`) rather than guesses.
|
||||
|
||||
@@ -203,3 +203,9 @@ export const ComputerBlockedMcpArgs = [
|
||||
"--output-dir",
|
||||
"--file-paths",
|
||||
] as const;
|
||||
|
||||
/**
|
||||
* The `app_settings` key holding how much a computer's workspace may hold,
|
||||
* in MB (0 sets no limit).
|
||||
*/
|
||||
export const ComputerWorkspaceQuotaSettingKey = "computer_workspace_quota_mb";
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
import { afterEach, describe, expect, test } from "bun:test";
|
||||
import fs from "fs";
|
||||
import os from "os";
|
||||
import path from "path";
|
||||
import listArchiveExclusions from "./list-archive-exclusions";
|
||||
|
||||
const dirs: string[] = [];
|
||||
|
||||
function makeDataDir() {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "cobble-exclusions-"));
|
||||
|
||||
dirs.push(dir);
|
||||
|
||||
return dir;
|
||||
}
|
||||
|
||||
function write({ root, relative, content = "x" }: { root: string; relative: string; content?: string }) {
|
||||
const target = path.join(root, relative);
|
||||
|
||||
fs.mkdirSync(path.dirname(target), { recursive: true });
|
||||
fs.writeFileSync(target, content);
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
for (const dir of dirs.splice(0)) {
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
describe("listArchiveExclusions", () => {
|
||||
test("leaves out the install's disposable folders and keeps everything else", async () => {
|
||||
const root = makeDataDir();
|
||||
|
||||
write({ root, relative: "computers/1/bots/3/users/1/node_modules/pkg/index.js" });
|
||||
write({ root, relative: "computer-browsers/1/Default/Cache/data" });
|
||||
write({ root, relative: "computer-browsers/1/Default/Code Cache/js" });
|
||||
write({ root, relative: "computer-browsers/1/GPUCache/data" });
|
||||
write({ root, relative: "computer-browsers/1/Default/Cookies" });
|
||||
write({ root, relative: "computer-browsers/1/Default/Preferences" });
|
||||
write({ root, relative: "db/.backups/cobble-1" });
|
||||
write({ root, relative: "db/cobble" });
|
||||
write({ root, relative: ".bun-sqlite/.tmp/temp.db" });
|
||||
write({ root, relative: "bots/1/report.md" });
|
||||
|
||||
const excluded = await listArchiveExclusions({ data_dir: root });
|
||||
|
||||
expect(excluded.sort()).toEqual([
|
||||
"./.bun-sqlite",
|
||||
"./computer-browsers/1/Default/Cache",
|
||||
"./computer-browsers/1/Default/Code Cache",
|
||||
"./computer-browsers/1/GPUCache",
|
||||
"./computers",
|
||||
"./db/.backups",
|
||||
]);
|
||||
});
|
||||
|
||||
test("lists only what is there", async () => {
|
||||
const root = makeDataDir();
|
||||
|
||||
write({ root, relative: "bots/1/report.md" });
|
||||
|
||||
expect(await listArchiveExclusions({ data_dir: root })).toEqual([]);
|
||||
});
|
||||
|
||||
test("a profile's logins and preferences stay", async () => {
|
||||
const root = makeDataDir();
|
||||
|
||||
write({ root, relative: "computer-browsers/2/Profile 1/Cache/data" });
|
||||
write({ root, relative: "computer-browsers/2/Profile 1/Login Data" });
|
||||
write({ root, relative: "computer-browsers/2/Default/Extensions/abc/manifest.json" });
|
||||
|
||||
const excluded = await listArchiveExclusions({ data_dir: root });
|
||||
|
||||
expect(excluded).toEqual(["./computer-browsers/2/Profile 1/Cache"]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,101 @@
|
||||
import fs from "fs/promises";
|
||||
import path from "path";
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
import { BrowserProfileCacheDirs } from "@/src/data/computer-cache-paths";
|
||||
|
||||
type Params = {
|
||||
/**
|
||||
* The volume's root, as `grabDirNames` gives it.
|
||||
*/
|
||||
data_dir: string;
|
||||
};
|
||||
|
||||
type AddExclusion = (segments: string[]) => void;
|
||||
|
||||
type ProfileParams = {
|
||||
dir: string;
|
||||
rel: string[];
|
||||
add: AddExclusion;
|
||||
};
|
||||
|
||||
const ProfileCacheNames = new Set<string>(BrowserProfileCacheDirs);
|
||||
|
||||
/**
|
||||
* Every path under `DATA_DIR` a data archive leaves out, as tar members
|
||||
* (`./db/.backups`), which `writeDataBackupArchive` hands tar with
|
||||
* `--no-wildcards`: these are exact paths, never patterns, so a folder a
|
||||
* bot named `node_modules!` or `Cache*` never takes a real one with it.
|
||||
*
|
||||
* A data archive used to tar the whole volume with one exclusion, so an
|
||||
* install's archive grew to 2 GB: 2457 MB of computer workspaces (against
|
||||
* 178 MB of bot files), 993 MB of Chrome profile caches, 148 MB of
|
||||
* database snapshots and 15 MB of bun-sqlite's scratch space.
|
||||
*
|
||||
* What stays out and why:
|
||||
* - `AppData.ComputerDataDir`: a computer's workspace is that computer's
|
||||
* own state, and the restore leaves it live rather than replacing it
|
||||
* (`restoreDataBackup`), so archiving it only grew every archive. Its
|
||||
* caches are also cleared in place (`pruneComputerCaches`).
|
||||
* - a Chrome profile's caches (`BrowserProfileCacheDirs`): the profile is
|
||||
* kept for its logins, which are a few MB next to hundreds of MB of HTTP
|
||||
* and code caches Chrome downloads again.
|
||||
* - `db/.backups`: Settings > Backups > Database's own list, not part of
|
||||
* the data volume; a restore keeps the running install's snapshots.
|
||||
* - `.bun-sqlite`: bun-sqlite's own scratch space, written again on the
|
||||
* next start.
|
||||
*/
|
||||
export default async function listArchiveExclusions({ data_dir }: Params): Promise<string[]> {
|
||||
const excluded: string[] = [];
|
||||
const add: AddExclusion = (segments) => excluded.push(`./${segments.join("/")}`);
|
||||
|
||||
if (await exists(path.join(data_dir, AppData.ComputerDataDir))) add([AppData.ComputerDataDir]);
|
||||
|
||||
for (const entry of await readDirectories(path.join(data_dir, AppData.ComputerBrowserDataDir))) {
|
||||
const rel = [AppData.ComputerBrowserDataDir, entry.name];
|
||||
|
||||
await excludeBrowserProfile({ dir: path.join(data_dir, ...rel), rel, add });
|
||||
}
|
||||
|
||||
if (await exists(path.join(data_dir, "db", ".backups"))) add(["db", ".backups"]);
|
||||
|
||||
if (await exists(path.join(data_dir, ".bun-sqlite"))) add([".bun-sqlite"]);
|
||||
|
||||
return excluded;
|
||||
}
|
||||
|
||||
/**
|
||||
* A Chrome profile's caches, at its root and inside its `Default` (or
|
||||
* `Profile N`) folder. Cookies, logins, preferences, extensions and local
|
||||
* storage stay.
|
||||
*/
|
||||
async function excludeBrowserProfile({ dir, rel, add }: ProfileParams) {
|
||||
for (const entry of await readEntries(dir)) {
|
||||
if (ProfileCacheNames.has(entry.name)) {
|
||||
add([...rel, entry.name]);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!entry.isDirectory()) continue;
|
||||
|
||||
for (const inner of await readEntries(path.join(dir, entry.name))) {
|
||||
if (ProfileCacheNames.has(inner.name)) add([...rel, entry.name, inner.name]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function readDirectories(dir: string) {
|
||||
return (await readEntries(dir)).filter((entry) => entry.isDirectory());
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads a folder's entries without following a symlink (`withFileTypes`
|
||||
* reports the link itself), so a link inside a profile never leads the
|
||||
* walk out of the volume.
|
||||
*/
|
||||
async function readEntries(dir: string) {
|
||||
return await fs.readdir(dir, { withFileTypes: true }).catch(() => []);
|
||||
}
|
||||
|
||||
async function exists(target: string) {
|
||||
return Boolean(await fs.stat(target).catch(() => null));
|
||||
}
|
||||
@@ -49,10 +49,9 @@ function findArchiveRoot({ staging_dir }: RootParams) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Replaces the whole `DATA_DIR` with the contents of a data archive:
|
||||
* the database, media, computer homes, bot and workspace files, and the
|
||||
* database snapshots in `db/.backups` (which the archive's own overwrite,
|
||||
* so the restore is one consistent set).
|
||||
* Replaces the install's data with the contents of a data archive: the
|
||||
* database, media, bot and workspace files (which the archive's own
|
||||
* database snapshots come with, so the restore is one consistent set).
|
||||
*
|
||||
* The archive is read into a temporary directory on the same volume
|
||||
* first, must hold one root folder with a database in it, and nothing on
|
||||
@@ -60,6 +59,10 @@ function findArchiveRoot({ staging_dir }: RootParams) {
|
||||
* is taken as a safety copy, then the data directory is emptied (the
|
||||
* database snapshots included) and filled from the archive.
|
||||
*
|
||||
* A computer's folders (`AppData.ComputerDataDir`) are neither emptied nor
|
||||
* copied: the archive doesn't hold them, and a computer's workspace is the
|
||||
* computer's own state, so a restore leaves it as it is.
|
||||
*
|
||||
* Runs only inside `startDataBackupRun`, which holds the backup run lock
|
||||
* for it (taking it again here would refuse every restore).
|
||||
*
|
||||
@@ -118,9 +121,29 @@ export default async function restoreDataBackup({
|
||||
// current ones, so the safety copy is taken before them.
|
||||
const safety = await writeDataBackupArchive();
|
||||
|
||||
// Everything goes, the snapshots in `db/.backups` included:
|
||||
// the archive's own set replaces them.
|
||||
/**
|
||||
* The database snapshots are their own feature (Settings >
|
||||
* Backups > Database) and no data archive carries them
|
||||
* (`listArchiveExclusions`), so wiping the volume would lose
|
||||
* them for good. Held aside and put back under the restored
|
||||
* database.
|
||||
*/
|
||||
const snapshots_dir = path.join(DATA_DIR, "db", ".backups");
|
||||
const kept_snapshots = path.join(staging_dir, "kept-snapshots");
|
||||
const has_snapshots = fs.existsSync(snapshots_dir);
|
||||
|
||||
if (has_snapshots) {
|
||||
fs.cpSync(snapshots_dir, kept_snapshots, {
|
||||
recursive: true,
|
||||
force: true,
|
||||
});
|
||||
}
|
||||
|
||||
// Everything goes, the snapshots included (put back below). A
|
||||
// computer's folders stay, live and unarchived.
|
||||
for (const entry of fs.readdirSync(DATA_DIR)) {
|
||||
if (entry == AppData.ComputerDataDir) continue;
|
||||
|
||||
fs.rmSync(path.join(DATA_DIR, entry), {
|
||||
recursive: true,
|
||||
force: true,
|
||||
@@ -128,6 +151,8 @@ export default async function restoreDataBackup({
|
||||
}
|
||||
|
||||
for (const entry of fs.readdirSync(source_dir)) {
|
||||
if (entry == AppData.ComputerDataDir) continue;
|
||||
|
||||
fs.cpSync(
|
||||
path.join(source_dir, entry),
|
||||
path.join(DATA_DIR, entry),
|
||||
@@ -135,6 +160,14 @@ export default async function restoreDataBackup({
|
||||
);
|
||||
}
|
||||
|
||||
if (has_snapshots) {
|
||||
fs.mkdirSync(path.join(DATA_DIR, "db"), { recursive: true });
|
||||
fs.cpSync(kept_snapshots, snapshots_dir, {
|
||||
recursive: true,
|
||||
force: true,
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
safety_name: safety.name,
|
||||
restored_name: archive_name,
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
import { afterEach, describe, expect, test } from "bun:test";
|
||||
import fs from "fs";
|
||||
import os from "os";
|
||||
import path from "path";
|
||||
import writeDataBackupArchive from "./write-data-backup-archive";
|
||||
|
||||
const dirs: string[] = [];
|
||||
const previous = {
|
||||
DATA_DIR: process.env.DATA_DIR,
|
||||
BACKUP_ARCHIVE_DIR: process.env.BACKUP_ARCHIVE_DIR,
|
||||
};
|
||||
|
||||
function makeRoot() {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "cobble-archive-"));
|
||||
|
||||
dirs.push(dir);
|
||||
|
||||
return dir;
|
||||
}
|
||||
|
||||
function write({ root, relative, content = "x" }: { root: string; relative: string; content?: string }) {
|
||||
const target = path.join(root, relative);
|
||||
|
||||
fs.mkdirSync(path.dirname(target), { recursive: true });
|
||||
fs.writeFileSync(target, content);
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
for (const dir of dirs.splice(0)) {
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
|
||||
for (const [key, value] of Object.entries(previous)) {
|
||||
if (value === undefined) delete process.env[key];
|
||||
else process.env[key] = value;
|
||||
}
|
||||
});
|
||||
|
||||
describe("writeDataBackupArchive", () => {
|
||||
test("tars the install's data and leaves out what is rebuilt or kept elsewhere", async () => {
|
||||
const data_dir = makeRoot();
|
||||
const archive_dir = makeRoot();
|
||||
|
||||
process.env.DATA_DIR = data_dir;
|
||||
process.env.BACKUP_ARCHIVE_DIR = archive_dir;
|
||||
|
||||
write({ root: data_dir, relative: "db/cobble" });
|
||||
write({ root: data_dir, relative: "db/.backups/cobble-1" });
|
||||
write({ root: data_dir, relative: ".bun-sqlite/.tmp/temp.db" });
|
||||
write({ root: data_dir, relative: "computers/1/bots/3/users/1/work.txt" });
|
||||
write({ root: data_dir, relative: "computers/1/bots/3/users/1/node_modules/pkg/index.js" });
|
||||
write({ root: data_dir, relative: "computer-browsers/1/Default/Cookies" });
|
||||
write({ root: data_dir, relative: "computer-browsers/1/Default/Code Cache/js" });
|
||||
write({ root: data_dir, relative: "bots/1/report.md" });
|
||||
write({ root: data_dir, relative: "media/1/picture.png" });
|
||||
|
||||
const created = await writeDataBackupArchive();
|
||||
const list = Bun.spawnSync(["tar", "-tzf", created.path]);
|
||||
const members = new TextDecoder().decode(list.stdout).split("\n").filter(Boolean);
|
||||
const root = created.name.replace(/\.tar\.gz$/, "");
|
||||
|
||||
/**
|
||||
* Every member sits under one folder named after the archive, so
|
||||
* an extract lands one folder.
|
||||
*/
|
||||
expect(members.every((member) => member.startsWith(`${root}/`))).toBe(true);
|
||||
|
||||
for (const kept of [
|
||||
`${root}/db/cobble`,
|
||||
`${root}/bots/1/report.md`,
|
||||
`${root}/media/1/picture.png`,
|
||||
`${root}/computer-browsers/1/Default/Cookies`,
|
||||
]) {
|
||||
expect(members).toContain(kept);
|
||||
}
|
||||
|
||||
for (const left_out of [
|
||||
`${root}/computers`,
|
||||
`${root}/db/.backups`,
|
||||
`${root}/.bun-sqlite`,
|
||||
`${root}/computer-browsers/1/Default/Code Cache`,
|
||||
]) {
|
||||
expect(members.some((member) => member == left_out || member.startsWith(`${left_out}/`))).toBe(false);
|
||||
}
|
||||
});
|
||||
|
||||
test("keeps only the newest archives", async () => {
|
||||
const data_dir = makeRoot();
|
||||
const archive_dir = makeRoot();
|
||||
|
||||
process.env.DATA_DIR = data_dir;
|
||||
process.env.BACKUP_ARCHIVE_DIR = archive_dir;
|
||||
|
||||
write({ root: data_dir, relative: "db/cobble" });
|
||||
write({ root: archive_dir, relative: "cobble-data-1.tar.gz" });
|
||||
|
||||
const created = await writeDataBackupArchive();
|
||||
|
||||
expect(fs.existsSync(created.path)).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -1,9 +1,11 @@
|
||||
import fs from "fs";
|
||||
import os from "os";
|
||||
import path from "path";
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
import grabDirNames from "@/src/utils/grab-dir-names";
|
||||
import grabBackupArchiveDir from "@/src/utils/grab-backup-archive-dir";
|
||||
import grabDataBackups from "./grab-data-backups";
|
||||
import listArchiveExclusions from "./list-archive-exclusions";
|
||||
|
||||
export type CreatedDataBackup = {
|
||||
name: string;
|
||||
@@ -11,13 +13,20 @@ export type CreatedDataBackup = {
|
||||
};
|
||||
|
||||
/**
|
||||
* Writes one archive of the whole `DATA_DIR` (database, media, computer
|
||||
* workspaces, bot and workspace files, MCP installs) into
|
||||
* `BACKUP_ARCHIVE_DIR` and keeps only the newest `AppData.DataBackupsKept`.
|
||||
* Every entry sits under one root folder named after the archive, so
|
||||
* extracting it lands one folder. The SQLite file inside is only as
|
||||
* consistent as the moment tar read it; `db/.backups` is for consistent
|
||||
* snapshots.
|
||||
* Writes one archive of the install's data (`DATA_DIR`: database, media,
|
||||
* bot and workspace files, MCP installs, Chrome profiles) into
|
||||
* `BACKUP_ARCHIVE_DIR` and keeps only the newest
|
||||
* `AppData.DataBackupsKept`. Every entry sits under one root folder named
|
||||
* after the archive, so extracting it lands one folder. The SQLite file
|
||||
* inside is only as consistent as the moment tar read it; `db/.backups` is
|
||||
* for consistent snapshots.
|
||||
*
|
||||
* It leaves out what is rebuilt on demand or kept elsewhere
|
||||
* (`listArchiveExclusions`): a computer's own folders, Chrome profile
|
||||
* caches, the database snapshots and bun-sqlite's scratch space. Without
|
||||
* that, an install's 178 MB of bot files came with 2457 MB of computer
|
||||
* workspaces and 993 MB of browser caches, and every archive carried it
|
||||
* again.
|
||||
*
|
||||
* It takes no lock: callers run inside `startDataBackupRun`, which holds
|
||||
* the backup run lock (`withBackupRunLock`) for the whole run, so the
|
||||
@@ -30,8 +39,14 @@ export default async function writeDataBackupArchive(): Promise<CreatedDataBacku
|
||||
const archive_root = archive_name.replace(/\.tar\.gz$/, "");
|
||||
const archive_path = path.join(archive_dir, archive_name);
|
||||
const part_path = `${archive_path}.part`;
|
||||
const excl_dir = fs.mkdtempSync(path.join(os.tmpdir(), "cobble-archive-"));
|
||||
const excl_path = path.join(excl_dir, "exclude.txt");
|
||||
|
||||
try {
|
||||
const exclusions = await listArchiveExclusions({ data_dir: DATA_DIR });
|
||||
|
||||
fs.writeFileSync(excl_path, exclusions.map((line) => `${line}\n`).join(""));
|
||||
|
||||
const proc = Bun.spawn(
|
||||
[
|
||||
"tar",
|
||||
@@ -45,13 +60,12 @@ export default async function writeDataBackupArchive(): Promise<CreatedDataBacku
|
||||
// after it and an extract drops a single folder.
|
||||
"--transform",
|
||||
`s,^\\.$,${archive_root},;s,^\\./,${archive_root}/,`,
|
||||
// A computer's old whole home, moved aside when only its
|
||||
// workspace became the mount (`prepareComputerDataDir`),
|
||||
// is kept on disk but never archived: only workspaces are.
|
||||
// `*` stops at `/`, so a file inside a workspace whose name
|
||||
// happens to hold the suffix is still archived.
|
||||
"--no-wildcards-match-slash",
|
||||
`--exclude=./${AppData.ComputerDataDir}/*${AppData.ComputerOldHomeSuffix}*`,
|
||||
// The exclusions are exact member paths
|
||||
// (`listArchiveExclusions`), never patterns: a folder a
|
||||
// bot named `node_modules!` or `Cache*` must not take a
|
||||
// real one with it.
|
||||
"--no-wildcards",
|
||||
`--exclude-from=${excl_path}`,
|
||||
"-C",
|
||||
DATA_DIR,
|
||||
".",
|
||||
@@ -86,6 +100,8 @@ export default async function writeDataBackupArchive(): Promise<CreatedDataBacku
|
||||
if (fs.existsSync(part_path)) {
|
||||
fs.rmSync(part_path, { force: true });
|
||||
}
|
||||
|
||||
fs.rmSync(excl_dir, { recursive: true, force: true });
|
||||
}
|
||||
|
||||
const old = grabDataBackups().slice(AppData.DataBackupsKept);
|
||||
@@ -98,4 +114,4 @@ export default async function writeDataBackupArchive(): Promise<CreatedDataBacku
|
||||
name: archive_name,
|
||||
path: archive_path,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
import type { ComputerApi } from "./computer-fetch";
|
||||
import computerJson from "./computer-json";
|
||||
|
||||
type Params = {
|
||||
computer: ComputerApi;
|
||||
signal?: AbortSignal;
|
||||
};
|
||||
|
||||
export type ComputerUsage = {
|
||||
/**
|
||||
* How much the whole workspace holds, every bot's and user's folder
|
||||
* included.
|
||||
*/
|
||||
used_bytes: number;
|
||||
/**
|
||||
* Where it is on the computer, for messages.
|
||||
*/
|
||||
workspace_dir: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* What a computer's workspace holds (`GET /api/usage` on its agent). The
|
||||
* agent measures with `du` and reuses the answer for a few seconds, so
|
||||
* asking before each write costs little.
|
||||
*/
|
||||
export default function grabComputerUsage({ computer, signal }: Params) {
|
||||
return computerJson<ComputerUsage>({ computer, path: "/api/usage", timeout_ms: 30_000, signal });
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
import { afterEach, describe, expect, test } from "bun:test";
|
||||
import fs from "fs";
|
||||
import os from "os";
|
||||
import path from "path";
|
||||
import pruneComputerCacheFolders from "./prune-computer-cache-folders";
|
||||
|
||||
const dirs: string[] = [];
|
||||
|
||||
function makeRoot() {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "cobble-prune-"));
|
||||
|
||||
dirs.push(dir);
|
||||
|
||||
return dir;
|
||||
}
|
||||
|
||||
function write({ root, relative, content = "x" }: { root: string; relative: string; content?: string }) {
|
||||
const target = path.join(root, relative);
|
||||
|
||||
fs.mkdirSync(path.dirname(target), { recursive: true });
|
||||
fs.writeFileSync(target, content);
|
||||
}
|
||||
|
||||
function has({ root, relative }: { root: string; relative: string }) {
|
||||
return fs.existsSync(path.join(root, relative));
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
for (const dir of dirs.splice(0)) {
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
describe("pruneComputerCacheFolders", () => {
|
||||
test("clears caches, bytecode and a bot's own browser profile's caches, and nothing else", async () => {
|
||||
const computer_dir = makeRoot();
|
||||
const profile_dir = makeRoot();
|
||||
|
||||
write({ root: computer_dir, relative: "bots/3/keep.md" });
|
||||
write({ root: computer_dir, relative: "bots/3/.cache/pip/wheel" });
|
||||
write({ root: computer_dir, relative: "bots/3/.npm/_cacache/index" });
|
||||
write({ root: computer_dir, relative: "bots/3/.npm/_logs/debug.log" });
|
||||
write({ root: computer_dir, relative: "bots/3/.npm/package.json" });
|
||||
write({ root: computer_dir, relative: "bots/3/.bun/install/cache/dep" });
|
||||
write({ root: computer_dir, relative: "bots/3/.bun/bin/tool" });
|
||||
write({ root: computer_dir, relative: "bots/3/project/node_modules/pkg/index.js" });
|
||||
write({ root: computer_dir, relative: "bots/3/project/__pycache__/main.pyc" });
|
||||
write({ root: computer_dir, relative: "bots/3/project/main.py" });
|
||||
write({ root: computer_dir, relative: "bots/3/.cobble-browser/Default/Cache/data" });
|
||||
write({ root: computer_dir, relative: "bots/3/.cobble-browser/Default/Cookies" });
|
||||
write({ root: computer_dir, relative: "bots/3/users/1/work.txt" });
|
||||
write({ root: computer_dir, relative: "bots/3/users/1/.cache/chromium/data" });
|
||||
write({ root: computer_dir, relative: "workspaces/2/designs/a.png" });
|
||||
write({ root: computer_dir, relative: "workspaces/2/.cache/pip/wheel" });
|
||||
|
||||
write({ root: profile_dir, relative: "Default/Cache/data" });
|
||||
write({ root: profile_dir, relative: "Default/Code Cache/js" });
|
||||
write({ root: profile_dir, relative: "GPUCache/data" });
|
||||
write({ root: profile_dir, relative: "Default/Cookies" });
|
||||
write({ root: profile_dir, relative: "Default/Preferences" });
|
||||
write({ root: profile_dir, relative: "SingletonLock" });
|
||||
|
||||
const pruned = await pruneComputerCacheFolders({ computer_dir, profile_dir });
|
||||
const in_computer = pruned.filter((entry) => entry.dir.startsWith(`${computer_dir}/`));
|
||||
const in_profile = pruned.filter((entry) => entry.dir.startsWith(`${profile_dir}/`));
|
||||
|
||||
expect(in_computer.map((entry) => path.relative(computer_dir, entry.dir)).sort()).toEqual([
|
||||
"bots/3/.bun/install/cache",
|
||||
"bots/3/.cache",
|
||||
"bots/3/.cobble-browser/Default/Cache",
|
||||
"bots/3/.npm/_cacache",
|
||||
"bots/3/.npm/_logs",
|
||||
"bots/3/project/__pycache__",
|
||||
"bots/3/users/1/.cache",
|
||||
"workspaces/2/.cache",
|
||||
]);
|
||||
|
||||
expect(in_profile.map((entry) => path.relative(profile_dir, entry.dir)).sort()).toEqual([
|
||||
"Default/Cache",
|
||||
"Default/Code Cache",
|
||||
"GPUCache",
|
||||
]);
|
||||
|
||||
/**
|
||||
* The caches and bytecode go.
|
||||
*/
|
||||
for (const gone of [
|
||||
"bots/3/.cache",
|
||||
"bots/3/.npm/_cacache",
|
||||
"bots/3/.npm/_logs",
|
||||
"bots/3/.bun/install/cache",
|
||||
"bots/3/project/__pycache__",
|
||||
"bots/3/.cobble-browser/Default/Cache",
|
||||
"bots/3/users/1/.cache",
|
||||
"workspaces/2/.cache",
|
||||
]) {
|
||||
expect(has({ root: computer_dir, relative: gone })).toBe(false);
|
||||
}
|
||||
|
||||
/**
|
||||
* Work and installs stay: a run still needs its packages, and the
|
||||
* profile its logins.
|
||||
*/
|
||||
for (const kept of [
|
||||
"bots/3/keep.md",
|
||||
"bots/3/.npm/package.json",
|
||||
"bots/3/.bun/bin/tool",
|
||||
"bots/3/project/node_modules/pkg/index.js",
|
||||
"bots/3/project/main.py",
|
||||
"bots/3/.cobble-browser/Default/Cookies",
|
||||
"bots/3/users/1/work.txt",
|
||||
"workspaces/2/designs/a.png",
|
||||
]) {
|
||||
expect(has({ root: computer_dir, relative: kept })).toBe(true);
|
||||
}
|
||||
|
||||
expect(has({ root: profile_dir, relative: "Default/Cache" })).toBe(false);
|
||||
expect(has({ root: profile_dir, relative: "Default/Code Cache" })).toBe(false);
|
||||
expect(has({ root: profile_dir, relative: "GPUCache" })).toBe(false);
|
||||
expect(has({ root: profile_dir, relative: "Default/Cookies" })).toBe(true);
|
||||
expect(has({ root: profile_dir, relative: "Default/Preferences" })).toBe(true);
|
||||
expect(has({ root: profile_dir, relative: "SingletonLock" })).toBe(true);
|
||||
});
|
||||
|
||||
test("counts what it freed", async () => {
|
||||
const computer_dir = makeRoot();
|
||||
const profile_dir = makeRoot();
|
||||
|
||||
write({ root: profile_dir, relative: "Default/Cache/data", content: "1234567890" });
|
||||
|
||||
const pruned = await pruneComputerCacheFolders({ computer_dir, profile_dir });
|
||||
|
||||
expect(pruned).toHaveLength(1);
|
||||
expect(pruned[0]?.bytes).toBe(10);
|
||||
});
|
||||
|
||||
test("a folder with no caches in it is untouched", async () => {
|
||||
const computer_dir = makeRoot();
|
||||
const profile_dir = makeRoot();
|
||||
|
||||
write({ root: computer_dir, relative: "bots/3/report.md" });
|
||||
|
||||
expect(await pruneComputerCacheFolders({ computer_dir, profile_dir })).toEqual([]);
|
||||
expect(has({ root: computer_dir, relative: "bots/3/report.md" })).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,161 @@
|
||||
import fs from "fs/promises";
|
||||
import path from "path";
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
import {
|
||||
BrowserProfileCacheDirs,
|
||||
ComputerBytecodeCacheDir,
|
||||
ComputerRunBrowserProfileDir,
|
||||
ComputerRunCacheEntries,
|
||||
} from "@/src/data/computer-cache-paths";
|
||||
|
||||
export type PrunedCacheFolder = {
|
||||
dir: string;
|
||||
bytes: number;
|
||||
};
|
||||
|
||||
type Params = {
|
||||
/**
|
||||
* One computer's folders: `DATA_DIR/computers/<id>`.
|
||||
*/
|
||||
computer_dir: string;
|
||||
/**
|
||||
* Its browser profile: `DATA_DIR/computer-browsers/<id>`.
|
||||
*/
|
||||
profile_dir: string;
|
||||
};
|
||||
|
||||
const ProfileCacheNames = new Set<string>(BrowserProfileCacheDirs);
|
||||
|
||||
/**
|
||||
* Clears the caches in one computer's folders and browser profile
|
||||
* (`data/computer-cache-paths.ts` explains each list): what pip, npm and
|
||||
* bun write beside a run's work, Python's `__pycache__` anywhere below it,
|
||||
* a profile a bot started itself, and every Chrome profile cache. Never a
|
||||
* bot's work and never an install: `node_modules`, `~/.local` and `~/.pi`
|
||||
* stay, a run would otherwise lose its packages.
|
||||
*
|
||||
* Called only while nothing works on the computer (`pruneComputerCaches`
|
||||
* checks), so no run has a cache folder open.
|
||||
*/
|
||||
export default async function pruneComputerCacheFolders({
|
||||
computer_dir,
|
||||
profile_dir,
|
||||
}: Params): Promise<PrunedCacheFolder[]> {
|
||||
const pruned: PrunedCacheFolder[] = [];
|
||||
|
||||
for (const bot of await readDirectories(path.join(computer_dir, AppData.BotDataDir))) {
|
||||
const bot_dir = path.join(computer_dir, AppData.BotDataDir, bot.name);
|
||||
|
||||
await pruneRunFolder({ dir: bot_dir, pruned });
|
||||
|
||||
for (const user of await readDirectories(path.join(bot_dir, "users"))) {
|
||||
await pruneRunFolder({ dir: path.join(bot_dir, "users", user.name), pruned });
|
||||
}
|
||||
}
|
||||
|
||||
for (const workspace of await readDirectories(path.join(computer_dir, AppData.WorkspaceDataDir))) {
|
||||
await pruneRunFolder({
|
||||
dir: path.join(computer_dir, AppData.WorkspaceDataDir, workspace.name),
|
||||
pruned,
|
||||
});
|
||||
}
|
||||
|
||||
await pruneBrowserProfile({ dir: profile_dir, pruned });
|
||||
|
||||
return pruned;
|
||||
}
|
||||
|
||||
/**
|
||||
* One folder a run works in: its caches, and the caches made anywhere
|
||||
* below it.
|
||||
*/
|
||||
async function pruneRunFolder({ dir, pruned }: { dir: string; pruned: PrunedCacheFolder[] }) {
|
||||
for (const entry of ComputerRunCacheEntries) {
|
||||
await remove({ target: path.join(dir, entry), pruned });
|
||||
}
|
||||
|
||||
await pruneNestedCaches({ dir, pruned });
|
||||
}
|
||||
|
||||
async function pruneNestedCaches({ dir, pruned }: { dir: string; pruned: PrunedCacheFolder[] }) {
|
||||
for (const entry of await readDirectories(dir)) {
|
||||
const target = path.join(dir, entry.name);
|
||||
|
||||
if (entry.name == ComputerBytecodeCacheDir) {
|
||||
await remove({ target, pruned });
|
||||
continue;
|
||||
}
|
||||
|
||||
if (entry.name == ComputerRunBrowserProfileDir) {
|
||||
await pruneBrowserProfile({ dir: target, pruned });
|
||||
continue;
|
||||
}
|
||||
|
||||
await pruneNestedCaches({ dir: target, pruned });
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A Chrome profile's caches, at its root and inside its `Default` (or
|
||||
* `Profile N`) folder. Cookies, logins, preferences and extensions stay.
|
||||
*/
|
||||
async function pruneBrowserProfile({ dir, pruned }: { dir: string; pruned: PrunedCacheFolder[] }) {
|
||||
for (const entry of await readEntries(dir)) {
|
||||
const target = path.join(dir, entry.name);
|
||||
|
||||
if (ProfileCacheNames.has(entry.name)) {
|
||||
await remove({ target, pruned });
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!entry.isDirectory()) continue;
|
||||
|
||||
for (const inner of await readEntries(target)) {
|
||||
if (ProfileCacheNames.has(inner.name)) {
|
||||
await remove({ target: path.join(target, inner.name), pruned });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes a folder (or a file) and notes how much it held. A missing one
|
||||
* is nothing to do.
|
||||
*/
|
||||
async function remove({ target, pruned }: { target: string; pruned: PrunedCacheFolder[] }) {
|
||||
const stats = await fs.lstat(target).catch(() => null);
|
||||
|
||||
if (!stats) return;
|
||||
|
||||
const bytes = stats.isDirectory() ? await folderBytes({ dir: target }) : stats.size;
|
||||
|
||||
await fs.rm(target, { recursive: true, force: true }).catch(() => {});
|
||||
|
||||
pruned.push({ dir: target, bytes });
|
||||
}
|
||||
|
||||
async function folderBytes({ dir }: { dir: string }): Promise<number> {
|
||||
let total = 0;
|
||||
|
||||
for (const entry of await readEntries(dir)) {
|
||||
const target = path.join(dir, entry.name);
|
||||
|
||||
if (entry.isDirectory()) total += await folderBytes({ dir: target });
|
||||
else if (entry.isFile()) total += (await fs.stat(target).catch(() => null))?.size || 0;
|
||||
}
|
||||
|
||||
return total;
|
||||
}
|
||||
|
||||
async function readDirectories(dir: string) {
|
||||
return (await readEntries(dir)).filter((entry) => entry.isDirectory());
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads a folder's entries without following a symlink (`withFileTypes`
|
||||
* reports the link itself), so a bot's link elsewhere is never walked or
|
||||
* deleted through.
|
||||
*/
|
||||
async function readEntries(dir: string) {
|
||||
return await fs.readdir(dir, { withFileTypes: true }).catch(() => []);
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
import fs from "fs/promises";
|
||||
import path from "path";
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
import grabDirNames from "@/src/utils/grab-dir-names";
|
||||
import countComputerTaskJobs from "../db/bots-queue/count-computer-task-jobs";
|
||||
import pruneComputerCacheFolders, { type PrunedCacheFolder } from "./prune-computer-cache-folders";
|
||||
|
||||
/**
|
||||
* Clears every computer's disposable caches (`pruneComputerCacheFolders`):
|
||||
* the ones pip, npm and bun write beside a run's work, Python's bytecode,
|
||||
* and every Chrome profile's caches.
|
||||
*
|
||||
* A computer's folders sit on the data volume, so this is what keeps them
|
||||
* from growing with what a bot's tools left behind: one install held 2.4 GB
|
||||
* there against 178 MB of bot files. A computer with a task queued or
|
||||
* running is skipped: it may be installing into one of those caches right
|
||||
* now. Ids that aren't a computer's own folder (`prune-computer-homes`'
|
||||
* moved-aside homes) are left alone.
|
||||
*/
|
||||
export default async function pruneComputerCaches(): Promise<PrunedCacheFolder[]> {
|
||||
const { DATA_DIR } = grabDirNames();
|
||||
const computers_dir = path.join(DATA_DIR, AppData.ComputerDataDir);
|
||||
const profiles_dir = path.join(DATA_DIR, AppData.ComputerBrowserDataDir);
|
||||
const pruned: PrunedCacheFolder[] = [];
|
||||
|
||||
for (const entry of await readDirectories(computers_dir)) {
|
||||
if (!/^\d+$/.test(entry.name)) continue;
|
||||
|
||||
const busy = await countComputerTaskJobs({ computer_id: Number(entry.name) });
|
||||
|
||||
if (busy > 0) continue;
|
||||
|
||||
pruned.push(
|
||||
...(await pruneComputerCacheFolders({
|
||||
computer_dir: path.join(computers_dir, entry.name),
|
||||
profile_dir: path.join(profiles_dir, entry.name),
|
||||
})),
|
||||
);
|
||||
}
|
||||
|
||||
return pruned;
|
||||
}
|
||||
|
||||
async function readDirectories(dir: string) {
|
||||
return (await readEntries(dir)).filter((entry) => entry.isDirectory());
|
||||
}
|
||||
|
||||
async function readEntries(dir: string) {
|
||||
return await fs.readdir(dir, { withFileTypes: true }).catch(() => []);
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
import { computerWorkspaceQuotaMb } from "./grab-computer-workspace-quota-bytes";
|
||||
|
||||
/**
|
||||
* An install that never touched the setting gets the code's default, while
|
||||
* one that saved 0 asked for no limit: reading the two alike either caps
|
||||
* every computer at a limit nobody set, or leaves them all uncapped.
|
||||
*/
|
||||
describe("computerWorkspaceQuotaMb", () => {
|
||||
test("never saved means the default", () => {
|
||||
expect(computerWorkspaceQuotaMb({ saved: undefined })).toBe(AppData.ComputerWorkspaceQuotaMb);
|
||||
expect(computerWorkspaceQuotaMb({ saved: null })).toBe(AppData.ComputerWorkspaceQuotaMb);
|
||||
expect(computerWorkspaceQuotaMb({ saved: " " })).toBe(AppData.ComputerWorkspaceQuotaMb);
|
||||
});
|
||||
|
||||
test("saved 0 means no limit", () => {
|
||||
expect(computerWorkspaceQuotaMb({ saved: "0" })).toBe(0);
|
||||
});
|
||||
|
||||
test("a saved number is the limit", () => {
|
||||
expect(computerWorkspaceQuotaMb({ saved: "20480" })).toBe(20480);
|
||||
expect(computerWorkspaceQuotaMb({ saved: "512.5" })).toBe(512.5);
|
||||
});
|
||||
|
||||
test("something that isn't a number is the default, and a negative is no limit", () => {
|
||||
expect(computerWorkspaceQuotaMb({ saved: "lots" })).toBe(AppData.ComputerWorkspaceQuotaMb);
|
||||
expect(computerWorkspaceQuotaMb({ saved: "-1" })).toBe(0);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,36 @@
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
import { ComputerWorkspaceQuotaSettingKey } from "@/src/dict/computer-dict";
|
||||
import grabAppSetting from "../app-settings/grab-app-setting";
|
||||
|
||||
/**
|
||||
* The MB a saved setting means. Never saved, or saved as something that
|
||||
* isn't a number, is the code's default; a saved `0` is the install saying
|
||||
* it sets no limit, which is why the two can't be read alike.
|
||||
*/
|
||||
export function computerWorkspaceQuotaMb({ saved }: { saved?: string | null }) {
|
||||
if (saved == undefined || String(saved).trim() == "") return AppData.ComputerWorkspaceQuotaMb;
|
||||
|
||||
const mb = Number(saved);
|
||||
|
||||
if (!Number.isFinite(mb)) return AppData.ComputerWorkspaceQuotaMb;
|
||||
|
||||
return Math.max(0, mb);
|
||||
}
|
||||
|
||||
/**
|
||||
* The most a computer's workspace may hold, from the General settings
|
||||
* (`computer_workspace_quota_mb`), else `AppData.ComputerWorkspaceQuotaMb`.
|
||||
* 0 means the install sets no limit.
|
||||
*/
|
||||
export default async function grabComputerWorkspaceQuotaBytes() {
|
||||
const saved = await grabAppSetting({ key: ComputerWorkspaceQuotaSettingKey });
|
||||
|
||||
return Math.round(computerWorkspaceQuotaMb({ saved }) * 1024 * 1024);
|
||||
}
|
||||
|
||||
/**
|
||||
* The same limit in MB, for the settings page.
|
||||
*/
|
||||
export async function grabComputerWorkspaceQuotaMb() {
|
||||
return computerWorkspaceQuotaMb({ saved: await grabAppSetting({ key: ComputerWorkspaceQuotaSettingKey }) });
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import { ComputerWorkspaceQuotaSettingKey } from "@/src/dict/computer-dict";
|
||||
import { grabComputerWorkspaceQuotaMb } from "./grab-computer-workspace-quota-bytes";
|
||||
|
||||
/**
|
||||
* The General settings' computer workspace limit: how much one computer's
|
||||
* workspace may hold. Only the limit, not what each computer holds now: a
|
||||
* live size is one request per computer, so the computers' own pages show
|
||||
* theirs instead.
|
||||
*/
|
||||
export default async function grabComputerWorkspaceQuotaOverview() {
|
||||
return {
|
||||
setting_key: ComputerWorkspaceQuotaSettingKey,
|
||||
quota_mb: await grabComputerWorkspaceQuotaMb(),
|
||||
};
|
||||
}
|
||||
|
||||
export type ComputerWorkspaceQuotaOverview = Awaited<
|
||||
ReturnType<typeof grabComputerWorkspaceQuotaOverview>
|
||||
>;
|
||||
@@ -1,4 +1,5 @@
|
||||
import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
import deleteUnlinkedAttachmentMedia from "../media/delete-unlinked-attachment-media";
|
||||
|
||||
type Params = {
|
||||
/**
|
||||
@@ -33,7 +34,18 @@ export default async function deleteHookSessionRows({ hook_id }: Params) {
|
||||
await BunSQLite.sql({ sql: `DELETE FROM bots_queue WHERE session_id IN (${list})` });
|
||||
await BunSQLite.sql({ sql: `DELETE FROM bot_tasks WHERE session_id IN (${list})` });
|
||||
await BunSQLite.sql({ sql: `DELETE FROM bot_message_reactions WHERE message_id IN (${messages})` });
|
||||
|
||||
/**
|
||||
* An upload's bytes are its `media` row, which the message's link was
|
||||
* the only way to reach.
|
||||
*/
|
||||
const uploads = await BunSQLite.sql<{ media_id: number }>({
|
||||
sql: `SELECT media_id FROM bot_message_media WHERE message_id IN (${messages})`,
|
||||
});
|
||||
|
||||
await BunSQLite.sql({ sql: `DELETE FROM bot_message_media WHERE message_id IN (${messages})` });
|
||||
|
||||
await deleteUnlinkedAttachmentMedia({ media_ids: (uploads.payload || []).map((row) => Number(row.media_id)) }).catch(() => []);
|
||||
await BunSQLite.sql({ sql: `DELETE FROM bot_messages WHERE session_id IN (${list})` });
|
||||
await BunSQLite.sql({ sql: `DELETE FROM bot_sessions WHERE id IN (${list})` });
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
import deleteUnlinkedAttachmentMedia from "../media/delete-unlinked-attachment-media";
|
||||
|
||||
type Params = {
|
||||
/**
|
||||
@@ -31,9 +32,21 @@ export default async function deleteChatroomRows({ rooms }: Params) {
|
||||
await BunSQLite.sql({
|
||||
sql: `DELETE FROM bot_message_reactions WHERE message_id IN (SELECT id FROM bot_messages WHERE session_id IN (${sessions}))`,
|
||||
});
|
||||
|
||||
/**
|
||||
* An upload's bytes are its `media` row, which the message's link was
|
||||
* the only way to reach: without this the room's files would stay on
|
||||
* the data volume forever.
|
||||
*/
|
||||
const uploads = await BunSQLite.sql<{ media_id: number }>({
|
||||
sql: `SELECT media_id FROM bot_message_media WHERE message_id IN (SELECT id FROM bot_messages WHERE session_id IN (${sessions}))`,
|
||||
});
|
||||
|
||||
await BunSQLite.sql({
|
||||
sql: `DELETE FROM bot_message_media WHERE message_id IN (SELECT id FROM bot_messages WHERE session_id IN (${sessions}))`,
|
||||
});
|
||||
|
||||
await deleteUnlinkedAttachmentMedia({ media_ids: (uploads.payload || []).map((row) => Number(row.media_id)) }).catch(() => []);
|
||||
await BunSQLite.sql({ sql: `DELETE FROM bot_messages WHERE session_id IN (${sessions})` });
|
||||
await BunSQLite.sql({ sql: `DELETE FROM bot_sessions WHERE chatroom_id IN (${list})` });
|
||||
await BunSQLite.sql({ sql: `DELETE FROM chatrooms WHERE id IN (${list})` });
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import oldComputerHomeName from "./old-computer-home-name";
|
||||
|
||||
describe("oldComputerHomeName", () => {
|
||||
test("reads both names prepareComputerDataDir makes", () => {
|
||||
expect(oldComputerHomeName({ name: "4-home-1700000000000" })).toBe(1700000000000);
|
||||
expect(oldComputerHomeName({ name: "4-1700000000000" })).toBe(1700000000000);
|
||||
});
|
||||
|
||||
test("ignores a live computer's own folder", () => {
|
||||
expect(oldComputerHomeName({ name: "4" })).toBeNull();
|
||||
expect(oldComputerHomeName({ name: "12" })).toBeNull();
|
||||
});
|
||||
|
||||
test("ignores a file that only looks similar", () => {
|
||||
expect(oldComputerHomeName({ name: "4-home-1700000000000-workspace" })).toBeNull();
|
||||
expect(oldComputerHomeName({ name: "bots" })).toBeNull();
|
||||
expect(oldComputerHomeName({ name: "4-home-x" })).toBeNull();
|
||||
expect(oldComputerHomeName({ name: "x-1700000000000" })).toBeNull();
|
||||
expect(oldComputerHomeName({ name: "1700000000000-workspace" })).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,30 @@
|
||||
/**
|
||||
* A folder `prepareComputerDataDir` moved aside:
|
||||
* `<id><ComputerOldHomeSuffix><timestamp>` for a computer's home from
|
||||
* before only its workspace was mounted, or `<id>-<timestamp>` when a new
|
||||
* computer took a deleted one's id. The suffix decides which is which, so
|
||||
* it is read from `AppData.ComputerOldHomeSuffix` rather than written out.
|
||||
*/
|
||||
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
|
||||
const stem = AppData.ComputerOldHomeSuffix.replace(/-$/, "").replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
||||
|
||||
const OldHomeName = new RegExp(`^\\d+(?:${stem})?-\\d+$`);
|
||||
|
||||
type Params = {
|
||||
name: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* The timestamp a moved-aside folder's name holds, or null when the name
|
||||
* isn't one of them. Nothing is mounted from such a folder, so a name this
|
||||
* recognises is a folder nothing can read again.
|
||||
*/
|
||||
export default function oldComputerHomeName({ name }: Params) {
|
||||
if (!OldHomeName.test(name)) return null;
|
||||
|
||||
const stamp = Number(name.slice(name.lastIndexOf("-") + 1));
|
||||
|
||||
return Number.isFinite(stamp) && stamp > 0 ? stamp : null;
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
import { afterEach, describe, expect, test } from "bun:test";
|
||||
import { mkdirSync, mkdtempSync, readdirSync, rmSync, utimesSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
import pruneComputerHomes from "./prune-computer-homes";
|
||||
|
||||
/**
|
||||
* These folders are never archived and nothing mounts them, so this is the
|
||||
* only thing that ever removes them: too eager loses a computer's old home
|
||||
* before anyone looked, too shy fills the data volume for good.
|
||||
*/
|
||||
const DayMs = 24 * 60 * 60 * 1000;
|
||||
const Old = Date.now() - (AppData.ComputerOldHomeKeepDays + 5) * DayMs;
|
||||
const New = Date.now() - DayMs;
|
||||
|
||||
const roots: string[] = [];
|
||||
const previous_data_dir = process.env.DATA_DIR;
|
||||
|
||||
function setup({ folders }: { folders: { name: string; stamp: number; touched: number }[] }) {
|
||||
const data_dir = mkdtempSync(path.join(tmpdir(), "cobble-homes-"));
|
||||
|
||||
roots.push(data_dir);
|
||||
process.env.DATA_DIR = data_dir;
|
||||
|
||||
const computers = path.join(data_dir, AppData.ComputerDataDir);
|
||||
|
||||
mkdirSync(computers, { recursive: true });
|
||||
|
||||
for (const folder of folders) {
|
||||
const target = path.join(computers, folder.name);
|
||||
|
||||
mkdirSync(target, { recursive: true });
|
||||
writeFileSync(path.join(target, "keep.txt"), "x");
|
||||
utimesSync(target, new Date(folder.touched), new Date(folder.touched));
|
||||
}
|
||||
|
||||
return { data_dir, computers };
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true });
|
||||
|
||||
if (previous_data_dir == undefined) delete process.env.DATA_DIR;
|
||||
else process.env.DATA_DIR = previous_data_dir;
|
||||
});
|
||||
|
||||
describe("pruneComputerHomes", () => {
|
||||
test("takes the folders moved aside long ago, keeps everything else", async () => {
|
||||
const { computers } = setup({
|
||||
folders: [
|
||||
{ name: "1", stamp: Old, touched: Old },
|
||||
{ name: "1-home-1700000000000", stamp: Old, touched: Old },
|
||||
{ name: "2-1700000000000", stamp: Old, touched: Old },
|
||||
{ name: "3-home-1700000000000", stamp: New, touched: New },
|
||||
],
|
||||
});
|
||||
|
||||
writeFileSync(path.join(computers, "notes.txt"), "x");
|
||||
|
||||
expect((await pruneComputerHomes()).sort()).toEqual(["1-home-1700000000000", "2-1700000000000"]);
|
||||
expect(readdirSync(computers).sort()).toEqual(["1", "3-home-1700000000000", "notes.txt"]);
|
||||
});
|
||||
|
||||
test("a folder whose own time is recent is kept, whatever its name says", async () => {
|
||||
const { computers } = setup({
|
||||
folders: [{ name: "4-home-1700000000000", stamp: Old, touched: Date.now() }],
|
||||
});
|
||||
|
||||
expect(await pruneComputerHomes()).toEqual([]);
|
||||
expect(readdirSync(computers)).toEqual(["4-home-1700000000000"]);
|
||||
});
|
||||
|
||||
test("no computers folder at all is not a failure", async () => {
|
||||
process.env.DATA_DIR = path.join(tmpdir(), "cobble-homes-missing");
|
||||
|
||||
expect(await pruneComputerHomes()).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,49 @@
|
||||
import fs from "fs/promises";
|
||||
import path from "path";
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
import grabDirNames from "@/src/utils/grab-dir-names";
|
||||
import oldComputerHomeName from "./old-computer-home-name";
|
||||
|
||||
const DayMs = 24 * 60 * 60 * 1000;
|
||||
|
||||
/**
|
||||
* Deletes the folders `prepareComputerDataDir` moved aside, once they are
|
||||
* older than `AppData.ComputerOldHomeKeepDays` (`prune-computer-homes`):
|
||||
* a computer's whole old home, kept in case someone wants what it held,
|
||||
* then forgotten. Data backups leave them out
|
||||
* (`writeDataBackupArchive`), so nothing else ever removes them and they
|
||||
* only grow the data volume.
|
||||
*
|
||||
* Returns the folders it deleted.
|
||||
*/
|
||||
export default async function pruneComputerHomes() {
|
||||
const { DATA_DIR } = grabDirNames();
|
||||
const root = path.join(DATA_DIR, AppData.ComputerDataDir);
|
||||
const cutoff = Date.now() - AppData.ComputerOldHomeKeepDays * DayMs;
|
||||
const entries = await fs.readdir(root, { withFileTypes: true }).catch(() => []);
|
||||
const deleted: string[] = [];
|
||||
|
||||
for (const entry of entries) {
|
||||
if (!entry.isDirectory()) continue;
|
||||
|
||||
const stamp = oldComputerHomeName({ name: entry.name });
|
||||
|
||||
if (!stamp) continue;
|
||||
|
||||
const target = path.join(root, entry.name);
|
||||
|
||||
/**
|
||||
* The name's timestamp, checked against the folder's own time too:
|
||||
* a folder still being written is never old enough.
|
||||
*/
|
||||
const stats = await fs.stat(target).catch(() => null);
|
||||
|
||||
if (!stats || Math.max(stamp, stats.mtimeMs) > cutoff) continue;
|
||||
|
||||
await fs.rm(target, { recursive: true, force: true }).catch(() => {});
|
||||
|
||||
deleted.push(entry.name);
|
||||
}
|
||||
|
||||
return deleted;
|
||||
}
|
||||
@@ -54,6 +54,7 @@ export default async function grabHarnessModelEntries({
|
||||
name: `${model.name || model.slug}${row.available == 0 ? " (no longer listed)" : ""}`,
|
||||
free: model.free,
|
||||
voices: model.voices,
|
||||
input_modalities: model.input_modalities,
|
||||
supported_parameters: model.supported_parameters,
|
||||
},
|
||||
};
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
import deleteMedia from "./delete-media";
|
||||
import { unlinkedAttachmentIdsSql } from "./media-orphan-sql";
|
||||
|
||||
type Params = {
|
||||
/**
|
||||
* Media ids an upload put on a chat message, now that their message is
|
||||
* gone.
|
||||
*/
|
||||
media_ids: number[];
|
||||
};
|
||||
|
||||
/**
|
||||
* Deletes chat uploads whose message is being deleted, unless something
|
||||
* still points at the same media row: a bot file's bytes, a task's
|
||||
* deliverable, a knowledgebase document, a profile or bot picture. A chat
|
||||
* upload is its own `media` row (`upload-and-record-media`) and its
|
||||
* reference is the message's (`bot_message_media`), so an upload no
|
||||
* message shows is unreachable and only takes space. The bytes of a bot
|
||||
* file the upload was also copied into (`store-chat-attachments`) are a
|
||||
* separate row and stay.
|
||||
*
|
||||
* Returns the ids it deleted.
|
||||
*/
|
||||
export default async function deleteUnlinkedAttachmentMedia({ media_ids }: Params) {
|
||||
const query = unlinkedAttachmentIdsSql({ media_ids });
|
||||
|
||||
if (!query) return [];
|
||||
|
||||
const found = ((await BunSQLite.sql<{ id: number }>(query)).payload || []).map((row) =>
|
||||
Number(row.id),
|
||||
);
|
||||
|
||||
if (!found.length) return [];
|
||||
|
||||
await deleteMedia({ ids: found, can_delete_all_media: true });
|
||||
|
||||
return found;
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
import { Database } from "bun:sqlite";
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { mediaOrphanIdsSql, unlinkedAttachmentIdsSql } from "./media-orphan-sql";
|
||||
|
||||
/**
|
||||
* The two queries that decide a file is unreachable run against real
|
||||
* SQLite: a wrong condition here either deletes bytes a page still shows,
|
||||
* or leaves every orphan on disk forever.
|
||||
*/
|
||||
const db = new Database(":memory:");
|
||||
|
||||
db.run(`CREATE TABLE media (id INTEGER PRIMARY KEY, created_at INTEGER)`);
|
||||
db.run(`CREATE TABLE media_paradigms (media_id INTEGER, media_paradigm TEXT)`);
|
||||
db.run(`CREATE TABLE bot_message_media (media_id INTEGER)`);
|
||||
db.run(`CREATE TABLE bot_files (media_id INTEGER)`);
|
||||
db.run(`CREATE TABLE task_media (media_id INTEGER)`);
|
||||
db.run(`CREATE TABLE knowledgebase_documents (media_id INTEGER)`);
|
||||
db.run(`CREATE TABLE bots (image_media_id INTEGER)`);
|
||||
db.run(`CREATE TABLE workspaces (image_media_id INTEGER)`);
|
||||
|
||||
const Old = 1_000;
|
||||
const New = 10_000;
|
||||
|
||||
db.run(`INSERT INTO media VALUES
|
||||
(1, ${Old}), -- an old upload whose message is gone
|
||||
(2, ${Old}), -- an old upload its message still shows
|
||||
(3, ${Old}), -- an old row nothing ever recorded
|
||||
(4, ${Old}), -- a bot file's bytes, waiting for the link
|
||||
(5, ${New}), -- a fresh upload, still on its way
|
||||
(6, ${Old}), -- an old upload a bot file now holds
|
||||
(7, ${Old}), -- an old picture a bot shows
|
||||
(8, ${Old}) -- an old row a task holds`);
|
||||
|
||||
db.run(`INSERT INTO media_paradigms VALUES
|
||||
(1, 'bot-attachment'),
|
||||
(2, 'bot-attachment'),
|
||||
(4, 'bot-file'),
|
||||
(5, 'bot-attachment'),
|
||||
(6, 'bot-attachment'),
|
||||
(7, 'bot-image'),
|
||||
(8, 'bot-attachment')`);
|
||||
|
||||
db.run(`INSERT INTO bot_message_media VALUES (2)`);
|
||||
db.run(`INSERT INTO bot_files VALUES (6)`);
|
||||
db.run(`INSERT INTO bots VALUES (7)`);
|
||||
db.run(`INSERT INTO task_media VALUES (8)`);
|
||||
|
||||
function orphans({ cutoff, limit = 200 }: { cutoff: number; limit?: number }) {
|
||||
const { sql, values } = mediaOrphanIdsSql({ cutoff, limit });
|
||||
|
||||
return (db.query(sql).all(...(values as number[])) as { id: number }[]).map((row) => row.id);
|
||||
}
|
||||
|
||||
describe("mediaOrphanIdsSql", () => {
|
||||
test("takes an old upload no message shows and one nothing recorded", () => {
|
||||
expect(orphans({ cutoff: New })).toEqual([1, 3]);
|
||||
});
|
||||
|
||||
test("leaves alone anything a table still points at", () => {
|
||||
const taken = orphans({ cutoff: New });
|
||||
|
||||
expect(taken).not.toContain(2);
|
||||
expect(taken).not.toContain(6);
|
||||
expect(taken).not.toContain(7);
|
||||
expect(taken).not.toContain(8);
|
||||
});
|
||||
|
||||
test("leaves a row with another paradigm to whatever made it", () => {
|
||||
expect(orphans({ cutoff: New })).not.toContain(4);
|
||||
});
|
||||
|
||||
test("never takes a row newer than the cutoff", () => {
|
||||
expect(orphans({ cutoff: New })).not.toContain(5);
|
||||
expect(orphans({ cutoff: 0 })).toEqual([]);
|
||||
});
|
||||
|
||||
test("stops at the batch size", () => {
|
||||
expect(orphans({ cutoff: New, limit: 1 })).toEqual([1]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("unlinkedAttachmentIdsSql", () => {
|
||||
function unlinked(media_ids: number[]) {
|
||||
const query = unlinkedAttachmentIdsSql({ media_ids });
|
||||
|
||||
if (!query) return null;
|
||||
|
||||
const { sql, values } = query;
|
||||
|
||||
return (db.query(sql).all(...(values as number[])) as { id: number }[]).map((row) => row.id);
|
||||
}
|
||||
|
||||
test("takes only the ids nothing points at", () => {
|
||||
expect(unlinked([1, 2, 6, 7, 8])).toEqual([1]);
|
||||
});
|
||||
|
||||
test("repeats and bad ids change nothing", () => {
|
||||
expect(unlinked([1, 1, 0, -3, Number.NaN])).toEqual([1]);
|
||||
});
|
||||
|
||||
test("an empty list asks nothing", () => {
|
||||
expect(unlinked([])).toBeNull();
|
||||
expect(unlinked([0, -1])).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,60 @@
|
||||
/**
|
||||
* Every table that keeps a `media` row in use: a chat message's link, a bot
|
||||
* file's bytes, a task's file, a knowledgebase document, a bot's or a
|
||||
* workspace's picture. A row none of them names is unreachable: the pages
|
||||
* find media through those, never by id alone.
|
||||
*/
|
||||
export const UnreferencedMediaSql = `NOT EXISTS (SELECT 1 FROM bot_message_media l WHERE l.media_id = m.id)
|
||||
AND NOT EXISTS (SELECT 1 FROM bot_files f WHERE f.media_id = m.id)
|
||||
AND NOT EXISTS (SELECT 1 FROM task_media t WHERE t.media_id = m.id)
|
||||
AND NOT EXISTS (SELECT 1 FROM knowledgebase_documents d WHERE d.media_id = m.id)
|
||||
AND NOT EXISTS (SELECT 1 FROM bots b WHERE b.image_media_id = m.id)
|
||||
AND NOT EXISTS (SELECT 1 FROM workspaces w WHERE w.image_media_id = m.id)`;
|
||||
|
||||
type OrphanParams = {
|
||||
/** Rows newer than this are left alone, so an upload in flight survives. */
|
||||
cutoff: number;
|
||||
limit: number;
|
||||
};
|
||||
|
||||
/**
|
||||
* The orphaned uploads older than `cutoff`, in one batch.
|
||||
*
|
||||
* A chat upload (`bot-attachment`) is reached only by its message's link;
|
||||
* one with no paradigm at all was never recorded. A row with another
|
||||
* paradigm is left to whatever made it, even when nothing points at it yet.
|
||||
*/
|
||||
export function mediaOrphanIdsSql({ cutoff, limit }: OrphanParams) {
|
||||
return {
|
||||
sql: `SELECT m.id FROM media m WHERE m.created_at < ?
|
||||
AND (NOT EXISTS (SELECT 1 FROM media_paradigms p WHERE p.media_id = m.id)
|
||||
OR (EXISTS (SELECT 1 FROM media_paradigms p WHERE p.media_id = m.id AND p.media_paradigm = 'bot-attachment')
|
||||
AND NOT EXISTS (SELECT 1 FROM bot_message_media l WHERE l.media_id = m.id)))
|
||||
AND ${UnreferencedMediaSql}
|
||||
LIMIT ${Math.max(1, Math.floor(limit))}`,
|
||||
values: [cutoff],
|
||||
};
|
||||
}
|
||||
|
||||
type UnlinkedParams = {
|
||||
/** Media ids an upload put on a chat message, now that its message is gone. */
|
||||
media_ids: number[];
|
||||
};
|
||||
|
||||
/**
|
||||
* Which of `media_ids` nothing points at any more. Placeholders rather than
|
||||
* an id list in the text, so a number can never change the query.
|
||||
*/
|
||||
export function unlinkedAttachmentIdsSql({ media_ids }: UnlinkedParams) {
|
||||
const ids = Array.from(
|
||||
new Set(media_ids.map(Number).filter((id) => Number.isInteger(id) && id > 0)),
|
||||
);
|
||||
|
||||
if (!ids.length) return null;
|
||||
|
||||
return {
|
||||
sql: `SELECT m.id FROM media m WHERE m.id IN (${ids.map(() => "?").join(", ")})
|
||||
AND ${UnreferencedMediaSql}`,
|
||||
values: ids,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
import deleteMedia from "./delete-media";
|
||||
import { mediaOrphanIdsSql } from "./media-orphan-sql";
|
||||
|
||||
/**
|
||||
* How many orphaned rows go in one delete: a delete walks each file, so
|
||||
* they are taken in small runs rather than one long hold on the process.
|
||||
*/
|
||||
const BatchSize = 200;
|
||||
|
||||
/**
|
||||
* Up to how many batches one run takes, so a large backlog drains over a
|
||||
* few nights without a cron run that never ends.
|
||||
*/
|
||||
const MaxBatches = 20;
|
||||
|
||||
const DayMs = 24 * 60 * 60 * 1000;
|
||||
|
||||
/**
|
||||
* Deletes media nothing points at any more, older than
|
||||
* `AppData.MediaOrphanKeepDays` (`prune-orphan-media`): a chat upload whose
|
||||
* message was pruned with its room or hook session before the deletes
|
||||
* unlinked its bytes, and an upload whose message never got saved. Recent
|
||||
* rows are left alone so an upload in flight is never taken. The age also
|
||||
* keeps a profile picture's replaced predecessor, which a delete may leave
|
||||
* for a moment, out of it.
|
||||
*
|
||||
* Returns the ids it deleted.
|
||||
*/
|
||||
export default async function pruneOrphanMedia() {
|
||||
const cutoff = Date.now() - AppData.MediaOrphanKeepDays * DayMs;
|
||||
const deleted: number[] = [];
|
||||
|
||||
for (let batch = 0; batch < MaxBatches; batch++) {
|
||||
const { sql, values } = mediaOrphanIdsSql({ cutoff, limit: BatchSize });
|
||||
|
||||
const found = (await BunSQLite.sql<{ id: number }>({ sql, values })).payload || [];
|
||||
|
||||
if (!found.length) break;
|
||||
|
||||
const ids = found.map((row) => Number(row.id));
|
||||
|
||||
await deleteMedia({ ids, can_delete_all_media: true });
|
||||
|
||||
deleted.push(...ids);
|
||||
|
||||
if (found.length < BatchSize) break;
|
||||
}
|
||||
|
||||
return deleted;
|
||||
}
|
||||
@@ -11,6 +11,12 @@ type Params = {
|
||||
*/
|
||||
message_id: number;
|
||||
created_at?: number | null;
|
||||
/**
|
||||
* The most calls and failures listed one by one; the totals count
|
||||
* every one either way. The modal shows `AppData.MessageDetailsMaxCalls`
|
||||
* of them, its copied report far more.
|
||||
*/
|
||||
max_calls?: number;
|
||||
};
|
||||
|
||||
type CallRow = {
|
||||
@@ -64,7 +70,11 @@ type JobRow = {
|
||||
* model's display name come from their live rows, so a deleted provider
|
||||
* or an unlisted model still reads by the name it was called with.
|
||||
*/
|
||||
export default async function grabMessageDetails({ message_id, created_at }: Params): Promise<MessageDetails> {
|
||||
export default async function grabMessageDetails({
|
||||
message_id,
|
||||
created_at,
|
||||
max_calls = AppData.MessageDetailsMaxCalls,
|
||||
}: Params): Promise<MessageDetails> {
|
||||
const rows =
|
||||
(
|
||||
await BunSQLite.sql<CallRow>({
|
||||
@@ -145,8 +155,8 @@ export default async function grabMessageDetails({ message_id, created_at }: Par
|
||||
created_at: created_at || null,
|
||||
totals,
|
||||
models: groupMessageCalls({ calls }),
|
||||
calls: calls.slice(0, AppData.MessageDetailsMaxCalls),
|
||||
failures: failures.slice(0, AppData.MessageDetailsMaxCalls),
|
||||
calls: calls.slice(0, max_calls),
|
||||
failures: failures.slice(0, max_calls),
|
||||
failed_calls: failures.length,
|
||||
job: job_id ? await grabJob({ job_id: Number(job_id) }) : null,
|
||||
};
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
import type { LiveCrewRefreshedDetail } from "@/src/types";
|
||||
|
||||
export const LiveCrewRefreshedEvent = "cobble:live-crew-refreshed";
|
||||
|
||||
/**
|
||||
* Tells the page's lists (the rail's bots and workspaces) the crew as it
|
||||
* stands now, once it has been read again.
|
||||
*/
|
||||
export default function announceLiveCrew(detail: LiveCrewRefreshedDetail) {
|
||||
window.dispatchEvent(new CustomEvent(LiveCrewRefreshedEvent, { detail }));
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
export const LiveCrewRefreshRequestedEvent = "cobble:refresh-live-crew";
|
||||
|
||||
/**
|
||||
* Asks the layout to read the crew again, for an action that wants the
|
||||
* whole page current (the thread's pull-to-reload) rather than each list
|
||||
* fetching its own copy.
|
||||
*/
|
||||
export default function requestLiveCrewRefresh() {
|
||||
window.dispatchEvent(new Event(LiveCrewRefreshRequestedEvent));
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import createReadingCache from "./create-reading-cache";
|
||||
|
||||
describe("createReadingCache", () => {
|
||||
test("keeps a reading by key", () => {
|
||||
const cache = createReadingCache({ max: 4 });
|
||||
|
||||
cache.set({ key: "a", text: "A cat." });
|
||||
|
||||
expect(cache.get({ key: "a" })).toBe("A cat.");
|
||||
expect(cache.get({ key: "b" })).toBeUndefined();
|
||||
});
|
||||
|
||||
test("drops the least recently used reading when full", () => {
|
||||
const cache = createReadingCache({ max: 2 });
|
||||
|
||||
cache.set({ key: "a", text: "A" });
|
||||
cache.set({ key: "b", text: "B" });
|
||||
// Using "a" again keeps it, so "b" is the oldest.
|
||||
expect(cache.get({ key: "a" })).toBe("A");
|
||||
cache.set({ key: "c", text: "C" });
|
||||
|
||||
expect(cache.size()).toBe(2);
|
||||
expect(cache.get({ key: "a" })).toBe("A");
|
||||
expect(cache.get({ key: "b" })).toBeUndefined();
|
||||
expect(cache.get({ key: "c" })).toBe("C");
|
||||
});
|
||||
|
||||
test("a new reading for a key replaces the old one", () => {
|
||||
const cache = createReadingCache({ max: 4 });
|
||||
|
||||
cache.set({ key: "a", text: "first" });
|
||||
cache.set({ key: "a", text: "second" });
|
||||
|
||||
expect(cache.get({ key: "a" })).toBe("second");
|
||||
expect(cache.size()).toBe(1);
|
||||
});
|
||||
|
||||
test("clears", () => {
|
||||
const cache = createReadingCache({ max: 4 });
|
||||
|
||||
cache.set({ key: "a", text: "A" });
|
||||
cache.clear();
|
||||
|
||||
expect(cache.get({ key: "a" })).toBeUndefined();
|
||||
expect(cache.size()).toBe(0);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,49 @@
|
||||
type Params = {
|
||||
/**
|
||||
* How many readings to keep (`AppData.HarnessMediaReadingsCached`).
|
||||
*/
|
||||
max?: number;
|
||||
};
|
||||
|
||||
/**
|
||||
* Readings of images by what they are (`imageReadingKey`), kept across
|
||||
* runs: the same image was read again on every reply, one vision call
|
||||
* each time, since a run's own cache (`media_cache`) dies with it.
|
||||
*
|
||||
* Oldest first out when it's full, and a reading that's used again moves
|
||||
* to the back, so a picture the conversation keeps coming back to stays.
|
||||
*/
|
||||
export default function createReadingCache({ max = 100 }: Params = {}) {
|
||||
const readings = new Map<string, string>();
|
||||
|
||||
return {
|
||||
get({ key }: { key: string }) {
|
||||
const text = readings.get(key);
|
||||
|
||||
if (text === undefined) return undefined;
|
||||
|
||||
readings.delete(key);
|
||||
readings.set(key, text);
|
||||
|
||||
return text;
|
||||
},
|
||||
set({ key, text }: { key: string; text: string }) {
|
||||
readings.delete(key);
|
||||
readings.set(key, text);
|
||||
|
||||
while (readings.size > max) {
|
||||
const oldest = readings.keys().next().value;
|
||||
|
||||
if (oldest === undefined) break;
|
||||
|
||||
readings.delete(oldest);
|
||||
}
|
||||
},
|
||||
clear() {
|
||||
readings.clear();
|
||||
},
|
||||
size: () => readings.size,
|
||||
};
|
||||
}
|
||||
|
||||
export type ReadingCache = ReturnType<typeof createReadingCache>;
|
||||
@@ -0,0 +1,12 @@
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
import createReadingCache from "./create-reading-cache";
|
||||
|
||||
/**
|
||||
* The process-wide image readings every run shares, so one upload is read
|
||||
* once rather than once per reply.
|
||||
*/
|
||||
const MediaReadings = createReadingCache({
|
||||
max: AppData.HarnessMediaReadingsCached,
|
||||
});
|
||||
|
||||
export default MediaReadings;
|
||||
@@ -1,5 +1,7 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { beforeEach, describe, expect, test } from "bun:test";
|
||||
import { MediaReadNote } from "@/src/data/harness-prompts";
|
||||
import createReadingCache from "../media/create-reading-cache";
|
||||
import MediaReadings from "../media/media-readings";
|
||||
import type { HarnessMessage } from "../types";
|
||||
import prepareMessagesForModel from "./prepare-messages-for-model";
|
||||
|
||||
@@ -18,6 +20,10 @@ const messages: HarnessMessage[] = [
|
||||
const signal = new AbortController().signal;
|
||||
|
||||
describe("prepareMessagesForModel", () => {
|
||||
// Readings are kept across runs in one process-wide cache, so a test that
|
||||
// expects an image to be read must start without another test's reading.
|
||||
beforeEach(() => MediaReadings.clear());
|
||||
|
||||
test("keeps media the model can take", async () => {
|
||||
const fitted = await prepareMessagesForModel({
|
||||
messages,
|
||||
@@ -144,6 +150,73 @@ describe("prepareMessagesForModel", () => {
|
||||
expect(fitted[0]).toEqual({ role: "user", content: [image] });
|
||||
});
|
||||
|
||||
test("a reading is kept across runs, so the same image isn't read twice", async () => {
|
||||
const readings = createReadingCache({ max: 4 });
|
||||
let reads = 0;
|
||||
const run = () =>
|
||||
prepareMessagesForModel({
|
||||
messages: [
|
||||
{ role: "user", content: [{ type: "image", url: "data:image/png;base64,CCCC" }] },
|
||||
],
|
||||
model: { input_modalities: ["text"] },
|
||||
cache: new Map(),
|
||||
readings,
|
||||
signal,
|
||||
read_image: async () => {
|
||||
reads++;
|
||||
return "A cat.";
|
||||
},
|
||||
});
|
||||
|
||||
await run();
|
||||
const second = await run();
|
||||
|
||||
expect(reads).toBe(1);
|
||||
expect(readings.size()).toBe(1);
|
||||
expect(second[0]).toEqual({
|
||||
role: "user",
|
||||
content: [{ type: "text", text: "[Image: A cat.]" }],
|
||||
});
|
||||
});
|
||||
|
||||
test("a reading made to redact secrets is not kept across runs", async () => {
|
||||
const readings = createReadingCache({ max: 4 });
|
||||
let reads = 0;
|
||||
const run = () =>
|
||||
prepareMessagesForModel({
|
||||
messages: [
|
||||
{
|
||||
role: "user",
|
||||
content: [
|
||||
{
|
||||
type: "image",
|
||||
url: "data:image/png;base64,DDDD",
|
||||
redact: (text) => text.replaceAll("hunter2", "[secret]"),
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
model: { input_modalities: ["text"] },
|
||||
cache: new Map(),
|
||||
readings,
|
||||
signal,
|
||||
read_image: async () => {
|
||||
reads++;
|
||||
return "hunter2";
|
||||
},
|
||||
});
|
||||
|
||||
const first = await run();
|
||||
await run();
|
||||
|
||||
expect(first[0]).toEqual({
|
||||
role: "user",
|
||||
content: [{ type: "text", text: "[Image: [secret]]" }],
|
||||
});
|
||||
expect(reads).toBe(2);
|
||||
expect(readings.size()).toBe(0);
|
||||
});
|
||||
|
||||
test("reads images for a model that sees when the setting is off", async () => {
|
||||
const fitted = await prepareMessagesForModel({
|
||||
messages: [
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
import { MediaReadNote } from "@/src/data/harness-prompts";
|
||||
import transcribeAudio from "../audio/transcribe-audio";
|
||||
import HarnessError from "../harness-error";
|
||||
import type { ReadingCache } from "../media/create-reading-cache";
|
||||
import imageReadingKey from "../media/image-reading-key";
|
||||
import MediaReadings from "../media/media-readings";
|
||||
import readImage from "../media/read-image";
|
||||
import type {
|
||||
HarnessContentPart,
|
||||
@@ -23,6 +25,13 @@ type Params = {
|
||||
* read twice.
|
||||
*/
|
||||
cache: Map<string, string>;
|
||||
/**
|
||||
* Readings kept across runs (`MediaReadings`), so an image the
|
||||
* conversation carries is read once rather than once per reply. An
|
||||
* image with a `redact` is never written here: a secret's reading must
|
||||
* not outlive the run that asked for it.
|
||||
*/
|
||||
readings?: ReadingCache;
|
||||
signal: AbortSignal;
|
||||
/**
|
||||
* Reads media with this bot's models when it has its own.
|
||||
@@ -50,6 +59,7 @@ export default async function prepareMessagesForModel({
|
||||
model,
|
||||
sees_images = false,
|
||||
cache,
|
||||
readings = MediaReadings,
|
||||
signal,
|
||||
bot_id,
|
||||
workspace_id,
|
||||
@@ -71,6 +81,8 @@ export default async function prepareMessagesForModel({
|
||||
key: imageReadingKey({ url: part.url, focus: part.focus }),
|
||||
label: `Image${part.name ? ` "${part.name}"` : ""}`,
|
||||
cache,
|
||||
readings,
|
||||
share: !part.redact,
|
||||
signal,
|
||||
read: async () => {
|
||||
const reading = await read_image({
|
||||
@@ -95,6 +107,8 @@ export default async function prepareMessagesForModel({
|
||||
key: `audio:${Bun.hash(part.data)}`,
|
||||
label: `Audio${part.name ? ` "${part.name}"` : ""}, transcribed`,
|
||||
cache,
|
||||
readings,
|
||||
share: true,
|
||||
signal,
|
||||
read: () =>
|
||||
transcribe({
|
||||
@@ -148,22 +162,34 @@ async function readOnce({
|
||||
key,
|
||||
label,
|
||||
cache,
|
||||
readings,
|
||||
share,
|
||||
signal,
|
||||
read,
|
||||
}: {
|
||||
key: string;
|
||||
label: string;
|
||||
cache: Map<string, string>;
|
||||
readings: ReadingCache;
|
||||
/**
|
||||
* Whether the reading may be kept across runs. Not for an image read
|
||||
* so a secret can be cut out of it: that reading belongs to this run.
|
||||
*/
|
||||
share: boolean;
|
||||
signal: AbortSignal;
|
||||
read: () => Promise<string>;
|
||||
}) {
|
||||
const cached = cache.get(key);
|
||||
const cached = cache.get(key) ?? (share ? readings.get({ key }) : undefined);
|
||||
|
||||
if (cached !== undefined) return cached;
|
||||
if (cached !== undefined) {
|
||||
cache.set(key, cached);
|
||||
return cached;
|
||||
}
|
||||
|
||||
try {
|
||||
const text = `[${label}: ${await read()}]`;
|
||||
cache.set(key, text);
|
||||
if (share) readings.set({ key, text });
|
||||
return text;
|
||||
} catch (error: unknown) {
|
||||
if (signal.aborted || (error instanceof HarnessError && error.code == "aborted")) {
|
||||
|
||||
@@ -5,7 +5,12 @@ import { DroppedToolImageNote, SupersededSnapshotNote, ToolImagesNote } from "@/
|
||||
import HarnessError from "../harness-error";
|
||||
import type { HarnessCandidate, HarnessTool } from "../types";
|
||||
import type { GenerateTextParams, GenerateTextResult } from "./generate-text";
|
||||
import runTextLoop, { IncomingMessagesNote, RedraftNote, stepsLowNote } from "./run-text-loop";
|
||||
import runTextLoop, {
|
||||
IncomingMessagesNote,
|
||||
RedraftNote,
|
||||
stepsLowNote,
|
||||
stepsLowWarningLeft,
|
||||
} from "./run-text-loop";
|
||||
|
||||
const candidate: HarnessCandidate = {
|
||||
key: "1:m",
|
||||
@@ -173,6 +178,7 @@ describe("runTextLoop", () => {
|
||||
loop_call,
|
||||
loop_call,
|
||||
{ text: "Ran out of room; here's where I got to.", ...loop_call },
|
||||
{ text: "Ran out of room; here's where I got to.", ...loop_call },
|
||||
]);
|
||||
|
||||
const result = await runTextLoop({
|
||||
@@ -201,6 +207,85 @@ describe("runTextLoop", () => {
|
||||
});
|
||||
});
|
||||
|
||||
test("at the wrap up, offers only the tools that save, then answers without any", async () => {
|
||||
const save: HarnessTool<{ path: string }> = {
|
||||
name: "write_file",
|
||||
description: "Saves a file.",
|
||||
schema: z.object({ path: z.string() }),
|
||||
run: async ({ args }) => `Saved ${args.path}.`,
|
||||
};
|
||||
const loop_call = {
|
||||
tool_calls: [{ id: "c", name: "remember", arguments: `{"note":"x"}` }],
|
||||
};
|
||||
const { generate, seen } = scripted([
|
||||
loop_call,
|
||||
{
|
||||
text: "Writing the report.",
|
||||
tool_calls: [{ id: "w", name: "write_file", arguments: `{"path":"report.md"}` }],
|
||||
usage: { prompt_tokens: 10, completion_tokens: 1 },
|
||||
},
|
||||
{ text: "Report saved; here's what I found." },
|
||||
]);
|
||||
|
||||
const result = await runTextLoop({
|
||||
system: "s",
|
||||
messages: [{ role: "user", content: "audit the disk" }],
|
||||
tools: [remember, save],
|
||||
max_steps: 1,
|
||||
generate,
|
||||
resolveCandidates,
|
||||
});
|
||||
|
||||
expect(seen).toHaveLength(3);
|
||||
expect(seen[1]!.tools!.map((tool) => tool.name)).toEqual(["write_file"]);
|
||||
expect(seen[1]!.messages.at(-1)!.content).toContain("one turn to save what the user needs: write_file");
|
||||
expect(seen[2]!.tools).toBe(undefined);
|
||||
expect(result.tool_uses).toEqual([
|
||||
{ name: "remember", ok: true },
|
||||
{ name: "write_file", ok: true },
|
||||
]);
|
||||
expect(result.text).toBe("Report saved; here's what I found.");
|
||||
});
|
||||
|
||||
test("tells a saving turn that reaches for another tool what it may still call", async () => {
|
||||
const save: HarnessTool<{ path: string }> = {
|
||||
name: "write_file",
|
||||
description: "Saves a file.",
|
||||
schema: z.object({ path: z.string() }),
|
||||
run: async ({ args }) => `Saved ${args.path}.`,
|
||||
};
|
||||
const loop_call = {
|
||||
tool_calls: [{ id: "c", name: "remember", arguments: `{"note":"x"}` }],
|
||||
};
|
||||
const { generate, seen } = scripted([
|
||||
loop_call,
|
||||
{ tool_calls: [{ id: "r", name: "remember", arguments: `{"note":"more"}` }] },
|
||||
{
|
||||
tool_calls: [{ id: "w", name: "write_file", arguments: `{"path":"report.md"}` }],
|
||||
},
|
||||
{ text: "Report saved." },
|
||||
]);
|
||||
|
||||
const result = await runTextLoop({
|
||||
system: "s",
|
||||
messages: [{ role: "user", content: "audit the disk" }],
|
||||
tools: [remember, save],
|
||||
max_steps: 1,
|
||||
generate,
|
||||
resolveCandidates,
|
||||
});
|
||||
|
||||
expect(seen[2]!.messages.at(-1)!.content).toContain(
|
||||
"Only write_file can still be called in this run.",
|
||||
);
|
||||
expect(seen[3]!.tools).toBe(undefined);
|
||||
expect(result.tool_uses).toEqual([
|
||||
{ name: "remember", ok: true },
|
||||
{ name: "write_file", ok: true },
|
||||
]);
|
||||
expect(result.text).toBe("Report saved.");
|
||||
});
|
||||
|
||||
test("warns once, a few steps before the wrap up, in a long enough run", async () => {
|
||||
const max_steps = AppData.HarnessStepsLowMinSteps;
|
||||
const loop_call = {
|
||||
@@ -217,8 +302,9 @@ describe("runTextLoop", () => {
|
||||
resolveCandidates,
|
||||
});
|
||||
|
||||
const warned_at = max_steps - AppData.HarnessStepsLowWarning;
|
||||
const note = stepsLowNote({ left: AppData.HarnessStepsLowWarning });
|
||||
const left = stepsLowWarningLeft({ max_steps });
|
||||
const warned_at = max_steps - left;
|
||||
const note = stepsLowNote({ left });
|
||||
const warnings = seen.map((call) => call.messages.filter((m) => m.role == "user" && String(m.content).includes(note)).length);
|
||||
|
||||
expect(warnings[warned_at - 1]).toBe(0);
|
||||
@@ -227,6 +313,17 @@ describe("runTextLoop", () => {
|
||||
expect(warnings.at(-1)).toBe(1);
|
||||
});
|
||||
|
||||
test("warns a long run early enough to write its report", () => {
|
||||
/**
|
||||
* A 200 step audit once measured to its last step with the report
|
||||
* unwritten: the warning has to reach it with real room left.
|
||||
*/
|
||||
expect(stepsLowWarningLeft({ max_steps: AppData.HarnessMaxToolSteps })).toBe(
|
||||
Math.ceil(AppData.HarnessMaxToolSteps * AppData.HarnessStepsLowWarnShare),
|
||||
);
|
||||
expect(stepsLowWarningLeft({ max_steps: 20 })).toBe(AppData.HarnessStepsLowWarning);
|
||||
});
|
||||
|
||||
test("doesn't warn a short run", async () => {
|
||||
const loop_call = {
|
||||
tool_calls: [{ id: "c", name: "remember", arguments: `{"note":"x"}` }],
|
||||
|
||||
@@ -116,21 +116,57 @@ export type TextLoopResult = {
|
||||
tool_uses: HarnessToolUse[];
|
||||
};
|
||||
|
||||
/**
|
||||
* The only tools the wrap up may still call: saving the work. A run that
|
||||
* spent every step measuring can write the report the user waits for
|
||||
* rather than throw its findings away (`write_file`, and `import_file`
|
||||
* for what it pulled off a computer).
|
||||
*/
|
||||
export const WrapUpToolNames = ["write_file", "import_file"];
|
||||
|
||||
/**
|
||||
* Saving turns a wrap up may take: the first, and one more when it reached
|
||||
* for a tool it no longer has. After them the run answers with no tools.
|
||||
*/
|
||||
export const WrapUpSavingTurns = 2;
|
||||
|
||||
/**
|
||||
* Told on the last step, with the app's record of the tools the run
|
||||
* called (`describeToolUses`): out of steps, a model tends to report the
|
||||
* work it planned as done. `tokens` when the run's token budget ended it
|
||||
* rather than its steps.
|
||||
* rather than its steps. `saving` names the tools it may still call, if
|
||||
* any: its one saving round, after which it answers with none.
|
||||
*/
|
||||
export const wrapUpPrompt = ({ uses, reason = "steps" }: { uses: HarnessToolUse[]; reason?: "steps" | "tokens" }) =>
|
||||
`${reason == "tokens" ? "This run has used all the tokens it may spend." : "You've used every step this run allows."} Don't call any more tools. Report what you did, what is left, and anything you need from the user.
|
||||
export const wrapUpPrompt = ({
|
||||
uses,
|
||||
reason = "steps",
|
||||
saving = [],
|
||||
}: {
|
||||
uses: HarnessToolUse[];
|
||||
reason?: "steps" | "tokens";
|
||||
saving?: string[];
|
||||
}) =>
|
||||
`${reason == "tokens" ? "This run has used all the tokens it may spend." : "You've used every step this run allows."} ${
|
||||
saving.length
|
||||
? `You have one turn to save what the user needs: ${saving.join(" and ")} are still yours. Call only what saves the work (the report or deliverable) and nothing else, then report. After this turn no tool is left, so anything unsaved is lost.`
|
||||
: `Don't call any more tools.`
|
||||
} Report what you did, what is left, and anything you need from the user.
|
||||
|
||||
The tools you actually called this run: ${describeToolUses({ uses })}. Nothing else happened. Don't say you saved, created, changed or sent anything this list doesn't show; what you meant to do and didn't is still left, so say so.`;
|
||||
|
||||
/**
|
||||
* Told once, `AppData.HarnessStepsLowWarning` steps before the wrap up,
|
||||
* while the run can still save what it has: the wrap up has no tools, so a
|
||||
* report not written by then is lost.
|
||||
* Steps left when a run is warned, once, to save: a share of the run for
|
||||
* long ones, since 5 steps is the whole budget of a short one and no time
|
||||
* at all to write a report on a 200 step run (two runs in a row measured
|
||||
* to their last step with the report unwritten). Never below
|
||||
* `AppData.HarnessStepsLowWarning`.
|
||||
*/
|
||||
export const stepsLowWarningLeft = ({ max_steps }: { max_steps: number }) =>
|
||||
Math.max(AppData.HarnessStepsLowWarning, Math.ceil(max_steps * AppData.HarnessStepsLowWarnShare));
|
||||
|
||||
/**
|
||||
* Told once, `stepsLowWarningLeft` steps before the wrap up, while the run
|
||||
* can still save what it has.
|
||||
*/
|
||||
export const stepsLowNote = ({ left }: { left: number }) =>
|
||||
`You have ${left} step${left == 1 ? "" : "s"} left in this run. Save what the user will want now (the report or deliverable, with write_file or import_file) before anything else, then finish. What isn't saved when the steps run out is lost.`;
|
||||
@@ -159,7 +195,8 @@ Don't repeat tool calls you have already made.`;
|
||||
* go back to it, and so on until it answers without calling a tool. Tools
|
||||
* run one at a time, in order; images they return follow their results. Stays on one model unless it fails. After
|
||||
* `max_steps` turns, or once the run has sent `max_prompt_tokens`, the
|
||||
* model is asked to wrap up without tools. An answer `review` finds fault
|
||||
* model is asked to wrap up: one turn with only the saving tools
|
||||
* (`WrapUpToolNames`), then one with none. An answer `review` finds fault
|
||||
* with is written again once.
|
||||
*
|
||||
* Every turn resends everything, so the run keeps it small: only the
|
||||
@@ -224,28 +261,60 @@ export default async function runTextLoop({
|
||||
cost: 0,
|
||||
};
|
||||
const tool_uses: HarnessToolUse[] = [];
|
||||
/**
|
||||
* The tools a wrap up may still call: only the ones that save the work.
|
||||
* A run that spent every step measuring can then still write the report
|
||||
* the user is waiting for, which is what two runs in a row failed to do
|
||||
* (they measured to the last step and had no tool left to save with).
|
||||
*/
|
||||
const save_tools = run_tools.filter((tool) => WrapUpToolNames.includes(tool.name));
|
||||
const save_definitions = save_tools.map((tool) => all_definitions.get(tool.name)!);
|
||||
const warn_at = stepsLowWarningLeft({ max_steps });
|
||||
let prefer_key: string | undefined;
|
||||
let reviewed = false;
|
||||
let warned_steps = max_steps < AppData.HarnessStepsLowMinSteps;
|
||||
/**
|
||||
* The wrap up is announced once, and may save until it has: a run told
|
||||
* to stop with its report unwritten gets a turn to write it (at most
|
||||
* `WrapUpSavingTurns`, so it always ends).
|
||||
*/
|
||||
let wrap_up_announced = false;
|
||||
let saving_turns = 0;
|
||||
let saved = false;
|
||||
|
||||
for (let index = 0; index <= max_steps; index++) {
|
||||
for (let index = 0; index <= max_steps + 1 + WrapUpSavingTurns; index++) {
|
||||
if (signal.aborted) {
|
||||
throw new HarnessError({ message: `Cancelled.`, code: "aborted" });
|
||||
}
|
||||
|
||||
const out_of_steps = index >= max_steps;
|
||||
const out_of_tokens = Boolean(max_prompt_tokens && max_prompt_tokens > 0 && usage.prompt_tokens >= max_prompt_tokens);
|
||||
const wrap_up = index == max_steps || out_of_tokens;
|
||||
const wrap_up = out_of_steps || out_of_tokens;
|
||||
/**
|
||||
* The saving turn: only the tools that save the work. Without one
|
||||
* of them, or once it saved, the wrap up is the old one, with no
|
||||
* tools at all, so the run always ends.
|
||||
*/
|
||||
const wrap_up_saving = wrap_up && !saved && saving_turns < WrapUpSavingTurns && save_tools.length > 0;
|
||||
|
||||
if (wrap_up && !wrap_up_announced) {
|
||||
wrap_up_announced = true;
|
||||
|
||||
if (wrap_up) {
|
||||
if (incoming_notes?.wrap_up) await takeIncoming({ note: incoming_notes.wrap_up });
|
||||
|
||||
pushUserTurn({
|
||||
transcript,
|
||||
content: wrapUpPrompt({ uses: tool_uses, reason: index == max_steps ? "steps" : "tokens" }),
|
||||
content: wrapUpPrompt({
|
||||
uses: tool_uses,
|
||||
reason: out_of_steps ? "steps" : "tokens",
|
||||
saving: wrap_up_saving ? save_tools.map((tool) => tool.name) : [],
|
||||
}),
|
||||
});
|
||||
}
|
||||
|
||||
const definitions = definitionsNow();
|
||||
if (wrap_up_saving) saving_turns++;
|
||||
|
||||
const definitions = wrap_up_saving ? save_definitions : wrap_up ? [] : definitionsNow();
|
||||
|
||||
/**
|
||||
* Sized for the model the run is on (or will start on). A fallback
|
||||
@@ -258,12 +327,12 @@ export default async function runTextLoop({
|
||||
transcript,
|
||||
context_length: model?.context_length || AppData.HarnessAutoMinContext,
|
||||
budget_tokens: context_budget,
|
||||
tools_chars: wrap_up ? 0 : JSON.stringify(definitions).length,
|
||||
tools_chars: JSON.stringify(definitions).length,
|
||||
});
|
||||
|
||||
const answer = await generate({
|
||||
messages: [{ role: "system", content: run_system }, ...transcript],
|
||||
tools: wrap_up || !definitions.length ? undefined : definitions,
|
||||
tools: definitions.length ? definitions : undefined,
|
||||
candidates,
|
||||
prefer_key,
|
||||
signal,
|
||||
@@ -277,7 +346,26 @@ export default async function runTextLoop({
|
||||
usage.completion_tokens += answer.usage?.completion_tokens || 0;
|
||||
usage.cost += answer.usage?.cost || 0;
|
||||
|
||||
const tool_calls = wrap_up ? [] : answer.tool_calls;
|
||||
/**
|
||||
* Only the tools this turn offered: at the wrap up that is the
|
||||
* saving ones, and the last turn offers none.
|
||||
*/
|
||||
const tool_calls = (wrap_up ? (wrap_up_saving ? answer.tool_calls : []) : answer.tool_calls).filter(
|
||||
(call) => !wrap_up || save_tools.some((tool) => tool.name == call.name),
|
||||
);
|
||||
|
||||
/**
|
||||
* A saving turn that reached for anything else is told what it has
|
||||
* left, and gets that one round again (never more, so the run
|
||||
* ends).
|
||||
*/
|
||||
if (wrap_up_saving && answer.tool_calls.length && !tool_calls.length) {
|
||||
pushUserTurn({
|
||||
transcript,
|
||||
content: `Only ${save_tools.map((tool) => tool.name).join(" and ")} can still be called in this run. Nothing else you call will run. Save the report or deliverable with one of them, or answer with what you have.`,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
|
||||
transcript.push({
|
||||
role: "assistant",
|
||||
@@ -324,6 +412,8 @@ export default async function runTextLoop({
|
||||
};
|
||||
}
|
||||
|
||||
if (wrap_up_saving) saved = true;
|
||||
|
||||
const shown: { tool_name: string; images: HarnessToolImage[] }[] = [];
|
||||
|
||||
for (const call of tool_calls) {
|
||||
@@ -367,7 +457,7 @@ export default async function runTextLoop({
|
||||
*/
|
||||
const left = max_steps - (index + 1);
|
||||
|
||||
if (!warned_steps && left <= AppData.HarnessStepsLowWarning) {
|
||||
if (!warned_steps && left <= warn_at) {
|
||||
warned_steps = true;
|
||||
pushUserTurn({ transcript, content: stepsLowNote({ left }) });
|
||||
}
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
import { afterAll, describe, expect, mock, test } from "bun:test";
|
||||
import type { HarnessTool } from "../../types";
|
||||
import type { BUN_SQLITE_COBBLE_BOTS } from "@/db/types/db";
|
||||
|
||||
/**
|
||||
* The coordinator keeps the install's skills, MCP servers and tools
|
||||
* wherever it works. Its workspace conversation is where a runbook for
|
||||
* that workspace's crew gets written, so the branch that returns early for
|
||||
* a workspace must still carry `grabCoordinatorExtensionTools`: a
|
||||
* coordinator asked to make a skill there once had no tool to make one
|
||||
* with, and wrote a file into its folder instead.
|
||||
*
|
||||
* Everything the tool list would read from the database is mocked, so this
|
||||
* suite checks the list's structure alone: which branch pushed what.
|
||||
*/
|
||||
const marker = ({ name }: { name: string }): HarnessTool => ({
|
||||
name,
|
||||
description: `${name} marker`,
|
||||
run: async () => "ok",
|
||||
});
|
||||
|
||||
/**
|
||||
* What `grabCrewWorkers` answers, per test: a workspace with no worker is
|
||||
* the branch that returned before the extension tools were pushed.
|
||||
*/
|
||||
let workers: BUN_SQLITE_COBBLE_BOTS[] = [{ id: 5, name: "A worker", kind: "worker" }];
|
||||
|
||||
mock.module("./extensions/grab-coordinator-extension-tools", () => ({
|
||||
default: async () => [marker({ name: "list_extensions" }), marker({ name: "propose_skill" })],
|
||||
}));
|
||||
mock.module("./grab-bot-tools", () => ({
|
||||
default: async () => [marker({ name: "update_memory" })],
|
||||
}));
|
||||
mock.module("@/src/functions/backend/db/workspaces/grab-user-workspaces", () => ({
|
||||
default: async () => [{ id: 11, name: "A workspace", archived: 0 }],
|
||||
}));
|
||||
mock.module("@/src/functions/backend/db/bots/grab-crew-workers", () => ({
|
||||
default: async () => workers,
|
||||
}));
|
||||
|
||||
const grabBotChatTools = (await import("./grab-bot-chat-tools")).default;
|
||||
|
||||
afterAll(() => {
|
||||
mock.restore();
|
||||
});
|
||||
|
||||
async function names({ workspace_id }: { workspace_id: number | null }) {
|
||||
const coordinator = {
|
||||
bot_types: [],
|
||||
is_coordinator: true,
|
||||
admin_workspace_ids: [],
|
||||
is_workspace_admin: false,
|
||||
can: () => true,
|
||||
};
|
||||
|
||||
const tools = await grabBotChatTools({
|
||||
bot: { id: 1, kind: "coordinator", name: "Coordinator" },
|
||||
powers: coordinator,
|
||||
user_id: 1,
|
||||
computers: [],
|
||||
session_id: 9,
|
||||
workspace_id,
|
||||
onPropose: () => {},
|
||||
});
|
||||
|
||||
return tools.map((tool) => tool.name);
|
||||
}
|
||||
|
||||
describe("grabBotChatTools", () => {
|
||||
test("the coordinator in a workspace reaches the install's skills, servers and tools", async () => {
|
||||
workers = [{ id: 5, name: "A worker", kind: "worker" }];
|
||||
|
||||
const list = await names({ workspace_id: 11 });
|
||||
|
||||
expect(list).toContain("list_extensions");
|
||||
expect(list).toContain("propose_skill");
|
||||
});
|
||||
|
||||
test("a workspace with no worker still gets them, before the empty-crew return", async () => {
|
||||
workers = [];
|
||||
|
||||
const list = await names({ workspace_id: 11 });
|
||||
|
||||
expect(list).toContain("list_extensions");
|
||||
expect(list).toContain("propose_skill");
|
||||
});
|
||||
|
||||
test("its own chat carries them too", async () => {
|
||||
workers = [{ id: 5, name: "A worker", kind: "worker" }];
|
||||
|
||||
const list = await names({ workspace_id: null });
|
||||
|
||||
expect(list).toContain("list_extensions");
|
||||
expect(list).toContain("propose_skill");
|
||||
});
|
||||
});
|
||||
@@ -105,10 +105,12 @@ type Params = {
|
||||
* update_bot, delete_bot and delete_workspace (which workspace, which
|
||||
* computers, and which name, role and core instructions each crew member
|
||||
* gets, and what goes) and the install's skills, MCP servers and custom
|
||||
* tools (`grabCoordinatorExtensionTools`) or, in a workspace,
|
||||
* set_bot_workspace_instructions and update_bot for the workspace's crew
|
||||
* (a bot's core prompt is asked for from wherever the user is), plus
|
||||
* set_bot_type to make a worker a workspace's admin. A workspace admin, in the workspace it leads, gets
|
||||
* tools (`grabCoordinatorExtensionTools`, in a workspace as much as in its
|
||||
* own chat: a runbook for the crew there is written from either) or, in a
|
||||
* workspace, set_bot_workspace_instructions and update_bot for the
|
||||
* workspace's crew (a bot's core prompt is asked for from wherever the
|
||||
* user is), plus set_bot_type to make a worker a workspace's admin. A
|
||||
* workspace admin, in the workspace it leads, gets
|
||||
* `grabWorkspaceAdminTools`. Every gate reads the bot's types (`powers`),
|
||||
* never `bots.kind`. Anything else on a computer goes through a task,
|
||||
* never mid-reply.
|
||||
@@ -177,6 +179,14 @@ export default async function grabBotChatTools({
|
||||
return tools;
|
||||
}
|
||||
|
||||
/**
|
||||
* The install's skills, MCP servers and tools are the coordinator's
|
||||
* wherever it works, a workspace as much as its own chat: a skill the
|
||||
* crew there needs is written from either, and every tool checks the
|
||||
* super admin again when it runs.
|
||||
*/
|
||||
tools.push(...(await grabCoordinatorExtensionTools({ user_id, bot_id, session_id, workspace_id, onPropose })));
|
||||
|
||||
const workspaces = (await grabUserWorkspaces({ user_id })).filter((w) => !w.archived);
|
||||
|
||||
/**
|
||||
@@ -227,12 +237,7 @@ export default async function grabBotChatTools({
|
||||
return tools;
|
||||
}
|
||||
|
||||
tools.push(
|
||||
findBotTool(),
|
||||
findWorkspaceTool({ user_id }),
|
||||
listWorkspaceBotsTool({ user_id }),
|
||||
...(await grabCoordinatorExtensionTools({ user_id, bot_id, session_id, workspace_id, onPropose })),
|
||||
);
|
||||
tools.push(findBotTool(), findWorkspaceTool({ user_id }), listWorkspaceBotsTool({ user_id }));
|
||||
|
||||
tools.push(deleteWorkspaceTool({ user_id, workspaces }));
|
||||
|
||||
|
||||
@@ -7,10 +7,17 @@ describe("capToolOutput", () => {
|
||||
});
|
||||
|
||||
test("keeps the start and the end of long text", () => {
|
||||
const out = capToolOutput({ text: `${"a".repeat(50)}${"b".repeat(50)}`, max_chars: 20 });
|
||||
const out = capToolOutput({ text: `${"a".repeat(50)}${"b".repeat(50)}`, max_chars: 60 });
|
||||
|
||||
expect(out.startsWith("a".repeat(8))).toBe(true);
|
||||
expect(out.endsWith("b".repeat(12))).toBe(true);
|
||||
expect(out).toContain("80 characters left out");
|
||||
expect(out.startsWith("a")).toBe(true);
|
||||
expect(out.endsWith("b")).toBe(true);
|
||||
expect(out).toContain("40 characters left out");
|
||||
});
|
||||
|
||||
test("stays inside max_chars, so the harness never cuts its end off again", () => {
|
||||
const out = capToolOutput({ text: "h".repeat(20000) + "totals", max_chars: 20000 });
|
||||
|
||||
expect(out.length).toBeLessThanOrEqual(20000);
|
||||
expect(out).toEndWith("totals");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -11,8 +11,15 @@ type Params = {
|
||||
export default function capToolOutput({ text, max_chars }: Params) {
|
||||
if (text.length <= max_chars) return text;
|
||||
|
||||
const head = Math.floor(max_chars * 0.4);
|
||||
const tail = max_chars - head;
|
||||
/**
|
||||
* Sized before the two ends are cut, so the note can't push the result
|
||||
* past `max_chars` (the harness cuts there too, and would cut the end
|
||||
* this keeps).
|
||||
*/
|
||||
const note = `\n\n[... ${text.length - max_chars} characters left out ...]\n\n`;
|
||||
const room = Math.max(0, max_chars - note.length);
|
||||
const head = Math.floor(room * 0.4);
|
||||
const tail = room - head;
|
||||
|
||||
return `${text.slice(0, head)}\n\n[... ${text.length - max_chars} characters left out ...]\n\n${text.slice(-tail)}`;
|
||||
return `${text.slice(0, head)}${note}${text.slice(-tail)}`;
|
||||
}
|
||||
|
||||
@@ -8,6 +8,7 @@ import computerWorkerAccount from "@/src/utils/computer-worker-account";
|
||||
import capToolOutput from "./cap-tool-output";
|
||||
import computerDirsShell from "./computer-dirs-shell";
|
||||
import type { ComputerToolContext } from "./computer-tool-context";
|
||||
import { computerWorkspaceFullWarning } from "./computer-workspace-room";
|
||||
|
||||
type Args = {
|
||||
command: string;
|
||||
@@ -57,11 +58,19 @@ export default function computerBashTool({ computer, dirs, shell_path, redact }:
|
||||
|
||||
const output = capToolOutput({ text: redact(result.output.replace(/\s+$/, "")), max_chars: AppData.ComputerCommandMaxOutputChars });
|
||||
|
||||
/**
|
||||
* A command writes whatever it likes, past what the agent sees:
|
||||
* say when the workspace has outgrown its limit, so the bot
|
||||
* clears space before its next write is refused.
|
||||
*/
|
||||
const full = await computerWorkspaceFullWarning({ computer, dirs }).catch(() => null);
|
||||
|
||||
return [
|
||||
`Exit code: ${result.exit_code ?? "unknown"}`,
|
||||
output || "(no output)",
|
||||
result.timed_out ? `[Stopped after ${seconds}s: the command timed out. Run long work in the background and check its log.]` : "",
|
||||
result.truncated ? `[The computer kept only the first part of a very long output.]` : "",
|
||||
full || "",
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join("\n");
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
import computerWorkerAccount from "@/src/utils/computer-worker-account";
|
||||
import shellQuote from "@/src/utils/shell-quote";
|
||||
import type { ComputerRunDirs } from "@/src/utils/computer-work-dirs";
|
||||
|
||||
/**
|
||||
* Where a run's caches go: the account's own home inside the container
|
||||
* (`/home/cb-<bot>/.cache`, `/home/gem/.cache`), never the run's folder.
|
||||
*
|
||||
* A run's `HOME` is its folder on the computer's mounted workspace
|
||||
* (`computerDirsShell`), because that is where its work must land. With no
|
||||
* cache home set, everything pip, npm, bun and Python cache on the side
|
||||
* went there too and was kept forever: one install's data volume held
|
||||
* 368 MB of npm cache, 188 MB of pip and headless-Chromium caches and
|
||||
* 53 MB of bun's install cache, against 178 MB of real bot files, and a
|
||||
* data archive carried all of it. Caches are rebuilt on demand, so they
|
||||
* belong in the part of the home a new container starts without.
|
||||
*/
|
||||
export default function computerCacheEnv({ dirs }: { dirs: ComputerRunDirs }) {
|
||||
const home = dirs.run_as
|
||||
? computerWorkerAccount({ bot_id: dirs.run_as.bot_id }).home
|
||||
: AppData.ComputerHomeDir;
|
||||
const cache_home = `${home}/.cache`;
|
||||
|
||||
/**
|
||||
* Each tool reads its own variable: `XDG_CACHE_HOME` covers what
|
||||
* follows the convention (Playwright's browsers, Chromium's headless
|
||||
* profile, pip's http cache), the rest name their cache directly.
|
||||
* `NPM_CONFIG_PREFIX` stays on `$HOME/.local` (`computerDirsShell`),
|
||||
* since installed packages have to survive a recreate.
|
||||
*/
|
||||
const assignments = [
|
||||
`XDG_CACHE_HOME=${shellQuote({ text: cache_home })}`,
|
||||
`npm_config_cache=${shellQuote({ text: `${cache_home}/npm` })}`,
|
||||
`PIP_CACHE_DIR=${shellQuote({ text: `${cache_home}/pip` })}`,
|
||||
`BUN_INSTALL_CACHE_DIR=${shellQuote({ text: `${cache_home}/bun` })}`,
|
||||
`PYTHONPYCACHEPREFIX=${shellQuote({ text: `${cache_home}/pycache` })}`,
|
||||
].join(" ");
|
||||
|
||||
return { cache_home, assignments };
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import type { ComputerRunDirs } from "@/src/utils/computer-work-dirs";
|
||||
import computerWorkspacePath from "@/src/utils/computer-workspace-path";
|
||||
import shellQuote from "@/src/utils/shell-quote";
|
||||
import computerCacheEnv from "./computer-cache-env";
|
||||
|
||||
/**
|
||||
* The shell that puts a command in the run's folder on the computer:
|
||||
@@ -13,22 +14,30 @@ import shellQuote from "@/src/utils/shell-quote";
|
||||
* worker (its own account, no sudo) also gets `umask 007`, so its files
|
||||
* stay its workspace group's and nobody else's, and installs into that
|
||||
* home that work without root (`pip install --user`, `npm install -g` into
|
||||
* `~/.local`, on `PATH`). Ends with `; `, ready to prefix a command.
|
||||
* `~/.local`, on `PATH`). Caches go to the account's own home inside the
|
||||
* container instead (`computerCacheEnv`), so no cache a run makes is kept
|
||||
* on the data volume. Ends with `; `, ready to prefix a command.
|
||||
*/
|
||||
export default function computerDirsShell({ dirs }: { dirs: ComputerRunDirs }) {
|
||||
const cwd = shellQuote({ text: dirs.cwd });
|
||||
const cache = computerCacheEnv({ dirs });
|
||||
const cache_dir = shellQuote({ text: cache.cache_home });
|
||||
|
||||
if (!dirs.run_as) {
|
||||
const folders = [dirs.cwd, ...(dirs.shared_dir ? [dirs.shared_dir] : [])]
|
||||
const folders = [
|
||||
dirs.cwd,
|
||||
cache.cache_home,
|
||||
...(dirs.shared_dir ? [dirs.shared_dir] : []),
|
||||
]
|
||||
.map((dir) => shellQuote({ text: dir }))
|
||||
.join(" ");
|
||||
|
||||
return `mkdir -p ${folders} && cd ${cwd} && export HOME=${cwd}; `;
|
||||
return `mkdir -p ${folders} && cd ${cwd} && export HOME=${cwd} ${cache.assignments}; `;
|
||||
}
|
||||
|
||||
const shared = dirs.shared_dir ? sharedLinkShell({ link: dirs.shared_dir }) : "";
|
||||
|
||||
return `umask 007 && ${shared}mkdir -p ${cwd} && cd ${cwd} && export HOME=${cwd} && export PATH="$HOME/.local/bin:$PATH" NPM_CONFIG_PREFIX="$HOME/.local"; `;
|
||||
return `umask 007 && ${shared}mkdir -p ${cwd} ${cache_dir} && cd ${cwd} && export HOME=${cwd} ${cache.assignments} && export PATH="$HOME/.local/bin:$PATH" NPM_CONFIG_PREFIX="$HOME/.local"; `;
|
||||
}
|
||||
|
||||
function sharedLinkShell({ link }: { link: string }) {
|
||||
|
||||
@@ -5,6 +5,7 @@ import writeComputerFile from "@/src/functions/backend/computers/write-computer-
|
||||
import { resolveComputerPath } from "@/src/utils/computer-work-dirs";
|
||||
import type { HarnessTool } from "../../types";
|
||||
import type { ComputerToolContext } from "./computer-tool-context";
|
||||
import computerWorkspaceRoomError from "./computer-workspace-room";
|
||||
import replaceInText from "./replace-in-text";
|
||||
|
||||
type Args = {
|
||||
@@ -59,8 +60,16 @@ export default function computerEditFileTool({ computer, dirs }: ComputerToolCon
|
||||
: `old_text is in ${path} ${edit.count} times. Include more of the lines around it, or pass replace_all.`;
|
||||
}
|
||||
|
||||
await writeComputerFile({ computer, path, content: edit.text, run_as: dirs.run_as, signal });
|
||||
const too_big = await computerWorkspaceRoomError({
|
||||
computer,
|
||||
dirs,
|
||||
incoming_bytes: Buffer.byteLength(edit.text, "utf8") - download.bytes.length,
|
||||
signal,
|
||||
});
|
||||
|
||||
if (too_big) return too_big;
|
||||
|
||||
await writeComputerFile({ computer, path, content: edit.text, run_as: dirs.run_as, signal });
|
||||
return `Edited ${path} (${edit.count} replacement${edit.count == 1 ? "" : "s"}).`;
|
||||
},
|
||||
};
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { workspaceHasRoom } from "./computer-workspace-room";
|
||||
|
||||
const MB = 1024 * 1024;
|
||||
|
||||
/**
|
||||
* The check the two write tools make before writing: a wrong sum either
|
||||
* refuses a write that fits, or lets a bot fill the computer's volume.
|
||||
*/
|
||||
describe("workspaceHasRoom", () => {
|
||||
test("lets a write land at or under the limit", () => {
|
||||
expect(workspaceHasRoom({ used_bytes: 0, quota_bytes: 10 * MB, incoming_bytes: MB })).toBe(true);
|
||||
expect(workspaceHasRoom({ used_bytes: 9 * MB, quota_bytes: 10 * MB, incoming_bytes: MB })).toBe(true);
|
||||
});
|
||||
|
||||
test("refuses a write that would pass it", () => {
|
||||
expect(workspaceHasRoom({ used_bytes: 9 * MB, quota_bytes: 10 * MB, incoming_bytes: MB + 1 })).toBe(false);
|
||||
expect(workspaceHasRoom({ used_bytes: 50 * MB, quota_bytes: 10 * MB, incoming_bytes: 1 })).toBe(false);
|
||||
});
|
||||
|
||||
test("a quota of 0 sets no limit", () => {
|
||||
expect(workspaceHasRoom({ used_bytes: 900 * MB, quota_bytes: 0, incoming_bytes: MB })).toBe(true);
|
||||
});
|
||||
|
||||
test("a shrinking write always fits, even over the limit", () => {
|
||||
expect(workspaceHasRoom({ used_bytes: 20 * MB, quota_bytes: 10 * MB, incoming_bytes: -5 * MB })).toBe(true);
|
||||
expect(workspaceHasRoom({ used_bytes: 10 * MB, quota_bytes: 10 * MB, incoming_bytes: -5 * MB })).toBe(true);
|
||||
expect(workspaceHasRoom({ used_bytes: 20 * MB, quota_bytes: 10 * MB, incoming_bytes: 0 })).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,114 @@
|
||||
import type { ComputerApi } from "@/src/functions/backend/computers/computer-fetch";
|
||||
import grabComputerUsage from "@/src/functions/backend/computers/grab-computer-usage";
|
||||
import grabComputerWorkspaceQuotaBytes from "@/src/functions/backend/db/app-settings/grab-computer-workspace-quota-bytes";
|
||||
import type { ComputerRunDirs } from "@/src/utils/computer-work-dirs";
|
||||
import formatBytes from "@/src/utils/format-bytes";
|
||||
|
||||
type Params = {
|
||||
computer: ComputerApi;
|
||||
dirs: ComputerRunDirs;
|
||||
/**
|
||||
* How many bytes the call is about to add. A rewrite of an existing
|
||||
* file passes only the growth.
|
||||
*/
|
||||
incoming_bytes: number;
|
||||
signal?: AbortSignal;
|
||||
};
|
||||
|
||||
/**
|
||||
* Refuses a write that would push the computer's workspace past its limit
|
||||
* (`grabComputerWorkspaceQuotaBytes`), naming what is used and what to do
|
||||
* instead, so a bot clears space rather than retrying. The workspace is one
|
||||
* folder for every bot and user on that computer, mounted from the data
|
||||
* volume, so it is the one thing on a computer that can fill the host's
|
||||
* disk; everything else in the container goes with it.
|
||||
*
|
||||
* Returns the refusal's message, or null when the write fits. A computer
|
||||
* that won't report its usage is left to the write itself to refuse.
|
||||
*/
|
||||
type RoomParams = {
|
||||
used_bytes: number;
|
||||
quota_bytes: number;
|
||||
incoming_bytes: number;
|
||||
};
|
||||
|
||||
/**
|
||||
* Whether a write of `incoming_bytes` fits: the one place the sum is made,
|
||||
* so the two write tools and the shell's warning agree. A quota of 0 means
|
||||
* the install sets no limit. A write that adds nothing (a rewrite the same
|
||||
* size, or a shrink) always fits, since refusing it would leave a bot over
|
||||
* the limit with no way back down.
|
||||
*/
|
||||
export function workspaceHasRoom({ used_bytes, quota_bytes, incoming_bytes }: RoomParams) {
|
||||
if (quota_bytes <= 0) return true;
|
||||
if (incoming_bytes <= 0) return true;
|
||||
|
||||
return used_bytes + incoming_bytes <= quota_bytes;
|
||||
}
|
||||
|
||||
export default async function computerWorkspaceRoomError({ computer, dirs, incoming_bytes, signal }: Params) {
|
||||
const quota_bytes = await grabComputerWorkspaceQuotaBytes();
|
||||
|
||||
if (quota_bytes <= 0) return null;
|
||||
|
||||
const usage = await grabComputerUsage({ computer, signal }).catch(() => null);
|
||||
|
||||
if (!usage) return null;
|
||||
if (workspaceHasRoom({ used_bytes: usage.used_bytes, quota_bytes, incoming_bytes })) return null;
|
||||
|
||||
return computerWorkspaceFullMessage({ used_bytes: usage.used_bytes, quota_bytes, dirs });
|
||||
}
|
||||
|
||||
/**
|
||||
* What a bot is told when the workspace is full: what is used, what the
|
||||
* limit is, and what to do instead. `dir` is where its own work is, the one
|
||||
* folder it may safely clear.
|
||||
*/
|
||||
export function computerWorkspaceFullMessage({
|
||||
used_bytes,
|
||||
quota_bytes,
|
||||
dirs,
|
||||
}: {
|
||||
used_bytes: number;
|
||||
quota_bytes: number;
|
||||
dirs: ComputerRunDirs;
|
||||
}) {
|
||||
return [
|
||||
`No room left on this computer: its workspace holds ${formatBytes({ bytes: used_bytes })} of ${formatBytes({ bytes: quota_bytes })}.`,
|
||||
`Nothing was written. Free space first with computer_bash: delete what you no longer need in ${dirs.bot_dir ?? dirs.cwd} (screenshots, downloads, old reports, raw dumps), or import what matters into your files and then remove it here.`,
|
||||
].join(" ");
|
||||
}
|
||||
|
||||
/**
|
||||
* The same, as a line added to a `computer_bash` result: that command can
|
||||
* write anything the agent never sees, so it is reported rather than
|
||||
* refused.
|
||||
*/
|
||||
export function computerWorkspaceFullNote({
|
||||
used_bytes,
|
||||
quota_bytes,
|
||||
dirs,
|
||||
}: {
|
||||
used_bytes: number;
|
||||
quota_bytes: number;
|
||||
dirs: ComputerRunDirs;
|
||||
}) {
|
||||
return `[This computer's workspace now holds ${formatBytes({ bytes: used_bytes })} of ${formatBytes({ bytes: quota_bytes })}: writes through computer_write_file and computer_edit_file are refused until there is room. Free space in ${dirs.bot_dir ?? dirs.cwd} (screenshots, downloads, old reports, raw dumps), or import what matters into your files and remove it here.]`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the workspace has passed its limit, and the message saying so, or
|
||||
* null while it has room or the install sets no limit.
|
||||
*/
|
||||
export async function computerWorkspaceFullWarning({ computer, dirs, signal }: Omit<Params, "incoming_bytes">) {
|
||||
const quota_bytes = await grabComputerWorkspaceQuotaBytes();
|
||||
|
||||
if (quota_bytes <= 0) return null;
|
||||
|
||||
const usage = await grabComputerUsage({ computer, signal }).catch(() => null);
|
||||
|
||||
if (!usage) return null;
|
||||
if (workspaceHasRoom({ used_bytes: usage.used_bytes, quota_bytes, incoming_bytes: 0 })) return null;
|
||||
|
||||
return computerWorkspaceFullNote({ used_bytes: usage.used_bytes, quota_bytes, dirs });
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import writeComputerFile from "@/src/functions/backend/computers/write-computer-
|
||||
import { resolveComputerPath } from "@/src/utils/computer-work-dirs";
|
||||
import type { HarnessTool } from "../../types";
|
||||
import type { ComputerToolContext } from "./computer-tool-context";
|
||||
import computerWorkspaceRoomError from "./computer-workspace-room";
|
||||
|
||||
type Args = {
|
||||
path: string;
|
||||
@@ -24,6 +25,15 @@ export default function computerWriteFileTool({ computer, dirs }: ComputerToolCo
|
||||
}),
|
||||
run: async ({ args, signal }) => {
|
||||
const path = resolveComputerPath({ path: args.path, dirs });
|
||||
const too_big = await computerWorkspaceRoomError({
|
||||
computer,
|
||||
dirs,
|
||||
incoming_bytes: Buffer.byteLength(args.content, "utf8"),
|
||||
signal,
|
||||
});
|
||||
|
||||
if (too_big) return too_big;
|
||||
|
||||
const written = await writeComputerFile({ computer, path, content: args.content, run_as: dirs.run_as, signal });
|
||||
|
||||
return `Wrote ${path} (${written.size} bytes).`;
|
||||
|
||||
@@ -5,6 +5,7 @@ import type { ComputerApi } from "@/src/functions/backend/computers/computer-fet
|
||||
import browserOutputText from "@/src/utils/browser-output-text";
|
||||
import type { ComputerRunDirs } from "@/src/utils/computer-work-dirs";
|
||||
import type { HarnessTool } from "../../types";
|
||||
import { computerWorkspaceFullWarning } from "./computer-workspace-room";
|
||||
|
||||
type Params = {
|
||||
tool: HarnessTool;
|
||||
@@ -20,6 +21,11 @@ type Params = {
|
||||
* downloading (`AppData.ComputerBrowserDownloadsDir`) are moved into the
|
||||
* run's `downloads` folder, so `import_file` and the shell reach them, and
|
||||
* the result says where; one still downloading is named, for a later call.
|
||||
*
|
||||
* A call that wrote into those folders (a screenshot saved by name, a
|
||||
* download) also says when the computer's workspace has passed its limit
|
||||
* (`computerWorkspaceFullWarning`): browser output is where most of a
|
||||
* computer's disk goes, and nothing refuses it on the way in.
|
||||
*/
|
||||
export default function withBrowserOutputs({ tool, computer, dirs }: Params): HarnessTool {
|
||||
const output_dir = AppData.ComputerBrowserOutputDir;
|
||||
@@ -38,7 +44,17 @@ export default function withBrowserOutputs({ tool, computer, dirs }: Params): Ha
|
||||
...moved.map(({ name, path }) => `- Downloaded file ${name} to "${path}"`),
|
||||
...pending.map((name) => `- Still downloading ${name}: it will be moved to ${downloads_dir} after a later browser call`),
|
||||
];
|
||||
const next = lines.length ? `${text}\n### Downloads\n${lines.join("\n")}` : text;
|
||||
const wrote =
|
||||
moved.length > 0 ||
|
||||
(typeof args.filename == "string" && Boolean(args.filename.trim()));
|
||||
const full = wrote
|
||||
? await computerWorkspaceFullWarning({ computer, dirs, signal }).catch(() => null)
|
||||
: null;
|
||||
const parts = [lines.length ? `${text}\n### Downloads\n${lines.join("\n")}` : text];
|
||||
|
||||
if (full) parts.push(full);
|
||||
|
||||
const next = parts.join("\n\n");
|
||||
|
||||
return typeof output == "string" ? next : { ...output, text: next };
|
||||
},
|
||||
|
||||
@@ -62,16 +62,19 @@ describe("withComputerDirs", () => {
|
||||
});
|
||||
});
|
||||
|
||||
const workerCaches = `XDG_CACHE_HOME='/home/cb-3/.cache' npm_config_cache='/home/cb-3/.cache/npm' PIP_CACHE_DIR='/home/cb-3/.cache/pip' BUN_INSTALL_CACHE_DIR='/home/cb-3/.cache/bun' PYTHONPYCACHEPREFIX='/home/cb-3/.cache/pycache'`;
|
||||
const coordinatorCaches = `XDG_CACHE_HOME='/home/gem/.cache' npm_config_cache='/home/gem/.cache/npm' PIP_CACHE_DIR='/home/gem/.cache/pip' BUN_INSTALL_CACHE_DIR='/home/gem/.cache/bun' PYTHONPYCACHEPREFIX='/home/gem/.cache/pycache'`;
|
||||
|
||||
describe("computerDirsShell", () => {
|
||||
test("a worker's: its umask, the shared link put back, its folder, moved in, installs into its home", () => {
|
||||
expect(computerDirsShell({ dirs })).toBe(
|
||||
`umask 007 && { [ -e '${shared}' ] || [ -L '${shared}' ] || { mkdir -p '/home/cb-3/workspace/workspaces' && ln -s '/home/gem/workspace/workspaces/2' '${shared}'; }; } && mkdir -p '${cwd}' && cd '${cwd}' && export HOME='${cwd}' && export PATH="$HOME/.local/bin:$PATH" NPM_CONFIG_PREFIX="$HOME/.local"; `,
|
||||
`umask 007 && { [ -e '${shared}' ] || [ -L '${shared}' ] || { mkdir -p '/home/cb-3/workspace/workspaces' && ln -s '/home/gem/workspace/workspaces/2' '${shared}'; }; } && mkdir -p '${cwd}' '/home/cb-3/.cache' && cd '${cwd}' && export HOME='${cwd}' ${workerCaches} && export PATH="$HOME/.local/bin:$PATH" NPM_CONFIG_PREFIX="$HOME/.local"; `,
|
||||
);
|
||||
});
|
||||
|
||||
test("a worker outside a workspace: no shared link", () => {
|
||||
expect(computerDirsShell({ dirs: computerRunDirs({ bot_id: 3, user_id: 7 }) })).toBe(
|
||||
`umask 007 && mkdir -p '${cwd}' && cd '${cwd}' && export HOME='${cwd}' && export PATH="$HOME/.local/bin:$PATH" NPM_CONFIG_PREFIX="$HOME/.local"; `,
|
||||
`umask 007 && mkdir -p '${cwd}' '/home/cb-3/.cache' && cd '${cwd}' && export HOME='${cwd}' ${workerCaches} && export PATH="$HOME/.local/bin:$PATH" NPM_CONFIG_PREFIX="$HOME/.local"; `,
|
||||
);
|
||||
});
|
||||
|
||||
@@ -79,7 +82,15 @@ describe("computerDirsShell", () => {
|
||||
const coordinator = computerRunDirs({ bot_id: 1, bot_kind: "coordinator", user_id: 7 });
|
||||
|
||||
expect(computerDirsShell({ dirs: coordinator })).toBe(
|
||||
`mkdir -p '/home/gem/workspace/bots/1/users/7' && cd '/home/gem/workspace/bots/1/users/7' && export HOME='/home/gem/workspace/bots/1/users/7'; `,
|
||||
`mkdir -p '/home/gem/workspace/bots/1/users/7' '/home/gem/.cache' && cd '/home/gem/workspace/bots/1/users/7' && export HOME='/home/gem/workspace/bots/1/users/7' ${coordinatorCaches}; `,
|
||||
);
|
||||
});
|
||||
|
||||
test("a run's caches go to the account's own home, never into its folder", () => {
|
||||
const shell = computerDirsShell({ dirs: computerRunDirs({ bot_id: 3, user_id: 7 }) });
|
||||
|
||||
expect(shell).toContain("XDG_CACHE_HOME='/home/cb-3/.cache'");
|
||||
expect(shell).not.toContain(`XDG_CACHE_HOME='${cwd}'`);
|
||||
expect(shell).not.toContain(`PIP_CACHE_DIR='${cwd}'`);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -58,11 +58,27 @@ describe("runToolCall", () => {
|
||||
expect(await call("fail", "")).toBe("Error: disk full");
|
||||
});
|
||||
|
||||
test("cuts long results", async () => {
|
||||
test("cuts long results, keeping their start and their end", async () => {
|
||||
const long = "x".repeat(AppData.HarnessToolResultMaxChars + 5);
|
||||
const result = await call("echo", JSON.stringify({ text: long }));
|
||||
|
||||
expect(result).toEndWith("[Cut: 5 more characters.]");
|
||||
expect(result).toContain("[... 5 characters left out. ...]");
|
||||
expect(result).toStartWith("x".repeat(100));
|
||||
expect(result).toEndWith("x".repeat(100));
|
||||
expect(result.length).toBeLessThanOrEqual(AppData.HarnessToolResultMaxChars);
|
||||
});
|
||||
|
||||
test("keeps the end of a long command's output, where its totals are", async () => {
|
||||
/**
|
||||
* A `du`/`find` sweep: the biggest entries and the sum are on the
|
||||
* last lines, so a head-only cut made each run re-run it.
|
||||
*/
|
||||
const sweep = `${"4.0K\t/usr/lib/x\n".repeat(4000)}112G\t/home/gem/workspace\n`;
|
||||
const result = await call("echo", JSON.stringify({ text: sweep }));
|
||||
|
||||
expect(result).toStartWith("4.0K");
|
||||
expect(result).toContain("characters left out");
|
||||
expect(result).toEndWith("112G\t/home/gem/workspace\n");
|
||||
});
|
||||
|
||||
test("cuts a browser tool's result sooner, saying how to see the rest", async () => {
|
||||
@@ -74,14 +90,16 @@ describe("runToolCall", () => {
|
||||
signal,
|
||||
});
|
||||
|
||||
expect(text).toStartWith("x".repeat(AppData.HarnessBrowserResultMaxChars) + "\n[Cut: 7 more characters.");
|
||||
expect(text).toStartWith("x".repeat(100));
|
||||
expect(text).toContain("[... 7 characters left out. ...]");
|
||||
expect(text).toContain("Narrow the call");
|
||||
expect(text).toEndWith("x".repeat(100));
|
||||
});
|
||||
|
||||
test("passes images on, capped and marked as a tool's", async () => {
|
||||
const result = await run("shot", "{}");
|
||||
|
||||
expect(result.text).toEndWith("[Cut: 5 more characters.]");
|
||||
expect(result.text).toContain("[... 5 characters left out. ...]");
|
||||
expect(result.images).toHaveLength(AppData.HarnessToolMaxImages);
|
||||
expect(result.images[0]).toEqual({
|
||||
url: "data:image/png;base64,0",
|
||||
|
||||
@@ -8,6 +8,11 @@ import unknownToolArgs from "./unknown-tool-args";
|
||||
import unknownToolMessage from "./unknown-tool-message";
|
||||
import type { HarnessTool, HarnessToolCall, HarnessToolImage } from "../types";
|
||||
|
||||
/**
|
||||
* Share of a cut result given to its start; the rest keeps its end.
|
||||
*/
|
||||
const TruncateHeadShare = 0.5;
|
||||
|
||||
type Params = {
|
||||
call: HarnessToolCall;
|
||||
tools: HarnessTool[];
|
||||
@@ -102,9 +107,13 @@ async function runTool({ call, tools, signal }: Params) {
|
||||
}
|
||||
|
||||
/**
|
||||
* A result past its tool's cap is cut there. Browser tools get the
|
||||
* smaller cap: a page snapshot or an evaluate over a whole page was the
|
||||
* heaviest thing a run kept resending.
|
||||
* A result past its tool's cap is cut there, keeping its start and its
|
||||
* end: a command's answer and the totals or error it ends with are the
|
||||
* parts worth reading, and a head-only cut once threw away the end of
|
||||
* every long `du`/`find` sweep, so runs re-ran the command to see it. The
|
||||
* note between them says what was left out. Browser tools get the smaller
|
||||
* cap: a page snapshot or an evaluate over a whole page was the heaviest
|
||||
* thing a run kept resending.
|
||||
*/
|
||||
function truncate({ text, name }: { text: string; name: string }) {
|
||||
const browser = isBrowserTool({ name });
|
||||
@@ -112,5 +121,15 @@ function truncate({ text, name }: { text: string; name: string }) {
|
||||
|
||||
if (text.length <= max) return text;
|
||||
|
||||
return `${text.slice(0, max)}\n[Cut: ${text.length - max} more characters.${browser ? " Narrow the call (a selector, an element ref, a smaller evaluate) to see the rest." : ""}]`;
|
||||
const hint = browser ? " Narrow the call (a selector, an element ref, a smaller evaluate) to see the rest." : "";
|
||||
/**
|
||||
* Sized before the two ends are cut, so the whole result stays inside
|
||||
* the cap instead of the note pushing it over.
|
||||
*/
|
||||
const note = `\n\n[... ${text.length - max} characters left out. ...]${hint}\n\n`;
|
||||
const room = Math.max(0, max - note.length);
|
||||
const head = Math.floor(room * TruncateHeadShare);
|
||||
const tail = room - head;
|
||||
|
||||
return `${text.slice(0, head)}${note}${text.slice(-tail)}`;
|
||||
}
|
||||
|
||||
@@ -1,18 +1,30 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
|
||||
/**
|
||||
* Changes after a reason the socket may have died: the browser went back
|
||||
* online, the page was restored, or a hidden tab became visible again.
|
||||
* online, the page was restored, a hidden tab became visible again, or
|
||||
* another window was focused (a phone locked while the socket closed).
|
||||
* twui's `useWebSocket` gives up after three attempts, so the socket is
|
||||
* remounted instead of waiting for a reload.
|
||||
* remounted instead of waiting for a reload. A second trigger within
|
||||
* `AppData.RefocusGapMs` is the same return.
|
||||
*/
|
||||
export default function useConnectionEpoch() {
|
||||
const [epoch, setEpoch] = useState(0);
|
||||
|
||||
useEffect(() => {
|
||||
const bump = () => setEpoch((value) => value + 1);
|
||||
let last = 0;
|
||||
|
||||
const bump = () => {
|
||||
const now = Date.now();
|
||||
|
||||
if (now - last < AppData.RefocusGapMs) return;
|
||||
|
||||
last = now;
|
||||
setEpoch((value) => value + 1);
|
||||
};
|
||||
|
||||
const onVisible = () => {
|
||||
if (document.visibilityState == "visible") bump();
|
||||
@@ -20,11 +32,13 @@ export default function useConnectionEpoch() {
|
||||
|
||||
window.addEventListener("online", bump);
|
||||
window.addEventListener("pageshow", bump);
|
||||
window.addEventListener("focus", bump);
|
||||
document.addEventListener("visibilitychange", onVisible);
|
||||
|
||||
return () => {
|
||||
window.removeEventListener("online", bump);
|
||||
window.removeEventListener("pageshow", bump);
|
||||
window.removeEventListener("focus", bump);
|
||||
document.removeEventListener("visibilitychange", onVisible);
|
||||
};
|
||||
}, []);
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
import { useState } from "react";
|
||||
import { useEffect, useState } from "react";
|
||||
import type { BUN_SQLITE_COBBLE_BOT_MESSAGES, BUN_SQLITE_COBBLE_BOTS } from "@/db/types/db";
|
||||
import { LiveCrewRefreshedEvent } from "@/src/functions/frontend/announce-live-crew";
|
||||
import type {
|
||||
BotCreatedData,
|
||||
BotRemovedData,
|
||||
BotUpdatedData,
|
||||
BotWithLastMessage,
|
||||
LiveCrewRefreshedDetail,
|
||||
} from "@/src/types";
|
||||
import useServerEvent from "./use-server-event";
|
||||
|
||||
@@ -23,7 +25,10 @@ type Params = {
|
||||
|
||||
/**
|
||||
* The crew, kept current from server pushes: faces and status lines,
|
||||
* latest messages, and unread for conversations that aren't open.
|
||||
* latest messages, and unread for conversations that aren't open. A task
|
||||
* step's push never reaches a page that was in the background, so the
|
||||
* whole list is also read again when the user comes back
|
||||
* (`cobble:live-crew-refreshed`).
|
||||
*/
|
||||
export default function useLiveBots({ bots, open_bot_id, workspace_id = null }: Params) {
|
||||
const [live, setLive] = useState(bots);
|
||||
@@ -132,5 +137,30 @@ export default function useLiveBots({ bots, open_bot_id, workspace_id = null }:
|
||||
},
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
const onRefresh = (event: Event) => {
|
||||
const detail = (event as CustomEvent<LiveCrewRefreshedDetail>).detail;
|
||||
|
||||
if (!detail) return;
|
||||
|
||||
/**
|
||||
* The list read for another place: this one keeps what it has.
|
||||
*/
|
||||
if ((detail.workspace_id || null) != (workspace_id ? Number(workspace_id) : null)) {
|
||||
return;
|
||||
}
|
||||
|
||||
setLive(
|
||||
detail.bots.map((bot) =>
|
||||
bot.id == open_bot_id ? { ...bot, unread: 0 } : bot,
|
||||
),
|
||||
);
|
||||
};
|
||||
|
||||
window.addEventListener(LiveCrewRefreshedEvent, onRefresh);
|
||||
|
||||
return () => window.removeEventListener(LiveCrewRefreshedEvent, onRefresh);
|
||||
}, [workspace_id, open_bot_id]);
|
||||
|
||||
return live;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useRef } from "react";
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
|
||||
type Params = {
|
||||
onRefocus: () => void;
|
||||
};
|
||||
|
||||
/**
|
||||
* Calls `onRefocus` when the user comes back to the page: another window
|
||||
* was focused, or a hidden tab (a phone, a notification tapped) became
|
||||
* visible again. Pushes that arrived while the page was in the background
|
||||
* never reach it, so what it shows may be stale until it reads it again.
|
||||
* A window regaining focus and its tab becoming visible are often one
|
||||
* return (a phone brings the page back and focuses it), and each may fire
|
||||
* more than once, so a second call within `AppData.RefocusGapMs` is the
|
||||
* same return.
|
||||
*/
|
||||
export default function useRefocus({ onRefocus }: Params) {
|
||||
const handler = useRef(onRefocus);
|
||||
|
||||
handler.current = onRefocus;
|
||||
|
||||
useEffect(() => {
|
||||
let last = 0;
|
||||
|
||||
const refresh = () => {
|
||||
const now = Date.now();
|
||||
|
||||
if (now - last < AppData.RefocusGapMs) return;
|
||||
|
||||
last = now;
|
||||
handler.current();
|
||||
};
|
||||
|
||||
const onVisible = () => {
|
||||
if (document.visibilityState == "visible") refresh();
|
||||
};
|
||||
|
||||
window.addEventListener("focus", refresh);
|
||||
document.addEventListener("visibilitychange", onVisible);
|
||||
|
||||
return () => {
|
||||
window.removeEventListener("focus", refresh);
|
||||
document.removeEventListener("visibilitychange", onVisible);
|
||||
};
|
||||
}, []);
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
import fetchApi from "@moduletrace/twui/utils/fetch/fetchApi";
|
||||
import type { APIResponseObject } from "@moduletrace/bunext/types";
|
||||
import type { LiveCrewRequest } from "@/src/schemas/bot-schema";
|
||||
import type { LiveCrewPayload } from "@/src/types";
|
||||
|
||||
/**
|
||||
* The rail's crew as it stands now: the bots in a workspace or the bots'
|
||||
* own chats (`workspace_id`), and the user's workspaces.
|
||||
*/
|
||||
export default async function fetchLiveCrew({ workspace_id }: LiveCrewRequest) {
|
||||
return await fetchApi<LiveCrewRequest, APIResponseObject<LiveCrewPayload>>(
|
||||
`/api/admin/bots/live-crew`,
|
||||
{
|
||||
method: "POST",
|
||||
body: { workspace_id },
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
import { useCallback, useEffect } from "react";
|
||||
import announceLiveCrew from "@/src/functions/frontend/announce-live-crew";
|
||||
import { LiveCrewRefreshRequestedEvent } from "@/src/functions/frontend/request-live-crew-refresh";
|
||||
import useRefocus from "@/src/hooks/use-refocus";
|
||||
import fetchLiveCrew from "../(functions)/fetch-live-crew";
|
||||
|
||||
type Params = {
|
||||
/**
|
||||
* The workspace the rail lists a crew for, or null for the bots' own
|
||||
* chats (`railWorkspaceId`).
|
||||
*/
|
||||
workspace_id: number | null;
|
||||
};
|
||||
|
||||
/**
|
||||
* Reads the rail's crew again when the user comes back to the page
|
||||
* (`useRefocus`), or when a page asks for it (`requestLiveCrewRefresh`,
|
||||
* the thread's pull-to-reload): faces and status lines, latest messages,
|
||||
* unread marks and the workspaces, all as they stand now. It lives in the
|
||||
* layout, so every page under it keeps the rail current without each list
|
||||
* holding its own copy. The lists take the result through
|
||||
* `cobble:live-crew-refreshed`.
|
||||
*/
|
||||
export default function useLiveCrewRefresh({ workspace_id }: Params) {
|
||||
const refresh = useCallback(async () => {
|
||||
const res = await fetchLiveCrew({ workspace_id }).catch(() => null);
|
||||
|
||||
if (!res?.success || !res.singleRes) return;
|
||||
|
||||
announceLiveCrew({
|
||||
workspace_id,
|
||||
bots: res.singleRes.bots,
|
||||
workspaces: res.singleRes.workspaces,
|
||||
});
|
||||
}, [workspace_id]);
|
||||
|
||||
useRefocus({ onRefocus: () => void refresh() });
|
||||
|
||||
useEffect(() => {
|
||||
window.addEventListener(LiveCrewRefreshRequestedEvent, refresh);
|
||||
|
||||
return () => window.removeEventListener(LiveCrewRefreshRequestedEvent, refresh);
|
||||
}, [refresh]);
|
||||
}
|
||||
@@ -1,7 +1,9 @@
|
||||
import { useState } from "react";
|
||||
import { useEffect, useState } from "react";
|
||||
import type { BUN_SQLITE_COBBLE_BOT_MESSAGES } from "@/db/types/db";
|
||||
import { LiveCrewRefreshedEvent } from "@/src/functions/frontend/announce-live-crew";
|
||||
import useServerEvent from "@/src/hooks/use-server-event";
|
||||
import type {
|
||||
LiveCrewRefreshedDetail,
|
||||
WorkspaceCreatedData,
|
||||
WorkspaceRemovedData,
|
||||
WorkspaceUpdatedData,
|
||||
@@ -19,7 +21,8 @@ type Params = {
|
||||
/**
|
||||
* The user's workspaces, marked unread as bot messages arrive in them and
|
||||
* kept current when one is created (a bot can create one, so it shows
|
||||
* without a reload).
|
||||
* without a reload). Read again as a whole when the user comes back
|
||||
* (`cobble:live-crew-refreshed`), like the bots' list.
|
||||
*/
|
||||
export default function useLiveWorkspaces({ workspaces, open_workspace_id }: Params) {
|
||||
const [live, setLive] = useState(workspaces);
|
||||
@@ -72,5 +75,25 @@ export default function useLiveWorkspaces({ workspaces, open_workspace_id }: Par
|
||||
},
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
const onRefresh = (event: Event) => {
|
||||
const detail = (event as CustomEvent<LiveCrewRefreshedDetail>).detail;
|
||||
|
||||
if (!detail?.workspaces) return;
|
||||
|
||||
setLive(
|
||||
detail.workspaces.map((workspace) =>
|
||||
Number(workspace.id) == open_workspace_id
|
||||
? { ...workspace, unread: 0 }
|
||||
: workspace,
|
||||
),
|
||||
);
|
||||
};
|
||||
|
||||
window.addEventListener(LiveCrewRefreshedEvent, onRefresh);
|
||||
|
||||
return () => window.removeEventListener(LiveCrewRefreshedEvent, onRefresh);
|
||||
}, [open_workspace_id]);
|
||||
|
||||
return live;
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ import Stack from "@moduletrace/twui/layout/Stack";
|
||||
import { AppContext } from "@/src/pages/__root";
|
||||
import useLiveBots from "@/src/hooks/use-live-bots";
|
||||
import useLiveWorkspaces from "../(hooks)/use-live-workspaces";
|
||||
import railWorkspaceId from "../(utils)/rail-workspace-id";
|
||||
import { RailPages } from "@/src/dict/rail-pages-dict";
|
||||
import { RailDrawerContext } from "../(data)/rail-drawer-context";
|
||||
import RailHeader from "../(partials)/rail-header";
|
||||
@@ -38,20 +39,17 @@ export default function BotsRail() {
|
||||
Boolean(pathname?.startsWith(`${page.url}/`)),
|
||||
);
|
||||
const workspace = pageProps?.workspace;
|
||||
const in_workspace = Boolean(
|
||||
workspace?.id && pathname?.startsWith("/admin/workspaces/"),
|
||||
);
|
||||
const workspace_id = railWorkspaceId({ workspace, pathname });
|
||||
const in_workspace = Boolean(workspace_id);
|
||||
|
||||
const bots = useLiveBots({
|
||||
bots: pageProps?.bots || [],
|
||||
open_bot_id: pageProps?.bot?.id || undefined,
|
||||
workspace_id: in_workspace ? workspace?.id || null : null,
|
||||
workspace_id,
|
||||
});
|
||||
const workspaces = useLiveWorkspaces({
|
||||
workspaces: pageProps?.workspaces || [],
|
||||
open_workspace_id: in_workspace
|
||||
? workspace?.id || undefined
|
||||
: undefined,
|
||||
open_workspace_id: workspace_id || undefined,
|
||||
});
|
||||
const live_workspace = workspaces.find((w) => w.id == workspace?.id);
|
||||
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import railWorkspaceId from "./rail-workspace-id";
|
||||
|
||||
describe("railWorkspaceId", () => {
|
||||
test("lists a workspace's crew on its own pages", () => {
|
||||
expect(
|
||||
railWorkspaceId({
|
||||
workspace: { id: 4 },
|
||||
pathname: "/admin/workspaces/4/chatrooms",
|
||||
}),
|
||||
).toBe(4);
|
||||
});
|
||||
|
||||
test("lists the bots' own chats elsewhere, even with a workspace at hand", () => {
|
||||
expect(
|
||||
railWorkspaceId({
|
||||
workspace: { id: 4 },
|
||||
pathname: "/admin/settings/general",
|
||||
}),
|
||||
).toBeNull();
|
||||
expect(
|
||||
railWorkspaceId({ workspace: { id: 4 }, pathname: "/admin/bots/2" }),
|
||||
).toBeNull();
|
||||
});
|
||||
|
||||
test("a workspace page with no workspace listed has no scope", () => {
|
||||
expect(
|
||||
railWorkspaceId({ workspace: null, pathname: "/admin/workspaces/4" }),
|
||||
).toBeNull();
|
||||
expect(railWorkspaceId({ workspace: { id: null }, pathname: null })).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,18 @@
|
||||
type Params = {
|
||||
workspace: { id?: number | string | null } | null | undefined;
|
||||
pathname: string | null | undefined;
|
||||
};
|
||||
|
||||
/**
|
||||
* The workspace the rail lists a crew for, or null for the bots' own
|
||||
* chats. `pageProps.workspace` alone can be set on a page outside
|
||||
* `/admin/workspaces/` (Settings keeps the last conversation's), and only
|
||||
* a workspace's own pages list its crew.
|
||||
*/
|
||||
export default function railWorkspaceId({ workspace, pathname }: Params) {
|
||||
const id = Number(workspace?.id) || 0;
|
||||
|
||||
if (!id || !pathname?.startsWith("/admin/workspaces/")) return null;
|
||||
|
||||
return id;
|
||||
}
|
||||
@@ -11,7 +11,9 @@ import BotsRail from "./(sections)/bots-rail";
|
||||
import LiveSocket from "./(sections)/live-socket";
|
||||
import AddFlow from "./(partials)/add-flow";
|
||||
import OfflineBanner from "./(partials)/offline-banner";
|
||||
import useLiveCrewRefresh from "./(hooks)/use-live-crew-refresh";
|
||||
import isRaillessPage from "./(utils)/is-railless-page";
|
||||
import railWorkspaceId from "./(utils)/rail-workspace-id";
|
||||
|
||||
/**
|
||||
* Full-bleed shell for every `/admin/*` page: the rail of bot conversations
|
||||
@@ -54,6 +56,14 @@ export default function BotsLayout({
|
||||
|
||||
const has_rail = !isRaillessPage({ pathname });
|
||||
|
||||
/**
|
||||
* The crew the rail lists, read again whenever the user comes back to
|
||||
* the page: pushes that never arrived leave it stale until a reload.
|
||||
*/
|
||||
const workspace_id = railWorkspaceId({ workspace: pageProps?.workspace, pathname });
|
||||
|
||||
useLiveCrewRefresh({ workspace_id });
|
||||
|
||||
const drawer = useMemo(
|
||||
() => ({ open: drawer_open, setOpen: setDrawerOpen, has_rail }),
|
||||
[drawer_open, has_rail],
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
import fetchApi from "@moduletrace/twui/utils/fetch/fetchApi";
|
||||
import type { APIResponseObject } from "@moduletrace/bunext/types";
|
||||
import type { MessageDetailsRequest } from "@/src/schemas/bot-schema";
|
||||
import type { MessageDetails } from "@/src/types";
|
||||
|
||||
type Params = {
|
||||
message_id: MessageDetailsRequest["message_id"];
|
||||
/**
|
||||
* Every call and failure, for the report's copy, not the first the
|
||||
* modal lists.
|
||||
*/
|
||||
full?: boolean;
|
||||
};
|
||||
|
||||
/**
|
||||
* How one of the bot's messages was generated. `full` reads every call
|
||||
* and failure it took, which the modal's copy of the report needs.
|
||||
*/
|
||||
export default async function fetchMessageDetails({ message_id, full }: Params) {
|
||||
const query = new URLSearchParams({ message_id: String(message_id) });
|
||||
|
||||
if (full) query.set("full", "1");
|
||||
|
||||
return await fetchApi<{}, APIResponseObject<MessageDetails>>(
|
||||
`/api/admin/bots/message-details?${query.toString()}`,
|
||||
{ method: "GET" },
|
||||
);
|
||||
}
|
||||
@@ -15,7 +15,9 @@ type Params = {
|
||||
* Loads the open conversation's history once the page is on screen, and
|
||||
* again whenever the browser restores the page from its back-forward
|
||||
* cache (`pageshow` with `persisted`), so going back never shows an old
|
||||
* thread. The page's `?session_id=` picks a session other than the
|
||||
* thread. `reload` reads it again without the loading line, for the
|
||||
* phone's pull-to-reload, which shows its own spinner. The page's
|
||||
* `?session_id=` picks a session other than the
|
||||
* active one, read on every load. Everything else on the page (the header, the composer) comes
|
||||
* from the server and shows at once. `loaded` turns true with the first
|
||||
* load; a conversation the user can no longer open sends them where the
|
||||
@@ -30,13 +32,15 @@ export default function useConversationHistory({ bot_id, workspace_id, onLoaded
|
||||
|
||||
on_loaded.current = onLoaded;
|
||||
|
||||
const load = async () => {
|
||||
const load = async ({ silent = false }: { silent?: boolean } = {}) => {
|
||||
if (!bot_id) return;
|
||||
|
||||
const id = ++request.current;
|
||||
|
||||
setLoading(true);
|
||||
setError(undefined);
|
||||
if (!silent) {
|
||||
setLoading(true);
|
||||
setError(undefined);
|
||||
}
|
||||
|
||||
const session_id =
|
||||
Number(new URLSearchParams(window.location.search).get("session_id")) || null;
|
||||
@@ -53,14 +57,19 @@ export default function useConversationHistory({ bot_id, workspace_id, onLoaded
|
||||
|
||||
const history = res?.success ? res.singleRes?.history : null;
|
||||
|
||||
setLoading(false);
|
||||
if (!silent) setLoading(false);
|
||||
|
||||
if (!history?.session?.id) {
|
||||
setError(res?.msg || "Couldn't load the conversation.");
|
||||
/**
|
||||
* A silent reload leaves the thread it couldn't read alone:
|
||||
* the pull's own control says it failed, not the page.
|
||||
*/
|
||||
if (!silent) setError(res?.msg || "Couldn't load the conversation.");
|
||||
return;
|
||||
}
|
||||
|
||||
on_loaded.current({ history });
|
||||
setError(undefined);
|
||||
setLoaded(true);
|
||||
};
|
||||
|
||||
@@ -75,5 +84,11 @@ export default function useConversationHistory({ bot_id, workspace_id, onLoaded
|
||||
return () => window.removeEventListener("pageshow", onPageShow);
|
||||
}, [bot_id, workspace_id]);
|
||||
|
||||
return { loading, loaded, error, retry: load };
|
||||
return {
|
||||
loading,
|
||||
loaded,
|
||||
error,
|
||||
retry: () => load(),
|
||||
reload: () => load({ silent: true }),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import fetchApi from "@moduletrace/twui/utils/fetch/fetchApi";
|
||||
import type { APIResponseObject } from "@moduletrace/bunext/types";
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import type { MessageDetails } from "@/src/types";
|
||||
import fetchMessageDetails from "../(functions)/fetch-message-details";
|
||||
|
||||
type Params = {
|
||||
message_id: number;
|
||||
@@ -24,10 +23,7 @@ export default function useMessageDetails({ message_id, enabled = true }: Params
|
||||
setLoading(true);
|
||||
setError(undefined);
|
||||
|
||||
const res = await fetchApi<{}, APIResponseObject<MessageDetails>>(
|
||||
`/api/admin/bots/message-details?message_id=${message_id}`,
|
||||
{ method: "GET" },
|
||||
).catch(() => null);
|
||||
const res = await fetchMessageDetails({ message_id }).catch(() => null);
|
||||
|
||||
setLoading(false);
|
||||
|
||||
|
||||
@@ -0,0 +1,254 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useRef, useState, type RefObject } from "react";
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
import minimumWait from "../(utils)/minimum-wait";
|
||||
import pullToRefreshState from "../(utils)/pull-to-refresh";
|
||||
/**
|
||||
* What the pull indicator shows: nothing yet, a pull that isn't far
|
||||
* enough, one that will reload on release, or a reload in flight.
|
||||
*/
|
||||
export type PullToRefreshState = "idle" | "pulling" | "ready" | "refreshing";
|
||||
|
||||
type Params = {
|
||||
/**
|
||||
* The thread's scrolling column.
|
||||
*/
|
||||
column_ref: RefObject<HTMLDivElement | null>;
|
||||
/**
|
||||
* The thread's content, which the pull moves up to open its room.
|
||||
*/
|
||||
content_ref: RefObject<HTMLDivElement | null>;
|
||||
/**
|
||||
* Whether the thread's content ends at the column's bottom right now:
|
||||
* only there does pulling up have nothing left of the conversation to
|
||||
* scroll, so the pull belongs to the app.
|
||||
*/
|
||||
at_bottom: () => boolean;
|
||||
/**
|
||||
* Reads the conversation again; the pull indicator stays up until it
|
||||
* finishes, and no less than a moment after.
|
||||
*/
|
||||
on_refresh: () => Promise<void> | void;
|
||||
};
|
||||
|
||||
/**
|
||||
* A phone gesture: touching the thread while it sits at its bottom and
|
||||
* dragging up lifts the newest message off the edge, opening room for a
|
||||
* refresh icon, since there is nothing newer to scroll to. Once the room is
|
||||
* as deep as it opens, the finger has to stay there for a moment before
|
||||
* letting go reloads: a thread whose scroll is already exhausted opens its
|
||||
* limit easily by accident, and the hold is what says the reload was meant.
|
||||
* The icon lights up when it is, and a release before that closes the room
|
||||
* and reloads nothing.
|
||||
*
|
||||
* Touches are read rather than `scrollTop`, whose sign a reversed column
|
||||
* reports differently across engines. Once the pull has started it owns the
|
||||
* gesture until the finger lifts: it is not interrupted by a scroll, a
|
||||
* resize or a text selection, so a press that is still down always shows
|
||||
* its icon, and the reload happens on release, never before.
|
||||
*
|
||||
* The room is written straight onto the content as the finger moves, never
|
||||
* through a render: a phone drags in steps of a couple of pixels, and
|
||||
* re-rendering a long thread that often would cost more than the gesture is
|
||||
* worth. Only the icon's few states go through state.
|
||||
*/
|
||||
export default function usePullToRefresh({
|
||||
column_ref,
|
||||
content_ref,
|
||||
at_bottom,
|
||||
on_refresh,
|
||||
}: Params) {
|
||||
const [state, setState] = useState<PullToRefreshState>("idle");
|
||||
const refresh = useRef(on_refresh);
|
||||
const bottom = useRef(at_bottom);
|
||||
|
||||
refresh.current = on_refresh;
|
||||
bottom.current = at_bottom;
|
||||
|
||||
useEffect(() => {
|
||||
const column = column_ref.current;
|
||||
const content = content_ref.current;
|
||||
|
||||
if (!column) return;
|
||||
|
||||
let start_y: number | null = null;
|
||||
/** The pull has begun: it runs to the release regardless. */
|
||||
let engaged = false;
|
||||
/** The room has stayed full long enough: letting go now reloads. */
|
||||
let armed = false;
|
||||
/** When the room last became full, while the finger holds it there. */
|
||||
let held_since: number | null = null;
|
||||
let held_timer: ReturnType<typeof setTimeout> | null = null;
|
||||
let busy = false;
|
||||
|
||||
/**
|
||||
* The content is moved up, never resized: the thread follows its
|
||||
* content's size by jumping back to the bottom, and a padding that
|
||||
* grew under the finger would send it there mid-pull.
|
||||
*/
|
||||
const setRoom = (distance: number) => {
|
||||
if (!content) return;
|
||||
|
||||
content.style.transform = distance > 0 ? `translate3d(0, -${distance}px, 0)` : "";
|
||||
};
|
||||
|
||||
/**
|
||||
* A drag over a message selects its text, in the emulated and real
|
||||
* touch alike, and the selection would grow while the thread is
|
||||
* lifted away from the finger. It is taken out of the way once a
|
||||
* pull has begun, since the pull is what this finger is doing.
|
||||
*/
|
||||
const holdSelection = (held: boolean) => {
|
||||
if (!content) return;
|
||||
|
||||
content.style.userSelect = held ? "none" : "";
|
||||
|
||||
if (held) window.getSelection()?.removeAllRanges();
|
||||
};
|
||||
|
||||
/**
|
||||
* The room is full: the hold that makes it a reload starts, or is
|
||||
* already running. A finger that rests on the limit fires no further
|
||||
* touches, so the timer is what notices the hold, not the moves.
|
||||
*/
|
||||
const beginHold = () => {
|
||||
if (held_since != null) return;
|
||||
|
||||
held_since = Date.now();
|
||||
held_timer = setTimeout(() => {
|
||||
held_timer = null;
|
||||
|
||||
if (held_since == null) return;
|
||||
|
||||
armed = true;
|
||||
setState("ready");
|
||||
}, AppData.PullToRefreshHoldMs);
|
||||
};
|
||||
|
||||
/** Not full any more: the hold starts again from nothing. */
|
||||
const dropHold = () => {
|
||||
held_since = null;
|
||||
armed = false;
|
||||
|
||||
if (held_timer == null) return;
|
||||
|
||||
clearTimeout(held_timer);
|
||||
held_timer = null;
|
||||
};
|
||||
|
||||
const reset = () => {
|
||||
start_y = null;
|
||||
engaged = false;
|
||||
dropHold();
|
||||
setRoom(0);
|
||||
holdSelection(false);
|
||||
setState("idle");
|
||||
};
|
||||
|
||||
const onStart = (event: TouchEvent) => {
|
||||
start_y = null;
|
||||
engaged = false;
|
||||
dropHold();
|
||||
|
||||
if (busy || event.touches.length != 1) return;
|
||||
if (!bottom.current()) return;
|
||||
|
||||
start_y = event.touches[0]?.clientY ?? null;
|
||||
};
|
||||
|
||||
const onMove = (event: TouchEvent) => {
|
||||
if (busy || start_y == null) return;
|
||||
|
||||
const current_y = event.touches[0]?.clientY;
|
||||
|
||||
if (current_y == undefined || event.touches.length != 1) {
|
||||
/**
|
||||
* A move that arrives without its touch holds no finger
|
||||
* position; the release's own event is on its way, and it
|
||||
* is that one that decides.
|
||||
*/
|
||||
if (!event.touches.length) return;
|
||||
|
||||
reset();
|
||||
return;
|
||||
}
|
||||
|
||||
if (!engaged) {
|
||||
if (!bottom.current()) {
|
||||
reset();
|
||||
return;
|
||||
}
|
||||
|
||||
if (pullToRefreshState({ start_y, current_y }).pulling) {
|
||||
engaged = true;
|
||||
holdSelection(true);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A finger dragged back down before it was let go takes the
|
||||
* room back down with it and hides the icon at the very travel
|
||||
* that showed it, so the pull reads the same in either
|
||||
* direction. The gesture stays its own until the release, and
|
||||
* a hold that has not finished yet starts over from nothing.
|
||||
*/
|
||||
const pulled = pullToRefreshState({ start_y, current_y });
|
||||
|
||||
if (pulled.ready) beginHold();
|
||||
else dropHold();
|
||||
|
||||
setRoom(pulled.distance);
|
||||
setState(armed ? "ready" : pulled.pulling ? "pulling" : "idle");
|
||||
};
|
||||
|
||||
const onEnd = async () => {
|
||||
if (busy) return;
|
||||
|
||||
const reload = engaged && armed;
|
||||
|
||||
start_y = null;
|
||||
engaged = false;
|
||||
dropHold();
|
||||
|
||||
if (!reload) {
|
||||
reset();
|
||||
return;
|
||||
}
|
||||
|
||||
busy = true;
|
||||
/**
|
||||
* The room it was let go at stays open while it reloads, so
|
||||
* nothing moves under the finger that just lifted.
|
||||
*/
|
||||
setState("refreshing");
|
||||
|
||||
try {
|
||||
await minimumWait({
|
||||
task: (async () => refresh.current())(),
|
||||
minimum_ms: AppData.PullToRefreshMinLoadingMs,
|
||||
});
|
||||
} finally {
|
||||
busy = false;
|
||||
reset();
|
||||
}
|
||||
};
|
||||
|
||||
column.addEventListener("touchstart", onStart, { passive: true });
|
||||
column.addEventListener("touchmove", onMove, { passive: true });
|
||||
column.addEventListener("touchend", onEnd);
|
||||
column.addEventListener("touchcancel", reset);
|
||||
|
||||
return () => {
|
||||
column.removeEventListener("touchstart", onStart);
|
||||
column.removeEventListener("touchmove", onMove);
|
||||
column.removeEventListener("touchend", onEnd);
|
||||
column.removeEventListener("touchcancel", reset);
|
||||
dropHold();
|
||||
setRoom(0);
|
||||
holdSelection(false);
|
||||
};
|
||||
}, [column_ref, content_ref]);
|
||||
|
||||
return state;
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useEffect, useRef } from "react";
|
||||
import { useCallback, useEffect, useRef } from "react";
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
import type {
|
||||
BotMessageWithAttachments,
|
||||
@@ -6,6 +6,7 @@ import type {
|
||||
WebSocketDataType,
|
||||
} from "@/src/types";
|
||||
import postSessionApi from "@/src/functions/frontend/post-session-api";
|
||||
import useRefocus from "@/src/hooks/use-refocus";
|
||||
|
||||
type Params = {
|
||||
session_id?: number | null;
|
||||
@@ -20,73 +21,83 @@ type Params = {
|
||||
};
|
||||
|
||||
/**
|
||||
* While a reply is due, checks the session's latest messages every
|
||||
* `AppData.BotReplyCatchUpMs`. Replies arrive live; this only catches one
|
||||
* whose push was missed (the socket was down at the time), so the
|
||||
* thinking row can't stay up until a reload. It also checks at once when
|
||||
* the page comes back into view or online. A missed message is replayed
|
||||
* as the `server:bot-message` it would have been, so the thread, the rail
|
||||
* and the unread flag all take it the usual way. The bot's face, status
|
||||
* line and active task are replayed too, as `server:bot-updated`, so a
|
||||
* Keeps the thread from waiting on a push that never came: every return to
|
||||
* the page (`useRefocus`) reads the session's latest messages and the
|
||||
* bot's face, status line and active task, and while a reply is due it
|
||||
* does so every `AppData.BotReplyCatchUpMs` too. A missed message is
|
||||
* replayed as the `server:bot-message` it would have been, so the thread,
|
||||
* the rail and the unread flag all take it the usual way. The bot's face,
|
||||
* status line and active task are replayed as `server:bot-updated`, so a
|
||||
* reply that ended without a final message (its face push missed) can't
|
||||
* leave the bot working on screen.
|
||||
* leave the bot thinking or a finished task on screen. Reading it even
|
||||
* when no reply is due is what lets a row stuck on a stale face or task
|
||||
* clear itself without a reload.
|
||||
*/
|
||||
export default function useReplyCatchUp({ session_id, awaiting_reply, last_message_id }: Params) {
|
||||
const last_message = useRef(Number(last_message_id) || 0);
|
||||
/**
|
||||
* The open session: a read that lands after the thread moved to
|
||||
* another one is dropped instead of replaying into the wrong thread.
|
||||
*/
|
||||
const open_session = useRef(session_id);
|
||||
|
||||
last_message.current = Number(last_message_id) || 0;
|
||||
open_session.current = session_id;
|
||||
|
||||
useEffect(() => {
|
||||
if (!awaiting_reply || !session_id) return;
|
||||
const check = useCallback(async () => {
|
||||
if (!session_id) return;
|
||||
|
||||
let stale = false;
|
||||
const res = (await postSessionApi<BotMessageWithAttachments>({
|
||||
path: "session-messages",
|
||||
body: { session_id },
|
||||
}).catch(() => null)) as SessionMessagesResponse | null;
|
||||
|
||||
if (open_session.current != session_id) return;
|
||||
if (!res?.success || !Array.isArray(res.payload)) return;
|
||||
|
||||
const replay = ({ data }: { data: WebSocketDataType }) =>
|
||||
window.dispatchEvent(new CustomEvent("wsDataEvent", { detail: { data, message: data } }));
|
||||
|
||||
const check = async () => {
|
||||
const res = (await postSessionApi<BotMessageWithAttachments>({
|
||||
path: "session-messages",
|
||||
body: { session_id },
|
||||
}).catch(() => null)) as SessionMessagesResponse | null;
|
||||
const missed = res.payload.filter(
|
||||
(message) => Number(message.id) > last_message.current,
|
||||
);
|
||||
|
||||
if (stale || !res?.success || !Array.isArray(res.payload)) return;
|
||||
|
||||
const missed = res.payload.filter(
|
||||
(message) => Number(message.id) > last_message.current,
|
||||
);
|
||||
|
||||
for (const message of missed) {
|
||||
replay({ data: { event: "server:bot-message", data: message } });
|
||||
}
|
||||
|
||||
/**
|
||||
* After the messages, so a reply that ended silently (its last
|
||||
* word an interim one) drops the row once its face moves on.
|
||||
*/
|
||||
if (res.bot?.id) replay({ data: { event: "server:bot-updated", data: res.bot } });
|
||||
};
|
||||
for (const message of missed) {
|
||||
replay({ data: { event: "server:bot-message", data: message } });
|
||||
}
|
||||
|
||||
/**
|
||||
* Coming back to the app (a notification tapped, the PWA brought
|
||||
* forward) checks at once: the socket was likely down meanwhile.
|
||||
* After the messages, so a reply that ended silently (its last
|
||||
* word an interim one) drops the row once its face moves on.
|
||||
*/
|
||||
const onVisible = () => {
|
||||
if (document.visibilityState == "visible") check();
|
||||
};
|
||||
if (res.bot?.id) replay({ data: { event: "server:bot-updated", data: res.bot } });
|
||||
}, [session_id]);
|
||||
|
||||
const timer = setInterval(check, AppData.BotReplyCatchUpMs);
|
||||
useRefocus({ onRefocus: () => void check() });
|
||||
|
||||
/**
|
||||
* While a reply is due, a poll covers a reply whose push was missed
|
||||
* while the page stayed in front (a socket that dropped silently).
|
||||
*/
|
||||
useEffect(() => {
|
||||
if (!awaiting_reply || !session_id) return;
|
||||
|
||||
const timer = setInterval(() => void check(), AppData.BotReplyCatchUpMs);
|
||||
|
||||
return () => clearInterval(timer);
|
||||
}, [awaiting_reply, session_id, check]);
|
||||
|
||||
/**
|
||||
* The socket was down while the page stayed open: going back online or
|
||||
* restoring it from the back-forward cache checks at once.
|
||||
*/
|
||||
useEffect(() => {
|
||||
window.addEventListener("online", check);
|
||||
window.addEventListener("pageshow", check);
|
||||
document.addEventListener("visibilitychange", onVisible);
|
||||
|
||||
return () => {
|
||||
stale = true;
|
||||
clearInterval(timer);
|
||||
window.removeEventListener("online", check);
|
||||
window.removeEventListener("pageshow", check);
|
||||
document.removeEventListener("visibilitychange", onVisible);
|
||||
};
|
||||
}, [awaiting_reply, session_id]);
|
||||
}
|
||||
}, [check]);
|
||||
}
|
||||
@@ -52,6 +52,13 @@ export default function useThreadScroll({ messages }: Params) {
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* Whether the content's end is exactly at the column's bottom, with no
|
||||
* slack: the pull-to-reload gesture reads it, since a thread a few
|
||||
* pixels short still has somewhere of its own to scroll to.
|
||||
*/
|
||||
const atBottom = () => (measure()?.distance ?? 1) <= 0;
|
||||
|
||||
/** The user's own scrolling: it decides whether the thread follows. */
|
||||
const onScroll = () => {
|
||||
const offset = measure();
|
||||
@@ -158,5 +165,6 @@ export default function useThreadScroll({ messages }: Params) {
|
||||
jump_visible,
|
||||
jump_to_bottom: jumpToBottom,
|
||||
on_scroll: onScroll,
|
||||
at_bottom: atBottom,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import Button from "@moduletrace/twui/layout/Button";
|
||||
import { Check, ClipboardCopy } from "lucide-react";
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
import copyPendingText from "@/src/utils/copy-pending-text";
|
||||
import messageDetailsMarkdown from "../(utils)/message-details-markdown";
|
||||
import fetchMessageDetails from "../(functions)/fetch-message-details";
|
||||
|
||||
type Props = {
|
||||
message_id: number;
|
||||
};
|
||||
|
||||
/**
|
||||
* The details modal's "Copy report": puts the message's whole details on
|
||||
* the clipboard as one markdown document (`messageDetailsMarkdown`),
|
||||
* every call and failure it took included, not only the ones the modal
|
||||
* lists. The row shows a check for a moment, then goes back.
|
||||
*/
|
||||
export default function CopyMessageDetailsButton({ message_id }: Props) {
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [copied, setCopied] = useState(false);
|
||||
const timeout = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
if (timeout.current) clearTimeout(timeout.current);
|
||||
};
|
||||
}, []);
|
||||
|
||||
const copy = async () => {
|
||||
setLoading(true);
|
||||
|
||||
const markdown = fetchMessageDetails({ message_id, full: true }).then((res) => {
|
||||
if (!res?.success || !res.singleRes) {
|
||||
throw new Error(res?.msg || "Couldn't load this message's details.");
|
||||
}
|
||||
|
||||
return messageDetailsMarkdown({ details: res.singleRes, now: Date.now() });
|
||||
});
|
||||
|
||||
try {
|
||||
const worked = await copyPendingText({ text: markdown });
|
||||
|
||||
setLoading(false);
|
||||
|
||||
if (!worked) {
|
||||
window.alert("Couldn't copy the report to the clipboard.");
|
||||
return;
|
||||
}
|
||||
|
||||
setCopied(true);
|
||||
timeout.current = setTimeout(() => setCopied(false), AppData.CopyConfirmationMs);
|
||||
} catch (error: unknown) {
|
||||
setLoading(false);
|
||||
window.alert(error instanceof Error ? error.message : "Couldn't copy the report.");
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Button
|
||||
title={copied ? "Copied" : "Copy this message's whole details as markdown"}
|
||||
type="button"
|
||||
variant="ghost"
|
||||
color="gray"
|
||||
size="small"
|
||||
beforeIcon={copied ? <Check size={14} aria-hidden /> : <ClipboardCopy size={14} aria-hidden />}
|
||||
loading={loading}
|
||||
disabled={loading}
|
||||
onClick={() => {
|
||||
if (!copied) void copy();
|
||||
}}
|
||||
className="shrink-0 px-2! text-[12px]"
|
||||
>
|
||||
{copied ? "Copied" : "Copy report"}
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
@@ -1,12 +1,10 @@
|
||||
import Span from "@moduletrace/twui/layout/Span";
|
||||
import Stack from "@moduletrace/twui/layout/Stack";
|
||||
import { BotJobKinds } from "@/src/dict/bot-queue-dict";
|
||||
import type { MessageDetails } from "@/src/types";
|
||||
import formatDuration from "@/src/utils/format-duration";
|
||||
import formatTokens from "@/src/utils/format-tokens";
|
||||
import relativeTime from "@/src/utils/relative-time";
|
||||
import costLabel from "../(utils)/cost-label";
|
||||
import providerLabel from "../(utils)/provider-label";
|
||||
import messageDetailsFacts from "../(utils)/message-details-facts";
|
||||
import MessageDetailRow from "./message-detail-row";
|
||||
import MessageDetailsCallRow from "./message-details-call-row";
|
||||
import MessageDetailsFailureRow from "./message-details-failure-row";
|
||||
@@ -24,17 +22,7 @@ type Props = {
|
||||
*/
|
||||
export default function MessageDetailsBody({ details }: Props) {
|
||||
const { totals, models, calls, failures, failed_calls, job } = details;
|
||||
const providers = [
|
||||
...new Set(models.map((m) => providerLabel({ name: m.provider_name, kind: m.provider_kind }))),
|
||||
];
|
||||
const model_names = [...new Set(models.map((m) => m.model_name || m.model_slug || "Unknown model"))];
|
||||
const first_at = Math.min(
|
||||
...[calls[0]?.created_at, failures[0]?.created_at].filter((at): at is number => Boolean(at)),
|
||||
Number.MAX_SAFE_INTEGER,
|
||||
);
|
||||
const job_kind = BotJobKinds.find((k) => k.value == job?.kind)?.title || job?.kind;
|
||||
const job_took =
|
||||
job?.started_at && job.finished_at ? formatDuration({ ms: job.finished_at - job.started_at }) : "";
|
||||
const { providers, model_names, first_at, job_kind, job_took } = messageDetailsFacts({ details });
|
||||
|
||||
return (
|
||||
<Stack className="w-full gap-0! items-stretch">
|
||||
|
||||
@@ -3,6 +3,7 @@ import Span from "@moduletrace/twui/layout/Span";
|
||||
import Stack from "@moduletrace/twui/layout/Stack";
|
||||
import type { MessageDetailsFailure } from "@/src/types";
|
||||
import formatDuration from "@/src/utils/format-duration";
|
||||
import failureSourceLabel from "../(utils)/failure-source-label";
|
||||
import harnessLabel from "../(utils)/harness-label";
|
||||
import providerLabel from "../(utils)/provider-label";
|
||||
|
||||
@@ -16,12 +17,6 @@ type Props = {
|
||||
first_at: number;
|
||||
};
|
||||
|
||||
const SourceLabels: Record<NonNullable<MessageDetailsFailure["source"]>, string> = {
|
||||
pinned: "the pick",
|
||||
fallback: "a fallback model",
|
||||
auto: "an automatic pick",
|
||||
};
|
||||
|
||||
/**
|
||||
* One model call that failed: its number, when it came after the first
|
||||
* call, which model and its HTTP status, then what the provider said and
|
||||
@@ -46,7 +41,7 @@ export default function MessageDetailsFailureRow({ failure, index, first_at }: P
|
||||
className="grow min-w-0 text-[12px] leading-4 text-ink truncate"
|
||||
title={[
|
||||
`${model}${failure.model_slug ? ` (${failure.model_slug})` : ""} on ${provider}`,
|
||||
`${harnessLabel({ harness: failure.harness })}${failure.source ? `, ${SourceLabels[failure.source]}` : ""}`,
|
||||
`${harnessLabel({ harness: failure.harness })}${failure.source ? `, ${failureSourceLabel({ source: failure.source })}` : ""}`,
|
||||
].join("\n")}
|
||||
>
|
||||
{model}
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
import { useState } from "react";
|
||||
import Modal from "@moduletrace/twui/elements/Modal";
|
||||
import H2 from "@moduletrace/twui/layout/H2";
|
||||
import Row from "@moduletrace/twui/layout/Row";
|
||||
import Span from "@moduletrace/twui/layout/Span";
|
||||
import Stack from "@moduletrace/twui/layout/Stack";
|
||||
import { Info } from "lucide-react";
|
||||
import useMessageDetails from "../(hooks)/use-message-details";
|
||||
import CopyMessageDetailsButton from "./copy-message-details-button";
|
||||
import MessageActionButton from "./message-action-button";
|
||||
import MessageDetailsBody from "./message-details-body";
|
||||
|
||||
@@ -34,7 +36,10 @@ export default function MessageDetailsModal({ message_id }: Props) {
|
||||
className="max-w-xl bg-paper p-6"
|
||||
>
|
||||
<Stack className="w-full gap-1! items-stretch">
|
||||
<H2 className="text-lg! leading-6! tracking-normal! font-bold text-ink">Message details</H2>
|
||||
<Row className="w-full gap-2! flex-nowrap items-center">
|
||||
<H2 className="grow text-lg! leading-6! tracking-normal! font-bold text-ink">Message details</H2>
|
||||
<CopyMessageDetailsButton message_id={message_id} />
|
||||
</Row>
|
||||
<Span className="text-[13px] leading-[18px] text-ink-secondary">
|
||||
How this answer was generated: the provider and model behind it, the settings they were called with, and what it spent.
|
||||
</Span>
|
||||
|
||||
@@ -7,12 +7,14 @@ import type {
|
||||
BotWithLastMessage,
|
||||
} from "@/src/types";
|
||||
import useMessageSelection from "../(hooks)/use-message-selection";
|
||||
import usePullToRefresh from "../(hooks)/use-pull-to-refresh";
|
||||
import useThreadScroll from "../(hooks)/use-thread-scroll";
|
||||
import groupMessages from "../(utils)/group-messages";
|
||||
import BotThinkingRow from "./bot-thinking-row";
|
||||
import ConversationChatroomStatus from "./conversation-chatroom-status";
|
||||
import MessageGroupBlock from "./message-group-block";
|
||||
import OlderMessagesLoader from "./older-messages-loader";
|
||||
import PullToRefreshIndicator from "./pull-to-refresh-indicator";
|
||||
import QuoteSelectionButton from "./quote-selection-button";
|
||||
import ScrollToBottomButton from "./scroll-to-bottom-button";
|
||||
import quotableText from "../(utils)/quotable-text";
|
||||
@@ -54,6 +56,11 @@ type Props = {
|
||||
* Quotes text selected in a message in the composer.
|
||||
*/
|
||||
onQuote?: (params: { text: string }) => void;
|
||||
/**
|
||||
* Reads the conversation again, pulled up from the bottom of the
|
||||
* thread on a phone.
|
||||
*/
|
||||
onReload: () => Promise<void>;
|
||||
/**
|
||||
* The session's older messages, loaded at the top of the thread.
|
||||
*/
|
||||
@@ -82,7 +89,8 @@ type Props = {
|
||||
* above it (shown only, never put in the bot's prompt); the reversed column keeps
|
||||
* the view where it was as they land above it. The thread follows new
|
||||
* messages while it sits at its bottom, stays put while it's scrolled up
|
||||
* and then offers a button to get back down.
|
||||
* and then offers a button to get back down. Pulled up past its bottom on
|
||||
* a phone, it offers to read the conversation again.
|
||||
*/
|
||||
export default function MessageThread({
|
||||
bot,
|
||||
@@ -95,17 +103,24 @@ export default function MessageThread({
|
||||
no_reply_due,
|
||||
notice,
|
||||
onQuote,
|
||||
onReload,
|
||||
older,
|
||||
}: Props) {
|
||||
const groups = useMemo(() => groupMessages({ messages }), [messages]);
|
||||
const scroll = useThreadScroll({ messages });
|
||||
const pull_state = usePullToRefresh({
|
||||
column_ref: scroll.column_ref,
|
||||
content_ref: scroll.content_ref,
|
||||
at_bottom: scroll.at_bottom,
|
||||
on_refresh: onReload,
|
||||
});
|
||||
const { selection, clear } = useMessageSelection({ ref: scroll.column_ref });
|
||||
|
||||
return (
|
||||
<Stack className="relative grow min-h-0 gap-0! items-stretch">
|
||||
<Stack
|
||||
componentRef={scroll.column_ref as RefObject<HTMLDivElement>}
|
||||
className="grow min-h-0 gap-0! items-stretch overflow-y-auto flex-col-reverse"
|
||||
className="grow min-h-0 gap-0! items-stretch overflow-y-auto overscroll-contain flex-col-reverse"
|
||||
onScroll={scroll.on_scroll}
|
||||
>
|
||||
<Stack
|
||||
@@ -162,6 +177,7 @@ export default function MessageThread({
|
||||
{scroll.jump_visible ? (
|
||||
<ScrollToBottomButton onClick={scroll.jump_to_bottom} />
|
||||
) : null}
|
||||
<PullToRefreshIndicator state={pull_state} onReload={onReload} />
|
||||
{selection && onQuote ? (
|
||||
<QuoteSelectionButton
|
||||
selection={selection}
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { renderToString } from "react-dom/server";
|
||||
import PullToRefreshIndicator from "./pull-to-refresh-indicator";
|
||||
|
||||
const reload = async () => {};
|
||||
|
||||
describe("PullToRefreshIndicator", () => {
|
||||
test("shows nothing until the thread is pulled", () => {
|
||||
expect(
|
||||
renderToString(<PullToRefreshIndicator state="idle" onReload={reload} />),
|
||||
).toBe("");
|
||||
});
|
||||
|
||||
test("is one icon in a ghost button, with no word beside it", () => {
|
||||
const html = renderToString(<PullToRefreshIndicator state="pulling" onReload={reload} />);
|
||||
|
||||
expect(html).toContain("twui-button-secondary-ghost");
|
||||
expect(html).toContain(`aria-label="Reload the conversation"`);
|
||||
expect(html).toContain("<svg");
|
||||
/**
|
||||
* Nothing but the icon: the button's content wrapper holds no text.
|
||||
*/
|
||||
expect(html).not.toMatch(/twui-button-content-wrapper[^>]*>[A-Za-z]/);
|
||||
});
|
||||
|
||||
test("dims the icon while it's only being pulled and lights it up once letting go reloads", () => {
|
||||
expect(
|
||||
renderToString(<PullToRefreshIndicator state="pulling" onReload={reload} />),
|
||||
).toContain("opacity-40");
|
||||
expect(
|
||||
renderToString(<PullToRefreshIndicator state="ready" onReload={reload} />),
|
||||
).not.toContain("opacity-40");
|
||||
});
|
||||
|
||||
test("holds the icon's place with a spinner while it reloads", () => {
|
||||
const html = renderToString(
|
||||
<PullToRefreshIndicator state="refreshing" onReload={reload} />,
|
||||
);
|
||||
|
||||
expect(html).toContain("twui-loading");
|
||||
expect(html).toContain("aria-busy");
|
||||
expect(html).toContain("disabled");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,41 @@
|
||||
import { twMerge } from "tailwind-merge";
|
||||
import { RefreshCw } from "lucide-react";
|
||||
import Button from "@moduletrace/twui/layout/Button";
|
||||
import type { PullToRefreshState } from "../(hooks)/use-pull-to-refresh";
|
||||
|
||||
type Props = {
|
||||
state: PullToRefreshState;
|
||||
onReload: () => Promise<void>;
|
||||
};
|
||||
|
||||
/**
|
||||
* The phone's pull-to-reload control: a lone icon in the room the pull
|
||||
* opens under the newest message, a ghost button so it reads as part of
|
||||
* the paper rather than a card over it. It stays dim while the pull is
|
||||
* only being made or the room is only being held, and lights up once
|
||||
* letting go will reload. While the conversation is read again the button
|
||||
* shows its own spinner in the icon's place, and tapping it reloads too,
|
||||
* so the gesture isn't the only way. Nothing shows until the thread is
|
||||
* pulled.
|
||||
*/
|
||||
export default function PullToRefreshIndicator({ state, onReload }: Props) {
|
||||
if (state == "idle") return null;
|
||||
|
||||
return (
|
||||
<Button
|
||||
title="Reload the conversation"
|
||||
variant="ghost"
|
||||
color="text"
|
||||
size="smaller"
|
||||
loading={state == "refreshing"}
|
||||
loadingIconSize="normal"
|
||||
onClick={() => void onReload()}
|
||||
className={twMerge(
|
||||
"absolute bottom-3 left-1/2 z-20 -translate-x-1/2 text-ink-secondary",
|
||||
state == "pulling" && "opacity-40",
|
||||
state == "ready" && "text-ink",
|
||||
)}
|
||||
beforeIcon={<RefreshCw size={16} aria-hidden />}
|
||||
/>
|
||||
);
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user