Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
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
|
||||
|
||||
@@ -98,11 +98,11 @@ Enables SQLite foreign keys (`enableForeignKeys`), `bunextInit()`, `ensureDocker
|
||||
- **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`.
|
||||
@@ -139,8 +139,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 +214,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 +232,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 +245,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.5",
|
||||
"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) {
|
||||
|
||||
@@ -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 };
|
||||
}
|
||||
+62
-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,
|
||||
@@ -675,6 +718,13 @@ export const AppData = {
|
||||
* 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 +862,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;
|
||||
@@ -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,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)}`;
|
||||
}
|
||||
|
||||
@@ -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" },
|
||||
);
|
||||
}
|
||||
@@ -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,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>
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
import type { MessageDetailsFailure } from "@/src/types";
|
||||
|
||||
const SourceLabels: Record<NonNullable<MessageDetailsFailure["source"]>, string> = {
|
||||
pinned: "the pick",
|
||||
fallback: "a fallback model",
|
||||
auto: "an automatic pick",
|
||||
};
|
||||
|
||||
type Params = {
|
||||
source: MessageDetailsFailure["source"];
|
||||
};
|
||||
|
||||
/**
|
||||
* How a failed call's model was picked, in words: "the pick", "a fallback
|
||||
* model", "an automatic pick". Empty when the call recorded no source.
|
||||
*/
|
||||
export default function failureSourceLabel({ source }: Params) {
|
||||
return source ? SourceLabels[source] : "";
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
import { BotJobKinds } from "@/src/dict/bot-queue-dict";
|
||||
import type { MessageDetails } from "@/src/types";
|
||||
import formatDuration from "@/src/utils/format-duration";
|
||||
import providerLabel from "./provider-label";
|
||||
|
||||
type Params = {
|
||||
details: MessageDetails;
|
||||
};
|
||||
|
||||
export type MessageDetailsFacts = {
|
||||
/**
|
||||
* Every provider name that answered, in the order they first did.
|
||||
*/
|
||||
providers: string[];
|
||||
/**
|
||||
* Every model name that answered, in the order they first did.
|
||||
*/
|
||||
model_names: string[];
|
||||
/**
|
||||
* When the earliest call or failure was made, so each reads as an
|
||||
* offset from it.
|
||||
*/
|
||||
first_at: number;
|
||||
job_kind: string;
|
||||
job_took: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* What a message's details say at a glance, worked out once so the modal
|
||||
* and the copy of it never disagree: the providers and models behind the
|
||||
* message, when its first call was made, and how the run reads.
|
||||
*/
|
||||
export default function messageDetailsFacts({ details }: Params): MessageDetailsFacts {
|
||||
const { models, calls, failures, job } = details;
|
||||
|
||||
return {
|
||||
providers: [
|
||||
...new Set(models.map((model) => providerLabel({ name: model.provider_name, kind: model.provider_kind }))),
|
||||
],
|
||||
model_names: [...new Set(models.map((model) => model.model_name || model.model_slug || "Unknown model"))],
|
||||
first_at: Math.min(
|
||||
...[calls[0]?.created_at, failures[0]?.created_at].filter((at): at is number => Boolean(at)),
|
||||
Number.MAX_SAFE_INTEGER,
|
||||
),
|
||||
job_kind: BotJobKinds.find((kind) => kind.value == job?.kind)?.title || job?.kind || "",
|
||||
job_took:
|
||||
job?.started_at && job.finished_at ? formatDuration({ ms: job.finished_at - job.started_at }) : "",
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,201 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import type { HarnessCallSettings } from "@/src/harness/usage/types";
|
||||
import type { MessageDetails, MessageDetailsCall, MessageDetailsFailure } from "@/src/types";
|
||||
import messageDetailsMarkdown from "./message-details-markdown";
|
||||
|
||||
const format_time = (time: number) => `t${time}`;
|
||||
|
||||
const settings: HarnessCallSettings = {
|
||||
model_source: "pinned",
|
||||
settings_source: "bot",
|
||||
params: { temperature: 0.3 },
|
||||
};
|
||||
|
||||
function call(overrides: Partial<MessageDetailsCall>): MessageDetailsCall {
|
||||
return {
|
||||
id: 1,
|
||||
created_at: 1_000,
|
||||
harness: "text",
|
||||
provider_id: 1,
|
||||
provider_name: "OpenRouter",
|
||||
provider_kind: "openrouter",
|
||||
model_slug: "deepseek/deepseek-v4",
|
||||
model_name: "DeepSeek V4",
|
||||
prompt_tokens: 1_200,
|
||||
cached_tokens: 200,
|
||||
completion_tokens: 80,
|
||||
cost: 0.0123,
|
||||
settings,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function failure(overrides: Partial<MessageDetailsFailure>): MessageDetailsFailure {
|
||||
return {
|
||||
id: 1,
|
||||
created_at: 1_000,
|
||||
harness: "text",
|
||||
provider_name: "OpenRouter",
|
||||
provider_kind: "openrouter",
|
||||
model_slug: "deepseek/deepseek-v4",
|
||||
model_name: "DeepSeek V4",
|
||||
source: "pinned",
|
||||
status: 429,
|
||||
error: "Rate limited\nTry again later",
|
||||
rests_until: 61_000,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function details(overrides: Partial<MessageDetails>): MessageDetails {
|
||||
return {
|
||||
message_id: 42,
|
||||
created_at: 5_000,
|
||||
totals: { prompt_tokens: 1_200, completion_tokens: 80, total_tokens: 1_280, calls: 1 },
|
||||
models: [],
|
||||
calls: [],
|
||||
failures: [],
|
||||
failed_calls: 0,
|
||||
job: null,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe("messageDetailsMarkdown", () => {
|
||||
test("heads the report with the message, its totals and when it was copied", () => {
|
||||
const markdown = messageDetailsMarkdown({
|
||||
details: details({
|
||||
totals: { prompt_tokens: 0, completion_tokens: 0, total_tokens: 0, calls: 0 },
|
||||
}),
|
||||
now: 9_000,
|
||||
format_time,
|
||||
});
|
||||
|
||||
expect(markdown).toContain("# Message details");
|
||||
expect(markdown).toContain("- **Message:** #42");
|
||||
expect(markdown).toContain("- **Written:** t5000");
|
||||
expect(markdown).toContain("- **Tokens:** 0 (0 in, 0 out)");
|
||||
expect(markdown).toContain("- **Copied:** t9000");
|
||||
expect(markdown).toContain("No model calls were recorded for this message.");
|
||||
});
|
||||
|
||||
test("lists every call in a table, with its offset and fallback mark", () => {
|
||||
const markdown = messageDetailsMarkdown({
|
||||
details: details({
|
||||
totals: { prompt_tokens: 1_300, completion_tokens: 90, total_tokens: 1_390, calls: 2 },
|
||||
calls: [
|
||||
call({ id: 1, created_at: 1_000 }),
|
||||
call({
|
||||
id: 2,
|
||||
created_at: 5_200,
|
||||
prompt_tokens: 100,
|
||||
completion_tokens: 10,
|
||||
settings: { ...settings, fell_back_from: ["openrouter:big"] },
|
||||
}),
|
||||
],
|
||||
}),
|
||||
now: 9_000,
|
||||
format_time,
|
||||
});
|
||||
|
||||
expect(markdown).toContain("| # | At | Model | Harness | Prompt | Cached | Completion | Cost |");
|
||||
expect(markdown).toContain("| 1 | start | DeepSeek V4 (deepseek/deepseek-v4) | Text | 1,200 | 200 | 80 | $0.0123 |");
|
||||
expect(markdown).toContain("| 2 | +4.2s | DeepSeek V4 (deepseek/deepseek-v4) (fallback) | Text | 100 | 200 | 10 | $0.0123 |");
|
||||
});
|
||||
|
||||
test("quotes a failed call's error line by line and names what rested", () => {
|
||||
const markdown = messageDetailsMarkdown({
|
||||
details: details({ failures: [failure({})], failed_calls: 1 }),
|
||||
now: 9_000,
|
||||
format_time,
|
||||
});
|
||||
|
||||
expect(markdown).toContain("## Failed call");
|
||||
expect(markdown).toContain("### Failure #1 · start");
|
||||
expect(markdown).toContain("- **Status:** HTTP 429");
|
||||
expect(markdown).toContain("- **Rested for:** 1m");
|
||||
expect(markdown).toContain("> Rate limited\n> Try again later");
|
||||
});
|
||||
|
||||
test("sums each model with its settings in a table", () => {
|
||||
const markdown = messageDetailsMarkdown({
|
||||
details: details({
|
||||
models: [
|
||||
{
|
||||
harness: "text",
|
||||
provider_name: "OpenRouter",
|
||||
provider_kind: "openrouter",
|
||||
model_slug: "deepseek/deepseek-v4",
|
||||
model_name: "DeepSeek V4",
|
||||
settings,
|
||||
prompt_tokens: 1_200,
|
||||
completion_tokens: 80,
|
||||
total_tokens: 1_280,
|
||||
calls: 1,
|
||||
cost: 0.0123,
|
||||
},
|
||||
],
|
||||
}),
|
||||
now: 9_000,
|
||||
format_time,
|
||||
});
|
||||
|
||||
expect(markdown).toContain("## Model used");
|
||||
expect(markdown).toContain("### DeepSeek V4");
|
||||
expect(markdown).toContain("- **Provider:** OpenRouter");
|
||||
expect(markdown).toContain("| Setting | Value |");
|
||||
expect(markdown).toContain("| Temperature | 0.3 |");
|
||||
});
|
||||
|
||||
test("spells out the run behind the message", () => {
|
||||
const markdown = messageDetailsMarkdown({
|
||||
details: details({
|
||||
job: {
|
||||
id: 7,
|
||||
kind: "task",
|
||||
title: "Weekly report",
|
||||
status: "completed",
|
||||
attempts: 1,
|
||||
started_at: 1_000,
|
||||
finished_at: 181_000,
|
||||
steps: 12,
|
||||
},
|
||||
}),
|
||||
now: 200_000,
|
||||
format_time,
|
||||
});
|
||||
|
||||
expect(markdown).toContain("## Run");
|
||||
expect(markdown).toContain("- **Id:** #7");
|
||||
expect(markdown).toContain("- **Kind:** Task");
|
||||
expect(markdown).toContain("- **Title:** Weekly report");
|
||||
expect(markdown).toContain("- **Took:** 3m");
|
||||
expect(markdown).toContain("- **Steps:** 12");
|
||||
});
|
||||
|
||||
test("says when the report lists fewer calls than were made", () => {
|
||||
const markdown = messageDetailsMarkdown({
|
||||
details: details({
|
||||
totals: { prompt_tokens: 1_200, completion_tokens: 80, total_tokens: 1_280, calls: 5 },
|
||||
calls: [call({})],
|
||||
}),
|
||||
now: 9_000,
|
||||
format_time,
|
||||
});
|
||||
|
||||
expect(markdown).toContain("Showing the first 1 of 5 calls. The totals count every one.");
|
||||
});
|
||||
|
||||
test("keeps a pipe in a model name from breaking a table cell", () => {
|
||||
const markdown = messageDetailsMarkdown({
|
||||
details: details({
|
||||
calls: [call({ model_name: "A|B" })],
|
||||
totals: { prompt_tokens: 1_200, completion_tokens: 80, total_tokens: 1_280, calls: 1 },
|
||||
}),
|
||||
now: 9_000,
|
||||
format_time,
|
||||
});
|
||||
|
||||
expect(markdown).toContain("A\\|B");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,203 @@
|
||||
import type { MessageDetails, MessageDetailsCall, MessageDetailsFailure, MessageDetailsModel } from "@/src/types";
|
||||
import describeCallSettings from "@/src/utils/describe-call-settings";
|
||||
import formatDuration from "@/src/utils/format-duration";
|
||||
import costLabel from "./cost-label";
|
||||
import failureSourceLabel from "./failure-source-label";
|
||||
import harnessLabel from "./harness-label";
|
||||
import messageDetailsFacts from "./message-details-facts";
|
||||
import providerLabel from "./provider-label";
|
||||
|
||||
type Params = {
|
||||
details: MessageDetails;
|
||||
/**
|
||||
* When the copy was made.
|
||||
*/
|
||||
now: number;
|
||||
/**
|
||||
* A timestamp as the reader sees it; local time by default.
|
||||
*/
|
||||
format_time?: (time: number) => string;
|
||||
};
|
||||
|
||||
type DetailLine = {
|
||||
label: string;
|
||||
value: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* Everything a message's details hold as one markdown report, for a bug
|
||||
* report or a note: the provider and model that answered and what it
|
||||
* spent, the run behind it, every model it used, every call in order and
|
||||
* every call that failed, with why. The whole message, not only the calls
|
||||
* the modal lists.
|
||||
*/
|
||||
export default function messageDetailsMarkdown({
|
||||
details,
|
||||
now,
|
||||
format_time = (time) =>
|
||||
new Date(time).toLocaleString(undefined, {
|
||||
dateStyle: "medium",
|
||||
timeStyle: "short",
|
||||
}),
|
||||
}: Params) {
|
||||
const { totals, models, calls, failures, failed_calls, job } = details;
|
||||
const { providers, model_names, first_at, job_kind, job_took } = messageDetailsFacts({ details });
|
||||
const out: string[] = [
|
||||
"# Message details",
|
||||
"",
|
||||
...lines([
|
||||
{ label: "Message", value: `#${details.message_id}` },
|
||||
{ label: "Written", value: details.created_at ? format_time(details.created_at) : "" },
|
||||
{ label: providers.length > 1 ? "Providers" : "Provider", value: providers.join(", ") },
|
||||
{ label: model_names.length > 1 ? "Models" : "Model", value: model_names.join(", ") },
|
||||
{ label: "Tokens", value: `${totals.total_tokens.toLocaleString()} (${totals.prompt_tokens.toLocaleString()} in, ${totals.completion_tokens.toLocaleString()} out)` },
|
||||
{ label: "Cost", value: costLabel({ cost: totals.cost }) },
|
||||
{ label: "Model calls", value: String(totals.calls) },
|
||||
{ label: "Failed calls", value: failed_calls ? String(failed_calls) : "" },
|
||||
{ label: "Copied", value: format_time(now) },
|
||||
]),
|
||||
];
|
||||
|
||||
if (!totals.calls && !failed_calls) {
|
||||
out.push(
|
||||
"",
|
||||
"No model calls were recorded for this message. It was written by the app itself (a stop, a failure notice), or before usage was recorded.",
|
||||
);
|
||||
}
|
||||
|
||||
if (job) {
|
||||
out.push(
|
||||
"",
|
||||
"## Run",
|
||||
"",
|
||||
...lines([
|
||||
{ label: "Id", value: `#${job.id}` },
|
||||
{ label: "Kind", value: job_kind },
|
||||
{ label: "Title", value: job.title || "" },
|
||||
{ label: "Status", value: job.status || "" },
|
||||
{ label: "Took", value: job_took },
|
||||
{ label: "Attempts", value: String(job.attempts || 1) },
|
||||
{ label: "Steps", value: String(job.steps) },
|
||||
]),
|
||||
);
|
||||
}
|
||||
|
||||
if (models.length) {
|
||||
out.push("", `## ${models.length > 1 ? "Models used" : "Model used"}`, ...models.flatMap(modelBlock));
|
||||
}
|
||||
|
||||
if (calls.length) {
|
||||
out.push("", "## Calls in order", "", callTable({ calls, first_at }));
|
||||
|
||||
if (totals.calls > calls.length) {
|
||||
out.push("", `Showing the first ${calls.length} of ${totals.calls} calls. The totals count every one.`);
|
||||
}
|
||||
}
|
||||
|
||||
if (failures.length) {
|
||||
out.push("", `## ${failures.length > 1 ? "Failed calls" : "Failed call"}`, ...failures.flatMap((failure, index) => failureBlock({ failure, index, first_at })));
|
||||
|
||||
if (failed_calls > failures.length) {
|
||||
out.push("", `Showing the first ${failures.length} of ${failed_calls} failed calls.`);
|
||||
}
|
||||
}
|
||||
|
||||
return `${out.join("\n").trimEnd()}\n`;
|
||||
}
|
||||
|
||||
/**
|
||||
* A label and its value per line, skipping the ones with nothing to say.
|
||||
*/
|
||||
function lines(rows: DetailLine[]) {
|
||||
return rows.filter((row) => row.value).map((row) => `- **${row.label}:** ${row.value}`);
|
||||
}
|
||||
|
||||
function modelBlock(model: MessageDetailsModel) {
|
||||
const name = model.model_name || model.model_slug || "Unknown model";
|
||||
const settings = model.settings ? describeCallSettings({ settings: model.settings, harness: model.harness }) : [];
|
||||
const out = [
|
||||
"",
|
||||
`### ${name}`,
|
||||
"",
|
||||
...lines([
|
||||
{ label: "Id", value: model.model_slug && model.model_slug != name ? model.model_slug : "" },
|
||||
{ label: "Provider", value: providerLabel({ name: model.provider_name, kind: model.provider_kind }) },
|
||||
{ label: "Harness", value: harnessLabel({ harness: model.harness }) },
|
||||
{ label: "Calls", value: String(model.calls) },
|
||||
{ label: "Tokens", value: `${model.total_tokens.toLocaleString()} (${model.prompt_tokens.toLocaleString()} in, ${model.completion_tokens.toLocaleString()} out)` },
|
||||
{ label: "Cost", value: costLabel({ cost: model.cost }) },
|
||||
]),
|
||||
];
|
||||
|
||||
if (settings.length) {
|
||||
out.push("", "| Setting | Value |", "| --- | --- |");
|
||||
out.push(...settings.map(({ label, value }) => `| ${label} | ${escapeCell({ text: value })} |`));
|
||||
}
|
||||
|
||||
return out;
|
||||
}
|
||||
|
||||
function callTable({ calls, first_at }: { calls: MessageDetailsCall[]; first_at: number }) {
|
||||
const out = [
|
||||
"| # | At | Model | Harness | Prompt | Cached | Completion | Cost |",
|
||||
"| --- | --- | --- | --- | --- | --- | --- | --- |",
|
||||
];
|
||||
|
||||
out.push(
|
||||
...calls.map((call, index) => {
|
||||
const model = `${call.model_name || call.model_slug || "Unknown model"}${call.model_slug && call.model_name ? ` (${call.model_slug})` : ""}`;
|
||||
const fell_back = call.settings?.fell_back_from?.length ? " (fallback)" : "";
|
||||
|
||||
return [
|
||||
`| ${index + 1}`,
|
||||
offsetLabel({ at: call.created_at, first_at }),
|
||||
escapeCell({ text: `${model}${fell_back}` }),
|
||||
harnessLabel({ harness: call.harness }),
|
||||
call.prompt_tokens.toLocaleString(),
|
||||
call.cached_tokens.toLocaleString(),
|
||||
call.completion_tokens.toLocaleString(),
|
||||
escapeCell({ text: costLabel({ cost: call.cost }) }),
|
||||
].join(" | ") + " |";
|
||||
}),
|
||||
);
|
||||
|
||||
return out.join("\n");
|
||||
}
|
||||
|
||||
function failureBlock({ failure, index, first_at }: { failure: MessageDetailsFailure; index: number; first_at: number }) {
|
||||
const model = `${failure.model_name || failure.model_slug || "Unknown model"}${failure.model_slug && failure.model_name ? ` (${failure.model_slug})` : ""}`;
|
||||
const rested =
|
||||
failure.rests_until && failure.rests_until > failure.created_at
|
||||
? formatDuration({ ms: failure.rests_until - failure.created_at })
|
||||
: "";
|
||||
|
||||
return [
|
||||
"",
|
||||
`### Failure #${index + 1} · ${offsetLabel({ at: failure.created_at, first_at })}`,
|
||||
"",
|
||||
...lines([
|
||||
{ label: "Model", value: model },
|
||||
{ label: "Provider", value: providerLabel({ name: failure.provider_name, kind: failure.provider_kind }) },
|
||||
{ label: "Harness", value: harnessLabel({ harness: failure.harness }) },
|
||||
{ label: "Picked", value: failureSourceLabel({ source: failure.source }) },
|
||||
{ label: "Status", value: failure.status ? `HTTP ${failure.status}` : "No response" },
|
||||
{ label: "Rested for", value: rested },
|
||||
]),
|
||||
"",
|
||||
"> " + failure.error.split("\n").join("\n> "),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* When a call came after the first: "+4.2s", or "start" for the first.
|
||||
*/
|
||||
function offsetLabel({ at, first_at }: { at: number; first_at: number }) {
|
||||
return at > first_at ? `+${formatDuration({ ms: at - first_at })}` : "start";
|
||||
}
|
||||
|
||||
/**
|
||||
* A value inside a table cell, kept on one line.
|
||||
*/
|
||||
function escapeCell({ text }: { text: string }) {
|
||||
return text.replaceAll("|", "\\|").replaceAll("\n", " ");
|
||||
}
|
||||
@@ -13,6 +13,7 @@ import grabChatroomRetentionOverview from "@/src/functions/backend/db/app-settin
|
||||
import grabSessionLengthOverview from "@/src/functions/backend/db/app-settings/grab-bot-session-max-messages";
|
||||
import grabMessageLengthOverview from "@/src/functions/backend/db/app-settings/grab-bot-message-max-chars";
|
||||
import grabStorageQuotaOverview from "@/src/functions/backend/db/app-settings/grab-storage-quota-overview";
|
||||
import grabComputerWorkspaceQuotaOverview from "@/src/functions/backend/db/app-settings/grab-computer-workspace-quota-overview";
|
||||
import { grabSystemPromptAppendOverview } from "@/src/functions/backend/db/app-settings/grab-system-prompt-append";
|
||||
import runningVersion from "@/src/utils/running-version";
|
||||
|
||||
@@ -51,6 +52,7 @@ export default async function grabSettingsServerProps({ req }: Params) {
|
||||
person: sanitizeUserBio({ user: user_res.singleRes }),
|
||||
has_password,
|
||||
storage_quota: await grabStorageQuotaOverview().catch(() => null),
|
||||
computer_workspace_quota: await grabComputerWorkspaceQuotaOverview().catch(() => null),
|
||||
system_prompt_append: await grabSystemPromptAppendOverview().catch(() => null),
|
||||
run_limits: await grabRunLimitsOverview().catch(() => null),
|
||||
skill_limits: await grabSkillLimitsOverview().catch(() => null),
|
||||
|
||||
@@ -12,7 +12,7 @@ type Params = {
|
||||
* background, so this hands back the run for the page to follow.
|
||||
*/
|
||||
export default async function restoreDataBackup({ backup }: Params) {
|
||||
const confirm_msg = `Restore the data volume from the archive of ${dayjs(backup.created_at).format("MMM D, YYYY HH:mm:ss")}?\n\nEvery bot, workspace, computer home, file, media item and database snapshot is replaced by the archive's, and the app restarts. A safety archive of the current data is made first.`;
|
||||
const confirm_msg = `Restore the data volume from the archive of ${dayjs(backup.created_at).format("MMM D, YYYY HH:mm:ss")}?\n\nEvery bot, workspace, file, media item and database snapshot is replaced by the archive's (a computer's own folder stays as it is), and the app restarts. A safety archive of the current data is made first.`;
|
||||
|
||||
if (!window.confirm(confirm_msg)) {
|
||||
return { success: false, cancelled: true };
|
||||
|
||||
@@ -11,7 +11,7 @@ type Params = {
|
||||
* follow.
|
||||
*/
|
||||
export default async function uploadRestoreDataBackup({ file }: Params) {
|
||||
const confirm_msg = `Restore the data volume from "${file.name}"?\n\nEvery bot, workspace, computer home, file, media item and database snapshot is replaced by the archive's, and the app restarts. A safety archive of the current data is made first.`;
|
||||
const confirm_msg = `Restore the data volume from "${file.name}"?\n\nEvery bot, workspace, file, media item and database snapshot is replaced by the archive's (a computer's own folder stays as it is), and the app restarts. A safety archive of the current data is made first.`;
|
||||
|
||||
if (!window.confirm(confirm_msg)) {
|
||||
return { success: false, cancelled: true };
|
||||
|
||||
@@ -22,7 +22,7 @@ export default function DataBackupsSection() {
|
||||
return (
|
||||
<SettingsGroup
|
||||
title="Data archives"
|
||||
description="One tar.gz of the whole data volume, under a single folder named after the archive: the database, media, computer homes, every bot and workspace file, and the database snapshots. They live outside the data volume, and the newest few are kept."
|
||||
description="One tar.gz of the install's data, under a single folder named after the archive: the database, media, every bot and workspace file, and the database snapshots. Computers' own folders are left out, since they are that computer's state and often the largest thing on the volume. The archives live outside the data volume, and the newest few are kept."
|
||||
>
|
||||
<Row className="w-full items-center justify-between gap-2! flex-wrap">
|
||||
<Span size="small" variant="faded">
|
||||
|
||||
@@ -0,0 +1,107 @@
|
||||
import { useState } from "react";
|
||||
import fetchApi from "@moduletrace/twui/utils/fetch/fetchApi";
|
||||
import type { APIResponseObject } from "@moduletrace/bunext/types";
|
||||
import Form from "@moduletrace/twui/form/Form";
|
||||
import Input from "@moduletrace/twui/form/Input";
|
||||
import Span from "@moduletrace/twui/layout/Span";
|
||||
import Stack from "@moduletrace/twui/layout/Stack";
|
||||
import type { ComputerWorkspaceQuotaOverview } from "@/src/functions/backend/db/app-settings/grab-computer-workspace-quota-overview";
|
||||
import SettingsSaveBar from "../../(partials)/settings-save-bar";
|
||||
|
||||
type Props = {
|
||||
quota?: ComputerWorkspaceQuotaOverview | null;
|
||||
};
|
||||
|
||||
/**
|
||||
* The most one computer's workspace may hold. A run's writes past it are
|
||||
* refused, so the bot frees space first; bash is never refused, since it is
|
||||
* how a bot cleans up. Saved on its own, without a reload.
|
||||
*/
|
||||
export default function ComputerWorkspaceQuotaForm({ quota }: Props) {
|
||||
const [overview, setOverview] = useState(quota || undefined);
|
||||
const [dirty, setDirty] = useState(false);
|
||||
const [value, setValue] = useState(String(quota?.quota_mb ?? ""));
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [status, setStatus] = useState<{
|
||||
msg?: string;
|
||||
error?: boolean;
|
||||
success?: boolean;
|
||||
}>();
|
||||
|
||||
const save = async () => {
|
||||
setLoading(true);
|
||||
setStatus(undefined);
|
||||
|
||||
const res = await fetchApi<{}, APIResponseObject<ComputerWorkspaceQuotaOverview>>(
|
||||
"/api/admin/settings/computer-workspace-quota",
|
||||
{ method: "POST", body: { quota_mb: Number(value) || 0 } },
|
||||
).catch(() => null);
|
||||
|
||||
setLoading(false);
|
||||
|
||||
if (!res?.success || !res.singleRes) {
|
||||
setStatus({
|
||||
error: true,
|
||||
msg: res?.msg || `Couldn't save the limit.`,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
setOverview(res.singleRes);
|
||||
setValue(String(res.singleRes.quota_mb));
|
||||
setDirty(false);
|
||||
setStatus({
|
||||
success: true,
|
||||
msg: res.singleRes.quota_mb > 0
|
||||
? `Saved: ${res.singleRes.quota_mb} MB per computer.`
|
||||
: `Saved: no limit.`,
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<Form
|
||||
onSubmit={(event) => {
|
||||
event.preventDefault();
|
||||
save().catch(() => {});
|
||||
}}
|
||||
className="w-full gap-3! items-stretch"
|
||||
>
|
||||
<Stack className="w-full gap-1! items-stretch">
|
||||
<Input
|
||||
label="Megabytes per computer"
|
||||
type="number"
|
||||
min={0}
|
||||
step={512}
|
||||
numberText
|
||||
rawNumber
|
||||
defaultValue={value}
|
||||
onChange={(event) => {
|
||||
setValue(event.target.value);
|
||||
setDirty(true);
|
||||
setStatus(undefined);
|
||||
}}
|
||||
suffix={`MB`}
|
||||
info="Each computer's workspace gets this much. A write past it is refused, so the bot clears space first (bash still works, since it is how a bot cleans up). 0 sets no limit."
|
||||
/>
|
||||
{overview ? (
|
||||
<Span className="text-[13px] leading-[18px] text-ink-secondary">
|
||||
{overview.quota_mb > 0
|
||||
? `Each computer may hold ${overview.quota_mb} MB.`
|
||||
: `Computers have no limit.`}
|
||||
</Span>
|
||||
) : null}
|
||||
</Stack>
|
||||
<SettingsSaveBar
|
||||
dirty={dirty}
|
||||
loading={loading}
|
||||
status={status}
|
||||
save_label="Save limit"
|
||||
onDiscard={() => {
|
||||
setValue(String(overview?.quota_mb ?? ""));
|
||||
setDirty(false);
|
||||
setStatus(undefined);
|
||||
}}
|
||||
/>
|
||||
</Form>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
import { useContext } from "react";
|
||||
import { AppContext } from "@/src/pages/__root";
|
||||
import canManageCrew from "@/src/utils/rbac/can-manage-crew";
|
||||
import SettingsGroup from "../../(partials)/settings-group";
|
||||
import ComputerWorkspaceQuotaForm from "../(partials)/computer-workspace-quota-form";
|
||||
|
||||
/**
|
||||
* What a computer keeps on its own volume: browsers save screenshots,
|
||||
* downloads and whole sites there, so one busy computer fills a small disk
|
||||
* on its own. Only a crew manager sees it, since it's an install-wide limit.
|
||||
*/
|
||||
export default function ComputerWorkspacesSection() {
|
||||
const { pageProps } = useContext(AppContext);
|
||||
|
||||
if (!canManageCrew({ user_types: pageProps?.user_types })) return null;
|
||||
|
||||
return (
|
||||
<SettingsGroup
|
||||
title="Computer workspace limit"
|
||||
description="Browsers and shells on a computer fill its own volume, not the app's: screenshots, downloads and everything a site caches. Each computer's workspace is capped so one can't fill the host it runs on."
|
||||
id="computer-workspaces"
|
||||
>
|
||||
<ComputerWorkspaceQuotaForm quota={pageProps?.computer_workspace_quota} />
|
||||
</SettingsGroup>
|
||||
);
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import AppearanceSection from "./(sections)/appearance-section";
|
||||
import AppNetworksSection from "./(sections)/app-networks-section";
|
||||
import ChatroomRetentionSection from "./(sections)/chatroom-retention-section";
|
||||
import ComputerWorkspacesSection from "./(sections)/computer-workspaces-section";
|
||||
import HookCallRetentionSection from "./(sections)/hook-call-retention-section";
|
||||
import InstallIconSection from "./(sections)/install-icon-section";
|
||||
import InstallNameSection from "./(sections)/install-name-section";
|
||||
@@ -35,6 +36,7 @@ export default function AdminSettingsGeneralPage() {
|
||||
<ChatroomRetentionSection />
|
||||
<LogRetentionSection />
|
||||
<StorageSection />
|
||||
<ComputerWorkspacesSection />
|
||||
<AppNetworksSection />
|
||||
<VersionSection />
|
||||
</SettingsShell>
|
||||
|
||||
@@ -1,10 +1,20 @@
|
||||
import Checkbox from "@moduletrace/twui/form/Checkbox";
|
||||
import type { HarnessOverview, HarnessFormValue, HarnessProviderChoice } from "@/src/types";
|
||||
import type {
|
||||
HarnessOverview,
|
||||
HarnessFormValue,
|
||||
HarnessModelOption,
|
||||
HarnessProviderChoice,
|
||||
} from "@/src/types";
|
||||
import HarnessSeesImagesNote from "./harness-sees-images-note";
|
||||
|
||||
type Props = {
|
||||
harness: HarnessOverview;
|
||||
value: HarnessFormValue;
|
||||
provider?: HarnessProviderChoice;
|
||||
/**
|
||||
* The model the setting runs on (the pick, else what it runs on now).
|
||||
*/
|
||||
model?: HarnessModelOption;
|
||||
falls_back_title?: string;
|
||||
onChange: (value: HarnessFormValue) => void;
|
||||
};
|
||||
@@ -16,6 +26,7 @@ export default function HarnessOptionsCheckboxes({
|
||||
harness,
|
||||
value,
|
||||
provider,
|
||||
model,
|
||||
falls_back_title,
|
||||
onChange,
|
||||
}: Props) {
|
||||
@@ -40,13 +51,16 @@ export default function HarnessOptionsCheckboxes({
|
||||
/>
|
||||
) : null}
|
||||
{harness.harness == "text" ? (
|
||||
<Checkbox
|
||||
title="Use the model's own media reading"
|
||||
label="Use the model's own media reading"
|
||||
info="It looks at images and screenshots itself when it takes image input. Otherwise the media reading model reads them."
|
||||
checked={Boolean(value.sees_images)}
|
||||
changeHandler={(sees_images) => onChange({ ...value, sees_images })}
|
||||
/>
|
||||
<>
|
||||
<Checkbox
|
||||
title="Use the model's own media reading"
|
||||
label="Use the model's own media reading"
|
||||
info="It looks at images and screenshots itself when it takes image input. Otherwise the media reading model reads them."
|
||||
checked={Boolean(value.sees_images)}
|
||||
changeHandler={(sees_images) => onChange({ ...value, sees_images })}
|
||||
/>
|
||||
{value.sees_images ? <HarnessSeesImagesNote model={model} /> : null}
|
||||
</>
|
||||
) : null}
|
||||
{harness.required ? null : (
|
||||
<Checkbox
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { renderToString } from "react-dom/server";
|
||||
import HarnessSeesImagesNote from "./harness-sees-images-note";
|
||||
|
||||
const model = (input_modalities?: string[]) => ({
|
||||
id: 1,
|
||||
provider_id: 1,
|
||||
provider_name: "Alibaba Cloud Token Plan",
|
||||
slug: "qwen3.8-flash",
|
||||
name: "qwen3.8-flash",
|
||||
free: false,
|
||||
input_modalities,
|
||||
});
|
||||
|
||||
describe("HarnessSeesImagesNote", () => {
|
||||
test("says a text-only model won't read anything itself", () => {
|
||||
const html = renderToString(<HarnessSeesImagesNote model={model(["text"])} />);
|
||||
|
||||
expect(html).toContain("listed as taking text only");
|
||||
});
|
||||
|
||||
test("says nothing for a model that takes images", () => {
|
||||
const html = renderToString(
|
||||
<HarnessSeesImagesNote model={model(["text", "image"])} />,
|
||||
);
|
||||
|
||||
expect(html).toBe("");
|
||||
});
|
||||
|
||||
test("says nothing when there's no model to judge", () => {
|
||||
expect(renderToString(<HarnessSeesImagesNote />)).toBe("");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,22 @@
|
||||
import Span from "@moduletrace/twui/layout/Span";
|
||||
import type { HarnessModelOption } from "@/src/types";
|
||||
|
||||
type Props = {
|
||||
model?: HarnessModelOption;
|
||||
};
|
||||
|
||||
/**
|
||||
* A word when the text setting says the model reads its own media but the
|
||||
* catalog has it as text only, so nothing would be read by it: it's a
|
||||
* silencer otherwise (`qwen3.8-flash` on a provider that lists bare ids is
|
||||
* guessed text only, and every reply paid for a media reading call).
|
||||
*/
|
||||
export default function HarnessSeesImagesNote({ model }: Props) {
|
||||
if (!model || model.input_modalities?.includes("image")) return null;
|
||||
|
||||
return (
|
||||
<Span className="text-[13px] leading-[18px] text-ink-secondary">
|
||||
{`${model.name} is listed as taking text only, so the media reading model still reads images for it. Set the text model to one that takes images to use this.`}
|
||||
</Span>
|
||||
);
|
||||
}
|
||||
@@ -73,6 +73,7 @@ export default function HarnessSettingGroup({ harness, value, onChange }: Props)
|
||||
harness={harness}
|
||||
value={value}
|
||||
provider={provider}
|
||||
model={value.inherit ? harness.default?.current : picked || harness.current}
|
||||
falls_back_title={falls_back_title}
|
||||
onChange={onChange}
|
||||
/>
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
import userAuth from "@/src/functions/backend/auth/user-auth";
|
||||
import grabSpeakableMessage from "@/src/functions/backend/db/bots/grab-speakable-message";
|
||||
import grabMessageDetails from "@/src/functions/backend/db/usage/grab-message-details";
|
||||
@@ -11,7 +12,8 @@ import type { APIResponseObject, BunextAPIRouteHandler } from "@moduletrace/bune
|
||||
* `GET ?message_id=`: how one of the bot's messages in the user's own
|
||||
* conversation was generated (the job, every model call with its provider
|
||||
* and model, and the tokens and cost). Loaded when its details modal
|
||||
* opens, so the thread's messages stay small.
|
||||
* opens, so the thread's messages stay small. `&full=1` lists every call
|
||||
* and failure, for the copy of the report.
|
||||
*/
|
||||
export const handler: BunextAPIRouteHandler<APIResponseObject<MessageDetails>> = async ({ req, query }) => {
|
||||
try {
|
||||
@@ -25,7 +27,7 @@ export const handler: BunextAPIRouteHandler<APIResponseObject<MessageDetails>> =
|
||||
return { success: false, msg: `Unauthorized`, logoutUser: true };
|
||||
}
|
||||
|
||||
const { message_id } = parseWithSchema({ schema: MessageDetailsRequestSchema, data: query });
|
||||
const { message_id, full } = parseWithSchema({ schema: MessageDetailsRequestSchema, data: query });
|
||||
const { message } = await grabSpeakableMessage({ user_id: Number(user.id), message_id });
|
||||
|
||||
return {
|
||||
@@ -33,6 +35,7 @@ export const handler: BunextAPIRouteHandler<APIResponseObject<MessageDetails>> =
|
||||
singleRes: await grabMessageDetails({
|
||||
message_id: Number(message.id),
|
||||
created_at: Number(message.created_at) || null,
|
||||
...(full ? { max_calls: AppData.MessageDetailsCopyMaxCalls } : {}),
|
||||
}),
|
||||
};
|
||||
} catch (error: unknown) {
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
import grabSuperAdminUser from "@/src/functions/backend/backups/grab-super-admin-user";
|
||||
import grabComputerWorkspaceQuotaOverview, {
|
||||
type ComputerWorkspaceQuotaOverview,
|
||||
} from "@/src/functions/backend/db/app-settings/grab-computer-workspace-quota-overview";
|
||||
import saveAppSetting from "@/src/functions/backend/db/app-settings/save-app-setting";
|
||||
import logEvent, { grabRequestIP } from "@/src/functions/backend/logger";
|
||||
import { ComputerWorkspaceQuotaSettingKey } from "@/src/dict/computer-dict";
|
||||
import { SaveComputerWorkspaceQuotaRequestSchema } from "@/src/schemas/computer-workspace-quota-schema";
|
||||
import AppError from "@/src/utils/app-error";
|
||||
import parseWithSchema from "@/src/utils/parse-with-schema";
|
||||
import safeErrorMessage from "@/src/utils/safe-error-message";
|
||||
import type { APIResponseObject, BunextAPIRouteHandler } from "@moduletrace/bunext/types";
|
||||
|
||||
/**
|
||||
* Super admin only: the most a computer's workspace may hold, in MB. Only
|
||||
* the limit is stored, so every computer picks a new one up on its next
|
||||
* write without being recreated. Zero sets no limit.
|
||||
*/
|
||||
export const handler: BunextAPIRouteHandler<APIResponseObject<ComputerWorkspaceQuotaOverview>> = async ({
|
||||
req,
|
||||
body,
|
||||
}) => {
|
||||
try {
|
||||
if (req.method != "POST") throw new AppError(`Method not allowed`);
|
||||
|
||||
const user = await grabSuperAdminUser({ req });
|
||||
|
||||
if (!user?.id) throw new AppError(`Only a super admin can change the computer workspace limit.`);
|
||||
|
||||
const { quota_mb } = parseWithSchema({
|
||||
schema: SaveComputerWorkspaceQuotaRequestSchema,
|
||||
data: body,
|
||||
});
|
||||
|
||||
await saveAppSetting({
|
||||
key: ComputerWorkspaceQuotaSettingKey,
|
||||
value: String(quota_mb > 0 ? quota_mb : 0),
|
||||
});
|
||||
|
||||
await logEvent({
|
||||
title: "Computer workspace limit changed",
|
||||
category: "system",
|
||||
user_id: user.id,
|
||||
plain_text: `User #${user.id} set the computer workspace limit to ${quota_mb} MB.`,
|
||||
metadata: { quota_mb },
|
||||
ip_address: grabRequestIP(req),
|
||||
});
|
||||
|
||||
return { success: true, singleRes: await grabComputerWorkspaceQuotaOverview() };
|
||||
} catch (error: unknown) {
|
||||
return { success: false, msg: safeErrorMessage({ error }) };
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,23 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { MessageDetailsRequestSchema } from "./bot-schema";
|
||||
|
||||
describe("MessageDetailsRequestSchema", () => {
|
||||
test("asks for the modal's calls by default", () => {
|
||||
const parsed = MessageDetailsRequestSchema.parse({ message_id: "7" });
|
||||
|
||||
expect(parsed).toEqual({ message_id: 7, full: false });
|
||||
});
|
||||
|
||||
test("reads the report's flag from a query string", () => {
|
||||
expect(MessageDetailsRequestSchema.parse({ message_id: "7", full: "1" }).full).toBe(true);
|
||||
expect(MessageDetailsRequestSchema.parse({ message_id: "7", full: "true" }).full).toBe(true);
|
||||
expect(MessageDetailsRequestSchema.parse({ message_id: "7", full: "0" }).full).toBe(false);
|
||||
expect(MessageDetailsRequestSchema.parse({ message_id: "7", full: false }).full).toBe(false);
|
||||
});
|
||||
|
||||
test("refuses a message it can't read", () => {
|
||||
expect(MessageDetailsRequestSchema.safeParse({ message_id: "0" }).success).toBe(false);
|
||||
expect(MessageDetailsRequestSchema.safeParse({ message_id: "abc" }).success).toBe(false);
|
||||
expect(MessageDetailsRequestSchema.safeParse({}).success).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -220,6 +220,14 @@ export type SpeakBotMessageRequest = z.infer<typeof SpeakBotMessageRequestSchema
|
||||
|
||||
export const MessageDetailsRequestSchema = z.object({
|
||||
message_id: z.coerce.number().int().positive("Pick a message"),
|
||||
/**
|
||||
* `1` lists every call and failure the message took, for its copied
|
||||
* report, instead of the modal's first `MessageDetailsMaxCalls`.
|
||||
*/
|
||||
full: z
|
||||
.union([z.literal("1"), z.literal("true"), z.literal("0"), z.literal("false"), z.boolean()])
|
||||
.optional()
|
||||
.transform((value) => value === "1" || value === "true" || value === true),
|
||||
});
|
||||
|
||||
export type MessageDetailsRequest = z.infer<typeof MessageDetailsRequestSchema>;
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
import { z } from "zod";
|
||||
|
||||
/**
|
||||
* The General settings' computer workspace limit, in MB. Zero means the
|
||||
* install sets no limit.
|
||||
*/
|
||||
export const SaveComputerWorkspaceQuotaRequestSchema = z.object({
|
||||
quota_mb: z.coerce.number().int().min(0).max(10_000_000),
|
||||
});
|
||||
@@ -575,6 +575,12 @@ export type HarnessModelOption = {
|
||||
name: string;
|
||||
free: boolean;
|
||||
voices?: string[];
|
||||
/**
|
||||
* What the model takes, from the catalog. A provider that lists only
|
||||
* ids gets these guessed, so a model it names in a way the guesser
|
||||
* doesn't know is text only.
|
||||
*/
|
||||
input_modalities?: string[];
|
||||
/**
|
||||
* The generation settings the model takes; undefined: all of them.
|
||||
*/
|
||||
@@ -2247,6 +2253,14 @@ export type PagePropsType = {
|
||||
total_files: number;
|
||||
folders: number;
|
||||
} | null;
|
||||
/**
|
||||
* The most one computer's workspace may hold (the General settings
|
||||
* page).
|
||||
*/
|
||||
computer_workspace_quota?: {
|
||||
setting_key: string;
|
||||
quota_mb: number;
|
||||
} | null;
|
||||
/**
|
||||
* The install-wide text appended to every bot's prompt (the General
|
||||
* settings page).
|
||||
|
||||
Reference in New Issue
Block a user