Compare commits

...
7 Commits
Author SHA1 Message Date
tben c892cda0eb Plan a task run before it starts, and read a file once
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
A task run used to work out what the task was while spending its steps:
the same file read again to see it once more, the same folder listed
twice, a plan formed turn by turn at the price of a model call each.

- `planBotTask` spends one turn before the first step on the very system
  prompt the run then sends, so the provider's cache serves it and it
  costs little more than the plan. The bounded JSON plan
  (`BotTaskPlanSchema`) opens the run as `taskPlanNote` and shows as its
  first step line. `shouldPlanBotTask` keeps it off short runs and
  chatroom turns, and a plan that can't be written starts the run the way
  it always did.
- `runTextLoop` answers a read it already made from that answer
  (`RepeatableToolNames`, `repeatToolCallKey`, `alreadyRanToolNote`)
  instead of running it again; any non-read tool clears what was
  remembered, so a file read, edited and read again is read again.
2026-11-13 05:14:07 +01:00
tben b8fd60608d Stop letting a run that did nothing end as a finished task
Five honest "I did nothing" reports in a row left nothing to notice them
by, so the app now has an opinion of its own:

- A reply's wrap up offers start_task beside write_file and import_file,
  so work it can't finish in 20 steps is handed on with a brief instead of
  being promised for later.
- A run that used every step it had blocks the task it was handed
  (trackerTaskEnding), rather than leaving it open under a "run finished"
  note.
- A full workspace names the folder holding the space and whether the run
  can clear it (computerWorkspaceSpace), the agent reports the folder
  sizes with its usage, a failed measurement no longer reads as 0, and a
  daily cron logs a computer past 80% of its quota.
- A message's details count its run's calls by tool (MessageToolsRollup),
  so 242 calls read as one line rather than 242 rows.
2026-11-13 04:59:18 +01:00
tben 1bf50b717b Bump version to 0.18.7
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
2026-11-13 04:42:16 +01:00
tben c6697c91cd Hold the full pull before letting go reloads it
Opening the room is easy to do by accident on a thread whose scroll is
already exhausted, so reaching the limit no longer reloads on its own: the
finger has to stay on the full room for half a second, which lights the icon
so the release is the user's decision, and a release before that closes the
room and reads nothing. A finger that rests fires no further touch moves, so
a timer notices the hold, not the moves, and dragging back down starts it
over.

The gesture's geometry and its hold now live in AppData with the other
conversation timings, and the refocus debounce both use-refocus and
use-connection-epoch were carrying separately is one AppData.RefocusGapMs.
2026-11-13 04:38:19 +01:00
tben 8d7309084f Refresh the conversation when the page comes back, and let a phone pull it
A thread that missed its pushes while the phone slept kept its thinking row
and a stale face until the page was reloaded. Every return to the page
(window focus, a hidden tab visible, back online) now reads the crew again
(api/admin/bots/live-crew -> cobble:live-crew-refreshed, taken by both
rails) and the session's latest messages, its bot's face and its task,
whether or not a reply is due, which is what the catch-up refused to do
before. The history is not reloaded: that would drop the older messages
loaded above it.

On a phone, pulling the thread up past its bottom lifts the newest message
off the edge, opening just enough room for a refresh icon (a ghost button,
no label) and letting go once that room is full reloads the conversation and
the rail, with the spinner up for at least a second. The room is written
straight onto the content as the finger moves, never through a render, the
pull owns the gesture until release, and a finger that rested first is a
selection, not a pull.
2026-11-13 04:27:08 +01:00
tben 6f26222e2c Bump version to 0.18.6
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
2026-11-12 20:59:39 +01:00
tben 343fdb2d25 Make every bot ask before it widens a request
A production coordinator was asked only to create two bots. It placed
both in a workspace and handed each a task, then explained the extra
steps as the user's saved preference that new bots get put to work.

- RequestScopeNote, injected into every reply and task, says the request
  sets the scope, that memory, habits, routines and initiative never
  widen it, and that crew changes (create, place, remove, assign a
  computer, change a role) and handing work out (delegating, handing over
  a task or routine) happen only after the user asked for them: one
  ask_user card in a reply or task, and a proposal in the report where
  nobody watches (routine, hook call, chatroom).
- A decline is dropped, not done smaller and not re-offered.
- The memory sections of composeBotPrompt say memory shapes how the bot
  does the work, never what it does beyond the request.
- The default coordinator prompt says a request to create a bot is a
  request for that bot alone; existing installs keep their stored prompt
  and get the rule from the note.
2026-11-12 20:59:35 +01:00
73 changed files with 2764 additions and 256 deletions
+10 -7
View File
@@ -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-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`.
`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`), `warn-computer-workspaces` (logs a computer whose workspace passed `AppData.ComputerWorkspaceWarnShare` of its quota, daily, reports only), `prune-logs`.
### Admin CRUD API
@@ -92,7 +92,7 @@ Enables SQLite foreign keys (`enableForeignKeys`), `bunextInit()`, `ensureDocker
- **Coordinator:** exactly one, the super admin's alone, created idempotently by `ensureCoordinatorBot`. Default prompt `src/data/coordinator-system-prompt.ts`, backfilled only when empty.
- **Routes:** `/admin/bots` reopens the last visited bot's own chat (cookie `cobble_last_visited_bot_id`, `<bot>` or `<bot>:<workspace>`; the landing uses only the bot) if still reachable, else coordinator (super admin) / latest bot / first workspace / empty. Workspace and conversation pages record the visit per user (`recordWorkspaceVisit`/`workspace_user_visits`, `recordBotVisit`/`bot_user_visits`) and the rail lists both latest visited first (`last_visited_at`, `orderByLastVisit`; a workspace nobody visited yet ranks by its creation, so a new one leads); it never decides the landing. Settings and the rail pages get the cookie's conversation, workspace included, as root prop `last_conversation` (`grabLastConversation`, access-checked, only on those paths: `isPagesRailPath`), shown above their rail list as the way back (`RailLastConversation`). `/admin/bots/[bot_id]` conversation (header, thread and composer at 760px, no right panel; `?session_id=` opens another of the user's sessions there: a closed one is reopened, except a carried-over one, which shows with `SessionMovedBar` instead of the composer, pointing where the conversation went on); `/admin/bots/[bot_id]/models`; `/admin/workspaces/[id]` dashboard; `/admin/workspaces/[id]/chatrooms` that workspace's chatrooms; `/admin/workspaces/[id]/bots/[bot_id]` same conversation scoped to the workspace.
- **No model:** while the bot has no text model there (`bot_text_model` null, kept live by the models modal), the thread shows `NoModelNotice` (centred when empty): super admins get Connect a provider / Guided setup, others are told the super admin sets it up.
- **Conversation loading:** pages render everything server-side (`grabConversationProps`) **except the history**, which the client loads (`api/admin/bots/conversation-history`, merged with what's already shown, refetched on bfcache restore) and pages older messages on scroll. Rail lists go through `railBots`/`railWorkspaces` (no prompts/memory, previews cut). While a reply is due (read with the live face, never the page's) the page polls `session-messages` (`use-reply-catch-up`, also at once when the page comes back into view or online) in case a push was missed, replaying the messages and the bot's face and task as their pushes.
- **Conversation loading:** pages render everything server-side (`grabConversationProps`) **except the history**, which the client loads (`api/admin/bots/conversation-history`, merged with what's already shown, refetched on bfcache restore) and pages older messages on scroll. Rail lists go through `railBots`/`railWorkspaces` (no prompts/memory, previews cut). Every return to the page (window focus, a hidden tab visible, back online: `use-refocus`, `AppData.RefocusGapMs`) reads the crew again (`use-live-crew-refresh` -> `api/admin/bots/live-crew` -> `cobble:live-crew-refreshed`, taken by `useLiveBots`/`useLiveWorkspaces`) and the session's latest messages plus its bot's face and task (`session-messages`, `use-reply-catch-up`), and the page polls the same while a reply is due (read with the live face, never the page's): pushes missed while the phone slept left threads thinking and faces stale until a reload. On a phone, pulling the thread up past its bottom lifts the newest message off the edge, opening just enough room for a lone refresh icon (a ghost button, no label; no deeper, however far the drag goes), and letting go only reloads once that full room has been held for half a second, which lights the icon (`AppData.PullToRefreshHoldMs`: an exhausted thread reaches the limit by accident too easily) and then turns it into its spinner for at least a second (`AppData.PullToRefreshMinLoadingMs`) while the conversation and the rail are read again (`use-pull-to-refresh` writes that room straight onto the content as the finger moves, never through a render, and owns the gesture until release; `PullToRefreshIndicator`; dragged back down before the release, the icon hides at the travel that showed it).
- **Sending:** `api/admin/bots/send-message.ts` -> `enqueueBotReply` -> `wakeBotsQueue`. **Never import `src/bots-queue/index.ts` from a page or API route** (pulls the bunext runtime into page bundles). Optimistic bubble in `pending_messages` until the saved message replaces it. A message is capped at the app setting `bot_message_max_chars` (Settings > General, default `AppData.BotMessageMaxChars`, counted on the trimmed markdown), checked by the composer before it sends (the reason shows under the input) and again by the route.
- **Composer:** Tiptap editor reading/writing markdown, drafts in `localStorage`, `@` bots / `#` workspaces written as `[bot:ID]`/`[workspace:ID]`. Enter sends (Mod+Enter in lists/code). `@tiptap/react` needs `use-sync-external-store`; the app ships an ESM stand-in in `packages/use-sync-external-store-esm` (file dependency + override; the Dockerfile copies `packages/` before `bun install`).
- **Rendering:** markdown via `react-markdown` + `remark-gfm`, raw HTML never rendered, component map in `[bot_id]/(data)/message-markdown-components.tsx`. Inline refs, all linked by `link-computer-refs.ts` and rendered by chips in `(partials)/`: `[bot:ID]`, `[workspace:ID]`, `[computer:ID]`, `[file:ID]` (a saved file), `[folder:<volume>:<owner>:<path>]` (opens `FolderPreviewModal`, the files browser's listing over the chat, files opening their own preview; a modified click or its Open in Files goes to `/admin/files`), `[take-over:ID:mode]`, `[proposal:ID]`, `[hook-proposal:ID]`, `[secret:ID]` (masked env, Reveal/Copy), `[secret-request:ID]` (masked input card), `[question:ID]` (a bot's questions), `[graphic:ID]` (a bot graphic, framed inline), `[room:ID]` (a chatroom), `[task:ID]` (a tracker task, opening `TaskDetailModal`). Parsers in `src/utils/*-ref.ts`. Anywhere else that renders bot-written markdown with `MessageMarkdownComponents` (a workspace's context on its dashboard, a task's description and notes through `TaskMarkdown`) runs it through `linkComputerRefs` and provides `CrewBotsContext`/`CrewWorkspacesContext` too. A ref quoted alone in a code span still links; one inside longer code stays literal (`linkComputerRefs` splits out code first). A file chip opens a file from another bot's folder for a user who reaches that folder (`userReachesFileScope`, the same rule as its bytes), so answers passed on from chatrooms keep working.
@@ -112,13 +112,16 @@ Enables SQLite foreign keys (`enableForeignKeys`), `bunextInit()`, `ensureDocker
### Prompt and memory
`composeBotPrompt` (`src/utils/compose-bot-prompt.ts`, via `grab-bot-prompt`): core `system_prompt`, install-wide append (`bot_system_prompt_append`), then in a workspace its context, the bot's instructions there and the run's user's role there (`workspace_user_roles`), then core `memory`, per-user memory (`bot_user_memories`), workspace memory (`workspace_bots.memory`). Core memory is never about one user. `update_memory` defaults to `user` (`workspace` in a workspace); core only for what holds for everyone. Whole-text replace, capped at `AppData.PromptMaxLength`.
`composeBotPrompt` (`src/utils/compose-bot-prompt.ts`, via `grab-bot-prompt`): core `system_prompt`, install-wide append (`bot_system_prompt_append`), then in a workspace its context, the bot's instructions there and the run's user's role there (`workspace_user_roles`), then core `memory`, per-user memory (`bot_user_memories`), workspace memory (`workspace_bots.memory`). Core memory is never about one user. `update_memory` defaults to `user` (`workspace` in a workspace); core only for what holds for everyone. Whole-text replace, capped at `AppData.PromptMaxLength`. Each memory section says it shapes how the bot does the work, never what it does beyond the request.
Every run also gets `RequestScopeNote` (`src/data/harness-prompts.ts`): the user's request sets the scope, and crew changes (create, place, remove, assign a computer, change a role) and handing work out (delegating, handing over a task or routine) happen only once the user asked for them, through one `ask_user` card in a reply or task, or as a proposal in a run nobody watches (routine, hook call, chatroom). Memory, habits and the bot's own initiative never widen a request.
### Queue (`bots_queue`)
- Kinds (`BotJobKinds`): `reply` (chat answer, no task row) and `task` (long work, usually on a computer). bun-sqlite `isQueue` table. Helpers in `src/functions/backend/db/bots-queue/`: `enqueueBotJob`, `claimBotJobs` (kind-filtered atomic claim), `updateBotJob` (false once lost/cancelled), `completeBotJob`, `failBotJob` (backoff or fatal), `deferBotJob` (all models resting: attempt refunded, face `asleep`), `cancelBotJob`, `stop-bot-jobs`.
- Handler `src/bots-queue/index.ts`: separate reply/task slots, heartbeat, per-attempt deadline (`AppData.BotJobAttemptTimeoutMs`), one task per computer and one reply per session (`createKeyLock`). A chatroom job never waits for a busy computer (the asking bot is often the one holding it): it runs beside it with the shell and files but no browser (`computer_shared`, `openComputerTools({ browser: false })`). Work in `run-bot-job.ts` -> `run-bot-reply.ts` / `run-bot-task.ts`. Throw `BotJobFatalError` for failures retrying can't fix. A computer that's down (`isComputerDown`: failed, dead, exited) is one: `start_task` refuses it and a task run on it fails at once.
- Every model turn is a step in `bots_queue_updates` (tool names, never arguments; `describe-job-step.ts`, labels in `JobStepToolLabels`), pushed as `server:bot-job-update` by the live relay only. Steps feed the live working row alone: the `clear-job-steps` cron deletes them `AppData.BotJobStepsKeepMs` after the job ends, however it ended, keeping their count on `bots_queue.steps`. Never delete them the moment a job ends (the relay would miss the last ones).
- **A task run plans before it starts:** `planBotTask` (from `run-bot-task`) spends one turn, no tools, on the very system prompt the run then sends, so the provider's cache serves it and it costs little more than the plan. The answer is a bounded JSON plan (`BotTaskPlanSchema`, caps in `AppData.BotTaskPlan*`) that opens the run as `taskPlanNote` and shows as its first step line; `shouldPlanBotTask` keeps it off short runs (`AppData.BotTaskPlanMinSteps`) and chatroom turns. A plan that can't be written or read starts the run unplanned, never blocks it.
- **A bot can't vouch for itself:** a run's tool calls (`tool_uses`, names and ok, never arguments) go to the wrap-up turn when steps run out and onto the result message as `bot_messages.tool_log`; history follows each recorded bot message with an `[App record: ...]` line (`botMessagesToHarness`), and copies of that line in an answer are stripped (`stripAppRecords`). Before a reply goes out, `reviewBotReply` (the loop's `review`, once per run) sends it back when it names a `[file:ID]`/`[task:ID]` that doesn't exist for the user, or says work is under way or a report will follow (`claimsWorkUnderWay`) with no `start_task`/`delegate_task`/`ask_crew` this reply and nothing open from the session: bots wrote "I'm scanning now" plus made-up results in one answer. A long bot message whose run called no tools shows "No tools used" (`MessageNoToolsChip`).
- **`start_task`/`delegate_task` jobs are runs, not tasks:** their results say `Run #<job id>` and that `list_tasks` doesn't show them (bots sent users to the tracker for them). `start_task` refuses a second open run in its session on the same computer unless `separate` (it would only wait behind it) and says how many runs are ahead on that computer. Its `max_steps` (`params.max_steps`) caps the run below the install's limit; the brief alone never did. Nothing wakes a bot when a run ends, so different follow-up work is queued at once with `separate`, never promised for later (`start_task`, `chatReplyNote`).
- **Replies take in messages sent mid-run** (`incoming`, `IncomingMessagesNote`, redraft); separate requests are acknowledged with `send_message` (interim). A queued reply finishes silently only when a finished reply already read every user message (`hasUnansweredMessage`), never by who wrote last. **Task runs take them in too** (`taskIncoming`, only runs the user follows: no routines, hook calls or rooms): everything the user wrote since the run was queued, at the start, between steps, past a report not yet out and by the wrap up (`incoming_notes`, `TaskIncomingNote`); a correction changes the work, anything else is left to the chat, and crew messages to the reply they wake. A reply is told which runs open in its session hear the user (`openRunsNote`), so a correction never starts a second run.
@@ -141,7 +144,7 @@ A worker reaches another worker **only through the coordinator**: `ask_crew` (ev
- 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. **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`).
- **The workspace has a limit** (`computer_workspace_quota_mb`, Settings > General, default `AppData.ComputerWorkspaceQuotaMb`, 0 = none): it is the one folder on a computer mounted from the data volume, so it is what can fill the host. The agent measures it (`GET /api/usage` -> `grabComputerUsage`, `du` cached 10s, per-folder figures with it: `bots/<id>` and `workspaces/<id>`, highest first); the app refuses a write that would pass it (`computerWorkspaceRoomError` in `computer_write_file`/`computer_edit_file`), reports it after `computer_bash` and after a browser call that wrote a file (`computerWorkspaceFullWarning`, screenshots and downloads included) and bash still works, since it is how a bot cleans up. A refusal names the folder holding the space and whether the run can clear it (`computerWorkspaceSpace`: its own folder or its workspace's, else another bot's, which it can only report); nothing prunes that folder, so the daily `warn-computer-workspaces` cron logs an install past the quota rather than letting it fill quietly. A run's caches go to the account's own home inside the container, never its folder (`computerCacheEnv`).
- One main computer (`ensureMainComputer`), whose coordinator grant is locked (`isLockedComputerAccess`). With `MAIN_COMPUTER_URL` set (dev) it isn't provisioned. Only super admins create/delete/retry/restart computers. Restart (`ComputerRestartButton`, in the shared viewer modal, so every computer modal has it) restarts the same container, so what's installed stays, even with a job on it (`restartComputer`, clearing Chrome's `Singleton*` links while stopped; a container docker lost is provisioned instead).
- A bot's effective computers (`grab-bot-computers`): the workspace's in a workspace; otherwise direct grants plus its workspaces' (coordinator: all); `bots.computer_id` first. Only a `running` (healthy) computer is reached (`grabComputerMcpUrl` `ready`, `computerNotReadyMessage`).
- **Folders:** a run works only in its user's folder (cwd, `HOME`), its bot's and its workspace's (`computerRunDirs`, `withComputerDirs`, `resolveComputerPath`). **A worker sees them through its home:** `/home/cb-<bot>/workspace` (a link the agent keeps to `bots/<bot>`, checked every request by `ensureRunUser`; the rest of the home stays in the container and is never kept), with `users/<user>` and, in a workspace, `workspaces/<id>` (a link to the shared `workspaces/<id>`) inside it; the coordinator works in `bots/<bot>/users/<user>` and reaches the whole workspace. Paths are checked on their real place (`computerWorkspacePath`) and shown to a worker its way (`computerRunPath`); computer folder refs take either spelling. Linux enforces it between bots: **every worker works as its own account** `cb-<bot>` (uid `100000 + id`, no sudo, `ComputerRunDirs.run_as` -> the agent's `run_as`, made by `ensureRunUser`, commands through `setpriv --init-groups`), owning `bots/<bot>` (`2770`); a workspace's folder (root's) belongs to group `cw-<id>` its bots join. **`gem`, and so Chrome, has no way into either** (a page could show another bot's files): a worker's downloads (`collectComputerDownloads`), uploads and files saved by name (`withWorkerBrowserFiles`) pass through a folder of the call's own and are copied by the worker's account (`sudo -u`), never written by `gem` into its folder, and a worker opens no `file:` URLs (it serves its pages on localhost). Its env files are in its own home. A worker can't reach the computer's services: the agent's nftables rule (`guardServicePorts`, container `CapAdd: NET_ADMIN`) resets its connections to the agent, CDP, Playwright MCP, VNC and ttyd, and the X display needs gem's cookie; **without the rule the agent refuses everything for a worker** (never falls back to `gem`). The agent reads files for a worker only inside its folders and home, checked on the open descriptor (`openRunFile`), and writes as the worker (`writeFileAs`). Only the coordinator works as `gem` (sudo). Users within one bot's folder aren't separated by Linux (same account). Keep `computerWorkerAccount` and `runUserFor` alike.
@@ -161,7 +164,7 @@ A secret URL, `POST /api/hooks/<token>` (`src/pages/api/hooks/[token].ts`, publi
### Tasks (the to-do tracker)
`tasks` (**a task belongs to a bot by default**, the coordinator included: a bot's own list is `bot_id` alone, a workspace's task has `workspace_id` plus the `bot_id` that has it there; the one exception is a **workspace-wide** task (`workspace_id`, `bot_id` null), only when asked for (`workspace_wide`, enforced by `taskScopeValues`), which every bot working there sees and works on; a worker reaches its own plus the workspace-wide ones in its workspaces, a workspace admin all of that workspace's, the coordinator all, `botTaskScopesSql`; on a workspace-wide task `update_task` logs each call's status move and filed files as a note under the bot (`task_notes.bot_id`), and `list_tasks` with `task_id` reads the whole log with who and when; the coordinator and a workspace's admin bot (`update_task` `workspace_wide`) or a crew manager (Make workspace-wide, `api/admin/tasks/make-workspace-wide`) turn a bot's open workspace task workspace-wide (`makeTaskWorkspaceWide`, noted in its log; never a bot's own list), and hand-over gives one back to a single bot; a bot removed from a workspace or deleted passes its own tasks there to the workspace's admin bot, else the coordinator (`passOnBotTasks`), workspace-wide ones stay), `task_notes`, `task_media` (deliverable|reference). Not the same as `bot_tasks`/`bots_queue` (those record jobs). Visibility SQL in `src/utils/task-access/`. Helpers in `src/functions/backend/db/tasks/`; tools `list_tasks`/`create_task`/`update_task` (which also renames a task and rewrites its brief, refusing an open twin's title, and unlinks bot files with `unlink_file_ids`: a task holds `AppData.TaskMediaMaxPerTask` files; `list_tasks` with `task_id` lists them) and, in chat replies the user follows only (never routines, hook calls or rooms), `delete_task`; API `api/admin/tasks/` (`userAuth` -> `isReadOnlyUser` -> `assertUserReachesTask` -> `safeErrorMessage`). UI in the workspace dashboard and the header's Tasks modal (shared components in `src/components/general/`); a card's title opens `TaskDetailModal` with everything about the task and its status moves (a modal over the list, never swapped in place). **Hand-over:** `handOverTask` (bot: `delegate_task` with `task_id`; UI: Hand over, crew managers) moves an open task to the new bot (a workspace's stays in the workspace, now the new bot's, and is worked there), sets it doing and queues a job with `params.tracker_task_id` (with `start: false` it only moves it, as to do, no job: for "take it and wait for the go-ahead"); `noteTrackerTask` notes the job's end on it and blocks it on failure. **Not built yet:** task steps, `server:task-changed` pushes, a `/admin/tasks` page.
`tasks` (**a task belongs to a bot by default**, the coordinator included: a bot's own list is `bot_id` alone, a workspace's task has `workspace_id` plus the `bot_id` that has it there; the one exception is a **workspace-wide** task (`workspace_id`, `bot_id` null), only when asked for (`workspace_wide`, enforced by `taskScopeValues`), which every bot working there sees and works on; a worker reaches its own plus the workspace-wide ones in its workspaces, a workspace admin all of that workspace's, the coordinator all, `botTaskScopesSql`; on a workspace-wide task `update_task` logs each call's status move and filed files as a note under the bot (`task_notes.bot_id`), and `list_tasks` with `task_id` reads the whole log with who and when; the coordinator and a workspace's admin bot (`update_task` `workspace_wide`) or a crew manager (Make workspace-wide, `api/admin/tasks/make-workspace-wide`) turn a bot's open workspace task workspace-wide (`makeTaskWorkspaceWide`, noted in its log; never a bot's own list), and hand-over gives one back to a single bot; a bot removed from a workspace or deleted passes its own tasks there to the workspace's admin bot, else the coordinator (`passOnBotTasks`), workspace-wide ones stay), `task_notes`, `task_media` (deliverable|reference). Not the same as `bot_tasks`/`bots_queue` (those record jobs). Visibility SQL in `src/utils/task-access/`. Helpers in `src/functions/backend/db/tasks/`; tools `list_tasks`/`create_task`/`update_task` (which also renames a task and rewrites its brief, refusing an open twin's title, and unlinks bot files with `unlink_file_ids`: a task holds `AppData.TaskMediaMaxPerTask` files; `list_tasks` with `task_id` lists them) and, in chat replies the user follows only (never routines, hook calls or rooms), `delete_task`; API `api/admin/tasks/` (`userAuth` -> `isReadOnlyUser` -> `assertUserReachesTask` -> `safeErrorMessage`). UI in the workspace dashboard and the header's Tasks modal (shared components in `src/components/general/`); a card's title opens `TaskDetailModal` with everything about the task and its status moves (a modal over the list, never swapped in place). **Hand-over:** `handOverTask` (bot: `delegate_task` with `task_id`; UI: Hand over, crew managers) moves an open task to the new bot (a workspace's stays in the workspace, now the new bot's, and is worked there), sets it doing and queues a job with `params.tracker_task_id` (with `start: false` it only moves it, as to do, no job: for "take it and wait for the go-ahead"); `noteTrackerTask` notes the job's end on it, blocks it on failure, and blocks it too when the run used every step it had without finishing (`trackerTaskEnding`, so a run measured to its last step no longer leaves the task silently open). **Not built yet:** task steps, `server:task-changed` pushes, a `/admin/tasks` page.
### Envs
@@ -214,7 +217,7 @@ 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 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.
- **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`, and `start_task` for work the run can't finish: a 20-step reply used for research otherwise left the writing undone and the next reply had the same budget) for a saving-or-hand-off 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. A read the run already made is answered from that answer (`RepeatableToolNames`, `repeatToolCallKey`, `alreadyRanToolNote`): calling `read_file`, `list_files`, `search_knowledgebase`, `list_tasks` and the like again with the same arguments returns a pointer to the output above instead of running again, and any non-read tool (a write, `computer_bash`) clears what was remembered, so a file read, edited and read again is read again.
- **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`).
@@ -227,7 +230,7 @@ Read-only browser of every volume (`src/utils/storage-volumes.ts`: bots, workspa
- Every model call writes a `token_usages` row via `record-harness-usage.ts` (never throws) in `withCandidates`'s `on_success`, with the provider/model that actually answered and the call's settings (`HarnessCallSettings`).
- Attribution through an `AsyncLocalStorage` scope (`src/harness/usage/harness-usage-scope.ts`) entered once in `run-bot-job.ts`; merged, not replaced; `null` clears a field. `withUsageScope` / `runWithFallbackScope` for calls outside a run. No owner, no row.
- Every failed model call also writes a `harness_call_failures` row (`recordHarnessFailure`, beside the log in `withCandidates`: model, pick, HTTP status, the provider's reason, rest), same attribution, no foreign keys, pruned with the logs' retention by `prune-logs`.
- `attachJobCallsToMessage` back-fills `message_id` for the job's calls and failures, from `complete-bot-job.ts` and `notify-bot-job-failed.ts` (so a failure notice shows why). Messages show `MessageUsageChip` and a details modal (`grabMessageDetails`, failed calls listed with their reasons).
- `attachJobCallsToMessage` back-fills `message_id` for the job's calls and failures, from `complete-bot-job.ts` and `notify-bot-job-failed.ts` (so a failure notice shows why). Messages show `MessageUsageChip` and a details modal (`grabMessageDetails`, failed calls listed with their reasons, and the run's calls counted by tool from `bot_messages.tool_log` in `MessageToolsRollup`: 242 model calls read differently once it says `computer_bash` 210, `start_task` 0).
- `/admin/usage` (crew managers). **Days are local, not UTC:** group with `date(created_at / 1000, 'unixepoch', 'localtime')`; never name a local day with `toISOString().slice(0, 10)` (`bucket-usage-days.test.ts` pins this). Bars use static `h-*` classes from `(data)/usage-bar-heights.ts`.
### Installer and release
+10 -4
View File
@@ -4,11 +4,17 @@ 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
* `GET /api/usage`: what the computer's workspace holds, and its biggest
* folders (`workspaceUsage`). Only sizes: what may be written there is the
* app's call (`grabComputerWorkspaceQuotaBytes`), so changing the limit
* needs no new container.
* needs no new container. The folders are how a full one is told apart from
* a bot's own overrun, which the app says in its refusal.
*/
export default async function handleUsage({ res }: { req: IncomingMessage; res: ServerResponse }) {
sendJson({ res, body: { used_bytes: await workspaceUsage(), workspace_dir: AgentConfig.WorkspaceDir } });
const { bytes, folders } = await workspaceUsage();
sendJson({
res,
body: { used_bytes: bytes, workspace_dir: AgentConfig.WorkspaceDir, folders },
});
}
+112 -19
View File
@@ -2,11 +2,34 @@ 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.
* One folder inside the workspace, with what it holds: `bots/9` is a bot's
* folder, `workspaces/3` a workspace's shared one.
*/
let measured = { bytes: 0, at: 0 };
export type WorkspaceFolderUsage = {
/**
* Relative to the workspace root, e.g. `bots/9`.
*/
path: string;
bytes: number;
};
/**
* What the workspace holds, and the biggest folders in it. The whole
* folder, every bot's and user's included, is what grows on the data
* volume; the folders are what says whose it is.
*/
export type WorkspaceUsage = {
bytes: number;
folders: WorkspaceFolderUsage[];
};
/**
* When the workspace was last measured, and what it held. A measurement
* that fails keeps the last one: reporting 0 would let writes through a
* quota the app can't see (and `du` on a workspace full of small files can
* outlast its timeout).
*/
let measured: { usage: WorkspaceUsage; at: number } | null = null;
/**
* Measuring walks the whole workspace, so a run writing several files in a
@@ -16,29 +39,99 @@ let measured = { bytes: 0, at: 0 };
const CacheMs = 10_000;
/**
* How many bytes the workspace holds, measured with `du` (which reads the
* folders in C) and reused for `CacheMs`.
* How many of the biggest folders are named: enough that the one filling
* the volume is there, few enough to say in a sentence.
*/
export async function workspaceUsage() {
if (measured.at && Date.now() - measured.at < CacheMs) return measured.bytes;
const FoldersShown = 5;
measured = { bytes: await measureWorkspace(), at: Date.now() };
/**
* The workspace's folders whose size is reported: a bot's, a workspace's,
* and anything else sitting at the top.
*/
const GroupedFolders = ["bots", "workspaces"];
return measured.bytes;
/**
* What the workspace holds, measured with `du` (which reads the folders in
* C) and reused for `CacheMs`.
*/
export async function workspaceUsage(): Promise<WorkspaceUsage> {
if (measured && Date.now() - measured.at < CacheMs) return measured.usage;
const usage = await measureWorkspace();
if (!usage) return measured?.usage || { bytes: 0, folders: [] };
measured = { usage, at: Date.now() };
return usage;
}
/**
* The workspace's size through `du` (bytes), 0 when it can't be read: a
* missing folder holds nothing.
* The workspace's size and its biggest folders through `du`, or null when
* it can't be read.
*/
function measureWorkspace() {
return new Promise<number>((resolve) => {
execFile("du", ["-s", "-B1", "--", AgentConfig.WorkspaceDir], { timeout: 30_000 }, (error, stdout) => {
if (error) return resolve(0);
return new Promise<WorkspaceUsage | null>((resolve) => {
execFile(
"du",
["-B1", "--max-depth=2", "--", AgentConfig.WorkspaceDir],
{ timeout: 30_000, maxBuffer: 16 * 1024 * 1024 },
(error, stdout) => {
if (error) return resolve(null);
const bytes = Number(String(stdout).trim().split(/\s+/)[0]);
resolve(Number.isFinite(bytes) && bytes > 0 ? bytes : 0);
});
resolve(parseDu(String(stdout)));
},
);
});
}
/**
* `du`'s lines (`<bytes>\t<path>`) as the whole workspace and the folders
* that make it up: each bot's and each workspace's own, and whatever else
* sits at the top. A passthrough folder (`bots`, `workspaces`) is only
* counted through its children.
*/
function parseDu(stdout: string): WorkspaceUsage {
const root = AgentConfig.WorkspaceDir.replace(/\/+$/, "");
const deep: WorkspaceFolderUsage[] = [];
const shallow = new Map<string, number>();
let bytes = 0;
for (const line of stdout.split("\n")) {
const [size, path] = line.split("\t");
const value = Number(size);
if (!path || !Number.isFinite(value) || value <= 0) continue;
if (path == root) {
bytes = value;
continue;
}
const relative = path.startsWith(`${root}/`) ? path.slice(root.length + 1) : "";
const [top, second] = relative.split("/");
if (!top || !GroupedFolders.includes(top)) {
shallow.set(relative, value);
continue;
}
if (second) deep.push({ path: relative, bytes: value });
else shallow.set(relative, value);
}
const folders = [...deep, ...[...shallow].map(([path, value]) => ({ path, bytes: value }))];
/**
* A passthrough folder with children is only counted through them: its
* own total would show every bot's folder twice.
*/
const grouped = new Set(deep.map((folder) => folder.path.split("/")[0]));
return {
bytes: bytes || folders.reduce((total, folder) => total + folder.bytes, 0),
folders: folders
.filter((folder) => !(shallow.has(folder.path) && grouped.has(folder.path)))
.sort((left, right) => right.bytes - left.bytes)
.slice(0, FoldersShown),
};
}
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "cobble",
"version": "0.18.5",
"version": "0.18.8",
"module": "index.ts",
"type": "module",
"private": true,
+17
View File
@@ -0,0 +1,17 @@
import { z } from "zod";
import { AppData } from "@/src/data/app-data";
/**
* The plan a task run writes for itself before its first step
* (`planBotTask`). Validated because it comes back from a model: anything
* that doesn't fit starts the run unplanned instead of steered by
* nonsense.
*/
export const BotTaskPlanSchema = z.object({
goal: z.string().trim().min(1).max(AppData.BotTaskPlanTextMaxChars),
gather: z.array(z.string().trim().min(1)).max(AppData.BotTaskPlanMaxGather).default([]),
steps: z.array(z.string().trim().min(1)).min(1).max(AppData.BotTaskPlanMaxSteps),
done: z.string().trim().max(AppData.BotTaskPlanTextMaxChars).default(""),
});
export type BotTaskPlan = z.infer<typeof BotTaskPlanSchema>;
+2 -30
View File
@@ -1,10 +1,6 @@
import {
JobStepBrowserToolInfix,
JobStepToolLabels,
JobStepToolPrefixLabels,
type BotJobUpdateKind,
} from "@/src/dict/bot-queue-dict";
import type { BotJobUpdateKind } from "@/src/dict/bot-queue-dict";
import type { TextLoopStep } from "@/src/harness/text/run-text-loop";
import toolLabel from "@/src/utils/tool-label";
/**
* Longest step line kept: the chat shows one line per step.
@@ -54,27 +50,3 @@ function firstLine({ text }: { text: string | null }) {
return line.length > MaxStepChars ? `${line.slice(0, MaxStepChars - 1)}…` : line;
}
function toolLabel({ name }: { name: string }) {
if (name.includes(JobStepBrowserToolInfix)) return JobStepToolPrefixLabels.browser_ as string;
const prefix = Object.keys(JobStepToolPrefixLabels).find((p) => name.startsWith(p));
return JobStepToolLabels[name] || (prefix && JobStepToolPrefixLabels[prefix]) || `Using ${readableToolName({ name })}`;
}
/**
* A tool name in words: `get_weather` reads "get weather", and an MCP
* server's `<slug>__<tool>` reads "Exa search (web search exa)".
*/
function readableToolName({ name }: { name: string }) {
const words = (part: string) => part.replace(/_+/g, " ").trim();
const [server, ...rest] = name.split("__");
const tool = words(rest.join(" "));
if (!tool) return words(name);
const server_words = words(server || "");
return `${server_words.charAt(0).toUpperCase()}${server_words.slice(1)} (${tool})`;
}
@@ -0,0 +1,56 @@
import { describe, expect, test } from "bun:test";
import { AppData } from "@/src/data/app-data";
import parseBotTaskPlan from "./parse-bot-task-plan";
const plan = {
goal: "Ship the release notes",
gather: ["docs/changelog.md"],
steps: ["Read the changelog", "Write the notes", "Publish them"],
done: "The notes are on the site",
};
describe("parseBotTaskPlan", () => {
test("reads a plan", () => {
expect(parseBotTaskPlan({ text: JSON.stringify(plan) })).toEqual(plan);
});
test("tolerates a code fence and a sentence around the object", () => {
const fenced = `Here is the plan:\n\`\`\`json\n${JSON.stringify(plan)}\n\`\`\`\nReady.`;
expect(parseBotTaskPlan({ text: fenced })).toEqual(plan);
});
test("fills what a plan may leave out", () => {
expect(parseBotTaskPlan({ text: `{"goal":"G","steps":["one"]}` })).toEqual({
goal: "G",
gather: [],
steps: ["one"],
done: "",
});
});
test("is null when it isn't a plan", () => {
expect(parseBotTaskPlan({})).toBeNull();
expect(parseBotTaskPlan({ text: null })).toBeNull();
expect(parseBotTaskPlan({ text: "" })).toBeNull();
expect(parseBotTaskPlan({ text: "I will just do it." })).toBeNull();
expect(parseBotTaskPlan({ text: "{nope" })).toBeNull();
expect(parseBotTaskPlan({ text: `{"goal":"G"}` })).toBeNull();
expect(parseBotTaskPlan({ text: `{"goal":"","steps":["one"]}` })).toBeNull();
expect(parseBotTaskPlan({ text: `{"goal":"G","steps":[]}` })).toBeNull();
});
test("caps how much a plan may ask for", () => {
const too_many = {
goal: "G",
steps: Array.from({ length: AppData.BotTaskPlanMaxSteps + 1 }, (_, index) => `step ${index}`),
};
expect(parseBotTaskPlan({ text: JSON.stringify(too_many) })).toBeNull();
expect(
parseBotTaskPlan({
text: JSON.stringify({ ...too_many, steps: too_many.steps.slice(1), goal: "x".repeat(AppData.BotTaskPlanTextMaxChars + 1) }),
}),
).toBeNull();
});
});
+28
View File
@@ -0,0 +1,28 @@
import { BotTaskPlanSchema, type BotTaskPlan } from "./bot-task-plan-schema";
/**
* Reads the plan a planning turn answered with. Models wrap JSON in a code
* fence or a sentence whatever the prompt says, so the object is cut out
* of the answer first. Null when it isn't a plan: the run then starts the
* way it always did, since a plan is an economy and never a gate.
*/
export default function parseBotTaskPlan({ text }: { text?: string | null }): BotTaskPlan | null {
if (!text) return null;
const start = text.indexOf("{");
const end = text.lastIndexOf("}");
if (start < 0 || end <= start) return null;
let value: unknown;
try {
value = JSON.parse(text.slice(start, end + 1));
} catch {
return null;
}
const parsed = BotTaskPlanSchema.safeParse(value);
return parsed.success ? parsed.data : null;
}
+79
View File
@@ -0,0 +1,79 @@
import { describe, expect, test } from "bun:test";
import { TaskPlanPrompt } from "@/src/data/harness-prompts";
import type { HarnessCandidate, HarnessMessage } from "@/src/harness/types";
import type { GenerateTextParams } from "@/src/harness/text/generate-text";
import planBotTask from "./plan-bot-task";
const candidate = {
key: "1:m",
provider: { id: 1, kind: "openrouter", base_url: "https://x.test" },
model: { slug: "m", input_modalities: ["text"], output_modalities: ["text"], supports_tools: true },
source: "auto",
} as HarnessCandidate;
const plan = {
goal: "Ship the release notes",
gather: ["docs/changelog.md"],
steps: ["Read the changelog", "Write the notes"],
done: "The notes are on the site",
};
function fakeGenerate({ text }: { text: string }) {
const seen: GenerateTextParams[] = [];
const generate = (async (params: GenerateTextParams) => {
seen.push(structuredClone({ ...params, signal: undefined }));
return { text, tool_calls: [], candidate };
}) as unknown as typeof import("@/src/harness/text/generate-text").default;
return { generate, seen };
}
const messages: HarnessMessage[] = [{ role: "user", content: "Write the release notes." }];
describe("planBotTask", () => {
test("asks for the plan in one turn on the prompt the run sends anyway", async () => {
const { generate, seen } = fakeGenerate({ text: JSON.stringify(plan) });
const planned = await planBotTask({
system: "You are a bot.",
messages,
signal: new AbortController().signal,
bot_id: 3,
workspace_id: 7,
generate,
});
expect(planned).toEqual({ plan, candidate });
expect(seen.length).toBe(1);
expect(seen[0]!.messages[0]).toEqual({ role: "system", content: "You are a bot." });
expect(String(seen[0]!.messages[1]!.role)).toBe("user");
expect(String(seen[0]!.messages[1]!.content)).toContain("Write the release notes.");
expect(String(seen[0]!.messages[1]!.content)).toContain(TaskPlanPrompt);
expect(seen[0]!.bot_id).toBe(3);
expect(seen[0]!.workspace_id).toBe(7);
expect(seen[0]!.tools).toBeUndefined();
});
test("leaves the run's own opening as it was", async () => {
const { generate } = fakeGenerate({ text: JSON.stringify(plan) });
await planBotTask({ system: "You are a bot.", messages, signal: new AbortController().signal, generate });
expect(messages).toEqual([{ role: "user", content: "Write the release notes." }]);
});
test("is null when the answer isn't a plan, so the run starts unplanned", async () => {
const { generate } = fakeGenerate({ text: "I'll figure it out as I go." });
const planned = await planBotTask({
system: "You are a bot.",
messages,
signal: new AbortController().signal,
generate,
});
expect(planned).toBeNull();
});
});
+56
View File
@@ -0,0 +1,56 @@
import { TaskPlanPrompt } from "@/src/data/harness-prompts";
import generateText from "@/src/harness/text/generate-text";
import pushUserTurn from "@/src/harness/text/push-user-turn";
import type { HarnessCandidate, HarnessMessage } from "@/src/harness/types";
import type { BotTaskPlan } from "./bot-task-plan-schema";
import parseBotTaskPlan from "./parse-bot-task-plan";
type Params = {
/**
* The system prompt the run's own turns send, unchanged: this turn
* shares its cached prefix, so the plan costs little more than the
* plan itself.
*/
system: string;
/**
* What the run opens with (its brief, and what the user wrote since).
* Planned from a copy: the run's own opening is left as it is.
*/
messages: HarnessMessage[];
signal: AbortSignal;
bot_id?: number | string;
workspace_id?: number | string | null;
generate?: typeof generateText;
};
/**
* Asks the run's model for the plan before the run takes a step
* (`TaskPlanPrompt`). One turn, no tools: a plan that takes steps to write
* is the wandering it exists to avoid.
*
* Null when the answer isn't a plan, so the run starts unplanned rather
* than steered by one it can't read.
*/
export default async function planBotTask({
system,
messages,
signal,
bot_id,
workspace_id,
generate = generateText,
}: Params): Promise<{ plan: BotTaskPlan; candidate: HarnessCandidate } | null> {
const planning = structuredClone(messages);
pushUserTurn({ transcript: planning, content: TaskPlanPrompt });
const answer = await generate({
messages: [{ role: "system", content: system }, ...planning],
signal,
bot_id,
workspace_id,
});
const plan = parseBotTaskPlan({ text: answer.text });
return plan ? { plan, candidate: answer.candidate } : null;
}
+1
View File
@@ -238,6 +238,7 @@ export default async function processBotJob({
attachments: outcome.attachments,
tool_log: outcome.tool_log,
task_ids: outcome.task_ids,
exhausted: outcome.exhausted,
});
await pushBotNotice({ bot_id, ...completion });
+2
View File
@@ -3,6 +3,7 @@ import { grabSkillBodyShownChars } from "@/src/functions/backend/db/app-settings
import { AppData } from "@/src/data/app-data";
import {
ActionCheckNote,
RequestScopeNote,
QuestionsNote,
AskCrewNote,
SecretsNote,
@@ -354,6 +355,7 @@ export default async function runBotReply({
TasksNote,
TaskReminderNote,
ActionCheckNote,
RequestScopeNote({ can_ask: true }),
QuestionsNote,
SecretsNote,
composeEnvsNote({ ...envs, has_computer: computers.length > 0 }),
+93 -54
View File
@@ -6,6 +6,7 @@ import workspaceAdminsNote from "./workspace-admins-note";
import type { BUN_SQLITE_COBBLE_BOTS } from "@/db/types/db";
import {
ActionCheckNote,
RequestScopeNote,
QuestionsNote,
SecretsNote,
GraphicsNote,
@@ -22,6 +23,7 @@ import {
TaskIncomingNote,
TaskRedraftNote,
TaskWrapUpIncomingNote,
taskPlanNote,
} from "@/src/data/harness-prompts";
import {
grabContextBudgetTokens,
@@ -65,6 +67,8 @@ import ScheduledRunFailedError from "./scheduled-run-failed-error";
import type { BotJobContext, BotJobOutcome } from "./types";
import computerRunDirs from "@/src/utils/computer-work-dirs";
import taskIncoming from "./task-incoming";
import planBotTask from "./plan-bot-task";
import shouldPlanBotTask from "./should-plan-bot-task";
import pushUserTurn from "@/src/harness/text/push-user-turn";
import type { HarnessMessage } from "@/src/harness/types";
@@ -400,61 +404,91 @@ export default async function runBotTask({
}
}
const system = [
prompt,
carry_over,
TaskRunNote,
`This run has at most ${max_steps} steps (model turns)${budget > 0 ? ", set when it was queued" : ""}. Plan for that: pace yourself, save what you find as you go, and if you're no closer after a few tries, stop and report what you tried and what you need from the user rather than spending the rest.`,
scheduled ? ScheduledRunNote : "",
hooked ? HookRunNote : "",
install_request_id ? InstallRequestNote : "",
botFilesNote({ bot_id: bot.id }),
ComputerFilesNote({ computer_id: job.computer_id || 0, dirs }),
TasksNote,
ActionCheckNote,
RequestScopeNote({ can_ask }),
can_ask ? QuestionsNote : "",
SecretsNote,
GraphicsNote,
workspace_id ? WorkspaceLearningNote : "",
powers.is_coordinator
? `If this brief asked you to record something in a workspace (its context, or a new one), do it yourself with update_workspace or create_workspace before you report: the report alone changes nothing.`
: admin_tools.some((tool) => tool.name == "update_workspace")
? `If this brief asked you to record something in this workspace's context, do it yourself with update_workspace before you report: the report alone changes nothing.`
: "",
powers.is_coordinator || powers.is_workspace_admin
? ""
: await workspaceAdminsNote({ bot_id: bot.id, workspace_id }),
powers.is_coordinator || hooked ? "" : AskCrewNote,
powers.is_coordinator || hooked || params.chatroom_id
? ""
: crewRequestsNote({ requests: await grabCrewRequests({ user_id, bot_id: bot.id, workspace_id }) }),
computer && computer_shared
? `You're working on the computer "${computer.name}" (a Linux sandbox with a shell, files and code runners) while another run uses it, so you have its shell and files but not its browser. If the answer needs the browser, say so in your report instead of waiting.`
: computer
? `You're working on the computer "${computer.name}" (a Linux sandbox with a shell, files, code runners and a browser). Use its tools; don't ask the user to run anything.${hooked ? "" : " When only the user can go on (a login, a captcha, a code sent to them), ask them to take over with ask_user_to_take_over."}`
: workspace_id
? `You have no computer for this task: this workspace has none. If the task needs one, stop and say so in the report; the user can add a computer to the workspace.`
: `You have no computer for this task.`,
computers.length > 1
? `search_computers runs a read-only command on every computer you have. When you name one in the report, write its ref, e.g. ${computerRef({ id: computers[0]!.id || 0 })}: the user can click it to switch you to that computer.`
: "",
computer?.envs.length
? `Environment variables set on this computer (use them by name, e.g. $KEY; never print their values):\n${computer.envs
.map((env) => `- ${env.key}${env.description ? `: ${env.description}` : ""}`)
.join("\n")}`
: "",
composeBrowsersNote({
browsers: browsers.browsers,
has_computer_browser: Boolean(computer),
run_kind: browser_run_kind,
}),
skills.note,
knowledge.note,
extensions.note,
]
.filter(Boolean)
.join("\n\n");
/*
* The plan this run works from, written in one turn before it takes
* a step (`planBotTask`). It shares this run's prompt, so it costs
* little more than the plan, and it saves the steps a long run
* spends finding out what it is doing. A run whose plan can't be
* written starts the way it always did.
*/
const planned = shouldPlanBotTask({ max_steps, in_chatroom: Boolean(params.chatroom_id) })
? await planBotTask({ system, messages: opening, signal, bot_id: bot.id, workspace_id }).catch(
(error) => {
if (signal.aborted) throw error;
return null;
},
)
: null;
if (planned) {
pushUserTurn({ transcript: opening, content: taskPlanNote({ plan: planned.plan }) });
await report({
index: -1,
text: `Plan: ${planned.plan.goal}`,
tool_calls: [],
candidate: planned.candidate,
});
}
const result = await runTextLoop({
system: [
prompt,
carry_over,
TaskRunNote,
`This run has at most ${max_steps} steps (model turns)${budget > 0 ? ", set when it was queued" : ""}. Plan for that: pace yourself, save what you find as you go, and if you're no closer after a few tries, stop and report what you tried and what you need from the user rather than spending the rest.`,
scheduled ? ScheduledRunNote : "",
hooked ? HookRunNote : "",
install_request_id ? InstallRequestNote : "",
botFilesNote({ bot_id: bot.id }),
ComputerFilesNote({ computer_id: job.computer_id || 0, dirs }),
TasksNote,
ActionCheckNote,
can_ask ? QuestionsNote : "",
SecretsNote,
GraphicsNote,
workspace_id ? WorkspaceLearningNote : "",
powers.is_coordinator
? `If this brief asked you to record something in a workspace (its context, or a new one), do it yourself with update_workspace or create_workspace before you report: the report alone changes nothing.`
: admin_tools.some((tool) => tool.name == "update_workspace")
? `If this brief asked you to record something in this workspace's context, do it yourself with update_workspace before you report: the report alone changes nothing.`
: "",
powers.is_coordinator || powers.is_workspace_admin
? ""
: await workspaceAdminsNote({ bot_id: bot.id, workspace_id }),
powers.is_coordinator || hooked ? "" : AskCrewNote,
powers.is_coordinator || hooked || params.chatroom_id
? ""
: crewRequestsNote({ requests: await grabCrewRequests({ user_id, bot_id: bot.id, workspace_id }) }),
computer && computer_shared
? `You're working on the computer "${computer.name}" (a Linux sandbox with a shell, files and code runners) while another run uses it, so you have its shell and files but not its browser. If the answer needs the browser, say so in your report instead of waiting.`
: computer
? `You're working on the computer "${computer.name}" (a Linux sandbox with a shell, files, code runners and a browser). Use its tools; don't ask the user to run anything.${hooked ? "" : " When only the user can go on (a login, a captcha, a code sent to them), ask them to take over with ask_user_to_take_over."}`
: workspace_id
? `You have no computer for this task: this workspace has none. If the task needs one, stop and say so in the report; the user can add a computer to the workspace.`
: `You have no computer for this task.`,
computers.length > 1
? `search_computers runs a read-only command on every computer you have. When you name one in the report, write its ref, e.g. ${computerRef({ id: computers[0]!.id || 0 })}: the user can click it to switch you to that computer.`
: "",
computer?.envs.length
? `Environment variables set on this computer (use them by name, e.g. $KEY; never print their values):\n${computer.envs
.map((env) => `- ${env.key}${env.description ? `: ${env.description}` : ""}`)
.join("\n")}`
: "",
composeBrowsersNote({
browsers: browsers.browsers,
has_computer_browser: Boolean(computer),
run_kind: browser_run_kind,
}),
skills.note,
knowledge.note,
extensions.note,
]
.filter(Boolean)
.join("\n\n"),
system,
messages: opening,
tools: [...tools, ...extensions.tools, ...browsers.tools, ...skills.tools, ...knowledge.tools],
max_steps,
@@ -492,6 +526,11 @@ export default async function runBotTask({
attachments: attachments.length ? attachments : undefined,
tool_log: result.tool_uses,
task_ids,
/**
* The wrap up was announced (`steps` counts its turns), so the
* run never got to the end of the work it was given.
*/
exhausted: result.steps > max_steps,
};
} finally {
await extensions?.close();
@@ -0,0 +1,19 @@
import { describe, expect, test } from "bun:test";
import { AppData } from "@/src/data/app-data";
import shouldPlanBotTask from "./should-plan-bot-task";
describe("shouldPlanBotTask", () => {
test("plans a run long enough to repay the plan", () => {
expect(shouldPlanBotTask({ max_steps: AppData.BotTaskPlanMinSteps })).toBe(true);
expect(shouldPlanBotTask({ max_steps: AppData.HarnessMaxToolSteps })).toBe(true);
});
test("leaves a short run alone: its first turn is its plan", () => {
expect(shouldPlanBotTask({ max_steps: AppData.BotTaskPlanMinSteps - 1 })).toBe(false);
expect(shouldPlanBotTask({ max_steps: 1 })).toBe(false);
});
test("never plans a chatroom turn", () => {
expect(shouldPlanBotTask({ max_steps: AppData.HarnessMaxToolSteps, in_chatroom: true })).toBe(false);
});
});
+24
View File
@@ -0,0 +1,24 @@
import { AppData } from "@/src/data/app-data";
/**
* Whether a task run plans before its first step (`planBotTask`).
*
* Planning is an economy, not a rule. It costs one turn, mostly served
* from the cache the run's own turns share, and it saves the steps a run
* spends working out what it is doing. A run too short to repay that gets
* nothing from it: its first turn is its plan.
*
* A chatroom turn is never planned: it is short, it has almost no tools,
* and nobody follows it.
*/
export default function shouldPlanBotTask({
max_steps,
in_chatroom,
}: {
max_steps: number;
in_chatroom?: boolean;
}) {
if (in_chatroom) return false;
return max_steps >= AppData.BotTaskPlanMinSteps;
}
+7
View File
@@ -62,6 +62,13 @@ export type BotJobOutcome = {
* kept on the result message as `task_ids`.
*/
task_ids?: number[];
/**
* The run used every step it was allowed and stopped before it finished
* (its wrap up was announced). A handed-over task stays open only when
* the run did no work, so the task is blocked rather than left `doing`
* (`noteTrackerTask`).
*/
exhausted?: boolean;
};
export type BotJobRunner = (context: BotJobContext) => Promise<BotJobOutcome>;
+8
View File
@@ -6,6 +6,7 @@ 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 cronWarnComputerWorkspaces from "./warn-computer-workspaces";
import cronPruneOrphanMedia from "./prune-orphan-media";
import pruneLogs from "./prune-logs";
import syncNotifyWatchers from "./sync-notify-watchers";
@@ -80,6 +81,13 @@ export default function cron() {
task: pruneLogs,
});
registerCronJob({
title: "warn-computer-workspaces",
schedule: "@daily",
task: cronWarnComputerWorkspaces,
quiet: true,
});
registerCronJob({
title: "sync-notify-watchers",
schedule: "*/5 * * * *",
@@ -0,0 +1,13 @@
import warnFullComputerWorkspaces from "@/src/functions/backend/db/computers/warn-full-computer-workspaces";
/**
* Reports every computer whose workspace is nearly full
* (`warnFullComputerWorkspaces`): it is the one folder on a computer
* mounted from the data volume, so it is what can fill the host, and a bot
* only ever finds out when a write is refused mid-run.
*/
export default async function cronWarnComputerWorkspaces() {
const full = await warnFullComputerWorkspaces();
return { nearly_full: full.map((entry) => entry.computer_id) };
}
+45 -1
View File
@@ -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.4.0",
ComputerImage: "ghcr.io/moduletrace/cobble-computer:1.4.1",
ComputerContainerPrefix: `${SiteData["SiteSlug"]}-computer`,
/**
* Only a computer's workspace (`ComputerWorkspaceDir` in its
@@ -167,6 +167,13 @@ export const AppData = {
* first (`computerWorkspaceRoomError`). 0 sets no limit.
*/
ComputerWorkspaceQuotaMb: 10240,
/**
* The share of the workspace quota past which `warn-computer-workspaces`
* reports a computer, so the install hears about it while writes still
* fit: a bot only ever learns of a full workspace when its own write is
* refused, mid-run.
*/
ComputerWorkspaceWarnShare: 0.8,
/**
* How long a media row nothing points at stays before
* `prune-orphan-media` deletes it. Long enough that an upload in flight,
@@ -700,6 +707,12 @@ export const AppData = {
* How many of a session's latest messages that check reads.
*/
BotReplyCatchUpMessages: 20,
/**
* A window regaining focus and its tab becoming visible are often one
* return, and each may fire more than once: a second signal this soon
* after the first (a refocus, a socket remount) is the same return.
*/
RefocusGapMs: 1000,
/**
* How much of the conversation a bot sees when it replies.
*/
@@ -713,6 +726,27 @@ export const AppData = {
* How many older messages each scroll to the top of the thread loads.
*/
ConversationOlderMessages: 30,
/**
* The phone's pull-to-reload gesture on the thread, in pixels: how far
* the finger travels before the gesture counts as a pull rather than a
* tap (`PullToRefreshMinPx`), how much of that travel shows
* (`PullToRefreshResistance`), and the room it opens under the newest
* message (`PullToRefreshRoomPx`), which no drag opens deeper.
*/
PullToRefreshMinPx: 8,
PullToRefreshResistance: 0.6,
PullToRefreshRoomPx: 64,
/**
* How long that room must stay full, in milliseconds, before letting go
* reloads: an exhausted thread reaches the limit by accident too easily,
* and keeping the finger there says the reload was meant.
*/
PullToRefreshHoldMs: 500,
/**
* The shortest the reloading icon stays up, in milliseconds: a reload
* the server answers at once still says it happened.
*/
PullToRefreshMinLoadingMs: 1000,
/**
* The most model calls a message's details modal lists one by one. A
* long task can take hundreds; the totals still count every one.
@@ -843,6 +877,16 @@ export const AppData = {
* hour of tool calls, and a huge limit still ends with a report.
*/
BotStepLimitMax: 1000,
/**
* The least steps a task run needs before it plans first (`planBotTask`):
* a shorter run's own first turn already is its plan. How long a plan
* may be is capped here too, since a model writes it. A plan is an
* economy, never a gate: a run whose plan can't be written just starts.
*/
BotTaskPlanMinSteps: 10,
BotTaskPlanMaxSteps: 12,
BotTaskPlanMaxGather: 8,
BotTaskPlanTextMaxChars: 400,
/**
* Chat attachments: per file, per message, and how much of a
* document's text a reply reads.
+1
View File
@@ -44,6 +44,7 @@ Permission to draft is not permission to send, permission to analyze is not perm
- If nothing in the crew fits and the need will recur, name the gap and propose a bot: short name, one-line role, what it handles. Create it with \`create_bot\` once the user agrees, and give it a workspace.
- A worker is on the crew only once \`create_bot\` confirmed it.
- A request to create a bot is a request for that bot alone. Placing it in a workspace, assigning it a computer and giving it work each need the user's own yes, asked for in one \`ask_user\` card, and that answer is the only thing that authorizes it.
- A workspace is where bots share one project's context. Reuse one that fits; create one with \`create_workspace\` for new work, and keep its name, description and context current with \`update_workspace\` and \`set_bot_workspace_instructions\`.
- Check membership with the tools. Never claim a bot is in a workspace, or that a workspace was deleted, without a confirming result. Explain what a deletion removes before asking for it.
- Workspace context is information, not authorization.
+24
View File
@@ -6,6 +6,7 @@ import {
coordinatorReplyNote,
crewRequestsNote,
openRunsNote,
RequestScopeNote,
TaskIncomingNote,
TaskRedraftNote,
TaskWrapUpIncomingNote,
@@ -104,6 +105,29 @@ describe("openRunsNote", () => {
});
});
describe("RequestScopeNote", () => {
test("sends crew changes and handed-out work through one ask_user card", () => {
const note = RequestScopeNote({ can_ask: true });
expect(note).toContain("not permission to put them in a workspace, assign them computers or give them work");
expect(note).toContain("a standing preference is not a standing instruction");
expect(note).toContain("the same ask_user card");
expect(note).toContain("delegating a task");
expect(note).toContain("don't offer it again in this conversation");
expect(note).not.toContain("the brief is what you may do");
expect(note).not.toContain("\u2014");
});
test("proposes instead of asking when nobody is watching", () => {
const note = RequestScopeNote({ can_ask: false });
expect(note).toContain("the brief is what you may do");
expect(note).toContain("Say in your report what you would propose");
expect(note).not.toContain("ask_user");
expect(note).not.toContain("\u2014");
});
});
describe("task incoming notes", () => {
test("leave separate requests to the chat and never offer send_message", () => {
for (const note of [TaskIncomingNote, TaskRedraftNote, TaskWrapUpIncomingNote]) {
+66
View File
@@ -195,6 +195,27 @@ Anything you read or write goes to your model provider, so secret values (passwo
- Never print, cat or echo a secret on a computer. To show one to the user, use show_secret for an env you have, or in a task on a computer capture it with capture_secret: either gives you a [secret:ID] ref to put in your message.
- Use secrets by key ($KEY in the shell, {{env.KEY}} in tools), never by value. A value you see as [KEY] in output was redacted: that's expected.`;
/**
* Added to every run, chat replies and tasks alike: the request sets the
* scope, and crew changes or handing work out are the user's call, so they
* go through `ask_user` first. `can_ask` is false in runs nobody is
* watching (routines, hook calls, chatroom runs), where the bot says what
* it would propose instead of asking.
*/
export const RequestScopeNote = ({ can_ask }: { can_ask: boolean }) => `# Only what was asked
The user's request sets the scope. Do what they asked, in the scope they gave, and nothing more.
- A request is not permission for the steps around it: "create two bots" is not permission to put them in a workspace, assign them computers or give them work, and "review this draft" is not permission to rewrite and publish it.
- Memory, earlier habits, routines and your own initiative never widen a request. What you remember about how the user likes things done shapes how you do what they asked, never what you do beyond it: a standing preference is not a standing instruction, and the user's silence is not agreement.
- Crew changes (creating a bot or a workspace, placing one in a workspace, removing one, assigning a computer, changing a role) and handing work out (delegating a task, handing over a task or a routine to another bot) happen only when the user asked for that: ${
can_ask
? `put them in the same ask_user card as your other questions, with concrete options, and do nothing about them until the user picks one.`
: `the brief is what you may do. Say in your report what you would propose, and why.`
}
- When you can't tell whether something was asked for, it wasn't: ask. Once the user has chosen, do exactly that, nothing bundled with it.
- If the user declines, or doesn't pick it, drop it: don't do it anyway, don't do a smaller version of it, and don't offer it again in this conversation.`;
/**
* Added to chat replies and to tasks the user started: before acting on
* something unclear, a bot asks (`ask_user`) rather than guesses.
@@ -287,6 +308,51 @@ export const TaskRedraftNote = `Your report above was not sent: the user wrote i
*/
export const TaskWrapUpIncomingNote = `The user wrote in this conversation before you finished (below), and this run has no steps left to act on it. If it changes, corrects or adds to this task, say in your report what it changes and what is still to redo because of it; never report a result it overruled as it stands.`;
/**
* The one turn a task run plans in before its first step (`planBotTask`).
* It is a user turn, not part of the system prompt, so the prompt the run's
* own turns send is the same one this call already cached.
*/
export const TaskPlanPrompt = `Before you start, plan this run in one turn, so you spend its steps doing the work instead of finding out what the work is.
Answer with a JSON object only, no markdown fence and no other text:
{"goal": "...", "gather": ["..."], "steps": ["..."], "done": "..."}
- goal: what finishing this run gives the user, in one sentence.
- gather: everything whose content you will need, each once, named as exactly as you can (a path, a URL, a command). A file you will edit is read first, a folder you will save into is listed first, and a fact you need twice is looked up once.
- steps: the work in order, the shortest way that finishes it. Fold each check into the step it belongs to: no step that only verifies a previous one, and nothing you would do the same way twice.
- done: how you will know it is finished, from what you can see for yourself.
The plan is for you, and it replaces finding out as you go: anything it says to gather is gathered once and reused, never re-read or re-run to see it again.`;
/**
* The plan a task run wrote before its first step, given back to it as the
* turn it works from. It stays advice, not an order: what a step turns up
* can change the rest, and the run says so in its report.
*/
export const taskPlanNote = ({
plan,
}: {
plan: { goal: string; gather: string[]; steps: string[]; done: string };
}) =>
`# Your plan
You wrote this before starting, and this run works from it now. Steps count, so follow it: gather once what it says to gather, and reuse what you already have instead of calling the same tool again for it. When a step turns up something that changes the rest, change the plan and carry on; don't repeat a step that is done.
Goal: ${plan.goal}
${plan.gather.length ? `Gather first, once each:\n${plan.gather.map((item) => `- ${item}`).join("\n")}\n\n` : ""}Steps:
${plan.steps.map((step, index) => `${index + 1}. ${step}`).join("\n")}${plan.done ? `\n\nDone when: ${plan.done}` : ""}`;
/**
* What a run gets back instead of a second identical read: the answer is
* already in its transcript, and paying for it again buys nothing. Only
* reads reach this (`RepeatableToolNames`), and any run write clears what
* was remembered, so "nothing has changed" holds.
*/
export const alreadyRanToolNote = ({ name, step }: { name: string; step: number }) =>
`You already called ${name} with these exact arguments on step ${step + 1} of this run, and nothing has changed since. Its output is above: use that instead of calling it again.`;
/**
* Added to a chat reply while the bot has runs open in this conversation
* that take in what the user writes here: a correction to one reaches it,
@@ -6,6 +6,15 @@ type Params = {
signal?: AbortSignal;
};
export type ComputerUsageFolder = {
/**
* Relative to the workspace root: `bots/9` is a bot's folder,
* `workspaces/3` a workspace's shared one.
*/
path: string;
bytes: number;
};
export type ComputerUsage = {
/**
* How much the whole workspace holds, every bot's and user's folder
@@ -16,6 +25,11 @@ export type ComputerUsage = {
* Where it is on the computer, for messages.
*/
workspace_dir: string;
/**
* The biggest folders in it, most first. A computer whose agent is
* older than this sends none.
*/
folders?: ComputerUsageFolder[];
};
/**
@@ -24,5 +38,5 @@ export type ComputerUsage = {
* 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 });
return computerJson<ComputerUsage>({ computer, path: "/api/usage", timeout_ms: 60_000, signal });
}
@@ -48,6 +48,12 @@ type Params = {
* The tracker tasks the run worked on, linked under the message.
*/
task_ids?: number[];
/**
* The run used every step it was allowed (`BotJobOutcome.exhausted`):
* a handed-over task it left open is blocked by `noteTrackerTask`, since
* a run that spent its whole budget and did no work says so itself.
*/
exhausted?: boolean;
};
/**
@@ -57,7 +63,8 @@ type Params = {
* after a task and idle after a reply; with others open, it shows the one
* still running (a reply in another session mustn't hide a task's row).
* Nobody else's face changes. A handed-over job's result also goes to the bot that handed
* it over (`relay`), and a handed-over task left open says so (`noteTrackerTask`). A hook
* it over (`relay`), and a handed-over task left open says so, or is blocked when the run used
* its whole step budget without finishing (`noteTrackerTask`). A hook
* run's result is kept on the calls it answered (`recordHookCallResponse`). A job in a chatroom
* moves the room on (`onChatroomJobEnded`) and leaves the bot's face alone. Throws if this handler no longer holds the job.
*/
@@ -70,6 +77,7 @@ export default async function completeBotJob({
attachments,
tool_log,
task_ids = [],
exhausted,
}: Params) {
const job = await grabLockedBotJob({ job_id, worker });
@@ -165,7 +173,7 @@ export default async function completeBotJob({
face: job.kind == "reply" ? "idle" : "done",
});
await noteTrackerTask({ job });
await noteTrackerTask({ job, exhausted });
await recordHookCallResponse({ job, status: "done", response: result, message_id: inserted?.id });
@@ -7,6 +7,7 @@ import grabTaskRow, { isOpenTask } from "../tasks/grab-task-scope";
import updateTask from "../tasks/update-task";
import grabJobUserId from "./grab-job-user-id";
import jobTrackerTaskId from "./job-tracker-task-id";
import trackerTaskEnding from "./tracker-task-ending";
type Params = {
job: BUN_SQLITE_COBBLE_BOTS_QUEUE;
@@ -14,17 +15,24 @@ type Params = {
* Why it failed; left out when it finished.
*/
failure?: string;
/**
* The run used every step it was allowed and stopped before finishing
* (`run-bot-task`'s `result.steps > max_steps`). A finished run that
* did no work blocks the task, rather than leaving it `doing`.
*/
exhausted?: boolean;
};
/**
* The end of a job worked on a handed-over task (`params.tracker_task_id`,
* set by `handOverTask`), written on that task while it's still open: a
* run that finished without closing it says so, a failed one blocks it
* with the reason. The bot moves the task along itself as it works; this
* only keeps the task honest when it didn't. Best effort: never fails
* the job's wrap-up.
* with the reason, and so does one that used up every step it had without
* doing the work (`trackerTaskEnding`). The bot moves the task along
* itself as it works; this only keeps the task honest when it didn't. Best
* effort: never fails the job's wrap-up.
*/
export default async function noteTrackerTask({ job, failure }: Params) {
export default async function noteTrackerTask({ job, failure, exhausted }: Params) {
const tracker_task_id = jobTrackerTaskId({ job });
if (!tracker_task_id || !job.bot_id) return;
@@ -35,17 +43,14 @@ export default async function noteTrackerTask({ job, failure }: Params) {
if (!isOpenTask({ status: task.status })) return;
const name = (await grabBotById({ bot_id: job.bot_id }))?.name || "The bot";
const ending = trackerTaskEnding({ name, status: task.status, failure, exhausted });
const text = ending.note.slice(0, AppData.TaskNoteMaxLength);
if (failure === undefined) {
await addTaskNote({
task_id: tracker_task_id,
text: `${name}'s run finished; the task is still ${task.status}.`,
bot_id: job.bot_id,
});
if (ending.blocked_reason === null) {
await addTaskNote({ task_id: tracker_task_id, text, bot_id: job.bot_id });
return;
}
const reason = `${name} couldn't finish it. ${failure}`.trim().slice(0, AppData.TaskNoteMaxLength);
const user_id = await grabJobUserId({ job });
if (user_id) {
@@ -53,12 +58,12 @@ export default async function noteTrackerTask({ job, failure }: Params) {
user_id,
task_id: tracker_task_id,
status: "blocked",
blocked_reason: reason,
blocked_reason: text,
updated_by_bot_id: job.bot_id,
});
}
await addTaskNote({ task_id: tracker_task_id, text: reason, bot_id: job.bot_id });
await addTaskNote({ task_id: tracker_task_id, text, bot_id: job.bot_id });
} catch (error) {
await logError({
title: `Couldn't note job #${job.id} on task #${tracker_task_id}`,
@@ -0,0 +1,32 @@
import { describe, expect, test } from "bun:test";
import trackerTaskEnding from "./tracker-task-ending";
describe("trackerTaskEnding", () => {
test("says a finished run left the task where it was", () => {
expect(trackerTaskEnding({ name: "Writer", status: "doing" })).toEqual({
blocked_reason: null,
note: "Writer's run finished; the task is still doing.",
});
});
test("blocks the task with why the run failed", () => {
expect(trackerTaskEnding({ name: "Writer", status: "doing", failure: "Model refused." })).toEqual({
blocked_reason: "Writer couldn't finish it. Model refused.",
note: "Writer couldn't finish it. Model refused.",
});
});
test("blocks the task when the run used every step it had", () => {
const ending = trackerTaskEnding({ name: "Writer", status: "doing", exhausted: true });
expect(ending.blocked_reason || "").toContain("used every step its run allowed and stopped before finishing it");
expect(ending.note).toBe(String(ending.blocked_reason));
});
test("a failure's reason wins over a spent budget", () => {
expect(
trackerTaskEnding({ name: "Writer", status: "doing", failure: "No room.", exhausted: true })
.blocked_reason,
).toBe("Writer couldn't finish it. No room.");
});
});
@@ -0,0 +1,57 @@
type Params = {
/**
* The bot's name, as the task's own readers see it.
*/
name: string;
/**
* The task's status now.
*/
status?: string | null;
/**
* Why the run failed, when it did.
*/
failure?: string | undefined;
/**
* The run used every step it was allowed. A handed-over task's run that
* spends its whole budget and still leaves the task open did not do the
* work: it ended `completed` with a report saying so, which the tracker
* never heard of, so the task read as under way forever (a retrofit run
* spent 242 steps re-reading the branch it had to change, converted
* nothing, and its task stayed `doing`).
*/
exhausted?: boolean;
};
export type TrackerTaskEnding = {
/**
* Why the task is blocked, or null to leave its status alone.
*/
blocked_reason: string | null;
/**
* The note left on the task, which says the same thing.
*/
note: string;
};
/**
* What finishing (or failing) a job says on the task it was handed over
* with, while that task is still open. The bot moves the task along itself
* as it works; this only keeps the task honest when it didn't, and a run
* that says it did nothing blocks the task rather than leaving it looking
* like work in hand.
*/
export default function trackerTaskEnding({ name, status, failure, exhausted }: Params): TrackerTaskEnding {
if (failure !== undefined) {
const note = `${name} couldn't finish it. ${failure}`.trim();
return { blocked_reason: note, note };
}
if (exhausted) {
const note = `${name} used every step its run allowed and stopped before finishing it. Its report says where it got to, so the rest needs a run of its own.`;
return { blocked_reason: note, note };
}
return { blocked_reason: null, note: `${name}'s run finished; the task is still ${status || "open"}.` };
}
@@ -0,0 +1,90 @@
import BunSQLite from "@moduletrace/bun-sqlite";
import { AppData } from "@/src/data/app-data";
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 logEvent from "@/src/functions/backend/logger";
import formatBytes from "@/src/utils/format-bytes";
import grabComputerMcpUrl from "./grab-computer-mcp-url";
export type FullComputerWorkspace = {
computer_id: number;
name: string;
used_bytes: number;
quota_bytes: number;
/**
* The biggest folder in it, from the agent's own listing.
*/
folder: string | null;
};
type Params = {
/**
* The share of the quota past which a computer is reported, so the
* install hears about it while writes still fit. `AppData.ComputerWorkspaceWarnShare`
* when left out.
*/
share?: number;
};
/**
* Logs every computer whose workspace is nearly full, with what holds most
* of it, and returns them. The workspace is the one folder on a computer
* mounted from the data volume, so it is what can fill the host; nothing
* prunes a bot's own files there (only caches, `prune-computer-caches`), so
* without this the first sign is a bot refused its write (`21.3 GB of
* 10.0 GB` on a real computer, nobody told until a run failed).
*
* Reported, never deleted: whose files to remove is the user's call.
*/
export default async function warnFullComputerWorkspaces({ share }: Params = {}): Promise<
FullComputerWorkspace[]
> {
const quota_bytes = await grabComputerWorkspaceQuotaBytes();
if (quota_bytes <= 0) return [];
const threshold = quota_bytes * (share ?? AppData.ComputerWorkspaceWarnShare);
const rows =
(
await BunSQLite.sql<{ id: number; name: string | null }>({
sql: `SELECT id, name FROM computers`,
})
).payload || [];
const full: FullComputerWorkspace[] = [];
for (const row of rows) {
const address = await grabComputerMcpUrl({ computer_id: row.id }).catch(() => null);
if (!address?.ready) continue;
const usage = await grabComputerUsage({
computer: { base_url: address.base_url, token: address.token },
}).catch(() => null);
if (!usage || usage.used_bytes < threshold) continue;
const entry: FullComputerWorkspace = {
computer_id: Number(row.id),
name: row.name || `#${row.id}`,
used_bytes: usage.used_bytes,
quota_bytes,
folder: usage.folders?.[0]?.path || null,
};
full.push(entry);
await logEvent({
title: `Computer ${entry.name} is nearly full`,
category: "system",
plain_text: `Computer ${entry.name} (#${entry.computer_id}) holds ${formatBytes({ bytes: entry.used_bytes })} of its ${formatBytes({ bytes: quota_bytes })} workspace limit${entry.folder ? `, most of it in ${entry.folder}` : ""}. Writes are refused once it passes the limit; clear the folder in Files, or raise the limit in Settings > General.`,
metadata: {
computer_id: entry.computer_id,
used_bytes: entry.used_bytes,
quota_bytes,
folder: entry.folder,
},
}).catch(() => {});
}
return full;
}
@@ -0,0 +1,11 @@
import type { LiveCrewRefreshedDetail } from "@/src/types";
export const LiveCrewRefreshedEvent = "cobble:live-crew-refreshed";
/**
* Tells the page's lists (the rail's bots and workspaces) the crew as it
* stands now, once it has been read again.
*/
export default function announceLiveCrew(detail: LiveCrewRefreshedDetail) {
window.dispatchEvent(new CustomEvent(LiveCrewRefreshedEvent, { detail }));
}
@@ -0,0 +1,10 @@
export const LiveCrewRefreshRequestedEvent = "cobble:refresh-live-crew";
/**
* Asks the layout to read the crew again, for an action that wants the
* whole page current (the thread's pull-to-reload) rather than each list
* fetching its own copy.
*/
export default function requestLiveCrewRefresh() {
window.dispatchEvent(new Event(LiveCrewRefreshRequestedEvent));
}
+219 -1
View File
@@ -1,7 +1,7 @@
import { describe, expect, test } from "bun:test";
import { z } from "zod";
import { AppData } from "@/src/data/app-data";
import { DroppedToolImageNote, SupersededSnapshotNote, ToolImagesNote } from "@/src/data/harness-prompts";
import { alreadyRanToolNote, DroppedToolImageNote, SupersededSnapshotNote, ToolImagesNote } from "@/src/data/harness-prompts";
import HarnessError from "../harness-error";
import type { HarnessCandidate, HarnessTool } from "../types";
import type { GenerateTextParams, GenerateTextResult } from "./generate-text";
@@ -286,6 +286,83 @@ describe("runTextLoop", () => {
expect(result.text).toBe("Report saved.");
});
test("hands the work it can't finish to start_task at the wrap up", async () => {
const hand_off: HarnessTool<{ brief: string }> = {
name: "start_task",
description: "Queues a run.",
schema: z.object({ brief: z.string() }),
run: async ({ args }) => `Run #7 queued: ${args.brief}`,
};
const loop_call = {
tool_calls: [{ id: "c", name: "remember", arguments: `{"note":"x"}` }],
};
const { generate, seen } = scripted([
loop_call,
{
tool_calls: [{ id: "t", name: "start_task", arguments: `{"brief":"write the piece"}` }],
},
{ text: "Research done; the writing is queued as a run." },
]);
const result = await runTextLoop({
system: "s",
messages: [{ role: "user", content: "write the guide" }],
tools: [remember, hand_off],
max_steps: 1,
generate,
resolveCandidates,
});
expect(seen).toHaveLength(3);
expect(seen[1]!.tools!.map((tool) => tool.name)).toEqual(["start_task"]);
expect(seen[1]!.messages.at(-1)!.content).toContain(
"one turn to hand the work on: start_task is still yours",
);
expect(seen[2]!.tools).toBe(undefined);
expect(result.tool_uses).toEqual([
{ name: "remember", ok: true },
{ name: "start_task", ok: true },
]);
expect(result.text).toBe("Research done; the writing is queued as a run.");
});
test("offers the saving tools and the hand off together", 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 hand_off: HarnessTool<{ brief: string }> = {
name: "start_task",
description: "Queues a run.",
schema: z.object({ brief: z.string() }),
run: async ({ args }) => `Run #7 queued: ${args.brief}`,
};
const loop_call = {
tool_calls: [{ id: "c", name: "remember", arguments: `{"note":"x"}` }],
};
const { generate, seen } = scripted([
loop_call,
{ text: "Saved what I have." },
]);
await runTextLoop({
system: "s",
messages: [{ role: "user", content: "audit the disk" }],
tools: [remember, save, hand_off],
max_steps: 1,
generate,
resolveCandidates,
});
expect(seen[1]!.tools!.map((tool) => tool.name)).toEqual(["write_file", "start_task"]);
const prompt = String(seen[1]!.messages.at(-1)!.content);
expect(prompt).toContain("one turn to save what the user needs: write_file");
expect(prompt).toContain("call start_task with a complete brief of what's left");
});
test("warns once, a few steps before the wrap up, in a long enough run", async () => {
const max_steps = AppData.HarnessStepsLowMinSteps;
const loop_call = {
@@ -739,3 +816,144 @@ describe("runTextLoop", () => {
expect(String(seen[0]!.messages[0]!.content)).not.toContain("Tools you can load");
});
});
describe("runTextLoop repeated reads", () => {
const readCall = ({ id, path }: { id: string; path: string }) => ({
id,
name: "read_file",
arguments: JSON.stringify({ path }),
});
/**
* A read that counts how often it actually ran, and a write that only
* exists to change what a read would say.
*/
const makeTools = () => {
const counts = { reads: 0, writes: 0 };
const read: HarnessTool<{ path: string }> = {
name: "read_file",
description: "Reads a file.",
schema: z.object({ path: z.string() }),
run: async ({ args }) => {
counts.reads++;
return `contents of ${args.path} (read ${counts.reads})`;
},
};
const write: HarnessTool<{ path: string }> = {
name: "write_file",
description: "Writes a file.",
schema: z.object({ path: z.string() }),
run: async () => {
counts.writes++;
return "Saved.";
},
};
return { tools: [read, write], counts };
};
test("answers a read repeated word for word from the first", async () => {
const { tools, counts } = makeTools();
const { generate, seen } = scripted([
{ text: null, tool_calls: [readCall({ id: "c1", path: "a.md" })] },
{ text: null, tool_calls: [readCall({ id: "c2", path: "a.md" })] },
{ text: "Done.", tool_calls: [] },
]);
const result = await runTextLoop({
system: "You are a bot.",
messages: [{ role: "user", content: "Read a.md twice." }],
tools,
generate,
resolveCandidates,
});
expect(counts.reads).toBe(1);
expect(result.tool_uses.map((use) => use.ok)).toEqual([true, true]);
const results = seen[2]!.messages.filter((message) => message.role == "tool");
expect(results.map((message) => message.role == "tool" && message.content)).toEqual([
"contents of a.md (read 1)",
alreadyRanToolNote({ name: "read_file", step: 0 }),
]);
});
test("reads again after something may have written", async () => {
const { tools, counts } = makeTools();
const { generate, seen } = scripted([
{ text: null, tool_calls: [readCall({ id: "c1", path: "a.md" })] },
{ text: null, tool_calls: [{ id: "c2", name: "write_file", arguments: `{"path":"a.md"}` }] },
{ text: null, tool_calls: [readCall({ id: "c3", path: "a.md" })] },
{ text: "Done.", tool_calls: [] },
]);
await runTextLoop({
system: "You are a bot.",
messages: [{ role: "user", content: "Update a.md." }],
tools,
generate,
resolveCandidates,
});
expect(counts.reads).toBe(2);
expect(counts.writes).toBe(1);
const results = seen[3]!.messages.filter((message) => message.role == "tool");
expect(results.map((message) => message.role == "tool" && message.content)).toEqual([
"contents of a.md (read 1)",
"Saved.",
"contents of a.md (read 2)",
]);
});
test("reads a different file on its own", async () => {
const { tools, counts } = makeTools();
const { generate } = scripted([
{ text: null, tool_calls: [readCall({ id: "c1", path: "a.md" }), readCall({ id: "c2", path: "b.md" })] },
{ text: "Done.", tool_calls: [] },
]);
await runTextLoop({
system: "You are a bot.",
messages: [{ role: "user", content: "Read both." }],
tools,
generate,
resolveCandidates,
});
expect(counts.reads).toBe(2);
});
test("keeps its own answers apart from other runs", async () => {
const { tools, counts } = makeTools();
const turns = [
{ text: null, tool_calls: [readCall({ id: "c1", path: "a.md" })] },
{ text: "Done.", tool_calls: [] },
];
const first = scripted(turns);
await runTextLoop({
system: "You are a bot.",
messages: [{ role: "user", content: "Read a.md." }],
tools,
generate: first.generate,
resolveCandidates,
});
const second = scripted(turns);
await runTextLoop({
system: "You are a bot.",
messages: [{ role: "user", content: "Read a.md." }],
tools,
generate: second.generate,
resolveCandidates,
});
expect(counts.reads).toBe(2);
});
});
+105 -30
View File
@@ -1,7 +1,9 @@
import { AppData } from "@/src/data/app-data";
import { alreadyRanToolNote } from "@/src/data/harness-prompts";
import HarnessError from "../harness-error";
import resolveHarnessCandidates from "../resolve/resolve-harness-candidates";
import loadToolsTool from "../tools/load-tools-tool";
import repeatToolCallKey from "../tools/repeat-tool-call-key";
import runToolCall from "../tools/run-tool-call";
import toolDefinition from "../tools/tool-definition";
import type {
@@ -117,12 +119,28 @@ export type TextLoopResult = {
};
/**
* 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).
* The wrap-up tools that save 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"];
export const WrapUpSaveToolNames = ["write_file", "import_file"];
/**
* The wrap-up tool that hands the work on. A chat reply gets
* `AppData.BotReplyMaxToolSteps` steps, and a reply that used them all
* researching leaves the writing undone; the next reply starts from the
* same budget, so the run queues the rest as a task (`start_task`) while it
* can still call a tool, rather than saying it will do it later. The app
* runs it as soon as the reply is out.
*/
export const WrapUpHandOffToolNames = ["start_task"];
/**
* Every tool the wrap up may still call (`WrapUpSaveToolNames` and
* `WrapUpHandOffToolNames`): those the run has, in its own order.
*/
export const WrapUpToolNames = [...WrapUpSaveToolNames, ...WrapUpHandOffToolNames];
/**
* Saving turns a wrap up may take: the first, and one more when it reached
@@ -134,26 +152,50 @@ 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. `saving` names the tools it may still call, if
* any: its one saving round, after which it answers with none.
* rather than its steps. `saving` and `hand_off` name the tools it may
* still call, if any: its one last round, after which it answers with
* none.
*/
export const wrapUpPrompt = ({
uses,
reason = "steps",
saving = [],
hand_off = [],
}: {
uses: HarnessToolUse[];
reason?: "steps" | "tokens";
saving?: string[];
hand_off?: 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.
`${reason == "tokens" ? "This run has used all the tokens it may spend." : "You've used every step this run allows."} ${wrapUpToolsPrompt({
saving,
hand_off,
})} 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.`;
/**
* What the wrap up may still call, said in one line: save the work, hand
* on what it can't finish, or neither.
*/
const wrapUpToolsPrompt = ({ saving, hand_off }: { saving: string[]; hand_off: string[] }) => {
if (!saving.length && !hand_off.length) return `Don't call any more tools.`;
return [
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.`
: "",
saving.length
? `If real work is left that this run can't finish, call ${hand_off.join(" or ")} with a complete brief of what's left: it runs after this turn and posts its own result.`
: hand_off.length
? `You have one turn to hand the work on: ${hand_off.join(" or ")} is still yours. If real work is left, call it with a complete brief of what's left: it runs after this turn and posts its own result.`
: "",
`After this turn no tool is left, so anything unsaved is lost, and so is work you only say you'll do later.`,
]
.filter(Boolean)
.join(" ");
};
/**
* 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
@@ -195,8 +237,9 @@ 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: one turn with only the saving tools
* (`WrapUpToolNames`), then one with none. An answer `review` finds fault
* model is asked to wrap up: one turn with only the wrap-up tools
* (`WrapUpToolNames`: what saves the work, and `start_task` for the rest),
* 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
@@ -262,13 +305,25 @@ export default async function runTextLoop({
};
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).
* The reads this run already made, by the call they answer
* (`repeatToolCallKey`) and the step it was. A read repeated word for
* word gets this answer instead of being run again, and anything that
* may have written forgets them: a file read once, then edited, is
* read again.
*/
const save_tools = run_tools.filter((tool) => WrapUpToolNames.includes(tool.name));
const save_definitions = save_tools.map((tool) => all_definitions.get(tool.name)!);
const repeated_reads = new Map<string, number>();
/**
* The tools a wrap up may still call: what saves the work, and
* `start_task` for the work it can't finish. 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), and a reply out of
* steps hands the rest to a task instead of promising it.
*/
const wrap_tools = run_tools.filter((tool) => WrapUpToolNames.includes(tool.name));
const save_tools = wrap_tools.filter((tool) => WrapUpSaveToolNames.includes(tool.name));
const hand_off_tools = wrap_tools.filter((tool) => WrapUpHandOffToolNames.includes(tool.name));
const wrap_definitions = wrap_tools.map((tool) => all_definitions.get(tool.name)!);
const warn_at = stepsLowWarningLeft({ max_steps });
let prefer_key: string | undefined;
let reviewed = false;
@@ -280,7 +335,11 @@ export default async function runTextLoop({
*/
let wrap_up_announced = false;
let saving_turns = 0;
let saved = false;
/**
* The wrap up had its one round of tools (saving, or handing the work
* on): the next turn offers none, so the run always ends.
*/
let used_wrap_turn = false;
for (let index = 0; index <= max_steps + 1 + WrapUpSavingTurns; index++) {
if (signal.aborted) {
@@ -291,11 +350,12 @@ export default async function runTextLoop({
const out_of_tokens = Boolean(max_prompt_tokens && max_prompt_tokens > 0 && usage.prompt_tokens >= max_prompt_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.
* The saving turn: only the tools a wrap up has left. Without one
* of them, or once it had its round, 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;
const wrap_up_saving =
wrap_up && !used_wrap_turn && saving_turns < WrapUpSavingTurns && wrap_tools.length > 0;
if (wrap_up && !wrap_up_announced) {
wrap_up_announced = true;
@@ -308,13 +368,14 @@ export default async function runTextLoop({
uses: tool_uses,
reason: out_of_steps ? "steps" : "tokens",
saving: wrap_up_saving ? save_tools.map((tool) => tool.name) : [],
hand_off: wrap_up_saving ? hand_off_tools.map((tool) => tool.name) : [],
}),
});
}
if (wrap_up_saving) saving_turns++;
const definitions = wrap_up_saving ? save_definitions : wrap_up ? [] : definitionsNow();
const definitions = wrap_up_saving ? wrap_definitions : wrap_up ? [] : definitionsNow();
/**
* Sized for the model the run is on (or will start on). A fallback
@@ -351,7 +412,7 @@ export default async function runTextLoop({
* 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),
(call) => !wrap_up || wrap_tools.some((tool) => tool.name == call.name),
);
/**
@@ -362,7 +423,7 @@ export default async function runTextLoop({
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.`,
content: `Only ${wrap_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;
}
@@ -412,12 +473,18 @@ export default async function runTextLoop({
};
}
if (wrap_up_saving) saved = true;
if (wrap_up_saving) used_wrap_turn = true;
const shown: { tool_name: string; images: HarnessToolImage[] }[] = [];
for (const call of tool_calls) {
const { text: content, images } = await runToolCall({ call, tools: run_tools, signal });
const repeat_key = repeatToolCallKey({ call });
const already_read = repeat_key ? repeated_reads.get(repeat_key) : undefined;
const { text: content, images } =
already_read !== undefined
? { text: alreadyRanToolNote({ name: call.name, step: already_read }), images: [] }
: await runToolCall({ call, tools: run_tools, signal });
/**
* A deferred tool called without loading it ran all the same;
@@ -428,6 +495,14 @@ export default async function runTextLoop({
}
tool_uses.push({ name: call.name, ok: !content.startsWith("Error:") });
if (!repeat_key) {
repeated_reads.clear();
} else if (already_read === undefined) {
if (content.startsWith("Error:")) repeated_reads.delete(repeat_key);
else repeated_reads.set(repeat_key, index);
}
transcript.push({ role: "tool", tool_call_id: call.id, content });
if (images.length) shown.push({ tool_name: call.name, images });
@@ -1,8 +1,9 @@
import type { ComputerApi } from "@/src/functions/backend/computers/computer-fetch";
import grabComputerUsage from "@/src/functions/backend/computers/grab-computer-usage";
import grabComputerUsage, { type ComputerUsageFolder } 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";
import computerWorkspaceSpace from "./computer-workspace-space";
type Params = {
computer: ComputerApi;
@@ -56,27 +57,44 @@ export default async function computerWorkspaceRoomError({ computer, dirs, incom
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 });
return computerWorkspaceFullMessage({
used_bytes: usage.used_bytes,
quota_bytes,
dirs,
folders: usage.folders,
});
}
/**
* 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.
* limit is, where the space went (`computerWorkspaceSpace`), and what to do
* instead. `dirs` is where its own work is, the one folder it may safely
* clear.
*/
export function computerWorkspaceFullMessage({
used_bytes,
quota_bytes,
dirs,
folders,
}: {
used_bytes: number;
quota_bytes: number;
dirs: ComputerRunDirs;
folders?: ComputerUsageFolder[];
}) {
const space = computerWorkspaceSpace({ folders, dirs });
const advice = space && !space.clearable
? `Nothing was written. The room has to come back from that folder: name it in your report, with what you needed to write, so the user can clear it through Files or raise the limit. Anything you can delete in ${dirs.bot_dir ?? dirs.cwd} still helps, and importing what matters into your files and removing it here frees that much.`
: `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.`;
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(" ");
space?.description || "",
advice,
]
.filter(Boolean)
.join(" ");
}
/**
@@ -88,12 +106,16 @@ export function computerWorkspaceFullNote({
used_bytes,
quota_bytes,
dirs,
folders,
}: {
used_bytes: number;
quota_bytes: number;
dirs: ComputerRunDirs;
folders?: ComputerUsageFolder[];
}) {
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.]`;
const space = computerWorkspaceSpace({ folders, dirs });
return `[This computer's workspace now holds ${formatBytes({ bytes: used_bytes })} of ${formatBytes({ bytes: quota_bytes })}${space ? `: ${space.description}` : ""} 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.]`;
}
/**
@@ -110,5 +132,10 @@ export async function computerWorkspaceFullWarning({ computer, dirs, signal }: O
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 });
return computerWorkspaceFullNote({
used_bytes: usage.used_bytes,
quota_bytes,
dirs,
folders: usage.folders,
});
}
@@ -0,0 +1,66 @@
import { describe, expect, test } from "bun:test";
import type { ComputerRunDirs } from "@/src/utils/computer-work-dirs";
import computerWorkspaceSpace from "./computer-workspace-space";
const worker: ComputerRunDirs = {
workspace: "/home/gem/workspace",
cwd: "/home/cb-9/workspace/users/1",
bot_dir: "/home/cb-9/workspace",
shared_dir: null,
roots: ["/home/cb-9/workspace"],
user_id: 1,
run_as: { bot_id: 9, workspace_id: null },
};
const coordinator: ComputerRunDirs = {
...worker,
bot_dir: "/home/gem/workspace/bots/2",
run_as: null,
};
const folders = (path: string) => [{ path, bytes: 22_000_000_000 }];
describe("computerWorkspaceSpace", () => {
test("says nothing without a folder to name", () => {
expect(computerWorkspaceSpace({ dirs: worker })).toBe(null);
expect(computerWorkspaceSpace({ folders: [], dirs: worker })).toBe(null);
});
test("names the run's own folder as one it may clear", () => {
const space = computerWorkspaceSpace({ folders: folders("bots/9"), dirs: worker });
expect(space?.clearable).toBe(true);
expect(space?.description).toContain("your own folder (bots/9");
});
test("names the workspace's shared folder as one it may clear", () => {
const space = computerWorkspaceSpace({
folders: folders("workspaces/3"),
dirs: { ...worker, shared_dir: "/home/cb-9/workspace/workspaces/3", run_as: { bot_id: 9, workspace_id: 3 } },
});
expect(space?.clearable).toBe(true);
expect(space?.description).toContain("this workspace's shared folder (workspaces/3");
});
test("a worker is told when the space is another bot's folder", () => {
const space = computerWorkspaceSpace({ folders: folders("bots/3"), dirs: worker });
expect(space?.clearable).toBe(false);
expect(space?.description).toContain("another bot's folder");
});
test("a worker is told when the space is a workspace it isn't in", () => {
const space = computerWorkspaceSpace({ folders: folders("workspaces/4"), dirs: worker });
expect(space?.clearable).toBe(false);
expect(space?.description).toContain("another workspace's folder");
});
test("the coordinator may clear any folder it is shown", () => {
const space = computerWorkspaceSpace({ folders: folders("bots/3"), dirs: coordinator });
expect(space?.clearable).toBe(true);
expect(space?.description).toContain("which you can reach as the coordinator");
});
});
@@ -0,0 +1,71 @@
import type { ComputerUsageFolder } from "@/src/functions/backend/computers/grab-computer-usage";
import type { ComputerRunDirs } from "@/src/utils/computer-work-dirs";
import formatBytes from "@/src/utils/format-bytes";
type Params = {
/**
* The biggest folders in the workspace, most first (`grabComputerUsage`).
*/
folders?: ComputerUsageFolder[];
dirs: ComputerRunDirs;
};
export type WorkspaceSpace = {
/**
* What the run is told about the folder holding the space, one sentence.
*/
description: string;
/**
* Whether that folder is one the run may clear: its own, the shared one
* in a workspace, or anything at all for the coordinator. A worker
* can't touch another bot's folder, so clearing it itself is not an
* option it should be pointed at.
*/
clearable: boolean;
};
/**
* Where a computer's workspace went: its biggest folder, named with whose
* it is. The workspace is one folder for every bot and user on that
* computer, so a bot told only "it's full" reported a limit it could never
* reach from its own folder (a bot's `du` showed 25 MB while the volume
* held 21.3 GB, most of it another bot's screenshots), which is what this
* answers.
*/
export default function computerWorkspaceSpace({ folders, dirs }: Params): WorkspaceSpace | null {
const biggest = folders?.[0];
if (!biggest) return null;
const size = formatBytes({ bytes: biggest.bytes });
const shared = dirs.shared_dir ? dirs.shared_dir.replace(/\/+$/, "").split("/").slice(-2).join("/") : "";
if (biggest.path == `bots/${dirs.run_as?.bot_id}`) {
return {
description: `Most of it is in your own folder (${biggest.path}, ${size}), so clearing it is yours to do.`,
clearable: true,
};
}
if (shared && biggest.path == shared) {
return {
description: `Most of it is in this workspace's shared folder (${biggest.path}, ${size}).`,
clearable: true,
};
}
if (!dirs.run_as) {
return {
description: `Most of it is in ${biggest.path} (${size}), which you can reach as the coordinator, so clearing it is yours to do.`,
clearable: true,
};
}
const [group] = biggest.path.split("/");
const owner = group == "workspaces" ? "workspace" : "bot";
return {
description: `Most of it is in ${biggest.path} (${size}), another ${owner}'s folder (this computer has one workspace for every bot and user), which you can't clear.`,
clearable: false,
};
}
@@ -0,0 +1,44 @@
import { describe, expect, test } from "bun:test";
import repeatToolCallKey from "./repeat-tool-call-key";
const call = ({ name, arguments: args }: { name: string; arguments: string }) => ({ id: "1", name, arguments: args });
describe("repeatToolCallKey", () => {
test("matches the same read whatever order the arguments came in", () => {
const first = repeatToolCallKey({ call: call({ name: "read_file", arguments: `{"path":"a.md","offset":1}` }) });
const second = repeatToolCallKey({ call: call({ name: "read_file", arguments: `{"offset":1,"path":"a.md"}` }) });
expect(first).not.toBeNull();
expect(second).toBe(first);
});
test("tells different arguments and different tools apart", () => {
const first = repeatToolCallKey({ call: call({ name: "read_file", arguments: `{"path":"a.md"}` }) });
expect(repeatToolCallKey({ call: call({ name: "read_file", arguments: `{"path":"b.md"}` }) })).not.toBe(first);
expect(repeatToolCallKey({ call: call({ name: "list_files", arguments: `{"path":"a.md"}` }) })).not.toBe(first);
});
test("reads arguments left out as an empty object", () => {
expect(repeatToolCallKey({ call: call({ name: "list_tasks", arguments: "" }) })).toBe("list_tasks:{}");
expect(repeatToolCallKey({ call: call({ name: "list_tasks", arguments: " " }) })).toBe("list_tasks:{}");
});
test("never repeats a tool that may write", () => {
expect(repeatToolCallKey({ call: call({ name: "computer_bash", arguments: `{"command":"ls"}` }) })).toBeNull();
expect(repeatToolCallKey({ call: call({ name: "write_file", arguments: `{"path":"a.md"}` }) })).toBeNull();
expect(repeatToolCallKey({ call: call({ name: "computer_write_file", arguments: `{"path":"a.md"}` }) })).toBeNull();
});
test("leaves arguments it can't read alone", () => {
expect(repeatToolCallKey({ call: call({ name: "read_file", arguments: "{nope" }) })).toBeNull();
expect(repeatToolCallKey({ call: call({ name: "read_file", arguments: `["a.md"]` }) })).toBeNull();
});
test("sorts keys inside nested arguments too", () => {
const first = repeatToolCallKey({ call: call({ name: "list_files", arguments: `{"where":{"b":1,"a":2}}` }) });
const second = repeatToolCallKey({ call: call({ name: "list_files", arguments: `{"where":{"a":2,"b":1}}` }) });
expect(second).toBe(first);
});
});
+43
View File
@@ -0,0 +1,43 @@
import type { HarnessToolCall } from "../types";
import isRepeatableTool from "./repeatable-tool-names";
/**
* What makes two calls the same call: the tool and its arguments, whatever
* order the model wrote their keys in (a model re-reads a file it read
* before with the same fields in another order). Null for a tool whose
* answer may change, and for arguments that aren't a JSON object, which
* `runToolCall` turns down anyway.
*/
export default function repeatToolCallKey({ call }: { call: HarnessToolCall }): string | null {
if (!isRepeatableTool({ name: call.name })) return null;
let args: unknown;
try {
args = call.arguments.trim() ? JSON.parse(call.arguments) : {};
} catch {
return null;
}
if (!args || typeof args != "object" || Array.isArray(args)) return null;
return `${call.name}:${JSON.stringify(sortKeys({ value: args }))}`;
}
/**
* The value with every object's keys sorted, so two spellings of the same
* arguments compare equal.
*/
function sortKeys({ value }: { value: unknown }): unknown {
if (Array.isArray(value)) return value.map((item) => sortKeys({ value: item }));
if (value && typeof value == "object") {
return Object.fromEntries(
Object.entries(value as Record<string, unknown>)
.sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0))
.map(([key, inner]) => [key, sortKeys({ value: inner })]),
);
}
return value;
}
@@ -0,0 +1,42 @@
import { ReadKnowledgebaseDocumentToolName, SearchKnowledgebaseToolName } from "@/src/dict/knowledgebase-dict";
/**
* Tools that only read. Called twice with the same arguments in one run
* they answer the same thing, so `runTextLoop` answers the second call from
* the first instead of running it again (`repeatToolCallKey`): a run that
* re-reads the same file or re-lists the same folder stops paying for it
* twice, in the call and in the transcript it resends every turn.
*
* Only reads belong here. A write, a command, or anything else with a side
* effect clears everything remembered, so a read is reused only while
* nothing has run that could have changed its answer.
*/
export const RepeatableToolNames: readonly string[] = [
"read_file",
"list_files",
"computer_read_file",
SearchKnowledgebaseToolName,
ReadKnowledgebaseDocumentToolName,
"list_tasks",
"list_extensions",
"list_graphics",
"read_graphic",
"list_hooks",
"read_hook_call",
"search_hook_calls",
"list_schedules",
"list_workspace_bots",
"list_workspace_people",
"find_bot",
"find_workspace",
"search_past_sessions",
"read_past_session",
"search_computers",
];
/**
* Whether a tool call may be answered from an earlier identical one.
*/
export default function isRepeatableTool({ name }: { name: string }) {
return RepeatableToolNames.includes(name);
}
+17 -3
View File
@@ -1,18 +1,30 @@
"use client";
import { useEffect, useState } from "react";
import { AppData } from "@/src/data/app-data";
/**
* Changes after a reason the socket may have died: the browser went back
* online, the page was restored, or a hidden tab became visible again.
* online, the page was restored, a hidden tab became visible again, or
* another window was focused (a phone locked while the socket closed).
* twui's `useWebSocket` gives up after three attempts, so the socket is
* remounted instead of waiting for a reload.
* remounted instead of waiting for a reload. A second trigger within
* `AppData.RefocusGapMs` is the same return.
*/
export default function useConnectionEpoch() {
const [epoch, setEpoch] = useState(0);
useEffect(() => {
const bump = () => setEpoch((value) => value + 1);
let last = 0;
const bump = () => {
const now = Date.now();
if (now - last < AppData.RefocusGapMs) return;
last = now;
setEpoch((value) => value + 1);
};
const onVisible = () => {
if (document.visibilityState == "visible") bump();
@@ -20,11 +32,13 @@ export default function useConnectionEpoch() {
window.addEventListener("online", bump);
window.addEventListener("pageshow", bump);
window.addEventListener("focus", bump);
document.addEventListener("visibilitychange", onVisible);
return () => {
window.removeEventListener("online", bump);
window.removeEventListener("pageshow", bump);
window.removeEventListener("focus", bump);
document.removeEventListener("visibilitychange", onVisible);
};
}, []);
+33 -3
View File
@@ -1,10 +1,12 @@
import { useState } from "react";
import { useEffect, useState } from "react";
import type { BUN_SQLITE_COBBLE_BOT_MESSAGES, BUN_SQLITE_COBBLE_BOTS } from "@/db/types/db";
import { LiveCrewRefreshedEvent } from "@/src/functions/frontend/announce-live-crew";
import type {
BotCreatedData,
BotRemovedData,
BotUpdatedData,
BotWithLastMessage,
LiveCrewRefreshedDetail,
} from "@/src/types";
import useServerEvent from "./use-server-event";
@@ -23,7 +25,10 @@ type Params = {
/**
* The crew, kept current from server pushes: faces and status lines,
* latest messages, and unread for conversations that aren't open.
* latest messages, and unread for conversations that aren't open. A task
* step's push never reaches a page that was in the background, so the
* whole list is also read again when the user comes back
* (`cobble:live-crew-refreshed`).
*/
export default function useLiveBots({ bots, open_bot_id, workspace_id = null }: Params) {
const [live, setLive] = useState(bots);
@@ -132,5 +137,30 @@ export default function useLiveBots({ bots, open_bot_id, workspace_id = null }:
},
});
useEffect(() => {
const onRefresh = (event: Event) => {
const detail = (event as CustomEvent<LiveCrewRefreshedDetail>).detail;
if (!detail) return;
/**
* The list read for another place: this one keeps what it has.
*/
if ((detail.workspace_id || null) != (workspace_id ? Number(workspace_id) : null)) {
return;
}
setLive(
detail.bots.map((bot) =>
bot.id == open_bot_id ? { ...bot, unread: 0 } : bot,
),
);
};
window.addEventListener(LiveCrewRefreshedEvent, onRefresh);
return () => window.removeEventListener(LiveCrewRefreshedEvent, onRefresh);
}, [workspace_id, open_bot_id]);
return live;
}
}
+49
View File
@@ -0,0 +1,49 @@
"use client";
import { useEffect, useRef } from "react";
import { AppData } from "@/src/data/app-data";
type Params = {
onRefocus: () => void;
};
/**
* Calls `onRefocus` when the user comes back to the page: another window
* was focused, or a hidden tab (a phone, a notification tapped) became
* visible again. Pushes that arrived while the page was in the background
* never reach it, so what it shows may be stale until it reads it again.
* A window regaining focus and its tab becoming visible are often one
* return (a phone brings the page back and focuses it), and each may fire
* more than once, so a second call within `AppData.RefocusGapMs` is the
* same return.
*/
export default function useRefocus({ onRefocus }: Params) {
const handler = useRef(onRefocus);
handler.current = onRefocus;
useEffect(() => {
let last = 0;
const refresh = () => {
const now = Date.now();
if (now - last < AppData.RefocusGapMs) return;
last = now;
handler.current();
};
const onVisible = () => {
if (document.visibilityState == "visible") refresh();
};
window.addEventListener("focus", refresh);
document.addEventListener("visibilitychange", onVisible);
return () => {
window.removeEventListener("focus", refresh);
document.removeEventListener("visibilitychange", onVisible);
};
}, []);
}
@@ -0,0 +1,18 @@
import fetchApi from "@moduletrace/twui/utils/fetch/fetchApi";
import type { APIResponseObject } from "@moduletrace/bunext/types";
import type { LiveCrewRequest } from "@/src/schemas/bot-schema";
import type { LiveCrewPayload } from "@/src/types";
/**
* The rail's crew as it stands now: the bots in a workspace or the bots'
* own chats (`workspace_id`), and the user's workspaces.
*/
export default async function fetchLiveCrew({ workspace_id }: LiveCrewRequest) {
return await fetchApi<LiveCrewRequest, APIResponseObject<LiveCrewPayload>>(
`/api/admin/bots/live-crew`,
{
method: "POST",
body: { workspace_id },
},
);
}
@@ -0,0 +1,44 @@
import { useCallback, useEffect } from "react";
import announceLiveCrew from "@/src/functions/frontend/announce-live-crew";
import { LiveCrewRefreshRequestedEvent } from "@/src/functions/frontend/request-live-crew-refresh";
import useRefocus from "@/src/hooks/use-refocus";
import fetchLiveCrew from "../(functions)/fetch-live-crew";
type Params = {
/**
* The workspace the rail lists a crew for, or null for the bots' own
* chats (`railWorkspaceId`).
*/
workspace_id: number | null;
};
/**
* Reads the rail's crew again when the user comes back to the page
* (`useRefocus`), or when a page asks for it (`requestLiveCrewRefresh`,
* the thread's pull-to-reload): faces and status lines, latest messages,
* unread marks and the workspaces, all as they stand now. It lives in the
* layout, so every page under it keeps the rail current without each list
* holding its own copy. The lists take the result through
* `cobble:live-crew-refreshed`.
*/
export default function useLiveCrewRefresh({ workspace_id }: Params) {
const refresh = useCallback(async () => {
const res = await fetchLiveCrew({ workspace_id }).catch(() => null);
if (!res?.success || !res.singleRes) return;
announceLiveCrew({
workspace_id,
bots: res.singleRes.bots,
workspaces: res.singleRes.workspaces,
});
}, [workspace_id]);
useRefocus({ onRefocus: () => void refresh() });
useEffect(() => {
window.addEventListener(LiveCrewRefreshRequestedEvent, refresh);
return () => window.removeEventListener(LiveCrewRefreshRequestedEvent, refresh);
}, [refresh]);
}
@@ -1,7 +1,9 @@
import { useState } from "react";
import { useEffect, useState } from "react";
import type { BUN_SQLITE_COBBLE_BOT_MESSAGES } from "@/db/types/db";
import { LiveCrewRefreshedEvent } from "@/src/functions/frontend/announce-live-crew";
import useServerEvent from "@/src/hooks/use-server-event";
import type {
LiveCrewRefreshedDetail,
WorkspaceCreatedData,
WorkspaceRemovedData,
WorkspaceUpdatedData,
@@ -19,7 +21,8 @@ type Params = {
/**
* The user's workspaces, marked unread as bot messages arrive in them and
* kept current when one is created (a bot can create one, so it shows
* without a reload).
* without a reload). Read again as a whole when the user comes back
* (`cobble:live-crew-refreshed`), like the bots' list.
*/
export default function useLiveWorkspaces({ workspaces, open_workspace_id }: Params) {
const [live, setLive] = useState(workspaces);
@@ -72,5 +75,25 @@ export default function useLiveWorkspaces({ workspaces, open_workspace_id }: Par
},
});
useEffect(() => {
const onRefresh = (event: Event) => {
const detail = (event as CustomEvent<LiveCrewRefreshedDetail>).detail;
if (!detail?.workspaces) return;
setLive(
detail.workspaces.map((workspace) =>
Number(workspace.id) == open_workspace_id
? { ...workspace, unread: 0 }
: workspace,
),
);
};
window.addEventListener(LiveCrewRefreshedEvent, onRefresh);
return () => window.removeEventListener(LiveCrewRefreshedEvent, onRefresh);
}, [open_workspace_id]);
return live;
}
+5 -7
View File
@@ -5,6 +5,7 @@ import Stack from "@moduletrace/twui/layout/Stack";
import { AppContext } from "@/src/pages/__root";
import useLiveBots from "@/src/hooks/use-live-bots";
import useLiveWorkspaces from "../(hooks)/use-live-workspaces";
import railWorkspaceId from "../(utils)/rail-workspace-id";
import { RailPages } from "@/src/dict/rail-pages-dict";
import { RailDrawerContext } from "../(data)/rail-drawer-context";
import RailHeader from "../(partials)/rail-header";
@@ -38,20 +39,17 @@ export default function BotsRail() {
Boolean(pathname?.startsWith(`${page.url}/`)),
);
const workspace = pageProps?.workspace;
const in_workspace = Boolean(
workspace?.id && pathname?.startsWith("/admin/workspaces/"),
);
const workspace_id = railWorkspaceId({ workspace, pathname });
const in_workspace = Boolean(workspace_id);
const bots = useLiveBots({
bots: pageProps?.bots || [],
open_bot_id: pageProps?.bot?.id || undefined,
workspace_id: in_workspace ? workspace?.id || null : null,
workspace_id,
});
const workspaces = useLiveWorkspaces({
workspaces: pageProps?.workspaces || [],
open_workspace_id: in_workspace
? workspace?.id || undefined
: undefined,
open_workspace_id: workspace_id || undefined,
});
const live_workspace = workspaces.find((w) => w.id == workspace?.id);
@@ -0,0 +1,32 @@
import { describe, expect, test } from "bun:test";
import railWorkspaceId from "./rail-workspace-id";
describe("railWorkspaceId", () => {
test("lists a workspace's crew on its own pages", () => {
expect(
railWorkspaceId({
workspace: { id: 4 },
pathname: "/admin/workspaces/4/chatrooms",
}),
).toBe(4);
});
test("lists the bots' own chats elsewhere, even with a workspace at hand", () => {
expect(
railWorkspaceId({
workspace: { id: 4 },
pathname: "/admin/settings/general",
}),
).toBeNull();
expect(
railWorkspaceId({ workspace: { id: 4 }, pathname: "/admin/bots/2" }),
).toBeNull();
});
test("a workspace page with no workspace listed has no scope", () => {
expect(
railWorkspaceId({ workspace: null, pathname: "/admin/workspaces/4" }),
).toBeNull();
expect(railWorkspaceId({ workspace: { id: null }, pathname: null })).toBeNull();
});
});
@@ -0,0 +1,18 @@
type Params = {
workspace: { id?: number | string | null } | null | undefined;
pathname: string | null | undefined;
};
/**
* The workspace the rail lists a crew for, or null for the bots' own
* chats. `pageProps.workspace` alone can be set on a page outside
* `/admin/workspaces/` (Settings keeps the last conversation's), and only
* a workspace's own pages list its crew.
*/
export default function railWorkspaceId({ workspace, pathname }: Params) {
const id = Number(workspace?.id) || 0;
if (!id || !pathname?.startsWith("/admin/workspaces/")) return null;
return id;
}
+10
View File
@@ -11,7 +11,9 @@ import BotsRail from "./(sections)/bots-rail";
import LiveSocket from "./(sections)/live-socket";
import AddFlow from "./(partials)/add-flow";
import OfflineBanner from "./(partials)/offline-banner";
import useLiveCrewRefresh from "./(hooks)/use-live-crew-refresh";
import isRaillessPage from "./(utils)/is-railless-page";
import railWorkspaceId from "./(utils)/rail-workspace-id";
/**
* Full-bleed shell for every `/admin/*` page: the rail of bot conversations
@@ -54,6 +56,14 @@ export default function BotsLayout({
const has_rail = !isRaillessPage({ pathname });
/**
* The crew the rail lists, read again whenever the user comes back to
* the page: pushes that never arrived leave it stale until a reload.
*/
const workspace_id = railWorkspaceId({ workspace: pageProps?.workspace, pathname });
useLiveCrewRefresh({ workspace_id });
const drawer = useMemo(
() => ({ open: drawer_open, setOpen: setDrawerOpen, has_rail }),
[drawer_open, has_rail],
@@ -15,7 +15,9 @@ type Params = {
* Loads the open conversation's history once the page is on screen, and
* again whenever the browser restores the page from its back-forward
* cache (`pageshow` with `persisted`), so going back never shows an old
* thread. The page's `?session_id=` picks a session other than the
* thread. `reload` reads it again without the loading line, for the
* phone's pull-to-reload, which shows its own spinner. The page's
* `?session_id=` picks a session other than the
* active one, read on every load. Everything else on the page (the header, the composer) comes
* from the server and shows at once. `loaded` turns true with the first
* load; a conversation the user can no longer open sends them where the
@@ -30,13 +32,15 @@ export default function useConversationHistory({ bot_id, workspace_id, onLoaded
on_loaded.current = onLoaded;
const load = async () => {
const load = async ({ silent = false }: { silent?: boolean } = {}) => {
if (!bot_id) return;
const id = ++request.current;
setLoading(true);
setError(undefined);
if (!silent) {
setLoading(true);
setError(undefined);
}
const session_id =
Number(new URLSearchParams(window.location.search).get("session_id")) || null;
@@ -53,14 +57,19 @@ export default function useConversationHistory({ bot_id, workspace_id, onLoaded
const history = res?.success ? res.singleRes?.history : null;
setLoading(false);
if (!silent) setLoading(false);
if (!history?.session?.id) {
setError(res?.msg || "Couldn't load the conversation.");
/**
* A silent reload leaves the thread it couldn't read alone:
* the pull's own control says it failed, not the page.
*/
if (!silent) setError(res?.msg || "Couldn't load the conversation.");
return;
}
on_loaded.current({ history });
setError(undefined);
setLoaded(true);
};
@@ -75,5 +84,11 @@ export default function useConversationHistory({ bot_id, workspace_id, onLoaded
return () => window.removeEventListener("pageshow", onPageShow);
}, [bot_id, workspace_id]);
return { loading, loaded, error, retry: load };
return {
loading,
loaded,
error,
retry: () => load(),
reload: () => load({ silent: true }),
};
}
@@ -0,0 +1,254 @@
"use client";
import { useEffect, useRef, useState, type RefObject } from "react";
import { AppData } from "@/src/data/app-data";
import minimumWait from "../(utils)/minimum-wait";
import pullToRefreshState from "../(utils)/pull-to-refresh";
/**
* What the pull indicator shows: nothing yet, a pull that isn't far
* enough, one that will reload on release, or a reload in flight.
*/
export type PullToRefreshState = "idle" | "pulling" | "ready" | "refreshing";
type Params = {
/**
* The thread's scrolling column.
*/
column_ref: RefObject<HTMLDivElement | null>;
/**
* The thread's content, which the pull moves up to open its room.
*/
content_ref: RefObject<HTMLDivElement | null>;
/**
* Whether the thread's content ends at the column's bottom right now:
* only there does pulling up have nothing left of the conversation to
* scroll, so the pull belongs to the app.
*/
at_bottom: () => boolean;
/**
* Reads the conversation again; the pull indicator stays up until it
* finishes, and no less than a moment after.
*/
on_refresh: () => Promise<void> | void;
};
/**
* A phone gesture: touching the thread while it sits at its bottom and
* dragging up lifts the newest message off the edge, opening room for a
* refresh icon, since there is nothing newer to scroll to. Once the room is
* as deep as it opens, the finger has to stay there for a moment before
* letting go reloads: a thread whose scroll is already exhausted opens its
* limit easily by accident, and the hold is what says the reload was meant.
* The icon lights up when it is, and a release before that closes the room
* and reloads nothing.
*
* Touches are read rather than `scrollTop`, whose sign a reversed column
* reports differently across engines. Once the pull has started it owns the
* gesture until the finger lifts: it is not interrupted by a scroll, a
* resize or a text selection, so a press that is still down always shows
* its icon, and the reload happens on release, never before.
*
* The room is written straight onto the content as the finger moves, never
* through a render: a phone drags in steps of a couple of pixels, and
* re-rendering a long thread that often would cost more than the gesture is
* worth. Only the icon's few states go through state.
*/
export default function usePullToRefresh({
column_ref,
content_ref,
at_bottom,
on_refresh,
}: Params) {
const [state, setState] = useState<PullToRefreshState>("idle");
const refresh = useRef(on_refresh);
const bottom = useRef(at_bottom);
refresh.current = on_refresh;
bottom.current = at_bottom;
useEffect(() => {
const column = column_ref.current;
const content = content_ref.current;
if (!column) return;
let start_y: number | null = null;
/** The pull has begun: it runs to the release regardless. */
let engaged = false;
/** The room has stayed full long enough: letting go now reloads. */
let armed = false;
/** When the room last became full, while the finger holds it there. */
let held_since: number | null = null;
let held_timer: ReturnType<typeof setTimeout> | null = null;
let busy = false;
/**
* The content is moved up, never resized: the thread follows its
* content's size by jumping back to the bottom, and a padding that
* grew under the finger would send it there mid-pull.
*/
const setRoom = (distance: number) => {
if (!content) return;
content.style.transform = distance > 0 ? `translate3d(0, -${distance}px, 0)` : "";
};
/**
* A drag over a message selects its text, in the emulated and real
* touch alike, and the selection would grow while the thread is
* lifted away from the finger. It is taken out of the way once a
* pull has begun, since the pull is what this finger is doing.
*/
const holdSelection = (held: boolean) => {
if (!content) return;
content.style.userSelect = held ? "none" : "";
if (held) window.getSelection()?.removeAllRanges();
};
/**
* The room is full: the hold that makes it a reload starts, or is
* already running. A finger that rests on the limit fires no further
* touches, so the timer is what notices the hold, not the moves.
*/
const beginHold = () => {
if (held_since != null) return;
held_since = Date.now();
held_timer = setTimeout(() => {
held_timer = null;
if (held_since == null) return;
armed = true;
setState("ready");
}, AppData.PullToRefreshHoldMs);
};
/** Not full any more: the hold starts again from nothing. */
const dropHold = () => {
held_since = null;
armed = false;
if (held_timer == null) return;
clearTimeout(held_timer);
held_timer = null;
};
const reset = () => {
start_y = null;
engaged = false;
dropHold();
setRoom(0);
holdSelection(false);
setState("idle");
};
const onStart = (event: TouchEvent) => {
start_y = null;
engaged = false;
dropHold();
if (busy || event.touches.length != 1) return;
if (!bottom.current()) return;
start_y = event.touches[0]?.clientY ?? null;
};
const onMove = (event: TouchEvent) => {
if (busy || start_y == null) return;
const current_y = event.touches[0]?.clientY;
if (current_y == undefined || event.touches.length != 1) {
/**
* A move that arrives without its touch holds no finger
* position; the release's own event is on its way, and it
* is that one that decides.
*/
if (!event.touches.length) return;
reset();
return;
}
if (!engaged) {
if (!bottom.current()) {
reset();
return;
}
if (pullToRefreshState({ start_y, current_y }).pulling) {
engaged = true;
holdSelection(true);
}
}
/**
* A finger dragged back down before it was let go takes the
* room back down with it and hides the icon at the very travel
* that showed it, so the pull reads the same in either
* direction. The gesture stays its own until the release, and
* a hold that has not finished yet starts over from nothing.
*/
const pulled = pullToRefreshState({ start_y, current_y });
if (pulled.ready) beginHold();
else dropHold();
setRoom(pulled.distance);
setState(armed ? "ready" : pulled.pulling ? "pulling" : "idle");
};
const onEnd = async () => {
if (busy) return;
const reload = engaged && armed;
start_y = null;
engaged = false;
dropHold();
if (!reload) {
reset();
return;
}
busy = true;
/**
* The room it was let go at stays open while it reloads, so
* nothing moves under the finger that just lifted.
*/
setState("refreshing");
try {
await minimumWait({
task: (async () => refresh.current())(),
minimum_ms: AppData.PullToRefreshMinLoadingMs,
});
} finally {
busy = false;
reset();
}
};
column.addEventListener("touchstart", onStart, { passive: true });
column.addEventListener("touchmove", onMove, { passive: true });
column.addEventListener("touchend", onEnd);
column.addEventListener("touchcancel", reset);
return () => {
column.removeEventListener("touchstart", onStart);
column.removeEventListener("touchmove", onMove);
column.removeEventListener("touchend", onEnd);
column.removeEventListener("touchcancel", reset);
dropHold();
setRoom(0);
holdSelection(false);
};
}, [column_ref, content_ref]);
return state;
}
@@ -1,4 +1,4 @@
import { useEffect, useRef } from "react";
import { useCallback, useEffect, useRef } from "react";
import { AppData } from "@/src/data/app-data";
import type {
BotMessageWithAttachments,
@@ -6,6 +6,7 @@ import type {
WebSocketDataType,
} from "@/src/types";
import postSessionApi from "@/src/functions/frontend/post-session-api";
import useRefocus from "@/src/hooks/use-refocus";
type Params = {
session_id?: number | null;
@@ -20,73 +21,83 @@ type Params = {
};
/**
* While a reply is due, checks the session's latest messages every
* `AppData.BotReplyCatchUpMs`. Replies arrive live; this only catches one
* whose push was missed (the socket was down at the time), so the
* thinking row can't stay up until a reload. It also checks at once when
* the page comes back into view or online. A missed message is replayed
* as the `server:bot-message` it would have been, so the thread, the rail
* and the unread flag all take it the usual way. The bot's face, status
* line and active task are replayed too, as `server:bot-updated`, so a
* Keeps the thread from waiting on a push that never came: every return to
* the page (`useRefocus`) reads the session's latest messages and the
* bot's face, status line and active task, and while a reply is due it
* does so every `AppData.BotReplyCatchUpMs` too. A missed message is
* replayed as the `server:bot-message` it would have been, so the thread,
* the rail and the unread flag all take it the usual way. The bot's face,
* status line and active task are replayed as `server:bot-updated`, so a
* reply that ended without a final message (its face push missed) can't
* leave the bot working on screen.
* leave the bot thinking or a finished task on screen. Reading it even
* when no reply is due is what lets a row stuck on a stale face or task
* clear itself without a reload.
*/
export default function useReplyCatchUp({ session_id, awaiting_reply, last_message_id }: Params) {
const last_message = useRef(Number(last_message_id) || 0);
/**
* The open session: a read that lands after the thread moved to
* another one is dropped instead of replaying into the wrong thread.
*/
const open_session = useRef(session_id);
last_message.current = Number(last_message_id) || 0;
open_session.current = session_id;
useEffect(() => {
if (!awaiting_reply || !session_id) return;
const check = useCallback(async () => {
if (!session_id) return;
let stale = false;
const res = (await postSessionApi<BotMessageWithAttachments>({
path: "session-messages",
body: { session_id },
}).catch(() => null)) as SessionMessagesResponse | null;
if (open_session.current != session_id) return;
if (!res?.success || !Array.isArray(res.payload)) return;
const replay = ({ data }: { data: WebSocketDataType }) =>
window.dispatchEvent(new CustomEvent("wsDataEvent", { detail: { data, message: data } }));
const check = async () => {
const res = (await postSessionApi<BotMessageWithAttachments>({
path: "session-messages",
body: { session_id },
}).catch(() => null)) as SessionMessagesResponse | null;
const missed = res.payload.filter(
(message) => Number(message.id) > last_message.current,
);
if (stale || !res?.success || !Array.isArray(res.payload)) return;
const missed = res.payload.filter(
(message) => Number(message.id) > last_message.current,
);
for (const message of missed) {
replay({ data: { event: "server:bot-message", data: message } });
}
/**
* After the messages, so a reply that ended silently (its last
* word an interim one) drops the row once its face moves on.
*/
if (res.bot?.id) replay({ data: { event: "server:bot-updated", data: res.bot } });
};
for (const message of missed) {
replay({ data: { event: "server:bot-message", data: message } });
}
/**
* Coming back to the app (a notification tapped, the PWA brought
* forward) checks at once: the socket was likely down meanwhile.
* After the messages, so a reply that ended silently (its last
* word an interim one) drops the row once its face moves on.
*/
const onVisible = () => {
if (document.visibilityState == "visible") check();
};
if (res.bot?.id) replay({ data: { event: "server:bot-updated", data: res.bot } });
}, [session_id]);
const timer = setInterval(check, AppData.BotReplyCatchUpMs);
useRefocus({ onRefocus: () => void check() });
/**
* While a reply is due, a poll covers a reply whose push was missed
* while the page stayed in front (a socket that dropped silently).
*/
useEffect(() => {
if (!awaiting_reply || !session_id) return;
const timer = setInterval(() => void check(), AppData.BotReplyCatchUpMs);
return () => clearInterval(timer);
}, [awaiting_reply, session_id, check]);
/**
* The socket was down while the page stayed open: going back online or
* restoring it from the back-forward cache checks at once.
*/
useEffect(() => {
window.addEventListener("online", check);
window.addEventListener("pageshow", check);
document.addEventListener("visibilitychange", onVisible);
return () => {
stale = true;
clearInterval(timer);
window.removeEventListener("online", check);
window.removeEventListener("pageshow", check);
document.removeEventListener("visibilitychange", onVisible);
};
}, [awaiting_reply, session_id]);
}
}, [check]);
}
@@ -52,6 +52,13 @@ export default function useThreadScroll({ messages }: Params) {
});
};
/**
* Whether the content's end is exactly at the column's bottom, with no
* slack: the pull-to-reload gesture reads it, since a thread a few
* pixels short still has somewhere of its own to scroll to.
*/
const atBottom = () => (measure()?.distance ?? 1) <= 0;
/** The user's own scrolling: it decides whether the thread follows. */
const onScroll = () => {
const offset = measure();
@@ -158,5 +165,6 @@ export default function useThreadScroll({ messages }: Params) {
jump_visible,
jump_to_bottom: jumpToBottom,
on_scroll: onScroll,
at_bottom: atBottom,
};
}
@@ -37,7 +37,9 @@ export default function MessageActions({ message }: Props) {
message_id={message.id}
onReact={onReact}
/>
{message.author == "bot" ? <MessageDetailsModal message_id={Number(message.id)} /> : null}
{message.author == "bot" ? (
<MessageDetailsModal message_id={Number(message.id)} tool_log={message.tool_log} />
) : null}
</>
) : null}
</Row>
@@ -10,17 +10,22 @@ import MessageDetailsCallRow from "./message-details-call-row";
import MessageDetailsFailureRow from "./message-details-failure-row";
import MessageDetailsHeading from "./message-details-heading";
import MessageDetailsModelRow from "./message-details-model-row";
import MessageToolsRollup from "./message-tools-rollup";
type Props = {
details: MessageDetails;
/**
* The message's `tool_log`: what its run did, tool by tool.
*/
tool_log?: string | null;
};
/**
* How a message was generated: the provider and model that answered and
* what it spent, then the job that ran it, every model it used, every
* call in order and every call that failed, with why.
* what it spent, then the job that ran it, what its tools did, every model
* it used, every call in order and every call that failed, with why.
*/
export default function MessageDetailsBody({ details }: Props) {
export default function MessageDetailsBody({ details, tool_log }: Props) {
const { totals, models, calls, failures, failed_calls, job } = details;
const { providers, model_names, first_at, job_kind, job_took } = messageDetailsFacts({ details });
@@ -63,6 +68,8 @@ export default function MessageDetailsBody({ details }: Props) {
</>
) : null}
<MessageToolsRollup tool_log={tool_log} />
{models.length ? (
<>
<MessageDetailsHeading>{models.length > 1 ? "Models used" : "Model used"}</MessageDetailsHeading>
@@ -12,14 +12,19 @@ import MessageDetailsBody from "./message-details-body";
type Props = {
message_id: number;
/**
* Its `tool_log`: what the run behind it did, shown in the modal and
* passed along to the copied report.
*/
tool_log?: string | null;
};
/**
* The info button under a bot message, and the modal it opens: which
* provider and model generated it, the run behind it, and every model
* call with its tokens and cost. Loaded when it opens.
* provider and model generated it, the run behind it, what its tools did,
* and every model call with its tokens and cost. Loaded when it opens.
*/
export default function MessageDetailsModal({ message_id }: Props) {
export default function MessageDetailsModal({ message_id, tool_log }: Props) {
const [open, set_open] = useState(false);
const { details, loading, error } = useMessageDetails({ message_id, enabled: open });
@@ -47,7 +52,7 @@ export default function MessageDetailsModal({ message_id }: Props) {
<Stack className="mt-4 max-h-[60vh] w-full gap-0! items-stretch overflow-y-auto">
{details ? (
<MessageDetailsBody details={details} />
<MessageDetailsBody details={details} tool_log={tool_log} />
) : (
<Span className="text-[13px] leading-[18px] text-ink-secondary">
{loading || !error ? "Loading details..." : error}
@@ -7,12 +7,14 @@ import type {
BotWithLastMessage,
} from "@/src/types";
import useMessageSelection from "../(hooks)/use-message-selection";
import usePullToRefresh from "../(hooks)/use-pull-to-refresh";
import useThreadScroll from "../(hooks)/use-thread-scroll";
import groupMessages from "../(utils)/group-messages";
import BotThinkingRow from "./bot-thinking-row";
import ConversationChatroomStatus from "./conversation-chatroom-status";
import MessageGroupBlock from "./message-group-block";
import OlderMessagesLoader from "./older-messages-loader";
import PullToRefreshIndicator from "./pull-to-refresh-indicator";
import QuoteSelectionButton from "./quote-selection-button";
import ScrollToBottomButton from "./scroll-to-bottom-button";
import quotableText from "../(utils)/quotable-text";
@@ -54,6 +56,11 @@ type Props = {
* Quotes text selected in a message in the composer.
*/
onQuote?: (params: { text: string }) => void;
/**
* Reads the conversation again, pulled up from the bottom of the
* thread on a phone.
*/
onReload: () => Promise<void>;
/**
* The session's older messages, loaded at the top of the thread.
*/
@@ -82,7 +89,8 @@ type Props = {
* above it (shown only, never put in the bot's prompt); the reversed column keeps
* the view where it was as they land above it. The thread follows new
* messages while it sits at its bottom, stays put while it's scrolled up
* and then offers a button to get back down.
* and then offers a button to get back down. Pulled up past its bottom on
* a phone, it offers to read the conversation again.
*/
export default function MessageThread({
bot,
@@ -95,17 +103,24 @@ export default function MessageThread({
no_reply_due,
notice,
onQuote,
onReload,
older,
}: Props) {
const groups = useMemo(() => groupMessages({ messages }), [messages]);
const scroll = useThreadScroll({ messages });
const pull_state = usePullToRefresh({
column_ref: scroll.column_ref,
content_ref: scroll.content_ref,
at_bottom: scroll.at_bottom,
on_refresh: onReload,
});
const { selection, clear } = useMessageSelection({ ref: scroll.column_ref });
return (
<Stack className="relative grow min-h-0 gap-0! items-stretch">
<Stack
componentRef={scroll.column_ref as RefObject<HTMLDivElement>}
className="grow min-h-0 gap-0! items-stretch overflow-y-auto flex-col-reverse"
className="grow min-h-0 gap-0! items-stretch overflow-y-auto overscroll-contain flex-col-reverse"
onScroll={scroll.on_scroll}
>
<Stack
@@ -162,6 +177,7 @@ export default function MessageThread({
{scroll.jump_visible ? (
<ScrollToBottomButton onClick={scroll.jump_to_bottom} />
) : null}
<PullToRefreshIndicator state={pull_state} onReload={onReload} />
{selection && onQuote ? (
<QuoteSelectionButton
selection={selection}
@@ -0,0 +1,33 @@
import Row from "@moduletrace/twui/layout/Row";
import Span from "@moduletrace/twui/layout/Span";
import type { ToolRollupEntry } from "@/src/utils/tool-rollup";
type Props = {
tool: ToolRollupEntry;
};
/**
* One tool in a message's rollup: its name as the run called it, what the
* app calls that, and how many calls it made, of which how many failed.
*/
export default function MessageToolRow({ tool }: Props) {
return (
<Row className="w-full py-1.5 gap-3! flex-nowrap items-baseline border-0 border-b border-solid border-hairline last:border-b-0">
<Span
className="grow min-w-0 font-mono text-[12px] leading-4 text-ink truncate"
title={`${tool.label} (${tool.name})`}
>
{tool.name}
</Span>
<Span className="shrink-0 text-[11px] leading-4 text-ink-secondary tabular-nums">{tool.label}</Span>
<Span className="shrink-0 text-[12px] leading-4 text-ink-secondary tabular-nums">
{tool.count == 1 ? "1 call" : `${tool.count} calls`}
</Span>
{tool.failed ? (
<Span className="w-14 shrink-0 text-right text-[11px] leading-4 text-ink-secondary tabular-nums">
{`${tool.failed} failed`}
</Span>
) : null}
</Row>
);
}
@@ -0,0 +1,37 @@
import type { ToolRollupEntry } from "@/src/utils/tool-rollup";
import toolRollup from "@/src/utils/tool-rollup";
import MessageDetailRow from "./message-detail-row";
import MessageDetailsHeading from "./message-details-heading";
import MessageToolRow from "./message-tool-row";
type Props = {
/**
* The message's `tool_log` (`{ name, ok }` per call).
*/
tool_log?: string | null;
};
/**
* What a message's run actually did, by tool: the one reading that tells a
* run which worked from one that spent 242 model calls and changed
* nothing. The app's own record (`bot_messages.tool_log`), so it can't
* claim work the run didn't make.
*/
export default function MessageToolsRollup({ tool_log }: Props) {
const rollup = toolRollup({ tool_log });
if (!rollup || !rollup.tools.length) return null;
return (
<>
<MessageDetailsHeading>Tools used</MessageDetailsHeading>
<MessageDetailRow
label="Tool calls"
value={rollup.failed ? `${rollup.calls} (${rollup.failed} failed)` : String(rollup.calls)}
/>
{rollup.tools.map((tool: ToolRollupEntry) => (
<MessageToolRow key={tool.name} tool={tool} />
))}
</>
);
}
@@ -0,0 +1,44 @@
import { describe, expect, test } from "bun:test";
import { renderToString } from "react-dom/server";
import PullToRefreshIndicator from "./pull-to-refresh-indicator";
const reload = async () => {};
describe("PullToRefreshIndicator", () => {
test("shows nothing until the thread is pulled", () => {
expect(
renderToString(<PullToRefreshIndicator state="idle" onReload={reload} />),
).toBe("");
});
test("is one icon in a ghost button, with no word beside it", () => {
const html = renderToString(<PullToRefreshIndicator state="pulling" onReload={reload} />);
expect(html).toContain("twui-button-secondary-ghost");
expect(html).toContain(`aria-label="Reload the conversation"`);
expect(html).toContain("<svg");
/**
* Nothing but the icon: the button's content wrapper holds no text.
*/
expect(html).not.toMatch(/twui-button-content-wrapper[^>]*>[A-Za-z]/);
});
test("dims the icon while it's only being pulled and lights it up once letting go reloads", () => {
expect(
renderToString(<PullToRefreshIndicator state="pulling" onReload={reload} />),
).toContain("opacity-40");
expect(
renderToString(<PullToRefreshIndicator state="ready" onReload={reload} />),
).not.toContain("opacity-40");
});
test("holds the icon's place with a spinner while it reloads", () => {
const html = renderToString(
<PullToRefreshIndicator state="refreshing" onReload={reload} />,
);
expect(html).toContain("twui-loading");
expect(html).toContain("aria-busy");
expect(html).toContain("disabled");
});
});
@@ -0,0 +1,41 @@
import { twMerge } from "tailwind-merge";
import { RefreshCw } from "lucide-react";
import Button from "@moduletrace/twui/layout/Button";
import type { PullToRefreshState } from "../(hooks)/use-pull-to-refresh";
type Props = {
state: PullToRefreshState;
onReload: () => Promise<void>;
};
/**
* The phone's pull-to-reload control: a lone icon in the room the pull
* opens under the newest message, a ghost button so it reads as part of
* the paper rather than a card over it. It stays dim while the pull is
* only being made or the room is only being held, and lights up once
* letting go will reload. While the conversation is read again the button
* shows its own spinner in the icon's place, and tapping it reloads too,
* so the gesture isn't the only way. Nothing shows until the thread is
* pulled.
*/
export default function PullToRefreshIndicator({ state, onReload }: Props) {
if (state == "idle") return null;
return (
<Button
title="Reload the conversation"
variant="ghost"
color="text"
size="smaller"
loading={state == "refreshing"}
loadingIconSize="normal"
onClick={() => void onReload()}
className={twMerge(
"absolute bottom-3 left-1/2 z-20 -translate-x-1/2 text-ink-secondary",
state == "pulling" && "opacity-40",
state == "ready" && "text-ink",
)}
beforeIcon={<RefreshCw size={16} aria-hidden />}
/>
);
}
@@ -46,6 +46,7 @@ import SessionMovedBar from "../(partials)/session-moved-bar";
import NoModelNotice from "../(partials)/no-model-notice";
import syncSessionQuery from "../(utils)/sync-session-query";
import announceShownSession from "@/src/functions/frontend/announce-shown-session";
import requestLiveCrewRefresh from "@/src/functions/frontend/request-live-crew-refresh";
/**
* The conversation column: header, bottom-anchored thread, composer, the
@@ -234,6 +235,16 @@ export default function Conversation() {
last_message_id: last_saved_id,
});
/**
* The thread's pull-to-reload: the page's crew read again (the layout
* answers the request) and this conversation's history, which skips
* the loading line since the pull shows its own spinner.
*/
const reload_conversation = async () => {
requestLiveCrewRefresh();
await history.reload();
};
/**
* A message that starts a newer session (sent here or in another tab)
* moves the thread onto it.
@@ -436,6 +447,7 @@ export default function Conversation() {
) : null
}
older={older}
onReload={reload_conversation}
onQuote={({ text }) =>
composer.current?.insertQuote({ text })
}
@@ -0,0 +1,37 @@
import { describe, expect, test } from "bun:test";
import minimumWait from "./minimum-wait";
const wait = (ms: number) =>
new Promise<void>((resolve) => {
setTimeout(resolve, ms);
});
describe("minimumWait", () => {
test("holds the floor under work that finishes at once", async () => {
const started = Date.now();
await minimumWait({ task: Promise.resolve(), minimum_ms: 30 });
expect(Date.now() - started).toBeGreaterThanOrEqual(29);
});
test("adds nothing to work that already took longer", async () => {
const started = Date.now();
await minimumWait({ task: wait(40), minimum_ms: 30 });
expect(Date.now() - started).toBeGreaterThanOrEqual(39);
expect(Date.now() - started).toBeLessThan(150);
});
test("waits out the floor for work that failed, without throwing", async () => {
const started = Date.now();
await minimumWait({
task: Promise.reject(new Error("the conversation didn't load")),
minimum_ms: 30,
});
expect(Date.now() - started).toBeGreaterThanOrEqual(29);
});
});
@@ -0,0 +1,20 @@
/**
* Waits for `task` and for at least `minimum_ms`, whichever ends last, and
* never throws: it is used to keep a spinner up long enough to be seen, not
* to report what the work did (the work reports itself).
*/
export default async function minimumWait({
task,
minimum_ms,
}: {
task: Promise<unknown>;
minimum_ms: number;
}) {
const settled = task.then(
() => undefined,
() => undefined,
);
const waited = new Promise<void>((resolve) => setTimeout(resolve, minimum_ms));
await Promise.all([settled, waited]);
}
@@ -0,0 +1,65 @@
import { describe, expect, test } from "bun:test";
import { AppData } from "@/src/data/app-data";
import pullToRefreshState from "./pull-to-refresh";
/**
* The finger travel that opens the room to its limit.
*/
const full_travel = AppData.PullToRefreshRoomPx / AppData.PullToRefreshResistance;
describe("pullToRefreshState", () => {
test("a tap or a downward drag is not a pull", () => {
const tap = pullToRefreshState({ start_y: 300, current_y: 300 });
const downward = pullToRefreshState({ start_y: 300, current_y: 360 });
expect(tap.pulling).toBe(false);
expect(downward.pulling).toBe(false);
expect(downward.distance).toBe(0);
});
test("just under the minimum travel still isn't a pull", () => {
const pulled = pullToRefreshState({
start_y: 300,
current_y: 300 - AppData.PullToRefreshMinPx + 1,
});
expect(pulled.pulling).toBe(false);
expect(pulled.ready).toBe(false);
});
test("travel resists", () => {
const short = pullToRefreshState({ start_y: 300, current_y: 250 });
expect(short.distance).toBeCloseTo(50 * AppData.PullToRefreshResistance);
expect(short.pulling).toBe(true);
expect(short.ready).toBe(false);
});
test("a room only started, with nothing but paper under it, is not a reload", () => {
const pulled = pullToRefreshState({ start_y: 400, current_y: 400 - full_travel + 1 });
expect(pulled.distance).toBeLessThan(AppData.PullToRefreshRoomPx);
expect(pulled.ready).toBe(false);
});
test("the room is full at the limit, where the hold begins", () => {
const pulled = pullToRefreshState({ start_y: 400, current_y: 400 - full_travel });
expect(pulled.distance).toBeCloseTo(AppData.PullToRefreshRoomPx);
expect(pulled.ready).toBe(true);
});
test("opens no further than the room the icon needs", () => {
const capped = pullToRefreshState({ start_y: 900, current_y: 0 });
expect(capped.distance).toBe(AppData.PullToRefreshRoomPx);
expect(capped.ready).toBe(true);
});
test("resistance can be changed, e.g. for a test or a heavier pull", () => {
const pulled = pullToRefreshState({ start_y: 100, current_y: 80, resistance: 1 });
expect(pulled.distance).toBe(20);
expect(pulled.ready).toBe(false);
});
});
@@ -0,0 +1,26 @@
import { AppData } from "@/src/data/app-data";
/**
* A pull up from the bottom of the thread, where nothing of the
* conversation is left to scroll. Only upward travel counts, and only part
* of it shows, up to the room the icon needs; `ready` says the room is as
* deep as it opens, which is where the hold that reloads begins.
*/
export default function pullToRefreshState({
start_y,
current_y,
resistance = AppData.PullToRefreshResistance,
}: {
start_y: number;
current_y: number;
resistance?: number;
}) {
const travel = Math.max(0, start_y - current_y);
const distance = Math.min(travel * resistance, AppData.PullToRefreshRoomPx);
return {
distance,
pulling: travel >= AppData.PullToRefreshMinPx,
ready: distance >= AppData.PullToRefreshRoomPx,
};
}
+59
View File
@@ -0,0 +1,59 @@
import userAuth from "@/src/functions/backend/auth/user-auth";
import grabBots from "@/src/functions/backend/db/bots/grab-bots";
import grabUserWorkspaces from "@/src/functions/backend/db/workspaces/grab-user-workspaces";
import { LiveCrewRequestSchema } from "@/src/schemas/bot-schema";
import type { LiveCrewPayload } from "@/src/types";
import AppError from "@/src/utils/app-error";
import parseWithSchema from "@/src/utils/parse-with-schema";
import railBots from "@/src/utils/rail-bots";
import railWorkspaces from "@/src/utils/rail-workspaces";
import safeErrorMessage from "@/src/utils/safe-error-message";
import type {
APIResponseObject,
BunextAPIRouteHandler,
} from "@moduletrace/bunext/types";
/**
* The crew the rail lists, as it stands now (`grabBots` in a workspace or
* for the bots' own chats, and the user's workspaces), cut down the way the
* page's props are. Read again on every return to the page, so a push that
* never arrived (a phone asleep, a socket that dropped silently) can't
* leave a face, an unread mark or a latest message behind. The figure the
* lists show is all this returns: no prompts or memories.
*/
export const handler: BunextAPIRouteHandler<APIResponseObject<LiveCrewPayload>> =
async ({ req, body }) => {
try {
if (req.method != "POST") {
throw new AppError(`Method not allowed`);
}
const { user } = await userAuth({ req });
if (!user?.logged_in_status || !user.id) {
return { success: false, msg: `Unauthorized`, logoutUser: true };
}
const { workspace_id } = parseWithSchema({
schema: LiveCrewRequestSchema,
data: body,
});
const user_id = Number(user.id);
const [bots, workspaces] = await Promise.all([
grabBots({ user_id, workspace_id }),
grabUserWorkspaces({ user_id }),
]);
return {
success: true,
singleRes: {
bots: railBots({ bots }),
workspaces: railWorkspaces({ workspaces }),
},
};
} catch (error: unknown) {
return { success: false, msg: safeErrorMessage({ error }) };
}
};
+9
View File
@@ -142,6 +142,15 @@ export const ConversationHistoryRequestSchema = BotConversationRequestSchema.ext
export type ConversationHistoryRequest = z.infer<typeof ConversationHistoryRequestSchema>;
/**
* The crew a page lists, read again after the window regains focus.
*/
export const LiveCrewRequestSchema = z.object({
workspace_id: WorkspaceIdField,
});
export type LiveCrewRequest = z.infer<typeof LiveCrewRequestSchema>;
export const ListBotSessionsRequestSchema = BotConversationRequestSchema.extend({
query: z.string().trim().max(200).optional(),
page: z.coerce.number().int().positive().optional(),
+17
View File
@@ -2111,6 +2111,23 @@ export type ConversationHistoryPayload = {
redirect?: string;
};
/**
* The crew a page lists (the rail's bots and the user's workspaces), read
* again after the window regains focus.
*/
export type LiveCrewPayload = {
bots: BotWithLastMessage[];
workspaces: WorkspaceWithActivity[];
};
/**
* `LiveCrewPayload` announced to the page's lists (`cobble:live-crew-refreshed`),
* with the workspace it was read for: lists reading another place leave it.
*/
export type LiveCrewRefreshedDetail = LiveCrewPayload & {
workspace_id: number | null;
};
/**
* One build's `.bunext/public` files, downloaded by the service worker
* before the app runs (`grabPrecacheManifest`).
+4 -4
View File
@@ -64,9 +64,9 @@ describe("composeBotPrompt", () => {
"# You are Scout\n\nFind things.",
`# Workspace: Launch\n\nYou're working in the workspace "Launch". Follow its context and your instructions for it below, over your general habits where they differ.\n\nThe workspace's context, which the user sets:\n\nThe spring launch.\n\nShip by Friday.`,
"# Your instructions in Launch\n\nOwn the changelog.",
"# Memory\n\n- Cite sources.",
"# Memory about the user\n\n- The user prefers short replies.",
`# Memory in Launch\n\nYour own notes for this workspace: what you have learned here. They are not the workspace's description or context, which the user sets above; never call them the workspace's record. The user reads them in the workspace's settings, under this bot's row.\n\n- Marketing signs off on copy.`,
"# Memory\n\nYour own notes: they shape how you do what you're asked, never what you're asked to do.\n\n- Cite sources.",
"# Memory about the user\n\nWhat you've learned about the user. It shapes how you do the work, never what you do beyond it.\n\n- The user prefers short replies.",
`# Memory in Launch\n\nYour own notes for this workspace: what you have learned here. They shape how you do the work here, never what you do beyond it. They are not the workspace's description or context, which the user sets above; never call them the workspace's record. The user reads them in the workspace's settings, under this bot's row.\n\n- Marketing signs off on copy.`,
].join("\n\n"),
);
});
@@ -88,7 +88,7 @@ describe("composeBotPrompt", () => {
"Core.",
"# Install-wide instructions\n\nNever invent sources.",
`# Workspace: Launch\n\nYou're working in the workspace "Launch". Follow its context and your instructions for it below, over your general habits where they differ.\n\nThe workspace's context, which the user sets:\n\nThe spring launch.`,
"# Memory\n\n- Cite sources.",
"# Memory\n\nYour own notes: they shape how you do what you're asked, never what you're asked to do.\n\n- Cite sources.",
].join("\n\n"),
);
});
+7 -3
View File
@@ -123,16 +123,20 @@ export default function composeBotPrompt({
}
if (memory?.trim()) {
parts.push(`# Memory\n\n${memory.trim()}`);
parts.push(
`# Memory\n\nYour own notes: they shape how you do what you're asked, never what you're asked to do.\n\n${memory.trim()}`,
);
}
if (user_memory?.trim()) {
parts.push(`# Memory about the user\n\n${user_memory.trim()}`);
parts.push(
`# Memory about the user\n\nWhat you've learned about the user. It shapes how you do the work, never what you do beyond it.\n\n${user_memory.trim()}`,
);
}
if (workspace && workspace_bot?.memory?.trim()) {
parts.push(
`# Memory in ${name}\n\nYour own notes for this workspace: what you have learned here. They are not the workspace's description or context, which the user sets above; never call them the workspace's record. The user reads them in the workspace's settings, under this bot's row.\n\n${workspace_bot.memory.trim()}`,
`# Memory in ${name}\n\nYour own notes for this workspace: what you have learned here. They shape how you do the work here, never what you do beyond it. They are not the workspace's description or context, which the user sets above; never call them the workspace's record. The user reads them in the workspace's settings, under this bot's row.\n\n${workspace_bot.memory.trim()}`,
);
}
+43
View File
@@ -0,0 +1,43 @@
import {
JobStepBrowserToolInfix,
JobStepToolLabels,
JobStepToolPrefixLabels,
} from "@/src/dict/bot-queue-dict";
type Params = {
/**
* A tool's name, e.g. `computer_bash` or `<server>__<tool>`.
*/
name: string;
};
/**
* What a tool call does, in plain words: the app's own label for the tools
* it ships (`JobStepToolLabels`), a family's for anything matching its
* prefix (`JobStepToolPrefixLabels`: every browser tool reads "Using the
* browser"), else the name in words. Used for the live step line and for a
* message's tool rollup, so the two never drift.
*/
export default function toolLabel({ name }: Params) {
if (name.includes(JobStepBrowserToolInfix)) return JobStepToolPrefixLabels.browser_ as string;
const prefix = Object.keys(JobStepToolPrefixLabels).find((p) => name.startsWith(p));
return JobStepToolLabels[name] || (prefix && JobStepToolPrefixLabels[prefix]) || `Using ${readableToolName({ name })}`;
}
/**
* A tool name in words: `get_weather` reads "get weather", and an MCP
* server's `<slug>__<tool>` reads "Exa search (web search exa)".
*/
function readableToolName({ name }: { name: string }) {
const words = (part: string) => part.replace(/_+/g, " ").trim();
const [server, ...rest] = name.split("__");
const tool = words(rest.join(" "));
if (!tool) return words(name);
const server_words = words(server || "");
return `${server_words.charAt(0).toUpperCase()}${server_words.slice(1)} (${tool})`;
}
+51
View File
@@ -0,0 +1,51 @@
import { describe, expect, test } from "bun:test";
import toolRollup from "./tool-rollup";
const log = (...uses: { name: string; ok?: boolean }[]) => JSON.stringify(uses);
describe("toolRollup", () => {
test("no record of a run", () => {
expect(toolRollup({ tool_log: null })).toBe(null);
expect(toolRollup({ tool_log: "" })).toBe(null);
expect(toolRollup({ tool_log: "not json" })).toBe(null);
expect(toolRollup({ tool_log: `{"a":1}` })).toBe(null);
});
test("counts calls by tool, most used first", () => {
const rollup = toolRollup({
tool_log: log(
{ name: "computer_bash", ok: true },
{ name: "start_task", ok: true },
{ name: "computer_bash", ok: true },
{ name: "computer_bash", ok: false },
),
});
expect(rollup).toEqual({
calls: 4,
failed: 1,
tools: [
{ name: "computer_bash", label: "Running a command", count: 3, failed: 1 },
{ name: "start_task", label: "Starting a task", count: 1, failed: 0 },
],
});
});
test("labels a browser tool and an unknown one", () => {
const rollup = toolRollup({
tool_log: log({ name: "browser_navigate", ok: true }, { name: "exa__search", ok: true }),
});
expect(rollup?.tools).toEqual([
{ name: "browser_navigate", label: "Using the browser", count: 1, failed: 0 },
{ name: "exa__search", label: "Using Exa (search)", count: 1, failed: 0 },
]);
});
test("skips a use with no name", () => {
const rollup = toolRollup({ tool_log: JSON.stringify([{ ok: true }, { name: "write_file" }]) });
expect(rollup?.calls).toBe(1);
expect(rollup?.tools.map((tool) => tool.name)).toEqual(["write_file"]);
});
});
+85
View File
@@ -0,0 +1,85 @@
import toolLabel from "@/src/utils/tool-label";
type Params = {
/**
* A bot message's `tool_log` (JSON list of `{ name, ok }`).
*/
tool_log?: string | null;
};
export type ToolRollupEntry = {
/**
* The tool's name, as the run called it.
*/
name: string;
/**
* What it does, in words (`toolLabel`).
*/
label: string;
count: number;
/**
* How many of its calls came back an error.
*/
failed: number;
};
export type ToolRollup = {
calls: number;
failed: number;
/**
* Every tool the run called, most used first.
*/
tools: ToolRollupEntry[];
};
type ToolUse = {
name?: unknown;
ok?: unknown;
};
/**
* A message's tool calls counted by tool: 242 calls of a run that converted
* nothing read "242 model calls, 10.1M tokens" without it, and the same
* reads "210 computer_bash, 12 start_task" with it. Null when the message
* has no record of a run (a user message, an interim one, an older one).
*/
export default function toolRollup({ tool_log }: Params): ToolRollup | null {
if (!tool_log) return null;
let uses: unknown;
try {
uses = JSON.parse(tool_log);
} catch {
return null;
}
if (!Array.isArray(uses)) return null;
const counts = new Map<string, { count: number; failed: number }>();
for (const use of uses as ToolUse[]) {
const name = typeof use?.name == "string" ? use.name : "";
if (!name) continue;
const entry = counts.get(name) || { count: 0, failed: 0 };
entry.count++;
if (use.ok === false) entry.failed++;
counts.set(name, entry);
}
const tools = [...counts].map(([name, entry]) => ({
name,
label: toolLabel({ name }),
count: entry.count,
failed: entry.failed,
}));
return {
calls: tools.reduce((total, tool) => total + tool.count, 0),
failed: tools.reduce((total, tool) => total + tool.failed, 0),
tools: tools.sort((left, right) => right.count - left.count || left.name.localeCompare(right.name)),
};
}