Compare commits

..
6 Commits
Author SHA1 Message Date
tben 37bd3335ff Bump version to 0.19.0
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
2026-11-13 12:12:22 +01:00
tben 0a6d7d7410 Let a worker hand on a task of its own, and stop rooms closing over live work
A worker told to hand its tasks to another bot had no tool for it: it asked
the crew instead, the coordinator answered over the Software Engineer's
still-running job (closing the room cancels it), and the answer said the
tasks were picked up. Nothing had moved.

hand_over_task passes an open task of the worker's own list to a bot it
could already ask, reporting back in its session. answer_requester and
refuse_request now refuse over a live job unless close_anyway says
otherwise. ask_user and suggest_next_steps stay out of hidden sessions,
where no card exists to answer and a bare ref reached the coordinator.
2026-11-13 12:12:18 +01:00
tben 7a0e16a6b5 Show what a chatroom's bots spent, message by message and in total 2026-11-13 11:55:58 +01:00
tben 0885e12a8b Bump version to 0.18.10
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
2026-11-13 11:42:18 +01:00
tben 7da9003e7b Walk the user's earlier messages in the composer
Up recalls the message the user sent before (the newest from an empty
input, older ones from there), Down comes forward again and back to what
was being typed, a keystroke takes the input back, and an open mention
menu or a selection keeps the arrows. Only the user's own messages, never
a crew message.

A clear button (X, disabled while the input is empty) empties the text
without sending it, keeping the quote and the picked files.

The composer now reads ordered lists from digit markers only: Tiptap also
takes `a.` and `i.`, so a recalled "Ok. Do another pass on the browser."
came back as item 401 with "Ok." eaten as the marker, while the thread
(remark) always showed it as plain text.
2026-11-13 11:41:16 +01:00
tben b609d72888 Let a bot offer its next steps, one click from the input 2026-11-13 11:22:12 +01:00
84 changed files with 2627 additions and 114 deletions
+8 -7
View File
@@ -83,7 +83,7 @@ Enables SQLite foreign keys (`enableForeignKeys`), `bunextInit()`, `ensureDocker
### Bot types
`bot_types` extends `bots.kind` (worker | coordinator) the way `user_types` extends users (`src/dict/bot-types-dict.ts`): today only `workspace_admin`, each row naming its workspace (no row = just the kind; the coordinator is its kind, written only by `ensureCoordinatorBot`). A bot's role where it works is its kind plus the types it holds there (`botTypesIn`). `BotTypePermissionMatrix`, `BotTypeTargetMatrix` (keyed by role), `BotTypeAssignmentMatrix`/`DeletionMatrix` (types only) are read by the generic interpreter `src/utils/rbac/type-assignment.ts`. Every run reads `grabBotRunPowers` once and gates tools on its `is_coordinator`, `admin_workspace_ids` and `can(permission)`, never on its own check of `kind`. A run's powers are its role's AND its user's. Rows from v0.2.8 and earlier (`admin`, `coordinator`) are fixed at boot by `migrateBotTypes`. A workspace admin gets `grabWorkspaceAdminTools` (delegate to members, set their workspace instructions, edit that workspace). Set via `api/admin/bots/set-bot-type`. Admins are marked with `AdminShield` (green, beside the name, never on the stone).
`bot_types` extends `bots.kind` (worker | coordinator) the way `user_types` extends users (`src/dict/bot-types-dict.ts`): today only `workspace_admin`, each row naming its workspace (no row = just the kind; the coordinator is its kind, written only by `ensureCoordinatorBot`). A bot's role where it works is its kind plus the types it holds there (`botTypesIn`). `BotTypePermissionMatrix`, `BotTypeTargetMatrix` (keyed by role), `BotTypeAssignmentMatrix`/`DeletionMatrix` (types only) are read by the generic interpreter `src/utils/rbac/type-assignment.ts`. Every run reads `grabBotRunPowers` once and gates tools on its `is_coordinator`, `admin_workspace_ids` and `can(permission)`, never on its own check of `kind`. A run's powers are its role's AND its user's. Rows from v0.2.8 and earlier (`admin`, `coordinator`) are fixed at boot by `migrateBotTypes`. A workspace admin gets `grabWorkspaceAdminTools` (delegate to members, set their workspace instructions, edit that workspace). A plain worker gets no work to hand out, but may pass on an open task of its own to a bot it could ask (`hand_over_task`, `hand-over-task-tool.ts`): its one permission, its own list only, and `BotTypeTargetMatrix` is left alone so it still directs no one, the targets coming from `chatroomAskableBots`. Set via `api/admin/bots/set-bot-type`. Admins are marked with `AdminShield` (green, beside the name, never on the stone).
### Bots, sessions, chat
@@ -94,12 +94,13 @@ Enables SQLite foreign keys (`enableForeignKeys`), `bunextInit()`, `ensureDocker
- **No model:** while the bot has no text model there (`bot_text_model` null, kept live by the models modal), the thread shows `NoModelNotice` (centred when empty): super admins get Connect a provider / Guided setup, others are told the super admin sets it up.
- **Conversation loading:** pages render everything server-side (`grabConversationProps`) **except the history**, which the client loads (`api/admin/bots/conversation-history`, merged with what's already shown, refetched on bfcache restore) and pages older messages on scroll. Rail lists go through `railBots`/`railWorkspaces` (no prompts/memory, previews cut). Every return to the page (window focus, a hidden tab visible, back online: `use-refocus`, `AppData.RefocusGapMs`) reads the crew again (`use-live-crew-refresh` -> `api/admin/bots/live-crew` -> `cobble:live-crew-refreshed`, taken by `useLiveBots`/`useLiveWorkspaces`) and the session's latest messages plus its bot's face and task (`session-messages`, `use-reply-catch-up`), and the page polls the same while a reply is due (read with the live face, never the page's): pushes missed while the phone slept left threads thinking and faces stale until a reload. On a phone, pulling the thread up past its bottom lifts the newest message off the edge, opening just enough room for a lone refresh icon (a ghost button, no label; no deeper, however far the drag goes), and letting go only reloads once that full room has been held for half a second, which lights the icon (`AppData.PullToRefreshHoldMs`: an exhausted thread reaches the limit by accident too easily) and then turns it into its spinner for at least a second (`AppData.PullToRefreshMinLoadingMs`) while the conversation and the rail are read again (`use-pull-to-refresh` writes that room straight onto the content as the finger moves, never through a render, and owns the gesture until release; `PullToRefreshIndicator`; dragged back down before the release, the icon hides at the travel that showed it).
- **Sending:** `api/admin/bots/send-message.ts` -> `enqueueBotReply` -> `wakeBotsQueue`. **Never import `src/bots-queue/index.ts` from a page or API route** (pulls the bunext runtime into page bundles). Optimistic bubble in `pending_messages` until the saved message replaces it. A message is capped at the app setting `bot_message_max_chars` (Settings > General, default `AppData.BotMessageMaxChars`, counted on the trimmed markdown), checked by the composer before it sends (the reason shows under the input) and again by the route.
- **Composer:** Tiptap editor reading/writing markdown, drafts in `localStorage`, `@` bots / `#` workspaces written as `[bot:ID]`/`[workspace:ID]`. Enter sends (Mod+Enter in lists/code). `@tiptap/react` needs `use-sync-external-store`; the app ships an ESM stand-in in `packages/use-sync-external-store-esm` (file dependency + override; the Dockerfile copies `packages/` before `bun install`).
- **Rendering:** markdown via `react-markdown` + `remark-gfm`, raw HTML never rendered, component map in `[bot_id]/(data)/message-markdown-components.tsx`. Inline refs, all linked by `link-computer-refs.ts` and rendered by chips in `(partials)/`: `[bot:ID]`, `[workspace:ID]`, `[computer:ID]`, `[file:ID]` (a saved file), `[folder:<volume>:<owner>:<path>]` (opens `FolderPreviewModal`, the files browser's listing over the chat, files opening their own preview; a modified click or its Open in Files goes to `/admin/files`), `[take-over:ID:mode]`, `[proposal:ID]`, `[hook-proposal:ID]`, `[secret:ID]` (masked env, Reveal/Copy), `[secret-request:ID]` (masked input card), `[question:ID]` (a bot's questions), `[graphic:ID]` (a bot graphic, framed inline), `[room:ID]` (a chatroom), `[task:ID]` (a tracker task, opening `TaskDetailModal`), `[setting:<section>:<field>]` (`SettingRefChip`: the exact Settings > General page and field to change, from `src/dict/general-settings-dict.ts`; every group of that page also has its own page under `/admin/settings/general/<section>`, and its fields are anchors). 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.
- **Composer:** Tiptap editor reading/writing markdown, drafts in `localStorage`, `@` bots / `#` workspaces written as `[bot:ID]`/`[workspace:ID]`. Enter sends (Mod+Enter in lists/code). **Up/Down walk the user's own earlier messages** (`use-composer-history`, from `composerHistoryTexts` over the thread's user messages, never a crew message): Up recalls the newest from an empty input and older ones from there, Down comes forward again and back to what was being typed, a keystroke takes the input back, an open mention menu or a selection keeps the arrows. A clear button (X, disabled while the input is empty) empties the text without sending, keeping the quote and the picked files. Ordered lists are read back from digit markers only (`composer-ordered-list`): Tiptap also takes `a.`/`i.`, so a recalled "Ok. Do that." came back as item 401 with "Ok." eaten. `@tiptap/react` needs `use-sync-external-store`; the app ships an ESM stand-in in `packages/use-sync-external-store-esm` (file dependency + override; the Dockerfile copies `packages/` before `bun install`).
- **Rendering:** markdown via `react-markdown` + `remark-gfm`, raw HTML never rendered, component map in `[bot_id]/(data)/message-markdown-components.tsx`. Inline refs, all linked by `link-computer-refs.ts` and rendered by chips in `(partials)/`: `[bot:ID]`, `[workspace:ID]`, `[computer:ID]`, `[file:ID]` (a saved file), `[folder:<volume>:<owner>:<path>]` (opens `FolderPreviewModal`, the files browser's listing over the chat, files opening their own preview; a modified click or its Open in Files goes to `/admin/files`), `[take-over:ID:mode]`, `[proposal:ID]`, `[hook-proposal:ID]`, `[secret:ID]` (masked env, Reveal/Copy), `[secret-request:ID]` (masked input card), `[question:ID]` (a bot's questions), `[suggestion:ID]` (its suggested next steps, buttons that fill the composer), `[graphic:ID]` (a bot graphic, framed inline), `[room:ID]` (a chatroom), `[task:ID]` (a tracker task, opening `TaskDetailModal`), `[setting:<section>:<field>]` (`SettingRefChip`: the exact Settings > General page and field to change, from `src/dict/general-settings-dict.ts`; every group of that page also has its own page under `/admin/settings/general/<section>`, and its fields are anchors). Parsers in `src/utils/*-ref.ts`. Anywhere else that renders bot-written markdown with `MessageMarkdownComponents` (a workspace's context on its dashboard, a task's description and notes through `TaskMarkdown`) runs it through `linkComputerRefs` and provides `CrewBotsContext`/`CrewWorkspacesContext` too. A ref quoted alone in a code span still links; one inside longer code stays literal (`linkComputerRefs` splits out code first). A file chip opens a file from another bot's folder for a user who reaches that folder (`userReachesFileScope`, the same rule as its bytes), so answers passed on from chatrooms keep working.
- **Task chips:** which tracker tasks a bot message is about is the app's record, not the bot's word: a run's task tools report each task they touch (`onTask`: `list_tasks` with `task_id`, `create_task`, `update_task`, `delegate_task`'s hand-over), plus a handed-over job's `tracker_task_id`, into `bot_messages.task_ids` (also on its failure notice and its report relayed to the requester). The thread shows them under the message (`MessageTaskChips`) with title and status, read per viewer and only for tasks they reach (`grabMessagesTasks`; pushes carry them through `withMessageTasks`).
- **File preview:** every file link (chips, attachments, files modal, task files, `/admin/files`) is a `FilePreviewLink`: a plain click opens `FilePreviewModal` (its header shows the size and the file's full path on the data volume, `full_path`, e.g. `bots/3/reports/q3.md`, absolute when outside it; every opener passes it; markdown rendered with the message elements, CSV/TSV as a table via `parseCsv`, images in `ImageViewer` (zoom buttons and keys, Ctrl/Cmd+wheel or pinch at the pointer, Fit, Fit width (a full-page screenshot opens that way and scrolls down), Actual size, double click, drag to pan; sized by the `width` attribute and centred with auto margins, never flex centring, which cuts off a tall picture's top), PDF/audio/video in place, HTML in a frame with `sandbox=""` (plus the media server's `sandbox` CSP), other text as code, the kind from `filePreviewKind`; Download and Open in a new tab), a modified click still opens a tab. Text is read up to `AppData.FilePreviewMaxTextBytes`. Never render a file's HTML on the app's origin or with scripts. Opened from a list (a folder, the files modal, a message's images), an image gets that list's images as its `gallery` (`imagePreviewGallery`): Previous/Next and the arrow keys step through them in the same modal, neighbours preloaded. Escape closes only the top modal of a stack (`useTopModalEscape`; twui closes every open one). The message elements and the preview import each other (through the file chips), so the preview merges `MessageMarkdownComponents` when it renders, never at module load.
- **Copy chat** (header menu): the active session (the one on screen) as one markdown document (`api/admin/bots/conversation-export` -> `conversationMarkdown`, refs as names, message headings demoted). The clipboard write starts on the click with a pending `ClipboardItem` (`copyPendingText`), since Safari drops the gesture after a fetch. A message's Details modal has its own **Copy report** (`messageDetailsMarkdown`, the same pending write): that message's whole details, listing up to `AppData.MessageDetailsCopyMaxCalls` calls and failures (the route's `full=1`) instead of the modal's first `MessageDetailsMaxCalls`.
- **Asking before acting:** `ask_user` (`QuestionsNote`) puts up to `AppData.BotQuestionMaxQuestions` multiple-choice questions (`single` = radios, `multiple` = checkboxes, optional typed "Other") on one card, once per run -> `bot_questions` -> `[question:ID]` chip opening `BotQuestionCard`; the message needs the user. Answers are checked against the questions (`checkBotQuestionAnswers`) and stored, then sent as the user's chat message (`botQuestionAnswersText`); Skip says so. Replies and user-started tasks only: never routines, hook calls or chatroom sessions (no one sees those).
- **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). The reply's `ask_user`/`suggest_next_steps` and `QuestionsNote` are gated on `attended` (`isHiddenSession`), and a task run's on `can_ask`: a question in a hidden session has no card the user would see (one reached the coordinator as a bare `[question:22]`, its answer never getting back).
- **Suggested next steps:** `suggest_next_steps` puts up to `AppData.BotSuggestionMaxSteps` follow-ups under the answer, once per run -> `bot_suggestions` -> `[suggestion:ID]` rendered inline as buttons (`BotSuggestionsRef`); clicking one inserts it into the composer (`ComposerHandle.insertText`, never sends) and nothing waits on it, so it's `shown` in `withTakeOverRefs`, never `refs`, and never sets `needs_you`. For when the work is done and the bot offers follow-ups; when the answer decides what it does next, it's `ask_user`. Same runs as `ask_user`.
- **Quoting:** selected text quotes into the composer through `quotableText`, which reads each ref chip as one inline label (`MarkdownLink` wraps chips with `QuoteInlineAttribute`; `Selection.toString()` broke a quote into a paragraph per chip).
- **Replies/reactions:** `reply_to_message_id` (not an FK); reactions from the fixed `BotMessageReactions`, toggled by `react-message.ts` and the `react_to_message` tool, pushed as `server:bot-reaction`. A reply's history shows the user's own reactions on each bot message in its app record (`botMessagesToHarness`, so `run-bot-reply` loads history with `user_id`), and the chat reply note tells the bot to save lasting preferences they show in its memory of that user; 👎 is in the set for that.
- **Attachments:** uploaded on pick (`upload-attachment.ts`, private `media`, no text kept: a reply reads a document's text from the file), linked via `bot_message_media`. Replies read files of the last `BotReplyAttachmentMessages` messages that have any, and only while they're within `BotReplyAttachmentMaxAgeMessages` of the latest (`liveAttachmentMessages`: one old screenshot, being the last message with files, was re-attached and re-read on every reply for the rest of a long session); older files are only named. An upload's bytes go with its message: whatever deletes messages that carry them (`deleteChatroomRows`, `deleteHookSessionRows`, `prune-bot-hook-events`) unlinks them and deletes a media row nothing else points at (`deleteUnlinkedAttachmentMedia`), and `prune-orphan-media` takes what is left after `AppData.MediaOrphanKeepDays` (both share `UnreferencedMediaSql`). Tasks don't get files yet.
@@ -132,7 +133,7 @@ Server push only. `pushBotNotice` (`server:bot-message`, `server:bot-updated`),
### Chatrooms (`chatrooms`)
A worker reaches another worker **only through the coordinator**: `ask_crew` (every worker run except hook calls; never the coordinator) opens a room (`createChatroom`) for the run's user and place. Who can be asked is the app's call (`chatroomAskableBots`): in a workspace its members, else every worker the user reaches. Every bot in a room has a hidden session there (`bot_sessions.chatroom_id`, status `chatroom`) holding its messages and jobs; **every session query that lists or picks a conversation must exclude them** (`chatroom_id IS NULL`, and hook sessions the same way). The coordinator's turns are queued straight onto the queue (`enqueueChatroomTurn`, it works for a member there) and run by `runChatroomTurn` with only `ask_member`/`answer_requester`/`refuse_request`, the room fenced as data (`chatroomTurns`). A member saves to its own folder, which the asker can't read, so `answer_requester` copies every cited file the asker doesn't reach but a member does into the asker's folder (`crew/room-<id>/`) and repoints the refs (`shareRoomFiles`). `ask_crew` refuses a second open request from the same place unless it's `separate`, and task runs (which see only their brief) get their bot's open and recent requests (`grabCrewRequests`, `crewRequestsNote`). A room job ending (`onChatroomJobEnded`, from complete/fail) wakes the coordinator; closing (`closeChatroom`, once) cancels what's open and posts the outcome into the asking bot's session as a user-side message with `from_chatroom_id` (fenced for the model, shown as from the coordinator) and wakes it, except when stopped. Caps: `AppData.ChatroomMaxCoordinatorTurns`, `ChatroomMaxDepth` (nested rooms, `parent_chatroom_id`; a bot waiting up the chain can't be asked), `ChatroomMaxOpenPerBot`. Room jobs never change faces or name sessions (nor count when a face is put back after another job, `grabRunningBotJobFace`); their messages push as `server:chatroom-message`/`server:chatroom-updated`, never as notifications. Rooms are read-only records kept per place, like conversations: a workspace's open under it (`/admin/workspaces/<id>/chatrooms[/<room>]`, listed in the workspace rail after its bots), the rest under `/admin/chatrooms` (after the workspaces in the main rail); links go through `chatroomHref` and a room opened at the wrong place redirects. The rail loads its section itself (`api/admin/chatrooms/list?workspace_id=`); `[room:ID]` chip. The user can only Stop one, or Try again once it's `failed` or `stopped` (`retryChatroom`: the same room reopened with its turn budget reset and a note as the asking bot's message, since the room's turns must end on a non-coordinator one; refused past the open cap or when a nested room's parent closed; a stopped room's outcome doesn't wake the bot, so `chatroomHoldsReply` keeps the thinking row away). Under the thread an open room shows where each bot stands (`chatroomBotStatuses`, from the summary's open `jobs` plus live `server:bot-job-update` steps), and so does the asking bot's conversation, linked to the room (`useConversationChatrooms`, `?requester_bot_id=` on the list, refetched on reconnect); bots' faces stay out of it. **Retention:** closed rooms go after the app setting `chatroom_keep_days` (daily `prune-chatrooms`) and past `chatroom_max_per_place` rooms per place (also pruned as each room closes), oldest first (`pruneChatroomsSql`; open rooms and rooms an open one was asked from are never pruned; deletion through `deleteChatroomRows`).
A worker reaches another worker **only through the coordinator**: `ask_crew` (every worker run except hook calls; never the coordinator) opens a room (`createChatroom`) for the run's user and place. Who can be asked is the app's call (`chatroomAskableBots`): in a workspace its members, else every worker the user reaches. Every bot in a room has a hidden session there (`bot_sessions.chatroom_id`, status `chatroom`) holding its messages and jobs; **every session query that lists or picks a conversation must exclude them** (`chatroom_id IS NULL`, and hook sessions the same way). The coordinator's turns are queued straight onto the queue (`enqueueChatroomTurn`, it works for a member there) and run by `runChatroomTurn` with only `ask_member`/`answer_requester`/`refuse_request`, the room fenced as data (`chatroomTurns`). Closing is what cancels a room's jobs, so `answer_requester` and `refuse_request` refuse while a member job still runs (`grabChatroomOpenJobs`, `chatroomOpenJobsWarning`) unless given `close_anyway`: a coordinator that answered over a live run once killed the very work it was asked for, then reported it picked up. A coordinator's turn creates no task and moves none (`chatroomCoordinatorNote`): a task is handed over by the bot that has it or by the user. A member saves to its own folder, which the asker can't read, so `answer_requester` copies every cited file the asker doesn't reach but a member does into the asker's folder (`crew/room-<id>/`) and repoints the refs (`shareRoomFiles`). `ask_crew` refuses a second open request from the same place unless it's `separate`, and task runs (which see only their brief) get their bot's open and recent requests (`grabCrewRequests`, `crewRequestsNote`). A room job ending (`onChatroomJobEnded`, from complete/fail) wakes the coordinator; closing (`closeChatroom`, once) cancels what's open and posts the outcome into the asking bot's session as a user-side message with `from_chatroom_id` (fenced for the model, shown as from the coordinator) and wakes it, except when stopped. Caps: `AppData.ChatroomMaxCoordinatorTurns`, `ChatroomMaxDepth` (nested rooms, `parent_chatroom_id`; a bot waiting up the chain can't be asked), `ChatroomMaxOpenPerBot`. Room jobs never change faces or name sessions (nor count when a face is put back after another job, `grabRunningBotJobFace`); their messages push as `server:chatroom-message`/`server:chatroom-updated`, never as notifications. Rooms are read-only records kept per place, like conversations: a workspace's open under it (`/admin/workspaces/<id>/chatrooms[/<room>]`, listed in the workspace rail after its bots), the rest under `/admin/chatrooms` (after the workspaces in the main rail); links go through `chatroomHref` and a room opened at the wrong place redirects. The rail loads its section itself (`api/admin/chatrooms/list?workspace_id=`); `[room:ID]` chip. The user can only Stop one, or Try again once it's `failed` or `stopped` (`retryChatroom`: the same room reopened with its turn budget reset and a note as the asking bot's message, since the room's turns must end on a non-coordinator one; refused past the open cap or when a nested room's parent closed; a stopped room's outcome doesn't wake the bot, so `chatroomHoldsReply` keeps the thinking row away). Under the thread an open room shows where each bot stands (`chatroomBotStatuses`, from the summary's open `jobs` plus live `server:bot-job-update` steps), and so does the asking bot's conversation, linked to the room (`useConversationChatrooms`, `?requester_bot_id=` on the list, refetched on reconnect); bots' faces stay out of it. A room shows what it cost the way a conversation's messages do: each message carries its `MessageUsageChip` and the Details modal (read through the room's own `api/admin/chatrooms/message-details`, which checks the room's user), and above the thread `ChatroomUsageSummary` totals the room (`usage` on its summary, from `grabChatroomUsage`: every model call counted by its run's `bot_sessions.chatroom_id`, a turn still running included, with the room's failed calls and the same split by bot). **Retention:** closed rooms go after the app setting `chatroom_keep_days` (daily `prune-chatrooms`) and past `chatroom_max_per_place` rooms per place (also pruned as each room closes), oldest first (`pruneChatroomsSql`; open rooms and rooms an open one was asked from are never pruned; deletion through `deleteChatroomRows`).
### Workspaces
@@ -164,7 +165,7 @@ A secret URL, `POST /api/hooks/<token>` (`src/pages/api/hooks/[token].ts`, publi
### Tasks (the to-do tracker)
`tasks` (**a task belongs to a bot by default**, the coordinator included: a bot's own list is `bot_id` alone, a workspace's task has `workspace_id` plus the `bot_id` that has it there; the one exception is a **workspace-wide** task (`workspace_id`, `bot_id` null), only when asked for (`workspace_wide`, enforced by `taskScopeValues`), which every bot working there sees and works on; a worker reaches its own plus the workspace-wide ones in its workspaces, a workspace admin all of that workspace's, the coordinator all, `botTaskScopesSql`; on a workspace-wide task `update_task` logs each call's status move and filed files as a note under the bot (`task_notes.bot_id`), and `list_tasks` with `task_id` reads the whole log with who and when; the coordinator and a workspace's admin bot (`update_task` `workspace_wide`) or a crew manager (Make workspace-wide, `api/admin/tasks/make-workspace-wide`) turn a bot's open workspace task workspace-wide (`makeTaskWorkspaceWide`, noted in its log; never a bot's own list), and hand-over gives one back to a single bot; a bot removed from a workspace or deleted passes its own tasks there to the workspace's admin bot, else the coordinator (`passOnBotTasks`), workspace-wide ones stay), `task_notes`, `task_media` (deliverable|reference). Not the same as `bot_tasks`/`bots_queue` (those record jobs). Visibility SQL in `src/utils/task-access/`. Helpers in `src/functions/backend/db/tasks/`; tools `list_tasks`/`create_task`/`update_task` (which also renames a task and rewrites its brief, refusing an open twin's title, and unlinks bot files with `unlink_file_ids`: a task holds `AppData.TaskMediaMaxPerTask` files; `list_tasks` with `task_id` lists them) and, in chat replies the user follows only (never routines, hook calls or rooms), `delete_task`; API `api/admin/tasks/` (`userAuth` -> `isReadOnlyUser` -> `assertUserReachesTask` -> `safeErrorMessage`). UI in the workspace dashboard and the header's Tasks modal (shared components in `src/components/general/`); a card's title opens `TaskDetailModal` with everything about the task and its status moves (a modal over the list, never swapped in place). **Hand-over:** `handOverTask` (bot: `delegate_task` with `task_id`; UI: Hand over, crew managers) moves an open task to the new bot (a workspace's stays in the workspace, now the new bot's, and is worked there), sets it doing and queues a job with `params.tracker_task_id` (with `start: false` it only moves it, as to do, no job: for "take it and wait for the go-ahead"); `noteTrackerTask` notes the job's end on it, blocks it on failure, and blocks it too when the run used every step it had without finishing (`trackerTaskEnding`, so a run measured to its last step no longer leaves the task silently open). **Not built yet:** task steps, `server:task-changed` pushes, a `/admin/tasks` page.
`tasks` (**a task belongs to a bot by default**, the coordinator included: a bot's own list is `bot_id` alone, a workspace's task has `workspace_id` plus the `bot_id` that has it there; the one exception is a **workspace-wide** task (`workspace_id`, `bot_id` null), only when asked for (`workspace_wide`, enforced by `taskScopeValues`), which every bot working there sees and works on; a worker reaches its own plus the workspace-wide ones in its workspaces, a workspace admin all of that workspace's, the coordinator all, `botTaskScopesSql`; on a workspace-wide task `update_task` logs each call's status move and filed files as a note under the bot (`task_notes.bot_id`), and `list_tasks` with `task_id` reads the whole log with who and when; the coordinator and a workspace's admin bot (`update_task` `workspace_wide`) or a crew manager (Make workspace-wide, `api/admin/tasks/make-workspace-wide`) turn a bot's open workspace task workspace-wide (`makeTaskWorkspaceWide`, noted in its log; never a bot's own list), and hand-over gives one back to a single bot; a bot removed from a workspace or deleted passes its own tasks there to the workspace's admin bot, else the coordinator (`passOnBotTasks`), workspace-wide ones stay), `task_notes`, `task_media` (deliverable|reference). Not the same as `bot_tasks`/`bots_queue` (those record jobs). Visibility SQL in `src/utils/task-access/`. Helpers in `src/functions/backend/db/tasks/`; tools `list_tasks`/`create_task`/`update_task` (which also renames a task and rewrites its brief, refusing an open twin's title, and unlinks bot files with `unlink_file_ids`: a task holds `AppData.TaskMediaMaxPerTask` files; `list_tasks` with `task_id` lists them) and, in chat replies the user follows only (never routines, hook calls or rooms), `delete_task`; API `api/admin/tasks/` (`userAuth` -> `isReadOnlyUser` -> `assertUserReachesTask` -> `safeErrorMessage`). UI in the workspace dashboard and the header's Tasks modal (shared components in `src/components/general/`); a card's title opens `TaskDetailModal` with everything about the task and its status moves (a modal over the list, never swapped in place). **Hand-over:** `handOverTask` (bot: `delegate_task` with `task_id` when it directs work, else `hand_over_task` for a task of its own; UI: Hand over, crew managers) moves an open task to the new bot (a workspace's stays in the workspace, now the new bot's, and is worked there), sets it doing and queues a job with `params.tracker_task_id` (with `start: false` it only moves it, as to do, no job: for "take it and wait for the go-ahead"); `noteTrackerTask` notes the job's end on it, blocks it on failure, and blocks it too when the run used every step it had without finishing (`trackerTaskEnding`, so a run measured to its last step no longer leaves the task silently open). **Not built yet:** task steps, `server:task-changed` pushes, a `/admin/tasks` page.
### Envs
@@ -220,7 +221,7 @@ Read-only browser of every volume (`src/utils/storage-volumes.ts`: bots, workspa
- **Calling:** `resolveHarnessCandidates` -> `withCandidates` with process-wide cooldowns; errors are `HarnessError`. Order: the pick, the text setting's fallback models (`fallback_model_ids` in its options, up to `AppData.HarnessTextFallbackModelsMax`, any provider), then the free automatic picks (when `fallback` is on). Every failure is logged (`logCandidateFailure`) and benches its model (or provider, for a key or credits) for the model rest (app setting `harness_model_rest_seconds`, Settings > General run limits, default `AppData.HarnessModelRestMs`, or until the setting changes and the app restarts when the rest is unlimited), never longer, even past a `Retry-After`: one failure once left every reply on a weak free model for an hour. A message answered by a model in place of the one ahead of it shows the fallback on its usage chip (`fell_back_from`/`resting` in `token_usages.settings`). Entry points under `text/`, `media/`, `audio/`, `image/`, `embeddings/`. `run-text-loop.ts` sticks to one model (an automatic pick only until the pick or a fallback model has rested), caps steps (`grabHarnessMaxToolSteps`, `grabReplyMaxToolSteps`; routines and hook calls `grabUnattendedMaxToolSteps`, all unlimited by default, so a run's job deadline and its prompt-token budget are what end it; every run limit reads as `RunLimit` in `src/utils/run-limit.ts`, `number` or `"unlimited"`, saved as `-1` on the settings form and `"unlimited"` in `app_settings`; a run is told once, `stepsLowWarningLeft` steps before the wrap up, to save its report, and the wrap up keeps `WrapUpToolNames` (`write_file`, `import_file`, and `start_task` for work the run can't finish: a 20-step reply used for research otherwise left the writing undone and the next reply had the same budget) for a saving-or-hand-off turn before the last turn with no tools, since runs measured to their last step with the report unwritten) and the prompt tokens one run may spend (`grabRunMaxPromptTokens`, then the wrap up). Results are cut keeping their start and their end (`run-tool-call.ts`, `capToolOutput`), never the start alone: a `du`/`find` sweep's totals are its last lines. A read the run already made is answered from that answer (`RepeatableToolNames`, `repeatToolCallKey`, `alreadyRanToolNote`): calling `read_file`, `list_files`, `search_knowledgebase`, `list_tasks` and the like again with the same arguments returns a pointer to the output above instead of running again, and any non-read tool (a write, `computer_bash`) clears what was remembered, so a file read, edited and read again is read again.
- **Token use:** every turn resends the system prompt, tool definitions and whole transcript, so a run's cost grows with its length squared (production lost 39M tokens on one routine run on a 1M-window model that never trimmed). Keep turns small: `fitTranscriptToContext` trims to the working context (`grabContextBudgetTokens`, never just the window), cutting in one block down to 60% so the cached prefix holds between cuts; only the newest `browser_snapshot` per browser stays (`supersedeToolOutputs`); browser results are capped lower (`HarnessBrowserResultMaxChars`); MCP and user-browser tools are `deferred` (listed by name in the prompt, loaded with `load_tools`) once their definitions pass `HarnessDeferToolsMinChars`, loaded ones appended last. Don't rewrite earlier transcript messages every turn (it breaks providers' prompt caches); `token_usages.cached_tokens` shows what was served from cache. Models that can't take an image/audio part get it read by vision/transcription first (`prepareMessagesForModel`, per candidate). Tool images (screenshots, `read_file` images) are never read by the tool: tools return `{ text, images }`, the loop shows them in a user turn after the results (`toolImagesTurn`, fenced as tool output), and `prepareMessagesForModel` decides. A text model looks at images itself (attachments too) only when its text setting has "Use the model's own media reading" on (`sees_images` in the text harness options, per default/bot/workspace row, `textSeesImages`) and it takes image input: the catalog's `input_modalities` decide, so a custom provider's bare model id gets `guessModelModalities`, which says text-only for anything it doesn't recognise and then `sees_images` reads nothing (the Models page says so under the checkbox, `HarnessSeesImagesNote`, since the setting is otherwise silently useless). Otherwise the vision harness reads them (with the tool's `focus` and `redact`; pixels a seeing model gets can't be redacted). Readings are kept across runs by `MediaReadings` (`HarnessMediaReadingsCached`), keyed by `imageReadingKey`, so the same image is read once rather than once per reply; a reading made to `redact` a secret is never kept there. Only the newest `AppData.HarnessToolImagesKept` stay (`dropOldToolImages`).
- **Per-bot models:** workspace row > bot row > default; the coordinator always uses the defaults. Every entry point takes `bot_id` and passes it on. **Embeddings are install-wide** (`install_wide` in `Harnesses`, `isInstallWideHarness`): `grabHarnessSetting` ignores bot/workspace rows for them, the per-bot/workspace forms don't list them and saving one is refused, so every stored vector comes from one model. Shared form `settings/models/(partials)/harness-settings-form.tsx`.
- **Tools:** `HarnessTool` built per run; own tools validate with zod. `run-tool-call.ts` reports errors back to the model and caps each call (`AppData.HarnessToolTimeoutMs`); a `computer_*`/`browser_*` call from a run without them (a reply) is told to use `start_task` (`unknownToolMessage`). Bot tools in `src/harness/tools/bot/` (memory, instructions, tasks, schedules, `read_settings`, `read_message_usage`, `start_task`, coordinator's crew management, `delegate_task` and `hand_over_schedule`, with results relayed back by `relayJobToRequester`).
- **Tools:** `HarnessTool` built per run; own tools validate with zod. `run-tool-call.ts` reports errors back to the model and caps each call (`AppData.HarnessToolTimeoutMs`); a `computer_*`/`browser_*` call from a run without them (a reply) is told to use `start_task` (`unknownToolMessage`). Bot tools in `src/harness/tools/bot/` (memory, instructions, tasks, schedules, `read_settings`, `read_message_usage`, `start_task`, `hand_over_task`, coordinator's crew management, `delegate_task` and `hand_over_schedule`, with results relayed back by `relayJobToRequester`).
- **Extensions:** MCP servers (`mcp_servers`, remote or stdio), custom tools (`custom_tools`: http, script, prompt) and skills (`skills`, runbooks loaded with `load_skill`). Given per bot / per workspace (`botExtensionsSql`); `all_bots` only decides what new bots get. Templates `{{args.x}}`/`{{env.KEY}}` via `fillTemplate`; secrets redacted from results. stdio servers run in a per-process pool. Skill body limits are app settings (`grabSkillBodyMaxChars`, `grabSkillBodyShownChars`). A skill proposal says what it changes (`skillProposalChanges`) to the bot and in the confirm outcome, takes no unknown keys (a misnamed `body` would re-propose the saved runbook) and is refused when it changes nothing.
- **Bots never add or repoint extensions or set envs.** The coordinator may only change what can't alter where data is sent (name, description, on/off, access); its extension tools (`grabCoordinatorExtensionTools`) come wherever it works, a workspace as much as its own chat. New skills, servers, tools, or changes to a URL, headers, kind, config or a skill's runbook go through `propose_*` -> `extension_proposals` -> `[proposal:ID]` card, which the app describes from the config itself (never from what the bot says) and the super admin confirms (`checkProposalData` re-checks). Stdio servers are never proposed by bots (they run in the app container, which holds the docker socket).
- **Check before and after acting** (`ActionCheckNote`): look for an existing record before creating one, verify every action took effect. Tools enforce it (read-back on memory saves, duplicate checks on bots, schedules, tasks, workspaces).
+1
View File
@@ -60,6 +60,7 @@
"@types/sanitize-html": "^2.16.2",
"@types/turndown": "^5.0.6",
"@types/web-push": "^3.6.4",
"marked": "17.0.6",
"tailwindcss": "^4.3.3",
},
"peerDependencies": {
+42
View File
@@ -1797,6 +1797,48 @@ const schema: BUN_SQLITE_DatabaseSchemaType = {
},
],
},
{
tableName: "bot_suggestions",
tableDescription: `Next steps a bot suggests under its answer (\`suggest_next_steps\`): buttons that put the step in the user's input. Unlike \`bot_questions\`, nothing waits on them`,
fields: [
{
fieldName: "title",
fieldDescription: `A short heading for the row of buttons; empty for "Next steps"`,
dataType: "TEXT",
},
{
fieldName: "steps",
fieldDescription: `JSON array of the suggested steps, each put in the user's input when clicked`,
dataType: "TEXT",
},
{
fieldName: "user_id",
fieldDescription: `The user they were suggested to, who alone reads them. Not a foreign key`,
dataType: "INTEGER",
},
{
fieldName: "bot_id",
fieldDescription: `The bot that suggested them. Not a foreign key`,
dataType: "INTEGER",
},
{
fieldName: "session_id",
fieldDescription: `The conversation they were suggested in. Not a foreign key`,
dataType: "INTEGER",
},
{
fieldName: "workspace_id",
fieldDescription: `The session's workspace; null for the bot's own chat. Not a foreign key`,
dataType: "INTEGER",
},
],
indexes: [
{
indexName: "idx_bot_suggestions_session_id",
indexTableFields: ["session_id"],
},
],
},
{
tableName: "bot_graphics",
tableDescription: `A visual a bot made for a user (a chart, diagram, timeline or report) as one self-contained HTML document. Served by the app at \`/graphics/<id>\` in a sandbox with no network and an origin of its own, so it never runs with the viewer's session. Per user like the conversation it was made in; an edit replaces the HTML and bumps \`version\``,
+41 -1
View File
@@ -24,6 +24,7 @@ export const BunSQLiteTables = [
"secret_requests",
"install_requests",
"bot_questions",
"bot_suggestions",
"bot_graphics",
"workspaces",
"workspace_bots",
@@ -1164,6 +1165,45 @@ export type BUN_SQLITE_COBBLE_BOT_QUESTIONS = {
workspace_id?: number | "";
}
export type BUN_SQLITE_COBBLE_BOT_SUGGESTIONS = {
/**
* The unique identifier of the record.
*/
id?: number | "";
/**
* The time when the record was created. (Unix Timestamp)
*/
created_at?: number | "";
/**
* The time when the record was updated. (Unix Timestamp)
*/
updated_at?: number | "";
/**
* A short heading for the row of buttons; empty for "Next steps"
*/
title?: string;
/**
* JSON array of the suggested steps, each put in the user's input when clicked
*/
steps?: string;
/**
* The user they were suggested to, who alone reads them. Not a foreign key
*/
user_id?: number | "";
/**
* The bot that suggested them. Not a foreign key
*/
bot_id?: number | "";
/**
* The conversation they were suggested in. Not a foreign key
*/
session_id?: number | "";
/**
* The session's workspace; null for the bot's own chat. Not a foreign key
*/
workspace_id?: number | "";
}
export type BUN_SQLITE_COBBLE_BOT_GRAPHICS = {
/**
* The unique identifier of the record.
@@ -2826,4 +2866,4 @@ export type BUN_SQLITE_COBBLE_APP_SETTINGS = {
value?: string;
}
export type BUN_SQLITE_COBBLE_ALL_TYPEDEFS = BUN_SQLITE_COBBLE_USERS & BUN_SQLITE_COBBLE_USER_TYPES & BUN_SQLITE_COBBLE_SSO_LOGIN_CODES & BUN_SQLITE_COBBLE_USER_PASSWORDS & BUN_SQLITE_COBBLE_MEDIA & BUN_SQLITE_COBBLE_MEDIA_PARADIGMS & BUN_SQLITE_COBBLE_BOTS & BUN_SQLITE_COBBLE_CHATROOMS & BUN_SQLITE_COBBLE_BOT_SESSIONS & BUN_SQLITE_COBBLE_BOT_MESSAGES & BUN_SQLITE_COBBLE_BOT_MESSAGE_REACTIONS & BUN_SQLITE_COBBLE_BOT_TASKS & BUN_SQLITE_COBBLE_BOT_TASK_STEPS & BUN_SQLITE_COBBLE_TASKS & BUN_SQLITE_COBBLE_TASK_MEDIA & BUN_SQLITE_COBBLE_TASK_NOTES & BUN_SQLITE_COBBLE_BOTS_QUEUE & BUN_SQLITE_COBBLE_BOTS_QUEUE_UPDATES & BUN_SQLITE_COBBLE_CRON_JOBS & BUN_SQLITE_COBBLE_BOT_HOOKS & BUN_SQLITE_COBBLE_BOT_HOOK_EVENTS & BUN_SQLITE_COBBLE_HOOK_PROPOSALS & BUN_SQLITE_COBBLE_SECRET_REQUESTS & BUN_SQLITE_COBBLE_INSTALL_REQUESTS & BUN_SQLITE_COBBLE_BOT_QUESTIONS & BUN_SQLITE_COBBLE_BOT_GRAPHICS & BUN_SQLITE_COBBLE_WORKSPACES & BUN_SQLITE_COBBLE_WORKSPACE_BOTS & BUN_SQLITE_COBBLE_BOT_TYPES & BUN_SQLITE_COBBLE_WORKSPACE_USERS & BUN_SQLITE_COBBLE_BOT_USERS & BUN_SQLITE_COBBLE_BOT_USER_VISITS & BUN_SQLITE_COBBLE_WORKSPACE_USER_VISITS & BUN_SQLITE_COBBLE_WORKSPACE_USER_ROLES & BUN_SQLITE_COBBLE_BOT_USER_MEMORIES & BUN_SQLITE_COBBLE_BOT_USER_FACES & BUN_SQLITE_COBBLE_BOT_MESSAGE_MEDIA & BUN_SQLITE_COBBLE_CONTAINERS & BUN_SQLITE_COBBLE_COMPUTERS & BUN_SQLITE_COBBLE_BOT_COMPUTERS & BUN_SQLITE_COBBLE_WORKSPACE_COMPUTERS & BUN_SQLITE_COBBLE_HARNESS_PROVIDERS & BUN_SQLITE_COBBLE_HARNESS_MODELS & BUN_SQLITE_COBBLE_HARNESS_SETTINGS & BUN_SQLITE_COBBLE_BOT_HARNESS_SETTINGS & BUN_SQLITE_COBBLE_WORKSPACE_HARNESS_SETTINGS & BUN_SQLITE_COBBLE_MCP_SERVERS & BUN_SQLITE_COBBLE_BROWSERS & BUN_SQLITE_COBBLE_BROWSER_ACCESS & BUN_SQLITE_COBBLE_CUSTOM_TOOLS & BUN_SQLITE_COBBLE_SKILLS & BUN_SQLITE_COBBLE_EXTENSION_PROPOSALS & BUN_SQLITE_COBBLE_BOT_MCP_SERVERS & BUN_SQLITE_COBBLE_WORKSPACE_MCP_SERVERS & BUN_SQLITE_COBBLE_BOT_CUSTOM_TOOLS & BUN_SQLITE_COBBLE_WORKSPACE_CUSTOM_TOOLS & BUN_SQLITE_COBBLE_BOT_SKILLS & BUN_SQLITE_COBBLE_WORKSPACE_SKILLS & BUN_SQLITE_COBBLE_KNOWLEDGEBASES & BUN_SQLITE_COBBLE_KNOWLEDGEBASE_DOCUMENTS & BUN_SQLITE_COBBLE_KNOWLEDGEBASE_CHUNKS & BUN_SQLITE_COBBLE_KNOWLEDGEBASE_VECTORS & BUN_SQLITE_COBBLE_BOT_KNOWLEDGEBASES & BUN_SQLITE_COBBLE_WORKSPACE_KNOWLEDGEBASES & BUN_SQLITE_COBBLE_LOGS & BUN_SQLITE_COBBLE_USER_PRESENCE & BUN_SQLITE_COBBLE_PUSH_SUBSCRIPTIONS & BUN_SQLITE_COBBLE_ENVS & BUN_SQLITE_COBBLE_BOT_FILES & BUN_SQLITE_COBBLE_TOKEN_USAGES & BUN_SQLITE_COBBLE_HARNESS_CALL_FAILURES & BUN_SQLITE_COBBLE_FILE_INGEST_QUEUE & BUN_SQLITE_COBBLE_APP_SETTINGS
export type BUN_SQLITE_COBBLE_ALL_TYPEDEFS = BUN_SQLITE_COBBLE_USERS & BUN_SQLITE_COBBLE_USER_TYPES & BUN_SQLITE_COBBLE_SSO_LOGIN_CODES & BUN_SQLITE_COBBLE_USER_PASSWORDS & BUN_SQLITE_COBBLE_MEDIA & BUN_SQLITE_COBBLE_MEDIA_PARADIGMS & BUN_SQLITE_COBBLE_BOTS & BUN_SQLITE_COBBLE_CHATROOMS & BUN_SQLITE_COBBLE_BOT_SESSIONS & BUN_SQLITE_COBBLE_BOT_MESSAGES & BUN_SQLITE_COBBLE_BOT_MESSAGE_REACTIONS & BUN_SQLITE_COBBLE_BOT_TASKS & BUN_SQLITE_COBBLE_BOT_TASK_STEPS & BUN_SQLITE_COBBLE_TASKS & BUN_SQLITE_COBBLE_TASK_MEDIA & BUN_SQLITE_COBBLE_TASK_NOTES & BUN_SQLITE_COBBLE_BOTS_QUEUE & BUN_SQLITE_COBBLE_BOTS_QUEUE_UPDATES & BUN_SQLITE_COBBLE_CRON_JOBS & BUN_SQLITE_COBBLE_BOT_HOOKS & BUN_SQLITE_COBBLE_BOT_HOOK_EVENTS & BUN_SQLITE_COBBLE_HOOK_PROPOSALS & BUN_SQLITE_COBBLE_SECRET_REQUESTS & BUN_SQLITE_COBBLE_INSTALL_REQUESTS & BUN_SQLITE_COBBLE_BOT_QUESTIONS & BUN_SQLITE_COBBLE_BOT_SUGGESTIONS & BUN_SQLITE_COBBLE_BOT_GRAPHICS & BUN_SQLITE_COBBLE_WORKSPACES & BUN_SQLITE_COBBLE_WORKSPACE_BOTS & BUN_SQLITE_COBBLE_BOT_TYPES & BUN_SQLITE_COBBLE_WORKSPACE_USERS & BUN_SQLITE_COBBLE_BOT_USERS & BUN_SQLITE_COBBLE_BOT_USER_VISITS & BUN_SQLITE_COBBLE_WORKSPACE_USER_VISITS & BUN_SQLITE_COBBLE_WORKSPACE_USER_ROLES & BUN_SQLITE_COBBLE_BOT_USER_MEMORIES & BUN_SQLITE_COBBLE_BOT_USER_FACES & BUN_SQLITE_COBBLE_BOT_MESSAGE_MEDIA & BUN_SQLITE_COBBLE_CONTAINERS & BUN_SQLITE_COBBLE_COMPUTERS & BUN_SQLITE_COBBLE_BOT_COMPUTERS & BUN_SQLITE_COBBLE_WORKSPACE_COMPUTERS & BUN_SQLITE_COBBLE_HARNESS_PROVIDERS & BUN_SQLITE_COBBLE_HARNESS_MODELS & BUN_SQLITE_COBBLE_HARNESS_SETTINGS & BUN_SQLITE_COBBLE_BOT_HARNESS_SETTINGS & BUN_SQLITE_COBBLE_WORKSPACE_HARNESS_SETTINGS & BUN_SQLITE_COBBLE_MCP_SERVERS & BUN_SQLITE_COBBLE_BROWSERS & BUN_SQLITE_COBBLE_BROWSER_ACCESS & BUN_SQLITE_COBBLE_CUSTOM_TOOLS & BUN_SQLITE_COBBLE_SKILLS & BUN_SQLITE_COBBLE_EXTENSION_PROPOSALS & BUN_SQLITE_COBBLE_BOT_MCP_SERVERS & BUN_SQLITE_COBBLE_WORKSPACE_MCP_SERVERS & BUN_SQLITE_COBBLE_BOT_CUSTOM_TOOLS & BUN_SQLITE_COBBLE_WORKSPACE_CUSTOM_TOOLS & BUN_SQLITE_COBBLE_BOT_SKILLS & BUN_SQLITE_COBBLE_WORKSPACE_SKILLS & BUN_SQLITE_COBBLE_KNOWLEDGEBASES & BUN_SQLITE_COBBLE_KNOWLEDGEBASE_DOCUMENTS & BUN_SQLITE_COBBLE_KNOWLEDGEBASE_CHUNKS & BUN_SQLITE_COBBLE_KNOWLEDGEBASE_VECTORS & BUN_SQLITE_COBBLE_BOT_KNOWLEDGEBASES & BUN_SQLITE_COBBLE_WORKSPACE_KNOWLEDGEBASES & BUN_SQLITE_COBBLE_LOGS & BUN_SQLITE_COBBLE_USER_PRESENCE & BUN_SQLITE_COBBLE_PUSH_SUBSCRIPTIONS & BUN_SQLITE_COBBLE_ENVS & BUN_SQLITE_COBBLE_BOT_FILES & BUN_SQLITE_COBBLE_TOKEN_USAGES & BUN_SQLITE_COBBLE_HARNESS_CALL_FAILURES & BUN_SQLITE_COBBLE_FILE_INGEST_QUEUE & BUN_SQLITE_COBBLE_APP_SETTINGS
+2 -1
View File
@@ -1,6 +1,6 @@
{
"name": "cobble",
"version": "0.18.9",
"version": "0.19.0",
"module": "index.ts",
"type": "module",
"private": true,
@@ -35,6 +35,7 @@
"@types/sanitize-html": "^2.16.2",
"@types/turndown": "^5.0.6",
"@types/web-push": "^3.6.4",
"marked": "17.0.6",
"tailwindcss": "^4.3.3"
},
"peerDependencies": {
+38 -11
View File
@@ -17,6 +17,7 @@ import {
CoordinatorSoloNote,
TasksNote,
TaskReminderNote,
HandOverTaskNote,
workspaceAdminNote,
WorkspaceLearningNote,
openRunsNote,
@@ -61,6 +62,7 @@ import markReplyAnswered from "@/src/functions/backend/db/bots-queue/mark-reply-
import sendMessageTool from "@/src/harness/tools/bot/send-message-tool";
import grabBotSecretTools from "@/src/harness/tools/bot/secrets/grab-bot-secret-tools";
import askUserTool from "@/src/harness/tools/bot/questions/ask-user-tool";
import suggestNextStepsTool from "@/src/harness/tools/bot/suggestions/suggest-next-steps-tool";
import type { BotMessageWithAttachments } from "@/src/types";
import type { HarnessMessage } from "@/src/harness/types";
import type { BotJobContext, BotJobOutcome } from "./types";
@@ -211,8 +213,9 @@ export default async function runBotReply({
*/
const proposals: string[] = [];
/**
* The secrets the bot showed (`show_secret`) and the graphics it made
* or changed, whose chips the reply always carries.
* The secrets the bot showed (`show_secret`), the graphics it made
* or changed, and the next steps it suggested: their chips the reply
* always carries, without needing the user.
*/
const shown: string[] = [];
/**
@@ -329,6 +332,12 @@ export default async function runBotReply({
* admin is told who leads it.
*/
const can_delegate = tools.some((tool) => tool.name == "delegate_task");
/**
* A worker passes on a task of its own (`hand_over_task`): the reply says
* where it went and that it needs the run id, so no one claims a hand-over
* that didn't happen.
*/
const can_hand_over = tools.some((tool) => tool.name == "hand_over_task");
const lead = led as WorkspaceAdminTools | null;
const crew_note = powers.is_coordinator
? can_delegate
@@ -355,9 +364,10 @@ export default async function runBotReply({
ComputerFilesNote({ computer_id: computers[0]?.id || 0, dirs, can_import: false }),
TasksNote,
TaskReminderNote,
can_hand_over ? HandOverTaskNote : "",
ActionCheckNote,
RequestScopeNote({ can_ask: true }),
QuestionsNote,
RequestScopeNote({ can_ask: Boolean(attended) }),
attended ? QuestionsNote : "",
SecretsNote,
SettingsNote,
composeEnvsNote({ ...envs, has_computer: computers.length > 0 }),
@@ -408,13 +418,30 @@ export default async function runBotReply({
onRequest: ({ ref }) => proposals.push(ref),
onShow: ({ ref }) => shown.push(ref),
}),
askUserTool({
user_id,
bot_id: bot.id,
session_id,
workspace_id,
onAsk: ({ ref }) => proposals.push(ref),
}),
/**
* Only where the user follows the conversation: a chatroom's
* hidden session has no card they could answer, and a
* question there was once shown to the coordinator as a bare
* ref, its answer never reaching the bot.
*/
...(attended
? [
askUserTool({
user_id,
bot_id: bot.id,
session_id,
workspace_id,
onAsk: ({ ref }) => proposals.push(ref),
}),
suggestNextStepsTool({
user_id,
bot_id: bot.id,
session_id,
workspace_id,
onSuggest: ({ ref }) => shown.push(ref),
}),
]
: []),
...(has_past_sessions
? [searchPastSessionsTool(past_scope), readPastSessionTool(past_scope)]
: []),
+14 -1
View File
@@ -45,6 +45,7 @@ import openBotKnowledgebases from "@/src/harness/tools/knowledgebases/open-bot-k
import grabBotTools from "@/src/harness/tools/bot/grab-bot-tools";
import grabBotSecretTools from "@/src/harness/tools/bot/secrets/grab-bot-secret-tools";
import askUserTool from "@/src/harness/tools/bot/questions/ask-user-tool";
import suggestNextStepsTool from "@/src/harness/tools/bot/suggestions/suggest-next-steps-tool";
import createWorkspaceTool from "@/src/harness/tools/bot/create-workspace-tool";
import updateWorkspaceTool from "@/src/harness/tools/bot/update-workspace-tool";
import listWorkspacePeopleTool from "@/src/harness/tools/bot/list-workspace-people-tool";
@@ -163,6 +164,11 @@ export default async function runBotTask({
signal,
}).catch(() => "");
const take_overs: string[] = [];
/**
* The next steps the bot suggested: added to the message without
* needing the user.
*/
const suggestions: string[] = [];
/**
* Files the bot wrote and asked to send with its report.
*/
@@ -285,6 +291,13 @@ export default async function runBotTask({
in_task: true,
onAsk: ({ ref }) => take_overs.push(ref),
}),
suggestNextStepsTool({
user_id,
bot_id: bot.id,
session_id,
workspace_id,
onSuggest: ({ ref }) => suggestions.push(ref),
}),
]
: []),
...(scheduled || hooked ? [reportRunFailedTool({ onFail: ({ reason }) => (failure = reason) })] : []),
@@ -534,7 +547,7 @@ export default async function runBotTask({
...withTakeOverRefs({
text: computer ? computer.redact(text) : text,
refs: take_overs,
shown,
shown: [...shown, ...suggestions],
}),
attachments: attachments.length ? attachments : undefined,
tool_log: result.tool_uses,
@@ -1,5 +1,6 @@
import { describe, expect, test } from "bun:test";
import takeOverRef from "@/src/utils/take-over-ref";
import botSuggestionRef from "@/src/utils/bot-suggestion-ref";
import withTakeOverRefs from "./with-take-over-refs";
const ref = takeOverRef({ id: 1, mode: "browser" });
@@ -21,4 +22,13 @@ describe("withTakeOverRefs", () => {
test("leaves a message without a take-over alone", () => {
expect(withTakeOverRefs({ text: "Done.", refs: [] })).toEqual({ result: "Done.", needs_you: false });
});
test("adds suggested next steps without needing the user", () => {
const suggestions = botSuggestionRef({ id: 4 });
expect(withTakeOverRefs({ text: "Done.", refs: [], shown: [suggestions] })).toEqual({
result: `Done.\n\n${suggestions}`,
needs_you: false,
});
});
});
+5 -3
View File
@@ -6,8 +6,9 @@ type Params = {
*/
refs: string[];
/**
* The secrets it showed (`secretRef`): added the same way, but they
* don't need the user.
* The secrets it showed (`secretRef`) and the next steps it suggested
* (`botSuggestionRef`): added the same way, but they don't need the
* user, so neither makes the message.
*/
shown?: string[];
};
@@ -16,7 +17,8 @@ type Params = {
* A job's message with every take-over the bot asked for in it and every
* proposal it made: refs the bot didn't write itself are added at the
* end, so the user always gets the button. A message asking for either
* needs the user.
* needs the user; secrets it showed and next steps it suggested are added
* without asking anything of them.
*/
export default function withTakeOverRefs({ text, refs, shown = [] }: Params) {
const missing = [...new Set([...refs, ...shown])].filter((ref) => !text.includes(ref));
+13
View File
@@ -977,6 +977,19 @@ export const AppData = {
* Longest answer a user may type into a question's "Other".
*/
BotQuestionOtherMaxChars: 1000,
/**
* Most next steps one `suggest_next_steps` row offers.
*/
BotSuggestionMaxSteps: 4,
/**
* Longest one suggested next step may be (the text that fills the
* user's input).
*/
BotSuggestionStepMaxChars: 120,
/**
* Longest heading a bot may give its suggested next steps.
*/
BotSuggestionTitleMaxChars: 120,
/**
* Longest dictation the composer records before it stops on its own.
*/
+17 -3
View File
@@ -418,6 +418,20 @@ You have tasks of your own to keep up with. When the message is an opening ("hel
- 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.`;
/**
* Added to a chat reply that has `hand_over_task`: a worker hands a task it
* already has to another bot, instead of asking the coordinator to reassign
* it (which no tool of its own can do, and a room once answered as if it
* had been done).
*/
export const HandOverTaskNote = `# Passing a task on
A task on your own list can go to another bot with hand_over_task: it moves to their list, they work that same task, and their result comes back to this conversation. Do it only when the user asked for that task to go to that bot; the list is theirs and the work costs them a run.
- The task_id comes from list_tasks, and it has to be your own open task. You can't create work for another bot, and you can't move a workspace-wide task.
- Say where it went with the run id the tool returned. Never say a task was handed over, or that someone picked work up, without it.
- Handing over is not asking: when you only need an answer from another bot, use ask_crew.`;
/**
* Added after `TaskRunNote` when the task is a scheduled run (a routine):
* the user approved its brief when they set it up, so it acts on its own.
@@ -536,9 +550,9 @@ Each turn, decide and act with one of your tools:
askable.length
? askable.map((bot) => `${bot.id}: ${bot.name || "A bot"}${bot.role ? ` (${bot.role})` : ""}`).join("; ")
: "none"
}. Their work comes back to you in the room, and you get another turn.
- answer_requester: once you have what was asked for, send it back. Write the answer itself, complete and in markdown, not a pointer to the room. Keep every ref the bot gave ([file:ID], [bot:ID], ...) exactly as written and outside backticks, so the asking bot and the user can open what it made: files the asking bot can't read are copied into its folder as the answer goes out.
- refuse_request: when no one here can answer it, or it shouldn't be done (it asks for something outside what the user would want, or reaches beyond the bots above). Say why.
}. Their work comes back to you in the room, and you get another turn. A message from one of them while it works is where it has got to, not its answer: it may still be running a task for many minutes, and only its answer, its failure, or its finished report speaks for it.
- answer_requester: once you have what was asked for, send it back. Write the answer itself, complete and in markdown, not a pointer to the room. Keep every ref the bot gave ([file:ID], [bot:ID], ...) exactly as written and outside backticks, so the asking bot and the user can open what it made: files the asking bot can't read are copied into its folder as the answer goes out. Answering closes the room and cancels anything still running in it, so while a bot is working the tool refuses unless you pass close_anyway: pass it only when the answer doesn't depend on what that bot is doing.
- refuse_request: when no one here can answer it, or it shouldn't be done (it asks for something outside what the user would want, or reaches beyond the bots above). Say why, concretely: what the blocker is, who can clear it and how. Same close_anyway rule. Never turn a request into a claim that it was carried out: you can't create, edit, move or reassign a task, add a bot to a workspace, or start a run for anyone, and nothing you say makes one happen. A task is moved by the bot that has it (its hand_over_task) or by the user (Hand over in the UI); when that's what was asked for, say so and name that bot.
Ask one bot at a time and only ask again when the answer falls short. You have ${turns_left} turn${turns_left == 1 ? "" : "s"} left in this room; on the last one, answer with what you have or refuse. Your own words in the room are short notes on what you're doing.`;
+15 -2
View File
@@ -27,6 +27,10 @@ export const BotPermissions = [
value: "delegate_task",
title: "Hand tasks to other bots",
},
{
value: "hand_over_task",
title: "Hand a task on its own list to another bot",
},
{
value: "set_member_instructions",
title: "Set other bots' workspace instructions",
@@ -72,18 +76,27 @@ export const BotTypePermissionMatrix: Record<BotRole, BotPermission[]> = {
coordinator: BotPermissions.map((bp) => bp.value),
workspace_admin: [
"delegate_task",
"hand_over_task",
"set_member_instructions",
"manage_workspace_tasks",
"edit_workspace",
],
worker: [],
/**
* A worker can't hand out work: it passes on a task it already has
* (`hand_over_task`), and asks the crew for anything else through the
* coordinator (`ask_crew`).
*/
worker: ["hand_over_task"],
};
/**
* Which bots a bot may act on (hand a task to, set instructions for), keyed
* by the target's role. Same shape as `UserTypeAssignmentMatrix`: the
* coordinator passes through. A workspace admin directs workers only, so
* two admins never hand work back and forth.
* two admins never hand work back and forth. A worker directs no one
* either: `hand_over_task` takes a task it already has to a bot it could
* ask, which its own tool decides (`chatroomAskableBots`), not this
* matrix.
*/
export const BotTypeTargetMatrix: TypeAssignmentMatrixType<BotRole> = {
coordinator: {},
@@ -0,0 +1,37 @@
import BunSQLite from "@moduletrace/bun-sqlite";
import type { BUN_SQLITE_COBBLE_BOT_SUGGESTIONS, BunSQLiteTables } from "@/db/types/db";
type Params = {
user_id: number | string;
bot_id: number | string;
session_id: number | string;
workspace_id?: number | string | null;
title: string;
steps: string[];
};
/**
* Stores next steps a bot suggests under its answer, read back as buttons
* that put a step in the user's input. Returns its id.
*/
export default async function createBotSuggestion({ user_id, bot_id, session_id, workspace_id, title, steps }: Params) {
const res = await BunSQLite.insert<BUN_SQLITE_COBBLE_BOT_SUGGESTIONS, (typeof BunSQLiteTables)[number]>({
table: "bot_suggestions",
data: [
{
title,
steps: JSON.stringify(steps),
user_id: Number(user_id),
bot_id: Number(bot_id),
session_id: Number(session_id),
workspace_id: workspace_id ? Number(workspace_id) : undefined,
},
],
});
const id = Number(res.singleRes?.id || res.postInsertReturn?.insertId);
if (!res.success || !id) throw new Error(`Couldn't store the suggested next steps: ${res.msg}`);
return id;
}
@@ -0,0 +1,33 @@
import BunSQLite from "@moduletrace/bun-sqlite";
import type { BotSuggestionView } from "@/src/types";
import grabBotSuggestion from "./grab-bot-suggestion";
import parseBotSuggestionRow from "@/src/utils/parse-bot-suggestion-row";
type Params = {
suggestion_id: number | string;
user_id: number | string;
};
/**
* Next steps a bot suggested as the thread shows them: its heading and the
* steps, each a button that puts it in the user's input.
*/
export default async function grabBotSuggestionView({ suggestion_id, user_id }: Params): Promise<BotSuggestionView> {
const row = await grabBotSuggestion({ suggestion_id, user_id });
const { steps } = parseBotSuggestionRow({ row });
const bot = (
await BunSQLite.sql<{ name: string }>({
sql: `SELECT name FROM bots WHERE id = ? LIMIT 1`,
values: [row.bot_id || 0],
})
).payload?.[0];
return {
id: Number(row.id),
title: row.title || "",
steps,
bot_id: Number(row.bot_id),
bot_name: bot?.name || "The bot",
};
}
@@ -0,0 +1,28 @@
import BunSQLite from "@moduletrace/bun-sqlite";
import type { BUN_SQLITE_COBBLE_BOT_SUGGESTIONS } from "@/db/types/db";
import AppError from "@/src/utils/app-error";
type Params = {
suggestion_id: number | string;
/**
* Only the user they were suggested to reads them.
*/
user_id: number | string;
};
/**
* Next steps a bot suggested, only for the user they were suggested to.
* Throws otherwise.
*/
export default async function grabBotSuggestion({ suggestion_id, user_id }: Params) {
const row = (
await BunSQLite.sql<BUN_SQLITE_COBBLE_BOT_SUGGESTIONS>({
sql: `SELECT * FROM bot_suggestions WHERE id = ? AND user_id = ? LIMIT 1`,
values: [Number(suggestion_id), Number(user_id)],
})
).payload?.[0];
if (!row?.id) throw new AppError(`Those next steps aren't yours or no longer exist.`);
return row;
}
@@ -1,17 +1,24 @@
import BunSQLite from "@moduletrace/bun-sqlite";
import type { BUN_SQLITE_COBBLE_CHATROOMS } from "@/db/types/db";
import type { ChatroomBot, ChatroomJob, ChatroomSummary } from "@/src/types";
import grabChatroomUsage from "../usage/grab-chatroom-usage";
type Params = {
chatrooms: BUN_SQLITE_COBBLE_CHATROOMS[];
/**
* Sum what each room's bots spent there, for the room's own header. A
* list doesn't need it, and it costs a query per call.
*/
with_usage?: boolean;
};
/**
* Rooms with the bots in them, asking bot first, then the coordinator,
* then the bots it asked in the order they joined, the jobs still open in
* the room, and the workspace it's in by name.
* the room, the workspace it's in by name, and (when asked for) what its
* bots spent working there.
*/
export default async function chatroomSummaries({ chatrooms }: Params): Promise<ChatroomSummary[]> {
export default async function chatroomSummaries({ chatrooms, with_usage }: Params): Promise<ChatroomSummary[]> {
if (!chatrooms.length) return [];
const ids = chatrooms.map((room) => Number(room.id));
@@ -40,6 +47,7 @@ export default async function chatroomSummaries({ chatrooms }: Params): Promise<
).payload || [];
const workspace_ids = [...new Set(chatrooms.map((room) => Number(room.workspace_id)).filter(Boolean))];
const usage = with_usage ? await grabChatroomUsage({ chatroom_ids: ids }) : null;
const workspace_names = new Map(
(workspace_ids.length
? (
@@ -72,6 +80,7 @@ export default async function chatroomSummaries({ chatrooms }: Params): Promise<
session_id: Number(job.session_id),
})),
workspace_name: room.workspace_id ? workspace_names.get(Number(room.workspace_id)) || null : null,
...(usage ? { usage: usage.get(Number(room.id)) } : {}),
};
});
}
@@ -0,0 +1,43 @@
import BunSQLite from "@moduletrace/bun-sqlite";
type Params = {
message_id: number | string;
/**
* Only a message posted in one of the user's own rooms.
*/
user_id: number | string;
};
type ChatroomMessageRef = {
id: number;
created_at: number;
chatroom_id: number;
};
/**
* A message posted in a chatroom of the user's, with the room it's in, or
* null. The access check for what the message's details may show.
*/
export default async function grabChatroomMessage({
message_id,
user_id,
}: Params): Promise<ChatroomMessageRef | null> {
const row = (
await BunSQLite.sql<ChatroomMessageRef>({
sql: `SELECT m.id, m.created_at, s.chatroom_id FROM bot_messages m
JOIN bot_sessions s ON s.id = m.session_id
JOIN chatrooms c ON c.id = s.chatroom_id
WHERE m.id = ? AND c.user_id = ? AND s.chatroom_id IS NOT NULL
LIMIT 1`,
values: [message_id, user_id],
})
).payload?.[0];
if (!row?.id) return null;
return {
id: Number(row.id),
created_at: Number(row.created_at) || 0,
chatroom_id: Number(row.chatroom_id),
};
}
@@ -1,16 +1,21 @@
import BunSQLite from "@moduletrace/bun-sqlite";
import type { BUN_SQLITE_COBBLE_BOT_MESSAGES } from "@/db/types/db";
import type { BotMessageWithAttachments } from "@/src/types";
import grabMessageUsage from "../usage/grab-message-usage";
type Params = {
chatroom_id: number | string;
};
/**
* Every message in a chatroom, from every bot in it, oldest first. Rooms
* are short (the coordinator's turns are capped), so they're read whole.
* Every message in a chatroom, from every bot in it, oldest first, each
* with what it cost. Rooms are short (the coordinator's turns are capped),
* so they're read whole.
*/
export default async function grabChatroomMessages({ chatroom_id }: Params): Promise<BUN_SQLITE_COBBLE_BOT_MESSAGES[]> {
return (
export default async function grabChatroomMessages({
chatroom_id,
}: Params): Promise<BotMessageWithAttachments[]> {
const messages =
(
await BunSQLite.sql<BUN_SQLITE_COBBLE_BOT_MESSAGES>({
sql: `SELECT m.* FROM bot_messages m JOIN bot_sessions s ON s.id = m.session_id
@@ -18,6 +23,15 @@ export default async function grabChatroomMessages({ chatroom_id }: Params): Pro
ORDER BY m.created_at ASC, m.id ASC`,
values: [chatroom_id],
})
).payload || []
);
}
).payload || [];
if (!messages.length) return messages;
const usage = await grabMessageUsage({ message_ids: messages.map((message) => Number(message.id)) });
return messages.map((message): BotMessageWithAttachments => {
const spent = usage.get(Number(message.id));
return spent ? { ...message, usage: spent } : message;
});
}
@@ -0,0 +1,41 @@
import BunSQLite from "@moduletrace/bun-sqlite";
type Params = {
chatroom_id: number | string;
/**
* The job asking (the coordinator's own turn), which is still running as
* it reads: never counted.
*/
except_job_id?: number | string | null;
};
export type ChatroomOpenJob = {
id: number;
bot_id: number | null;
bot_name: string | null;
status: string;
};
/**
* The jobs a room still runs (pending or processing), with the bot each
* works for: closing a room cancels them (`cancelChatroomJobs`), so the
* tools that close one ask first whether anyone is still at work.
*/
export default async function grabChatroomOpenJobs({ chatroom_id, except_job_id }: Params): Promise<ChatroomOpenJob[]> {
const res = await BunSQLite.sql<ChatroomOpenJob>({
sql: `SELECT q.id, q.bot_id, b.name AS bot_name, q.status
FROM bots_queue q
JOIN bot_sessions s ON s.id = q.session_id
LEFT JOIN bots b ON b.id = q.bot_id
WHERE s.chatroom_id = ? AND q.status IN ('pending', 'processing') AND q.id != ?
ORDER BY q.id`,
values: [Number(chatroom_id), Number(except_job_id) || 0],
});
return (res.payload || []).map((job) => ({
id: Number(job.id),
bot_id: job.bot_id ? Number(job.bot_id) : null,
bot_name: job.bot_name || null,
status: job.status,
}));
}
@@ -8,12 +8,13 @@ type Params = {
};
/**
* One of the user's own chatrooms with the bots in it, or null.
* One of the user's own chatrooms with the bots in it and what they spent
* working there, or null.
*/
export default async function grabUserChatroom({ chatroom_id, user_id }: Params): Promise<ChatroomSummary | null> {
const room = await grabChatroom({ chatroom_id, user_id });
if (!room?.id) return null;
return (await chatroomSummaries({ chatrooms: [room] }))[0] || null;
return (await chatroomSummaries({ chatrooms: [room], with_usage: true }))[0] || null;
}
@@ -1,5 +1,6 @@
import type { BUN_SQLITE_COBBLE_BOT_MESSAGES } from "@/db/types/db";
import { sendToUser } from "@/src/websocket/(functions)/send-to-user";
import withMessageUsage from "../usage/with-message-usage";
import grabChatroom from "./grab-chatroom";
import pushChatroomUpdated from "./push-chatroom-updated";
@@ -9,18 +10,20 @@ type Params = {
};
/**
* Pushes a message posted in a room (`server:chatroom-message`) and the
* room as it is now to the room's user.
* Pushes a message posted in a room (`server:chatroom-message`), with what
* it cost, and the room as it is now to the room's user.
*/
export default async function pushChatroomMessage({ chatroom_id, message }: Params) {
const room = await grabChatroom({ chatroom_id });
if (!room?.id || !room.user_id) return;
const [pushed] = await withMessageUsage({ messages: [message] });
sendToUser({
user_id: room.user_id,
data: { event: "server:chatroom-message", data: { chatroom_id: Number(room.id), message } },
data: { event: "server:chatroom-message", data: { chatroom_id: Number(room.id), message: pushed } },
});
await pushChatroomUpdated({ chatroom_id: room.id });
}
}
@@ -9,7 +9,8 @@ type Params = {
/**
* Pushes a room as it is now (`server:chatroom-updated`) to its user's
* open tabs, for the rail and the room's header. Best effort.
* open tabs, for the rail and the room's header, what its bots spent
* included, for the totals at its top. Best effort.
*/
export default async function pushChatroomUpdated({ chatroom_id }: Params) {
try {
@@ -17,7 +18,7 @@ export default async function pushChatroomUpdated({ chatroom_id }: Params) {
if (!room?.id || !room.user_id) return;
const [summary] = await chatroomSummaries({ chatrooms: [room] });
const [summary] = await chatroomSummaries({ chatrooms: [room], with_usage: true });
if (summary) {
sendToUser({ user_id: room.user_id, data: { event: "server:chatroom-updated", data: summary } });
@@ -0,0 +1,145 @@
import { Database } from "bun:sqlite";
import { describe, expect, test } from "bun:test";
import { chatroomUsageCallsSql, chatroomUsageFailuresSql } from "./chatroom-usage-sql";
type Call = {
session_id: number | null;
job_id: number | null;
prompt_tokens: number;
cached_tokens: number | null;
completion_tokens: number;
cost: number | null;
};
function seed() {
const db = new Database(":memory:");
db.run(`CREATE TABLE bot_sessions (id INTEGER PRIMARY KEY, bot_id INTEGER, chatroom_id INTEGER, hook_id INTEGER)`);
db.run(`CREATE TABLE token_usages (id INTEGER PRIMARY KEY, bot_id INTEGER, session_id INTEGER, job_id INTEGER,
prompt_tokens INTEGER, cached_tokens INTEGER, completion_tokens INTEGER, cost REAL)`);
db.run(`CREATE TABLE harness_call_failures (id INTEGER PRIMARY KEY, bot_id INTEGER, session_id INTEGER, job_id INTEGER)`);
/**
* Room 1 has one hidden session per bot; 300 belongs to another room,
* 400 to a bot's own conversation (no room), 500 to a hook's own.
*/
db.run(`INSERT INTO bot_sessions VALUES
(100, 10, 1, NULL), (200, 20, 1, NULL), (300, 10, 2, NULL), (400, 10, NULL, NULL), (500, 20, NULL, 3)`);
let calls = 0;
const addCall = ({ bot_id, call }: { bot_id: number; call: Call }) =>
db.run(`INSERT INTO token_usages (id, bot_id, session_id, job_id, prompt_tokens, cached_tokens, completion_tokens, cost)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)`, [
++calls,
bot_id,
call.session_id,
call.job_id,
call.prompt_tokens,
call.cached_tokens,
call.completion_tokens,
call.cost,
]);
let failures = 0;
const addFailure = ({ bot_id, session_id }: { bot_id: number; session_id: number | null }) =>
db.run(`INSERT INTO harness_call_failures (id, bot_id, session_id, job_id) VALUES (?, ?, ?, NULL)`, [
++failures,
bot_id,
session_id,
]);
return { db, addCall, addFailure };
}
function callsByRoom({ db }: { db: Database }) {
const { sql, values } = chatroomUsageCallsSql({ chatroom_ids: [1] });
const rows = db.query(sql).all(...values) as {
chatroom_id: number;
bot_id: number;
calls: number;
prompt_tokens: number;
cached_tokens: number;
completion_tokens: number;
cost: number;
}[];
return rows
.map((row) => ({
chatroom_id: Number(row.chatroom_id),
bot_id: Number(row.bot_id),
calls: Number(row.calls),
prompt_tokens: Number(row.prompt_tokens),
cached_tokens: Number(row.cached_tokens),
completion_tokens: Number(row.completion_tokens),
cost: Number(row.cost),
}))
.sort((a, b) => a.bot_id - b.bot_id);
}
function failuresByRoom({ db }: { db: Database }) {
const { sql, values } = chatroomUsageFailuresSql({ chatroom_ids: [1] });
const rows = db.query(sql).all(...values) as { chatroom_id: number; failed_calls: number }[];
return rows.map((row) => ({ chatroom_id: Number(row.chatroom_id), failed_calls: Number(row.failed_calls) }));
}
describe("chatroomUsageCallsSql", () => {
test("sums a room's calls by bot", () => {
const { db, addCall } = seed();
addCall({
bot_id: 10,
call: { session_id: 100, job_id: null, prompt_tokens: 100, cached_tokens: 40, completion_tokens: 20, cost: 0.5 },
});
addCall({
bot_id: 10,
call: { session_id: 100, job_id: null, prompt_tokens: 50, cached_tokens: null, completion_tokens: 10, cost: null },
});
addCall({
bot_id: 20,
call: { session_id: 200, job_id: 50, prompt_tokens: 300, cached_tokens: 0, completion_tokens: 100, cost: 1 },
});
expect(callsByRoom({ db })).toEqual([
{ chatroom_id: 1, bot_id: 10, calls: 2, prompt_tokens: 150, cached_tokens: 40, completion_tokens: 30, cost: 0.5 },
{ chatroom_id: 1, bot_id: 20, calls: 1, prompt_tokens: 300, cached_tokens: 0, completion_tokens: 100, cost: 1 },
]);
});
test("another room's, a bot's own conversation's and a hook's calls stay out", () => {
const { db, addCall } = seed();
const call = { job_id: null, prompt_tokens: 10, cached_tokens: null, completion_tokens: 5, cost: null };
addCall({ bot_id: 10, call: { ...call, session_id: 100 } });
addCall({ bot_id: 10, call: { ...call, session_id: 300 } });
addCall({ bot_id: 10, call: { ...call, session_id: 400 } });
addCall({ bot_id: 20, call: { ...call, session_id: 500 } });
addCall({ bot_id: 10, call: { ...call, session_id: null } });
expect(callsByRoom({ db })).toEqual([
{ chatroom_id: 1, bot_id: 10, calls: 1, prompt_tokens: 10, cached_tokens: 0, completion_tokens: 5, cost: 0 },
]);
});
test("rooms with no calls have no rows", () => {
const { db } = seed();
expect(callsByRoom({ db })).toEqual([]);
});
});
describe("chatroomUsageFailuresSql", () => {
test("counts a room's failed calls, still-running turns included", () => {
const { db, addFailure } = seed();
addFailure({ bot_id: 10, session_id: 100 });
addFailure({ bot_id: 20, session_id: 200 });
addFailure({ bot_id: 10, session_id: 300 });
addFailure({ bot_id: 10, session_id: null });
expect(failuresByRoom({ db })).toEqual([{ chatroom_id: 1, failed_calls: 2 }]);
});
});
@@ -0,0 +1,46 @@
type Params = {
/**
* The rooms whose calls are read.
*/
chatroom_ids: number[];
};
const marks = ({ chatroom_ids }: Params) => chatroom_ids.map(() => "?").join(", ");
/**
* Every model call a room's bots made, by room and by bot, summed (read by
* `grabChatroomUsage`). A call is counted by the session it ran for (each
* bot in a room has its own hidden one, `bot_sessions.chatroom_id`), which
* is the run's own attribution: a turn still running counts too, before
* any message is written, so a room's total moves while it works.
*/
export function chatroomUsageCallsSql({ chatroom_ids }: Params) {
return {
sql: `SELECT s.chatroom_id AS chatroom_id, t.bot_id AS bot_id,
COUNT(*) AS calls,
SUM(t.prompt_tokens) AS prompt_tokens,
SUM(t.cached_tokens) AS cached_tokens,
SUM(t.completion_tokens) AS completion_tokens,
SUM(t.cost) AS cost
FROM token_usages t
JOIN bot_sessions s ON s.id = t.session_id
WHERE s.chatroom_id IN (${marks({ chatroom_ids })})
GROUP BY 1, 2`,
values: [...chatroom_ids],
};
}
/**
* The rooms' model calls that failed, by room, for the count beside the
* totals. Read the same way, by the session they ran for.
*/
export function chatroomUsageFailuresSql({ chatroom_ids }: Params) {
return {
sql: `SELECT s.chatroom_id AS chatroom_id, COUNT(*) AS failed_calls
FROM harness_call_failures t
JOIN bot_sessions s ON s.id = t.session_id
WHERE s.chatroom_id IN (${marks({ chatroom_ids })})
GROUP BY 1`,
values: [...chatroom_ids],
};
}
@@ -0,0 +1,82 @@
import BunSQLite from "@moduletrace/bun-sqlite";
import type { ChatroomUsage, ChatroomUsageBot } from "@/src/types";
import { chatroomUsageCallsSql, chatroomUsageFailuresSql } from "./chatroom-usage-sql";
import { sumSummary, toSummary } from "./grab-usage-totals";
type Params = {
/**
* The rooms whose usage is summed. A room no call touched is absent.
*/
chatroom_ids: (number | string)[];
};
type CallRow = {
chatroom_id: number;
bot_id: number | null;
calls: number | null;
prompt_tokens: number | null;
cached_tokens: number | null;
completion_tokens: number | null;
cost: number | null;
};
type FailureRow = {
chatroom_id: number;
failed_calls: number | null;
};
/**
* What each room's bots spent working in it: every model call they made
* there summed with the calls that failed, in total and per bot. A call
* belongs to the room through its run's own session, so a coordinator
* turn still running is counted before its answer is written, and a room's
* totals never wait for a message to land.
*/
export default async function grabChatroomUsage({ chatroom_ids }: Params): Promise<Map<number, ChatroomUsage>> {
const usage = new Map<number, ChatroomUsage>();
const ids = [...new Set(chatroom_ids.map(Number).filter((id) => id > 0))];
if (!ids.length) return usage;
const [call_res, failure_res] = await Promise.all([
BunSQLite.sql<CallRow>(chatroomUsageCallsSql({ chatroom_ids: ids })),
BunSQLite.sql<FailureRow>(chatroomUsageFailuresSql({ chatroom_ids: ids })),
]);
const calls = call_res.payload || [];
const failures = new Map(
(failure_res.payload || []).map((row) => [Number(row.chatroom_id), Number(row.failed_calls) || 0]),
);
const bot_ids = [...new Set(calls.map((row) => Number(row.bot_id)).filter((id) => id > 0))];
const names = new Map(
(
bot_ids.length
? (
await BunSQLite.sql<{ id: number; name: string }>({
sql: `SELECT id, name FROM bots WHERE id IN (${bot_ids.map(() => "?").join(", ")})`,
values: bot_ids,
})
).payload || []
: []
).map((row) => [Number(row.id), row.name || null]),
);
for (const id of ids) {
const by_bot: ChatroomUsageBot[] = calls
.filter((row) => Number(row.chatroom_id) == id)
.map((row) => ({
bot_id: Number(row.bot_id) || 0,
name: names.get(Number(row.bot_id)) || null,
...toSummary({ row }),
}))
.sort((a, b) => b.total_tokens - a.total_tokens || b.calls - a.calls);
usage.set(id, {
totals: sumSummary({ summaries: by_bot }),
failed_calls: failures.get(id) || 0,
by_bot,
});
}
return usage;
}
@@ -37,6 +37,9 @@ mock.module("@/src/functions/backend/db/workspaces/grab-user-workspaces", () =>
mock.module("@/src/functions/backend/db/bots/grab-crew-workers", () => ({
default: async () => workers,
}));
mock.module("@/src/functions/backend/db/chatrooms/chatroom-askable-bots", () => ({
default: async () => workers,
}));
const grabBotChatTools = (await import("./grab-bot-chat-tools")).default;
@@ -66,6 +69,32 @@ async function names({ workspace_id }: { workspace_id: number | null }) {
return tools.map((tool) => tool.name);
}
/**
* The same list for a plain worker: no work to hand out, only its own task to
* pass on, to a bot it could ask (`chatroomAskableBots`).
*/
async function workerNames({ workspace_id, allowed = ["hand_over_task"] }: { workspace_id: number | null; allowed?: string[] }) {
const worker = {
bot_types: [],
is_coordinator: false,
admin_workspace_ids: [],
is_workspace_admin: false,
can: (permission: string) => allowed.includes(permission),
};
const tools = await grabBotChatTools({
bot: { id: 5, kind: "worker", name: "SEO Expert" },
powers: worker,
user_id: 1,
computers: [],
session_id: 43,
workspace_id,
onPropose: () => {},
});
return tools.map((tool) => tool.name);
}
describe("grabBotChatTools", () => {
test("the coordinator in a workspace reaches the install's skills, servers and tools", async () => {
workers = [{ id: 5, name: "A worker", kind: "worker" }];
@@ -93,4 +122,23 @@ describe("grabBotChatTools", () => {
expect(list).toContain("list_extensions");
expect(list).toContain("propose_skill");
});
test("a worker gets no work to hand out, only its own task to pass on", async () => {
workers = [{ id: 6, name: "Software Engineer", kind: "worker" }];
const list = await workerNames({ workspace_id: 11 });
expect(list).toContain("hand_over_task");
expect(list).not.toContain("delegate_task");
expect(list).not.toContain("manage_workspace_tasks");
});
test("a worker whose types don't allow it gets neither", async () => {
workers = [{ id: 6, name: "Software Engineer", kind: "worker" }];
const list = await workerNames({ workspace_id: 11, allowed: [] });
expect(list).not.toContain("hand_over_task");
expect(list).not.toContain("delegate_task");
});
});
+32 -7
View File
@@ -24,6 +24,8 @@ import updateWorkspaceTool from "./update-workspace-tool";
import listWorkspacePeopleTool from "./list-workspace-people-tool";
import setUserWorkspaceRoleTool from "./set-user-workspace-role-tool";
import grabUserWorkspaces from "@/src/functions/backend/db/workspaces/grab-user-workspaces";
import chatroomAskableBots from "@/src/functions/backend/db/chatrooms/chatroom-askable-bots";
import handOverTaskTool from "./hand-over-task-tool";
import setWorkspaceInstructionsTool from "./set-workspace-instructions-tool";
import startTaskTool from "./start-task-tool";
import computerRunDirs from "@/src/utils/computer-work-dirs";
@@ -111,9 +113,10 @@ type Params = {
* workspace's crew (a bot's core prompt is asked for from wherever the
* user is), plus set_bot_type to make a worker a workspace's admin. A
* workspace admin, in the workspace it leads, gets
* `grabWorkspaceAdminTools`. Every gate reads the bot's types (`powers`),
* never `bots.kind`. Anything else on a computer goes through a task,
* never mid-reply.
* `grabWorkspaceAdminTools`. A worker gets no work to hand out, but it may
* pass on a task of its own to a bot it could ask (`hand_over_task`). Every
* gate reads the bot's types (`powers`), never `bots.kind`. Anything else on
* a computer goes through a task, never mid-reply.
*/
export default async function grabBotChatTools({
bot,
@@ -169,12 +172,34 @@ export default async function grabBotChatTools({
];
if (!powers.is_coordinator) {
if (!workspace_id || !powers.is_workspace_admin) return tools;
if (workspace_id && powers.is_workspace_admin) {
const admin = await grabWorkspaceAdminTools({ bot, user_id, workspace_id, powers, session_id, scopes, onTask });
const admin = await grabWorkspaceAdminTools({ bot, user_id, workspace_id, powers, session_id, scopes, onTask });
onWorkspaceAdmin?.(admin);
tools.push(...admin.tools);
onWorkspaceAdmin?.(admin);
tools.push(...admin.tools);
return tools;
}
/**
* Only what it already has goes: the bots it may hand to are the
* ones it could ask for this user, read again when it does.
*/
if (session_id && powers.can("hand_over_task")) {
const workers = await chatroomAskableBots({ user_id, requester_bot_id: bot_id, workspace_id });
tools.push(
handOverTaskTool({
user_id,
bot,
session_id,
powers,
workers,
grabTargets: () => chatroomAskableBots({ user_id, requester_bot_id: bot_id, workspace_id }),
onTask,
}),
);
}
return tools;
}
@@ -0,0 +1,161 @@
import { afterAll, beforeEach, describe, expect, mock, test } from "bun:test";
import type { BUN_SQLITE_COBBLE_BOTS, BUN_SQLITE_COBBLE_TASKS } from "@/db/types/db";
import type { BotRunPowers } from "@/src/functions/backend/db/bot-types/grab-bot-run-powers";
/**
* What `grabRunTask` answers: the task it would act on.
*/
let task: BUN_SQLITE_COBBLE_TASKS = {
id: 43,
title: "Cut the LCP on the homepage",
bot_id: 2,
workspace_id: 2,
status: "todo",
} as BUN_SQLITE_COBBLE_TASKS;
/**
* What `handOverTask` answers, and with which arguments it was called: a
* worker's hand-over has to carry the bot that had the task and the session
* the result is reported back to.
*/
let handed: Record<string, unknown> = {};
let handedArgs: Record<string, unknown> | null = null;
mock.module("@/src/functions/backend/db/tasks/grab-run-task", () => ({
default: async () => task,
}));
mock.module("@/src/functions/backend/db/tasks/hand-over-task", () => ({
default: async (args: Record<string, unknown>) => {
handedArgs = args;
return handed;
},
}));
const handOverTaskTool = (await import("./hand-over-task-tool")).default;
afterAll(() => {
mock.restore();
});
const bot = { id: 2, name: "SEO Expert", kind: "worker" } as BUN_SQLITE_COBBLE_BOTS;
const engineer = { id: 6, name: "Software Engineer", kind: "worker" } as BUN_SQLITE_COBBLE_BOTS;
const designer = { id: 3, name: "Graphic Designer", kind: "worker" } as BUN_SQLITE_COBBLE_BOTS;
const powers = {
bot_types: [],
is_coordinator: false,
admin_workspace_ids: [],
is_workspace_admin: false,
can: (permission: string) => permission == "hand_over_task",
} as unknown as BotRunPowers;
beforeEach(() => {
task = { id: 43, title: "Cut the LCP on the homepage", bot_id: 2, workspace_id: 2, status: "todo" } as BUN_SQLITE_COBBLE_TASKS;
handed = { task, job_id: 312, bot_name: "Software Engineer", workspace_id: 2, joined: "" };
handedArgs = null;
});
function build({ targets = [engineer, designer], onTask }: { targets?: BUN_SQLITE_COBBLE_BOTS[]; onTask?: (params: { task_id: number }) => void } = {}) {
return handOverTaskTool({
user_id: 1,
bot,
session_id: 43,
powers,
workers: targets,
grabTargets: async () => targets,
onTask,
});
}
describe("handOverTaskTool", () => {
test("takes a task of its own and one of the bots it can ask", () => {
const tool = build();
expect(tool.name).toBe("hand_over_task");
expect(tool.schema?.safeParse({ task_id: 43, bot_id: 6 }).success).toBe(true);
expect(tool.schema?.safeParse({ task_id: 43, bot_id: 6, start: false }).success).toBe(true);
expect(tool.schema?.safeParse({ bot_id: 6 }).success).toBe(false);
});
test("names the crew it can hand to", () => {
const tool = build();
expect(tool.description).toContain("6: Software Engineer; 3: Graphic Designer");
});
test("hands the task over with the bot and session to report back to", async () => {
const answer = await build().run({ args: { task_id: 43, bot_id: 6 }, signal: new AbortController().signal });
expect(handedArgs?.task_id).toBe(43);
expect(handedArgs?.to_bot_id).toBe(6);
expect(handedArgs?.user_id).toBe(1);
expect(handedArgs?.handed_by).toBe("SEO Expert");
expect(handedArgs?.requested_by_bot_id).toBe(2);
expect(handedArgs?.requested_by_session_id).toBe(43);
expect(handedArgs?.start).toBe(true);
expect(String(answer)).toContain("is with Software Engineer now (job #312)");
expect(String(answer)).toContain("it's off your list");
expect(String(answer)).toContain("their result is reported back here");
});
test("the same task, not a copy: it reports the new bot's joined note", async () => {
handed = { task, job_id: 312, bot_name: "Software Engineer", workspace_id: 2, joined: "It joined the workspace." };
const answer = await build().run({ args: { task_id: 43, bot_id: 6 }, signal: new AbortController().signal });
expect(String(answer)).toContain("It joined the workspace.");
});
test("start: false only moves it, and says nothing is running", async () => {
handed = { task, job_id: null, bot_name: "Software Engineer", workspace_id: 2, joined: "" };
const answer = await build().run({ args: { task_id: 43, bot_id: 6, start: false }, signal: new AbortController().signal });
expect(handedArgs?.start).toBe(false);
expect(String(answer)).toContain("as to do");
expect(String(answer)).toContain("Nothing is running");
});
test("reports the task it touched, so the message links it", async () => {
const touched: number[] = [];
await build({ onTask: ({ task_id }) => touched.push(task_id) }).run({ args: { task_id: 43, bot_id: 6 }, signal: new AbortController().signal });
expect(touched).toEqual([43]);
});
test("refuses a task that isn't its own", async () => {
task = { id: 44, title: "Someone else's", bot_id: 9, workspace_id: 2, status: "todo" } as BUN_SQLITE_COBBLE_TASKS;
await expect(build().run({ args: { task_id: 44, bot_id: 6 }, signal: new AbortController().signal })).rejects.toThrow(
"isn't on your own list (it's another bot's), so it isn't yours to hand over",
);
expect(handedArgs).toBeNull();
});
test("refuses a workspace-wide task", async () => {
task = { id: 44, title: "Everyone's", bot_id: null, workspace_id: 2, status: "todo" } as unknown as BUN_SQLITE_COBBLE_TASKS;
await expect(build().run({ args: { task_id: 44, bot_id: 6 }, signal: new AbortController().signal })).rejects.toThrow("(it's workspace-wide)");
});
test("refuses a bot it can't ask, and lists the ones it can", async () => {
await expect(build().run({ args: { task_id: 43, bot_id: 99 }, signal: new AbortController().signal })).rejects.toThrow(
"No bot has id 99 among the ones you can hand to. Bot: 6: Software Engineer; 3: Graphic Designer.",
);
expect(handedArgs).toBeNull();
});
test("with no crew says so", async () => {
const tool = build({ targets: [] });
expect(tool.description).toContain("Crew you can hand to: none.");
await expect(tool.run({ args: { task_id: 43, bot_id: 6 }, signal: new AbortController().signal })).rejects.toThrow(
"No bot has id 6 among the ones you can hand to. Bot: none.",
);
});
});
@@ -0,0 +1,128 @@
import { z } from "zod";
import type { BUN_SQLITE_COBBLE_BOTS } from "@/db/types/db";
import type { BotRunPowers } from "@/src/functions/backend/db/bot-types/grab-bot-run-powers";
import grabRunTask from "@/src/functions/backend/db/tasks/grab-run-task";
import handOverTask from "@/src/functions/backend/db/tasks/hand-over-task";
import type { HarnessTool } from "../../types";
type Params = {
user_id: number | string;
/**
* The bot passing its own task on: the worker that has it, or a
* workspace's admin.
*/
bot: BUN_SQLITE_COBBLE_BOTS;
/**
* The session it hands over from: the new bot's result is reported
* back there (`relayJobToRequester`).
*/
session_id: number | string;
/**
* The run's reach over the task tracker (`grabBotRunPowers`), beside the
* check that the task is this bot's own.
*/
powers: BotRunPowers;
/**
* The bots it may hand to, for the description (`chatroomAskableBots`).
*/
workers: BUN_SQLITE_COBBLE_BOTS[];
/**
* Reads the bots it may hand to when it does, so a bot added mid-run is
* there: the ones it could ask (`chatroomAskableBots`).
*/
grabTargets: () => Promise<BUN_SQLITE_COBBLE_BOTS[]>;
/**
* Called with the task it hands over, so the message the run posts links
* to it (`bot_messages.task_ids`).
*/
onTask?: (params: { task_id: number }) => void;
};
type Args = {
task_id: number;
bot_id: number;
/**
* False to only move it: the task goes to the other bot's list as to do
* and no job is queued, for when the user hasn't asked for the work to
* begin.
*/
start?: boolean;
};
/**
* Lets a bot give a task on its own list to another bot (`handOverTask`):
* the narrow hand-over of `delegate_task`, for the runs that have no right
* to hand out work. It only ever moves a task the run already has, only an
* open one, and only to a bot it could ask for the same user, so it can't
* create a task for someone else or widen a run's reach. The task keeps its
* place (a workspace's stays there), the other bot works that same task, and
* the result is reported back in this session.
*/
export default function handOverTaskTool({ user_id, bot, session_id, powers, workers, grabTargets, onTask }: Params): HarnessTool<Args> {
const bot_id = bot.id || 0;
const crew = workers.map((worker) => `${worker.id}: ${worker.name}`).join("; ");
return {
name: "hand_over_task",
description: `Hand over a task on your own list to another bot, when the user asked for that task to go to them. Pass its task_id (list_tasks) and the bot: the task moves to their list and they work that same task there, and their result is reported back here. Only a task of your own, and only an open one. To ask a bot something without giving it a task, use ask_crew; to have work made for another bot, ask the user. Crew you can hand to: ${crew || "none"}.`,
schema: z.object({
task_id: z.number().int().describe("An open task on your own list (list_tasks)"),
bot_id: z.number().int(),
start: z
.boolean()
.optional()
.describe("false to only move the task (to do, nothing runs) until the user says to start"),
}),
run: async ({ args }) => {
const task = await grabRunTask({
task_id: args.task_id,
bot_id,
is_coordinator: powers.is_coordinator,
admin_workspace_ids: powers.admin_workspace_ids,
});
/**
* A workspace-wide task is nobody's: handing it to one bot would
* take it away from the rest of the crew.
*/
if (Number(task.bot_id || 0) != bot_id) {
throw new Error(
`Task #${task.id} isn't on your own list (it's ${
task.workspace_id && !task.bot_id ? "workspace-wide" : "another bot's"
}), so it isn't yours to hand over.`,
);
}
const fresh = await grabTargets();
if (!fresh.some((target) => target.id == args.bot_id)) {
throw new Error(
`No bot has id ${args.bot_id} among the ones you can hand to. Bot: ${
fresh.map((target) => `${target.id}: ${target.name}`).join("; ") || "none"
}.`,
);
}
const handed = await handOverTask({
user_id,
task_id: Number(task.id),
to_bot_id: args.bot_id,
instructions: undefined,
handed_by: bot.name || "The bot that had it",
requested_by_bot_id: bot_id,
requested_by_session_id: session_id,
start: args.start !== false,
});
onTask?.({ task_id: Number(task.id) });
const where = handed.workspace_id ? ` in workspace ${handed.workspace_id}` : " in its own chat";
if (!handed.job_id) {
return `Task #${task.id} "${task.title}" is on ${handed.bot_name}'s list now${where}, as to do. Nothing is running: they start when the user tells them to.`;
}
return `Task #${task.id} "${task.title}" is with ${handed.bot_name} now (job #${handed.job_id})${where}, marked doing, and it's off your list.${handed.joined} They work that same task; their result is reported back here.`;
},
};
}
@@ -0,0 +1,23 @@
import { describe, expect, test } from "bun:test";
import suggestNextStepsTool from "./suggest-next-steps-tool";
const refs: string[] = [];
const tool = suggestNextStepsTool({ user_id: 1, bot_id: 2, session_id: 3, onSuggest: ({ ref }) => refs.push(ref) });
describe("suggestNextStepsTool", () => {
test("takes a set of steps with an optional heading", () => {
expect(tool.schema?.safeParse({ title: "What I can do next", steps: ["Write the report", "Email the team"] }).success).toBe(true);
expect(tool.schema?.safeParse({ steps: ["Write the report"] }).success).toBe(true);
});
test("needs at least one step and no duplicates", () => {
expect(tool.schema?.safeParse({ steps: [] }).success).toBe(false);
expect(tool.schema?.safeParse({ steps: ["Write the report", "write the report"] }).success).toBe(false);
expect(tool.schema?.safeParse({ steps: [" "] }).success).toBe(false);
});
test("caps how many steps one row holds and how long each is", () => {
expect(tool.schema?.safeParse({ steps: Array.from({ length: 5 }, (_, i) => `Step ${i}`) }).success).toBe(false);
expect(tool.schema?.safeParse({ steps: ["x".repeat(121)] }).success).toBe(false);
});
});
@@ -0,0 +1,71 @@
import { z } from "zod";
import createBotSuggestion from "@/src/functions/backend/db/bot-suggestions/create-bot-suggestion";
import { AppData } from "@/src/data/app-data";
import { BotSuggestionStepsSchema } from "@/src/schemas/bot-suggestion-schema";
import botSuggestionRef from "@/src/utils/bot-suggestion-ref";
import type { HarnessTool } from "../../../types";
type Params = {
user_id: number | string;
bot_id: number | string;
/**
* The conversation they show in.
*/
session_id: number | string;
workspace_id?: number | string | null;
/**
* Called with the suggestions' ref, so the message always carries
* their buttons.
*/
onSuggest: (params: { ref: string }) => void;
};
type Args = {
title?: string;
steps: z.infer<typeof BotSuggestionStepsSchema>;
};
/**
* Offers the user concrete next steps as buttons under the bot's answer.
* Clicking one puts it in their input; nothing waits on it, unlike
* `ask_user`, so the reply goes on as usual. Once per run, so every
* suggestion lands in one row.
*/
export default function suggestNextStepsTool({ user_id, bot_id, session_id, workspace_id, onSuggest }: Params): HarnessTool<Args> {
let suggested = false;
return {
name: "suggest_next_steps",
description: `Offer the user next steps they can take from here, shown as buttons under your answer: clicking one puts it in their input for them to send. Use it once the work is done or a reply is complete, to make follow-ups one click away (your best suggestion first). This never waits for a response: don't ask the user to pick one, don't put the answers on hold, and carry on as if they may ignore it. When their answer decides what you do next, use ask_user instead. Don't suggest what they already asked for, and don't repeat the steps in your text.`,
schema: z.object({
title: z
.string()
.trim()
.max(AppData.BotSuggestionTitleMaxChars)
.optional()
.describe(`A short heading for the row, e.g. "What I can do next" (defaults to "Next steps")`),
steps: BotSuggestionStepsSchema.describe("The suggested steps, best first, each written as the message the user would send"),
}),
run: async ({ args }) => {
if (suggested) {
throw new Error(`You already suggested next steps in this run. Put every suggestion in one suggest_next_steps call.`);
}
const id = await createBotSuggestion({
user_id,
bot_id,
session_id,
workspace_id,
title: args.title?.trim() || "",
steps: args.steps,
});
suggested = true;
onSuggest({ ref: botSuggestionRef({ id }) });
const count = args.steps.length;
return `Suggested ${count} next step${count == 1 ? "" : "s"}: the buttons are under your message, and clicking one puts it in the user's input. They need do nothing; don't wait for them and don't repeat the steps in your text.`;
},
};
}
@@ -0,0 +1,87 @@
import { afterAll, beforeEach, describe, expect, mock, test } from "bun:test";
import type { BUN_SQLITE_COBBLE_CHATROOMS } from "@/db/types/db";
/**
* Jobs still running in the room. Closing cancels them, so the tool has to
* refuse over one: a coordinator once answered while the Software Engineer
* ran the work it had been asked for, the run died with "The chatroom
* closed", and the answer said the tasks were picked up.
*/
let open: { id: number; bot_id: number | null; bot_name: string | null; status: string }[] = [];
let closedArgs: Record<string, unknown> | null = null;
let closed = true;
mock.module("@/src/functions/backend/db/chatrooms/grab-chatroom-open-jobs", () => ({
default: async () => open,
}));
mock.module("@/src/functions/backend/db/chatrooms/share-room-files", () => ({
default: async ({ answer }: { answer: string }) => answer,
}));
mock.module("@/src/functions/backend/db/chatrooms/close-chatroom", () => ({
default: async (args: Record<string, unknown>) => {
closedArgs = args;
return closed;
},
}));
const answerRequesterTool = (await import("./answer-requester-tool")).default;
afterAll(() => {
mock.restore();
});
const room = { id: 3, status: "open", requester_bot_id: 2 } as BUN_SQLITE_COBBLE_CHATROOMS;
beforeEach(() => {
open = [];
closedArgs = null;
closed = true;
});
function build(onClosed?: () => void) {
return answerRequesterTool({ chatroom: room, job_id: 300, onClosed });
}
describe("answerRequesterTool", () => {
test("answers and closes the room when nothing else runs", async () => {
const acted: string[] = [];
const answer = await build(() => acted.push("closed")).run({ args: { answer: "The plan." }, signal: new AbortController().signal });
expect(String(answer)).toContain("The room is closed");
expect(closedArgs?.status).toBe("answered");
expect(closedArgs?.outcome).toBe("The plan.");
expect(closedArgs?.job_id).toBe(300);
expect(acted).toEqual(["closed"]);
});
test("refuses while a member job still runs, naming it", async () => {
open = [{ id: 295, bot_id: 6, bot_name: "Software Engineer", status: "processing" }];
await expect(build().run({ args: { answer: "Done." }, signal: new AbortController().signal })).rejects.toThrow(
"Still working here: Software Engineer (run #295, processing). Answering closes the room and cancels that run",
);
expect(closedArgs).toBeNull();
});
test("close_anyway answers over it", async () => {
open = [{ id: 295, bot_id: 6, bot_name: "Software Engineer", status: "processing" }];
await build().run({ args: { answer: "Not needed after all.", close_anyway: true }, signal: new AbortController().signal });
expect(closedArgs?.status).toBe("answered");
});
test("a room already closed is reported, not acted on", async () => {
closed = false;
const acted: string[] = [];
await expect(build(() => acted.push("closed")).run({ args: { answer: "Late." }, signal: new AbortController().signal })).rejects.toThrow(
"This room is already closed.",
);
expect(acted).toEqual([]);
});
});
@@ -1,7 +1,9 @@
import { z } from "zod";
import type { BUN_SQLITE_COBBLE_CHATROOMS } from "@/db/types/db";
import closeChatroom from "@/src/functions/backend/db/chatrooms/close-chatroom";
import grabChatroomOpenJobs from "@/src/functions/backend/db/chatrooms/grab-chatroom-open-jobs";
import shareRoomFiles from "@/src/functions/backend/db/chatrooms/share-room-files";
import chatroomOpenJobsWarning from "@/src/utils/chatroom-open-jobs-warning";
import type { HarnessTool } from "../../types";
type Params = {
@@ -18,22 +20,38 @@ type Params = {
type Args = {
answer: string;
/**
* Closes over a job still running in the room, cancelling it.
*/
close_anyway?: boolean;
};
/**
* The coordinator sends the answer back to the bot that asked, closing the
* room as answered (`closeChatroom`). Files it names that the asker can't
* read are copied to it first and their refs pointed at the copies
* (`shareRoomFiles`).
* (`shareRoomFiles`). While a member's job still runs it refuses, unless
* `close_anyway` says the answer doesn't depend on it: closing cancels that
* job and the work with it.
*/
export default function answerRequesterTool({ chatroom, job_id, onClosed }: Params): HarnessTool<Args> {
return {
name: "answer_requester",
description: `Send the answer back to the bot that asked, and close the room. Write the answer itself, complete and in markdown.`,
description: `Send the answer back to the bot that asked, and close the room. Write the answer itself, complete and in markdown. Closing cancels whatever still runs in the room, so while a bot is working this refuses: read where it stands first, or pass close_anyway when the answer doesn't depend on its work.`,
schema: z.object({
answer: z.string().trim().min(1).max(12000),
close_anyway: z
.boolean()
.optional()
.describe("Close over a run still working here, cancelling it: only when the answer doesn't depend on it"),
}),
run: async ({ args }) => {
const open = await grabChatroomOpenJobs({ chatroom_id: chatroom.id!, except_job_id: job_id });
if (open.length && !args.close_anyway) {
throw new Error(chatroomOpenJobsWarning({ jobs: open, closing: "Answering" }));
}
const outcome = await shareRoomFiles({ chatroom, answer: args.answer });
const closed = await closeChatroom({ chatroom_id: chatroom.id!, status: "answered", outcome, job_id });
@@ -1,6 +1,8 @@
import { z } from "zod";
import type { BUN_SQLITE_COBBLE_CHATROOMS } from "@/db/types/db";
import closeChatroom from "@/src/functions/backend/db/chatrooms/close-chatroom";
import grabChatroomOpenJobs from "@/src/functions/backend/db/chatrooms/grab-chatroom-open-jobs";
import chatroomOpenJobsWarning from "@/src/utils/chatroom-open-jobs-warning";
import type { HarnessTool } from "../../types";
type Params = {
@@ -17,20 +19,35 @@ type Params = {
type Args = {
reason: string;
/**
* Closes over a job still running in the room, cancelling it.
*/
close_anyway?: boolean;
};
/**
* The coordinator turns the request down, telling the bot that asked why,
* and closes the room as refused (`closeChatroom`).
* and closes the room as refused (`closeChatroom`). While a member's job
* still runs it refuses, unless `close_anyway` (closing cancels it).
*/
export default function refuseRequestTool({ chatroom, job_id, onClosed }: Params): HarnessTool<Args> {
return {
name: "refuse_request",
description: `Turn the request down and close the room, when no one here can answer it or it shouldn't be done. Say why, so the bot that asked can go on without it.`,
description: `Turn the request down and close the room, when no one here can answer it or it shouldn't be done. Say why, so the bot that asked can go on without it. Closing cancels whatever still runs in the room, so while a bot is working this refuses: pass close_anyway when the refusal doesn't depend on its work.`,
schema: z.object({
reason: z.string().trim().min(1).max(4000),
close_anyway: z
.boolean()
.optional()
.describe("Close over a run still working here, cancelling it: only when the refusal doesn't depend on it"),
}),
run: async ({ args }) => {
const open = await grabChatroomOpenJobs({ chatroom_id: chatroom.id!, except_job_id: job_id });
if (open.length && !args.close_anyway) {
throw new Error(chatroomOpenJobsWarning({ jobs: open, closing: "Turning it down" }));
}
const closed = await closeChatroom({ chatroom_id: chatroom.id!, status: "refused", outcome: args.reason, job_id });
if (!closed) {
+1 -1
View File
@@ -29,7 +29,7 @@ export default async function relayChangedChatrooms({ since, users }: Params) {
const mine = rooms.filter((room) => room.user_id && users.has(String(room.user_id)));
for (const summary of await chatroomSummaries({ chatrooms: mine })) {
for (const summary of await chatroomSummaries({ chatrooms: mine, with_usage: true })) {
sendToUser({ user_id: summary.user_id!, data: { event: "server:chatroom-updated", data: summary } });
}
}
@@ -0,0 +1,60 @@
import { describe, expect, test } from "bun:test";
import { MarkdownManager } from "@tiptap/markdown";
import StarterKit from "@tiptap/starter-kit";
import { Marked, marked } from "marked";
import ComposerOrderedList from "./composer-ordered-list";
/**
* The composer reads a draft or a recalled message back through the same
* markdown manager its editor builds, extensions and all. Its own marked
* instance, since Tiptap hands every manager the module-level one and a
* manager built elsewhere (another test) would leave its tokenizers there.
*/
const manager = new MarkdownManager({
marked: new Marked() as unknown as typeof marked,
extensions: [StarterKit.configure({ orderedList: false }), ComposerOrderedList] as never,
});
const parse = ({ markdown }: { markdown: string }) => manager.parse(markdown) as {
type: string;
attrs?: { start?: number };
content?: {
type: string;
attrs?: { start?: number };
text?: string;
content?: { type: string; text?: string }[];
}[];
};
const text = ({ markdown }: { markdown: string }) => parse({ markdown }).content?.[0]?.content?.[0]?.text;
describe("composer ordered lists read digits only", () => {
test("a sentence opening with a short word stays a paragraph", () => {
const doc = parse({ markdown: "Ok. Do another pass on the browser." });
expect(doc.content?.map((node) => node.type)).toEqual(["paragraph"]);
expect(text({ markdown: "Ok. Do another pass on the browser." })).toBe(
"Ok. Do another pass on the browser.",
);
});
test("a two-letter word with a full stop stays a paragraph", () => {
expect(parse({ markdown: "ab. xyz" }).content?.[0]?.type).toBe("paragraph");
});
test("a roman numeral marker stays a paragraph", () => {
expect(parse({ markdown: "ii. second point" }).content?.[0]?.type).toBe("paragraph");
});
test("a digit marker is still an ordered list", () => {
expect(parse({ markdown: "1. first\n2. second" }).content?.[0]?.type).toBe("orderedList");
});
test("a list keeps its start number", () => {
expect(parse({ markdown: "10. tenth" }).content?.[0]?.attrs?.start).toBe(10);
});
test("a bullet list is untouched", () => {
expect(parse({ markdown: "- one\n- two" }).content?.[0]?.type).toBe("bulletList");
});
});
@@ -0,0 +1,26 @@
import type { MarkdownTokenizer } from "@tiptap/core";
import OrderedList from "@tiptap/extension-ordered-list";
/**
* The one way markdown starts an ordered list here: digits, as every
* renderer in the app reads it (react-markdown/remark). Tiptap's own
* tokenizer also takes `a.` and `i.`, so a recalled message such as
* "Ok. Do another pass on the browser." came back as a list item
* numbered 401 with "Ok." swallowed as the marker.
*/
const DigitMarker = /^ {0,3}\d{1,9}[.)][\t ]/;
const TiptapTokenizer = OrderedList.config.markdownTokenizer as MarkdownTokenizer;
const ComposerOrderedList = OrderedList.extend({
markdownTokenizer: {
...TiptapTokenizer,
tokenize: (src, tokens, lexer) => {
if (!DigitMarker.test(src)) return undefined;
return TiptapTokenizer.tokenize(src, tokens, lexer);
},
},
});
export default ComposerOrderedList;
@@ -9,9 +9,15 @@ import type { BotMessageWithAttachments } from "@/src/types";
export type BotMessageActions = {
onReply: (params: { message: BotMessageWithAttachments }) => void;
onReact: (params: { message_id: number; emoji: BotMessageReactionEmoji }) => void;
/**
* A suggested next step the user clicked (`[suggestion:ID]`): put it
* in their input, never send it.
*/
onUseSuggestion: (params: { text: string }) => void;
};
export const BotMessageActionsContext = React.createContext<BotMessageActions>({
onReply: () => {},
onReact: () => {},
onUseSuggestion: () => {},
});
@@ -10,19 +10,24 @@ type Params = {
* modal lists.
*/
full?: boolean;
/**
* The room the message was posted in: a chatroom's message is read
* from its own route, an answer in a bot's conversation from the
* bot's.
*/
chatroom_id?: number;
};
/**
* How one of the bot's messages was generated. `full` reads every call
* and failure it took, which the modal's copy of the report needs.
* How one bot message was generated. `full` reads every call and failure
* it took, which the modal's copy of the report needs.
*/
export default async function fetchMessageDetails({ message_id, full }: Params) {
export default async function fetchMessageDetails({ message_id, full, chatroom_id }: Params) {
const query = new URLSearchParams({ message_id: String(message_id) });
if (full) query.set("full", "1");
return await fetchApi<{}, APIResponseObject<MessageDetails>>(
`/api/admin/bots/message-details?${query.toString()}`,
{ method: "GET" },
);
}
const url = chatroom_id ? `/api/admin/chatrooms/message-details` : `/api/admin/bots/message-details`;
return await fetchApi<{}, APIResponseObject<MessageDetails>>(`${url}?${query.toString()}`, { method: "GET" });
}
@@ -0,0 +1,56 @@
import fetchApi from "@moduletrace/twui/utils/fetch/fetchApi";
import type { APIResponseObject } from "@moduletrace/bunext/types";
import { useEffect, useState } from "react";
import type { BotSuggestionView } from "@/src/types";
type Params = {
suggestion_id: number;
};
/**
* Next steps already read, by id, so a thread naming them twice asks once.
*/
const loaded = new Map<number, Promise<BotSuggestionView | null>>();
function loadSuggestion({ suggestion_id }: Params) {
const cached = loaded.get(suggestion_id);
if (cached) return cached;
const pending = fetchApi<{}, APIResponseObject<BotSuggestionView>>(
`/api/admin/bot-suggestions/get-suggestion?suggestion_id=${suggestion_id}`,
{ method: "GET" },
)
.then((res) => (res?.success && res.singleRes ? res.singleRes : null))
.catch(() => null);
loaded.set(suggestion_id, pending);
return pending;
}
/**
* Next steps a bot suggested (`[suggestion:ID]`): read when their buttons
* render. Only the user they were suggested to can read them; anyone else
* gets null.
*/
export default function useBotSuggestion({ suggestion_id }: Params) {
const [view, setView] = useState<BotSuggestionView | null>(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
let live = true;
loadSuggestion({ suggestion_id }).then((result) => {
if (!live) return;
setView(result);
setLoading(false);
});
return () => {
live = false;
};
}, [suggestion_id]);
return { view, loading };
}
@@ -6,6 +6,7 @@ import Placeholder from "@tiptap/extension-placeholder";
import { Markdown } from "@tiptap/markdown";
import type { SuggestionOptions, SuggestionProps } from "@tiptap/suggestion";
import type { BotWithLastMessage, WorkspaceWithActivity } from "@/src/types";
import ComposerOrderedList from "../(data)/composer-ordered-list";
import {
ComposerMentionKinds,
type ComposerMentionChar,
@@ -39,6 +40,11 @@ type Params = {
* Files pasted or dropped in.
*/
onFiles: (params: { files: File[] }) => void;
/**
* An arrow key that may walk the user's previous messages; true when it
* did, so the cursor stays where the recalled message left it.
*/
onHistory: (params: { direction: "up" | "down"; empty: boolean }) => boolean;
};
/**
@@ -49,7 +55,9 @@ type Params = {
* in a code block or list, where Enter is the editor's and Mod+Enter
* sends. Enter picks from an open mention menu. Pasted text comes in
* plain, without another site's styling; pasted or dropped files go to
* `onFiles`.
* `onFiles`. The Up and Down arrows walk the user's previous messages
* through `onHistory` (an empty input recalls the newest; an open mention
* menu keeps them for itself).
*/
export default function useComposerEditor({
placeholder,
@@ -58,9 +66,10 @@ export default function useComposerEditor({
onChange,
onSubmit,
onFiles,
onHistory,
}: Params) {
const latest = useRef({ bots, workspaces, onChange, onSubmit, onFiles });
latest.current = { bots, workspaces, onChange, onSubmit, onFiles };
const latest = useRef({ bots, workspaces, onChange, onSubmit, onFiles, onHistory });
latest.current = { bots, workspaces, onChange, onSubmit, onFiles, onHistory };
const [menu, setMenu] = useState<ComposerMentionMenu | null>(null);
const menu_ref = useRef<ComposerMentionMenu | null>(null);
@@ -134,7 +143,10 @@ export default function useComposerEditor({
horizontalRule: false,
underline: false,
link: { openOnClick: false, autolink: true },
orderedList: false,
}),
/** Digits only, so text like "Ok. Do that." stays a paragraph. */
ComposerOrderedList,
Placeholder.configure({ placeholder }),
Markdown,
Mention.extend({
@@ -155,7 +167,17 @@ export default function useComposerEditor({
const editorOwnsEnter = () =>
this.editor.isActive("codeBlock") || this.editor.isActive("listItem");
/** A selection, a composing IME or an open menu keep the arrows. */
const walkHistory = (direction: "up" | "down") => {
if (menu_ref.current?.items.length || this.editor.view.composing) return false;
if (!this.editor.state.selection.empty) return false;
return latest.current.onHistory({ direction, empty: this.editor.isEmpty });
};
return {
ArrowUp: () => walkHistory("up"),
ArrowDown: () => walkHistory("down"),
Enter: () => {
if (menu_ref.current?.items.length || this.editor.view.composing) return false;
if (editorOwnsEnter()) return false;
@@ -0,0 +1,70 @@
import { useRef } from "react";
import stepComposerHistory, {
EmptyComposerHistory,
type ComposerHistoryState,
} from "../(utils)/composer-history-step";
/**
* The user's previous messages, walked with the Up and Down arrows: what
* they were typing is kept and comes back when Down passes the newest
* message again.
*/
export type ComposerHistory = {
/** A recalled message is in the input (so the arrows keep walking). */
isActive: () => boolean;
/**
* One arrow press: the text the input takes, or null when the key
* belongs to the editor (a cursor to move, nothing to recall).
*/
step: (params: {
direction: "up" | "down";
/** What's in the input now, put back on the way down. */
draft: string;
/** Whether the input has nothing in it. */
empty: boolean;
}) => { text: string } | null;
/** Typing (or sending) takes the input back from the recalled messages. */
reset: () => void;
};
export default function useComposerHistory({
texts,
}: {
/** What the user typed before, oldest first. */
texts: string[];
}): ComposerHistory {
const state = useRef<ComposerHistoryState>(EmptyComposerHistory);
const texts_ref = useRef(texts);
texts_ref.current = texts;
const reset = () => {
state.current = EmptyComposerHistory;
};
const step = ({
direction,
draft,
empty,
}: {
direction: "up" | "down";
draft: string;
empty: boolean;
}) => {
const next = stepComposerHistory({
state: state.current,
texts: texts_ref.current,
direction,
draft,
empty,
});
if (!next) return null;
state.current = next.state;
return { text: next.text };
};
return { isActive: () => state.current.index > 0, step, reset };
}
@@ -8,13 +8,19 @@ type Params = {
* Load only once the modal opens, so the thread's messages stay small.
*/
enabled?: boolean;
/**
* Set when the message was posted in a chatroom, so its details are read
* from the room's route.
*/
chatroom_id?: number;
};
/**
* How one bot message was generated (`api/admin/bots/message-details`),
* loaded when its details modal opens and kept while the thread is open.
* How one bot message was generated (`api/admin/bots/message-details`, or
* the chatroom's own route for a message posted in a room), loaded when its
* details modal opens and kept while the thread is open.
*/
export default function useMessageDetails({ message_id, enabled = true }: Params) {
export default function useMessageDetails({ message_id, enabled = true, chatroom_id }: Params) {
const [details, setDetails] = useState<MessageDetails>();
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string>();
@@ -23,7 +29,7 @@ export default function useMessageDetails({ message_id, enabled = true }: Params
setLoading(true);
setError(undefined);
const res = await fetchMessageDetails({ message_id }).catch(() => null);
const res = await fetchMessageDetails({ message_id, chatroom_id }).catch(() => null);
setLoading(false);
@@ -33,7 +39,7 @@ export default function useMessageDetails({ message_id, enabled = true }: Params
}
setDetails(res.singleRes);
}, [message_id]);
}, [message_id, chatroom_id]);
useEffect(() => {
if (enabled) load().catch(() => {});
@@ -0,0 +1,32 @@
import { useContext } from "react";
import Button from "@moduletrace/twui/layout/Button";
import Span from "@moduletrace/twui/layout/Span";
import { ArrowUpRight } from "lucide-react";
import { BotMessageActionsContext } from "../(data)/message-actions-context";
type Props = {
step: string;
};
/**
* One suggested next step, a button that puts it in the user's input (it
* never sends on its own).
*/
export default function BotSuggestionChip({ step }: Props) {
const { onUseSuggestion } = useContext(BotMessageActionsContext);
return (
<Button
type="button"
variant="outlined"
color="gray"
size="smaller"
title={`Put this in your input: ${step}`}
className="inline-flex h-auto max-w-full gap-1! flex-nowrap align-middle px-2! py-1! text-left text-[13px] font-normal whitespace-normal [&_.twui-button-content-wrapper]:min-w-0"
onClick={() => onUseSuggestion({ text: step })}
>
<Span className="min-w-0">{step}</Span>
<ArrowUpRight size={14} aria-hidden className="shrink-0" />
</Button>
);
}
@@ -0,0 +1,36 @@
import Span from "@moduletrace/twui/layout/Span";
import useBotSuggestion from "../(hooks)/use-bot-suggestion";
import BotSuggestionChip from "./bot-suggestion-chip";
type Props = {
suggestion_id: number;
};
/**
* Next steps a bot suggested (`botSuggestionRef`): its heading and a
* button per step, inline under the answer. Clicking one puts it in the
* user's input; nothing has to be answered. Anyone they weren't suggested
* to sees their number only.
*/
export default function BotSuggestionsRef({ suggestion_id }: Props) {
const { view, loading } = useBotSuggestion({ suggestion_id });
if (!view) {
return (
<Span className="font-bold">
{loading ? `next steps ${suggestion_id}` : `next steps ${suggestion_id} (not available)`}
</Span>
);
}
if (!view.steps.length) return null;
return (
<Span className="inline-flex max-w-full flex-wrap items-center gap-1.5 align-middle">
<Span className="text-[13px] font-bold text-ink-secondary">{view.title || "Next steps"}</Span>
{view.steps.map((step) => (
<BotSuggestionChip key={step} step={step} />
))}
</Span>
);
}
@@ -0,0 +1,28 @@
import Button from "@moduletrace/twui/layout/Button";
import { X } from "lucide-react";
type Props = {
disabled?: boolean;
onClick: () => void;
};
/**
* Empties the input's text (the quote, the picked files and the draft it
* saves stay where they are).
*/
export default function ComposerClearButton({ disabled, onClick }: Props) {
return (
<Button
title={disabled ? "Nothing to clear" : "Clear the text"}
aria-label="Clear the text"
type="button"
variant="ghost"
color="text"
disabled={disabled}
onClick={onClick}
className="shrink-0 p-1! -mx-1 my-1 text-ink dark:text-ink rounded-default-xs focus-visible:ring-2 focus-visible:ring-ink"
>
<X size={16} aria-hidden />
</Button>
);
}
@@ -23,12 +23,15 @@ import transcribeVoice from "../(functions)/transcribe-voice";
import useComposerAttachments from "../(hooks)/use-composer-attachments";
import useComposerDraft from "../(hooks)/use-composer-draft";
import useComposerEditor from "../(hooks)/use-composer-editor";
import useComposerHistory from "../(hooks)/use-composer-history";
import useVoiceRecorder from "../(hooks)/use-voice-recorder";
import useOnlineStatus from "@/src/hooks/use-online-status";
import { AppData } from "@/src/data/app-data";
import messageTooLongMessage from "@/src/utils/message-too-long-message";
import composerHistoryTexts from "../(utils)/composer-history-texts";
import ComposerAttachButton from "./composer-attach-button";
import ComposerAttachments from "./composer-attachments";
import ComposerClearButton from "./composer-clear-button";
import ComposerEditor from "./composer-editor";
import ComposerMentionList from "./composer-mention-list";
import ComposerReplyPreview from "./composer-reply-preview";
@@ -44,6 +47,11 @@ export type ComposerHandle = {
* Quotes text from the thread at the cursor.
*/
insertQuote: (params: { text: string }) => void;
/**
* Puts text at the cursor (a suggested next step), leaving the draft
* to the user to edit and send.
*/
insertText: (params: { text: string }) => void;
};
type Props = {
@@ -69,6 +77,11 @@ type Props = {
* before anything is sent, and again by the server.
*/
max_chars?: number | null;
/**
* The user's own earlier messages in the thread, oldest first: the Up
* and Down arrows walk them.
*/
previous_messages?: BotMessageWithAttachments[];
/**
* The message the next one quotes, if the user picked one.
*/
@@ -100,7 +113,9 @@ type Props = {
* are listed under the input. The mic dictates: what's said is written
* into the input at the cursor, to edit before sending. Sending shows the
* message in the thread straight away and empties the input, so a slow
* connection never holds either; a failed send puts both back.
* connection never holds either; a failed send puts both back. Up recalls
* the message the user sent before (Down comes forward again, back to what
* they were typing), and the X button empties the text without sending it.
*/
export default function Composer({
bot,
@@ -109,6 +124,7 @@ export default function Composer({
voice,
has_browsers,
max_chars,
previous_messages,
reply_to,
onCancelReply,
onSendStart,
@@ -135,20 +151,54 @@ export default function Composer({
latest_text.current = text;
const history = useComposerHistory({
texts: composerHistoryTexts({ messages: previous_messages || [] }),
});
/**
* Assigned once the editor exists, since recalling a message writes
* into it; the editor's keys read it through a ref.
*/
const walk_history = useRef<
(params: { direction: "up" | "down"; empty: boolean }) => boolean
>(() => false);
const input = useComposerEditor({
placeholder: `Message ${bot.name}`,
bots,
workspaces,
onChange: ({ markdown }) => setText(markdown),
onChange: ({ markdown }) => {
history.reset();
setText(markdown);
},
onSubmit: () => send_ref.current(),
onFiles: files.add,
onHistory: (params) => walk_history.current(params),
});
const editor = input.editor;
walk_history.current = ({ direction, empty }) => {
const next = history.step({
direction,
draft: latest_text.current,
empty,
});
if (!next) return false;
setText(next.text);
input.setMarkdown({ markdown: next.text });
editor?.commands.focus("end");
return true;
};
useImperativeHandle(
handle_ref,
() => ({ insertQuote: input.insertQuote }),
[input.insertQuote],
() => ({
insertQuote: input.insertQuote,
insertText: input.insertText,
}),
[input.insertQuote, input.insertText],
);
/**
@@ -221,6 +271,17 @@ export default function Composer({
files.restore({ attachments });
};
/**
* Empties the input's text, without sending it: what was typed is
* dropped, the quote and the picked files stay.
*/
function clearText() {
setText("");
history.reset();
input.clear();
editor?.commands.focus();
}
/**
* The bubble and the bot's "getting your message" row show at once, and
* the input empties, so a slow connection never holds any of it. The
@@ -285,6 +346,7 @@ export default function Composer({
onCancelReply?.();
setText("");
history.reset();
input.clear();
files.clear();
@@ -363,6 +425,11 @@ export default function Composer({
title={error}
/>
<ComposerClearButton
disabled={!text.trim()}
onClick={clearText}
/>
{recorder.supported ? (
<ComposerVoiceButton
state={recorder.state}
@@ -8,6 +8,11 @@ import fetchMessageDetails from "../(functions)/fetch-message-details";
type Props = {
message_id: number;
/**
* Set when the message was posted in a chatroom, so its details are read
* from the room's route.
*/
chatroom_id?: number;
};
/**
@@ -16,7 +21,7 @@ type Props = {
* every call and failure it took included, not only the ones the modal
* lists. The row shows a check for a moment, then goes back.
*/
export default function CopyMessageDetailsButton({ message_id }: Props) {
export default function CopyMessageDetailsButton({ message_id, chatroom_id }: Props) {
const [loading, setLoading] = useState(false);
const [copied, setCopied] = useState(false);
const timeout = useRef<ReturnType<typeof setTimeout> | null>(null);
@@ -30,7 +35,7 @@ export default function CopyMessageDetailsButton({ message_id }: Props) {
const copy = async () => {
setLoading(true);
const markdown = fetchMessageDetails({ message_id, full: true }).then((res) => {
const markdown = fetchMessageDetails({ message_id, full: true, chatroom_id }).then((res) => {
if (!res?.success || !res.singleRes) {
throw new Error(res?.msg || "Couldn't load this message's details.");
}
@@ -3,7 +3,7 @@ import Stack from "@moduletrace/twui/layout/Stack";
import type { MessageDetails } from "@/src/types";
import formatTokens from "@/src/utils/format-tokens";
import relativeTime from "@/src/utils/relative-time";
import costLabel from "../(utils)/cost-label";
import costLabel from "@/src/utils/cost-label";
import messageDetailsFacts from "../(utils)/message-details-facts";
import MessageDetailRow from "./message-detail-row";
import MessageDetailsCallRow from "./message-details-call-row";
@@ -4,7 +4,7 @@ import type { MessageDetailsCall } from "@/src/types";
import describeCallSettings from "@/src/utils/describe-call-settings";
import formatDuration from "@/src/utils/format-duration";
import formatTokens from "@/src/utils/format-tokens";
import costLabel from "../(utils)/cost-label";
import costLabel from "@/src/utils/cost-label";
import harnessLabel from "../(utils)/harness-label";
type Props = {
@@ -17,16 +17,22 @@ type Props = {
* passed along to the copied report.
*/
tool_log?: string | null;
/**
* Set when the message was posted in a chatroom, so its details are read
* from the room's route.
*/
chatroom_id?: number;
};
/**
* The info button under a bot message, and the modal it opens: which
* provider and model generated it, the run behind it, what its tools did,
* and every model call with its tokens and cost. Loaded when it opens.
* The info button under a bot message (in a conversation or a chatroom),
* and the modal it opens: which provider and model generated it, the run
* behind it, what its tools did, and every model call with its tokens and
* cost. Loaded when it opens.
*/
export default function MessageDetailsModal({ message_id, tool_log }: Props) {
export default function MessageDetailsModal({ message_id, tool_log, chatroom_id }: Props) {
const [open, set_open] = useState(false);
const { details, loading, error } = useMessageDetails({ message_id, enabled: open });
const { details, loading, error } = useMessageDetails({ message_id, enabled: open, chatroom_id });
return (
<Modal
@@ -43,7 +49,7 @@ export default function MessageDetailsModal({ message_id, tool_log }: Props) {
<Stack className="w-full gap-1! items-stretch">
<Row className="w-full gap-2! flex-nowrap items-center">
<H2 className="grow text-lg! leading-6! tracking-normal! font-bold text-ink">Message details</H2>
<CopyMessageDetailsButton message_id={message_id} />
<CopyMessageDetailsButton message_id={message_id} chatroom_id={chatroom_id} />
</Row>
<Span className="text-[13px] leading-[18px] text-ink-secondary">
How this answer was generated: the provider and model behind it, the settings they were called with, and what it spent.
@@ -4,7 +4,7 @@ import Stack from "@moduletrace/twui/layout/Stack";
import type { MessageDetailsModel } from "@/src/types";
import describeCallSettings from "@/src/utils/describe-call-settings";
import formatTokens from "@/src/utils/format-tokens";
import costLabel from "../(utils)/cost-label";
import costLabel from "@/src/utils/cost-label";
import harnessLabel from "../(utils)/harness-label";
import providerLabel from "../(utils)/provider-label";
import MessageDetailsSetting from "./message-details-setting";
@@ -63,7 +63,8 @@ import requestLiveCrewRefresh from "@/src/functions/frontend/request-live-crew-r
* when the back button restores the page. Older messages load as the
* thread scrolls up. `?session_id=` opens another session of the
* conversation; a closed one shows, in the composer's place, a link to
* where the conversation went on.
* where the conversation went on. Up recalls the last message the user
* sent, in the composer.
*/
export default function Conversation() {
const { pageProps } = useContext(AppContext);
@@ -381,6 +382,8 @@ export default function Conversation() {
onReply: ({ message }: { message: BotMessageWithAttachments }) =>
setReplyTo(message),
onReact: reactToMessage,
onUseSuggestion: ({ text }: { text: string }) =>
composer.current?.insertText({ text }),
}),
[],
);
@@ -467,6 +470,7 @@ export default function Conversation() {
voice={pageProps?.bot_voice}
has_browsers={Boolean(pageProps?.has_browsers)}
max_chars={pageProps?.message_max_chars}
previous_messages={thread_messages}
reply_to={reply_to}
onCancelReply={() => setReplyTo(null)}
onSendStart={({ message }) =>
@@ -0,0 +1,144 @@
import { describe, expect, test } from "bun:test";
import stepComposerHistory, {
EmptyComposerHistory,
type ComposerHistoryState,
} from "./composer-history-step";
/** Presses arrows in turn, collecting what the input took each time. */
function walk({
texts,
presses,
draft = "",
empty = true,
state = EmptyComposerHistory,
}: {
texts: string[];
presses: ("up" | "down")[];
draft?: string;
empty?: boolean;
state?: ComposerHistoryState;
}) {
const shown: (string | null)[] = [];
let current = state;
let in_input = draft;
for (const direction of presses) {
const next = stepComposerHistory({
state: current,
texts,
direction,
draft: in_input,
empty,
});
shown.push(next ? next.text : null);
if (next) {
current = next.state;
in_input = next.text;
}
/** Once a message is in, the input isn't empty any more. */
empty = false;
}
return { shown, state: current, in_input };
}
const texts = ["first", "second", "third"];
describe("stepComposerHistory", () => {
test("Up on an empty input recalls the newest message", () => {
const { shown } = walk({ texts, presses: ["up"] });
expect(shown).toEqual(["third"]);
});
test("Up again walks back through older messages", () => {
const { shown } = walk({ texts, presses: ["up", "up", "up"] });
expect(shown).toEqual(["third", "second", "first"]);
});
test("Up on the oldest message is the editor's; the input stays as it is", () => {
const { shown, in_input } = walk({ texts, presses: ["up", "up", "up", "up"] });
expect(shown).toEqual(["third", "second", "first", null]);
expect(in_input).toEqual("first");
});
test("Down comes forward again and then back to what was being typed", () => {
const { shown, in_input } = walk({
texts,
presses: ["up", "up", "down", "down"],
draft: "half a thought",
});
expect(shown).toEqual(["third", "second", "third", "half a thought"]);
expect(in_input).toEqual("half a thought");
});
test("the draft survives walking all the way back and forth", () => {
const { in_input, state } = walk({
texts,
presses: ["up", "up", "up", "down", "down", "down"],
draft: "an edit",
});
expect(in_input).toEqual("an edit");
expect(state).toEqual(EmptyComposerHistory);
});
test("Down on the draft is the editor's", () => {
const { shown } = walk({ texts, presses: ["down"] });
expect(shown).toEqual([null]);
});
test("Up with text being edited moves the cursor, never replaces the text", () => {
const { shown } = walk({
texts,
presses: ["up"],
draft: "still typing",
empty: false,
});
expect(shown).toEqual([null]);
});
test("Up recalls nothing in a conversation with no earlier message", () => {
const { shown } = walk({ texts: [], presses: ["up"] });
expect(shown).toEqual([null]);
});
test("recalling the only message and pressing Up again stops there", () => {
const { shown } = walk({ texts: ["only"], presses: ["up", "up"] });
expect(shown).toEqual(["only", null]);
});
test("a session that holds fewer messages never reads past the oldest", () => {
const { shown, in_input } = walk({
texts: ["newest"],
presses: ["up", "down"],
state: { index: 3, draft: "my draft" },
});
expect(shown).toEqual([null, "my draft"]);
expect(in_input).toEqual("my draft");
});
test("the state it hands back is what the next press starts from", () => {
const first = stepComposerHistory({
state: EmptyComposerHistory,
texts,
direction: "up",
draft: "draft",
empty: true,
});
expect(first?.state).toEqual({ index: 1, draft: "draft" });
expect(first?.text).toEqual("third");
});
});
@@ -0,0 +1,75 @@
/**
* Where the Up and Down arrows stand in the user's previous messages: 0 is
* what they were typing, 1 the newest message recalled, 2 the one before it.
*/
export type ComposerHistoryState = {
index: number;
/**
* What was in the input when the newest message was recalled, put back
* when the arrows come down past it again.
*/
draft: string;
};
/**
* The input as the user left it: what they type is theirs, not a message
* from before.
*/
export const EmptyComposerHistory: ComposerHistoryState = { index: 0, draft: "" };
/**
* One press of an arrow through the user's previous messages, oldest last:
* Up recalls the newest from an empty input and older ones from there, Down
* walks back to the draft. Null when the key is the editor's own (nothing
* to recall, no older message, or text in the input the user is editing).
*/
export default function stepComposerHistory({
state,
texts,
direction,
draft,
empty,
}: {
state: ComposerHistoryState;
/** What the user typed before, oldest first. */
texts: string[];
direction: "up" | "down";
/** What's in the input now. */
draft: string;
/** Whether the input has nothing in it. */
empty: boolean;
}): { state: ComposerHistoryState; text: string } | null {
const count = texts.length;
if (!state.index) {
/**
* Text being edited keeps Up for moving the cursor: only an empty
* input starts walking back through the messages.
*/
if (direction == "down" || !empty || !count) return null;
return { state: { index: 1, draft }, text: texts[count - 1]! };
}
/**
* A session the input followed may hold fewer messages than the one the
* arrows started in: the oldest one left is as far back as it goes.
*/
const index = Math.min(state.index, count);
if (direction == "up") {
if (index >= count) return null;
return {
state: { ...state, index: index + 1 },
text: texts[count - (index + 1)]!,
};
}
if (index <= 1) return { state: EmptyComposerHistory, text: state.draft };
return {
state: { ...state, index: index - 1 },
text: texts[count - (index - 1)]!,
};
}
@@ -0,0 +1,49 @@
import { describe, expect, test } from "bun:test";
import composerHistoryTexts from "./composer-history-texts";
const sent = (text: string) => ({ author: "user" as const, text });
const answered = (text: string) => ({ author: "bot" as const, text });
describe("composerHistoryTexts", () => {
test("keeps what the user typed, oldest first", () => {
const texts = composerHistoryTexts({
messages: [
sent("plan the migration"),
answered("Here's the plan"),
sent("ship it tonight"),
],
});
expect(texts).toEqual(["plan the migration", "ship it tonight"]);
});
test("leaves out the bot's answers and blank messages", () => {
const texts = composerHistoryTexts({
messages: [answered("Morning"), sent(" "), sent(""), sent("real text")],
});
expect(texts).toEqual(["real text"]);
});
test("leaves out what a chatroom or an install request wrote on the user's side", () => {
const texts = composerHistoryTexts({
messages: [
sent("ask the crew"),
{ author: "user" as const, text: "Room closed: the answer", from_chatroom_id: 12 },
{ author: "user" as const, text: "Installed numpy", from_install_request_id: 3 },
],
});
expect(texts).toEqual(["ask the crew"]);
});
test("trims a message's text around it", () => {
const texts = composerHistoryTexts({ messages: [sent(" keep this ")] });
expect(texts).toEqual(["keep this"]);
});
test("is empty for a session with nothing sent yet", () => {
expect(composerHistoryTexts({ messages: [answered("Hello")] })).toEqual([]);
});
});
@@ -0,0 +1,34 @@
import type { BotMessageWithAttachments } from "@/src/types";
import isCrewMessage from "@/src/utils/is-crew-message";
/**
* A message the Up arrow can recall: only what the user typed here. A
* chatroom's outcome and an install request's answer are stored on the
* user's side, but the user wrote neither.
*/
export type ComposerHistoryMessage = Pick<
BotMessageWithAttachments,
"author" | "text" | "from_chatroom_id" | "from_install_request_id"
>;
/**
* What the user typed, oldest first, so the newest message Up recalls is
* its last entry.
*/
export default function composerHistoryTexts({
messages,
}: {
messages: ComposerHistoryMessage[];
}) {
const texts: string[] = [];
for (const message of messages) {
if (message.author != "user" || isCrewMessage({ message })) continue;
const text = message.text?.trim();
if (text) texts.push(text);
}
return texts;
}
@@ -1,7 +1,7 @@
import type { MessageDetails, MessageDetailsCall, MessageDetailsFailure, MessageDetailsModel } from "@/src/types";
import describeCallSettings from "@/src/utils/describe-call-settings";
import formatDuration from "@/src/utils/format-duration";
import costLabel from "./cost-label";
import costLabel from "@/src/utils/cost-label";
import failureSourceLabel from "./failure-source-label";
import harnessLabel from "./harness-label";
import messageDetailsFacts from "./message-details-facts";
@@ -1,5 +1,5 @@
import { describe, expect, test } from "bun:test";
import costLabel from "./cost-label";
import costLabel from "@/src/utils/cost-label";
import providerLabel from "./provider-label";
describe("providerLabel", () => {
@@ -13,11 +13,13 @@ import {
} from "@/src/utils/link-computer-refs";
import { parseFolderRefHref } from "@/src/utils/folder-ref";
import { botQuestionRefId } from "@/src/utils/bot-question-ref";
import { botSuggestionRefId } from "@/src/utils/bot-suggestion-ref";
import { graphicRefId } from "@/src/utils/graphic-ref";
import { chatroomRefId } from "@/src/utils/chatroom-ref";
import { taskRefId } from "@/src/utils/task-ref";
import { generalSettingsRefId } from "@/src/utils/general-settings-ref";
import BotQuestionRefChip from "../(partials)/bot-question-ref-chip";
import BotSuggestionsRef from "../(partials)/bot-suggestions-ref";
import BotRefChip from "../(partials)/bot-ref-chip";
import ChatroomRefChip from "../(partials)/chatroom-ref-chip";
import ComputerRefChip from "../(partials)/computer-ref-chip";
@@ -39,7 +41,8 @@ import WorkspaceRefChip from "../(partials)/workspace-ref-chip";
* computer, a bot or workspace a link to it, a file a chip that previews
* it, a folder a chip that opens it in the files browser, a proposal a chip
* that opens the confirm card, a secret a masked chip, a secret request or
* questions a chip that opens their card, a graphic the graphic itself, a
* questions a chip that opens their card, suggested next steps the
* buttons that fill the input, a graphic the graphic itself, a
* chatroom or task a chip that opens it, a setting a pill to that group of
* Settings > General. Null for any other link.
*/
@@ -110,6 +113,9 @@ export default function refChipForHref({ href }: { href?: string }): ReactNode |
const question_id = botQuestionRefId({ href });
if (question_id) return <BotQuestionRefChip question_id={question_id} />;
const suggestion_id = botSuggestionRefId({ href });
if (suggestion_id) return <BotSuggestionsRef suggestion_id={suggestion_id} />;
const chatroom_id = chatroomRefId({ href });
if (chatroom_id) return <ChatroomRefChip chatroom_id={chatroom_id} />;
@@ -1,11 +1,10 @@
import { useState } from "react";
import type { BUN_SQLITE_COBBLE_BOT_MESSAGES } from "@/db/types/db";
import useServerEvent from "@/src/hooks/use-server-event";
import type { ChatroomMessageData, ChatroomSummary } from "@/src/types";
import type { BotMessageWithAttachments, ChatroomMessageData, ChatroomSummary } from "@/src/types";
type Params = {
chatroom: ChatroomSummary;
messages: BUN_SQLITE_COBBLE_BOT_MESSAGES[];
messages: BotMessageWithAttachments[];
};
/**
@@ -3,12 +3,13 @@ import remarkGfm from "remark-gfm";
import Row from "@moduletrace/twui/layout/Row";
import Span from "@moduletrace/twui/layout/Span";
import Stack from "@moduletrace/twui/layout/Stack";
import type { BUN_SQLITE_COBBLE_BOT_MESSAGES } from "@/db/types/db";
import ChatroomStone from "@/src/components/general/chatroom-stone";
import type { ChatroomBot } from "@/src/types";
import type { BotMessageWithAttachments, ChatroomBot } from "@/src/types";
import linkComputerRefs from "@/src/utils/link-computer-refs";
import relativeTime from "@/src/utils/relative-time";
import { MessageMarkdownComponents } from "@/src/pages/admin/bots/[bot_id]/(data)/message-markdown-components";
import MessageDetailsModal from "@/src/pages/admin/bots/[bot_id]/(partials)/message-details-modal";
import MessageUsageChip from "@/src/pages/admin/bots/[bot_id]/(partials)/message-usage-chip";
/**
* Kept module-level: a new array on every render makes `react-markdown`
@@ -17,19 +18,25 @@ import { MessageMarkdownComponents } from "@/src/pages/admin/bots/[bot_id]/(data
const RemarkPlugins = [remarkGfm];
type Props = {
message: BUN_SQLITE_COBBLE_BOT_MESSAGES;
message: BotMessageWithAttachments;
/**
* The bot that posted it, null once it was deleted.
*/
bot?: ChatroomBot | null;
/**
* The room it was posted in, for its details (they're read from the
* room's own route).
*/
chatroom_id: number;
};
/**
* One message in a chatroom, under the stone and name of the bot that
* posted it, rendered from markdown like a conversation's (raw HTML
* never). Rooms are records: nothing here replies or reacts.
* never), with what it spent and its details underneath. Rooms are
* records: nothing here replies or reacts.
*/
export default function ChatroomMessageRow({ message, bot }: Props) {
export default function ChatroomMessageRow({ message, bot, chatroom_id }: Props) {
return (
<Row className="w-full gap-3! flex-nowrap items-start">
<Span className="inline-flex shrink-0 -mt-0.5">
@@ -47,6 +54,14 @@ export default function ChatroomMessageRow({ message, bot }: Props) {
{linkComputerRefs({ text: message.text || "" })}
</Markdown>
</Stack>
<Row className="w-full gap-1! flex-nowrap items-center">
<MessageUsageChip usage={message.usage} />
<MessageDetailsModal
message_id={Number(message.id)}
tool_log={message.tool_log}
chatroom_id={chatroom_id}
/>
</Row>
</Stack>
</Row>
);
@@ -0,0 +1,37 @@
import Row from "@moduletrace/twui/layout/Row";
import Span from "@moduletrace/twui/layout/Span";
import type { ChatroomUsageBot } from "@/src/types";
import costLabel from "@/src/utils/cost-label";
import formatTokens from "@/src/utils/format-tokens";
type Props = {
bot: ChatroomUsageBot;
};
/**
* One bot's part of what a room spent, under the room's totals: its name,
* then the tokens, calls and price of every model call it made there. The
* hover title breaks it down.
*/
export default function ChatroomUsageBotRow({ bot }: Props) {
const title = [
`${formatTokens({ tokens: bot.prompt_tokens })} in, ${formatTokens({ tokens: bot.completion_tokens })} out`,
`${bot.calls} model ${bot.calls == 1 ? "call" : "calls"}`,
typeof bot.cost == "number" && bot.cost > 0 ? costLabel({ cost: bot.cost }) : "",
]
.filter(Boolean)
.join(" · ");
return (
<Row className="w-full gap-3! flex-nowrap items-baseline justify-between">
<Span className="min-w-0 truncate text-[12px] leading-4 font-bold text-ink">
{bot.name || "A removed bot"}
</Span>
<Span title={title} className="shrink-0 text-[12px] leading-4 text-ink-secondary tabular-nums">
{formatTokens({ tokens: bot.total_tokens })} tokens · {formatTokens({ tokens: bot.calls })}{" "}
{bot.calls == 1 ? "call" : "calls"}
{typeof bot.cost == "number" && bot.cost > 0 ? ` · ${costLabel({ cost: bot.cost })}` : ""}
</Span>
</Row>
);
}
@@ -0,0 +1,85 @@
import { describe, expect, test } from "bun:test";
import { renderToString } from "react-dom/server";
import type { ChatroomUsage } from "@/src/types";
import ChatroomUsageSummary from "./chatroom-usage-summary";
const usage: ChatroomUsage = {
totals: {
prompt_tokens: 12_400,
cached_tokens: 6200,
completion_tokens: 1600,
total_tokens: 14_000,
cost: 0.042,
calls: 7,
},
failed_calls: 2,
by_bot: [
{
bot_id: 10,
name: "Ember",
prompt_tokens: 10_400,
cached_tokens: 6000,
completion_tokens: 1100,
total_tokens: 11_500,
cost: 0.031,
calls: 4,
},
{
bot_id: 20,
name: null,
prompt_tokens: 2000,
completion_tokens: 500,
total_tokens: 2500,
cost: 0.011,
calls: 3,
},
],
};
describe("ChatroomUsageSummary", () => {
test("totals what the room spent, and what failed", () => {
const html = renderToString(<ChatroomUsageSummary usage={usage} />);
expect(html).toContain("What this room spent");
expect(html).toContain("14K");
expect(html).toContain("12K in (50% cached), 1.6K out");
expect(html).toContain("7");
expect(html).toContain("2 failed");
expect(html).toContain("$0.0420");
});
test("splits it by bot, naming a bot that's gone", () => {
const html = renderToString(<ChatroomUsageSummary usage={usage} />);
expect(html).toContain("By bot");
expect(html).toContain("Ember");
expect(html).toContain("12K<!-- --> tokens");
expect(html).toContain("4<!-- --> <!-- -->calls");
expect(html).toContain("A removed bot");
expect(html).toContain("2.5K<!-- --> tokens");
expect(html).toContain("3<!-- --> <!-- -->calls");
});
test("says nothing was spent in a room with no calls yet", () => {
const html = renderToString(
<ChatroomUsageSummary
usage={{
totals: { prompt_tokens: 0, completion_tokens: 0, total_tokens: 0, calls: 0 },
failed_calls: 0,
by_bot: [],
}}
/>,
);
expect(html).toContain("Nothing spent yet");
expect(html).toContain("Not reported");
expect(html).not.toContain("By bot");
expect(html).not.toContain("failed");
});
test("reads a room with no usage at all as nothing yet", () => {
const html = renderToString(<ChatroomUsageSummary />);
expect(html).toContain("Nothing spent yet");
});
});
@@ -0,0 +1,75 @@
import Row from "@moduletrace/twui/layout/Row";
import Span from "@moduletrace/twui/layout/Span";
import Stack from "@moduletrace/twui/layout/Stack";
import UsageStat from "@/src/components/general/usage-stat";
import type { ChatroomUsage } from "@/src/types";
import costLabel from "@/src/utils/cost-label";
import formatTokens from "@/src/utils/format-tokens";
import ChatroomUsageBotRow from "./chatroom-usage-bot-row";
type Props = {
usage?: ChatroomUsage | null;
};
/**
* What everything in a room cost, under the bots in it: the tokens and
* model calls every bot's work there took (a turn still running included),
* the price when the providers reported it, the calls that failed, and the
* same split by bot.
*/
export default function ChatroomUsageSummary({ usage }: Props) {
const totals = usage?.totals;
const failed_calls = usage?.failed_calls || 0;
const by_bot = usage?.by_bot || [];
const calls = totals?.calls || 0;
return (
<Stack className="w-full gap-4! items-stretch py-6 border-0 border-t border-solid border-hairline">
<Stack className="w-full gap-1! items-stretch">
<Span className="text-[11px] uppercase tracking-wide text-ink-secondary">What this room spent</Span>
<Span className="text-[12px] leading-4 text-ink-secondary">
Every model call its bots made here, a turn still running included.
</Span>
</Stack>
<Row className="w-full gap-6! items-start flex-wrap">
<UsageStat
label="Tokens"
value={formatTokens({ tokens: totals?.total_tokens })}
hint={
calls
? `${formatTokens({ tokens: totals?.prompt_tokens })} in${cachedShare({ cached: totals?.cached_tokens, prompt: totals?.prompt_tokens })}, ${formatTokens({ tokens: totals?.completion_tokens })} out`
: "Nothing spent yet"
}
/>
<UsageStat
label="Model calls"
value={formatTokens({ tokens: calls })}
hint={failed_calls ? `${failed_calls} failed` : calls ? "None failed" : undefined}
/>
<UsageStat
label="Cost"
value={costLabel({ cost: totals?.cost })}
hint={totals?.cost ? "As the providers reported it" : "Free models, or no price"}
/>
</Row>
{by_bot.length ? (
<Stack className="w-full gap-1.5! items-stretch pt-1">
<Span className="text-[11px] uppercase tracking-wide text-ink-secondary">By bot</Span>
{by_bot.map((bot) => (
<ChatroomUsageBotRow key={bot.bot_id} bot={bot} />
))}
</Stack>
) : null}
</Stack>
);
}
/**
* How much of what was sent the providers served from their cache, when
* they said: " (40% cached)".
*/
function cachedShare({ cached, prompt }: { cached?: number; prompt?: number }) {
if (!cached || !prompt) return "";
return ` (${Math.round((cached / prompt) * 100)}% cached)`;
}
@@ -6,8 +6,7 @@ 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 type { BotMessageWithAttachments, ChatroomSummary } from "@/src/types";
import chatroomStatusLine from "@/src/utils/chatroom-status-line";
import isReadOnlyUser from "@/src/utils/rbac/is-read-only-user";
import useLiveChatroom from "../(hooks)/use-live-chatroom";
@@ -15,17 +14,19 @@ import ChatroomBotsRow from "../(partials)/chatroom-bots-row";
import ChatroomMessageRow from "../(partials)/chatroom-message-row";
import ChatroomOutcome from "../(partials)/chatroom-outcome";
import ChatroomStopButton from "../(partials)/chatroom-stop-button";
import ChatroomUsageSummary from "../(partials)/chatroom-usage-summary";
import ChatroomStatus from "./chatroom-status";
type Props = {
chatroom: ChatroomSummary;
messages: BUN_SQLITE_COBBLE_BOT_MESSAGES[];
messages: BotMessageWithAttachments[];
};
/**
* The open room, live: who is in it and their part, the thread and the
* outcome, where each bot stands while it's open, with Stop for anyone who
* can do more than read, and Try again once it failed or was stopped.
* The open room, live: who is in it and their part, what everything there
* spent, the thread and the outcome, where each bot stands while it's open,
* with Stop for anyone who can do more than read, and Try again once it
* failed or was stopped.
*/
export default function ChatroomBody({ chatroom, messages }: Props) {
const { pageProps } = useContext(AppContext);
@@ -64,12 +65,14 @@ export default function ChatroomBody({ chatroom, messages }: Props) {
/>
))}
</Row>
<ChatroomUsageSummary usage={room.usage} />
<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}
chatroom_id={Number(room.id)}
/>
))}
<ChatroomOutcome chatroom={room} />
@@ -1,8 +1,8 @@
import Row from "@moduletrace/twui/layout/Row";
import type { UsageOverview } from "@/src/types";
import UsageStat from "@/src/components/general/usage-stat";
import formatTokens from "@/src/utils/format-tokens";
import { UsageHarnessTitles } from "../(data)/usage-harness-titles";
import UsageStat from "./usage-stat";
type Props = {
usage: UsageOverview;
@@ -0,0 +1,32 @@
import userAuth from "@/src/functions/backend/auth/user-auth";
import grabBotSuggestionView from "@/src/functions/backend/db/bot-suggestions/grab-bot-suggestion-view";
import { BotSuggestionIdSchema } from "@/src/schemas/bot-suggestion-schema";
import type { BotSuggestionView } from "@/src/types";
import AppError from "@/src/utils/app-error";
import parseWithSchema from "@/src/utils/parse-with-schema";
import safeErrorMessage from "@/src/utils/safe-error-message";
import type { APIResponseObject, BunextAPIRouteHandler } from "@moduletrace/bunext/types";
/**
* `GET ?suggestion_id=`: next steps a bot suggested to the session user,
* as their buttons show them. Nobody else reads them.
*/
export const handler: BunextAPIRouteHandler<APIResponseObject<BotSuggestionView>> = async ({ req, query }) => {
try {
if (req.method != "GET") {
throw new AppError(`Method not allowed`);
}
const { user } = await userAuth({ req });
if (!user?.logged_in_status || !user.id) {
return { success: false, msg: `Unauthorized`, logoutUser: true };
}
const { suggestion_id } = parseWithSchema({ schema: BotSuggestionIdSchema, data: query });
return { success: true, singleRes: await grabBotSuggestionView({ suggestion_id, user_id: user.id }) };
} catch (error: unknown) {
return { success: false, msg: safeErrorMessage({ error }) };
}
};
@@ -0,0 +1,48 @@
import { AppData } from "@/src/data/app-data";
import userAuth from "@/src/functions/backend/auth/user-auth";
import grabChatroomMessage from "@/src/functions/backend/db/chatrooms/grab-chatroom-message";
import grabMessageDetails from "@/src/functions/backend/db/usage/grab-message-details";
import { MessageDetailsRequestSchema } from "@/src/schemas/bot-schema";
import type { MessageDetails } from "@/src/types";
import parseWithSchema from "@/src/utils/parse-with-schema";
import safeErrorMessage from "@/src/utils/safe-error-message";
import type { APIResponseObject, BunextAPIRouteHandler } from "@moduletrace/bunext/types";
/**
* `GET ?message_id=`: how a message posted in one of the user's chatrooms
* was generated (the job, every model call with its provider and model,
* and the tokens and cost). Loaded when its details modal opens, so the
* room's messages stay small. `&full=1` lists every call and failure, for
* the copy of the report.
*/
export const handler: BunextAPIRouteHandler<APIResponseObject<MessageDetails>> = async ({ req, query }) => {
try {
if (req.method != "GET") {
return { success: false, msg: `Method not allowed` };
}
const { user } = await userAuth({ req });
if (!user?.logged_in_status || !user.id) {
return { success: false, msg: `Unauthorized`, logoutUser: true };
}
const { message_id, full } = parseWithSchema({ schema: MessageDetailsRequestSchema, data: query });
const message = await grabChatroomMessage({ message_id, user_id: Number(user.id) });
if (!message) {
return { success: false, msg: `Not found` };
}
return {
success: true,
singleRes: await grabMessageDetails({
message_id: message.id,
created_at: message.created_at || null,
...(full ? { max_calls: AppData.MessageDetailsCopyMaxCalls } : {}),
}),
};
} catch (error: unknown) {
return { success: false, msg: safeErrorMessage({ error }) };
}
};
+19
View File
@@ -0,0 +1,19 @@
import { z } from "zod";
import { AppData } from "@/src/data/app-data";
/**
* The next steps a bot suggests (`suggest_next_steps`), as it writes them
* and as they're stored: short enough to read as a button, distinct so a
* step is never offered twice.
*/
export const BotSuggestionStepsSchema = z
.array(z.string().trim().min(1).max(AppData.BotSuggestionStepMaxChars, `Keep each step under ${AppData.BotSuggestionStepMaxChars} characters`))
.min(1, "Suggest at least one next step")
.max(AppData.BotSuggestionMaxSteps, `Suggest at most ${AppData.BotSuggestionMaxSteps} next steps`)
.refine((steps) => new Set(steps.map((step) => step.toLowerCase())).size == steps.length, "Steps must differ");
export const BotSuggestionIdSchema = z.object({
suggestion_id: z.coerce.number().int().positive("Pick the suggestions"),
});
export type BotSuggestionIdRequest = z.infer<typeof BotSuggestionIdSchema>;
+48 -3
View File
@@ -438,14 +438,47 @@ export type ChatroomSummary = BUN_SQLITE_COBBLE_CHATROOMS & {
* The workspace the request came from, by name.
*/
workspace_name?: string | null;
/**
* What the room's bots spent while working in it, summed. Only asked
* for the room itself (and its live pushes), never for a list.
*/
usage?: ChatroomUsage;
};
/**
* `server:chatroom-message` data: a message one of the room's bots posted.
* What one bot's work in a chatroom spent: every model call it made there,
* a call of a turn still running included.
*/
export type ChatroomUsageBot = TokenUsageSummary & {
bot_id: number;
/**
* Its name while it exists, like the messages it posted.
*/
name: string | null;
};
/**
* What everything in a chatroom cost: every model call its bots made there
* (a turn still running included), the calls that failed, and the same
* split by bot. This is what the totals at the top of a room show.
*/
export type ChatroomUsage = {
totals: TokenUsageSummary;
/**
* How many model calls failed there; they spent nothing, so they aren't
* in `totals`.
*/
failed_calls: number;
by_bot: ChatroomUsageBot[];
};
/**
* `server:chatroom-message` data: a message one of the room's bots posted,
* with what it cost.
*/
export type ChatroomMessageData = {
chatroom_id: number;
message: BUN_SQLITE_COBBLE_BOT_MESSAGES;
message: BotMessageWithAttachments;
};
/**
@@ -836,6 +869,18 @@ export type BotQuestionView = {
bot_name: string;
};
/**
* Next steps a bot suggested under its answer (`[suggestion:ID]`), shown
* as buttons that put the step in the user's input.
*/
export type BotSuggestionView = {
id: number;
title: string;
steps: string[];
bot_id: number;
bot_name: string;
};
export type SecretRequestView = {
id: number;
key: string;
@@ -2221,7 +2266,7 @@ export type PagePropsType = {
* message in it.
*/
chatroom?: ChatroomSummary | null;
chatroom_messages?: BUN_SQLITE_COBBLE_BOT_MESSAGES[] | null;
chatroom_messages?: BotMessageWithAttachments[] | null;
/**
* The user's chatrooms (`/admin/chatrooms`).
*/
+28
View File
@@ -0,0 +1,28 @@
type Params = {
id: number | string;
};
/**
* How a bot names next steps it suggested: `[suggestion:4]`. The chat
* turns it into a link (`linkComputerRefs`) that renders as a row of
* buttons putting each step in the user's input.
*/
export default function botSuggestionRef({ id }: Params) {
return `[suggestion:${id}]`;
}
/**
* The link target a suggestion ref becomes, e.g. `#suggestion-4`.
*/
export const BotSuggestionRefHrefPrefix = "#suggestion-";
/**
* The id in a suggestion ref's link target, or null.
*/
export function botSuggestionRefId({ href }: { href?: string | null }) {
if (!href?.startsWith(BotSuggestionRefHrefPrefix)) return null;
const id = Number(href.slice(BotSuggestionRefHrefPrefix.length));
return Number.isInteger(id) && id > 0 ? id : null;
}
@@ -0,0 +1,46 @@
import { describe, expect, test } from "bun:test";
import chatroomOpenJobsWarning from "@/src/utils/chatroom-open-jobs-warning";
/**
* A room can't be closed over a bot still working in it: closing cancels
* its job (`cancelChatroomJobs`). A coordinator once answered a room while
* the Software Engineer ran the very work it was asked for, the run died
* with "The chatroom closed", and the answer said the tasks were picked up.
* The warning is what the tool throws instead, so it has to name who is
* busy and how to go on.
*/
describe("chatroomOpenJobsWarning", () => {
test("says nothing when nothing runs", () => {
expect(chatroomOpenJobsWarning({ jobs: [], closing: "Answering" })).toBe("");
});
test("names the bot, its run and what it was about to do", () => {
const warning = chatroomOpenJobsWarning({
jobs: [{ id: 295, bot_name: "Software Engineer", status: "processing" }],
closing: "Answering",
});
expect(warning).toContain("Still working here: Software Engineer (run #295, processing).");
expect(warning).toContain("Answering closes the room and cancels that run, so the work is lost.");
expect(warning).toContain("close_anyway: true");
});
test("lists every job still open, in the order given", () => {
const warning = chatroomOpenJobsWarning({
jobs: [
{ id: 12, bot_name: "Writer", status: "pending" },
{ id: 13, bot_name: "Reviewer", status: "processing" },
],
closing: "Turning it down",
});
expect(warning).toContain("Writer (run #12, pending), Reviewer (run #13, processing)");
expect(warning).toContain("Turning it down closes the room");
});
test("copes with a job whose bot is gone", () => {
const warning = chatroomOpenJobsWarning({ jobs: [{ id: 7, bot_name: null }], closing: "Answering" });
expect(warning).toContain("Still working here: A bot (run #7).");
});
});
+33
View File
@@ -0,0 +1,33 @@
type Job = {
id: number | string;
bot_name?: string | null;
status?: string | null;
};
type Params = {
/**
* The room's open jobs (`grabChatroomOpenJobs`).
*/
jobs: Job[];
/**
* What the coordinator was about to do: "Answering", "Turning it down".
*/
closing: string;
};
/**
* Why a room can't be closed yet: closing cancels whatever still runs in it
* (`cancelChatroomJobs`), so a coordinator that answers over a member's
* live work throws that work away. Written as the tool's error, so the
* coordinator reads who is busy and asks again instead. Empty with no open
* job: then there is nothing to warn about.
*/
export default function chatroomOpenJobsWarning({ jobs, closing }: Params): string {
if (!jobs.length) return "";
const working = jobs
.map((job) => `${job.bot_name || "A bot"} (run #${job.id}${job.status ? `, ${job.status}` : ""})`)
.join(", ");
return `Still working here: ${working}. ${closing} closes the room and cancels that run, so the work is lost. Ask them where they stand first, or pass close_anyway: true when the outcome doesn't depend on what they find.`;
}
@@ -6,4 +6,4 @@ export default function costLabel({ cost }: { cost?: number | null }) {
if (typeof cost != "number" || !(cost > 0)) return "Not reported";
return `$${cost < 0.01 ? cost.toFixed(6) : cost.toFixed(4)}`;
}
}
+4
View File
@@ -36,6 +36,10 @@ describe("exportMessageText", () => {
expect(exportMessageText({ text: "Pick: [question:4]", ...names, heading_offset: 0 })).toBe("Pick: (questions 4)");
});
test("words suggested next steps by number", () => {
expect(exportMessageText({ text: "Then: [suggestion:4]", ...names, heading_offset: 0 })).toBe("Then: (next steps 4)");
});
test("words a task once, even after the bot's own word for it", () => {
expect(exportMessageText({ text: "Task [task:27] and [task:3]", ...names, heading_offset: 0 })).toBe(
"Task #27 and task #3",
+1
View File
@@ -87,6 +87,7 @@ function wordRefs({
.replace(/\[secret:(\d+)\](?!\()/g, "(secret $1, hidden)")
.replace(/\[secret-request:(\d+)\](?!\()/g, "(secret request $1)")
.replace(/\[question:(\d+)\](?!\()/g, "(questions $1)")
.replace(/\[suggestion:(\d+)\](?!\()/g, "(next steps $1)")
.replace(/\[graphic:(\d+)\](?!\()/g, "(graphic $1)")
.replace(
/(\btask\s+)?\[task:(\d+)\](?!\()/gi,
+8
View File
@@ -8,6 +8,7 @@ import proposalRef from "./proposal-ref";
import secretRef from "./secret-ref";
import secretRequestRef from "./secret-request-ref";
import botQuestionRef from "./bot-question-ref";
import botSuggestionRef from "./bot-suggestion-ref";
import takeOverRef from "./take-over-ref";
import generalSettingsRef from "./general-settings-ref";
@@ -61,6 +62,13 @@ describe("linkComputerRefs", () => {
expect(linkComputerRefs({ text: "See `[question:4]`" })).toBe("See [questions 4](#question-4)");
});
test("links the next steps a bot suggested, also when quoted alone in code", () => {
expect(linkComputerRefs({ text: `Done. ${botSuggestionRef({ id: 4 })}` })).toBe(
"Done. [next steps 4](#suggestion-4)",
);
expect(linkComputerRefs({ text: "See `[suggestion:4]`" })).toBe("See [next steps 4](#suggestion-4)");
});
test("links take-over requests", () => {
expect(
linkComputerRefs({
+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|task|setting|file|folder";
const RefKinds = "computer|take-over|bot|workspace|proposal|hook-proposal|secret|secret-request|question|suggestion|graphic|room|task|setting|file|folder";
/**
* A code span holding nothing but one ref (`` `[file:12]` ``): bots often
+7 -1
View File
@@ -1,4 +1,5 @@
import { BotQuestionRefHrefPrefix } from "./bot-question-ref";
import { BotSuggestionRefHrefPrefix } from "./bot-suggestion-ref";
import { ChatroomRefHrefPrefix } from "./chatroom-ref";
import { GeneralSettingsRefHrefPrefix } from "./general-settings-ref";
import { GraphicRefHrefPrefix } from "./graphic-ref";
@@ -22,7 +23,8 @@ import {
* (`[workspace:2]`), file ref (`[file:12]`), folder ref
* (`[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
* request ref (`[secret-request:4]`), question ref (`[question:4]`), suggestion ref (`[suggestion:4]`),
* graphic ref (`[graphic:5]`) and
* chatroom ref (`[room:<id>]`) and task ref (`[task:20]`), and a setting
* ref (`[setting:run-limits:reply_steps]`, pointing at that section of
* Settings > General) in a stretch of message text (never code) into a
@@ -66,6 +68,10 @@ export default function linkRefsInText({ text }: { text: string }) {
/\[question:(\d+)\](?!\()/g,
(_, id: string) => `[questions ${id}](${BotQuestionRefHrefPrefix}${id})`,
)
.replace(
/\[suggestion:(\d+)\](?!\()/g,
(_, id: string) => `[next steps ${id}](${BotSuggestionRefHrefPrefix}${id})`,
)
.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})`)
@@ -0,0 +1,20 @@
import { describe, expect, test } from "bun:test";
import parseBotSuggestionRow from "./parse-bot-suggestion-row";
describe("parseBotSuggestionRow", () => {
test("reads the suggested steps", () => {
expect(parseBotSuggestionRow({ row: { steps: JSON.stringify(["Write the report", "Email the team"]) } })).toEqual({
steps: ["Write the report", "Email the team"],
});
});
test("keeps only readable strings", () => {
expect(parseBotSuggestionRow({ row: { steps: JSON.stringify(["Write it", 4, "", " "]) } })).toEqual({ steps: ["Write it"] });
});
test("reads nothing from a missing or broken column", () => {
expect(parseBotSuggestionRow({ row: { steps: null } })).toEqual({ steps: [] });
expect(parseBotSuggestionRow({ row: { steps: "{" } })).toEqual({ steps: [] });
expect(parseBotSuggestionRow({ row: { steps: JSON.stringify({ a: 1 }) } })).toEqual({ steps: [] });
});
});
+23
View File
@@ -0,0 +1,23 @@
type Params = {
row: { steps?: string | null };
};
/**
* A `bot_suggestions` row's stored JSON read back: the steps it holds, and
* none if the column isn't readable.
*/
export default function parseBotSuggestionRow({ row }: Params): { steps: string[] } {
if (!row.steps) return { steps: [] };
try {
const steps = JSON.parse(row.steps) as unknown;
return {
steps: Array.isArray(steps)
? steps.filter((step): step is string => typeof step == "string" && Boolean(step.trim()))
: [],
};
} catch {
return { steps: [] };
}
}
+11
View File
@@ -49,6 +49,12 @@ describe("botCan", () => {
test("a worker can't delegate", () => {
expect(botCan({ kind: "worker", bot_types: [], permission: "delegate_task", workspace_id: 3 })).toBe(false);
});
test("a worker can hand on a task of its own, and a workspace admin can too", () => {
expect(botCan({ kind: "worker", bot_types: [], permission: "hand_over_task", workspace_id: 3 })).toBe(true);
expect(botCan({ kind: "worker", bot_types: [], permission: "hand_over_task" })).toBe(true);
expect(botCan({ bot_types: admin_of_3, permission: "hand_over_task", workspace_id: 3 })).toBe(true);
});
});
describe("botCanTarget", () => {
@@ -77,6 +83,11 @@ describe("botCanTarget", () => {
});
test("a worker directs no one", () => {
/**
* `hand_over_task` is separate: it moves a task the worker already
* has, to a bot it could ask (`chatroomAskableBots`). Nothing here
* lets it hand work out.
*/
expect(botCanTarget({ actor_bot_types: [], target_bot_types: [], workspace_id: 3 })).toBe(false);
});
});