Compare commits

...
17 Commits
Author SHA1 Message Date
tbenandClaude Opus 5.5 38648fc083 Release v0.15.3
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-06 12:57:54 +01:00
tbenandClaude Opus 5.5 6414d4e675 Let bots learn from the user's reactions
A reply's history now shows the user's own reactions on each bot message
in its app record, and the chat reply note tells the bot to save the
lasting preferences they show in its memory of that user. Adds a Dislike
reaction so a bot can tell what to avoid.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-06 12:57:54 +01:00
tbenandClaude Opus 5.5 ae64ef195d Release v0.15.2
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-06 11:37:53 +01:00
tbenandClaude Opus 5.5 06a4b7bb36 Step through a folder's images in the preview
An image opened from a list (a folder, the Files page, the chat's files
modal, a message's images) gets that list's images as a gallery:
Previous and Next in the header and the arrow keys step through them in
the same modal, each opening at its own fit, neighbours preloaded.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-06 11:37:53 +01:00
tbenandClaude Opus 5.5 2c8023ee4b Release v0.15.1
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-06 11:02:22 +01:00
tbenandClaude Opus 5.5 c0e79ee39c Open folder chips in a modal and give image previews zoom and fits
A folder chip opens the folder's listing over the chat, files opening
their own preview on top; a modified click or Open in Files still goes
to the files browser. Image previews get a viewer: zoom buttons and
keys, Ctrl/Cmd+wheel or pinch at the pointer, Fit, Fit width (a
full-page screenshot opens that way and scrolls down), Actual size,
double click and drag to pan. Escape closes only the top modal.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-06 11:02:22 +01:00
tbenandClaude Opus 5.5 bc9739509c Release v0.15.0
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-06 10:27:02 +01:00
tbenandClaude Opus 5.5 4d6c330954 Have worker bots work in their own home on computers
A worker now works in /home/cb-<bot>/workspace/users/<user> (cwd, HOME
and ~), with its bot-wide folder at /home/cb-<bot>/workspace and, in a
workspace, the shared folder at /home/cb-<bot>/workspace/workspaces/<id>.
Only /home/cb-<bot>/workspace is kept: the agent makes it a link to the
bot's folder on the mounted workspace (bots/<bot>), and workspaces/<id>
in it a link to the workspace's shared folder, checking both on every
request and putting back one that's gone. Nothing on disk moves, so
existing work opens at the new paths.

Paths are checked on their real place (computerWorkspacePath), so the
real spelling still works, and shown to a worker its own way
(computerRunPath). Computer folder refs take either spelling. The
coordinator keeps working in the computer's workspace.

Computer image 1.3.0; the layout bump recreates every computer once.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-06 10:27:02 +01:00
tbenandClaude Opus 5.5 78accbcc4f Release v0.14.2
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-06 08:48:20 +01:00
tbenandClaude Opus 5.5 5601e2c2b8 Keep ref forms out of the generated CSS
Comments in pages, hooks and types name refs like [task:ID], which
Tailwind read as arbitrary properties and emitted as "task: ID", so the
build warned it isn't a CSS property. The ref forms are now excluded as
candidates wherever they're written.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-06 08:48:20 +01:00
tbenandClaude Opus 5.5 7c678284ae Check replies against the app's record, budget runs and let bots delete tasks
A reply wrote "I'm scanning the contests now" and the scan's made-up
results in one answer, with no tool called and a file that didn't exist,
and the user built tasks on it. Before a reply goes out, reviewBotReply
now sends it back once when it names a file or task that doesn't exist
for the user, or says work is under way or a report will follow while
nothing was started and nothing is open from the conversation. A long
bot message whose run called no tools shows "No tools used".

start_task takes max_steps, enforced below the install's limit, and
task runs are told to stop and report when several tries leave them no
closer. Chat replies the user follows get delete_task (never routines,
hook calls or rooms), so a bot deletes a task instead of cancelling it
and calling it removed.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-06 08:48:20 +01:00
tbenandClaude Opus 5.5 8c868d6a04 Render task descriptions and notes as markdown
The task modal showed a task's description and notes as raw markdown.
Both now render through the message elements (TaskMarkdown): formatted,
raw HTML never rendered, links opening in a new tab and refs as their
chips, with the page's crew when no conversation gives one.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-06 08:35:45 +01:00
tbenandClaude Opus 5.5 179ff03d20 Release v0.14.1
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-06 07:37:58 +01:00
tbenandClaude Opus 5.5 0a19c2a3a9 Let bots rename tasks and queue follow-up runs instead of promising them
update_task now takes a title and brief, refusing an open twin's title,
so a bot fixes a task's name instead of offering a second task. start_task
says different work is queued at once with separate, and the chat reply
note says nothing wakes a bot when a run ends, so it never promises to do
something once a run finishes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-06 07:37:58 +01:00
tbenandClaude Opus 5.5 c3be864136 Load message markdown in any order and link workspace refs in rooms
The file preview merged the message markdown elements at module load,
but those reach the preview again through their file chips, so loading
them first crashed. It merges them when it renders now. Chatrooms and
hook call threads give their chips the user's workspaces, so a
[workspace:ID] there links instead of showing its number.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-06 07:28:16 +01:00
tbenandClaude Opus 5.5 e40fa823cb Show task refs as chips and link refs in a workspace's context
A bot's [task:ID] now renders as a chip that opens the task's detail
modal, and bots are told to write it when they name a task. The
workspace dashboard's context runs through linkComputerRefs with the
crew contexts, so bot and workspace mentions show as chips there too.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-06 07:25:44 +01:00
tbenandClaude Opus 5.5 4593decc13 Look for nft in the computer image build instead of running it
CI / check (push) Canceled after 0s
nft opens a netlink socket even for --version, which the emulated arm64 build has none of, so the v0.14.0 computer image failed to build. 1.2.0 was never published, so the fixed build keeps that tag.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-06 06:06:56 +01:00
105 changed files with 2833 additions and 262 deletions
+7 -7
View File
@@ -95,11 +95,11 @@ Enables SQLite foreign keys (`enableForeignKeys`), `bunextInit()`, `ensureDocker
- **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.
- **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.
- **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 `/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). Parsers in `src/utils/*-ref.ts`. 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.
- **File preview:** every file link (chips, attachments, files modal, task files, `/admin/files`) is a `FilePreviewLink`: a plain click opens `FilePreviewModal` (markdown rendered with the message elements, CSV/TSV as a table via `parseCsv`, images/PDF/audio/video in place, HTML in a frame with `sandbox=""` (plus the media server's `sandbox` CSP), other text as code, the kind from `filePreviewKind`; Download and Open in a new tab), a modified click still opens a tab. Text is read up to `AppData.FilePreviewMaxTextBytes`. Never render a file's HTML on the app's origin or with scripts.
- **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.
- **File preview:** every file link (chips, attachments, files modal, task files, `/admin/files`) is a `FilePreviewLink`: a plain click opens `FilePreviewModal` (markdown rendered with the message elements, CSV/TSV as a table via `parseCsv`, images in `ImageViewer` (zoom buttons and keys, Ctrl/Cmd+wheel or pinch at the pointer, Fit, Fit width (a full-page screenshot opens that way and scrolls down), Actual size, double click, drag to pan; sized by the `width` attribute and centred with auto margins, never flex centring, which cuts off a tall picture's top), PDF/audio/video in place, HTML in a frame with `sandbox=""` (plus the media server's `sandbox` CSP), other text as code, the kind from `filePreviewKind`; Download and Open in a new tab), a modified click still opens a tab. Text is read up to `AppData.FilePreviewMaxTextBytes`. Never render a file's HTML on the app's origin or with scripts. Opened from a list (a folder, the files modal, a message's images), an image gets that list's images as its `gallery` (`imagePreviewGallery`): Previous/Next and the arrow keys step through them in the same modal, neighbours preloaded. Escape closes only the top modal of a stack (`useTopModalEscape`; twui closes every open one). The message elements and the preview import each other (through the file chips), so the preview merges `MessageMarkdownComponents` when it renders, never at module load.
- **Copy chat** (header menu): the active session (the one on screen) as one markdown document (`api/admin/bots/conversation-export` -> `conversationMarkdown`, refs as names, message headings demoted). The clipboard write starts on the click with a pending `ClipboardItem` (`copyPendingText`), since Safari drops the gesture after a fetch.
- **Asking before acting:** `ask_user` (`QuestionsNote`) puts up to `AppData.BotQuestionMaxQuestions` multiple-choice questions (`single` = radios, `multiple` = checkboxes, optional typed "Other") on one card, once per run -> `bot_questions` -> `[question:ID]` chip opening `BotQuestionCard`; the message needs the user. Answers are checked against the questions (`checkBotQuestionAnswers`) and stored, then sent as the user's chat message (`botQuestionAnswersText`); Skip says so. Replies and user-started tasks only: never routines, hook calls or chatroom sessions (no one sees those).
- **Replies/reactions:** `reply_to_message_id` (not an FK); reactions from the fixed `BotMessageReactions`, toggled by `react-message.ts` and the `react_to_message` tool, pushed as `server:bot-reaction`.
- **Replies/reactions:** `reply_to_message_id` (not an FK); reactions from the fixed `BotMessageReactions`, toggled by `react-message.ts` and the `react_to_message` tool, pushed as `server:bot-reaction`. A reply's history shows the user's own reactions on each bot message in its app record (`botMessagesToHarness`, so `run-bot-reply` loads history with `user_id`), and the chat reply note tells the bot to save lasting preferences they show in its memory of that user; 👎 is in the set for that.
- **Attachments:** uploaded on pick (`upload-attachment.ts`, private `media`, no text kept: a reply reads a document's text from the file), linked via `bot_message_media`. Replies read files of the last `BotReplyAttachmentMessages` messages. Tasks don't get files yet.
- **Thinking row / stop:** `bot-busy-state.ts` decides the row's line and whether Stop shows. Stop (`api/admin/bots/stop.ts`, `stop-bot-jobs`) fails every open job of that bot for the user, aborts the running handler (`job-abort-registry`) and drops late face updates.
- **Voice:** mic -> `api/admin/bots/transcribe.ts`; play -> `GET speak-message` streamed into `<audio>`. Nothing recorded is stored. Both disabled with a note when the harness has no model.
@@ -117,8 +117,8 @@ Enables SQLite foreign keys (`enableForeignKeys`), `bunextInit()`, `ensureDocker
- 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`). Work in `run-bot-job.ts` -> `run-bot-reply.ts` / `run-bot-task.ts`. Throw `BotJobFatalError` for failures retrying can't fix.
- 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 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`).
- **`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.
- **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.
### Live updates
@@ -141,7 +141,7 @@ A worker reaches another worker **only through the coordinator**: `ask_crew` (ev
- **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.
- 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 `bots/<bot>/users/<user>` (cwd, `HOME`), `bots/<bot>` and `workspaces/<workspace>` (`computerRunDirs`, `withComputerDirs`, `resolveComputerPath`), and 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.
- **Folders:** a run works only in its user's folder (cwd, `HOME`), its bot's and its workspace's (`computerRunDirs`, `withComputerDirs`, `resolveComputerPath`). **A worker sees them through its home:** `/home/cb-<bot>/workspace` (a link the agent keeps to `bots/<bot>`, checked every request by `ensureRunUser`; the rest of the home stays in the container and is never kept), with `users/<user>` and, in a workspace, `workspaces/<id>` (a link to the shared `workspaces/<id>`) inside it; the coordinator works in `bots/<bot>/users/<user>` and reaches the whole workspace. Paths are checked on their real place (`computerWorkspacePath`) and shown to a worker its way (`computerRunPath`); computer folder refs take either spelling. Linux enforces it between bots: **every worker works as its own account** `cb-<bot>` (uid `100000 + id`, no sudo, `ComputerRunDirs.run_as` -> the agent's `run_as`, made by `ensureRunUser`, commands through `setpriv --init-groups`), owning `bots/<bot>` (`2770`); a workspace's folder (root's) belongs to group `cw-<id>` its bots join. **`gem`, and so Chrome, has no way into either** (a page could show another bot's files): a worker's downloads (`collectComputerDownloads`), uploads and files saved by name (`withWorkerBrowserFiles`) pass through a folder of the call's own and are copied by the worker's account (`sudo -u`), never written by `gem` into its folder, and a worker opens no `file:` URLs (it serves its pages on localhost). Its env files are in its own home. A worker can't reach the computer's services: the agent's nftables rule (`guardServicePorts`, container `CapAdd: NET_ADMIN`) resets its connections to the agent, CDP, Playwright MCP, VNC and ttyd, and the X display needs gem's cookie; **without the rule the agent refuses everything for a worker** (never falls back to `gem`). The agent reads files for a worker only inside its folders and home, checked on the open descriptor (`openRunFile`), and writes as the worker (`writeFileAs`). Only the coordinator works as `gem` (sudo). Users within one bot's folder aren't separated by Linux (same account). Keep `computerWorkerAccount` and `runUserFor` alike.
- **Installs:** workers install pip/npm packages into `~/.local` of their folder themselves; anything needing root goes through `request_install` (worker task runs the user follows) -> `install_requests` -> a coordinator task on that computer in the super admin's coordinator conversation (`createInstallRequest`, fenced `installRequestBlock`, `InstallRequestNote`, `answer_install_request`); when that job ends however it ends (`settleInstallRequest`, from the job helpers) the answer lands in the worker's session as a crew message (`from_install_request_id`, `isCrewMessage`) and wakes it. Stop also ends a worker's leftover processes on its computers (`endWorkerProcesses`).
- **Tools:** the app's own `computer_bash`, `computer_read_file`, `computer_write_file`, `computer_edit_file` (`src/harness/tools/computer/`, paths through `resolveComputerPath`) plus Playwright MCP's `browser_*` (minus `ComputerMcpExcludedTools`: close, resize, config, `browser_run_code_unsafe`; `withComputerDirs` checks `file:` URLs, `paths` and `filename`). Playwright MCP returns only `browser_snapshot` inline: actions save their snapshot and console log in its own folder (`ComputerBrowserOutputDir`, outside every run's folders), so `withBrowserOutputs` turns those links into the tool that reads them, and moves what Chrome finished downloading (`ComputerBrowserDownloadsDir`; Playwright over CDP never sees downloads) into the run's `downloads/` after each browser call. Each command is its own `bash -c` in its own process group, stdin `/dev/null`, killed with its children at its timeout (at most `AppData.ComputerCommandMaxSeconds`) or when the call is aborted (Stop), so nothing blocks the computer; background work (`nohup ... &`) doesn't hold the call.
- **Viewing:** `/computers/<id>/` proxy (`handleComputerProxy`, strips app cookies, adds the token, bridges websockets) passes **only the view paths** (`computerProxyPathAllowed`), never the agent's API or `/mcp` (those are the app's tools, with the folder rules). Modes (`ComputerViewModes`, `computerViewModesFor`): **Browser**, the computer's screen (noVNC, scaled to the frame; its size is the computer's setting, a viewer can't resize it), so Chrome shows whole: tab strip, address bar, menu, extensions, drop-downs and prompts (no window manager, Chrome's window fills the screen), and **Shell** (ttyd as `gem`, for crew managers only, `crew_only`: it reads every folder there). Never draw a stand-in browser UI around a page: the user wants Chrome itself. `computer/novnc/cobble-clipboard.js` (added to noVNC's page) makes Ctrl/Cmd+V paste the user's clipboard and copies the computer's back; browsers allow that only over HTTPS or localhost (otherwise noVNC's side panel). Chrome's `--window-size` is in scaled units, so the agent divides it by the scale. No code editor in the image; a mode can be added to `ComputerViewModes`. Old `[take-over:ID:code|desktop]` refs open the first mode; take-overs ask only for modes every user can open. **Take-over:** `ask_user_to_take_over` writes `[take-over:ID:mode]`; "Hand back" sends a chat message; tasks stop and report rather than wait.
@@ -158,7 +158,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`; 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`; `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, 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`; `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.
### Envs
+4 -2
View File
@@ -127,8 +127,10 @@ RUN set -eu; \
# coordinator, which installs what worker bots ask for (it's lost when the
# container is recreated). Worker bots get accounts of their own, without
# sudo, made by the agent. Chrome and Chromium read managed policies (the
# app's default extensions) from the same folder.
RUN setpriv --version && setfacl --version && nft --version \
# app's default extensions) from the same folder. nft is only looked for,
# never run: it opens a netlink socket even for --version, which an
# emulated (arm64 on amd64) build doesn't have.
RUN setpriv --version && setfacl --version && command -v nft \
&& useradd --create-home --uid 1000 --shell /bin/bash gem \
&& echo 'gem ALL=(ALL) NOPASSWD:ALL' > /etc/sudoers.d/gem \
&& chmod 440 /etc/sudoers.d/gem \
+8 -2
View File
@@ -55,7 +55,13 @@ commands. Every worker bot works as its own account, `cb-<bot id>` (uid and
gid `100000 + id`, no sudo), made by the agent the first time the app acts
for it (`run_as`). Its folder `bots/<id>` is its own (`2770`), and a
workspace's folder `workspaces/<id>` (root's) belongs to the group `cw-<id>`
its bots join. `gem`, and so Chrome, can't open either: the app passes a
its bots join. A worker works through its home: `/home/cb-<id>/workspace`
is a link to `bots/<id>` (the only part of its home that's kept, since the
home itself lives in the container), its users' folders are `users/<user>`
in it, and in a workspace `workspaces/<workspace id>` in it is a link to
that workspace's folder. The agent checks both links on every request for
the worker and puts back one that's gone (whatever sits in its place is
moved aside). `gem`, and so Chrome, can't open either: the app passes a
worker's uploads, downloads and files saved by name through a folder of the
call's own, copied by the worker's account (`sudo -u`), and a worker can't
open `file:` URLs. Its env files live in its own home.
@@ -116,7 +122,7 @@ tag; the release workflow builds a tag once (a dispatch with
bun run build:computer # builds AppData.ComputerImage for this machine
docker run -d --name cobble-computer-dev --shm-size 2g \
--security-opt seccomp=unconfined --cap-add NET_ADMIN -p 8170:8080 \
ghcr.io/moduletrace/cobble-computer:1.2.0
ghcr.io/moduletrace/cobble-computer:1.3.0
```
A computer run by hand like that has no token, so anyone who reaches its port
+78 -9
View File
@@ -1,8 +1,9 @@
import { execFile } from "node:child_process";
import { chmod, chown, mkdir, stat } from "node:fs/promises";
import { chmod, chown, lstat, mkdir, readlink, rename, stat, symlink, unlink } from "node:fs/promises";
import path from "node:path";
import { promisify } from "node:util";
import { AgentConfig } from "./config";
import commandArgv from "./command-argv";
import log from "./log";
import type { RunUser } from "./run-user-for";
@@ -20,19 +21,28 @@ let queue: Promise<unknown> = Promise.resolve();
* Makes a worker's account and, in a workspace, its group (idempotent,
* one at a time), and hands it its folders: its home (private), the bot's
* folder (its own) and the workspace's (its group's). Neither gem nor any
* other worker can read them; the coordinator, as gem, uses sudo.
* other worker can read them; the coordinator, as gem, uses sudo. Then,
* on every call, makes sure of the links the worker works through
* (`keepLinks`): only the bot's folder is kept, so a write through a link
* that's gone would land somewhere a recreate wipes.
*/
export default function ensureRunUser({ run_user }: { run_user: RunUser }) {
export default async function ensureRunUser({ run_user }: { run_user: RunUser }) {
const key = `${run_user.uid}:${run_user.workspace?.gid || 0}`;
if (ready.has(key)) return Promise.resolve();
if (!ready.has(key)) {
await serially(async () => {
if (ready.has(key)) return;
const next = queue.then(async () => {
if (ready.has(key)) return;
await setUp({ run_user });
ready.add(key);
});
}
await setUp({ run_user });
ready.add(key);
});
if (!(await linksInPlace({ run_user }))) await serially(() => keepLinks({ run_user }));
}
function serially(work: () => Promise<void>) {
const next = queue.then(work);
queue = next.catch(() => {});
@@ -71,6 +81,65 @@ async function setUp({ run_user }: { run_user: RunUser }) {
* bots share it through the group.
*/
if (workspace) await shareFolder({ dir: workspace.dir, uid: 0, gid: workspace.gid });
await keepLinks({ run_user });
}
/**
* Whether the worker's links lead where they should: `workspace` in its
* home to the bot's folder, and in a workspace, `workspaces/<id>` in the
* bot's folder to the workspace's shared one. Only reads.
*/
async function linksInPlace({ run_user }: { run_user: RunUser }) {
if (!(await isLinkTo({ link: run_user.kept_dir, target: run_user.bot_dir }))) return false;
return !run_user.workspace || isLinkTo({ link: run_user.workspace.link, target: run_user.workspace.dir });
}
async function isLinkTo({ link, target }: { link: string; target: string }) {
const info = await lstat(link).catch(() => null);
return !!info?.isSymbolicLink() && (await readlink(link).catch(() => "")) == target;
}
/**
* Puts the worker's links back where they're missing or lead elsewhere.
* Whatever else sits in a link's place is moved aside, never deleted.
* The home's link is made as root (the home is a real folder in root's
* /home, so nothing in its path is the worker's to swap); the shared
* folder's, inside the bot's folder (the worker's own), by the worker's
* account, so a link it left there can't send root anywhere.
*/
async function keepLinks({ run_user }: { run_user: RunUser }) {
const { kept_dir, bot_dir, workspace } = run_user;
if (!(await isLinkTo({ link: kept_dir, target: bot_dir }))) {
const info = await lstat(kept_dir).catch(() => null);
if (info?.isSymbolicLink()) await unlink(kept_dir);
else if (info) await rename(kept_dir, `${kept_dir}.before-${Date.now()}`);
await symlink(bot_dir, kept_dir);
}
if (workspace && !(await isLinkTo({ link: workspace.link, target: workspace.dir }))) {
const link = quoted({ text: workspace.link });
const target = quoted({ text: workspace.dir });
const argv = commandArgv({
command: [
`umask 007`,
`mkdir -p "$(dirname ${link})"`,
`if [ -L ${link} ]; then ln -sfn ${target} ${link}; elif [ -e ${link} ]; then mv ${link} ${link}.before-$(date +%s) && ln -s ${target} ${link}; else ln -s ${target} ${link}; fi`,
].join(" && "),
as: { uid: run_user.uid, gid: run_user.gid },
});
await run(argv.file, argv.args, { cwd: "/", timeout: 30_000 });
}
}
function quoted({ text }: { text: string }) {
return `'${text.replaceAll("'", `'\\''`)}'`;
}
/**
+2
View File
@@ -8,6 +8,7 @@ describe("runUserFor", () => {
uid: 100_007,
gid: 100_007,
home: "/home/cb-7",
kept_dir: "/home/cb-7/workspace",
bot_dir: "/home/gem/workspace/bots/7",
workspace: null,
});
@@ -18,6 +19,7 @@ describe("runUserFor", () => {
name: "cw-12",
gid: 10_000_012,
dir: "/home/gem/workspace/workspaces/12",
link: "/home/gem/workspace/bots/3/workspaces/12",
});
});
+16 -5
View File
@@ -9,21 +9,28 @@ export type RunUser = {
* Its home, in the container (the env files live there).
*/
home: string;
/**
* `workspace` in its home: a link to `bot_dir`, the only part of its
* home that's kept. The app names every worker path through it.
*/
kept_dir: string;
/**
* The bot's folder in the workspace, owned by the account.
*/
bot_dir: string;
/**
* The workspace the run is in: its shared folder belongs to this group,
* which the account joins.
* which the account joins, and `link` (`workspaces/<id>` in the bot's
* folder) leads to it.
*/
workspace: { name: string; gid: number; dir: string } | null;
workspace: { name: string; gid: number; dir: string; link: string } | null;
};
/**
* The account a worker bot's commands run as on this computer
* (`cb-<bot id>`, no sudo) and, in a workspace, the group its bots share
* (`cw-<id>`). Throws for an id that isn't a whole number in range.
* (`cw-<id>`). Keep alike the app's `computerWorkerAccount` and
* `computerRunDirs`. Throws for an id that isn't a whole number in range.
*/
export default function runUserFor({ bot_id, workspace_id }: { bot_id: unknown; workspace_id?: unknown }): RunUser {
const bot = runId({ value: bot_id });
@@ -38,18 +45,22 @@ export default function runUserFor({ bot_id, workspace_id }: { bot_id: unknown;
const id = AgentConfig.WorkerIdBase + bot;
const name = `cb-${bot}`;
const home = `/home/${name}`;
const bot_dir = path.posix.join(AgentConfig.WorkspaceDir, "bots", String(bot));
return {
name,
uid: id,
gid: id,
home: `/home/${name}`,
bot_dir: path.posix.join(AgentConfig.WorkspaceDir, "bots", String(bot)),
home,
kept_dir: path.posix.join(home, "workspace"),
bot_dir,
workspace: workspace
? {
name: `cw-${workspace}`,
gid: AgentConfig.WorkspaceGroupBase + workspace,
dir: path.posix.join(AgentConfig.WorkspaceDir, "workspaces", String(workspace)),
link: path.posix.join(bot_dir, "workspaces", String(workspace)),
}
: null,
};
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "cobble",
"version": "0.14.0",
"version": "0.15.3",
"module": "index.ts",
"type": "module",
"private": true,
@@ -212,3 +212,64 @@ describe("botMessagesToHarness with mentions", () => {
]);
});
});
describe("botMessagesToHarness with reactions", () => {
test("adds the user's reactions to the record of the message's tools", () => {
expect(
botMessagesToHarness({
messages: [
message("user", "summarise it"),
{
...message("bot", "Here it is."),
tool_log: JSON.stringify([{ name: "read_file", ok: true }]),
reactions: [
{ emoji: "👍" as const, count: 1, mine: true },
{ emoji: "👎" as const, count: 1, mine: true },
],
},
],
}),
).toEqual([
{ role: "user", content: "summarise it" },
{
role: "assistant",
content:
"Here it is.\n\n[App record: this message's run called read_file. The user reacted to it with 👍 (like), 👎 (dislike).]",
},
]);
});
test("records reactions on a message whose run wasn't recorded", () => {
expect(
botMessagesToHarness({
messages: [
message("user", "hi"),
{
...message("bot", "hello"),
reactions: [{ emoji: "❤️" as const, count: 1, mine: true }],
},
],
}),
).toEqual([
{ role: "user", content: "hi" },
{ role: "assistant", content: "hello\n\n[App record: The user reacted to it with ❤️ (love).]" },
]);
});
test("leaves out reactions that aren't the user's", () => {
expect(
botMessagesToHarness({
messages: [
message("user", "hi"),
{
...message("bot", "hello"),
reactions: [{ emoji: "🎉" as const, count: 1, mine: false }],
},
],
}),
).toEqual([
{ role: "user", content: "hi" },
{ role: "assistant", content: "hello" },
]);
});
});
+51 -8
View File
@@ -1,7 +1,8 @@
import isCrewMessage from "@/src/utils/is-crew-message";
import { BotMessageReactions } from "@/src/dict/bot-dict";
import describeToolUses from "@/src/harness/text/describe-tool-uses";
import type { HarnessContentPart, HarnessMessage, HarnessToolUse } from "@/src/harness/types";
import type { BotMessageWithAttachments } from "@/src/types";
import type { BotMessageReaction, BotMessageWithAttachments } from "@/src/types";
import describeMessageRefs, { type MessageRefNames } from "@/src/utils/describe-message-refs";
import { AppRecordPrefix } from "@/src/utils/strip-app-records";
import describeAttachment from "./describe-attachment";
@@ -10,7 +11,15 @@ import crewMessageBlock from "@/src/utils/crew-message-block";
type Params = {
messages: Pick<
BotMessageWithAttachments,
"id" | "author" | "text" | "attachments" | "reply_to" | "tool_log" | "from_chatroom_id" | "from_install_request_id"
| "id"
| "author"
| "text"
| "attachments"
| "reply_to"
| "tool_log"
| "reactions"
| "from_chatroom_id"
| "from_install_request_id"
>[];
/**
* Loaded files by message id (`loadAttachmentParts`). Files of other
@@ -34,7 +43,8 @@ type Turn = { role: "user" | "assistant"; parts: HarnessContentPart[] };
* starts with the user. A turn that is only text stays a string. A bot
* message whose run was recorded (`tool_log`) is followed by the app's
* record of the tools it called, so the bot can tell what its past
* messages actually did from what they say. A chatroom's outcome brought
* messages actually did from what they say, and of how the user reacted
* to it, their feedback on it. A chatroom's outcome brought
* back to the bot, or the coordinator's answer to its install request
* (`isCrewMessage`), is a user turn fenced as what the
* coordinator passed on (`crewMessageBlock`), never the user's words.
@@ -95,7 +105,9 @@ function messageParts({
const content: HarnessContentPart[] = text ? [{ type: "text", text }] : [];
if (role == "assistant") {
const record = text ? appRecord({ tool_log: message.tool_log }) : "";
const record = text
? appRecord({ tool_log: message.tool_log, reactions: message.reactions })
: "";
return record ? [...content, { type: "text", text: record }] : content;
}
@@ -116,10 +128,25 @@ function messageParts({
}
/**
* The app's line after a bot message naming the tools its run called, or
* nothing when the run wasn't recorded.
* The app's line after a bot message naming the tools its run called and
* the user's own reactions to it, or nothing when there's neither.
*/
function appRecord({ tool_log }: { tool_log?: string | null }) {
function appRecord({
tool_log,
reactions,
}: {
tool_log?: string | null;
reactions?: BotMessageReaction[];
}) {
const facts = [toolsRecord({ tool_log }), reactionsRecord({ reactions })].filter(Boolean);
return facts.length ? `${AppRecordPrefix} ${facts.join(" ")}]` : "";
}
/**
* The tools a recorded run called, or nothing when it wasn't recorded.
*/
function toolsRecord({ tool_log }: { tool_log?: string | null }) {
if (!tool_log) return "";
let uses: HarnessToolUse[];
@@ -134,7 +161,23 @@ function appRecord({ tool_log }: { tool_log?: string | null }) {
const called = uses.length ? describeToolUses({ uses }) : "no tools";
return `${AppRecordPrefix} this message's run called ${called}.]`;
return `this message's run called ${called}.`;
}
/**
* The reactions the user gave a message, named, or nothing. A bot's own
* reactions aren't the user's feedback.
*/
function reactionsRecord({ reactions }: { reactions?: BotMessageReaction[] }) {
const named = (reactions || [])
.filter((reaction) => reaction.mine)
.map((reaction) => {
const title = BotMessageReactions.find((known) => known.value == reaction.emoji)?.title;
return title ? `${reaction.emoji} (${title.toLowerCase()})` : reaction.emoji;
});
return named.length ? `The user reacted to it with ${named.join(", ")}.` : "";
}
/**
+110
View File
@@ -0,0 +1,110 @@
import BunSQLite from "@moduletrace/bun-sqlite";
import grabBotFile from "@/src/functions/backend/db/bot-files/grab-bot-file";
import grabBotFileScope from "@/src/functions/backend/db/bot-files/grab-bot-file-scope";
import userReachesFileScope from "@/src/functions/backend/db/bot-files/user-reaches-file-scope";
import assertUserReachesTask from "@/src/functions/backend/db/tasks/assert-user-reaches-task";
import describeToolUses from "@/src/harness/text/describe-tool-uses";
import type { HarnessToolUse } from "@/src/harness/types";
import replyClaimProblems from "@/src/utils/reply-claim-problems";
import replyRefIds from "@/src/utils/reply-ref-ids";
import type { StorageScope } from "@/src/utils/storage-access";
type Params = {
text: string;
tool_uses: HarnessToolUse[];
bot_id: number | string;
user_id: number | string;
session_id: number | string;
/**
* The run's folders (`grabRunScopes`).
*/
scopes: StorageScope[];
};
/**
* Checks a chat reply's answer against what the app knows before it goes
* out (`replyClaimProblems`): every file and task it names must exist for
* the user (as their chips would open them), and work it says is under
* way must have been started by this reply or still be open from this
* conversation. Returns the note that sends the answer back to be written
* again, or null when it holds up. Bots wrote "I'm scanning now" with the
* scan's made-up results in the same answer, and the user acted on them.
*/
export default async function reviewBotReply({ text, tool_uses, bot_id, user_id, session_id, scopes }: Params) {
if (!text.trim()) return null;
const missing_file_ids: number[] = [];
for (const file_id of replyRefIds({ text, kind: "file" })) {
if (!(await fileExistsForUser({ file_id, user_id, scopes }))) missing_file_ids.push(file_id);
}
const missing_task_ids: number[] = [];
for (const task_id of replyRefIds({ text, kind: "task" })) {
const reached = await assertUserReachesTask({ user_id, task_id }).catch(() => null);
if (!reached?.id) missing_task_ids.push(task_id);
}
const problems = replyClaimProblems({
text,
tool_uses,
missing_file_ids,
missing_task_ids,
has_open_work: await hasOpenWork({ bot_id, session_id }),
});
if (!problems.length) return null;
return `Your answer above was not sent: the app checked it against its record, and it doesn't hold up.
${problems.map((problem) => `- ${problem}`).join("\n")}
The tools you actually called in this reply: ${describeToolUses({ uses: tool_uses })}. Nothing else happened. Write the answer again, saying only what those tools returned and what the user told you. If the work still needs doing, call start_task now and say it's started; never describe results of work no tool did, and never promise a report nothing will send. If part of your answer was wrong, say so plainly.`;
}
/**
* Whether a file chip would open for the user: in the run's folders, or
* in another folder the user reaches (an answer passed on from a room).
*/
async function fileExistsForUser({
file_id,
user_id,
scopes,
}: {
file_id: number;
user_id: number | string;
scopes: StorageScope[];
}) {
if ((await grabBotFile({ scopes, file_id }))?.id) return true;
const elsewhere = await grabBotFileScope({ file_id });
if (!elsewhere || !(await userReachesFileScope({ ...elsewhere, user_id }))) return false;
return Boolean((await grabBotFile({ scopes: [elsewhere], file_id }))?.id);
}
/**
* A run of the bot's in this session, a job it handed over from here, or
* a room it asked from here, still open: its result is still to come.
*/
async function hasOpenWork({ bot_id, session_id }: { bot_id: number | string; session_id: number | string }) {
const jobs = await BunSQLite.sql<{ id: number }>({
sql: `SELECT id FROM bots_queue
WHERE status IN ('pending', 'processing') AND kind = 'task'
AND ((bot_id = ? AND session_id = ?) OR requested_by_session_id = ?)
LIMIT 1`,
values: [Number(bot_id), Number(session_id), Number(session_id)],
});
if (jobs.payload?.[0]) return true;
const rooms = await BunSQLite.sql<{ id: number }>({
sql: `SELECT id FROM chatrooms WHERE status = 'open' AND requester_bot_id = ? AND origin_session_id = ? LIMIT 1`,
values: [Number(bot_id), Number(session_id)],
});
return Boolean(rooms.payload?.[0]);
}
+18 -3
View File
@@ -53,6 +53,7 @@ import grabMessageRefNames from "@/src/functions/backend/db/bots/grab-message-re
import withTakeOverRefs from "./with-take-over-refs";
import stripAppRecords from "@/src/utils/strip-app-records";
import hasUnansweredMessage from "./has-unanswered-message";
import reviewBotReply from "./review-bot-reply";
import grabAnsweredMessageId from "@/src/functions/backend/db/bots-queue/grab-answered-message-id";
import markReplyAnswered from "@/src/functions/backend/db/bots-queue/mark-reply-answered";
import sendMessageTool from "@/src/harness/tools/bot/send-message-tool";
@@ -85,7 +86,9 @@ type Params = BotJobContext & {
* that's separate can be acknowledged at once (`send_message`) and done
* after the current work. The job records the newest
* one it read (`markReplyAnswered`). Finishes silently when an earlier
* reply already read everything (`hasUnansweredMessage`).
* reply already read everything (`hasUnansweredMessage`). An answer naming
* files or tasks that don't exist, or saying work is under way when none
* is, is written again once (`reviewBotReply`).
*/
export default async function runBotReply({
bot,
@@ -105,6 +108,7 @@ export default async function runBotReply({
const history = await grabBotMessages({
session_id,
limit: AppData.BotReplyHistoryMessages,
user_id,
});
const answered_id = await grabAnsweredMessageId({ session_id });
@@ -243,6 +247,10 @@ export default async function runBotReply({
* workspace's admin.
*/
const powers = await grabBotRunPowers({ bot_id: bot.id, workspace_id });
/**
* A chatroom's turn is a reply too, and nobody follows that.
*/
const attended = !(await isHiddenSession({ session_id }));
let led: WorkspaceAdminTools | null = null;
const tools = await grabBotChatTools({
@@ -253,6 +261,7 @@ export default async function runBotReply({
session_id,
workspace_id,
scopes,
attended,
message_id: job.message_id || undefined,
onTakeOver: ({ ref }) => take_overs.push(ref),
onPropose: ({ ref }) => proposals.push(ref),
@@ -279,9 +288,9 @@ export default async function runBotReply({
/**
* The user's own browsers, so a bot can browse from the chat with no
* computer. A room's turn is a reply too, and nobody follows that.
* computer.
*/
const browser_run_kind = (await isHiddenSession({ session_id })) ? "unattended" : "attended";
const browser_run_kind = attended ? "attended" : "unattended";
const browsers = await openBotBrowsers({
user_id,
bot_id: bot.id,
@@ -422,6 +431,12 @@ export default async function runBotReply({
signal,
onStep: report,
incoming,
/**
* Files, tasks and work the answer names are checked against
* the app's record before it goes out.
*/
review: ({ text, tool_uses }) =>
reviewBotReply({ text, tool_uses, bot_id: bot.id!, user_id, session_id, scopes }),
});
if (job.id && answering_id) {
+12 -1
View File
@@ -322,11 +322,22 @@ export default async function runBotTask({
taken: [...tools, ...extensions.tools, ...browsers.tools, ...skills.tools].map((tool) => tool.name),
});
/**
* The install's limit, or less when the brief's writer set a
* budget (`start_task` `max_steps`).
*/
const install_steps = await grabHarnessMaxToolSteps();
const budget = Math.floor(Number(params.max_steps) || 0);
const max_steps = budget > 0 ? Math.min(budget, install_steps) : install_steps;
const result = await runTextLoop({
system: [
prompt,
carry_over,
TaskRunNote,
budget > 0
? `This run has at most ${max_steps} steps (model turns), set when it was queued. Plan for that: 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 : "",
@@ -382,7 +393,7 @@ export default async function runBotTask({
},
],
tools: [...tools, ...extensions.tools, ...browsers.tools, ...skills.tools, ...knowledge.tools],
max_steps: await grabHarnessMaxToolSteps(),
max_steps,
bot_id: bot.id,
workspace_id,
signal,
+4 -7
View File
@@ -1,7 +1,7 @@
import Img from "@moduletrace/twui/layout/Img";
import Stack from "@moduletrace/twui/layout/Stack";
import type { FilePreviewKind } from "@/src/utils/file-preview-kind";
import FilePreviewNotice from "./file-preview-notice";
import ImageViewer from "./image-viewer";
import FilePreviewText from "./file-preview-text";
type Props = {
@@ -13,7 +13,8 @@ type Props = {
/**
* The preview itself, by kind. Media the browser draws itself (images,
* PDFs, audio, video) load from the file's URL; text kinds are read into
* PDFs, audio, video) load from the file's URL, an image in a viewer with
* zoom and fits (`ImageViewer`); text kinds are read into
* the page (`FilePreviewText`). Nothing here runs the file: an SVG shows
* through `<img>`, which runs no script, and an HTML page in a frame
* sandboxed twice (the attribute here and the `sandbox` CSP the media
@@ -22,11 +23,7 @@ type Props = {
*/
export default function FilePreviewBody({ kind, name, url, size }: Props) {
if (kind == "image") {
return (
<Stack className="grow min-h-0 w-full items-center justify-center p-4 overflow-auto bg-sunken">
<Img src={url} alt={name} className="max-w-full max-h-full object-contain" />
</Stack>
);
return <ImageViewer url={url} name={name} />;
}
if (kind == "pdf") {
+8 -1
View File
@@ -1,5 +1,6 @@
import { useState, type ReactNode } from "react";
import Link from "@moduletrace/twui/layout/Link";
import type { FilePreviewItem } from "@/src/types";
import isPlainClick from "@/src/utils/is-plain-click";
import FilePreviewModal from "./file-preview-modal";
@@ -8,6 +9,11 @@ type Props = {
url: string;
media_type?: string | null;
size?: number;
/**
* The images it sits among (`imagePreviewGallery`), for Previous and
* Next in the preview.
*/
gallery?: FilePreviewItem[];
title?: string;
className?: string;
children: ReactNode;
@@ -18,7 +24,7 @@ type Props = {
* plain click. It stays a real link to the bytes, so a middle click or
* Ctrl/Cmd click still opens the file in a new tab.
*/
export default function FilePreviewLink({ name, url, media_type, size, title, className, children }: Props) {
export default function FilePreviewLink({ name, url, media_type, size, gallery, title, className, children }: Props) {
const [open, setOpen] = useState(false);
return (
@@ -44,6 +50,7 @@ export default function FilePreviewLink({ name, url, media_type, size, title, cl
url={url}
media_type={media_type}
size={size}
gallery={gallery}
onClose={() => setOpen(false)}
/>
) : null}
@@ -1,3 +1,4 @@
import { useMemo } from "react";
import Markdown, { type Components } from "react-markdown";
import remarkGfm from "remark-gfm";
import { twMerge } from "tailwind-merge";
@@ -17,11 +18,12 @@ const RemarkPlugins = [remarkGfm];
const HeadingClassName = "my-0! tracking-normal! font-bold text-ink";
/**
* A message's markdown elements, with headings sized for a document
* rather than a chat line.
* Headings sized for a document rather than a chat line, laid over a
* message's markdown elements when the preview renders. Not merged here:
* the message elements reach this file again through their file chips, so
* at load time they may not exist yet.
*/
const DocumentComponents: Components = {
...MessageMarkdownComponents,
const DocumentHeadings: Components = {
h1: ({ children }) => <H2 className={twMerge(HeadingClassName, "text-2xl! leading-8! mt-2!")}>{children}</H2>,
h2: ({ children }) => <H3 className={twMerge(HeadingClassName, "text-xl! leading-7! mt-2!")}>{children}</H3>,
h3: ({ children }) => <H4 className={twMerge(HeadingClassName, "text-[17px]! leading-6! mt-1!")}>{children}</H4>,
@@ -35,10 +37,12 @@ const DocumentComponents: Components = {
* bot's messages (raw HTML never rendered), in a readable column.
*/
export default function FilePreviewMarkdown({ text }: Props) {
const components = useMemo<Components>(() => ({ ...MessageMarkdownComponents, ...DocumentHeadings }), []);
return (
<Stack className="grow min-h-0 w-full overflow-auto items-center">
<Stack className="w-full max-w-[760px] gap-3! items-stretch px-6 py-5">
<Markdown remarkPlugins={RemarkPlugins} components={DocumentComponents}>
<Markdown remarkPlugins={RemarkPlugins} components={components}>
{text}
</Markdown>
</Stack>
+42 -7
View File
@@ -1,3 +1,4 @@
import { useState } from "react";
import Modal from "@moduletrace/twui/elements/Modal";
import H2 from "@moduletrace/twui/layout/H2";
import Link from "@moduletrace/twui/layout/Link";
@@ -5,15 +6,27 @@ import Row from "@moduletrace/twui/layout/Row";
import Span from "@moduletrace/twui/layout/Span";
import Stack from "@moduletrace/twui/layout/Stack";
import { Download, SquareArrowOutUpRight } from "lucide-react";
import useGalleryKeys from "@/src/hooks/use-gallery-keys";
import usePreloadImages from "@/src/hooks/use-preload-images";
import useTopModalEscape from "@/src/hooks/use-top-modal-escape";
import type { FilePreviewItem } from "@/src/types";
import filePreviewKind from "@/src/utils/file-preview-kind";
import formatBytes from "@/src/utils/format-bytes";
import galleryIndex from "@/src/utils/gallery-index";
import FilePreviewBody from "./file-preview-body";
import FilePreviewStepper from "./file-preview-stepper";
type Props = {
name: string;
url: string;
media_type?: string | null;
size?: number;
/**
* The images it was opened among (a folder's, a message's). When the
* file is one of them, Previous and Next (and the arrow keys) step
* through them without closing the preview.
*/
gallery?: FilePreviewItem[];
onClose: () => void;
};
@@ -24,16 +37,29 @@ const ActionClassName =
* A file over the page: markdown rendered, a CSV as a table, an image,
* PDF, audio or video in place, other text as code, with ways to download
* it or open it in a new tab. A file it can't show offers those only.
* Opened from a gallery, it steps through its images; each one opens fresh
* (fitted, scrolled to the top), and its neighbours load ahead.
*/
export default function FilePreviewModal({
name,
url,
media_type,
size,
onClose,
}: Props) {
export default function FilePreviewModal({ gallery, onClose, ...opened }: Props) {
const [index, set_index] = useState(() => galleryIndex({ gallery, url: opened.url }));
const stepping = Boolean(gallery && index >= 0 && gallery.length > 1);
const shown: FilePreviewItem = (stepping && gallery?.[index]) || opened;
const { name, url, media_type, size } = shown;
const kind = filePreviewKind({ name, media_type });
const base_name = name.split("/").pop() || name;
const count = gallery?.length || 0;
const step = ({ by }: { by: number }) =>
set_index((current) => Math.min(count - 1, Math.max(0, current + by)));
useTopModalEscape({ onClose });
useGalleryKeys({
enabled: stepping,
onPrevious: () => step({ by: -1 }),
onNext: () => step({ by: 1 }),
});
usePreloadImages({
urls: stepping ? [gallery?.[index + 1]?.url || "", gallery?.[index - 1]?.url || ""] : [],
});
return (
<Modal
@@ -57,6 +83,14 @@ export default function FilePreviewModal({
</Span>
) : null}
</Stack>
{stepping ? (
<FilePreviewStepper
index={index}
count={count}
onPrevious={() => step({ by: -1 })}
onNext={() => step({ by: 1 })}
/>
) : null}
<Link
href={url}
download={base_name}
@@ -78,6 +112,7 @@ export default function FilePreviewModal({
</Link>
</Row>
<FilePreviewBody
key={url}
kind={kind}
name={base_name}
url={url}
@@ -0,0 +1,41 @@
import Row from "@moduletrace/twui/layout/Row";
import Span from "@moduletrace/twui/layout/Span";
import { ChevronLeft, ChevronRight } from "lucide-react";
import RowIconButton from "./row-icon-button";
type Props = {
/**
* The shown file's place in the gallery, from 0.
*/
index: number;
count: number;
onPrevious: () => void;
onNext: () => void;
};
/**
* Previous and Next through a preview's gallery (the images of a folder or
* a message), with where the shown one stands: "3 of 12". The arrow keys
* do the same.
*/
export default function FilePreviewStepper({ index, count, onPrevious, onNext }: Props) {
return (
<Row className="shrink-0 gap-0! flex-nowrap items-center">
<RowIconButton
icon={ChevronLeft}
title="Previous image (Left arrow)"
disabled={index <= 0}
onClick={onPrevious}
/>
<Span className="min-w-16 text-center text-[13px] leading-[18px] tabular-nums text-ink-secondary">
{`${index + 1} of ${count}`}
</Span>
<RowIconButton
icon={ChevronRight}
title="Next image (Right arrow)"
disabled={index >= count - 1}
onClick={onNext}
/>
</Row>
);
}
@@ -5,6 +5,8 @@ import FilePreviewBody from "./file-preview-body";
import FilePreviewLink from "./file-preview-link";
import FilePreviewMarkdown from "./file-preview-markdown";
import FilePreviewTable from "./file-preview-table";
import FilePreviewStepper from "./file-preview-stepper";
import FolderPreviewLink from "./folder-preview-link";
test("a markdown file renders as a document, raw HTML left out", () => {
const html = renderToString(
@@ -51,3 +53,36 @@ test("a file link stays a real link to the bytes until clicked", () => {
expect(html).toContain('href="/media/9"');
expect(html).toContain("Preview report.md");
});
test("an image opens in the viewer, with its zoom and fit controls", () => {
const html = renderToString(<FilePreviewBody kind="image" name="page.png" url="/media/5" />);
expect(html).toContain('src="/media/5"');
expect(html).toContain("Zoom in (+)");
expect(html).toContain("Zoom out (-)");
expect(html).toContain("Fit width");
expect(html).toContain("Actual size");
});
test("a folder link stays a real link to the files browser until clicked", () => {
const html = renderToString(
<FolderPreviewLink spec={{ volume: "bots", owner_id: 3 }} path="reports" href="/admin/files?volume=bots&owner=3&path=reports" title="Open reports">
reports
</FolderPreviewLink>,
);
expect(html).toContain('href="/admin/files?volume=bots&amp;owner=3&amp;path=reports"');
expect(html).toContain("Open reports");
});
test("a gallery's stepper says where the image stands and stops at the ends", () => {
const first = renderToString(<FilePreviewStepper index={0} count={3} onPrevious={() => {}} onNext={() => {}} />);
const last = renderToString(<FilePreviewStepper index={2} count={3} onPrevious={() => {}} onNext={() => {}} />);
expect(first).toContain("1 of 3");
expect(first).toContain("Previous image");
expect(first).toContain("Next image");
expect(last).toContain("3 of 3");
expect((first.match(/disabled=""/g) || []).length).toBe(1);
expect((last.match(/disabled=""/g) || []).length).toBe(1);
});
@@ -0,0 +1,45 @@
import { useState, type ReactNode } from "react";
import Link from "@moduletrace/twui/layout/Link";
import isPlainClick from "@/src/utils/is-plain-click";
import type { StorageSpec } from "@/src/utils/storage-volumes";
import FolderPreviewModal from "./folder-preview-modal";
type Props = {
spec: StorageSpec;
path: string;
/**
* The folder in the files browser, where a modified click goes.
*/
href: string;
title?: string;
className?: string;
children: ReactNode;
};
/**
* A link to a folder that opens it over the page (`FolderPreviewModal`) on
* a plain click. It stays a real link to the files browser, so a middle
* click or Ctrl/Cmd click still opens the folder there in a new tab.
*/
export default function FolderPreviewLink({ spec, path, href, title, className, children }: Props) {
const [open, setOpen] = useState(false);
return (
<>
<Link
href={href}
title={title}
onClick={(event) => {
if (!isPlainClick({ event })) return;
event.preventDefault();
setOpen(true);
}}
className={className}
>
{children}
</Link>
{open ? <FolderPreviewModal spec={spec} path={path} onClose={() => setOpen(false)} /> : null}
</>
);
}
@@ -0,0 +1,107 @@
import { useMemo, useState } from "react";
import Modal from "@moduletrace/twui/elements/Modal";
import H2 from "@moduletrace/twui/layout/H2";
import Link from "@moduletrace/twui/layout/Link";
import Row from "@moduletrace/twui/layout/Row";
import Span from "@moduletrace/twui/layout/Span";
import Stack from "@moduletrace/twui/layout/Stack";
import { SquareArrowOutUpRight } from "lucide-react";
import useDebouncedValue from "@/src/hooks/use-debounced-value";
import useStorageFolder from "@/src/hooks/use-storage-folder";
import useTopModalEscape from "@/src/hooks/use-top-modal-escape";
import { emptyFolderText, folderSummary } from "@/src/utils/folder-text";
import imagePreviewGallery from "@/src/utils/image-preview-gallery";
import { storagePathName, storageSpecHref, type StorageSpec } from "@/src/utils/storage-volumes";
import FilesBreadcrumbRow from "./files-breadcrumb-row";
import FilesSearchInput from "./files-search-input";
import StorageEntryRow from "./storage-entry-row";
type Props = {
spec: StorageSpec;
/**
* The folder it opens on, inside the volume (empty at the top).
*/
path: string;
onClose: () => void;
};
/**
* A folder over the page, as the files browser shows it: its entries,
* the trail back up and a search by name. A folder inside opens in place,
* a file opens in its own preview over this one (an image stepping
* through the folder's other images), and "Open in Files" goes
* to the same folder in the files browser. The listing loads through the
* files browser's API, so the same access rules hold.
*/
export default function FolderPreviewModal({ spec, path: start_path, onClose }: Props) {
const [path, set_path] = useState(start_path);
const [search, set_search] = useState("");
const query = useDebouncedValue({ value: search.trim() });
const { folder, loading, error } = useStorageFolder({ spec, path, search: query });
const name = folder?.breadcrumbs.at(-1)?.name || folder?.label || storagePathName({ volume: spec.volume, path });
const gallery = useMemo(
() => imagePreviewGallery({ items: (folder?.entries || []).map((entry) => ({ ...entry, url: entry.url || "" })) }),
[folder],
);
useTopModalEscape({ onClose });
const openFolder = (next_path: string) => {
set_path(next_path);
set_search("");
};
return (
<Modal
open
setOpen={(next_open) => {
if (!next_open) onClose();
}}
className="max-w-3xl! w-[95vw] h-[85vh] p-0 bg-paper flex flex-col overflow-hidden"
>
<Row className="w-full gap-3! flex-nowrap items-center pl-5 pr-14 py-3 border-0 border-b border-solid border-hairline">
<Stack className="min-w-0 grow gap-0! items-start">
<H2
title={path || name}
className="text-base! leading-6! tracking-normal! font-bold text-ink truncate w-full"
>
{name}
</H2>
<Span className="text-[13px] leading-[18px] text-ink-secondary">
{folderSummary({ folder })}
</Span>
</Stack>
<Link
href={storageSpecHref({ spec, path })}
title="Open this folder in Files"
className="shrink-0 inline-flex items-center gap-1.5 px-2 py-1.5 text-[13px] leading-[18px] text-ink-secondary hover:text-ink rounded-default hover:bg-sunken no-underline"
>
<SquareArrowOutUpRight size={16} aria-hidden />
<Span className="hidden sm:inline">Open in Files</Span>
</Link>
</Row>
<Stack className="w-full gap-0! items-stretch px-5">
<FilesBreadcrumbRow crumbs={folder?.breadcrumbs || []} onOpenFolder={openFolder} />
<FilesSearchInput value={search} onChange={set_search} />
</Stack>
<Stack className="grow min-h-0 w-full mt-2 gap-0! items-stretch overflow-y-auto px-5 pb-4">
{folder?.entries.length ? (
folder.entries.map((entry) => (
<StorageEntryRow
key={entry.path}
entry={entry}
selected={entry.kind == "folder" && entry.path == path}
gallery={gallery}
onOpenFolder={openFolder}
/>
))
) : (
<Span className="py-8 text-[13px] leading-[18px] text-ink-secondary">
{emptyFolderText({ folder, search, loading, error })}
</Span>
)}
</Stack>
</Modal>
);
}
+13 -5
View File
@@ -3,6 +3,7 @@ import Stack from "@moduletrace/twui/layout/Stack";
import { useContext, useMemo, useState } from "react";
import { AppContext } from "@/src/pages/__root";
import { CrewBotsContext } from "@/src/pages/admin/bots/[bot_id]/(data)/crew-bots-context";
import { CrewWorkspacesContext } from "@/src/pages/admin/bots/[bot_id]/(data)/crew-workspaces-context";
import { FilePlaceContext } from "@/src/pages/admin/bots/[bot_id]/(data)/file-place-context";
import SettingsList from "@/src/pages/admin/settings/(partials)/settings-list";
import type { BotHookEventStatus } from "@/src/dict/bot-hook-dict";
@@ -26,6 +27,11 @@ type Props = {
*/
export default function HookCalls({ hook_id, bot_id, workspace_id }: Props) {
const { pageProps } = useContext(AppContext);
/**
* A conversation's live workspaces when opened in one, else the page's.
*/
const outer_workspaces = useContext(CrewWorkspacesContext);
const workspaces = outer_workspaces.length ? outer_workspaces : pageProps?.workspaces || [];
const [query, set_query] = useState("");
const [status, set_status] = useState<BotHookEventStatus | "">("");
const { events, loading, error, more, loadOlder } = useHookEvents({ hook_id, query, status });
@@ -40,11 +46,13 @@ export default function HookCalls({ hook_id, bot_id, workspace_id }: Props) {
empty={loading ? "Loading calls..." : error || (filtered ? "No calls match." : "No calls yet.")}
>
<CrewBotsContext.Provider value={pageProps?.bots || []}>
<FilePlaceContext.Provider value={place}>
{events.map((event) => (
<HookEventRow key={`${event.id}-${event.status}`} event={event} />
))}
</FilePlaceContext.Provider>
<CrewWorkspacesContext.Provider value={workspaces}>
<FilePlaceContext.Provider value={place}>
{events.map((event) => (
<HookEventRow key={`${event.id}-${event.status}`} event={event} />
))}
</FilePlaceContext.Provider>
</CrewWorkspacesContext.Provider>
</CrewBotsContext.Provider>
</SettingsList>
{more && events.length ? (
@@ -0,0 +1,44 @@
import Button from "@moduletrace/twui/layout/Button";
import Span from "@moduletrace/twui/layout/Span";
import type { LucideIcon } from "lucide-react";
import { twMerge } from "tailwind-merge";
export type ImageViewerTool = {
id: string;
icon: LucideIcon;
/**
* What it does, with its key, for the tooltip and screen readers.
*/
title: string;
/**
* Shown beside the icon on wider screens; icon only without one.
*/
label?: string;
pressed?: boolean;
disabled?: boolean;
onClick: () => void;
};
/**
* One control on the image preview's toolbar: a zoom, or a preset that
* shows as pressed while it is the one in use.
*/
export default function ImageViewerToolButton({ icon: Icon, title, label, pressed, disabled, onClick }: ImageViewerTool) {
return (
<Button
type="button"
variant="ghost"
color="gray"
size="small"
title={title}
aria-label={title}
aria-pressed={pressed}
disabled={disabled}
onClick={onClick}
className={twMerge("gap-1.5! text-ink-secondary hover:text-ink", pressed && "bg-ink/5 text-ink")}
>
<Icon size={16} aria-hidden />
{label ? <Span className="hidden sm:inline text-[13px] leading-[18px]">{label}</Span> : null}
</Button>
);
}
@@ -0,0 +1,89 @@
import Row from "@moduletrace/twui/layout/Row";
import Span from "@moduletrace/twui/layout/Span";
import { MoveHorizontal, Scan, Shrink, ZoomIn, ZoomOut } from "lucide-react";
import {
ImageViewerMaxScale,
ImageViewerMinScale,
type ImageViewerMode,
} from "@/src/dict/image-viewer-dict";
import ImageViewerToolButton, { type ImageViewerTool } from "./image-viewer-tool-button";
type Props = {
mode: ImageViewerMode;
scale: number;
natural: { width: number; height: number } | null;
onZoom: (direction: "in" | "out") => void;
onChoose: (mode: Exclude<ImageViewerMode, "custom">) => void;
};
/**
* The image preview's controls: zoom out and in around the zoom level,
* the presets (whole, the frame's width, actual size), and the picture's
* own size in pixels.
*/
export default function ImageViewerToolbar({ mode, scale, natural, onZoom, onChoose }: Props) {
const loaded = Boolean(natural);
const zoom_out: ImageViewerTool = {
id: "out",
icon: ZoomOut,
title: "Zoom out (-)",
disabled: !loaded || scale <= ImageViewerMinScale,
onClick: () => onZoom("out"),
};
const zoom_in: ImageViewerTool = {
id: "in",
icon: ZoomIn,
title: "Zoom in (+)",
disabled: !loaded || scale >= ImageViewerMaxScale,
onClick: () => onZoom("in"),
};
const preset_tools: ImageViewerTool[] = [
{
id: "fit",
icon: Shrink,
title: "Show the whole image (0)",
label: "Fit",
pressed: mode == "fit",
disabled: !loaded,
onClick: () => onChoose("fit"),
},
{
id: "width",
icon: MoveHorizontal,
title: "Fit the width and scroll down (W)",
label: "Fit width",
pressed: mode == "width",
disabled: !loaded,
onClick: () => onChoose("width"),
},
{
id: "actual",
icon: Scan,
title: "Actual size, one image pixel per screen pixel (1)",
label: "Actual size",
pressed: mode == "actual",
disabled: !loaded,
onClick: () => onChoose("actual"),
},
];
return (
<Row className="w-full gap-1! flex-wrap items-center px-3 py-1.5 border-0 border-b border-solid border-hairline bg-paper">
<ImageViewerToolButton {...zoom_out} />
<Span className="min-w-12 text-center text-[13px] leading-[18px] font-bold tabular-nums text-ink">
{loaded ? `${Math.round(scale * 100)}%` : "..."}
</Span>
<ImageViewerToolButton {...zoom_in} />
<Span className="inline-block mx-1 h-5 w-px bg-hairline" aria-hidden />
{preset_tools.map((tool) => (
<ImageViewerToolButton key={tool.id} {...tool} />
))}
{natural ? (
<Span className="ml-auto pl-2 text-[12px] leading-4 tabular-nums text-ink-secondary">
{`${natural.width} x ${natural.height} px`}
<Span className="hidden md:inline">{" · Ctrl + scroll to zoom, drag to move"}</Span>
</Span>
) : null}
</Row>
);
}
+67
View File
@@ -0,0 +1,67 @@
import Img from "@moduletrace/twui/layout/Img";
import Stack from "@moduletrace/twui/layout/Stack";
import type { RefObject } from "react";
import { twMerge } from "tailwind-merge";
import useImageViewer from "@/src/hooks/use-image-viewer";
import useImageViewerGestures from "@/src/hooks/use-image-viewer-gestures";
import FilePreviewNotice from "./file-preview-notice";
import ImageViewerToolbar from "./image-viewer-toolbar";
type Props = {
url: string;
name: string;
};
/**
* An image in the file preview, to inspect rather than glance at: zoom
* (buttons, keys, Ctrl/Cmd + wheel or a pinch at the pointer), fit whole,
* fit the width (a full-page screenshot opens that way and scrolls down),
* actual size, double click to zoom into a spot, drag to move around.
* The picture is sized with its `width` attribute, so no style is set,
* and centred with auto margins, which (unlike flex centring) never push
* the top of a picture taller than the frame out of reach.
*/
export default function ImageViewer({ url, name }: Props) {
const viewer = useImageViewer();
const { dragging, pointerHandlers } = useImageViewerGestures(viewer);
const width = viewer.natural ? Math.max(1, Math.floor(viewer.natural.width * viewer.scale)) : undefined;
return (
<Stack className="grow min-h-0 w-full gap-0! items-stretch">
<ImageViewerToolbar
mode={viewer.mode}
scale={viewer.scale}
natural={viewer.natural}
onZoom={(direction) => viewer.zoom({ direction })}
onChoose={(mode) => viewer.choose({ mode })}
/>
<Stack
componentRef={viewer.container_ref as RefObject<HTMLDivElement>}
{...pointerHandlers}
onDoubleClick={(event) => viewer.toggle({ point: { x: event.clientX, y: event.clientY } })}
className={twMerge(
"relative grow min-h-0 w-full gap-0! items-stretch overflow-auto overscroll-contain bg-sunken select-none",
viewer.scale < 1 && "cursor-zoom-in",
dragging && "cursor-grabbing",
)}
>
<Stack className="shrink-0 w-max min-w-full min-h-full gap-0! items-start p-4">
<Img
ref={viewer.image_ref}
src={url}
alt={name}
loading="eager"
draggable={false}
width={width}
onLoad={viewer.onImageLoad}
imgErrComp={<FilePreviewNotice message="This image couldn't be loaded. Download it to open it." />}
className={twMerge(
"block shrink-0 m-auto h-auto object-contain",
width ? "max-w-none max-h-none" : "max-w-full max-h-full",
)}
/>
</Stack>
</Stack>
</Stack>
);
}
@@ -4,7 +4,7 @@ import Span from "@moduletrace/twui/layout/Span";
import Stack from "@moduletrace/twui/layout/Stack";
import { twMerge } from "tailwind-merge";
import { FolderOpen } from "lucide-react";
import type { MediaType, StorageEntry } from "@/src/types";
import type { FilePreviewItem, MediaType, StorageEntry } from "@/src/types";
import formatBytes from "@/src/utils/format-bytes";
import relativeTime from "@/src/utils/relative-time";
import AttachmentIcon from "@/src/pages/admin/bots/[bot_id]/(partials)/attachment-icon";
@@ -13,6 +13,10 @@ import FilePreviewLink from "@/src/components/general/file-preview-link";
type Props = {
entry: StorageEntry;
selected?: boolean;
/**
* The folder's images, so an image's preview steps through the rest.
*/
gallery?: FilePreviewItem[];
onOpenFolder: (path: string) => void;
};
@@ -21,7 +25,7 @@ type Props = {
* file preview (its own media record when it is one of the bot's files, else
* the browser's streaming route).
*/
export default function StorageEntryRow({ entry, selected, onOpenFolder }: Props) {
export default function StorageEntryRow({ entry, selected, gallery, onOpenFolder }: Props) {
const is_folder = entry.kind == "folder";
return (
@@ -57,6 +61,7 @@ export default function StorageEntryRow({ entry, selected, onOpenFolder }: Props
url={entry.url || ""}
media_type={entry.media_type}
size={entry.size}
gallery={gallery}
className="text-[13px] font-bold leading-5 text-ink break-words hover:opacity-80"
>
{entry.name}
+9 -3
View File
@@ -11,14 +11,19 @@ import TaskDetailPanel from "./task-detail-panel";
type Props = {
/**
* The list row clicked; open while set. Its notes and files load when
* it opens, so the list stays small.
* it opens, so the list stays small. A task named in a message gives
* its id alone.
*/
task?: TaskWithNames | null;
task?: (Partial<TaskWithNames> & { id?: TaskWithNames["id"] }) | null;
/**
* A crew manager can change it, file onto it and delete it.
*/
can_manage?: boolean;
onClose: () => void;
/**
* Its details came in.
*/
onLoaded?: (params: { task: TaskDetail }) => void;
onChanged: (params: { task: TaskDetail; msg?: string }) => void;
onDeleted: (params: { task_id: number }) => void;
};
@@ -27,7 +32,7 @@ type Props = {
* A task opened from a list in a modal of its own: everything about it, and
* for a crew manager its edit, hand-over, files and delete.
*/
export default function TaskDetailModal({ task, can_manage, onClose, onChanged, onDeleted }: Props) {
export default function TaskDetailModal({ task, can_manage, onClose, onLoaded, onChanged, onDeleted }: Props) {
const [detail, set_detail] = useState<TaskDetail | null>(null);
const [error, set_error] = useState<string>();
const task_id = task?.id ? Number(task.id) : 0;
@@ -53,6 +58,7 @@ export default function TaskDetailModal({ task, can_manage, onClose, onChanged,
}
set_detail(res.singleRes);
onLoaded?.({ task: res.singleRes });
});
return () => {
+2 -1
View File
@@ -14,6 +14,7 @@ import TaskStatusMoves from "@/src/components/general/task-status-moves";
import BotAvatar from "@/src/components/general/bot-avatar";
import TaskFactRow from "@/src/components/general/task-fact-row";
import TaskNoteRow from "@/src/components/general/task-note-row";
import TaskMarkdown from "@/src/components/general/task-markdown";
import type { BotFace } from "@/src/dict/bot-dict";
import { AppContext } from "@/src/pages/__root";
import botStoneProps from "@/src/utils/bot-stone-props";
@@ -306,7 +307,7 @@ export default function TaskDetailPanel({ task, can_manage, onChanged, onDeleted
) : null}
{task.description ? (
<Span className="whitespace-pre-wrap text-[13px] leading-[19px] text-ink">{task.description}</Span>
<TaskMarkdown text={task.description} />
) : null}
<Stack className="w-full gap-1! items-stretch">
@@ -0,0 +1,38 @@
import { describe, expect, test } from "bun:test";
import { renderToString } from "react-dom/server";
import TaskMarkdown from "./task-markdown";
describe("TaskMarkdown", () => {
test("renders the markdown, not as written", () => {
const html = renderToString(<TaskMarkdown text={"## Steps\n\n- **Check** the [docs](https://example.com)"} />);
expect(html).not.toContain("## Steps");
expect(html).not.toContain("**Check**");
expect(html).toContain("<li");
expect(html).toContain("Check");
});
test("opens links in a new tab, bare ones too", () => {
const html = renderToString(<TaskMarkdown text={"See [the docs](https://example.com) or https://example.org"} />);
expect(html).toContain('href="https://example.com"');
expect(html).toContain('href="https://example.org"');
expect(html.match(/target="_blank"/g)?.length).toBe(2);
expect(html).toContain("noopener");
});
test("shows refs as chips", () => {
const html = renderToString(<TaskMarkdown text={"Ask [bot:2] about [task:20]."} />);
expect(html).not.toContain("[bot:2]");
expect(html).toContain("bot 2");
expect(html).toContain("Task 20");
});
test("never renders raw HTML", () => {
const html = renderToString(<TaskMarkdown text={"<script>alert(1)</script> <b>hi</b>"} />);
expect(html).not.toContain("<script>");
expect(html).not.toContain("<b>");
});
});
+48
View File
@@ -0,0 +1,48 @@
import { useContext } from "react";
import Markdown from "react-markdown";
import remarkGfm from "remark-gfm";
import { twMerge } from "tailwind-merge";
import Stack from "@moduletrace/twui/layout/Stack";
import { AppContext } from "@/src/pages/__root";
import { CrewBotsContext } from "@/src/pages/admin/bots/[bot_id]/(data)/crew-bots-context";
import { CrewWorkspacesContext } from "@/src/pages/admin/bots/[bot_id]/(data)/crew-workspaces-context";
import { MessageMarkdownComponents } from "@/src/pages/admin/bots/[bot_id]/(data)/message-markdown-components";
import linkComputerRefs from "@/src/utils/link-computer-refs";
/**
* Kept module-level: a new array on every render makes `react-markdown`
* parse the text again.
*/
const RemarkPlugins = [remarkGfm];
type Props = {
text: string;
className?: string;
};
/**
* A task's description or a note on it, rendered like a bot's message
* (raw HTML never rendered, links in a new tab, refs as their chips). The
* crew the chips link to is the page's own when no conversation around it
* gives one. The message elements reach this file again through the task
* chip, so they're read when it renders, never at load.
*/
export default function TaskMarkdown({ text, className }: Props) {
const { pageProps } = useContext(AppContext);
const crew_bots = useContext(CrewBotsContext);
const crew_workspaces = useContext(CrewWorkspacesContext);
const bots = crew_bots.length ? crew_bots : pageProps?.workspace_bots || pageProps?.bots || [];
const workspaces = crew_workspaces.length ? crew_workspaces : pageProps?.workspaces || [];
return (
<CrewBotsContext.Provider value={bots}>
<CrewWorkspacesContext.Provider value={workspaces}>
<Stack className={twMerge("w-full min-w-0 gap-2! items-stretch", className)}>
<Markdown remarkPlugins={RemarkPlugins} components={MessageMarkdownComponents}>
{linkComputerRefs({ text })}
</Markdown>
</Stack>
</CrewWorkspacesContext.Provider>
</CrewBotsContext.Provider>
);
}
+3 -2
View File
@@ -3,6 +3,7 @@ import Span from "@moduletrace/twui/layout/Span";
import Stack from "@moduletrace/twui/layout/Stack";
import type { TaskNote } from "@/src/types";
import relativeTime from "@/src/utils/relative-time";
import TaskMarkdown from "./task-markdown";
type Props = {
note: TaskNote;
@@ -10,7 +11,7 @@ type Props = {
/**
* One note on an opened task: who wrote it (the user, or the bot by name),
* how long ago, and what it says.
* how long ago, and what it says (markdown, like a message).
*/
export default function TaskNoteRow({ note }: Props) {
const author = note.author == "user" ? "You" : note.bot_name || "Bot";
@@ -25,7 +26,7 @@ export default function TaskNoteRow({ note }: Props) {
</Span>
) : null}
</Row>
<Span className="whitespace-pre-wrap text-[13px] leading-[18px] text-ink">{note.text}</Span>
{note.text ? <TaskMarkdown text={note.text} /> : null}
</Stack>
);
}
+12 -3
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.2.0",
ComputerImage: "ghcr.io/moduletrace/cobble-computer:1.3.0",
ComputerContainerPrefix: `${SiteData["SiteSlug"]}-computer`,
/**
* Only a computer's workspace (`ComputerWorkspaceDir` in its
@@ -174,9 +174,12 @@ export const AppData = {
* (`migrateComputerLayout`), keeping its workspace and browser profile.
* `cobble-computer` moved every computer off the AIO sandbox;
* `cobble-computer-accounts` gave worker bots their own accounts (the
* container gets `NET_ADMIN` to keep them off its services).
* container gets `NET_ADMIN` to keep them off its services);
* `cobble-computer-homes` has workers work in their own home
* (`/home/cb-<bot>/workspace`, a link the agent keeps to their folder),
* which an older agent would make a folder that isn't kept.
*/
ComputerWorkspaceLayout: "cobble-computer-accounts",
ComputerWorkspaceLayout: "cobble-computer-homes",
ComputerUserUid: 1000,
ComputerUserGid: 1000,
/**
@@ -639,6 +642,12 @@ export const AppData = {
* reads it through `grabReplyMaxToolSteps`.
*/
BotReplyMaxToolSteps: 20,
/**
* From this many characters, a bot message whose run called no tools
* shows "No tools used" under it (`MessageNoToolsChip`): a long report
* with nothing behind it was made up, and the user acted on one.
*/
MessageNoToolsMinChars: 400,
/**
* Messages a chat reply may send while it works (`send_message`):
* acknowledging something the user wrote meanwhile, a heads-up. Its
+6 -3
View File
@@ -53,9 +53,10 @@ describe("harness prompts", () => {
dirs: computerRunDirs({ bot_id: 3, user_id: 7, workspace_id: 2 }),
});
expect(note).toContain("[folder:computer:8:bots/3/users/7/seo/coderank/raw]");
expect(note).toContain("/home/gem/workspace/bots/3/users/7");
expect(note).toContain("/home/gem/workspace/workspaces/2");
expect(note).toContain("[folder:computer:8:home/cb-3/workspace/users/7/seo/coderank/raw]");
expect(note).toContain("starts in /home/cb-3/workspace/users/7 (also ~ and $HOME)");
expect(note).toContain("/home/cb-3/workspace/workspaces/2: shared");
expect(note).toContain("only /home/cb-3/workspace and the browser's logins survive it (the rest of your account's home, /home/cb-3, doesn't)");
expect(note).toContain("request_install");
expect(note).not.toContain("sudo apt-get");
});
@@ -67,6 +68,8 @@ describe("harness prompts", () => {
});
expect(note).toContain("sudo apt-get");
expect(note).toContain("/home/gem/workspace/bots/1/users/7");
expect(note).toContain("only /home/gem/workspace and the browser's logins survive it. ");
expect(note).not.toContain("request_install");
});
+13 -7
View File
@@ -1,7 +1,8 @@
import { AppData } from "@/src/data/app-data";
import botRef from "@/src/utils/bot-ref";
import folderRef from "@/src/utils/folder-ref";
import { computerWorkspaceRelative, type ComputerRunDirs } from "@/src/utils/computer-work-dirs";
import computerWorkerAccount from "@/src/utils/computer-worker-account";
import type { ComputerRunDirs } from "@/src/utils/computer-work-dirs";
/**
* Prompts the helper harnesses send. The text model gets their output in
@@ -54,8 +55,10 @@ You are chatting with the user. Answer their latest messages directly and briefl
- When a message mixes both, answer the quick parts in this reply and start a task for the rest.
- When only the user can do something on a computer (log in, solve a captcha, enter a code), ask them to take over with ask_user_to_take_over and say exactly what to do. They'll tell you when they hand it back; then carry on.
- When the user tells you something worth keeping, save it with update_memory: about them in your memory of this user, never in your core memory, which every user you work for shares. When they correct how you work for everyone, update your instructions with update_instructions; a correction that's only their preference goes in your memory of them.
- An app record saying the user reacted to one of your messages is their feedback on it: 👍, ❤️ and 🎉 mean they liked it, 👎 that they didn't; 😂, 😮 and 😢 are how it made them feel, not a verdict. When reactions show a preference that lasts (length, format, tone, what to include or leave out), save it in your memory of this user with update_memory (scope "user", in a workspace too). One reaction to one answer isn't a preference yet, so don't save it, and don't save what your memory already says. Bring a reaction up only when it helps: after a 👎 on your last answer with no word about why, you can ask in one short question what to change.
- To add a worker to the crew, use create_bot once the user has asked for it or agreed, and add_bot_to_workspace to place it. A bot exists only when create_bot made it: never describe one as if it did, and never write it into a workspace's context.
- Never claim you did something you didn't do.
- Nothing wakes you when a run ends: its result is posted here, and that's all. So never promise to do something once a run finishes. Do it in this reply (renaming a task or logging a note with update_task needs no computer), or queue it now with start_task (with separate when another run of yours is open on that computer) and say it's queued.
- The user can mention a bot as [bot:ID] and a workspace as [workspace:ID]; a [Mentions: ...] line after their message says who and what those are. Write the same refs when you name them back.
- Documents, images and reports you make are files: save them with write_file, make_pdf or generate_image, and send one to the user with it ("attach"). When you name a file, write its [file:ID] ref, e.g. [file:12], so the user can open it. When you name a folder, write a folder ref instead, e.g. ${ownFolderRef({ bot_id })}: that opens the folder in Files and downloads nothing.
@@ -108,14 +111,16 @@ export const ComputerFilesNote = ({
can_import?: boolean;
}) => `# Files on the computer
You work only in your own folders on the computer, never elsewhere in it: every shell and file tool starts in ${dirs.cwd} (also ~), and a path outside your folders is refused.
You work only in your own folders on the computer, never elsewhere in it: every shell and file tool starts in ${dirs.cwd} (also ~ and $HOME), and a path outside your folders is refused.
- ${dirs.cwd}: this user's work. Everything for them goes here.
- ${dirs.bot_dir}: only what is the same for every user you work for (other users' folders in it are not yours).${
dirs.shared_dir ? `\n- ${dirs.shared_dir}: shared with every bot in this workspace.` : ""
}
- The browser downloads to its own folder: move what you download into your folder straight away.
- A computer can be restarted or rebuilt at any time, and only ${AppData.ComputerWorkspaceDir} and the browser's logins survive it. ${
- A computer can be restarted or rebuilt at any time, and only ${dirs.run_as ? dirs.bot_dir : AppData.ComputerWorkspaceDir} and the browser's logins survive it${
dirs.run_as ? ` (the rest of your account's home, ${computerWorkerAccount({ bot_id: dirs.run_as.bot_id }).home}, doesn't)` : ""
}. ${
dirs.run_as
? `You work as your own account, without sudo, and the browser can't open your folders' files (file: URLs): to look at a page you made, serve its folder on localhost (python3 -m http.server --bind 127.0.0.1, in the background) and open that. Python and Node packages you install yourself (pip install --user, npm install -g) go to ~/.local in this user's folder, so they stay. A system package (apt) needs the coordinator: in a task, ask with request_install, then end your run saying you're waiting for it; you're woken with the answer. System packages may be gone after a rebuild: check for one first (command -v) and ask again when it's missing.`
: `Programs you install (sudo apt-get install -y, pip, npm -g) may be gone afterwards: check for one first (command -v) and install it again when it's missing.`
@@ -123,7 +128,7 @@ You work only in your own folders on the computer, never elsewhere in it: every
What you make there (downloads, screenshots, a crawl, raw evidence, logs) is kept with the computer, not in your files, and it is not searchable.
- The user can open any of it: name a folder on the computer as a folder ref, its path from the computer's workspace (${AppData.ComputerWorkspaceDir}), e.g. ${folderRef({ volume: "computer", owner_id: computer_id, path: `${computerWorkspaceRelative({ absolute: dirs.cwd })}/seo/coderank/raw` })}. It opens that folder in Files, so it downloads nothing. Point at the folder holding the evidence they may want to see.
- The user can open any of it: name a folder on the computer as a folder ref with its full path as you see it, e.g. ${folderRef({ volume: "computer", owner_id: computer_id, path: `${dirs.cwd}/seo/coderank/raw` })}. It opens that folder in Files, so it downloads nothing. Point at the folder holding the evidence they may want to see.
${
can_import
? `- import_file copies a file or a folder off the computer into your own files, in one go, and the copy is searchable straight away. Import the finished work (the report, the spreadsheet, the final document), attach it when it is what they asked for, and name it with its [file:ID] ref.\n- The raw evidence can stay on the computer: import it only when the user needs it kept, or when the computer may be rebuilt.\n`
@@ -237,7 +242,7 @@ export const workspaceAdminsLine = ({ admins }: { admins: { id?: number | "" }[]
*/
export const TaskRunNote = `# Working on a task
You are working through a task on your own; the user isn't watching. Use your tools until the task is done, then answer with the report for the user: what you did, what you found, and anything left for them. End it with the next step you'd suggest, as a short question the user can say yes to. Keep the report short and in markdown. If you're blocked on something only the user can give you, stop and ask for it in the report. If they need to do it on the computer themselves (log in, a captcha, a code), call ask_user_to_take_over first.`;
You are working through a task on your own; the user isn't watching. Use your tools until the task is done, then answer with the report for the user: what you did, what you found, and anything left for them. End it with the next step you'd suggest, as a short question the user can say yes to. Keep the report short and in markdown. If you're blocked on something only the user can give you, stop and ask for it in the report. The same goes for being stuck: when several different tries at the same thing (a search, a page, a fix) leave you no closer, stop there and report what you tried and what you need, rather than spending the run on more of the same. If they need to do it on the computer themselves (log in, a captcha, a code), call ask_user_to_take_over first.`;
/**
* Added to every run: the shared to-do list, and how a bot keeps it
@@ -251,7 +256,8 @@ Tasks are the crew's to-do list. A task belongs to one bot, on its own list or i
- create_task adds one, with a brief: what to do, where, and what done looks like. Only add a task for work that will take more than this reply; never one for something you're doing now.
- update_task moves it along. Set doing when you start, blocked with a reason when only the user can unblock it, and done only once the work is verified (see the check note above). Add a note as you go: it's what the user reads on the task, so one short line per real step, not a play-by-play.
- On a workspace-wide task, read its log first (list_tasks with task_id) to see which bot did what and when, take a part nobody has done yet, and log each part you finish with update_task. Every note is recorded under your name and id, so the log is how the crew stays in step.
- A deliverable is a file: save it first with write_file, make_pdf or generate_image, then pass its [file:ID] ref in deliverable_file_ids, so the task carries what it produced.`;
- A deliverable is a file: save it first with write_file, make_pdf or generate_image, then pass its [file:ID] ref in deliverable_file_ids, so the task carries what it produced.
- When you name a task, write its [task:ID] ref, e.g. [task:12], so the user can open it. Only tasks from list_tasks or create_task have one; a run from start_task or delegate_task is not a task.`;
/**
* Added to a chat reply: when and how to bring pending tasks up, so the bot
@@ -261,7 +267,7 @@ export const TaskReminderNote = `# Mentioning pending tasks
You have tasks of your own to keep up with. When the message is an opening ("hello", "what's up"), or after you've answered and propose what's next, call list_tasks and look at what's open.
- If something is blocked on the user, or something open plainly connects to what they're asking, mention it in one short line with its status, at most ${AppData.TaskReminderDigestCount} tasks: "Still open: #12 send the signed form (blocked: you need to sign it), #14 recheck the invoices."
- If something is blocked on the user, or something open plainly connects to what they're asking, mention it in one short line with its status, at most ${AppData.TaskReminderDigestCount} tasks: "Still open: [task:12] send the signed form (blocked: you need to sign it), [task:14] recheck the invoices."
- Don't list everything, don't repeat the same reminder reply after reply, and skip it when the user is mid-task, winding down, or you've just asked them a question. A greeting is a good moment; every greeting is not.
- Never invent a task: name only what list_tasks returned.`;
+4
View File
@@ -173,6 +173,10 @@ export const BotMessageReactions = [
title: "Like",
value: "👍",
},
{
title: "Dislike",
value: "👎",
},
{
title: "Love",
value: "❤️",
+28
View File
@@ -0,0 +1,28 @@
/**
* How the image preview sizes a picture: `fit` shows it whole, `width`
* fills the frame's width and scrolls down (a full-page screenshot),
* `actual` is one image pixel per screen pixel, `custom` is wherever the
* user zoomed to. The fits never blow a small picture up past its own size.
*/
export const ImageViewerModes = ["fit", "width", "actual", "custom"] as const;
export type ImageViewerMode = (typeof ImageViewerModes)[number];
/**
* The stops the zoom buttons (and `+`/`-`) step through, from
* `ImageViewerMinScale` to `ImageViewerMaxScale`.
*/
export const ImageViewerZoomSteps = [
0.05, 0.1, 0.25, 0.33, 0.5, 0.67, 0.75, 0.9, 1, 1.25, 1.5, 2, 3, 4, 6, 8, 12, 16,
] as const;
export const ImageViewerMinScale = 0.05;
export const ImageViewerMaxScale = 16;
/**
* A picture this much taller (relative to its width) than the frame opens
* at the frame's width rather than whole: shrunk to fit, a page screenshot
* is a thin unreadable strip.
*/
export const ImageViewerTallRatio = 2;
+70
View File
@@ -373,4 +373,74 @@ describe("runTextLoop", () => {
expect(seen[1]!.messages.at(-1)!.content).toContain("Also this.");
expect(seen[1]!.messages.at(-1)!.content).toContain("You've used every step");
});
test("writes an answer the review faults again, once, with its note and the tool calls", async () => {
const { generate, seen } = scripted([
{ text: null, tool_calls: [{ id: "c1", name: "remember", arguments: '{"note":"x"}' }] },
{ text: "I'm scanning now. Scan done: 5 contests." },
{ text: "I haven't scanned yet." },
{ text: "never reached" },
]);
const reviewed: { text: string; tools: string[] }[] = [];
const result = await runTextLoop({
system: "s",
messages: [{ role: "user", content: "Scan." }],
tools: [remember],
generate,
resolveCandidates,
review: async ({ text, tool_uses }) => {
reviewed.push({ text, tools: tool_uses.map((use) => use.name) });
return "Not sent: nothing scanned.";
},
});
expect(result.text).toBe("I haven't scanned yet.");
expect(reviewed).toEqual([{ text: "I'm scanning now. Scan done: 5 contests.", tools: ["remember"] }]);
expect(seen[2]!.messages.slice(-2)).toEqual([
{ role: "assistant", content: "I'm scanning now. Scan done: 5 contests." },
{ role: "user", content: "Not sent: nothing scanned." },
]);
});
test("lets the answer through when the review passes it or throws", async () => {
for (const review of [async () => null, async () => Promise.reject(new Error("db down"))]) {
const { generate, seen } = scripted([{ text: "Fine." }]);
const result = await runTextLoop({
system: "s",
messages: [{ role: "user", content: "Hi." }],
generate,
resolveCandidates,
review,
});
expect(result.text).toBe("Fine.");
expect(seen.length).toBe(1);
}
});
test("doesn't review the wrap up", async () => {
const { generate } = scripted([
{ text: null, tool_calls: [{ id: "c1", name: "remember", arguments: '{"note":"x"}' }] },
{ text: "Out of steps." },
]);
let reviews = 0;
const result = await runTextLoop({
system: "s",
messages: [{ role: "user", content: "Go." }],
tools: [remember],
max_steps: 1,
generate,
resolveCandidates,
review: async () => {
reviews++;
return "Not sent.";
},
});
expect(result.text).toBe("Out of steps.");
expect(reviews).toBe(0);
});
});
+22 -1
View File
@@ -51,6 +51,13 @@ type Params = {
* is written again with them in mind.
*/
incoming?: () => Promise<HarnessMessage[]>;
/**
* Checks an answer before it's returned, with the tool calls the run
* made. A note sends the answer back to be written again with it, once
* per run; null lets it through. Not on the wrap up, and a check that
* throws lets the answer through.
*/
review?: (params: { text: string; tool_uses: HarnessToolUse[] }) => Promise<string | null | undefined>;
/**
* The bot the run is for: its own models are used where it has them.
*/
@@ -114,7 +121,8 @@ Don't repeat tool calls you have already made.`;
* The text harness at work: the model answers or calls tools, tool results
* 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 the model is asked to wrap up without tools.
* `max_steps` turns the model is asked to wrap up without tools. An answer
* `review` finds fault with is written again once.
*/
export default async function runTextLoop({
system,
@@ -124,6 +132,7 @@ export default async function runTextLoop({
signal = new AbortController().signal,
onStep,
incoming,
review,
bot_id,
workspace_id,
generate = generateText,
@@ -140,6 +149,7 @@ export default async function runTextLoop({
};
const tool_uses: HarnessToolUse[] = [];
let prefer_key: string | undefined;
let reviewed = false;
for (let index = 0; index <= max_steps; index++) {
if (signal.aborted) {
@@ -203,6 +213,17 @@ export default async function runTextLoop({
continue;
}
if (!tool_calls.length && !wrap_up && review && !reviewed) {
reviewed = true;
const note = await review({ text: answer.text || "", tool_uses }).catch(() => null);
if (note) {
pushUserTurn({ transcript, content: note });
continue;
}
}
if (!tool_calls.length) {
return {
text:
@@ -58,6 +58,11 @@ type Params = {
* copied from one it can already read.
*/
scopes?: StorageScope[];
/**
* The user follows the conversation (not a chatroom's hidden session):
* only then may the reply delete tasks.
*/
attended?: boolean;
/**
* Called when the bot asks the user to take over a computer.
*/
@@ -110,6 +115,7 @@ export default async function grabBotChatTools({
workspace_id,
message_id,
scopes = [],
attended,
onTakeOver,
onPropose,
onWorkspaceAdmin,
@@ -126,6 +132,7 @@ export default async function grabBotChatTools({
is_coordinator: powers.is_coordinator,
admin_workspace_ids: powers.admin_workspace_ids,
scopes,
can_delete_tasks: Boolean(attended),
onPropose,
onChatroom,
})),
+6
View File
@@ -48,6 +48,10 @@ type Params = {
* The run is a hook call, so it gets no hook tools.
*/
hooked?: boolean;
/**
* A chat reply the user follows, which may delete tasks.
*/
can_delete_tasks?: boolean;
/**
* In a chat reply: called with each hook proposal's ref, so the reply
* carries its card. Without it the bot can't propose hooks.
@@ -77,6 +81,7 @@ export default async function grabBotTools({
admin_workspace_ids,
scopes = [],
hooked,
can_delete_tasks,
onPropose,
onChatroom,
}: Params): Promise<HarnessTool[]> {
@@ -106,6 +111,7 @@ export default async function grabBotTools({
is_coordinator: Boolean(is_coordinator),
admin_workspace_ids,
workspace_id,
can_delete: Boolean(can_delete_tasks) && !hooked,
})),
];
}
@@ -0,0 +1,20 @@
import { describe, expect, test } from "bun:test";
import { AppData } from "@/src/data/app-data";
import startTaskTool from "./start-task-tool";
const tool = startTaskTool({ user_id: 1, bot_id: 5, session_id: 9, computers: [] });
/**
* The step budget the queuing bot sets, kept to what needs no database:
* `runBotTask` caps the run at it, below the install's limit.
*/
describe("startTaskTool", () => {
test("takes a step budget within the app's limit", () => {
const brief = { title: "Find the contest", instructions: "Look it up." };
expect(tool.schema?.safeParse({ ...brief, max_steps: 20 }).success).toBe(true);
expect(tool.schema?.safeParse(brief).success).toBe(true);
expect(tool.schema?.safeParse({ ...brief, max_steps: 0 }).success).toBe(false);
expect(tool.schema?.safeParse({ ...brief, max_steps: AppData.BotStepLimitMax + 1 }).success).toBe(false);
});
});
+23 -5
View File
@@ -1,4 +1,5 @@
import { z } from "zod";
import { AppData } from "@/src/data/app-data";
import type { BUN_SQLITE_COBBLE_COMPUTERS } from "@/db/types/db";
import enqueueBotJob from "@/src/functions/backend/db/bots-queue/enqueue-bot-job";
import countComputerTaskJobs from "@/src/functions/backend/db/bots-queue/count-computer-task-jobs";
@@ -27,6 +28,7 @@ type Args = {
instructions: string;
computer_id?: number;
separate?: boolean;
max_steps?: number;
};
/**
@@ -36,7 +38,13 @@ type Args = {
* (`tasks`), so it's called a run: told "Task #52", bots and users look
* for it in `list_tasks` and don't find it. While a run is open in the
* session on that computer a new one is refused unless it's separate
* work, since it would only wait behind it (one task per computer).
* work (one task per computer, so a repeat would only wait behind it).
* Different work is queued then and there with `separate`: nothing runs
* when a run ends but posting its result, so a bot that said "once that's
* done I'll start the next one" never did. `max_steps` caps the run's
* model turns below the install's limit (`params.max_steps`, read by
* `runBotTask`): a bot told to "keep it to ~20 steps" only wrote it in
* its brief, and the run searched on for 40 minutes.
*/
export default function startTaskTool({
user_id,
@@ -51,7 +59,7 @@ export default function startTaskTool({
return {
name: "start_task",
description: `Queue work that takes a while or needs a computer. It runs in the background and its result is posted in this chat. It's a run, not a task on the to-do list: list_tasks never shows it, so don't send the user there to find it. Write the instructions as a full brief for yourself: what to do, where, and how you'll know it's done. Tasks run one at a time per computer, so while one of yours is open here, a new one only waits behind it: don't start the same work again with another title. ${
description: `Queue work that takes a while or needs a computer. It runs in the background and its result is posted in this chat. It's a run, not a task on the to-do list: list_tasks never shows it, so don't send the user there to find it. Write the instructions as a full brief for yourself: what to do, where, and how you'll know it's done. Runs go one at a time per computer. While one of yours is open here, never start the same work again under another title, but queue different work now with separate: true and it starts as soon as the open one ends. Nothing starts it later but this call, so never tell the user you'll start it once the other run finishes. ${
computers.length
? `Computers you can use: ${listed}. Defaults to ${computers[0]!.id}, the one you're on.`
: `You have no computer, so the task can't run commands or browse.`
@@ -63,7 +71,16 @@ export default function startTaskTool({
separate: z
.boolean()
.optional()
.describe("Only for different work while another run of yours is open here on that computer, never to retry or redo it."),
.describe("For different work while another run of yours is open here on that computer: it's queued and starts when that one ends. Never to retry or redo the open run."),
max_steps: z
.number()
.int()
.min(1)
.max(AppData.BotStepLimitMax)
.optional()
.describe(
"The most model turns the run may take (each turn is one or more tool calls), enforced by the app; leave out for the install's limit. Set it whenever the user asked to keep a run short or cheap, and for lookups and searches (about 15 to 30), so a run that can't find something stops and reports what it tried instead of searching on.",
),
}),
run: async ({ args }) => {
const same = await grabOpenBotTask({ bot_id, session_id, title: args.title });
@@ -80,7 +97,7 @@ export default function startTaskTool({
if (open) {
throw new Error(
`Run #${open.id} "${open.title || "Task"}" is still ${open.status == "pending" ? "queued" : "under way"} here on that computer, and a new one would only wait behind it. If this is the same work, don't start it again: its result will be posted here (the user can Stop it to start over). Only for different work, call start_task again with separate.`,
`Run #${open.id} "${open.title || "Task"}" is still ${open.status == "pending" ? "queued" : "under way"} here on that computer. If this is the same work, don't start it again: its result will be posted here (the user can Stop it to start over). If it's different work, call start_task again now with separate: true; it's queued and starts as soon as run #${open.id} ends. Nothing starts it later but you, now, so never tell the user you'll start it once run #${open.id} is done.`,
);
}
@@ -92,11 +109,12 @@ export default function startTaskTool({
instructions: args.instructions,
message_id,
computer_id: computer_id || undefined,
params: args.max_steps ? { max_steps: args.max_steps } : undefined,
});
const ahead = computer_id ? await countComputerTaskJobs({ computer_id, except_job_id: job_id }) : 0;
return `Run #${job_id} queued; you'll work on it yourself in the background. It's not on the task list (list_tasks), so never tell the user to look for it there. ${
return `Run #${job_id} queued${args.max_steps ? ` with at most ${args.max_steps} steps` : ""}; you'll work on it yourself in the background. It's not on the task list (list_tasks), so never tell the user to look for it there. ${
ahead
? `The computer has ${ahead} other ${ahead == 1 ? "run" : "runs"} queued or working (they go one at a time), so it waits for ${ahead == 1 ? "it" : "them"} first: tell the user it's queued behind other work, not that it's running. `
: ""
@@ -0,0 +1,29 @@
import { describe, expect, test } from "bun:test";
import deleteTaskTool from "./delete-task-tool";
import grabBotTaskTools from "./grab-bot-task-tools";
/**
* What needs no database: who gets the tool and what it tells the bot.
* The delete itself, and its reach checks, reach the DB.
*/
describe("deleteTaskTool", () => {
test("only a run that may delete gets it", async () => {
const names = async (can_delete?: boolean) =>
(await grabBotTaskTools({ user_id: 1, bot_id: 5, is_coordinator: false, can_delete })).map(
(tool) => tool.name,
);
expect(await names(true)).toContain("delete_task");
expect(await names(false)).not.toContain("delete_task");
expect(await names()).not.toContain("delete_task");
});
test("takes a task id and says cancelling isn't deleting", () => {
const tool = deleteTaskTool({ user_id: 1, bot_id: 5, is_coordinator: false });
expect(tool.schema?.safeParse({ task_id: 20 }).success).toBe(true);
expect(tool.schema?.safeParse({}).success).toBe(false);
expect(tool.description).toContain("Only when the user asked");
expect(tool.description).toContain("cancelling isn't deleting");
});
});
@@ -0,0 +1,45 @@
import { z } from "zod";
import assertUserReachesTask from "@/src/functions/backend/db/tasks/assert-user-reaches-task";
import deleteTask from "@/src/functions/backend/db/tasks/delete-task";
import grabRunTask from "@/src/functions/backend/db/tasks/grab-run-task";
import type { HarnessTool } from "../../../types";
type Params = {
user_id: number | string;
bot_id: number | string;
is_coordinator: boolean;
/**
* The workspaces the bot is admin of (`grabBotRunPowers`).
*/
admin_workspace_ids?: number[];
};
type Args = {
task_id: number;
};
/**
* Lets a chat reply delete a task the user asked to have deleted, with its
* notes and file links (`deleteTask`; the files stay where they live).
* Without it, bots cancelled tasks and told the user they were removed.
* The run must reach the task (`grabRunTask`) and so must its user
* (`assertUserReachesTask`). Only chat replies get it: a routine, a hook
* call or a chatroom run has no user asking, and a payload could ask for it.
*/
export default function deleteTaskTool({ user_id, bot_id, is_coordinator, admin_workspace_ids = [] }: Params): HarnessTool<Args> {
return {
name: "delete_task",
description: `Delete a task from the to-do list for good, with its notes and file links (the files themselves stay). Only when the user asked for that task, or tasks like it, to be deleted; work that was dropped but should stay on record is cancelled with update_task instead. Say "deleted" only after this call says so; cancelling isn't deleting.`,
schema: z.object({
task_id: z.number().int(),
}),
run: async ({ args }) => {
const task = await grabRunTask({ task_id: args.task_id, bot_id, is_coordinator, admin_workspace_ids });
await assertUserReachesTask({ user_id, task_id: task.id! });
await deleteTask({ user_id, task_id: task.id!, deleted_by_bot_id: bot_id });
return `Deleted task #${task.id} "${task.title || "Untitled"}". It no longer exists, so don't update or link it again.`;
},
};
}
@@ -4,6 +4,7 @@ import grabUserWorkspaces from "@/src/functions/backend/db/workspaces/grab-user-
import grabStorageScopes from "@/src/utils/storage-access";
import type { HarnessTool } from "../../../types";
import createTaskTool from "./create-task-tool";
import deleteTaskTool from "./delete-task-tool";
import listTasksTool from "./list-tasks-tool";
import updateTaskTool from "./update-task-tool";
@@ -21,6 +22,11 @@ type Params = {
*/
admin_workspace_ids?: number[];
workspace_id?: number | string | null;
/**
* A chat reply the user follows: it also gets delete_task. Never a
* routine, a hook call or a chatroom run.
*/
can_delete?: boolean;
};
/**
@@ -30,6 +36,7 @@ type Params = {
* move it along and file what they produced. The coordinator's create_task
* may target any worker or workspace; its update_task may link any file it
* can reach. A workspace admin's may give tasks there to the other members.
* Only a chat reply the user follows deletes tasks (`can_delete`).
*/
export default async function grabBotTaskTools({
user_id,
@@ -37,6 +44,7 @@ export default async function grabBotTaskTools({
is_coordinator,
admin_workspace_ids = [],
workspace_id,
can_delete,
}: Params): Promise<HarnessTool[]> {
let workers: BUN_SQLITE_COBBLE_BOTS[] = [];
let members: BUN_SQLITE_COBBLE_BOTS[] = [];
@@ -76,5 +84,6 @@ export default async function grabBotTaskTools({
members,
}),
updateTaskTool({ user_id, bot_id, is_coordinator, admin_workspace_ids, scopes }),
...(can_delete ? [deleteTaskTool({ user_id, bot_id, is_coordinator, admin_workspace_ids })] : []),
];
}
@@ -0,0 +1,29 @@
import { describe, expect, test } from "bun:test";
import { AppData } from "@/src/data/app-data";
import updateTaskTool from "./update-task-tool";
const tool = updateTaskTool({ user_id: 1, bot_id: 5, is_coordinator: false });
/**
* The tool's own confines, kept to what needs no database: the rename and
* brief arguments it accepts and the description that steers a bot to
* them instead of a second task. The rename itself reaches the DB.
*/
describe("updateTaskTool", () => {
test("takes a new title and brief", () => {
expect(tool.schema?.safeParse({ task_id: 20, title: "99designs: contest 1 logo" }).success).toBe(true);
expect(tool.schema?.safeParse({ task_id: 20, description: "Enter the contest at ..." }).success).toBe(true);
});
test("refuses an empty or overlong title", () => {
expect(tool.schema?.safeParse({ task_id: 20, title: " " }).success).toBe(false);
expect(tool.schema?.safeParse({ task_id: 20, title: "x".repeat(AppData.TaskTitleMaxLength + 1) }).success).toBe(
false,
);
});
test("tells the bot to rename rather than add a second task", () => {
expect(tool.description).toContain("Rename it with title");
expect(tool.description).toContain("never create a second task");
});
});
+71 -11
View File
@@ -3,6 +3,8 @@ import { AppData } from "@/src/data/app-data";
import { type TaskStatus, TaskStatusValues } from "@/src/dict/task-dict";
import addTaskNote from "@/src/functions/backend/db/tasks/add-task-note";
import attachTaskFile from "@/src/functions/backend/db/tasks/attach-task-file";
import findDuplicateTask from "@/src/functions/backend/db/tasks/find-duplicate-task";
import grabTasks from "@/src/functions/backend/db/tasks/grab-tasks";
import grabRunTask from "@/src/functions/backend/db/tasks/grab-run-task";
import grabTaskMedia from "@/src/functions/backend/db/tasks/grab-task-media";
import makeTaskWorkspaceWide from "@/src/functions/backend/db/tasks/make-task-workspace-wide";
@@ -27,6 +29,8 @@ type Params = {
type Args = {
task_id: number;
title?: string;
description?: string;
status?: TaskStatus;
blocked_reason?: string;
note?: string;
@@ -36,11 +40,13 @@ type Args = {
};
/**
* Lets a bot move a task along: set its status, say what's blocking it, log
* a progress note, and file the deliverables it produced. One call does all
* of them, so a step in the work is a step in the log. On a workspace-wide
* task, which every bot there works on, the call's status move and filed
* files go into the log too, under the bot that did them, so the log says
* Lets a bot move a task along: rename it or rewrite its brief, set its
* status, say what's blocking it, log a progress note, and file the
* deliverables it produced. One call does all of them, so a step in the
* work is a step in the log. Without the rename, bots told users they
* couldn't fix a title and offered a second task for the same work. On a workspace-wide
* task, which every bot there works on, the call's rename, status move and
* filed files go into the log too, under the bot that did them, so the log says
* which bot did what and when. The coordinator and a workspace's admin bot
* can also turn a bot's task there into a workspace-wide one.
*/
@@ -52,9 +58,21 @@ export default function updateTaskTool({ user_id, bot_id, is_coordinator, admin_
return {
name: "update_task",
description: `Move a task along. Set its status (blocked needs a reason: what the user has to do), log a note of what you did or found, and file the files it produced. Call it as the work advances, not only at the end; every note is what the user sees on the task. A workspace-wide task is shared by every bot in its workspace: log a note for each part you do (it's recorded under your name and id, with the time) so the others see who did what, and don't mark it done while parts others are on are still open. Mark done only once you've verified the work (see the check note): starting a task isn't finishing it. To file a deliverable, save it first with write_file, make_pdf or generate_image, then pass its [file:ID] number.${can_share ? ` As ${is_coordinator ? "the coordinator" : "a workspace's admin"}, workspace_wide: true turns a bot's open task in ${is_coordinator ? "a" : "your"} workspace into a workspace-wide one every bot there works on (hand it to one bot again with delegate_task).` : ""}`,
description: `Move a task along. Rename it with title or rewrite its brief with description (never create a second task for the same work just to fix its name). Set its status (blocked needs a reason: what the user has to do), log a note of what you did or found, and file the files it produced. Call it as the work advances, not only at the end; every note is what the user sees on the task. A workspace-wide task is shared by every bot in its workspace: log a note for each part you do (it's recorded under your name and id, with the time) so the others see who did what, and don't mark it done while parts others are on are still open. Mark done only once you've verified the work (see the check note): starting a task isn't finishing it. To file a deliverable, save it first with write_file, make_pdf or generate_image, then pass its [file:ID] number.${can_share ? ` As ${is_coordinator ? "the coordinator" : "a workspace's admin"}, workspace_wide: true turns a bot's open task in ${is_coordinator ? "a" : "your"} workspace into a workspace-wide one every bot there works on (hand it to one bot again with delegate_task).` : ""}`,
schema: z.object({
task_id: z.number().int(),
title: z
.string()
.trim()
.min(1)
.max(AppData.TaskTitleMaxLength)
.optional()
.describe(`A new title, to rename it`),
description: z
.string()
.max(AppData.TaskDescriptionMaxLength)
.optional()
.describe(`A new brief (markdown), replacing the whole old one`),
status: z.enum(TaskStatusValues).optional(),
blocked_reason: z
.string()
@@ -105,19 +123,61 @@ export default function updateTaskTool({ user_id, bot_id, is_coordinator, admin_
said.push(`it's workspace-wide now, every bot in workspace ${task.workspace_id} works on it`);
}
if (args.status || args.blocked_reason !== undefined) {
if (args.status == "blocked" && !args.blocked_reason?.trim()) {
return `Blocked needs a reason: say in blocked_reason what the user has to do.`;
}
const title = args.title?.trim();
const renamed = Boolean(title) && title != (task.title || "").trim();
const rewritten = args.description != undefined && args.description != (task.description || "");
if (renamed) {
const open = await grabTasks({
bot_id,
is_coordinator,
admin_workspace_ids,
only_workspace_id: task.workspace_id,
own_list: !task.workspace_id,
open_only: true,
});
const twin = findDuplicateTask({
tasks: open.filter((other) => other.id != task.id),
title: title!,
bot_id: task.bot_id ? Number(task.bot_id) : null,
workspace_id: task.workspace_id ? Number(task.workspace_id) : null,
});
if (twin) {
return `Task #${twin.id} "${twin.title}" is already open with that title, so #${task.id} wasn't renamed. If they're the same work, carry on with #${twin.id} and cancel #${task.id}.`;
}
}
if (args.status == "blocked" && !args.blocked_reason?.trim()) {
return `Blocked needs a reason: say in blocked_reason what the user has to do.`;
}
if (renamed || rewritten || args.status || args.blocked_reason !== undefined) {
await updateTask({
user_id,
task_id: task.id!,
title: renamed ? title : undefined,
description: rewritten ? args.description : undefined,
status: args.status as never,
blocked_reason: args.blocked_reason ?? undefined,
updated_by_bot_id: bot_id,
});
if (renamed) {
said.push(`renamed to "${title}"`);
done.push(`Renamed it from "${task.title || "Task"}" to "${title}".`);
} else if (title) {
said.push(`title was already "${title}"`);
}
if (rewritten) {
said.push(`brief rewritten`);
done.push(`Rewrote the brief.`);
} else if (args.description != undefined) {
said.push(`brief was already that`);
}
if (args.status) {
said.push(task.status == args.status ? `status was already ${args.status}` : `status is now ${args.status}`);
@@ -168,7 +228,7 @@ export default function updateTaskTool({ user_id, bot_id, is_coordinator, admin_
const files = await grabTaskMedia({ task_id: task.id! });
return `Task #${task.id} "${task.title}": ${said.join(", ")}. It now carries ${files.length} file(s). Read it back with list_tasks before you tell the user.`;
return `Task #${task.id} "${renamed ? title : task.title}": ${said.join(", ")}. It now carries ${files.length} file(s). Read it back with list_tasks before you tell the user.`;
},
};
}
@@ -1,23 +1,40 @@
import type { ComputerRunDirs } from "@/src/utils/computer-work-dirs";
import computerWorkspacePath from "@/src/utils/computer-workspace-path";
import shellQuote from "@/src/utils/shell-quote";
/**
* The shell that puts a command in the run's folder on the computer:
* creates its folders (the user's in the bot's, and the workspace's shared
* one), moves into the user's and makes it `HOME`, so `~` and every
* relative path land there. A worker (its own account, no sudo) also
* gets `umask 007`, so its files stay its workspace group's and nobody
* else's, and installs into that home that work without root
* (`pip install --user`, `npm install -g` into `~/.local`, on `PATH`).
* Ends with `; `, ready to prefix a command.
* creates the user's folder in the bot's, moves into it and makes it
* `HOME`, so `~` and every relative path land there. The coordinator also
* creates the workspace's shared folder. A worker's shared folder is a
* link in its own (`workspaces/<id>`, made by the computer's agent) to the
* real one; when it's gone the link is put back, never a folder made in
* its place, which would keep the workspace's work from its other bots. A
* worker (its own account, no sudo) also gets `umask 007`, so its files
* stay its workspace group's and nobody else's, and installs into that
* home that work without root (`pip install --user`, `npm install -g` into
* `~/.local`, on `PATH`). Ends with `; `, ready to prefix a command.
*/
export default function computerDirsShell({ dirs }: { dirs: ComputerRunDirs }) {
const cwd = shellQuote({ text: dirs.cwd });
const folders = [dirs.cwd, ...(dirs.shared_dir ? [dirs.shared_dir] : [])]
.map((dir) => shellQuote({ text: dir }))
.join(" ");
if (!dirs.run_as) return `mkdir -p ${folders} && cd ${cwd} && export HOME=${cwd}; `;
if (!dirs.run_as) {
const folders = [dirs.cwd, ...(dirs.shared_dir ? [dirs.shared_dir] : [])]
.map((dir) => shellQuote({ text: dir }))
.join(" ");
return `umask 007 && mkdir -p ${folders} && cd ${cwd} && export HOME=${cwd} && export PATH="$HOME/.local/bin:$PATH" NPM_CONFIG_PREFIX="$HOME/.local"; `;
return `mkdir -p ${folders} && cd ${cwd} && export HOME=${cwd}; `;
}
const shared = dirs.shared_dir ? sharedLinkShell({ link: dirs.shared_dir }) : "";
return `umask 007 && ${shared}mkdir -p ${cwd} && cd ${cwd} && export HOME=${cwd} && export PATH="$HOME/.local/bin:$PATH" NPM_CONFIG_PREFIX="$HOME/.local"; `;
}
function sharedLinkShell({ link }: { link: string }) {
const quoted = shellQuote({ text: link });
const parent = shellQuote({ text: link.replace(/\/[^/]+$/, "") });
const target = shellQuote({ text: computerWorkspacePath({ absolute: link }) });
return `{ [ -e ${quoted} ] || [ -L ${quoted} ] || { mkdir -p ${parent} && ln -s ${target} ${quoted}; }; } && `;
}
+27 -16
View File
@@ -95,9 +95,8 @@ export default function importFileTool({
* Workspace-relative from here on, which is what a folder ref
* names.
*/
const source = computerWorkspaceRelative({
absolute: resolveComputerPath({ path: args.path, dirs }),
});
const shown = resolveComputerPath({ path: args.path, dirs });
const source = computerWorkspaceRelative({ absolute: shown });
if (!source) return `Give a file or folder inside your folder, e.g. "seo/coderank/raw".`;
@@ -110,13 +109,14 @@ export default function importFileTool({
const kind = await sourceKind({ computer: target, source, run_as: dirs.run_as, signal });
if (kind == "missing") {
return `Nothing at ${onComputer({ source })} on this computer. Check it with search_computers or the computer's own tools before importing.`;
return `Nothing at ${shown} on this computer. Check it with search_computers or the computer's own tools before importing.`;
}
if (kind == "folder") {
return importFolder({
computer: target,
source,
shown,
name: (args.name || source.split("/").pop() || "import").trim(),
scope: own,
bot_id,
@@ -130,6 +130,7 @@ export default function importFileTool({
return importOneFile({
computer: target,
source,
shown,
name: (args.name || source.split("/").pop() || "import").trim(),
scope: own,
bot_id,
@@ -146,7 +147,14 @@ export default function importFileTool({
type ImportTarget = {
computer: ComputerApi;
/**
* Relative to the computer's workspace, where it really is.
*/
source: string;
/**
* Its path as the run sees it, for what the bot is told.
*/
shown: string;
name: string;
scope: StorageScope;
bot_id: number | string;
@@ -180,7 +188,7 @@ async function importOneFile({
signal,
});
if (!download.ok) return importFailure({ reason: download.reason, size: download.size, path: target.source });
if (!download.ok) return importFailure({ reason: download.reason, size: download.size, shown: target.shown });
const previous = await grabBotFileRow({
scope: target.scope.scope,
@@ -206,11 +214,11 @@ async function importOneFile({
return [
previous?.id
? `You already had ${saved.path} (same ref, no second copy): its bytes are now this file, ${formatSize({ bytes: download.size })} byte for byte.`
: `Copied ${onComputer({ source: target.source })} into your files as ${saved.path} [file:${saved.id}], ${formatSize({ bytes: download.size })} byte for byte.`,
: `Copied ${target.shown} into your files as ${saved.path} [file:${saved.id}], ${formatSize({ bytes: download.size })} byte for byte.`,
`The original is still on the computer, in ${folderRef({
volume: "computer",
owner_id: target.computer_id,
path: sourceFolder({ path: target.source }),
path: sourceFolder({ path: target.shown }),
})}`,
"Name the copy with its [file:ID] ref when you tell the user about it.",
].join("\n");
@@ -239,22 +247,22 @@ async function importFolder({
return importFailure({
reason: archive.reason,
size: archive.size,
path: target.source,
shown: target.shown,
});
}
const saved = await unpackArchive({ archive: archive.bytes, folder: name.replace(/\/+$/, ""), scope, bot_id, user_id });
if (!saved.length) return `The folder ${onComputer({ source: target.source })} is empty, so nothing was imported.`;
if (!saved.length) return `The folder ${target.shown} is empty, so nothing was imported.`;
return [
`Copied ${saved.length} file(s) from ${onComputer({ source: target.source })} into your files under ${name}/:`,
`Copied ${saved.length} file(s) from ${target.shown} into your files under ${name}/:`,
...saved.slice(0, 20).map((file) => `- ${file.path} [file:${file.id}]`),
saved.length > 20 ? `(and ${saved.length - 20} more)` : "",
`The originals are still on the computer, in ${folderRef({
volume: "computer",
owner_id: computer_id,
path: target.source,
path: target.shown,
})}`,
"Name the copies that matter with their [file:ID] refs.",
]
@@ -306,23 +314,26 @@ async function sourceKind({
function importFailure({
reason,
size,
path: source,
shown,
}: {
reason: "missing" | "too_big" | "cut_short";
size: number;
path: string;
/**
* The path as the run sees it.
*/
shown: string;
}) {
const limit = formatSize({ bytes: AppData.BotFileImportMaxBytes });
if (reason == "missing") {
return `Nothing at ${onComputer({ source })} on this computer. Check it with search_computers or the computer's own tools before importing.`;
return `Nothing at ${shown} on this computer. Check it with search_computers or the computer's own tools before importing.`;
}
if (reason == "too_big") {
return `${onComputer({ source })} is ${formatSize({ bytes: size })}, over the ${limit} limit, so nothing was copied. Zip it on the computer first, or import the files that matter on their own.`;
return `${shown} is ${formatSize({ bytes: size })}, over the ${limit} limit, so nothing was copied. Zip it on the computer first, or import the files that matter on their own.`;
}
return `The copy of ${onComputer({ source })} came back with ${formatSize({ bytes: size })} of its bytes, so it was thrown away rather than saved. Try again; if it keeps happening, the file is changing while it is read.`;
return `The copy of ${shown} came back with ${formatSize({ bytes: size })} of its bytes, so it was thrown away rather than saved. Try again; if it keeps happening, the file is changing while it is read.`;
}
/**
@@ -12,16 +12,18 @@ const echoTool = (name: string): HarnessTool => ({
});
const dirs = computerRunDirs({ bot_id: 3, user_id: 7, workspace_id: 2 });
const cwd = "/home/gem/workspace/bots/3/users/7";
const cwd = "/home/cb-3/workspace/users/7";
const shared = "/home/cb-3/workspace/workspaces/2";
const signal = new AbortController().signal;
const call = async (name: string, args: Record<string, unknown>) =>
JSON.parse((await withComputerDirs({ tool: echoTool(name), dirs }).run({ args, signal })) as string);
describe("withComputerDirs", () => {
test("uploads resolve paths and refuse outside ones", async () => {
expect((await call("browser_file_upload", { paths: ["a.pdf", "/home/gem/workspace/workspaces/2/b.png"] })).paths).toEqual([
expect((await call("browser_file_upload", { paths: ["a.pdf", `${shared}/b.png`, "/home/gem/workspace/workspaces/2/c.png"] })).paths).toEqual([
`${cwd}/a.pdf`,
"/home/gem/workspace/workspaces/2/b.png",
`${shared}/b.png`,
`${shared}/c.png`,
]);
await expect(call("browser_file_upload", { paths: ["/home/gem/.bashrc"] })).rejects.toThrow();
await expect(call("browser_file_upload", { paths: ["../../../4/x"] })).rejects.toThrow();
@@ -50,9 +52,7 @@ describe("withComputerDirs", () => {
test("a file saved by name lands in the run's folders", async () => {
expect((await call("browser_take_screenshot", { filename: "shot.png" })).filename).toBe(`${cwd}/shot.png`);
expect((await call("browser_snapshot", { filename: "/home/gem/workspace/workspaces/2/page.md" })).filename).toBe(
"/home/gem/workspace/workspaces/2/page.md",
);
expect((await call("browser_snapshot", { filename: `${shared}/page.md` })).filename).toBe(`${shared}/page.md`);
await expect(call("browser_console_messages", { filename: "/home/gem/workspace/bots/4/log.txt" })).rejects.toThrow();
});
@@ -63,9 +63,15 @@ describe("withComputerDirs", () => {
});
describe("computerDirsShell", () => {
test("a worker's: its umask, the folders, moved in, installs into its home", () => {
test("a worker's: its umask, the shared link put back, its folder, moved in, installs into its home", () => {
expect(computerDirsShell({ dirs })).toBe(
`umask 007 && mkdir -p '${cwd}' '/home/gem/workspace/workspaces/2' && cd '${cwd}' && export HOME='${cwd}' && export PATH="$HOME/.local/bin:$PATH" NPM_CONFIG_PREFIX="$HOME/.local"; `,
`umask 007 && { [ -e '${shared}' ] || [ -L '${shared}' ] || { mkdir -p '/home/cb-3/workspace/workspaces' && ln -s '/home/gem/workspace/workspaces/2' '${shared}'; }; } && mkdir -p '${cwd}' && cd '${cwd}' && export HOME='${cwd}' && export PATH="$HOME/.local/bin:$PATH" NPM_CONFIG_PREFIX="$HOME/.local"; `,
);
});
test("a worker outside a workspace: no shared link", () => {
expect(computerDirsShell({ dirs: computerRunDirs({ bot_id: 3, user_id: 7 }) })).toBe(
`umask 007 && mkdir -p '${cwd}' && cd '${cwd}' && export HOME='${cwd}' && export PATH="$HOME/.local/bin:$PATH" NPM_CONFIG_PREFIX="$HOME/.local"; `,
);
});
+47
View File
@@ -0,0 +1,47 @@
import { useEffect, useRef } from "react";
function typingInField({ target }: { target: EventTarget | null }) {
if (!(target instanceof HTMLElement)) return false;
if (target.isContentEditable) return true;
return ["INPUT", "TEXTAREA", "SELECT"].includes(target.tagName);
}
/**
* The left and right arrow keys step a preview's gallery back and forth,
* except while typing in a field or with a modifier held.
*/
export default function useGalleryKeys({
enabled,
onPrevious,
onNext,
}: {
enabled: boolean;
onPrevious: () => void;
onNext: () => void;
}) {
const handlers_ref = useRef({ onPrevious, onNext });
handlers_ref.current = { onPrevious, onNext };
useEffect(() => {
if (!enabled) return;
const onKey = (event: KeyboardEvent) => {
if (event.ctrlKey || event.metaKey || event.altKey || event.shiftKey) return;
if (typingInField({ target: event.target })) return;
if (event.key == "ArrowLeft") handlers_ref.current.onPrevious();
else if (event.key == "ArrowRight") handlers_ref.current.onNext();
else return;
event.preventDefault();
};
window.addEventListener("keydown", onKey);
return () => window.removeEventListener("keydown", onKey);
}, [enabled]);
}
+127
View File
@@ -0,0 +1,127 @@
import { useEffect, useRef, useState, type PointerEvent, type RefObject } from "react";
import type { ImageViewerMode } from "@/src/dict/image-viewer-dict";
import type { ImageViewerPoint } from "./use-image-viewer";
type Params = {
container_ref: RefObject<HTMLDivElement | null>;
scale_ref: RefObject<number>;
zoom: (params: { direction: "in" | "out"; point?: ImageViewerPoint }) => void;
zoomTo: (params: { scale: number; point?: ImageViewerPoint }) => void;
choose: (params: { mode: Exclude<ImageViewerMode, "custom">; point?: ImageViewerPoint }) => void;
};
/**
* How much one wheel pixel zooms (a trackpad pinch arrives as small
* Ctrl+wheel steps, a mouse wheel as large ones).
*/
const WheelZoomRate = 0.0025;
function typingInField({ target }: { target: EventTarget | null }) {
if (!(target instanceof HTMLElement)) return false;
if (target.isContentEditable) return true;
return ["INPUT", "TEXTAREA", "SELECT"].includes(target.tagName);
}
/**
* The image preview's hands: Ctrl/Cmd + wheel (and a trackpad pinch) zooms
* at the pointer, a plain wheel scrolls, dragging with the mouse moves a
* picture bigger than the frame, and the keys `+` `-` zoom, `0` fits, `w`
* fits the width and `1` shows actual size.
*/
export default function useImageViewerGestures({ container_ref, scale_ref, zoom, zoomTo, choose }: Params) {
const drag_ref = useRef<{ x: number; y: number; left: number; top: number } | null>(null);
const [dragging, set_dragging] = useState(false);
useEffect(() => {
const container = container_ref.current;
if (!container) return;
const onWheel = (event: WheelEvent) => {
if (!event.ctrlKey && !event.metaKey) return;
event.preventDefault();
const pixels = event.deltaMode == 1 ? event.deltaY * 16 : event.deltaY;
const factor = Math.exp(-pixels * WheelZoomRate);
zoomTo({ scale: scale_ref.current * factor, point: { x: event.clientX, y: event.clientY } });
};
container.addEventListener("wheel", onWheel, { passive: false });
return () => container.removeEventListener("wheel", onWheel);
}, [container_ref, scale_ref, zoomTo]);
useEffect(() => {
const onKey = (event: KeyboardEvent) => {
if (event.ctrlKey || event.metaKey || event.altKey) return;
if (typingInField({ target: event.target })) return;
if (event.key == "+" || event.key == "=") zoom({ direction: "in" });
else if (event.key == "-" || event.key == "_") zoom({ direction: "out" });
else if (event.key == "0") choose({ mode: "fit" });
else if (event.key == "w" || event.key == "W") choose({ mode: "width" });
else if (event.key == "1") choose({ mode: "actual" });
else return;
event.preventDefault();
};
window.addEventListener("keydown", onKey);
return () => window.removeEventListener("keydown", onKey);
}, [zoom, choose]);
const onPointerDown = (event: PointerEvent<HTMLDivElement>) => {
const container = container_ref.current;
if (!container || event.pointerType != "mouse" || event.button != 0) return;
const overflows =
container.scrollWidth > container.clientWidth || container.scrollHeight > container.clientHeight;
if (!overflows) return;
event.preventDefault();
container.setPointerCapture(event.pointerId);
drag_ref.current = {
x: event.clientX,
y: event.clientY,
left: container.scrollLeft,
top: container.scrollTop,
};
set_dragging(true);
};
const onPointerMove = (event: PointerEvent<HTMLDivElement>) => {
const container = container_ref.current;
const drag = drag_ref.current;
if (!container || !drag) return;
container.scrollLeft = drag.left - (event.clientX - drag.x);
container.scrollTop = drag.top - (event.clientY - drag.y);
};
const onPointerUp = (event: PointerEvent<HTMLDivElement>) => {
if (!drag_ref.current) return;
drag_ref.current = null;
set_dragging(false);
container_ref.current?.releasePointerCapture(event.pointerId);
};
return {
dragging,
pointerHandlers: {
onPointerDown,
onPointerMove,
onPointerUp,
onPointerCancel: onPointerUp,
},
};
}
+197
View File
@@ -0,0 +1,197 @@
import { useCallback, useEffect, useLayoutEffect, useRef, useState } from "react";
import type { ImageViewerMode } from "@/src/dict/image-viewer-dict";
import imageViewerClampScale from "@/src/utils/image-viewer-clamp-scale";
import imageViewerDefaultMode from "@/src/utils/image-viewer-default-mode";
import imageViewerFitScale from "@/src/utils/image-viewer-fit-scale";
import imageViewerZoomStep from "@/src/utils/image-viewer-zoom-step";
type Size = { width: number; height: number };
/**
* A point on the screen (client coordinates) a zoom keeps still.
*/
export type ImageViewerPoint = { x: number; y: number };
/**
* Where a zoom lands: the part of the picture under a point stays under it,
* or the view goes back to the top left.
*/
type Anchor = { fx: number; fy: number; ax: number; ay: number } | "top";
/**
* The frame's padding on each side (the frame's `p-4`), left out of the
* room a fit has.
*/
const FramePadding = 16;
function clampUnit({ value }: { value: number }) {
if (!Number.isFinite(value)) return 0.5;
return Math.min(1, Math.max(0, value));
}
/**
* The image preview's state: how big the picture is drawn and where the
* frame is scrolled. A preset (`fit`, `width`, `actual`) follows the frame
* as it resizes; a zoom keeps the part of the picture under the pointer
* (or the frame's middle) where it was, so the user can walk into a detail.
*/
export default function useImageViewer() {
const container_ref = useRef<HTMLDivElement>(null);
const image_ref = useRef<HTMLImageElement>(null);
const anchor_ref = useRef<Anchor | null>(null);
const [natural, set_natural] = useState<Size | null>(null);
const [frame, set_frame] = useState<Size>({ width: 0, height: 0 });
const [mode, set_mode] = useState<ImageViewerMode | null>(null);
const [custom_scale, set_custom_scale] = useState(1);
const [tick, set_tick] = useState(0);
useEffect(() => {
const container = container_ref.current;
if (!container || typeof ResizeObserver == "undefined") return;
const measure = () =>
set_frame({
width: Math.max(0, container.clientWidth - FramePadding * 2),
height: Math.max(0, container.clientHeight - FramePadding * 2),
});
measure();
const observer = new ResizeObserver(measure);
observer.observe(container);
return () => observer.disconnect();
}, []);
useEffect(() => {
if (mode || !natural || !frame.width) return;
set_mode(imageViewerDefaultMode({ natural, frame }));
}, [mode, natural, frame]);
const shown_mode: ImageViewerMode = mode || "fit";
const scale = !natural
? 1
: shown_mode == "custom"
? custom_scale
: imageViewerFitScale({ mode: shown_mode, natural, frame });
const scale_ref = useRef(scale);
scale_ref.current = scale;
useLayoutEffect(() => {
const anchor = anchor_ref.current;
const container = container_ref.current;
const image = image_ref.current;
anchor_ref.current = null;
if (!anchor || !container || !image) return;
if (anchor == "top") {
container.scrollTo({ left: 0, top: 0 });
return;
}
container.scrollLeft = image.offsetLeft + anchor.fx * image.offsetWidth - anchor.ax;
container.scrollTop = image.offsetTop + anchor.fy * image.offsetHeight - anchor.ay;
}, [scale, tick]);
/**
* Which part of the picture is under a point (the frame's middle when
* none is given), to keep it there after the zoom.
*/
const captureAnchor = useCallback(({ point }: { point?: ImageViewerPoint }): Anchor | null => {
const container = container_ref.current;
const image = image_ref.current;
if (!container || !image) return null;
const box = container.getBoundingClientRect();
const at = point || {
x: box.left + container.clientLeft + container.clientWidth / 2,
y: box.top + container.clientTop + container.clientHeight / 2,
};
const rect = image.getBoundingClientRect();
return {
fx: clampUnit({ value: (at.x - rect.left) / (rect.width || 1) }),
fy: clampUnit({ value: (at.y - rect.top) / (rect.height || 1) }),
ax: at.x - box.left - container.clientLeft,
ay: at.y - box.top - container.clientTop,
};
}, []);
const zoomTo = useCallback(
({ scale: next, point }: { scale: number; point?: ImageViewerPoint }) => {
anchor_ref.current = captureAnchor({ point });
set_custom_scale(imageViewerClampScale({ scale: next }));
set_mode("custom");
set_tick((value) => value + 1);
},
[captureAnchor],
);
const zoom = useCallback(
({ direction, point }: { direction: "in" | "out"; point?: ImageViewerPoint }) =>
zoomTo({ scale: imageViewerZoomStep({ scale: scale_ref.current, direction }), point }),
[zoomTo],
);
/**
* A preset. Fitting starts from the top left (a page screenshot reads
* from its top); actual size keeps the point (or the middle) in view.
*/
const choose = useCallback(
({ mode: next, point }: { mode: Exclude<ImageViewerMode, "custom">; point?: ImageViewerPoint }) => {
anchor_ref.current = next == "actual" ? captureAnchor({ point }) : "top";
set_mode(next);
set_tick((value) => value + 1);
},
[captureAnchor],
);
/**
* A double click: into actual size at that point from anything
* smaller, else back to the picture's own fit.
*/
const toggle = useCallback(
({ point }: { point: ImageViewerPoint }) => {
if (scale_ref.current < 1) return choose({ mode: "actual", point });
if (!natural) return;
choose({ mode: imageViewerDefaultMode({ natural, frame }) });
},
[choose, natural, frame],
);
const onImageLoad = useCallback(() => {
const image = image_ref.current;
if (!image?.naturalWidth || !image.naturalHeight) return;
set_natural({ width: image.naturalWidth, height: image.naturalHeight });
}, []);
useEffect(() => {
if (image_ref.current?.complete) onImageLoad();
}, [onImageLoad]);
return {
container_ref,
image_ref,
natural,
mode: shown_mode,
scale,
scale_ref,
zoom,
zoomTo,
choose,
toggle,
onImageLoad,
};
}
+26
View File
@@ -0,0 +1,26 @@
import { useEffect } from "react";
/**
* Starts loading images the user is likely to open next (a gallery's
* neighbours), so stepping to one shows it at once.
*/
export default function usePreloadImages({ urls }: { urls: string[] }) {
const key = urls.join("\n");
useEffect(() => {
if (typeof Image == "undefined") return;
const images = urls.filter(Boolean).map((url) => {
const image = new Image();
image.decoding = "async";
image.src = url;
return image;
});
return () => {
for (const image of images) image.src = "";
};
}, [key]);
}
+40
View File
@@ -0,0 +1,40 @@
import { useEffect, useId, useRef } from "react";
/**
* The open modals that close on Escape one at a time, oldest first.
*/
const OpenModals: string[] = [];
/**
* Escape closes only the modal on top. twui's modal closes every open one
* on the same key press, so a file opened from a folder (or a folder from
* a file) would take both away. Listening first, on the window's capture
* phase, the modal on top closes itself and the press goes no further.
*/
export default function useTopModalEscape({ onClose }: { onClose: () => void }) {
const id = useId();
const close_ref = useRef(onClose);
close_ref.current = onClose;
useEffect(() => {
OpenModals.push(id);
const onKey = (event: KeyboardEvent) => {
if (event.key != "Escape" || OpenModals.at(-1) != id) return;
event.stopPropagation();
close_ref.current();
};
window.addEventListener("keydown", onKey, true);
return () => {
window.removeEventListener("keydown", onKey, true);
const index = OpenModals.lastIndexOf(id);
if (index >= 0) OpenModals.splice(index, 1);
};
}, [id]);
}
@@ -0,0 +1,11 @@
import { expect, test } from "bun:test";
import { MessageMarkdownComponents } from "./message-markdown-components";
/**
* Its links reach the file preview, which renders through these same
* elements: loading them first must still work (the preview merges them
* when it renders, never at load).
*/
test("loads on its own, before the file preview", () => {
expect(MessageMarkdownComponents.a).toBeFunction();
});
@@ -1,4 +1,4 @@
import { useContext, useEffect, useState } from "react";
import { useContext, useEffect, useMemo, useState } from "react";
import Modal from "@moduletrace/twui/elements/Modal";
import H2 from "@moduletrace/twui/layout/H2";
import Span from "@moduletrace/twui/layout/Span";
@@ -14,6 +14,7 @@ import HeaderIconButton from "@/src/components/general/header-icon-button";
import { AppContext } from "@/src/pages/__root";
import useDebouncedValue from "@/src/hooks/use-debounced-value";
import canManageCrew from "@/src/utils/rbac/can-manage-crew";
import imagePreviewGallery from "@/src/utils/image-preview-gallery";
import useBotFiles from "../(hooks)/use-bot-files";
import FileRow from "./file-row";
import HeaderMenuItem from "./header-menu-item";
@@ -83,6 +84,10 @@ export default function BotFilesModal({ bot, workspace, menu, on_open }: Props)
};
const files = data?.files || [];
const gallery = useMemo(
() => imagePreviewGallery({ items: files.map((file) => ({ ...file, name: file.path || file.name })) }),
[data],
);
const usage = data?.usage;
return (
@@ -146,6 +151,7 @@ export default function BotFilesModal({ bot, workspace, menu, on_open }: Props)
file={file}
can_manage={can_manage}
busy={busy_id == file.id}
gallery={gallery}
onDelete={() =>
run({
url: `/api/admin/bots/delete-file`,
@@ -13,6 +13,7 @@ import GroupTimestamp from "./group-timestamp";
import MessageActions from "./message-actions";
import MessageReactions from "./message-reactions";
import MessageReplyQuote from "./message-reply-quote";
import MessageNoToolsChip from "./message-no-tools-chip";
import MessageUsageChip from "./message-usage-chip";
import NeedsYouChip from "./needs-you-chip";
import SpeakMessageButton from "./speak-message-button";
@@ -85,6 +86,7 @@ function BotMessageLine({ message, bot_name, at }: Props) {
{message.needs_you ? <NeedsYouChip /> : null}
{at ? <GroupTimestamp at={at} /> : null}
<MessageUsageChip usage={message.usage} />
<MessageNoToolsChip message={message} />
{can_speak ? (
<SpeakMessageButton message_id={Number(message.id)} />
) : null}
@@ -3,7 +3,7 @@ import Span from "@moduletrace/twui/layout/Span";
import Stack from "@moduletrace/twui/layout/Stack";
import Button from "@moduletrace/twui/layout/Button";
import { Trash2 } from "lucide-react";
import type { MediaType, PublicBotFile } from "@/src/types";
import type { FilePreviewItem, MediaType, PublicBotFile } from "@/src/types";
import relativeTime from "@/src/utils/relative-time";
import FilePreviewLink from "@/src/components/general/file-preview-link";
import AttachmentIcon from "./attachment-icon";
@@ -15,6 +15,10 @@ type Props = {
*/
can_manage: boolean;
busy?: boolean;
/**
* The listed images, so an image's preview steps through the rest.
*/
gallery?: FilePreviewItem[];
onDelete: () => void;
};
@@ -22,7 +26,7 @@ type Props = {
* One file in the files modal: its type, path, size and age, and what can
* be done with it.
*/
export default function FileRow({ file, can_manage, busy, onDelete }: Props) {
export default function FileRow({ file, can_manage, busy, gallery, onDelete }: Props) {
return (
<Row className="w-full gap-3! flex-nowrap items-start py-2 border-0 border-b border-solid border-hairline last:border-b-0">
<Row className="mt-0.5 text-ink-secondary">
@@ -34,6 +38,7 @@ export default function FileRow({ file, can_manage, busy, onDelete }: Props) {
url={file.url}
media_type={file.media_type}
size={file.size}
gallery={gallery}
className="text-[13px] font-bold leading-5 text-ink break-words hover:opacity-80"
>
{file.path || file.name}
@@ -1,6 +1,6 @@
import Link from "@moduletrace/twui/layout/Link";
import Span from "@moduletrace/twui/layout/Span";
import { FolderOpen } from "lucide-react";
import FolderPreviewLink from "@/src/components/general/folder-preview-link";
import { folderRefUrl } from "@/src/utils/folder-ref";
import { storagePathName, type StorageSpec } from "@/src/utils/storage-volumes";
@@ -11,11 +11,13 @@ type Props = {
/**
* A folder a bot named in a message (`folderRef`): the name it ends with,
* linked into the files browser, where the user can look at everything in
* it. Nothing is downloaded: a folder ref never serves bytes, and this chip
* never guesses from the name whether it is a file or a folder, because the
* ref itself already says it is a folder. A file the bot saved is a file
* ref (`fileRef`) and opens the file instead.
* opening the folder over the chat (`FolderPreviewModal`), where each file
* opens in its own preview. It stays a link to the same folder in the
* files browser, for a middle or Ctrl/Cmd click and the modal's "Open in
* Files". Nothing is downloaded: a folder ref never serves bytes, and this
* chip never guesses from the name whether it is a file or a folder,
* because the ref itself already says it is a folder. A file the bot saved
* is a file ref (`fileRef`) and opens the file instead.
*
* Written without a literal ref in this comment on purpose: Tailwind scans
* every page and partial, reads a bracketed `name:value` as an
@@ -26,13 +28,15 @@ export default function FolderRefChip({ spec, path }: Props) {
const name = storagePathName({ volume: spec.volume, path });
return (
<Link
<FolderPreviewLink
spec={spec}
path={path}
href={folderRefUrl({ volume: spec.volume, owner_id: spec.owner_id, path })}
title={`Open ${path || name} in Files`}
title={`Open ${path || name}`}
className="inline-flex h-6 max-w-full gap-1.5 items-center px-1.5 align-middle rounded-default-xs border-0 bg-sunken text-[13px] font-bold leading-4 text-ink hover:opacity-80"
>
<FolderOpen size={14} aria-hidden className="shrink-0" />
<Span className="truncate">{name}</Span>
</Link>
</FolderPreviewLink>
);
}
@@ -16,6 +16,7 @@ import { parseFolderRefHref } from "@/src/utils/folder-ref";
import { botQuestionRefId } from "@/src/utils/bot-question-ref";
import { graphicRefId } from "@/src/utils/graphic-ref";
import { chatroomRefId } from "@/src/utils/chatroom-ref";
import { taskRefId } from "@/src/utils/task-ref";
import BotQuestionRefChip from "./bot-question-ref-chip";
import BotRefChip from "./bot-ref-chip";
import ChatroomRefChip from "./chatroom-ref-chip";
@@ -28,6 +29,7 @@ import ProposalRefChip from "./proposal-ref-chip";
import SecretRefChip from "./secret-ref-chip";
import SecretRequestRefChip from "./secret-request-ref-chip";
import TakeOverChip from "./take-over-chip";
import TaskRefChip from "./task-ref-chip";
import WorkspaceRefChip from "./workspace-ref-chip";
/**
@@ -40,7 +42,8 @@ import WorkspaceRefChip from "./workspace-ref-chip";
* secret it showed a masked chip, a secret it asked for a chip that opens
* the card it's typed into, questions it asked a chip that opens the card
* they're answered in, a graphic it made the graphic itself, a
* chatroom a chip that opens it;
* chatroom a chip that opens it, a task on the tracker a chip that opens
* the task;
* anything else opens in a new tab.
*/
export default function MarkdownLink({ href, children }: ComponentProps<"a">) {
@@ -115,6 +118,10 @@ export default function MarkdownLink({ href, children }: ComponentProps<"a">) {
if (chatroom_id) return <ChatroomRefChip chatroom_id={chatroom_id} />;
const task_id = taskRefId({ href });
if (task_id) return <TaskRefChip task_id={task_id} />;
const graphic_id = graphicRefId({ href });
if (graphic_id) return <GraphicRefCard graphic_id={graphic_id} />;
@@ -1,22 +1,24 @@
import Img from "@moduletrace/twui/layout/Img";
import Span from "@moduletrace/twui/layout/Span";
import type { BotMessageAttachment } from "@/src/types";
import type { BotMessageAttachment, FilePreviewItem } from "@/src/types";
import FilePreviewLink from "@/src/components/general/file-preview-link";
import AttachmentIcon from "./attachment-icon";
/**
* One file on a message: an image as a thumbnail, anything else as a
* named chip. Both open the file in the preview.
* named chip. Both open the file in the preview; an image steps through
* the message's other images (`gallery`).
*/
export default function MessageAttachment({
name,
media_type,
url,
thumbnail_url,
}: BotMessageAttachment) {
gallery,
}: BotMessageAttachment & { gallery?: FilePreviewItem[] }) {
if (media_type == "image") {
return (
<FilePreviewLink name={name} url={url} media_type={media_type} title={name} className="block">
<FilePreviewLink name={name} url={url} media_type={media_type} gallery={gallery} title={name} className="block">
<Img
src={thumbnail_url || url}
alt={name}
@@ -1,5 +1,6 @@
import Row from "@moduletrace/twui/layout/Row";
import type { BotMessageAttachment } from "@/src/types";
import imagePreviewGallery from "@/src/utils/image-preview-gallery";
import MessageAttachment from "./message-attachment";
type Props = {
@@ -7,15 +8,18 @@ type Props = {
};
/**
* A message's files, right-aligned above its bubble.
* A message's files, right-aligned above its bubble. Its images make one
* gallery, so opening one steps through the others.
*/
export default function MessageAttachments({ attachments }: Props) {
if (!attachments?.length) return null;
const gallery = imagePreviewGallery({ items: attachments });
return (
<Row className="max-w-[80%] gap-2! justify-end">
{attachments.map((attachment) => (
<MessageAttachment key={attachment.id} {...attachment} />
<MessageAttachment key={attachment.id} {...attachment} gallery={gallery} />
))}
</Row>
);
@@ -0,0 +1,29 @@
import Span from "@moduletrace/twui/layout/Span";
import { AppData } from "@/src/data/app-data";
import type { BotMessageWithAttachments } from "@/src/types";
import toolLogCount from "@/src/utils/tool-log-count";
type Props = {
message: Pick<BotMessageWithAttachments, "author" | "text" | "tool_log">;
};
/**
* "No tools used" under a long bot message whose run called no tool, in
* the row beside its timestamp: such a message can only say what the bot
* already knew, so a report of work in it wasn't done. A bot wrote a
* contest scan with links and a file in one, and the user acted on it.
*/
export default function MessageNoToolsChip({ message }: Props) {
if (message.author != "bot") return null;
if ((message.text || "").length < AppData.MessageNoToolsMinChars) return null;
if (toolLogCount({ tool_log: message.tool_log }) !== 0) return null;
return (
<Span
title="The app's record shows this message's run called no tools: nothing was browsed, saved or changed for it."
className="text-[11px] leading-4 text-ink-secondary whitespace-nowrap cursor-help"
>
No tools used
</Span>
);
}
@@ -0,0 +1,51 @@
import { useContext, useState } from "react";
import Button from "@moduletrace/twui/layout/Button";
import Span from "@moduletrace/twui/layout/Span";
import { ListChecks } from "lucide-react";
import TaskDetailModal from "@/src/components/general/task-detail-modal";
import { AppContext } from "@/src/pages/__root";
import canManageCrew from "@/src/utils/rbac/can-manage-crew";
type Props = {
task_id: number;
};
/**
* A task on the tracker named in a message (`taskRef`): a chip that opens
* the task in its own modal, read when it opens. One the user doesn't
* reach says so there.
*/
export default function TaskRefChip({ task_id }: Props) {
const { pageProps } = useContext(AppContext);
const [open, setOpen] = useState(false);
const [title, setTitle] = useState<string>();
const [deleted, setDeleted] = useState(false);
const label = title ? `#${task_id} ${title}` : `Task ${task_id}`;
return (
<>
<Button
type="button"
variant="ghost"
title={deleted ? "This task was deleted" : "Open the task"}
disabled={deleted}
onClick={() => setOpen(true)}
className="inline-flex h-6 max-w-full gap-1.5! flex-nowrap items-center px-1.5! py-0! align-middle rounded-default-xs border-0 bg-sunken text-[13px] font-bold leading-4 text-ink whitespace-nowrap hover:opacity-80 [&_.twui-button-content-wrapper]:min-w-0"
>
<ListChecks size={13} aria-hidden className="shrink-0" />
<Span className="min-w-0 truncate">{deleted ? `Task ${task_id} (deleted)` : label}</Span>
</Button>
<TaskDetailModal
task={open ? { id: task_id } : null}
can_manage={canManageCrew({ user_types: pageProps?.user_types })}
onClose={() => setOpen(false)}
onLoaded={({ task }) => setTitle(task.title || undefined)}
onChanged={({ task }) => setTitle(task.title || undefined)}
onDeleted={() => {
setDeleted(true);
setOpen(false);
}}
/>
</>
);
}
@@ -5,6 +5,7 @@ import { AppContext } from "@/src/pages/__root";
import SettingsShell from "@/src/pages/admin/settings/(partials)/settings-shell";
import ChatroomRetryButton from "@/src/components/general/chatroom-retry-button";
import { CrewBotsContext } from "@/src/pages/admin/bots/[bot_id]/(data)/crew-bots-context";
import { CrewWorkspacesContext } from "@/src/pages/admin/bots/[bot_id]/(data)/crew-workspaces-context";
import type { BUN_SQLITE_COBBLE_BOT_MESSAGES } from "@/db/types/db";
import type { ChatroomSummary } from "@/src/types";
import chatroomStatusLine from "@/src/utils/chatroom-status-line";
@@ -35,45 +36,47 @@ export default function ChatroomBody({ chatroom, messages }: Props) {
return (
<CrewBotsContext.Provider value={pageProps?.bots || []}>
<SettingsShell
title={room.title || "Chatroom"}
description={`${chatroomStatusLine(room)}. A request between bots, through the coordinator. Read-only.`}
action={
can_stop ? (
<ChatroomStopButton chatroom_id={Number(room.id)} />
) : (
<ChatroomRetryButton chatroom={room} />
)
}
no_trail={Boolean(room.workspace_id)}
>
<Row className="w-full gap-x-6! gap-y-2! py-5 items-center">
{room.bots.map((bot) => (
<ChatroomBotsRow
key={bot.id}
bot={bot}
part={
bot.id == room.requester_bot_id
? "asked"
: bot.kind == "coordinator"
? "passes it on"
: "was asked"
}
/>
))}
</Row>
<Stack className="w-full gap-6! items-stretch py-2">
{thread.map((message) => (
<ChatroomMessageRow
key={message.id}
message={message}
bot={bots.get(Number(message.bot_id)) || null}
/>
))}
<ChatroomOutcome chatroom={room} />
<ChatroomStatus room={room} />
</Stack>
</SettingsShell>
<CrewWorkspacesContext.Provider value={pageProps?.workspaces || []}>
<SettingsShell
title={room.title || "Chatroom"}
description={`${chatroomStatusLine(room)}. A request between bots, through the coordinator. Read-only.`}
action={
can_stop ? (
<ChatroomStopButton chatroom_id={Number(room.id)} />
) : (
<ChatroomRetryButton chatroom={room} />
)
}
no_trail={Boolean(room.workspace_id)}
>
<Row className="w-full gap-x-6! gap-y-2! py-5 items-center">
{room.bots.map((bot) => (
<ChatroomBotsRow
key={bot.id}
bot={bot}
part={
bot.id == room.requester_bot_id
? "asked"
: bot.kind == "coordinator"
? "passes it on"
: "was asked"
}
/>
))}
</Row>
<Stack className="w-full gap-6! items-stretch py-2">
{thread.map((message) => (
<ChatroomMessageRow
key={message.id}
message={message}
bot={bots.get(Number(message.bot_id)) || null}
/>
))}
<ChatroomOutcome chatroom={room} />
<ChatroomStatus room={room} />
</Stack>
</SettingsShell>
</CrewWorkspacesContext.Provider>
</CrewBotsContext.Provider>
);
}
@@ -1,14 +1,16 @@
import { useMemo } from "react";
import H2 from "@moduletrace/twui/layout/H2";
import Row from "@moduletrace/twui/layout/Row";
import Span from "@moduletrace/twui/layout/Span";
import Stack from "@moduletrace/twui/layout/Stack";
import type { StorageFolderPayload, StorageSpecOption } from "@/src/types";
import type { StorageSpec } from "@/src/utils/storage-volumes";
import { emptyFolderText, folderSummary } from "../(functions)/folder-text";
import FilesBreadcrumbRow from "../(partials)/files-breadcrumb-row";
import FilesSearchInput from "../(partials)/files-search-input";
import { emptyFolderText, folderSummary } from "@/src/utils/folder-text";
import imagePreviewGallery from "@/src/utils/image-preview-gallery";
import FilesBreadcrumbRow from "@/src/components/general/files-breadcrumb-row";
import FilesSearchInput from "@/src/components/general/files-search-input";
import FilesVolumeRow from "../(partials)/files-volume-row";
import StorageEntryRow from "../(partials)/storage-entry-row";
import StorageEntryRow from "@/src/components/general/storage-entry-row";
import Divider from "@moduletrace/twui/layout/Divider";
import Paper from "@moduletrace/twui/elements/Paper";
@@ -42,6 +44,11 @@ export default function FilesBrowser({
onOpenFolder,
onOpenVolume,
}: Props) {
const gallery = useMemo(
() => imagePreviewGallery({ items: (folder?.entries || []).map((entry) => ({ ...entry, url: entry.url || "" })) }),
[folder],
);
return (
<Row className="w-full mt-6 gap-6! flex-wrap items-start lg:flex-nowrap">
<Stack className="w-full lg:w-[180px] shrink-0 items-stretch">
@@ -98,6 +105,7 @@ export default function FilesBrowser({
entry.kind == "folder" &&
entry.path == path
}
gallery={gallery}
onOpenFolder={onOpenFolder}
/>
))
@@ -3,7 +3,7 @@ import useDebouncedValue from "@/src/hooks/use-debounced-value";
import { AppContext } from "@/src/pages/__root";
import type { StorageSpecOption } from "@/src/types";
import { parseStorageSpec, type StorageSpec } from "@/src/utils/storage-volumes";
import useStorageFolder from "../(hooks)/use-storage-folder";
import useStorageFolder from "@/src/hooks/use-storage-folder";
import FilesBrowser from "./files-browser";
/**
@@ -0,0 +1,18 @@
import { describe, expect, test } from "bun:test";
import { renderToString } from "react-dom/server";
import WorkspaceAboutGroup from "./workspace-about-group";
describe("WorkspaceAboutGroup", () => {
test("shows the refs in the context as chips, not as written", () => {
const html = renderToString(
<WorkspaceAboutGroup
workspace={{ id: 4, name: "Launch", system_prompt: "Ask [bot:2] first, then see [task:20]." }}
/>,
);
expect(html).not.toContain("[bot:2]");
expect(html).not.toContain("[task:20]");
expect(html).toContain("bot 2");
expect(html).toContain("Task 20");
});
});
@@ -1,3 +1,4 @@
import { useContext } from "react";
import Markdown from "react-markdown";
import remarkGfm from "remark-gfm";
import Row from "@moduletrace/twui/layout/Row";
@@ -5,8 +6,18 @@ import Span from "@moduletrace/twui/layout/Span";
import Stack from "@moduletrace/twui/layout/Stack";
import type { BUN_SQLITE_COBBLE_WORKSPACES } from "@/db/types/db";
import WorkspaceAvatar from "@/src/components/general/workspace-avatar";
import { AppContext } from "@/src/pages/__root";
import { CrewBotsContext } from "@/src/pages/admin/bots/[bot_id]/(data)/crew-bots-context";
import { CrewWorkspacesContext } from "@/src/pages/admin/bots/[bot_id]/(data)/crew-workspaces-context";
import { MessageMarkdownComponents } from "@/src/pages/admin/bots/[bot_id]/(data)/message-markdown-components";
import SettingsGroup from "@/src/pages/admin/settings/(partials)/settings-group";
import linkComputerRefs from "@/src/utils/link-computer-refs";
/**
* Kept module-level: a new array on every render makes `react-markdown`
* parse the context again.
*/
const RemarkPlugins = [remarkGfm];
type Props = {
workspace: BUN_SQLITE_COBBLE_WORKSPACES;
@@ -14,9 +25,11 @@ type Props = {
/**
* What the workspace is: its picture, name, what it's for, and the context
* every bot working here gets.
* every bot working here gets, its refs (`[bot:ID]`, `[task:ID]`, ...) shown
* as the chips a conversation shows.
*/
export default function WorkspaceAboutGroup({ workspace }: Props) {
const { pageProps } = useContext(AppContext);
const name = workspace.name || "Workspace";
const context = workspace.system_prompt?.trim();
@@ -41,14 +54,15 @@ export default function WorkspaceAboutGroup({ workspace }: Props) {
</Stack>
</Row>
{context ? (
<Stack className="gap-3! items-stretch min-w-0">
<Markdown
remarkPlugins={[remarkGfm]}
components={MessageMarkdownComponents}
>
{context}
</Markdown>
</Stack>
<CrewBotsContext.Provider value={pageProps?.workspace_bots || []}>
<CrewWorkspacesContext.Provider value={pageProps?.workspaces || []}>
<Stack className="gap-3! items-stretch min-w-0">
<Markdown remarkPlugins={RemarkPlugins} components={MessageMarkdownComponents}>
{linkComputerRefs({ text: context })}
</Markdown>
</Stack>
</CrewWorkspacesContext.Provider>
</CrewBotsContext.Provider>
) : (
<Span className="text-[13px] leading-[18px] text-ink-secondary">
No context yet. Every bot here works from its own instructions alone.
+3
View File
@@ -27,6 +27,9 @@
@source not "../styles/**";
@source not "../utils/**";
@source not "../websocket/**";
/* Pages, hooks and types still name refs in their comments (`[task:ID]`), so
the ref forms themselves are never utilities, wherever they're written. */
@source not inline("[{bot,workspace,computer,file,folder,task,room,graphic,question,proposal,hook-proposal,secret,secret-request,take-over}:ID]");
/* Cobble design tokens (handoff `tokens/tokens.css`). Light on `:root`, dark
on `.dark` (twui's dark variant). Exposed to Tailwind in `@theme inline`. */
+12
View File
@@ -1427,6 +1427,18 @@ export type BotFileScopesPayload = {
/**
* One entry in a folder the files browser shows: a file or a subfolder.
*/
/**
* One file the preview can show: its name, where its bytes are, and what
* kind of media it is. A list of them is a preview's gallery (the images
* of a folder or a message), stepped through with Previous and Next.
*/
export type FilePreviewItem = {
name: string;
url: string;
media_type?: string | null;
size?: number;
};
export type StorageEntry = {
name: string;
/**
+30
View File
@@ -0,0 +1,30 @@
import { describe, expect, test } from "bun:test";
import claimsWorkUnderWay from "./claims-work-under-way";
describe("claimsWorkUnderWay", () => {
test("catches the lines replies wrote before made-up results", () => {
for (const text of [
"I'm browsing the open contests on your account now, filtering for ones that fit your style.",
"I'm scanning the open contests now with a fresh list. When it's back, I'll create proper tasks.",
"I'm running the scan for real now: one pass over the open-contest listing.",
"I'm reading contest #1's full brief in the background right now.",
"Creating tasks now. Report follows in the next message.",
"I'll report back with the links once that run completes.",
"I’m checking your inbox now.",
]) {
expect(claimsWorkUnderWay({ text })).toBe(true);
}
});
test("leaves answers that only report or offer alone", () => {
for (const text of [
"Done. Task #20 is cancelled with a note.",
"Want me to start on contest 2 now?",
"I'm sorry, that contest isn't open any more.",
"I checked the board: 3 web design contests are open.",
"Right now there are 147 open contests.",
]) {
expect(claimsWorkUnderWay({ text })).toBe(false);
}
});
});
+27
View File
@@ -0,0 +1,27 @@
type Params = {
text: string;
};
/**
* How an answer says work is going on after it, or that a report will
* follow: the line a reply writes once it started a run ("I'm browsing
* the open contests now. I'll report back."). Written without starting
* one, it was followed by results made up on the spot.
*/
const UnderWayPatterns = [
/\bI(?:'|’)m\s+(?:now\s+)?[a-z]+ing\b[^.!?\n]{0,160}\bnow\b/i,
/\bin the background\b/i,
/\bI(?:'|’)ll\s+(?:report back|get back to you|let you know when|bring (?:you |it )?back|report (?:the|my) (?:results?|findings))/i,
/\b(?:report|results?|details|update)\s+(?:follows|will follow|to follow|coming)\b/i,
/\bin (?:my|the|a) (?:next|following) message\b/i,
/\b(?:when|once) (?:it|that|the (?:run|scan|search|check))(?:'|’)?s? (?:back|done|finished|complete)\b/i,
];
/**
* True when the answer says work is under way beyond it or that a report
* will follow (`UnderWayPatterns`). Only a started run makes that true,
* so a reply that says it without one is sent back (`reviewBotReply`).
*/
export default function claimsWorkUnderWay({ text }: Params) {
return UnderWayPatterns.some((pattern) => pattern.test(text));
}
+46 -17
View File
@@ -2,25 +2,30 @@ import { describe, expect, test } from "bun:test";
import computerRunDirs, { computerWorkspaceRelative, resolveComputerPath } from "./computer-work-dirs";
const W = "/home/gem/workspace";
const H = "/home/cb-3/workspace";
describe("computerRunDirs", () => {
test("a worker gets its own folder, the user's inside it", () => {
test("a worker works in its kept folder at home, the user's inside it", () => {
const dirs = computerRunDirs({ bot_id: 3, user_id: 7 });
expect(dirs.cwd).toBe(`${W}/bots/3/users/7`);
expect(dirs.roots).toEqual([`${W}/bots/3`]);
expect(dirs.cwd).toBe(`${H}/users/7`);
expect(dirs.bot_dir).toBe(H);
expect(dirs.roots).toEqual([H]);
expect(dirs.shared_dir).toBeNull();
});
test("in a workspace the shared folder joins", () => {
test("in a workspace the shared folder joins, inside its own", () => {
const dirs = computerRunDirs({ bot_id: 3, user_id: 7, workspace_id: 2 });
expect(dirs.roots).toEqual([`${W}/bots/3`, `${W}/workspaces/2`]);
expect(dirs.shared_dir).toBe(`${H}/workspaces/2`);
expect(dirs.roots).toEqual([H, `${H}/workspaces/2`]);
});
test("the coordinator reaches the whole workspace", () => {
const dirs = computerRunDirs({ bot_id: 1, bot_kind: "coordinator", user_id: 1 });
test("the coordinator works in the computer's workspace and reaches all of it", () => {
const dirs = computerRunDirs({ bot_id: 1, bot_kind: "coordinator", user_id: 1, workspace_id: 2 });
expect(dirs.cwd).toBe(`${W}/bots/1/users/1`);
expect(dirs.shared_dir).toBe(`${W}/workspaces/2`);
expect(dirs.roots).toEqual([W]);
});
@@ -35,27 +40,41 @@ describe("resolveComputerPath", () => {
const dirs = computerRunDirs({ bot_id: 3, user_id: 7, workspace_id: 2 });
test("relative paths and ~ land in the user's folder", () => {
expect(resolveComputerPath({ path: "seo/raw", dirs })).toBe(`${W}/bots/3/users/7/seo/raw`);
expect(resolveComputerPath({ path: "~/a.txt", dirs })).toBe(`${W}/bots/3/users/7/a.txt`);
expect(resolveComputerPath({ path: "~", dirs })).toBe(`${W}/bots/3/users/7`);
expect(resolveComputerPath({ path: "", dirs })).toBe(`${W}/bots/3/users/7`);
expect(resolveComputerPath({ path: "seo/raw", dirs })).toBe(`${H}/users/7/seo/raw`);
expect(resolveComputerPath({ path: "~/a.txt", dirs })).toBe(`${H}/users/7/a.txt`);
expect(resolveComputerPath({ path: "~", dirs })).toBe(`${H}/users/7`);
expect(resolveComputerPath({ path: "", dirs })).toBe(`${H}/users/7`);
});
test("absolute paths inside the roots pass", () => {
expect(resolveComputerPath({ path: `${W}/bots/3/notes.md`, dirs })).toBe(`${W}/bots/3/notes.md`);
expect(resolveComputerPath({ path: `${W}/workspaces/2/x/`, dirs })).toBe(`${W}/workspaces/2/x`);
expect(resolveComputerPath({ path: `${H}/notes.md`, dirs })).toBe(`${H}/notes.md`);
expect(resolveComputerPath({ path: `${H}/workspaces/2/x/`, dirs })).toBe(`${H}/workspaces/2/x`);
expect(resolveComputerPath({ path: "workspaces/2", dirs: computerRunDirs({ bot_id: 3, user_id: 7, workspace_id: 2 }) })).toBe(
`${H}/users/7/workspaces/2`,
);
});
test("the real paths they link to pass too, given back as the bot sees them", () => {
expect(resolveComputerPath({ path: `${W}/bots/3/users/7/a`, dirs })).toBe(`${H}/users/7/a`);
expect(resolveComputerPath({ path: `${W}/workspaces/2/x`, dirs })).toBe(`${H}/workspaces/2/x`);
});
test("anything outside is refused", () => {
for (const path of [
"/home/gem/x.txt",
"/home/cb-3/.cobble/env",
"/home/cb-3",
"/etc/passwd",
"../../../4/a",
"../8/secret",
"../../..",
`${W}/bots/4`,
"/home/cb-4/workspace",
`${H}/users/8/a`,
`${W}/bots/3/users/8/a`,
`${W}/bots/30`,
`${W}/workspaces/5`,
`${H}/workspaces/5`,
"~/../../../../x",
"a\0b",
]) {
@@ -63,19 +82,29 @@ describe("resolveComputerPath", () => {
}
});
test("the bot-wide folder and its users folder itself pass", () => {
expect(resolveComputerPath({ path: "..", dirs })).toBe(`${W}/bots/3/users`);
expect(resolveComputerPath({ path: "../..", dirs })).toBe(`${W}/bots/3`);
test("outside a workspace no workspace folder is the run's", () => {
const alone = computerRunDirs({ bot_id: 3, user_id: 7 });
expect(() => resolveComputerPath({ path: `${H}/workspaces/2`, dirs: alone })).toThrow();
});
test("the coordinator reaches any bot's folder", () => {
test("the bot-wide folder and its users folder itself pass", () => {
expect(resolveComputerPath({ path: "..", dirs })).toBe(`${H}/users`);
expect(resolveComputerPath({ path: "../..", dirs })).toBe(H);
});
test("the coordinator reaches any bot's folder, by either spelling", () => {
const coordinator = computerRunDirs({ bot_id: 1, bot_kind: "coordinator", user_id: 1 });
expect(resolveComputerPath({ path: `${W}/bots/3/report.md`, dirs: coordinator })).toBe(`${W}/bots/3/report.md`);
expect(resolveComputerPath({ path: `${H}/report.md`, dirs: coordinator })).toBe(`${W}/bots/3/report.md`);
expect(() => resolveComputerPath({ path: "/home/gem/.config", dirs: coordinator })).toThrow();
expect(() => resolveComputerPath({ path: "/home/cb-3/.cobble", dirs: coordinator })).toThrow();
});
test("workspace-relative names", () => {
expect(computerWorkspaceRelative({ absolute: `${W}/bots/3/users/7/seo` })).toBe("bots/3/users/7/seo");
expect(computerWorkspaceRelative({ absolute: `${H}/users/7/seo` })).toBe("bots/3/users/7/seo");
expect(computerWorkspaceRelative({ absolute: `${H}/workspaces/2/x` })).toBe("workspaces/2/x");
});
});
+70 -29
View File
@@ -1,11 +1,17 @@
import path from "node:path";
import { AppData } from "@/src/data/app-data";
import AppError from "@/src/utils/app-error";
import computerWorkerAccount from "@/src/utils/computer-worker-account";
import computerWorkspacePath from "@/src/utils/computer-workspace-path";
/**
* Where one run may work on a computer, every path absolute inside the
* computer's workspace (`AppData.ComputerWorkspaceDir`, the only directory
* mounted from the data volume).
* Where one run may work on a computer, every path absolute and as the run
* sees it. Only the computer's workspace (`AppData.ComputerWorkspaceDir`)
* is mounted from the data volume. A worker sees its folders through its
* own home: `/home/cb-<bot>/workspace` is a link to `bots/<bot>` in the
* workspace, and `workspaces/<id>` in it a link to the workspace's shared
* folder (`computerWorkspacePath` turns either spelling into the real
* one). The coordinator works in the workspace itself.
*/
export type ComputerRunDirs = {
/**
@@ -13,16 +19,18 @@ export type ComputerRunDirs = {
*/
workspace: string;
/**
* Where the run starts and where a relative path lands: the user's
* folder in the bot's (`bots/<bot>/users/<user>`).
* Where the run starts, its `HOME`, and where a relative path lands:
* the user's folder in the bot's (`users/<user>`).
*/
cwd: string;
/**
* The bot's own folder (`bots/<bot>`).
* The bot's own folder: a worker's `/home/cb-<bot>/workspace`, the
* coordinator's `bots/<bot>` in the workspace.
*/
bot_dir: string;
/**
* The workspace's shared folder (`workspaces/<id>`), in a workspace.
* The workspace's shared folder, in a workspace: a worker's
* `workspaces/<id>` inside its own, the coordinator's in the workspace.
*/
shared_dir: string | null;
/**
@@ -62,9 +70,11 @@ type Params = {
/**
* The folders a run works in on a computer: the user's own inside the
* bot's (`bots/<bot>/users/<user>`, where it starts), the bot's own
* (`bots/<bot>`, for work that is the same for every user) and, in a
* workspace, the folder its bots share (`workspaces/<id>`).
* bot's (`users/<user>`, where it starts), the bot's own (for work that is
* the same for every user) and, in a workspace, the folder its bots share.
* A worker's are under `/home/cb-<bot>/workspace` (its account's home
* stays in the container, only that folder is kept); the coordinator's
* are in the computer's workspace (`bots/<bot>`, `workspaces/<id>`).
*/
export default function computerRunDirs({
bot_id,
@@ -73,10 +83,14 @@ export default function computerRunDirs({
workspace_id,
}: Params): ComputerRunDirs {
const workspace = AppData.ComputerWorkspaceDir;
const bot_dir = path.posix.join(workspace, "bots", String(Number(bot_id)));
const is_coordinator = bot_kind == "coordinator";
const in_workspace = Number(workspace_id) > 0;
const bot_dir = is_coordinator
? path.posix.join(workspace, "bots", String(Number(bot_id)))
: computerWorkerAccount({ bot_id }).workspace;
const cwd = path.posix.join(bot_dir, "users", String(Number(user_id)));
const shared_dir = Number(workspace_id) > 0
? path.posix.join(workspace, "workspaces", String(Number(workspace_id)))
const shared_dir = in_workspace
? path.posix.join(is_coordinator ? workspace : bot_dir, "workspaces", String(Number(workspace_id)))
: null;
return {
@@ -84,13 +98,11 @@ export default function computerRunDirs({
cwd,
bot_dir,
shared_dir,
roots: bot_kind == "coordinator"
? [workspace]
: [bot_dir, ...(shared_dir ? [shared_dir] : [])],
roots: is_coordinator ? [workspace] : [bot_dir, ...(shared_dir ? [shared_dir] : [])],
user_id: Number(user_id),
run_as: bot_kind == "coordinator"
run_as: is_coordinator
? null
: { bot_id: Number(bot_id), workspace_id: Number(workspace_id) > 0 ? Number(workspace_id) : null },
: { bot_id: Number(bot_id), workspace_id: in_workspace ? Number(workspace_id) : null },
};
}
@@ -105,8 +117,11 @@ export function isInsideDir({ parent, child }: { parent: string; child: string }
* Turns a path a bot gave a computer tool into the absolute one it means,
* only when it is one of the run's: a relative path (or `~`, which the
* run's shells read as its folder) lands in `cwd`, an absolute one must be
* inside `roots`, and another user's folder in a bot's is refused. Throws
* an `AppError` the bot gets back as the tool's error.
* inside `roots`, and another user's folder in a bot's is refused. Checked
* on the real path (`computerWorkspacePath`), so a worker may also give
* one under the computer's workspace (what `pwd -P` or a script's own cwd
* prints), and returned as the run sees it (`computerRunPath`). Throws an
* `AppError` the bot gets back as the tool's error.
*/
export function resolveComputerPath({
path: requested,
@@ -130,22 +145,47 @@ export function resolveComputerPath({
: path.posix.join(dirs.cwd, raw || "."),
).replace(/(.)\/+$/, "$1");
if (!isComputerPathAllowed({ absolute, dirs })) {
const real = computerWorkspacePath({ absolute });
if (!isComputerPathAllowed({ real, dirs })) {
throw new AppError(
`${absolute} is outside your folders on this computer. Work in ${dirs.cwd} (this user's), ${dirs.roots.join(" or ")} for work every user shares.`,
);
}
return absolute;
return computerRunPath({ real, dirs });
}
/**
* Whether an absolute, normalized path is one the run may touch.
* A real path on the computer (`computerWorkspacePath`) as the run sees
* it: for a worker, its folder and the workspace's shared one through its
* own home (`/home/cb-<bot>/workspace/...`).
*/
function isComputerPathAllowed({ absolute, dirs }: { absolute: string; dirs: ComputerRunDirs }) {
if (!dirs.roots.some((root) => isInsideDir({ parent: root, child: absolute }))) return false;
export function computerRunPath({ real, dirs }: { real: string; dirs: ComputerRunDirs }) {
if (!dirs.run_as) return real;
const relative = path.posix.relative(dirs.workspace, absolute).split("/");
for (const dir of [dirs.shared_dir, dirs.bot_dir]) {
if (!dir) continue;
const dir_real = computerWorkspacePath({ absolute: dir });
if (isInsideDir({ parent: dir_real, child: real })) {
return `${dir}${real.slice(dir_real.length)}`;
}
}
return real;
}
/**
* Whether a real, normalized path is one the run may touch.
*/
function isComputerPathAllowed({ real, dirs }: { real: string; dirs: ComputerRunDirs }) {
const roots = dirs.roots.map((root) => computerWorkspacePath({ absolute: root }));
if (!roots.some((root) => isInsideDir({ parent: root, child: real }))) return false;
const relative = path.posix.relative(dirs.workspace, real).split("/");
/**
* `bots/<bot>/users/<user>/...`: only the run's own user.
@@ -158,9 +198,10 @@ function isComputerPathAllowed({ absolute, dirs }: { absolute: string; dirs: Com
}
/**
* A path inside the computer's workspace as a folder ref or the files
* browser names it: relative to the workspace root, no leading slash.
* A path inside the computer's workspace as the files browser names it:
* relative to the workspace root, no leading slash. A worker's
* `/home/cb-<bot>/workspace/...` is read as the real path it links to.
*/
export function computerWorkspaceRelative({ absolute }: { absolute: string }) {
return path.posix.relative(AppData.ComputerWorkspaceDir, absolute);
return path.posix.relative(AppData.ComputerWorkspaceDir, computerWorkspacePath({ absolute }));
}
+5 -2
View File
@@ -1,10 +1,13 @@
/**
* A worker bot's own account on a computer, as the computer's agent makes
* it (`computer/agent/run-user-for.ts`; keep both alike): `cb-<bot id>`,
* without sudo, its home inside the container (the env files live there).
* without sudo. Its home stays inside the container (the env files live
* there); only `workspace` in it is kept, a link the agent makes to the
* bot's folder on the computer's mounted workspace (`bots/<bot id>`).
*/
export default function computerWorkerAccount({ bot_id }: { bot_id: number | string }) {
const name = `cb-${Number(bot_id)}`;
const home = `/home/${name}`;
return { name, home: `/home/${name}` };
return { name, home, workspace: `${home}/workspace` };
}
+24
View File
@@ -0,0 +1,24 @@
import { describe, expect, test } from "bun:test";
import computerWorkspacePath from "./computer-workspace-path";
const W = "/home/gem/workspace";
describe("computerWorkspacePath", () => {
test("a worker's kept folder is the bot's folder in the workspace", () => {
expect(computerWorkspacePath({ absolute: "/home/cb-3/workspace" })).toBe(`${W}/bots/3`);
expect(computerWorkspacePath({ absolute: "/home/cb-3/workspace/users/7/a/" })).toBe(`${W}/bots/3/users/7/a`);
});
test("a workspace folder inside it is the shared one", () => {
expect(computerWorkspacePath({ absolute: "/home/cb-3/workspace/workspaces/2/x" })).toBe(`${W}/workspaces/2/x`);
expect(computerWorkspacePath({ absolute: `${W}/bots/3/workspaces/2` })).toBe(`${W}/workspaces/2`);
expect(computerWorkspacePath({ absolute: "/home/cb-3/workspace/workspaces" })).toBe(`${W}/bots/3/workspaces`);
});
test("the rest of a worker's home and other paths stay as they are", () => {
expect(computerWorkspacePath({ absolute: "/home/cb-3/.cobble/env" })).toBe("/home/cb-3/.cobble/env");
expect(computerWorkspacePath({ absolute: "/home/cb-3/workspace2" })).toBe("/home/cb-3/workspace2");
expect(computerWorkspacePath({ absolute: `${W}/bots/3/users/7` })).toBe(`${W}/bots/3/users/7`);
expect(computerWorkspacePath({ absolute: "/home/cb-3/workspace/../../gem/x" })).toBe("/home/gem/x");
});
});
+42
View File
@@ -0,0 +1,42 @@
import { AppData } from "@/src/data/app-data";
/**
* The real place of an absolute path on a computer, inside its mounted
* workspace (`AppData.ComputerWorkspaceDir`). A worker sees its folders
* through its home: `/home/cb-<bot>/workspace` is a link to `bots/<bot>`,
* and `workspaces/<id>` inside that a link to the workspace's shared
* `workspaces/<id>`, so both spellings (and the shared folder reached
* through the bot's link) come out as the one real path. Anything else is
* returned normalized, as it is.
*/
export default function computerWorkspacePath({ absolute }: { absolute: string }) {
const workspace = AppData.ComputerWorkspaceDir;
const normal = normalizeAbsolute({ absolute });
const home = normal.match(/^\/home\/cb-(\d+)\/workspace(\/.*)?$/);
const real = home ? `${workspace}/bots/${Number(home[1])}${home[2] || ""}` : normal;
const shared = real.match(new RegExp(`^${escapeRegExp(workspace)}/bots/\\d+/workspaces/(\\d+)(/.*)?$`));
return shared ? `${workspace}/workspaces/${Number(shared[1])}${shared[2] || ""}` : real;
}
/**
* `path.posix.normalize` for an absolute path, without `node:path` (folder
* refs read this in the browser): `.` and `..` resolved, slashes merged,
* no trailing one.
*/
function normalizeAbsolute({ absolute }: { absolute: string }) {
const segments: string[] = [];
for (const segment of absolute.split("/")) {
if (!segment || segment == ".") continue;
if (segment == "..") segments.pop();
else segments.push(segment);
}
return `/${segments.join("/")}`;
}
function escapeRegExp(text: string) {
return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
+1
View File
@@ -87,6 +87,7 @@ function wordRefs({
.replace(/\[secret-request:(\d+)\](?!\()/g, "(secret request $1)")
.replace(/\[question:(\d+)\](?!\()/g, "(questions $1)")
.replace(/\[graphic:(\d+)\](?!\()/g, "(graphic $1)")
.replace(/\[task:(\d+)\](?!\()/g, "task #$1")
.replace(/\[file:(\d+)\](?!\()/g, "file $1")
.replace(/\[folder:[a-z]+:\d+:([^\]\n]+)\](?!\()/g, "`$1`")
.replace(/\[folder:([a-z]+):(\d+)\](?!\()/g, "the $1 $2 folder");
+19
View File
@@ -105,3 +105,22 @@ describe("linkComputerRefs", () => {
expect(parseFolderRefHref({ href: linked.match(/\((#file-[^)]+)\)/)?.[1] })).toBeNull();
});
});
describe("computer folder refs written as the bot sees them", () => {
test("a worker's kept folder and the computer's workspace open their real place", () => {
const open = (path: string) => parseFolderRefHref({ href: folderRefHref({ volume: "computer", owner_id: 3, path }) })?.path;
expect(open("/home/cb-7/workspace/users/1/seo")).toBe("bots/7/users/1/seo");
expect(open("home/cb-7/workspace/workspaces/2/brief")).toBe("workspaces/2/brief");
expect(open("/home/gem/workspace/bots/7/notes")).toBe("bots/7/notes");
expect(open("/home/gem/workspace")).toBe("");
expect(open("bots/7/users/1")).toBe("bots/7/users/1");
expect(open("seo/raw")).toBe("seo/raw");
});
test("other volumes keep the path as written", () => {
expect(parseFolderRefHref({ href: folderRefHref({ volume: "bot", owner_id: 3, path: "home/cb-7/workspace" }) })?.path).toBe(
"home/cb-7/workspace",
);
});
});
+21 -2
View File
@@ -9,6 +9,8 @@
* (`fileRef`), which is what downloads. There is no guessing from the
* name's extension: the ref says which one it is.
*/
import { AppData } from "@/src/data/app-data";
import computerWorkspacePath from "./computer-workspace-path";
import {
isStorageVolume,
parseStorageSpec,
@@ -38,6 +40,23 @@ function cleanPath({ path }: { path?: string | null }) {
return (path || "").trim().replace(/^\/+|\/+$/g, "");
}
/**
* A path in a folder ref, as the files browser names it. On a computer a
* bot may write the folder as it sees it there (`/home/cb-3/workspace/...`,
* `/home/gem/workspace/...`): that becomes its real place in the
* computer's workspace (`computerWorkspacePath`), relative to it.
*/
function refPath({ volume, path }: { volume: string; path: string }) {
if (volume != "computers") return path;
const workspace = AppData.ComputerWorkspaceDir;
const real = computerWorkspacePath({ absolute: `/${path}` });
if (real == workspace) return "";
return real.startsWith(`${workspace}/`) ? real.slice(workspace.length + 1) : path;
}
/**
* How a bot names a folder in a message. The path is written as it is; the
* chat encodes it into the link.
@@ -91,7 +110,7 @@ export function parseFolderRefHref({
return {
spec: { volume, owner_id: Math.trunc(owner_id) },
path: rest.join(":").replace(/^\/+|\/+$/g, ""),
path: refPath({ volume, path: rest.join(":").replace(/^\/+|\/+$/g, "") }),
};
}
@@ -114,5 +133,5 @@ export function folderRefUrl({ volume, owner_id, path }: RefParams) {
if (!spec) return StorageBrowserPath;
return storageSpecHref({ spec, path });
return storageSpecHref({ spec, path: refPath({ volume: known, path: cleanPath({ path }) }) });
}
+11
View File
@@ -0,0 +1,11 @@
import type { FilePreviewItem } from "@/src/types";
/**
* Where a file stands in a gallery, by its URL, or -1 when it isn't in it
* (the preview then shows it alone, without Previous and Next).
*/
export default function galleryIndex({ gallery, url }: { gallery?: FilePreviewItem[]; url: string }) {
if (!gallery?.length || !url) return -1;
return gallery.findIndex((item) => item.url == url);
}
+24
View File
@@ -0,0 +1,24 @@
import { expect, test } from "bun:test";
import galleryIndex from "./gallery-index";
import imagePreviewGallery from "./image-preview-gallery";
const items = [
{ name: "notes.md", url: "/media/1" },
{ name: "shot-1.png", url: "/media/2" },
{ name: "raw", url: "" },
{ name: "photo", url: "/media/3", media_type: "image" },
{ name: "clip.mp4", url: "/media/4" },
{ name: "logo.svg", url: "/media/5" },
];
test("a gallery keeps only the images, in the folder's order", () => {
expect(imagePreviewGallery({ items }).map((item) => item.url)).toEqual(["/media/2", "/media/3", "/media/5"]);
});
test("a file is found in its gallery by its URL", () => {
const gallery = imagePreviewGallery({ items });
expect(galleryIndex({ gallery, url: "/media/3" })).toBe(1);
expect(galleryIndex({ gallery, url: "/media/1" })).toBe(-1);
expect(galleryIndex({ gallery: undefined, url: "/media/3" })).toBe(-1);
});
+15
View File
@@ -0,0 +1,15 @@
import type { FilePreviewItem } from "@/src/types";
import filePreviewKind from "./file-preview-kind";
/**
* The images in a list of files, in the list's order: what the preview
* steps through with Previous and Next. Files without a URL are left out,
* and so is every other kind (a gallery is for looking at pictures).
*/
export default function imagePreviewGallery({ items }: { items: FilePreviewItem[] }): FilePreviewItem[] {
return items.filter(
(item) =>
Boolean(item.url) &&
filePreviewKind({ name: item.name, media_type: item.media_type }) == "image",
);
}
+11
View File
@@ -0,0 +1,11 @@
import { ImageViewerMaxScale, ImageViewerMinScale } from "@/src/dict/image-viewer-dict";
/**
* A scale kept inside the viewer's range (a wheel or pinch can ask for
* anything).
*/
export default function imageViewerClampScale({ scale }: { scale: number }) {
if (!Number.isFinite(scale)) return 1;
return Math.min(ImageViewerMaxScale, Math.max(ImageViewerMinScale, scale));
}
+25
View File
@@ -0,0 +1,25 @@
import { ImageViewerTallRatio, type ImageViewerMode } from "@/src/dict/image-viewer-dict";
type Size = { width: number; height: number };
/**
* How a picture first opens: whole, unless it is far taller than the frame
* (a full-page screenshot), which opens at the frame's width so it reads
* from the top and scrolls down.
*/
export default function imageViewerDefaultMode({
natural,
frame,
}: {
natural: Size;
frame: Size;
}): Extract<ImageViewerMode, "fit" | "width"> {
if (natural.width <= 0 || natural.height <= 0) return "fit";
if (frame.width <= 0 || frame.height <= 0) return "fit";
const picture = natural.height / natural.width;
const window = frame.height / frame.width;
return picture > window * ImageViewerTallRatio ? "width" : "fit";
}
+28
View File
@@ -0,0 +1,28 @@
import type { ImageViewerMode } from "@/src/dict/image-viewer-dict";
type Size = { width: number; height: number };
type Params = {
mode: Exclude<ImageViewerMode, "custom">;
natural: Size;
frame: Size;
};
/**
* The scale a preset shows a picture at: whole (`fit`), filling the
* frame's width (`width`) or at its own size (`actual`). Neither fit
* enlarges a picture smaller than the frame: zooming in does that.
*/
export default function imageViewerFitScale({ mode, natural, frame }: Params) {
if (mode == "actual") return 1;
if (natural.width <= 0 || natural.height <= 0) return 1;
const frame_width = Math.max(1, frame.width);
const frame_height = Math.max(1, frame.height);
const by_width = frame_width / natural.width;
if (mode == "width") return Math.min(1, by_width);
return Math.min(1, by_width, frame_height / natural.height);
}
+25
View File
@@ -0,0 +1,25 @@
import {
ImageViewerMaxScale,
ImageViewerMinScale,
ImageViewerZoomSteps,
} from "@/src/dict/image-viewer-dict";
/**
* The next zoom stop in or out from a scale, so a fit at 37% zooms in to
* 50%, not 47%. Stays inside the viewer's range.
*/
export default function imageViewerZoomStep({
scale,
direction,
}: {
scale: number;
direction: "in" | "out";
}) {
const margin = 0.001;
if (direction == "in") {
return ImageViewerZoomSteps.find((step) => step > scale + margin) || ImageViewerMaxScale;
}
return [...ImageViewerZoomSteps].reverse().find((step) => step < scale - margin) || ImageViewerMinScale;
}
+36
View File
@@ -0,0 +1,36 @@
import { expect, test } from "bun:test";
import { ImageViewerMaxScale, ImageViewerMinScale } from "@/src/dict/image-viewer-dict";
import imageViewerClampScale from "./image-viewer-clamp-scale";
import imageViewerDefaultMode from "./image-viewer-default-mode";
import imageViewerFitScale from "./image-viewer-fit-scale";
import imageViewerZoomStep from "./image-viewer-zoom-step";
const frame = { width: 1000, height: 800 };
test("fit shows a big picture whole and never enlarges a small one", () => {
expect(imageViewerFitScale({ mode: "fit", natural: { width: 2000, height: 1000 }, frame })).toBe(0.5);
expect(imageViewerFitScale({ mode: "fit", natural: { width: 1000, height: 1600 }, frame })).toBe(0.5);
expect(imageViewerFitScale({ mode: "fit", natural: { width: 200, height: 100 }, frame })).toBe(1);
});
test("fit width fills the frame's width whatever the height", () => {
expect(imageViewerFitScale({ mode: "width", natural: { width: 2880, height: 20000 }, frame })).toBeCloseTo(1000 / 2880);
expect(imageViewerFitScale({ mode: "width", natural: { width: 400, height: 20000 }, frame })).toBe(1);
expect(imageViewerFitScale({ mode: "actual", natural: { width: 2880, height: 20000 }, frame })).toBe(1);
});
test("a full-page screenshot opens at the frame's width, a photo whole", () => {
expect(imageViewerDefaultMode({ natural: { width: 1440, height: 9000 }, frame })).toBe("width");
expect(imageViewerDefaultMode({ natural: { width: 4000, height: 3000 }, frame })).toBe("fit");
expect(imageViewerDefaultMode({ natural: { width: 0, height: 0 }, frame })).toBe("fit");
});
test("zoom steps move to the next stop and stay in range", () => {
expect(imageViewerZoomStep({ scale: 0.37, direction: "in" })).toBe(0.5);
expect(imageViewerZoomStep({ scale: 0.37, direction: "out" })).toBe(0.33);
expect(imageViewerZoomStep({ scale: 1, direction: "in" })).toBe(1.25);
expect(imageViewerZoomStep({ scale: ImageViewerMaxScale, direction: "in" })).toBe(ImageViewerMaxScale);
expect(imageViewerZoomStep({ scale: ImageViewerMinScale, direction: "out" })).toBe(ImageViewerMinScale);
expect(imageViewerClampScale({ scale: 100 })).toBe(ImageViewerMaxScale);
expect(imageViewerClampScale({ scale: Number.NaN })).toBe(1);
});
+1 -1
View File
@@ -69,7 +69,7 @@ export const SecretRequestRefHrefPrefix = "#secret-request-";
/**
* The kinds of ref a message can carry, as written before the colon.
*/
const RefKinds = "computer|take-over|bot|workspace|proposal|hook-proposal|secret|secret-request|question|graphic|room|file|folder";
const RefKinds = "computer|take-over|bot|workspace|proposal|hook-proposal|secret|secret-request|question|graphic|room|task|file|folder";
/**
* A code span holding nothing but one ref (`` `[file:12]` ``): bots often
+3 -1
View File
@@ -1,6 +1,7 @@
import { BotQuestionRefHrefPrefix } from "./bot-question-ref";
import { ChatroomRefHrefPrefix } from "./chatroom-ref";
import { GraphicRefHrefPrefix } from "./graphic-ref";
import { TaskRefHrefPrefix } from "./task-ref";
import {
BotRefHrefPrefix,
ComputerRefHrefPrefix,
@@ -21,7 +22,7 @@ import {
* (`[folder:computer:3:seo/raw]`), proposal ref (`[proposal:7]`) and hook
* proposal ref (`[hook-proposal:4]`), secret ref (`[secret:12]`) and secret
* request ref (`[secret-request:4]`), question ref (`[question:4]`), graphic ref (`[graphic:5]`) and
* chatroom ref (`[room:<id>]`) in a
* chatroom ref (`[room:<id>]`) and task ref (`[task:20]`) in a
* stretch of message text (never code) into a markdown link, so it
* survives markdown rendering as a link the chat can swap for a button,
* chip or download.
@@ -64,6 +65,7 @@ export default function linkRefsInText({ text }: { text: string }) {
)
.replace(/\[graphic:(\d+)\](?!\()/g, (_, id: string) => `[graphic ${id}](${GraphicRefHrefPrefix}${id})`)
.replace(/\[room:(\d+)\](?!\()/g, (_, id: string) => `[room ${id}](${ChatroomRefHrefPrefix}${id})`)
.replace(/\[task:(\d+)\](?!\()/g, (_, id: string) => `[task ${id}](${TaskRefHrefPrefix}${id})`)
.replace(/\[file:(\d+)\](?!\()/g, (_, id: string) => `[file ${id}](${FileRefHrefPrefix}${id})`)
.replace(/\[folder:([a-z]+):(\d+):([^\]\n]+)\](?!\()/g, (_, volume: string, owner: string, path: string) =>
`[${path}](${FolderRefHrefPrefix}${encodeURIComponent(`${volume}:${owner}:${path}`)})`,
+42
View File
@@ -0,0 +1,42 @@
import { describe, expect, test } from "bun:test";
import replyClaimProblems from "./reply-claim-problems";
const underWay = "I'm scanning the open contests now. When it's back, I'll create the tasks.";
describe("replyClaimProblems", () => {
test("faults work said to be under way when nothing was started or is open", () => {
const problems = replyClaimProblems({ text: underWay, tool_uses: [] });
expect(problems.length).toBe(1);
expect(problems[0]).toContain("start_task");
});
test("passes it once a run was started, handed over or a room asked, or one is open", () => {
for (const name of ["start_task", "delegate_task", "ask_crew"]) {
expect(replyClaimProblems({ text: underWay, tool_uses: [{ name, ok: true }] })).toEqual([]);
}
expect(replyClaimProblems({ text: underWay, tool_uses: [], has_open_work: true })).toEqual([]);
});
test("a start_task call that failed doesn't count", () => {
expect(replyClaimProblems({ text: underWay, tool_uses: [{ name: "start_task", ok: false }] }).length).toBe(1);
});
test("names files and tasks that don't exist", () => {
const problems = replyClaimProblems({
text: "Saved in [file:301]; see [task:20].",
tool_uses: [{ name: "list_tasks", ok: true }],
missing_file_ids: [301],
missing_task_ids: [20],
});
expect(problems.length).toBe(2);
expect(problems[0]).toContain("[file:301]");
expect(problems[1]).toContain("[task:20]");
});
test("an answer that holds up has no problems", () => {
expect(replyClaimProblems({ text: "Task #20 is cancelled.", tool_uses: [] })).toEqual([]);
});
});
+68
View File
@@ -0,0 +1,68 @@
import type { HarnessToolUse } from "@/src/harness/types";
import claimsWorkUnderWay from "./claims-work-under-way";
type Params = {
text: string;
/**
* Every tool call the reply made so far.
*/
tool_uses: HarnessToolUse[];
/**
* `[file:ID]` refs in the text that name no file the user can open.
*/
missing_file_ids?: number[];
/**
* `[task:ID]` refs in the text that name no task the user can open.
*/
missing_task_ids?: number[];
/**
* A run of the bot's, a job it handed over or a room it asked, still
* open from this conversation: its result is still to come.
*/
has_open_work?: boolean;
};
/**
* The tools whose work goes on after the reply and comes back to the
* conversation.
*/
const WorkStartingTools = ["start_task", "delegate_task", "ask_crew"];
/**
* What in a reply's answer the app's record contradicts: refs to files or
* tasks that don't exist, and work said to be under way or a report
* promised when nothing was started and nothing is open. Empty when the
* answer holds up. Bots wrote "I'm scanning the contests now" and the
* scan's results in one answer, with no tool called and a made-up file.
*/
export default function replyClaimProblems({
text,
tool_uses,
missing_file_ids = [],
missing_task_ids = [],
has_open_work,
}: Params): string[] {
const problems: string[] = [];
if (missing_file_ids.length) {
problems.push(
`It names ${missing_file_ids.map((id) => `[file:${id}]`).join(", ")}, but no such file exists. A file exists only once write_file, make_pdf, generate_image or import_file saved it; list_files shows what's there.`,
);
}
if (missing_task_ids.length) {
problems.push(
`It names ${missing_task_ids.map((id) => `[task:${id}]`).join(", ")}, which ${missing_task_ids.length == 1 ? "is" : "are"} no task the user can open (never created, or deleted). list_tasks shows what's there.`,
);
}
const started = tool_uses.some((use) => use.ok && WorkStartingTools.includes(use.name));
if (!started && !has_open_work && claimsWorkUnderWay({ text })) {
problems.push(
`It says work is under way or that a report will follow, but this reply started no run (start_task) and nothing of yours is open in this conversation. Nothing is running, so no result will come unless you call start_task now.`,
);
}
return problems;
}
+15
View File
@@ -0,0 +1,15 @@
import { describe, expect, test } from "bun:test";
import replyRefIds from "./reply-ref-ids";
describe("replyRefIds", () => {
test("reads each ref of the kind once, links and code spans included", () => {
const text = "Notes in [file:294](99designs/notes.md), scan in `[file:301]`, again [file:294]; [task:20] and [ task:21 ].";
expect(replyRefIds({ text, kind: "file" })).toEqual([294, 301]);
expect(replyRefIds({ text, kind: "task" })).toEqual([20]);
});
test("finds nothing in plain text", () => {
expect(replyRefIds({ text: "file 301 and task #20", kind: "file" })).toEqual([]);
});
});
+24
View File
@@ -0,0 +1,24 @@
type Params = {
text: string;
/**
* The ref's kind, as in `[file:12]` or `[task:20]`.
*/
kind: "file" | "task";
};
/**
* The ids of every `[<kind>:ID]` ref in a message, once each, in order:
* what a reply names, for checking each exists before it goes out.
*/
export default function replyRefIds({ text, kind }: Params): number[] {
const pattern = new RegExp(`\\[${kind}:\\s*(\\d+)\\s*\\]`, "gi");
const ids: number[] = [];
for (const match of text.matchAll(pattern)) {
const id = Number(match[1]);
if (Number.isInteger(id) && id > 0 && !ids.includes(id)) ids.push(id);
}
return ids;
}

Some files were not shown because too many files have changed in this diff Show More