Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7356494ff2 | ||
|
|
f08940341b | ||
|
|
915692a9ee | ||
|
|
8b1b7d9c64 | ||
|
|
45556b3b7f | ||
|
|
956a6b9772 |
@@ -68,7 +68,7 @@ Enables SQLite foreign keys (`enableForeignKeys`), `bunextInit()`, `ensureDocker
|
||||
|
||||
### Cron
|
||||
|
||||
`src/cron/index.ts` registers everything via `registerCronJob` (`src/cron/register-cron-job.ts`); one folder per task. In-process `Bun.cron`, UTC, never overlapping. Notable: `heartbeat`, `sync-harness-models` (hourly), `run-cron-jobs` (every minute, fires schedules), `sync-computers`, `sync-mcp-servers`, `clear-job-steps`, `prune-bots-queue`, `prune-chatrooms`, `prune-orphan-media` (unreferenced uploads, `AppData.MediaOrphanKeepDays`), `prune-computer-caches` (pip/npm/bun caches, `__pycache__` and Chrome profile caches, skipped while a task runs there), `prune-computer-homes` (a computer's moved-aside old home, `AppData.ComputerOldHomeKeepDays`), `warn-computer-workspaces` (logs a computer whose workspace passed `AppData.ComputerWorkspaceWarnShare` of its quota, daily, reports only), `prune-logs`.
|
||||
`src/cron/index.ts` registers everything via `registerCronJob` (`src/cron/register-cron-job.ts`); one folder per task. In-process `Bun.cron`, UTC, never overlapping. Notable: `heartbeat`, `sync-harness-models` (hourly), `run-cron-jobs` (every minute, fires schedules), `sync-computers`, `sync-mcp-servers`, `clear-job-steps`, `prune-bots-queue`, `prune-bot-traces` (the debug view's runs, app setting `bot_trace_keep_days`), `prune-chatrooms`, `prune-orphan-media` (unreferenced uploads, `AppData.MediaOrphanKeepDays`), `prune-computer-caches` (pip/npm/bun caches, `__pycache__` and Chrome profile caches, skipped while a task runs there), `prune-computer-homes` (a computer's moved-aside old home, `AppData.ComputerOldHomeKeepDays`), `warn-computer-workspaces` (logs a computer whose workspace passed `AppData.ComputerWorkspaceWarnShare` of its quota, daily, reports only), `prune-logs`.
|
||||
|
||||
### Admin CRUD API
|
||||
|
||||
@@ -87,12 +87,12 @@ Enables SQLite foreign keys (`enableForeignKeys`), `bunextInit()`, `ensureDocker
|
||||
|
||||
### Bots, sessions, chat
|
||||
|
||||
- **Tables:** `bots` (`kind`, `color` `#rrggbb`, `stone`, `role`, `system_prompt`; `hue` is a legacy fallback), `bot_user_faces`, `bot_sessions`, `bot_messages`, `bot_tasks`, `bot_task_steps` (unused yet). Enums in `src/dict/bot-dict.ts`.
|
||||
- **Tables:** `bots` (`kind`, `color` `#rrggbb`, `stone`, `role`, `system_prompt`; `hue` is a legacy fallback), `bot_user_faces`, `bot_sessions`, `bot_messages`, `bot_tasks`, `bot_task_steps` (unused yet), `bot_job_traces` (a run's debug view, 7 days by default). Enums in `src/dict/bot-dict.ts`.
|
||||
- **Sessions:** one thread per user per bot in its own chat plus one per workspace; split into `bot_sessions` (rollover at the app setting `bot_session_max_messages`, default `AppData.BotSessionMaxMessages`, via `grabBotSessionMaxMessages`; titled and summarised by `name-bot-session.ts` from the session's opening after a reply or a task (a session with no user message, work handed to the bot, is named from the bot's own messages; `grabSessionOpening`; `grabBotMessages` reads the latest), summary carried into the next session only when they're linked by `previous_session_id`, which only a carry-over sets; older implicit links are cleared at boot by `clearImplicitSessionLinks`). New session (`startBotSession`) and a conversation with no active session always start fresh. The rollover carries over like the bot does (`rollOverBotSession` -> `continueBotSession`, falling back to the stored summary; kept for the next message while a job is open in the full session or there's nothing to carry), inside send-message, so the user's message lands under the summary. Helpers in `src/functions/backend/db/bot-sessions/`. Job results land in the job's own session, even after it closes, except a reply that called `continue_in_new_session` (`carryOverBotSession`; the menu's and sessions modal's Continue in new session does the same through `continueBotSession`, the model writing title and summary, refused while a job is open in the session): its summary is kept on the closed session and opens the new one as a bot message (`carried_from_session_id`), the job's `session_id` moves so the answer follows, the new session is titled by the bot then (it has no first exchange to be named from), and the old one can never be reopened (`reopenBotSession` refuses; a thread showing it swaps its composer for a link to the new one). Session lists (rail, sessions modal) reopen a session on click, as before; a carried-over one can't be, so it opens to read (`?session_id=`, `conversationHref`). The page tells them which session it shows (`announceShownSession` -> `useShownSession`): they reload, mark it Current (greyed out; without `?session_id=` the active one is), list it even when it's older than the rail's latest, and the active row then leads back. From half the session length the reply prompt suggests moving on (`longSessionNote`). Earlier sessions never enter the prompt (only the last one's summary): the thread can open them above a session (`useOlderMessages.loadPrevious`, a divider per session, quote and reply as usual), and replies get `search_past_sessions`/`read_past_session` (scoped to that user, bot and place, never the current session) when the conversation has any.
|
||||
- **Coordinator:** exactly one, the super admin's alone, created idempotently by `ensureCoordinatorBot`. Default prompt `src/data/coordinator-system-prompt.ts`, backfilled only when empty.
|
||||
- **Routes:** `/admin/bots` reopens the last visited bot's own chat (cookie `cobble_last_visited_bot_id`, `<bot>` or `<bot>:<workspace>`; the landing uses only the bot) if still reachable, else coordinator (super admin) / latest bot / first workspace / empty. Workspace and conversation pages record the visit per user (`recordWorkspaceVisit`/`workspace_user_visits`, `recordBotVisit`/`bot_user_visits`) and the rail lists both latest visited first (`last_visited_at`, `orderByLastVisit`; a workspace nobody visited yet ranks by its creation, so a new one leads); it never decides the landing. Settings and the rail pages get the cookie's conversation, workspace included, as root prop `last_conversation` (`grabLastConversation`, access-checked, only on those paths: `isPagesRailPath`), shown above their rail list as the way back (`RailLastConversation`). `/admin/bots/[bot_id]` conversation (header, thread and composer at 760px, no right panel; `?session_id=` opens another of the user's sessions there: a closed one is reopened, except a carried-over one, which shows with `SessionMovedBar` instead of the composer, pointing where the conversation went on); `/admin/bots/[bot_id]/models`; `/admin/workspaces/[id]` dashboard; `/admin/workspaces/[id]/chatrooms` that workspace's chatrooms; `/admin/workspaces/[id]/bots/[bot_id]` same conversation scoped to the workspace.
|
||||
- **No model:** while the bot has no text model there (`bot_text_model` null, kept live by the models modal), the thread shows `NoModelNotice` (centred when empty): super admins get Connect a provider / Guided setup, others are told the super admin sets it up.
|
||||
- **Conversation loading:** pages render everything server-side (`grabConversationProps`) **except the history**, which the client loads (`api/admin/bots/conversation-history`, merged with what's already shown, refetched on bfcache restore) and pages older messages on scroll. Rail lists go through `railBots`/`railWorkspaces` (no prompts/memory, previews cut). 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).
|
||||
- **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, task and the step its reply is on (`session-messages`, `use-reply-catch-up`; the history's own `step` seeds that row on load, `use-reply-progress`, and a row only ever moves forward in `bots_queue_updates` ids), 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). **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.
|
||||
@@ -105,6 +105,7 @@ Enables SQLite foreign keys (`enableForeignKeys`), `bunextInit()`, `ensureDocker
|
||||
- **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.
|
||||
- **Thinking row / stop:** `bot-busy-state.ts` decides the row's line and whether Stop shows. Stop (`api/admin/bots/stop.ts`, `stop-bot-jobs`) fails every open job of that bot for the user, aborts the running handler (`job-abort-registry`) and drops late face updates.
|
||||
- **Debug view:** what a run did in order: each turn with what the model reasoned (`stripThinkTags`'s `reasoning`, or the provider's `reasoning`/`reasoning_content`) and answered, each tool call with the arguments it was sent and the answer it got (and its duration), and the loop's own events (`wrap_up`, `redraft`, `review`, `incoming`, `steps_low`). `runTextLoop` emits them through `Params.trace` into `bot_job_traces` (never `bots_queue_updates`, which the `clear-job-steps` cron deletes a minute after a job ends). While a run works, the thinking row's bug button, beside Stop (`BotThinkingRow`), toggles a 250px strip under it (`(partials)/trace-panel.tsx`, `(partials)/trace-log-line.tsx`: one line per step, following its newest line while scrolled to the bottom), read live through `(hooks)/use-bot-trace.ts` and `api/admin/bots/trace`; that toggle stays as the user left it in every conversation (on this device, per user: `useDebugOpen` over `readDebugOpen`/`rememberDebugOpen`, `AppData.DebugViewStorageKey`). When the run ends its logs are tied to the message it answered (`attachJobTracesToMessage`, from the job helpers) and read in that message's Details modal, under a **Debug logs** tab beside Details (`(partials)/message-debug-logs.tsx`, `(hooks)/use-message-trace.ts`, `api/admin/bots/message-trace`), which copies itself as one markdown document (`CopyDebugLogsButton` over `messageDebugLogsMarkdown`), which checks the message's session for the user, a super admin, or the room for a chatroom message). Every entry is redacted before storage (`insertBotJobTrace` with the run's reachable envs, plus the task run's computer redaction for what the bot captured), cut to `AppData.BotTraceTextMaxChars`/`BotTraceArgumentsMaxChars`/`BotTraceResultMaxChars`, at most `BotTraceRowsPerJob` entries per run and `BotTraceJobsPerSession` runs shown, kept for the app setting `bot_trace_keep_days` (default `AppData.BotTraceKeepDays`, daily `prune-bot-traces`). Pushes carry only `BotTraceData` (`job_id`, `session_id`): an open view reads the entries it doesn't have.
|
||||
- **Voice:** mic -> `api/admin/bots/transcribe.ts`; play -> `GET speak-message` streamed into `<audio>`. Nothing recorded is stored. Both disabled with a note when the harness has no model.
|
||||
- **Pictures:** `image_media_id` (private media, `bot-image`/`workspace-image`), via `set-profile-image.ts`, the `set_picture` tool or `update_workspace`. Bytes are **copied**, never moved; only picture-paradigm rows are deleted on replace. Format kept by `imageOutputFormat`.
|
||||
- **Colour:** only `src/utils/bot-color.ts` resolves/validates colours and stones (`resolveBotColor`, `resolveBotStone`, `botColorNeedsPaperFace`); new bots get `pick-free-color.ts`.
|
||||
@@ -120,7 +121,7 @@ Every run also gets `RequestScopeNote` (`src/data/harness-prompts.ts`): the user
|
||||
### Queue (`bots_queue`)
|
||||
|
||||
- Kinds (`BotJobKinds`): `reply` (chat answer, no task row) and `task` (long work, usually on a computer). bun-sqlite `isQueue` table. Helpers in `src/functions/backend/db/bots-queue/`: `enqueueBotJob`, `claimBotJobs` (kind-filtered atomic claim), `updateBotJob` (false once lost/cancelled), `completeBotJob`, `failBotJob` (backoff or fatal), `deferBotJob` (all models resting: attempt refunded, face `asleep`), `cancelBotJob`, `stop-bot-jobs`.
|
||||
- Handler `src/bots-queue/index.ts`: separate reply/task slots, heartbeat, per-attempt deadline (`AppData.BotJobAttemptTimeoutMs`), one task per computer and one reply per session (`createKeyLock`). A chatroom job never waits for a busy computer (the asking bot is often the one holding it): it runs beside it with the shell and files but no browser (`computer_shared`, `openComputerTools({ browser: false })`). Work in `run-bot-job.ts` -> `run-bot-reply.ts` / `run-bot-task.ts`. Throw `BotJobFatalError` for failures retrying can't fix. A computer that's down (`isComputerDown`: failed, dead, exited) is one: `start_task` refuses it and a task run on it fails at once.
|
||||
- Handler `src/bots-queue/index.ts`: separate reply/task slots, heartbeat, a per-attempt deadline for replies (`AppData.BotJobAttemptTimeoutMs`; a task run has none, since its script may run for hours, and Stop ends it), one task per computer and one reply per session (`createKeyLock`). A chatroom job never waits for a busy computer (the asking bot is often the one holding it): it runs beside it with the shell and files but no browser (`computer_shared`, `openComputerTools({ browser: false })`). Work in `run-bot-job.ts` -> `run-bot-reply.ts` / `run-bot-task.ts`. Throw `BotJobFatalError` for failures retrying can't fix. A computer that's down (`isComputerDown`: failed, dead, exited) is one: `start_task` refuses it and a task run on it fails at once.
|
||||
- Every model turn is a step in `bots_queue_updates` (tool names, never arguments; `describe-job-step.ts`, labels in `JobStepToolLabels`), pushed as `server:bot-job-update` by the live relay only. Steps feed the live working row alone: the `clear-job-steps` cron deletes them `AppData.BotJobStepsKeepMs` after the job ends, however it ended, keeping their count on `bots_queue.steps`. Never delete them the moment a job ends (the relay would miss the last ones).
|
||||
- **A task run plans before it starts:** `planBotTask` (from `run-bot-task`) spends one turn, no tools, on the very system prompt the run then sends, so the provider's cache serves it and it costs little more than the plan. The answer is a bounded JSON plan (`BotTaskPlanSchema`, caps in `AppData.BotTaskPlan*`) that opens the run as `taskPlanNote` and shows as its first step line; `shouldPlanBotTask` keeps it off short runs (`AppData.BotTaskPlanMinSteps`) and chatroom turns. A plan that can't be written or read starts the run unplanned, never blocks it.
|
||||
- **A bot can't vouch for itself:** a run's tool calls (`tool_uses`, names and ok, never arguments) go to the wrap-up turn when steps run out and onto the result message as `bot_messages.tool_log`; history follows each recorded bot message with an `[App record: ...]` line (`botMessagesToHarness`), and copies of that line in an answer are stripped (`stripAppRecords`). Before a reply goes out, `reviewBotReply` (the loop's `review`, once per run) sends it back when it names a `[file:ID]`/`[task:ID]` that doesn't exist for the user, a `[setting:...]` ref the app can't resolve (`unresolvedSettingRefs`), or says work is under way or a report will follow (`claimsWorkUnderWay`) with no `start_task`/`delegate_task`/`ask_crew` this reply and nothing open from the session: bots wrote "I'm scanning now" plus made-up results in one answer. A long bot message whose run called no tools shows "No tools used" (`MessageNoToolsChip`).
|
||||
@@ -129,7 +130,7 @@ Every run also gets `RequestScopeNote` (`src/data/harness-prompts.ts`): the user
|
||||
|
||||
### Live updates
|
||||
|
||||
Server push only. `pushBotNotice` (`server:bot-message`, `server:bot-updated`), `pushBotUpdated` (to the bot's whole audience), `server:bot-created|removed`, `server:workspace-created|updated|removed`, `server:computer-updated`. Deletions push to the audience read **before** the delete. `liveRelay` (`src/live-relay/`) polls the DB every `AppData.LiveRelayPollMs` so work from other processes shows; clients dedupe by id. `useLiveBots` keeps rail and header current.
|
||||
Server push only. `pushBotNotice` (`server:bot-message`, `server:bot-updated`), `pushBotUpdated` (to the bot's whole audience), `server:bot-created|removed`, `server:workspace-created|updated|removed`, `server:computer-updated`, and the debug view's `server:bot-trace` (just the job and its session). Deletions push to the audience read **before** the delete. `liveRelay` (`src/live-relay/`) polls the DB every `AppData.LiveRelayPollMs` so work from other processes shows; clients dedupe by id. `useLiveBots` keeps rail and header current.
|
||||
|
||||
### Chatrooms (`chatrooms`)
|
||||
|
||||
@@ -150,7 +151,7 @@ A worker reaches another worker **only through the coordinator**: `ask_crew` (ev
|
||||
- A bot's effective computers (`grab-bot-computers`): the workspace's in a workspace; otherwise direct grants plus its workspaces' (coordinator: all); `bots.computer_id` first. Only a `running` (healthy) computer is reached (`grabComputerMcpUrl` `ready`, `computerNotReadyMessage`).
|
||||
- **Folders:** a run works only in its user's folder (cwd, `HOME`), its bot's and its workspace's (`computerRunDirs`, `withComputerDirs`, `resolveComputerPath`). **A worker sees them through its home:** `/home/cb-<bot>/workspace` (a link the agent keeps to `bots/<bot>`, checked every request by `ensureRunUser`; the rest of the home stays in the container and is never kept), with `users/<user>` and, in a workspace, `workspaces/<id>` (a link to the shared `workspaces/<id>`) inside it; the coordinator works in `bots/<bot>/users/<user>` and reaches the whole workspace. Paths are checked on their real place (`computerWorkspacePath`) and shown to a worker its way (`computerRunPath`); computer folder refs take either spelling. Linux enforces it between bots: **every worker works as its own account** `cb-<bot>` (uid `100000 + id`, no sudo, `ComputerRunDirs.run_as` -> the agent's `run_as`, made by `ensureRunUser`, commands through `setpriv --init-groups`), owning `bots/<bot>` (`2770`); a workspace's folder (root's) belongs to group `cw-<id>` its bots join. **`gem`, and so Chrome, has no way into either** (a page could show another bot's files): a worker's downloads (`collectComputerDownloads`), uploads and files saved by name (`withWorkerBrowserFiles`) pass through a folder of the call's own and are copied by the worker's account (`sudo -u`), never written by `gem` into its folder, and a worker opens no `file:` URLs (it serves its pages on localhost). Its env files are in its own home. A worker can't reach the computer's services: the agent's nftables rule (`guardServicePorts`, container `CapAdd: NET_ADMIN`) resets its connections to the agent, CDP, Playwright MCP, VNC and ttyd, and the X display needs gem's cookie; **without the rule the agent refuses everything for a worker** (never falls back to `gem`). The agent reads files for a worker only inside its folders and home, checked on the open descriptor (`openRunFile`), and writes as the worker (`writeFileAs`). Only the coordinator works as `gem` (sudo). Users within one bot's folder aren't separated by Linux (same account). Keep `computerWorkerAccount` and `runUserFor` alike.
|
||||
- **Installs:** workers install pip/npm packages into `~/.local` of their folder themselves; anything needing root goes through `request_install` (worker task runs the user follows) -> `install_requests` -> a coordinator task on that computer in the super admin's coordinator conversation (`createInstallRequest`, fenced `installRequestBlock`, `InstallRequestNote`, `answer_install_request`); when that job ends however it ends (`settleInstallRequest`, from the job helpers) the answer lands in the worker's session as a crew message (`from_install_request_id`, `isCrewMessage`) and wakes it. Stop also ends a worker's leftover processes on its computers (`endWorkerProcesses`).
|
||||
- **Tools:** the app's own `computer_bash`, `computer_read_file`, `computer_write_file`, `computer_edit_file` (`src/harness/tools/computer/`, paths through `resolveComputerPath`) plus Playwright MCP's `browser_*` (minus `ComputerMcpExcludedTools`: close, resize, config, `browser_run_code_unsafe`; `withComputerDirs` checks `file:` URLs, `paths` and `filename`). Playwright MCP returns only `browser_snapshot` inline: actions save their snapshot and console log in its own folder (`ComputerBrowserOutputDir`, outside every run's folders), so `withBrowserOutputs` turns those links into the tool that reads them, and moves what Chrome finished downloading (`ComputerBrowserDownloadsDir`; Playwright over CDP never sees downloads) into the run's `downloads/` after each browser call. Each command is its own `bash -c` in its own process group, stdin `/dev/null`, killed with its children at its timeout (at most `AppData.ComputerCommandMaxSeconds`) or when the call is aborted (Stop), so nothing blocks the computer; background work (`nohup ... &`) doesn't hold the call.
|
||||
- **Tools:** the app's own `computer_bash`, `computer_read_file`, `computer_write_file`, `computer_edit_file` (`src/harness/tools/computer/`, paths through `resolveComputerPath`) plus Playwright MCP's `browser_*` (minus `ComputerMcpExcludedTools`: close, resize, config, `browser_run_code_unsafe`; `withComputerDirs` checks `file:` URLs, `paths` and `filename`). Playwright MCP returns only `browser_snapshot` inline: actions save their snapshot and console log in its own folder (`ComputerBrowserOutputDir`, outside every run's folders), so `withBrowserOutputs` turns those links into the tool that reads them, and moves what Chrome finished downloading (`ComputerBrowserDownloadsDir`; Playwright over CDP never sees downloads) into the run's `downloads/` after each browser call. Each command is its own `bash -c` in its own process group, stdin `/dev/null`, and has no time limit of its own: `computer_bash` asks for none unless the bot names `timeout` (an install can cap what a bot names with `AppData.ComputerCommandMaxSeconds`, 0 = no cap), so a long script runs for hours, and the command is killed with its children only when the call is aborted (Stop), so nothing blocks the computer; the agent keeps that answer's connection alive with a space every `CommandHeartbeatMs` while it runs, since the app's `fetch` drops a connection that stays silent for about six minutes. Background work (`nohup ... &`) doesn't hold the call.
|
||||
- **Viewing:** `/computers/<id>/` proxy (`handleComputerProxy`, strips app cookies, adds the token, bridges websockets) passes **only the view paths** (`computerProxyPathAllowed`), never the agent's API or `/mcp` (those are the app's tools, with the folder rules). Modes (`ComputerViewModes`, `computerViewModesFor`): **Browser**, the computer's screen (noVNC, scaled to the frame; its size is the computer's setting, a viewer can't resize it), so Chrome shows whole: tab strip, address bar, menu, extensions, drop-downs and prompts (no window manager, Chrome's window fills the screen), and **Shell** (ttyd as `gem`, for crew managers only, `crew_only`: it reads every folder there). Never draw a stand-in browser UI around a page: the user wants Chrome itself. `computer/novnc/cobble-clipboard.js` (added to noVNC's page) makes Ctrl/Cmd+V paste the user's clipboard and copies the computer's back; browsers allow that only over HTTPS or localhost (otherwise noVNC's side panel). Chrome's `--window-size` is in scaled units, so the agent divides it by the scale. No code editor in the image; a mode can be added to `ComputerViewModes`. Old `[take-over:ID:code|desktop]` refs open the first mode; take-overs ask only for modes every user can open. **Take-over:** `ask_user_to_take_over` writes `[take-over:ID:mode]`; "Hand back" sends a chat message; tasks stop and report rather than wait.
|
||||
|
||||
### Schedules (routines in the UI)
|
||||
@@ -221,7 +222,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`, `hand_over_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 at the tool's `timeout_ms` (its own, else `AppData.HarnessToolTimeoutMs`; `null` means no cap, as `computer_bash` has); 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).
|
||||
|
||||
@@ -124,14 +124,19 @@ export const AgentConfig = {
|
||||
*/
|
||||
NoVncDir: env.COBBLE_NOVNC_DIR || "/opt/novnc",
|
||||
/**
|
||||
* A command's timeout when it names none, and the most it may ask for.
|
||||
*/
|
||||
CommandDefaultSeconds: 270,
|
||||
CommandMaxSeconds: 3600,
|
||||
/**
|
||||
* Output past this is dropped (and the response says so).
|
||||
* A command has no time limit of its own: its caller asks for one (a
|
||||
* bot's `computer_bash` leaves it out for long scripts) and the
|
||||
* caller going away still kills it (`handle-exec`). Output past this is
|
||||
* dropped, and the response says so.
|
||||
*/
|
||||
CommandMaxOutputBytes: 4 * 1024 * 1024,
|
||||
/**
|
||||
* A command sends nothing while it runs, and the app's HTTP client gives
|
||||
* up on a connection that stays silent for minutes (Bun's own fetch cuts
|
||||
* one after about six minutes), so the answer keeps it alive with a space
|
||||
* this often. `JSON.parse` ignores the whitespace around the document.
|
||||
*/
|
||||
CommandHeartbeatMs: 15_000,
|
||||
/**
|
||||
* How long children get to exit on a stop before they're killed.
|
||||
*/
|
||||
|
||||
@@ -11,9 +11,11 @@ import workerEnv from "./worker-env";
|
||||
* `POST /api/exec` `{ command, timeout_seconds?, cwd?, run_as? }`: runs
|
||||
* one bash command as the computer's user (`runCommand`), or with
|
||||
* `run_as: { bot_id, workspace_id? }` as that worker bot's own account
|
||||
* (`requestRunUser`), from its home unless `cwd` is given. The command is
|
||||
* killed if the caller goes away. Answers `{ output, exit_code,
|
||||
* timed_out, truncated }`.
|
||||
* (`requestRunUser`), from its home unless `cwd` is given. It runs until
|
||||
* it ends unless the caller gives `timeout_seconds`, and is killed if the
|
||||
* caller goes away. Answers `{ output, exit_code, timed_out, truncated }`
|
||||
* after a space every `CommandHeartbeatMs` while it runs, so a client that
|
||||
* drops a silent connection keeps it.
|
||||
*/
|
||||
export default async function handleExec({ req, res }: { req: IncomingMessage; res: ServerResponse }) {
|
||||
const body = await readJsonBody({ req, max_bytes: 1024 * 1024 });
|
||||
@@ -27,18 +29,42 @@ export default async function handleExec({ req, res }: { req: IncomingMessage; r
|
||||
if (run_user === undefined) return;
|
||||
|
||||
const asked = Number(body.timeout_seconds);
|
||||
const timeout_seconds = Number.isFinite(asked) && asked > 0
|
||||
? Math.min(Math.ceil(asked), AgentConfig.CommandMaxSeconds)
|
||||
: AgentConfig.CommandDefaultSeconds;
|
||||
/**
|
||||
* A command has no time limit unless the caller asks for one: nothing,
|
||||
* or 0, means it runs until it ends, the caller goes away (this
|
||||
* response closes) or the container stops. A positive value is that
|
||||
* many seconds, however long, so a bot's script is never cut short.
|
||||
*/
|
||||
const timeout_seconds = Number.isFinite(asked) && asked > 0 ? Math.ceil(asked) : null;
|
||||
|
||||
const controller = new AbortController();
|
||||
|
||||
res.on("close", () => {
|
||||
if (!res.writableFinished) controller.abort();
|
||||
});
|
||||
/**
|
||||
* A heartbeat into a socket the caller closed must not take the agent
|
||||
* down, and there's nothing left to send it: stop the command.
|
||||
*/
|
||||
res.on("error", () => controller.abort());
|
||||
|
||||
const home = run_user ? run_user.home : AgentConfig.Home;
|
||||
|
||||
if (res.destroyed) return;
|
||||
|
||||
/**
|
||||
* The result goes out as one JSON body once the command ends, which may
|
||||
* be hours away, so the answer is opened now and kept alive with a space
|
||||
* until then: a client that drops a silent connection (`fetch` does, at
|
||||
* about six minutes) would otherwise lose the command's output and think
|
||||
* it failed. A space before the document is still JSON.
|
||||
*/
|
||||
res.writeHead(200, { "content-type": "application/json; charset=utf-8", "cache-control": "no-store" });
|
||||
|
||||
const heartbeat = setInterval(() => {
|
||||
if (!res.destroyed) res.write(" ");
|
||||
}, AgentConfig.CommandHeartbeatMs);
|
||||
|
||||
const result = await runCommand({
|
||||
command: body.command,
|
||||
cwd: typeof body.cwd == "string" && body.cwd.startsWith("/") ? body.cwd : home,
|
||||
@@ -49,5 +75,7 @@ export default async function handleExec({ req, res }: { req: IncomingMessage; r
|
||||
signal: controller.signal,
|
||||
});
|
||||
|
||||
if (!res.destroyed) sendJson({ res, body: result });
|
||||
clearInterval(heartbeat);
|
||||
|
||||
if (!res.destroyed) res.end(JSON.stringify(result));
|
||||
}
|
||||
|
||||
@@ -47,6 +47,14 @@ describe("runCommand", () => {
|
||||
expect(result.truncated).toBe(true);
|
||||
});
|
||||
|
||||
test("runs to the end with no time limit", async () => {
|
||||
const result = await runCommand({ ...base, timeout_seconds: null, command: "sleep 1; echo done" });
|
||||
|
||||
expect(result.output).toBe("done\n");
|
||||
expect(result.exit_code).toBe(0);
|
||||
expect(result.timed_out).toBe(false);
|
||||
});
|
||||
|
||||
test("is killed when aborted", async () => {
|
||||
const controller = new AbortController();
|
||||
|
||||
|
||||
@@ -13,7 +13,10 @@ type Params = {
|
||||
* and `gid` are then left out.
|
||||
*/
|
||||
as?: { uid: number; gid: number };
|
||||
timeout_seconds: number;
|
||||
/**
|
||||
* Stop it after this many seconds, `null` for no time limit at all.
|
||||
*/
|
||||
timeout_seconds: number | null;
|
||||
max_output_bytes: number;
|
||||
/**
|
||||
* Aborting (the caller went away, the run was stopped) kills it.
|
||||
@@ -32,9 +35,10 @@ export type CommandResult = {
|
||||
* Runs one command in its own `bash -c`, in its own process group, with
|
||||
* no input (a prompt fails at once instead of waiting). stdout and stderr
|
||||
* come back together, in order, cut at `max_output_bytes`. Past its
|
||||
* timeout, or when aborted, the whole group gets TERM, then KILL 5s later.
|
||||
* It resolves when bash exits, not when every pipe closes, so work left in
|
||||
* the background (`nohup ... &`) keeps running without holding the call.
|
||||
* timeout (when it has one), or when aborted, the whole group gets TERM,
|
||||
* then KILL 5s later. It resolves when bash exits, not when every pipe
|
||||
* closes, so work left in the background (`nohup ... &`) keeps running
|
||||
* without holding the call.
|
||||
*/
|
||||
export default function runCommand({
|
||||
command,
|
||||
@@ -91,10 +95,12 @@ export default function runCommand({
|
||||
kill_timer = setTimeout(() => child.pid && killGroup({ pid: child.pid, signal: "SIGKILL" }), 5000);
|
||||
};
|
||||
|
||||
const timer = setTimeout(() => {
|
||||
timed_out = true;
|
||||
stop();
|
||||
}, timeout_seconds * 1000);
|
||||
const timer = timeout_seconds == null
|
||||
? undefined
|
||||
: setTimeout(() => {
|
||||
timed_out = true;
|
||||
stop();
|
||||
}, timeout_seconds * 1000);
|
||||
|
||||
const onAbort = () => stop();
|
||||
|
||||
@@ -104,7 +110,7 @@ export default function runCommand({
|
||||
if (settled) return;
|
||||
|
||||
settled = true;
|
||||
clearTimeout(timer);
|
||||
if (timer) clearTimeout(timer);
|
||||
clearTimeout(kill_timer);
|
||||
signal?.removeEventListener("abort", onAbort);
|
||||
|
||||
|
||||
+102
@@ -20,6 +20,7 @@ import {
|
||||
import { Harnesses } from "@/src/dict/harness-dict";
|
||||
import { HarnessProviderKinds } from "@/src/dict/harness-provider-dict";
|
||||
import { BotJobKinds, BotJobUpdateKinds } from "@/src/dict/bot-queue-dict";
|
||||
import { BotTraceKinds } from "@/src/dict/bot-trace-dict";
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
import {
|
||||
BotHookEventStatuses,
|
||||
@@ -1188,6 +1189,107 @@ const schema: BUN_SQLITE_DatabaseSchemaType = {
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
tableName: "bot_job_traces",
|
||||
tableDescription: `What a job did, in detail, for the conversation's debug view: one row per model turn (what it answered and reasoned), per tool call (the arguments it wrote and the answer it read), and per loop event (the wrap up, a redraft, what the user wrote mid-run). Written by \`process-bot-job\` as the run goes, tied to the message it ends in, and pruned after the app setting \`bot_trace_keep_days\``,
|
||||
fields: [
|
||||
{
|
||||
fieldName: "bots_queue_id",
|
||||
fieldDescription: `The job (bots_queue) the trace belongs to`,
|
||||
dataType: "INTEGER",
|
||||
foreignKey: {
|
||||
cascadeDelete: true,
|
||||
destinationTableName: "bots_queue",
|
||||
destinationTableColumnName: "id",
|
||||
destinationTableColumnType: "INTEGER",
|
||||
foreignKeyName: "bot_job_traces_job_fk",
|
||||
},
|
||||
},
|
||||
{
|
||||
fieldName: "bot_id",
|
||||
fieldDescription: `The bot the job ran for`,
|
||||
dataType: "INTEGER",
|
||||
foreignKey: {
|
||||
cascadeDelete: true,
|
||||
destinationTableName: "bots",
|
||||
destinationTableColumnName: "id",
|
||||
destinationTableColumnType: "INTEGER",
|
||||
foreignKeyName: "bot_job_traces_bot_fk",
|
||||
},
|
||||
},
|
||||
{
|
||||
fieldName: "session_id",
|
||||
fieldDescription: `The session the job answers in: who may read the trace`,
|
||||
dataType: "INTEGER",
|
||||
foreignKey: {
|
||||
cascadeDelete: true,
|
||||
destinationTableName: "bot_sessions",
|
||||
destinationTableColumnName: "id",
|
||||
destinationTableColumnType: "INTEGER",
|
||||
foreignKeyName: "bot_job_traces_session_fk",
|
||||
},
|
||||
},
|
||||
{
|
||||
fieldName: "message_id",
|
||||
fieldDescription: `The message the run ended in, filled when the job completes: the debug logs tab of its Details modal reads them. No foreign key, so a message's rows wait for the prune rather than cascade`,
|
||||
dataType: "INTEGER",
|
||||
},
|
||||
{
|
||||
fieldName: "kind",
|
||||
fieldDescription: `turn, tool or event`,
|
||||
dataType: "TEXT",
|
||||
options: BotTraceKinds.map((k) => k.value),
|
||||
},
|
||||
{
|
||||
fieldName: "name",
|
||||
fieldDescription: `The tool or event's name; null on a model turn`,
|
||||
dataType: "TEXT",
|
||||
},
|
||||
{
|
||||
fieldName: "text",
|
||||
fieldDescription: `What the model answered, or what the event says`,
|
||||
dataType: "TEXT",
|
||||
},
|
||||
{
|
||||
fieldName: "reasoning",
|
||||
fieldDescription: `What the model reasoned before answering, when the provider hands it back`,
|
||||
dataType: "TEXT",
|
||||
},
|
||||
{
|
||||
fieldName: "arguments",
|
||||
fieldDescription: `The arguments a tool call was made with, as the model wrote them`,
|
||||
dataType: "TEXT",
|
||||
},
|
||||
{
|
||||
fieldName: "result",
|
||||
fieldDescription: `What the tool answered (cut to AppData.BotTraceResultMaxChars)`,
|
||||
dataType: "TEXT",
|
||||
},
|
||||
{
|
||||
fieldName: "metadata",
|
||||
fieldDescription: `JSON details: the step index, model, tokens, duration, and whether the call went through`,
|
||||
dataType: "TEXT",
|
||||
},
|
||||
],
|
||||
indexes: [
|
||||
{
|
||||
indexName: "idx_bot_job_traces_job_created_at",
|
||||
indexTableFields: ["bots_queue_id", "created_at"],
|
||||
},
|
||||
{
|
||||
indexName: "idx_bot_job_traces_session_created_at",
|
||||
indexTableFields: ["session_id", "created_at"],
|
||||
},
|
||||
{
|
||||
indexName: "idx_bot_job_traces_message",
|
||||
indexTableFields: ["message_id"],
|
||||
},
|
||||
{
|
||||
indexName: "idx_bot_job_traces_created_at",
|
||||
indexTableFields: ["created_at"],
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
tableName: "cron_jobs",
|
||||
tableDescription: `A bot's schedules (routines in the UI): a brief queued as a task on a cron schedule, in UTC. The \`run-cron-jobs\` cron queues the due ones every minute`,
|
||||
|
||||
+61
-1
@@ -17,6 +17,7 @@ export const BunSQLiteTables = [
|
||||
"task_notes",
|
||||
"bots_queue",
|
||||
"bots_queue_updates",
|
||||
"bot_job_traces",
|
||||
"cron_jobs",
|
||||
"bot_hooks",
|
||||
"bot_hook_events",
|
||||
@@ -763,6 +764,65 @@ export type BUN_SQLITE_COBBLE_BOTS_QUEUE_UPDATES = {
|
||||
metadata?: string;
|
||||
}
|
||||
|
||||
export type BUN_SQLITE_COBBLE_BOT_JOB_TRACES = {
|
||||
/**
|
||||
* 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 | "";
|
||||
/**
|
||||
* The job (bots_queue) the trace belongs to
|
||||
*/
|
||||
bots_queue_id?: number | "";
|
||||
/**
|
||||
* The bot the job ran for
|
||||
*/
|
||||
bot_id?: number | "";
|
||||
/**
|
||||
* The session the job answers in: who may read the trace
|
||||
*/
|
||||
session_id?: number | "";
|
||||
/**
|
||||
* The message the run ended in, filled when the job completes: the debug logs tab of its Details modal reads them. No foreign key, so a message's rows wait for the prune rather than cascade
|
||||
*/
|
||||
message_id?: number | "";
|
||||
/**
|
||||
* turn, tool or event
|
||||
*/
|
||||
kind?: "turn" | "tool" | "event" | "";
|
||||
/**
|
||||
* The tool or event's name; null on a model turn
|
||||
*/
|
||||
name?: string;
|
||||
/**
|
||||
* What the model answered, or what the event says
|
||||
*/
|
||||
text?: string;
|
||||
/**
|
||||
* What the model reasoned before answering, when the provider hands it back
|
||||
*/
|
||||
reasoning?: string;
|
||||
/**
|
||||
* The arguments a tool call was made with, as the model wrote them
|
||||
*/
|
||||
arguments?: string;
|
||||
/**
|
||||
* What the tool answered (cut to AppData.BotTraceResultMaxChars)
|
||||
*/
|
||||
result?: string;
|
||||
/**
|
||||
* JSON details: the step index, model, tokens, duration, and whether the call went through
|
||||
*/
|
||||
metadata?: string;
|
||||
}
|
||||
|
||||
export type BUN_SQLITE_COBBLE_CRON_JOBS = {
|
||||
/**
|
||||
* The unique identifier of the record.
|
||||
@@ -2866,4 +2926,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_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
|
||||
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_BOT_JOB_TRACES & 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
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "cobble",
|
||||
"version": "0.19.1",
|
||||
"version": "0.20.0",
|
||||
"module": "index.ts",
|
||||
"type": "module",
|
||||
"private": true,
|
||||
|
||||
@@ -5,6 +5,8 @@ import completeBotJob from "@/src/functions/backend/db/bots-queue/complete-bot-j
|
||||
import failBotJob from "@/src/functions/backend/db/bots-queue/fail-bot-job";
|
||||
import updateBotJob from "@/src/functions/backend/db/bots-queue/update-bot-job";
|
||||
import insertBotJobUpdate from "@/src/functions/backend/db/bots-queue/insert-bot-job-update";
|
||||
import insertBotJobTrace from "@/src/functions/backend/db/bots-queue/insert-bot-job-trace";
|
||||
import grabReachableEnvs from "@/src/functions/backend/db/envs/grab-reachable-envs";
|
||||
import { logError } from "@/src/functions/backend/logger";
|
||||
import createKeyLock from "@/src/utils/create-key-lock";
|
||||
import withTimeout from "@/src/utils/with-timeout";
|
||||
@@ -32,6 +34,7 @@ import nameBotSession from "./name-bot-session";
|
||||
import pushBotSession from "./push-bot-session";
|
||||
import grabSessionChatroomId from "@/src/functions/backend/db/chatrooms/grab-session-chatroom-id";
|
||||
import { registerJobAbort, unregisterJobAbort } from "./job-abort-registry";
|
||||
import type { BotTraceData } from "@/src/types";
|
||||
import type { BotJobUpdateData } from "@/src/types";
|
||||
import type { BotJobContext, BotJobRunner } from "./types";
|
||||
|
||||
@@ -159,10 +162,64 @@ export default async function processBotJob({
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Every secret the run reaches, blanked out of the trace it keeps: a
|
||||
* tool's arguments and answer carry whatever it handled, and the trace
|
||||
* is read by the user long after the run.
|
||||
*/
|
||||
let trace_secrets: { key: string; value: string }[] | undefined;
|
||||
/**
|
||||
* Rows this process wrote for the job, against
|
||||
* `AppData.BotTraceRowsPerJob`: a run that goes on for hours mustn't
|
||||
* fill the database with its details.
|
||||
*/
|
||||
let traced_rows = 0;
|
||||
|
||||
const trace: BotJobContext["trace"] = async (entry) => {
|
||||
if (!job.session_id || traced_rows >= AppData.BotTraceRowsPerJob) return;
|
||||
|
||||
try {
|
||||
trace_secrets ??= user_id
|
||||
? await grabReachableEnvs({
|
||||
bot_id,
|
||||
user_id,
|
||||
workspace_id: job.workspace_id,
|
||||
computer_id: job.computer_id,
|
||||
}).then((envs) =>
|
||||
[...envs.on_computer, ...envs.tools_only].map(({ key, value }) => ({ key, value })),
|
||||
)
|
||||
: [];
|
||||
|
||||
const row = await insertBotJobTrace({
|
||||
job_id,
|
||||
bot_id,
|
||||
session_id: Number(job.session_id) || null,
|
||||
trace: entry,
|
||||
secrets: trace_secrets,
|
||||
});
|
||||
|
||||
traced_rows++;
|
||||
|
||||
/**
|
||||
* The entry itself stays out of the push: the open drawer
|
||||
* reads it from the API, so a long tool result never crosses
|
||||
* a socket to a phone that isn't looking.
|
||||
*/
|
||||
await pushToSessionUser({
|
||||
session_id: job.session_id,
|
||||
data: {
|
||||
event: "server:bot-trace",
|
||||
data: { job_id, session_id: row.session_id ? Number(row.session_id) : null } satisfies BotTraceData,
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
await logError({ title: `Bot job #${job_id} trace not saved`, error }).catch(() => {});
|
||||
}
|
||||
};
|
||||
|
||||
const heartbeat = setInterval(() => {
|
||||
update({}).catch(() => {});
|
||||
}, HEARTBEAT_MS);
|
||||
|
||||
try {
|
||||
/**
|
||||
* The face changes once the job really starts, after any wait for
|
||||
@@ -178,12 +235,15 @@ export default async function processBotJob({
|
||||
});
|
||||
|
||||
/**
|
||||
* A deadline per attempt: the heartbeat keeps the lock alive
|
||||
* for as long as this run takes, so without one a call that
|
||||
* never answers would hold the slot forever.
|
||||
* A deadline per attempt for a reply: the heartbeat keeps the
|
||||
* lock alive for as long as this run takes, so without one a
|
||||
* chat answer that never comes would hold the conversation's
|
||||
* slot forever. A task run has none: a command or a build may
|
||||
* legitimately hold its computer for hours (`computer_bash` has
|
||||
* no time limit either), and Stop still ends it here and now.
|
||||
*/
|
||||
return await withTimeout({
|
||||
timeout_ms: AppData.BotJobAttemptTimeoutMs,
|
||||
timeout_ms: job.kind == "task" ? null : AppData.BotJobAttemptTimeoutMs,
|
||||
signal: controller.signal,
|
||||
message: timeout_message,
|
||||
on_timeout: () => {
|
||||
@@ -198,6 +258,7 @@ export default async function processBotJob({
|
||||
signal: run_signal,
|
||||
update,
|
||||
report,
|
||||
trace,
|
||||
}),
|
||||
});
|
||||
};
|
||||
@@ -205,10 +266,10 @@ export default async function processBotJob({
|
||||
/**
|
||||
* A task whose computer is busy says so while it waits, so the
|
||||
* user doesn't see silence. A chatroom job doesn't wait: the bot
|
||||
* that asked is often the one holding the computer, with a run of
|
||||
* up to an hour, and the room would sit silent until it ends. It
|
||||
* works beside it with the shell and files only (`computer_shared`),
|
||||
* which is all most answers need.
|
||||
* that asked is often the one holding the computer, with a task run
|
||||
* that may hold it for hours, and the room would sit silent until it
|
||||
* ends. It works beside it with the shell and files only
|
||||
* (`computer_shared`), which is all most answers need.
|
||||
*/
|
||||
const runOnComputer = async (computer_id: number) => {
|
||||
if (computer_lock.busy({ key: computer_id })) {
|
||||
|
||||
@@ -101,6 +101,7 @@ export default async function runBotReply({
|
||||
job,
|
||||
signal,
|
||||
report,
|
||||
trace,
|
||||
}: Params): Promise<BotJobOutcome> {
|
||||
/**
|
||||
* Moves when the bot carries the conversation into a new session
|
||||
@@ -466,6 +467,7 @@ export default async function runBotReply({
|
||||
workspace_id,
|
||||
signal,
|
||||
onStep: report,
|
||||
trace,
|
||||
incoming,
|
||||
/**
|
||||
* Files, tasks and work the answer names are checked against
|
||||
|
||||
@@ -36,6 +36,7 @@ import grabBotComputers from "@/src/functions/backend/db/computers/grab-bot-comp
|
||||
import grabBotPrompt from "@/src/functions/backend/db/bots/grab-bot-prompt";
|
||||
import grabUserWorkspaces from "@/src/functions/backend/db/workspaces/grab-user-workspaces";
|
||||
import runTextLoop from "@/src/harness/text/run-text-loop";
|
||||
import redactTrace from "@/src/harness/trace/redact-trace";
|
||||
import { isUnlimitedLimit, smallerRunLimit } from "@/src/utils/run-limit";
|
||||
import openComputerTools from "@/src/harness/tools/computer/open-computer-tools";
|
||||
import openBotBrowsers, { type OpenBotBrowsers } from "@/src/harness/tools/browsers/open-bot-browsers";
|
||||
@@ -108,6 +109,7 @@ export default async function runBotTask({
|
||||
computer_shared,
|
||||
signal,
|
||||
report,
|
||||
trace,
|
||||
}: Params): Promise<BotJobOutcome> {
|
||||
const workspace_id = job.workspace_id || null;
|
||||
/**
|
||||
@@ -525,6 +527,12 @@ export default async function runBotTask({
|
||||
signal,
|
||||
onStep: (step) =>
|
||||
report({ ...step, text: step.text && computer ? computer.redact(step.text) : step.text }),
|
||||
/**
|
||||
* The trace also holds a computer's own secrets: what the bot
|
||||
* captured mid-run (`capture_secret`) never reaches the
|
||||
* stored trace, whatever the job's envs are.
|
||||
*/
|
||||
trace: (entry) => trace(computer ? redactTrace({ trace: entry, redact: computer.redact }) : entry),
|
||||
...(incoming
|
||||
? {
|
||||
incoming: incoming.take,
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import type { BUN_SQLITE_COBBLE_BOTS_QUEUE } from "@/db/types/db";
|
||||
import type { TextLoopStep } from "@/src/harness/text/run-text-loop";
|
||||
import type { HarnessTracer } from "@/src/harness/trace/types";
|
||||
import type { HarnessToolUse } from "@/src/harness/types";
|
||||
|
||||
export type BotJobContext = {
|
||||
@@ -35,6 +36,14 @@ export type BotJobContext = {
|
||||
* `onStep`. Best effort: a failed write never stops the job.
|
||||
*/
|
||||
report: (step: TextLoopStep) => Promise<void>;
|
||||
/**
|
||||
* Keeps what the run did in detail (`bot_job_traces`): every turn with
|
||||
* its reasoning, every tool call with its arguments and answer, and
|
||||
* what the loop itself did. The conversation's debug view reads it.
|
||||
* Pass it as the text loop's `trace`. Best effort, redacted before it
|
||||
* is stored, and a failed write never stops the job.
|
||||
*/
|
||||
trace: HarnessTracer;
|
||||
};
|
||||
|
||||
export type BotJobOutcome = {
|
||||
|
||||
@@ -3,6 +3,7 @@ import cronHeartbeat from "./heartbeat";
|
||||
import pruneBotsQueue from "./prune-bots-queue";
|
||||
import cronClearJobSteps from "./clear-job-steps";
|
||||
import pruneBotHookEvents from "./prune-bot-hook-events";
|
||||
import pruneBotTraces from "./prune-bot-traces";
|
||||
import cronPruneChatrooms from "./prune-chatrooms";
|
||||
import cronPruneComputerCaches from "./prune-computer-caches";
|
||||
import cronPruneComputerHomes from "./prune-computer-homes";
|
||||
@@ -51,6 +52,12 @@ export default function cron() {
|
||||
task: pruneBotHookEvents,
|
||||
});
|
||||
|
||||
registerCronJob({
|
||||
title: "prune-bot-traces",
|
||||
schedule: "@daily",
|
||||
task: pruneBotTraces,
|
||||
});
|
||||
|
||||
registerCronJob({
|
||||
title: "prune-chatrooms",
|
||||
schedule: "@daily",
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
import { grabBotTraceKeepDays } from "@/src/functions/backend/db/app-settings/grab-bot-trace-keep-days";
|
||||
|
||||
/**
|
||||
* Deletes run traces (`bot_job_traces`, the conversation's debug view)
|
||||
* older than the install's retention (`grabBotTraceKeepDays`). Deleting a
|
||||
* job takes its traces with it (foreign keys), so this only takes what no
|
||||
* daily job prune would.
|
||||
*/
|
||||
export default async function pruneBotTraces() {
|
||||
const cutoff = Date.now() - (await grabBotTraceKeepDays()) * 24 * 60 * 60 * 1000;
|
||||
|
||||
return await BunSQLite.sql({
|
||||
sql: `DELETE FROM bot_job_traces WHERE created_at < ? RETURNING id`,
|
||||
values: [cutoff],
|
||||
});
|
||||
}
|
||||
+41
-13
@@ -51,6 +51,12 @@ export const AppData = {
|
||||
* next open starts there.
|
||||
*/
|
||||
ComputerViewModeStorageKey: `${SiteData["SiteSlug"]}_computer_view_modes`,
|
||||
/**
|
||||
* Whether each user left the conversation's debug view open, on this
|
||||
* device (`readDebugOpen`/`rememberDebugOpen`): the view is theirs, so
|
||||
* it stays as they left it in every conversation.
|
||||
*/
|
||||
DebugViewStorageKey: `${SiteData["SiteSlug"]}_debug_view_open`,
|
||||
ServerHealthMessage: "Server Running Well",
|
||||
AuthKeyCookieName: `${SiteData["SiteSlug"]}_auth_key`,
|
||||
AuthCSRFCookieName: `${SiteData["SiteSlug"]}_auth_csrf`,
|
||||
@@ -111,7 +117,7 @@ export const AppData = {
|
||||
* `computer/` (the release workflow builds that tag), and bump
|
||||
* `ComputerWorkspaceLayout` too when existing computers must move to it.
|
||||
*/
|
||||
ComputerImage: "ghcr.io/moduletrace/cobble-computer:1.4.1",
|
||||
ComputerImage: "ghcr.io/moduletrace/cobble-computer:1.4.2",
|
||||
ComputerContainerPrefix: `${SiteData["SiteSlug"]}-computer`,
|
||||
/**
|
||||
* Only a computer's workspace (`ComputerWorkspaceDir` in its
|
||||
@@ -305,11 +311,14 @@ export const AppData = {
|
||||
BotQueueLockTimeoutMs: 10 * 60 * 1000,
|
||||
BotQueueBackoffMs: 30 * 1000,
|
||||
/**
|
||||
* One attempt of a job (one model run or task, tools included) gives up
|
||||
* after this long and counts as a failed try, so a call that hangs
|
||||
* without ever answering can't hold the job, its computer or the
|
||||
* conversation forever. The lock is outlived by the heartbeat, so this
|
||||
* is the only thing that stops a live but stuck run.
|
||||
* A reply's deadline: one attempt (its model run and tools included)
|
||||
* gives up after this long and counts as a failed try, so a chat answer
|
||||
* that hangs without ever answering can't hold the conversation
|
||||
* forever. The lock is outlived by the heartbeat, so this is the only
|
||||
* thing that stops a live but stuck reply. A task run has none (a
|
||||
* command or a build may hold it for hours): only Stop, a lost lock or
|
||||
* the process ending stops its work, and a command on its computer is
|
||||
* stopped when the call is aborted.
|
||||
*/
|
||||
BotJobAttemptTimeoutMs: 2 * 60 * 60 * 1000,
|
||||
/**
|
||||
@@ -464,10 +473,10 @@ export const AppData = {
|
||||
HarnessMaxCandidates: 6,
|
||||
HarnessRequestTimeoutMs: 3 * 60 * 1000,
|
||||
/**
|
||||
* One tool call gives up after this long, whatever the tool is (bot
|
||||
* tools, MCP servers, computers, custom tools), so a tool that ignores
|
||||
* its own limits can't stall the run. Its result comes back as an error
|
||||
* the model can work around.
|
||||
* One tool call gives up after this long unless the tool names its own
|
||||
* deadline (`HarnessTool.timeout_ms`, `null` for none), so a tool that
|
||||
* ignores its own limits can't stall the run. Its result comes back as
|
||||
* an error the model can work around.
|
||||
*/
|
||||
HarnessToolTimeoutMs: 10 * 60 * 1000,
|
||||
/**
|
||||
@@ -640,10 +649,12 @@ export const AppData = {
|
||||
McpToolTimeoutMs: 5 * 60 * 1000,
|
||||
/**
|
||||
* A bash command on a computer (`computer_bash`) is killed there, with
|
||||
* everything it started, after at most this long, below
|
||||
* `HarnessToolTimeoutMs`.
|
||||
* everything it started, after at most this long: 0 leaves it no time
|
||||
* limit at all, so a script may run for hours. The bot may name its own
|
||||
* `timeout`, which a limit here still caps. Long work holds the
|
||||
* computer (one task run per computer), and Stop ends it.
|
||||
*/
|
||||
ComputerCommandMaxSeconds: 270,
|
||||
ComputerCommandMaxSeconds: 0,
|
||||
/**
|
||||
* What a computer's command hands the bot back (its start and end), and
|
||||
* what `computer_read_file` reads: lines at a time, each line cut
|
||||
@@ -725,6 +736,23 @@ export const AppData = {
|
||||
* to have pushed the last ones (`LiveRelayPollMs`).
|
||||
*/
|
||||
BotJobStepsKeepMs: 60 * 1000,
|
||||
/**
|
||||
* The debug view's detailed trace of a job (`bot_job_traces`, read and
|
||||
* written only by `process-bot-job`): how many rows one job keeps, how
|
||||
* much of any one text, and how long the rows stay before the daily
|
||||
* `prune-bot-traces` deletes them (the install may set its own, the app
|
||||
* setting `bot_trace_keep_days`, up to `BotTraceKeepDaysMax`).
|
||||
*/
|
||||
BotTraceRowsPerJob: 400,
|
||||
BotTraceTextMaxChars: 4000,
|
||||
BotTraceArgumentsMaxChars: 2000,
|
||||
BotTraceResultMaxChars: 8000,
|
||||
BotTraceKeepDays: 7,
|
||||
BotTraceKeepDaysMax: 365,
|
||||
/**
|
||||
* How many of a session's jobs the debug view offers, newest first.
|
||||
*/
|
||||
BotTraceJobsPerSession: 5,
|
||||
/**
|
||||
* How often each server process reads new bot messages, job steps and
|
||||
* bot changes from the database for its own sockets (`liveRelay`).
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
/**
|
||||
* A `bot_job_traces` row: what a run did in detail, behind the debug view.
|
||||
* One row per turn, tool call and loop event, kept beside the one-line
|
||||
* steps the conversation's working row reads (`bots_queue_updates`).
|
||||
*/
|
||||
export const BotTraceKinds = [
|
||||
{ title: "Turn", value: "turn" },
|
||||
{ title: "Tool call", value: "tool" },
|
||||
{ title: "Event", value: "event" },
|
||||
] as const;
|
||||
|
||||
export type BotTraceKind = (typeof BotTraceKinds)[number]["value"];
|
||||
|
||||
/**
|
||||
* The app setting (Settings > General) for how many days a run's trace is
|
||||
* kept, else `AppData.BotTraceKeepDays`.
|
||||
*/
|
||||
export const BotTraceKeepDaysSettingKey = "bot_trace_keep_days";
|
||||
@@ -181,6 +181,15 @@ export const GeneralSettingsSections: GeneralSettingsSection[] = [
|
||||
citable: true,
|
||||
fields: [{ key: "keep_days", title: "Keep hook calls for", kind: "days" }],
|
||||
},
|
||||
{
|
||||
key: "run-traces",
|
||||
title: "Run traces",
|
||||
description: "How long the debug view keeps what a run did in detail: its turns, reasoning, tool calls and results.",
|
||||
readable_by: "everyone",
|
||||
editable_by: "super_admin",
|
||||
citable: true,
|
||||
fields: [{ key: "keep_days", title: "Keep run traces for", kind: "days" }],
|
||||
},
|
||||
{
|
||||
key: "chatrooms",
|
||||
title: "Chatrooms",
|
||||
|
||||
@@ -14,7 +14,11 @@ type Params = {
|
||||
*/
|
||||
path: string;
|
||||
init?: RequestInit;
|
||||
timeout_ms: number;
|
||||
/**
|
||||
* Give up after this long; `null` or 0 waits for the caller's own
|
||||
* signal alone.
|
||||
*/
|
||||
timeout_ms: number | null;
|
||||
signal?: AbortSignal;
|
||||
};
|
||||
|
||||
@@ -24,12 +28,16 @@ type Params = {
|
||||
*/
|
||||
export default function computerFetch({ computer, path, init = {}, timeout_ms, signal }: Params) {
|
||||
const headers = new Headers(init.headers);
|
||||
const signals = [
|
||||
...(signal ? [signal] : []),
|
||||
...(timeout_ms != null && timeout_ms > 0 ? [AbortSignal.timeout(timeout_ms)] : []),
|
||||
];
|
||||
|
||||
headers.set("authorization", `Bearer ${computer.token}`);
|
||||
|
||||
return fetch(`${computer.base_url}${path}`, {
|
||||
...init,
|
||||
headers,
|
||||
signal: AbortSignal.any([...(signal ? [signal] : []), AbortSignal.timeout(timeout_ms)]),
|
||||
...(signals.length ? { signal: AbortSignal.any(signals) } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import computerJson from "./computer-json";
|
||||
|
||||
/**
|
||||
* The agent answers `/api/exec` with a space every 15 seconds while the
|
||||
* command runs (a client that drops a silent connection would otherwise
|
||||
* lose it), then the JSON. Leading whitespace is still a JSON document,
|
||||
* and this pins that the app reads such an answer.
|
||||
*/
|
||||
describe("computerJson", () => {
|
||||
test("reads an answer kept alive with heartbeat spaces", async () => {
|
||||
const encoder = new TextEncoder();
|
||||
const server = Bun.serve({
|
||||
port: 0,
|
||||
fetch: () =>
|
||||
new Response(
|
||||
new ReadableStream({
|
||||
start(controller) {
|
||||
controller.enqueue(encoder.encode(" "));
|
||||
controller.enqueue(encoder.encode(" "));
|
||||
controller.enqueue(encoder.encode(JSON.stringify({ output: "done\n", exit_code: 0, timed_out: false })));
|
||||
controller.close();
|
||||
},
|
||||
}),
|
||||
{ headers: { "content-type": "application/json" } },
|
||||
),
|
||||
});
|
||||
|
||||
try {
|
||||
const result = await computerJson<{ output: string; exit_code: number }>({
|
||||
computer: { base_url: `http://127.0.0.1:${server.port}`, token: "computer-token" },
|
||||
path: "/api/exec",
|
||||
timeout_ms: 5_000,
|
||||
});
|
||||
|
||||
expect(result.output).toBe("done\n");
|
||||
expect(result.exit_code).toBe(0);
|
||||
} finally {
|
||||
server.stop(true);
|
||||
}
|
||||
});
|
||||
|
||||
test("sends the computer's token and its body", async () => {
|
||||
let received: { token: string | null; body: unknown } = { token: null, body: null };
|
||||
const server = Bun.serve({
|
||||
port: 0,
|
||||
fetch: async (req) => {
|
||||
received = { token: req.headers.get("authorization"), body: await req.json() };
|
||||
return Response.json({ ok: true });
|
||||
},
|
||||
});
|
||||
|
||||
try {
|
||||
const result = await computerJson<{ ok: boolean }>({
|
||||
computer: { base_url: `http://127.0.0.1:${server.port}`, token: "computer-token" },
|
||||
path: "/api/exec",
|
||||
body: { command: "ls" },
|
||||
timeout_ms: 5_000,
|
||||
});
|
||||
|
||||
expect(result.ok).toBe(true);
|
||||
expect(received.token).toBe("Bearer computer-token");
|
||||
expect(received.body).toEqual({ command: "ls" });
|
||||
} finally {
|
||||
server.stop(true);
|
||||
}
|
||||
});
|
||||
|
||||
test("says what the computer refused", async () => {
|
||||
const server = Bun.serve({
|
||||
port: 0,
|
||||
fetch: () => Response.json({ error: "Give the command." }, { status: 400 }),
|
||||
});
|
||||
|
||||
try {
|
||||
const error = await computerJson({
|
||||
computer: { base_url: `http://127.0.0.1:${server.port}`, token: "computer-token" },
|
||||
path: "/api/exec",
|
||||
timeout_ms: 5_000,
|
||||
}).catch((caught: Error) => caught);
|
||||
|
||||
expect(String(error)).toContain("Give the command.");
|
||||
} finally {
|
||||
server.stop(true);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -7,9 +7,10 @@ type Params = {
|
||||
command: string;
|
||||
/**
|
||||
* The command is stopped on the computer after this (whole seconds,
|
||||
* rounded up), with its whole process group.
|
||||
* rounded up), with its whole process group; `null` leaves it no time
|
||||
* limit, so it runs until it ends or the call is aborted.
|
||||
*/
|
||||
timeout_ms: number;
|
||||
timeout_ms: number | null;
|
||||
/**
|
||||
* A worker's own account to run it as (`ComputerRunDirs.run_as`);
|
||||
* without it, the computer's user (gem, with sudo).
|
||||
@@ -25,6 +26,17 @@ export type ComputerCommandResult = {
|
||||
truncated: boolean;
|
||||
};
|
||||
|
||||
/**
|
||||
* The client's own ceiling for a call with no deadline: `AbortSignal.timeout`
|
||||
* needs a number, and twenty days is past any command a run would wait on
|
||||
* while staying under its maximum. The command's own limit, the run's Stop
|
||||
* and the computer's connection are what really end it; the agent keeps the
|
||||
* answer alive with a heartbeat while it runs, so a client that drops a
|
||||
* silent connection (Bun's fetch does, after about six minutes) never cuts
|
||||
* a long command.
|
||||
*/
|
||||
const NoDeadlineFetchMs = 20 * 24 * 60 * 60 * 1000;
|
||||
|
||||
/**
|
||||
* Runs one bash command on a computer as its user, or as a worker's own
|
||||
* account (`run_as`) (the agent's `/api/exec`): a fresh `bash -c` from its home, no input, stdout and
|
||||
@@ -36,11 +48,15 @@ export default async function runComputerCommand({ computer, command, timeout_ms
|
||||
const result = await computerJson<Partial<ComputerCommandResult>>({
|
||||
computer,
|
||||
path: "/api/exec",
|
||||
body: { command, timeout_seconds: Math.max(1, Math.ceil(timeout_ms / 1000)), ...(run_as ? { run_as } : {}) },
|
||||
body: {
|
||||
command,
|
||||
...(timeout_ms == null ? {} : { timeout_seconds: Math.max(1, Math.ceil(timeout_ms / 1000)) }),
|
||||
...(run_as ? { run_as } : {}),
|
||||
},
|
||||
/**
|
||||
* Room for the agent to stop it and answer.
|
||||
*/
|
||||
timeout_ms: timeout_ms + 15_000,
|
||||
timeout_ms: timeout_ms == null ? NoDeadlineFetchMs : timeout_ms + 15_000,
|
||||
signal,
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
import { BotTraceKeepDaysSettingKey } from "@/src/dict/bot-trace-dict";
|
||||
import type { BotTraceRetentionOverview } from "@/src/types";
|
||||
import readStepLimit from "@/src/utils/read-step-limit";
|
||||
import grabAppSetting from "./grab-app-setting";
|
||||
|
||||
/**
|
||||
* How many days a run's detailed trace is kept (the debug view): the
|
||||
* install's own number (`bot_trace_keep_days`, Settings > General), else
|
||||
* `AppData.BotTraceKeepDays`.
|
||||
*/
|
||||
export async function grabBotTraceKeepDays() {
|
||||
return readStepLimit({
|
||||
saved: await grabAppSetting({ key: BotTraceKeepDaysSettingKey }),
|
||||
fallback: AppData.BotTraceKeepDays,
|
||||
max: AppData.BotTraceKeepDaysMax,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* The number with its default and ceiling, for the settings page.
|
||||
*/
|
||||
export default async function grabBotTraceRetentionOverview() {
|
||||
const overview: BotTraceRetentionOverview = {
|
||||
keep_days: await grabBotTraceKeepDays(),
|
||||
default_days: AppData.BotTraceKeepDays,
|
||||
max: AppData.BotTraceKeepDaysMax,
|
||||
};
|
||||
|
||||
return overview;
|
||||
}
|
||||
@@ -9,6 +9,7 @@ import settingValueLabel from "@/src/utils/setting-value-label";
|
||||
import grabChatroomRetentionOverview from "./grab-chatroom-retention";
|
||||
import grabComputerWorkspaceQuotaOverview from "./grab-computer-workspace-quota-overview";
|
||||
import grabHookCallRetentionOverview from "./grab-hook-events-keep-days";
|
||||
import grabBotTraceRetentionOverview from "./grab-bot-trace-keep-days";
|
||||
import grabInstallName from "./grab-install-name";
|
||||
import grabLogRetentionOverview from "./grab-logs-keep-days";
|
||||
import grabMessageLengthOverview from "./grab-bot-message-max-chars";
|
||||
@@ -28,11 +29,12 @@ type RawValues = Record<string, number | string | null>;
|
||||
* started shows its new number).
|
||||
*/
|
||||
export default async function grabGeneralSettingsValues(): Promise<GeneralSettingsSectionValues[]> {
|
||||
const [run_limits, skill_limits, hook_calls, logs, chatrooms, sessions, messages, storage, computer_workspace, appendix, install_name] =
|
||||
const [run_limits, skill_limits, hook_calls, run_traces, logs, chatrooms, sessions, messages, storage, computer_workspace, appendix, install_name] =
|
||||
await Promise.all([
|
||||
grabRunLimitsOverview().catch(() => null),
|
||||
grabSkillLimitsOverview().catch(() => null),
|
||||
grabHookCallRetentionOverview().catch(() => null),
|
||||
grabBotTraceRetentionOverview().catch(() => null),
|
||||
grabLogRetentionOverview().catch(() => null),
|
||||
grabChatroomRetentionOverview().catch(() => null),
|
||||
grabSessionLengthOverview().catch(() => null),
|
||||
@@ -59,6 +61,7 @@ export default async function grabGeneralSettingsValues(): Promise<GeneralSettin
|
||||
body_shown_chars: skill_limits?.body_shown_chars ?? null,
|
||||
},
|
||||
"hook-calls": { keep_days: hook_calls?.keep_days ?? null },
|
||||
"run-traces": { keep_days: run_traces?.keep_days ?? null },
|
||||
chatrooms: {
|
||||
keep_days: chatrooms?.keep_days ?? null,
|
||||
max_per_place: chatrooms?.max_per_place ?? null,
|
||||
|
||||
@@ -2,6 +2,7 @@ import { AppData } from "@/src/data/app-data";
|
||||
import type { ConversationHistory } from "@/src/types";
|
||||
import grabActiveBotTask from "../bots/grab-active-bot-task";
|
||||
import grabBotMessages from "../bots/grab-bot-messages";
|
||||
import grabSessionReplyStep from "../bots-queue/grab-session-reply-step";
|
||||
import ensureBotSession from "./ensure-bot-session";
|
||||
import grabCarriedToSessionId from "./grab-carried-to-session-id";
|
||||
import reopenBotSession from "./reopen-bot-session";
|
||||
@@ -31,8 +32,9 @@ type Params = {
|
||||
* one is reopened, unless it was carried over, which only shows, with
|
||||
* where the conversation went on), its latest
|
||||
* `AppData.ConversationFirstMessages` messages (the thread loads older
|
||||
* ones as it scrolls) and the bot's active task in it. Everything else on
|
||||
* the page comes with it from the server (`grabConversationProps`).
|
||||
* ones as it scrolls), the bot's active task in it and the step its
|
||||
* running reply is on. Everything else on the page comes with it from the
|
||||
* server (`grabConversationProps`).
|
||||
* Null when the user can't chat with the bot there.
|
||||
*/
|
||||
export default async function grabConversationHistory({
|
||||
@@ -87,13 +89,14 @@ export default async function grabConversationHistory({
|
||||
session.unread = 0;
|
||||
}
|
||||
|
||||
const [messages, task] = await Promise.all([
|
||||
const [messages, task, step] = await Promise.all([
|
||||
grabBotMessages({
|
||||
session_id: session.id!,
|
||||
user_id,
|
||||
limit: AppData.ConversationFirstMessages + 1,
|
||||
}),
|
||||
grabActiveBotTask({ bot_id: open_bot_id, session_id: session.id }),
|
||||
grabSessionReplyStep({ session_id: session.id! }),
|
||||
]);
|
||||
|
||||
const has_more = messages.length > AppData.ConversationFirstMessages;
|
||||
@@ -103,6 +106,7 @@ export default async function grabConversationHistory({
|
||||
messages: has_more ? messages.slice(1) : messages,
|
||||
has_more,
|
||||
task,
|
||||
step,
|
||||
moved_to_session_id: carried_to,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
import type { BUN_SQLITE_COBBLE_BOT_MESSAGES, BUN_SQLITE_COBBLE_USER_TYPES } from "@/db/types/db";
|
||||
import isPassThroughUser from "@/src/utils/rbac/is-pass-through-user";
|
||||
|
||||
type Params = {
|
||||
message_id: number;
|
||||
user_id: number;
|
||||
user_types?: BUN_SQLITE_COBBLE_USER_TYPES[] | null;
|
||||
};
|
||||
|
||||
/**
|
||||
* A bot message whose run's trace the caller may read: one in a session
|
||||
* that's theirs, or any of them for a super admin. Null when it isn't.
|
||||
*/
|
||||
export default async function grabTraceMessage({
|
||||
message_id,
|
||||
user_id,
|
||||
user_types,
|
||||
}: Params): Promise<BUN_SQLITE_COBBLE_BOT_MESSAGES | null> {
|
||||
const message = (
|
||||
await BunSQLite.sql<BUN_SQLITE_COBBLE_BOT_MESSAGES & { session_user_id: number | null }>({
|
||||
sql: `SELECT m.*, s.user_id AS session_user_id
|
||||
FROM bot_messages m
|
||||
JOIN bot_sessions s ON s.id = m.session_id
|
||||
WHERE m.id = ? AND m.author = 'bot'`,
|
||||
values: [message_id],
|
||||
})
|
||||
).payload?.[0];
|
||||
|
||||
if (!message?.id) return null;
|
||||
|
||||
if (Number(message.session_user_id) == Number(user_id)) return message;
|
||||
|
||||
if (isPassThroughUser({ user_types })) return message;
|
||||
|
||||
return null;
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
import type { BUN_SQLITE_COBBLE_BOT_SESSIONS, BUN_SQLITE_COBBLE_USER_TYPES } from "@/db/types/db";
|
||||
import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
import isPassThroughUser from "@/src/utils/rbac/is-pass-through-user";
|
||||
|
||||
type Params = {
|
||||
session_id: number | string;
|
||||
user_id: number | string;
|
||||
user_types?: BUN_SQLITE_COBBLE_USER_TYPES[] | null;
|
||||
};
|
||||
|
||||
/**
|
||||
* A session whose run trace may be read: the session user's own, or any
|
||||
* session for a super admin (who reaches every bot and workspace).
|
||||
*/
|
||||
export default async function grabTraceSession({
|
||||
session_id,
|
||||
user_id,
|
||||
user_types,
|
||||
}: Params): Promise<BUN_SQLITE_COBBLE_BOT_SESSIONS | null> {
|
||||
const res = await BunSQLite.sql<BUN_SQLITE_COBBLE_BOT_SESSIONS>({
|
||||
sql: `SELECT s.* FROM bot_sessions s WHERE s.id = ? LIMIT 1`,
|
||||
values: [session_id],
|
||||
});
|
||||
|
||||
const session = res.payload?.[0] || null;
|
||||
|
||||
if (!session?.id) return null;
|
||||
|
||||
if (Number(session.user_id) == Number(user_id)) return session;
|
||||
|
||||
return isPassThroughUser({ user_types }) ? session : null;
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
|
||||
type Params = {
|
||||
job_id: number;
|
||||
message_id: number;
|
||||
};
|
||||
|
||||
/**
|
||||
* Ties a run's trace to the message it ended in, so its Details modal can
|
||||
* show what the run did under its debug logs tab. Best effort: a run that
|
||||
* kept no trace, or one whose entries the prune already took, has nothing
|
||||
* to update and isn't an error.
|
||||
*/
|
||||
export default async function attachJobTracesToMessage({ job_id, message_id }: Params) {
|
||||
await BunSQLite.sql({
|
||||
sql: `UPDATE bot_job_traces SET message_id = ? WHERE bots_queue_id = ? AND message_id IS NULL`,
|
||||
values: [message_id, job_id],
|
||||
}).catch(() => {});
|
||||
}
|
||||
@@ -13,6 +13,7 @@ import grabJobUserId from "./grab-job-user-id";
|
||||
import grabRunningBotJobFace from "./grab-running-bot-job-face";
|
||||
import withMessageUsage from "../usage/with-message-usage";
|
||||
import attachJobCallsToMessage from "../usage/attach-job-calls-to-message";
|
||||
import attachJobTracesToMessage from "./attach-job-traces-to-message";
|
||||
import type { HarnessToolUse } from "@/src/harness/types";
|
||||
import grabSessionChatroomId from "../chatrooms/grab-session-chatroom-id";
|
||||
import onChatroomJobEnded from "../chatrooms/on-chatroom-job-ended";
|
||||
@@ -129,6 +130,12 @@ export default async function completeBotJob({
|
||||
if (job.id && inserted?.id) {
|
||||
await attachJobCallsToMessage({ job_id: job.id, message_id: inserted.id });
|
||||
|
||||
/**
|
||||
* What the run did goes with the message it ended in, for its
|
||||
* Details modal's debug logs tab.
|
||||
*/
|
||||
await attachJobTracesToMessage({ job_id: job.id, message_id: inserted.id });
|
||||
|
||||
/**
|
||||
* Graphics the run made belong to the message it posted.
|
||||
*/
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
import type { BotTraceJob } from "@/src/types";
|
||||
import traceJobsFromRows from "./trace-jobs-from-rows";
|
||||
|
||||
type Params = {
|
||||
/**
|
||||
* A message the caller already checked the user reaches.
|
||||
*/
|
||||
message_id: number;
|
||||
};
|
||||
|
||||
type JobRow = {
|
||||
id: number;
|
||||
kind: string;
|
||||
title: string | null;
|
||||
status: string;
|
||||
created_at: number;
|
||||
};
|
||||
|
||||
/**
|
||||
* The traces behind one bot message: what its run did, turn by turn, for
|
||||
* the debug logs tab of its Details modal. Usually one job (a reply or the
|
||||
* task run that reported back); a retried job that posted the same message
|
||||
* would list both.
|
||||
*/
|
||||
export default async function grabMessageTraces({ message_id }: Params): Promise<BotTraceJob[]> {
|
||||
const res = await BunSQLite.sql<JobRow>({
|
||||
sql: `SELECT q.id, q.kind, q.title, q.status, q.created_at
|
||||
FROM bot_job_traces t
|
||||
JOIN bots_queue q ON q.id = t.bots_queue_id
|
||||
WHERE t.message_id = ?
|
||||
GROUP BY q.id
|
||||
ORDER BY q.created_at DESC`,
|
||||
values: [message_id],
|
||||
});
|
||||
|
||||
return traceJobsFromRows({ jobs: res.payload || [] });
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
import type { BotJobUpdateData } from "@/src/types";
|
||||
import openSessionReplyStepSql from "./open-session-reply-step-sql";
|
||||
|
||||
type Params = {
|
||||
session_id: number | string;
|
||||
};
|
||||
|
||||
/**
|
||||
* The step the reply running in a session is on, as `server:bot-job-update`
|
||||
* carries it, or null when no reply runs there. Read with a conversation's
|
||||
* history and by its catch-up, so a reload (or a push missed while the page
|
||||
* stayed open) shows what the reply is doing instead of only its label.
|
||||
*/
|
||||
export default async function grabSessionReplyStep({
|
||||
session_id,
|
||||
}: Params): Promise<BotJobUpdateData | null> {
|
||||
const { sql, values } = openSessionReplyStepSql({ session_id });
|
||||
const res = await BunSQLite.sql<BotJobUpdateData>({ sql, values });
|
||||
const step = (res.payload || [])[0];
|
||||
|
||||
return step ? { ...step, id: Number(step.id), task_id: null } : null;
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
import type { BotTraceJob } from "@/src/types";
|
||||
import traceJobsFromRows from "./trace-jobs-from-rows";
|
||||
|
||||
type Params = {
|
||||
session_id: number;
|
||||
};
|
||||
|
||||
type JobRow = {
|
||||
id: number;
|
||||
kind: string;
|
||||
title: string | null;
|
||||
status: string;
|
||||
created_at: number;
|
||||
};
|
||||
|
||||
/**
|
||||
* A session's traced jobs, newest first, each with everything it did in
|
||||
* detail: what the conversation's debug view streams while a run works and
|
||||
* what it lists when it's done. Read-only, and never more than
|
||||
* `AppData.BotTraceJobsPerSession` jobs.
|
||||
*
|
||||
* A job that's still open is listed even before its first step is kept, so
|
||||
* the live strip can say it's waiting on the bot rather than nothing being
|
||||
* there at all.
|
||||
*/
|
||||
export default async function grabSessionTraces({ session_id }: Params): Promise<BotTraceJob[]> {
|
||||
const res = await BunSQLite.sql<JobRow>({
|
||||
sql: `SELECT q.id, q.kind, q.title, q.status, q.created_at
|
||||
FROM bots_queue q
|
||||
WHERE q.id IN (
|
||||
SELECT bots_queue_id FROM bot_job_traces WHERE session_id = ?
|
||||
UNION
|
||||
SELECT id FROM bots_queue WHERE session_id = ? AND status IN ('pending', 'processing')
|
||||
)
|
||||
ORDER BY q.created_at DESC
|
||||
LIMIT ?`,
|
||||
values: [session_id, session_id, AppData.BotTraceJobsPerSession],
|
||||
});
|
||||
|
||||
return traceJobsFromRows({ jobs: res.payload || [] });
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
import type { BUN_SQLITE_COBBLE_BOT_JOB_TRACES, BunSQLiteTables } from "@/db/types/db";
|
||||
import prepareTrace from "@/src/harness/trace/prepare-trace";
|
||||
import redactTrace from "@/src/harness/trace/redact-trace";
|
||||
import type { HarnessTrace } from "@/src/harness/trace/types";
|
||||
import redactSecrets from "@/src/utils/redact-secrets";
|
||||
|
||||
type Params = {
|
||||
job_id: number;
|
||||
bot_id: number;
|
||||
session_id: number | null;
|
||||
trace: HarnessTrace;
|
||||
/**
|
||||
* Every secret the run reaches (`grabReachableEnvs`): a bot's tool
|
||||
* arguments and results carry whatever it handled, and a trace is read
|
||||
* by the user (and super admins) long after.
|
||||
*/
|
||||
secrets?: { key: string; value: string }[];
|
||||
};
|
||||
|
||||
/**
|
||||
* Records one trace entry of a running job (`bot_job_traces`) and returns
|
||||
* the row. Text is redacted and cut before it is written, never after.
|
||||
*/
|
||||
export default async function insertBotJobTrace({
|
||||
job_id,
|
||||
bot_id,
|
||||
session_id,
|
||||
trace,
|
||||
secrets = [],
|
||||
}: Params): Promise<BUN_SQLITE_COBBLE_BOT_JOB_TRACES> {
|
||||
const prepared = prepareTrace({
|
||||
trace: redactTrace({
|
||||
trace,
|
||||
redact: (text) => redactSecrets({ text, secrets }),
|
||||
}),
|
||||
});
|
||||
|
||||
const row: BUN_SQLITE_COBBLE_BOT_JOB_TRACES = {
|
||||
bots_queue_id: job_id,
|
||||
bot_id,
|
||||
session_id: session_id ?? undefined,
|
||||
kind: prepared.kind,
|
||||
name: prepared.name ?? undefined,
|
||||
text: prepared.text ?? undefined,
|
||||
reasoning: prepared.reasoning ?? undefined,
|
||||
arguments: prepared.arguments ?? undefined,
|
||||
result: prepared.result ?? undefined,
|
||||
metadata: prepared.metadata ?? undefined,
|
||||
};
|
||||
|
||||
const res = await BunSQLite.insert<BUN_SQLITE_COBBLE_BOT_JOB_TRACES, (typeof BunSQLiteTables)[number]>({
|
||||
table: "bot_job_traces",
|
||||
data: [row],
|
||||
});
|
||||
|
||||
const id = res.postInsertReturn?.insertId;
|
||||
|
||||
if (!res.success || !id) {
|
||||
throw new Error(`Failed to save the job trace: ${res.msg}`);
|
||||
}
|
||||
|
||||
return { ...row, id, created_at: Date.now() };
|
||||
}
|
||||
@@ -14,6 +14,7 @@ import grabSessionHookId from "../bot-hooks/grab-session-hook-id";
|
||||
import settleInstallRequest from "../install-requests/settle-install-request";
|
||||
import jobTrackerTaskId from "./job-tracker-task-id";
|
||||
import attachJobCallsToMessage from "../usage/attach-job-calls-to-message";
|
||||
import attachJobTracesToMessage from "./attach-job-traces-to-message";
|
||||
|
||||
type Params = {
|
||||
job: BUN_SQLITE_COBBLE_BOTS_QUEUE;
|
||||
@@ -71,6 +72,7 @@ export default async function notifyBotJobFailed({
|
||||
*/
|
||||
if (message?.id) {
|
||||
await attachJobCallsToMessage({ job_id: job.id, message_id: Number(message.id) });
|
||||
await attachJobTracesToMessage({ job_id: job.id, message_id: Number(message.id) });
|
||||
}
|
||||
|
||||
const user_id = await grabJobUserId({ job });
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
import { Database } from "bun:sqlite";
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import openSessionReplyStepSql from "./open-session-reply-step-sql";
|
||||
|
||||
/**
|
||||
* A conversation that reloads mid-reply reads the step the run is on from
|
||||
* the server. It must be the open reply job's newest tool step, never a
|
||||
* task's (a task brings its own), never a finished job's, never a closing
|
||||
* note (its text is the answer) and never another session's.
|
||||
*/
|
||||
function setup() {
|
||||
const db = new Database(":memory:");
|
||||
|
||||
db.run(
|
||||
`CREATE TABLE bots_queue (id INTEGER PRIMARY KEY, kind TEXT, status TEXT, session_id INTEGER, task_id INTEGER)`,
|
||||
);
|
||||
db.run(
|
||||
`CREATE TABLE bots_queue_updates (id INTEGER PRIMARY KEY, bots_queue_id INTEGER, bot_id INTEGER, kind TEXT, text TEXT, metadata TEXT, created_at INTEGER)`,
|
||||
);
|
||||
|
||||
db.run(`INSERT INTO bots_queue (id, kind, status, session_id, task_id) VALUES
|
||||
(10, 'reply', 'processing', 1, NULL),
|
||||
(11, 'task', 'processing', 1, 50),
|
||||
(12, 'reply', 'completed', 1, NULL),
|
||||
(13, 'reply', 'processing', 2, NULL)`);
|
||||
|
||||
db.run(`INSERT INTO bots_queue_updates (id, bots_queue_id, bot_id, kind, text, metadata, created_at) VALUES
|
||||
(100, 10, 7, 'tool', 'Reading the invoice', NULL, 1000),
|
||||
(101, 10, 7, 'note', 'Here is the invoice', NULL, 1001),
|
||||
(102, 11, 7, 'tool', 'Using sandbox_execute_bash', NULL, 1002),
|
||||
(103, 12, 7, 'tool', 'Read the finished job', NULL, 1003),
|
||||
(104, 13, 7, 'tool', 'Reading another session', NULL, 1004)`);
|
||||
|
||||
return db;
|
||||
}
|
||||
|
||||
describe("openSessionReplyStepSql", () => {
|
||||
test("reads the open reply's newest tool step, with its job's task and session", () => {
|
||||
const db = setup();
|
||||
const { sql, values } = openSessionReplyStepSql({ session_id: 1 });
|
||||
const step = db.query(sql).get(...values) as {
|
||||
id: number;
|
||||
bots_queue_id: number;
|
||||
bot_id: number;
|
||||
kind: string;
|
||||
text: string;
|
||||
task_id: number | null;
|
||||
session_id: number;
|
||||
} | null;
|
||||
|
||||
expect(step?.id).toBe(100);
|
||||
expect(step?.text).toBe("Reading the invoice");
|
||||
expect(step?.bot_id).toBe(7);
|
||||
expect(step?.task_id).toBeNull();
|
||||
expect(step?.session_id).toBe(1);
|
||||
});
|
||||
|
||||
test("a session with no reply running has no step", () => {
|
||||
const db = setup();
|
||||
db.run(`UPDATE bots_queue SET status = 'completed' WHERE id = 10`);
|
||||
|
||||
const { sql, values } = openSessionReplyStepSql({ session_id: 1 });
|
||||
|
||||
expect(db.query(sql).get(...values)).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,26 @@
|
||||
type Params = {
|
||||
session_id: number | string;
|
||||
};
|
||||
|
||||
/**
|
||||
* The newest step of the reply job a session still runs, with the job's
|
||||
* task and session beside it, so a conversation that reloaded (or missed
|
||||
* the step's push) shows what the reply is doing instead of waiting for its
|
||||
* next step. A reply's steps are never stored with the task they belong to
|
||||
* the way a task's are (`grabBotJobUpdates`), so they are read here.
|
||||
*
|
||||
* Only an open job's, only a reply's, and only a tool step: a closing note's
|
||||
* text is the answer, about to land as the message.
|
||||
*/
|
||||
export default function openSessionReplyStepSql({ session_id }: Params) {
|
||||
return {
|
||||
sql: `SELECT u.*, q.task_id AS task_id, q.session_id AS session_id
|
||||
FROM bots_queue_updates u
|
||||
JOIN bots_queue q ON q.id = u.bots_queue_id
|
||||
WHERE q.session_id = ? AND q.kind = 'reply' AND q.status IN ('pending', 'processing')
|
||||
AND u.kind = 'tool' AND u.text IS NOT NULL
|
||||
ORDER BY u.id DESC
|
||||
LIMIT 1`,
|
||||
values: [Number(session_id)],
|
||||
};
|
||||
}
|
||||
@@ -12,6 +12,7 @@ import grabSessionChatroomId from "../chatrooms/grab-session-chatroom-id";
|
||||
import closeChatroom from "../chatrooms/close-chatroom";
|
||||
import grabSessionHookId from "../bot-hooks/grab-session-hook-id";
|
||||
import settleInstallRequest from "../install-requests/settle-install-request";
|
||||
import attachJobTracesToMessage from "./attach-job-traces-to-message";
|
||||
|
||||
type Params = {
|
||||
bot_id: number | string;
|
||||
@@ -150,7 +151,15 @@ export default async function stopBotJobs({ bot_id, user_id }: Params): Promise<
|
||||
text: stoppedJobReport({ job }),
|
||||
}).catch(() => null);
|
||||
|
||||
if (message?.id) messages.push(message);
|
||||
if (message?.id) {
|
||||
messages.push(message);
|
||||
|
||||
/**
|
||||
* The run's debug logs go with the answer that took its place,
|
||||
* the way a finished run's go with its own.
|
||||
*/
|
||||
await attachJobTracesToMessage({ job_id: Number(job.id), message_id: Number(message.id) });
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
import type { BotTraceJob, BotTraceRow } from "@/src/types";
|
||||
|
||||
type JobRow = {
|
||||
id: number;
|
||||
kind: string;
|
||||
title: string | null;
|
||||
status: string;
|
||||
created_at: number;
|
||||
};
|
||||
|
||||
type Params = {
|
||||
/**
|
||||
* The jobs whose trace rows are wanted, in the order they're shown.
|
||||
*/
|
||||
jobs: JobRow[];
|
||||
};
|
||||
|
||||
/**
|
||||
* Each job with every entry it kept, oldest entry first (the order the run
|
||||
* did them in). One read for all of them, so a session's handful of jobs
|
||||
* costs two queries rather than one per job.
|
||||
*/
|
||||
export default async function traceJobsFromRows({ jobs }: Params): Promise<BotTraceJob[]> {
|
||||
if (!jobs.length) return [];
|
||||
|
||||
const traces =
|
||||
(
|
||||
await BunSQLite.sql<BotTraceRow>({
|
||||
sql: `SELECT id, created_at, bots_queue_id AS job_id, bot_id, kind, name, text, reasoning, arguments, result, metadata
|
||||
FROM bot_job_traces
|
||||
WHERE bots_queue_id IN (${jobs.map(() => "?").join(",")})
|
||||
ORDER BY id ASC`,
|
||||
values: jobs.map((job) => job.id),
|
||||
})
|
||||
).payload || [];
|
||||
|
||||
return jobs.map((job) => ({
|
||||
...job,
|
||||
traces: traces.filter((row) => row.job_id == job.id),
|
||||
}));
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
import { beforeEach, describe, expect, test } from "bun:test";
|
||||
import readDebugOpen from "./read-debug-open";
|
||||
import rememberDebugOpen from "./remember-debug-open";
|
||||
|
||||
class MemoryStorage {
|
||||
private store = new Map<string, string>();
|
||||
|
||||
get length() {
|
||||
return this.store.size;
|
||||
}
|
||||
|
||||
key(index: number) {
|
||||
return [...this.store.keys()][index] ?? null;
|
||||
}
|
||||
|
||||
getItem(key: string) {
|
||||
return this.store.get(key) ?? null;
|
||||
}
|
||||
|
||||
setItem(key: string, value: string) {
|
||||
this.store.set(key, value);
|
||||
}
|
||||
|
||||
removeItem(key: string) {
|
||||
this.store.delete(key);
|
||||
}
|
||||
|
||||
clear() {
|
||||
this.store.clear();
|
||||
}
|
||||
}
|
||||
|
||||
let storage: MemoryStorage;
|
||||
|
||||
beforeEach(() => {
|
||||
storage = new MemoryStorage();
|
||||
Object.defineProperty(globalThis, "localStorage", {
|
||||
value: storage as unknown as Storage,
|
||||
configurable: true,
|
||||
});
|
||||
});
|
||||
|
||||
describe("the debug view's remembered state", () => {
|
||||
test("starts closed", () => {
|
||||
expect(readDebugOpen({ user_id: 1 })).toBe(false);
|
||||
});
|
||||
|
||||
test("keeps its state per user, across conversations", () => {
|
||||
rememberDebugOpen({ user_id: 1, open: true });
|
||||
|
||||
expect(readDebugOpen({ user_id: 1 })).toBe(true);
|
||||
expect(readDebugOpen({ user_id: 2 })).toBe(false);
|
||||
});
|
||||
|
||||
test("remembers closing it again", () => {
|
||||
rememberDebugOpen({ user_id: 1, open: true });
|
||||
rememberDebugOpen({ user_id: 1, open: false });
|
||||
|
||||
expect(readDebugOpen({ user_id: 1 })).toBe(false);
|
||||
});
|
||||
|
||||
test("keeps the other users' answers when one changes", () => {
|
||||
rememberDebugOpen({ user_id: 1, open: true });
|
||||
rememberDebugOpen({ user_id: 2, open: true });
|
||||
|
||||
expect(readDebugOpen({ user_id: 1 })).toBe(true);
|
||||
expect(readDebugOpen({ user_id: 2 })).toBe(true);
|
||||
});
|
||||
|
||||
test("a broken stored value reads as closed, and is written over", () => {
|
||||
storage.setItem("cobble_debug_view_open", "not json");
|
||||
|
||||
expect(readDebugOpen({ user_id: 1 })).toBe(false);
|
||||
|
||||
rememberDebugOpen({ user_id: 1, open: true });
|
||||
|
||||
expect(readDebugOpen({ user_id: 1 })).toBe(true);
|
||||
});
|
||||
|
||||
test("keeps working without a user id", () => {
|
||||
rememberDebugOpen({ user_id: null, open: true });
|
||||
|
||||
expect(readDebugOpen({ user_id: null })).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,20 @@
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
|
||||
type Params = {
|
||||
user_id?: number | string | null;
|
||||
};
|
||||
|
||||
/**
|
||||
* Whether this user left the conversation's debug view open on this device
|
||||
* (`rememberDebugOpen`). The view belongs to them, not to a bot, so one
|
||||
* answer covers every conversation.
|
||||
*/
|
||||
export default function readDebugOpen({ user_id }: Params): boolean {
|
||||
try {
|
||||
const stored = JSON.parse(localStorage.getItem(AppData["DebugViewStorageKey"]) || "{}");
|
||||
|
||||
return Boolean(stored?.[String(user_id ?? "user")]);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
|
||||
type Params = {
|
||||
user_id?: number | string | null;
|
||||
open: boolean;
|
||||
};
|
||||
|
||||
type States = Record<string, boolean>;
|
||||
|
||||
/**
|
||||
* The answers stored so far. A value written by an older version (or
|
||||
* anything else in its place) reads as none, so the next save replaces it
|
||||
* rather than failing.
|
||||
*/
|
||||
function readStates(key: string): States {
|
||||
try {
|
||||
const stored = JSON.parse(localStorage.getItem(key) || "{}");
|
||||
|
||||
return stored && typeof stored == "object" && !Array.isArray(stored) ? stored : {};
|
||||
} catch {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Records whether this user keeps the conversation's debug view open on
|
||||
* this device, so the next conversation and the next visit start where
|
||||
* they left off (`readDebugOpen`). Best effort.
|
||||
*/
|
||||
export default function rememberDebugOpen({ user_id, open }: Params) {
|
||||
try {
|
||||
const key = AppData["DebugViewStorageKey"];
|
||||
const states = readStates(key);
|
||||
const id = String(user_id ?? "user");
|
||||
|
||||
if (Boolean(states[id]) == open) return;
|
||||
|
||||
states[id] = open;
|
||||
localStorage.setItem(key, JSON.stringify(states));
|
||||
} catch {}
|
||||
}
|
||||
@@ -38,6 +38,7 @@ describe("readChatResponse", () => {
|
||||
}),
|
||||
).toEqual({
|
||||
text: "Checking.",
|
||||
reasoning: null,
|
||||
tool_calls: [
|
||||
{
|
||||
id: "a1",
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import HarnessError from "../../harness-error";
|
||||
import type { HarnessChatResult, HarnessToolCall } from "../../types";
|
||||
import readReasoning from "./read-reasoning";
|
||||
|
||||
type WireToolCall = {
|
||||
id?: string;
|
||||
@@ -74,6 +75,13 @@ export default function readChatResponse({
|
||||
text: text || null,
|
||||
tool_calls,
|
||||
finish_reason: choice.finish_reason || undefined,
|
||||
/**
|
||||
* A reasoning model's own text, when the provider hands it back:
|
||||
* `reasoning` (OpenRouter), `reasoning_content` (DeepSeek and
|
||||
* others). Only the debug view shows it (`stripThinkTags` picks up
|
||||
* what a model writes inline instead).
|
||||
*/
|
||||
reasoning: readReasoning({ message: choice.message }),
|
||||
usage: json.usage
|
||||
? {
|
||||
prompt_tokens: json.usage.prompt_tokens,
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import readReasoning from "./read-reasoning";
|
||||
|
||||
describe("readReasoning", () => {
|
||||
test("reads the reason OpenRouter hands back", () => {
|
||||
expect(readReasoning({ message: { reasoning: "They want a report." } })).toBe(
|
||||
"They want a report.",
|
||||
);
|
||||
});
|
||||
|
||||
test("reads DeepSeek's spelling too", () => {
|
||||
expect(readReasoning({ message: { reasoning_content: " Two plus two. " } })).toBe(
|
||||
"Two plus two.",
|
||||
);
|
||||
});
|
||||
|
||||
test("joins a reason given as parts", () => {
|
||||
expect(
|
||||
readReasoning({
|
||||
message: { reasoning: [{ text: "First. " }, { text: "Then the answer." }] },
|
||||
}),
|
||||
).toBe("First. Then the answer.");
|
||||
});
|
||||
|
||||
test("falls back to the readable details", () => {
|
||||
expect(
|
||||
readReasoning({
|
||||
message: {
|
||||
reasoning_details: [
|
||||
{ type: "reasoning.encrypted", data: "gibberish" },
|
||||
{ type: "reasoning.summary", summary: "Checked the numbers." },
|
||||
],
|
||||
},
|
||||
}),
|
||||
).toBe("Checked the numbers.");
|
||||
});
|
||||
|
||||
test("is null when there's nothing readable", () => {
|
||||
expect(readReasoning({ message: {} })).toBeNull();
|
||||
expect(readReasoning({ message: { reasoning: " " } })).toBeNull();
|
||||
expect(readReasoning({ message: { reasoning_details: [{ data: "x" }] } })).toBeNull();
|
||||
expect(readReasoning({ message: null })).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,39 @@
|
||||
type Params = {
|
||||
/**
|
||||
* A chat completion's `message`.
|
||||
*/
|
||||
message: any;
|
||||
};
|
||||
|
||||
/**
|
||||
* What a reasoning model thought before it answered, when its provider
|
||||
* hands it back. The spellings in the wild: `reasoning` (OpenRouter, as a
|
||||
* string or a list of parts), `reasoning_content` (DeepSeek and the
|
||||
* providers that copied it), and `reasoning_details` (OpenRouter's list of
|
||||
* encrypted or summarised details, whose `text` or `summary` is readable).
|
||||
* Null when there's nothing readable.
|
||||
*/
|
||||
export default function readReasoning({ message }: Params): string | null {
|
||||
const candidates: unknown[] = [message?.reasoning, message?.reasoning_content];
|
||||
|
||||
if (Array.isArray(message?.reasoning_details)) {
|
||||
for (const detail of message.reasoning_details) candidates.push(detail?.text, detail?.summary);
|
||||
}
|
||||
|
||||
for (const candidate of candidates) {
|
||||
const text =
|
||||
typeof candidate == "string"
|
||||
? candidate
|
||||
: Array.isArray(candidate)
|
||||
? candidate
|
||||
.map((part: any) =>
|
||||
typeof part == "string" ? part : typeof part?.text == "string" ? part.text : "",
|
||||
)
|
||||
.join("")
|
||||
: "";
|
||||
|
||||
if (text.trim()) return text.trim();
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
@@ -140,9 +140,11 @@ export default async function generateText({
|
||||
signal,
|
||||
});
|
||||
|
||||
const text = answer.text ? stripThinkTags({ text: answer.text }) : "";
|
||||
const stripped = answer.text
|
||||
? stripThinkTags({ text: answer.text })
|
||||
: { text: "", reasoning: null };
|
||||
|
||||
if (!text && !answer.tool_calls.length) {
|
||||
if (!stripped.text && !answer.tool_calls.length) {
|
||||
throw new HarnessError({
|
||||
message: `The model returned an empty answer.`,
|
||||
retryable: true,
|
||||
@@ -150,7 +152,14 @@ export default async function generateText({
|
||||
});
|
||||
}
|
||||
|
||||
return { ...answer, text: text || null, sent_params };
|
||||
/**
|
||||
* Reasoning is kept only for the debug view: what the model
|
||||
* wrote inline wins over a provider's own field, since models
|
||||
* that write tags rarely send both.
|
||||
*/
|
||||
const reasoning = stripped.reasoning || answer.reasoning || null;
|
||||
|
||||
return { ...answer, text: stripped.text || null, reasoning, sent_params };
|
||||
},
|
||||
});
|
||||
|
||||
|
||||
@@ -5,6 +5,7 @@ import { UnlimitedLimit } from "@/src/utils/run-limit";
|
||||
import { alreadyRanToolNote, DroppedToolImageNote, SupersededSnapshotNote, ToolImagesNote } from "@/src/data/harness-prompts";
|
||||
import HarnessError from "../harness-error";
|
||||
import type { HarnessCandidate, HarnessTool } from "../types";
|
||||
import type { HarnessTrace } from "../trace/types";
|
||||
import type { GenerateTextParams, GenerateTextResult } from "./generate-text";
|
||||
import runTextLoop, {
|
||||
IncomingMessagesNote,
|
||||
@@ -985,4 +986,114 @@ describe("runTextLoop repeated reads", () => {
|
||||
|
||||
expect(counts.reads).toBe(2);
|
||||
});
|
||||
|
||||
test("traces a read it skipped as the step that answered it", async () => {
|
||||
const { tools, counts } = makeTools();
|
||||
const turns = [
|
||||
{
|
||||
text: null,
|
||||
tool_calls: [
|
||||
readCall({ id: "c1", path: "a.md" }),
|
||||
readCall({ id: "c2", path: "a.md" }),
|
||||
],
|
||||
},
|
||||
{ text: "Done.", tool_calls: [] },
|
||||
];
|
||||
const { generate } = scripted(turns);
|
||||
const traces: HarnessTrace[] = [];
|
||||
|
||||
await runTextLoop({
|
||||
system: "You are a bot.",
|
||||
messages: [{ role: "user", content: "Read a.md twice." }],
|
||||
tools,
|
||||
generate,
|
||||
resolveCandidates,
|
||||
trace: (entry) => {
|
||||
traces.push(entry);
|
||||
},
|
||||
});
|
||||
|
||||
expect(counts.reads).toBe(1);
|
||||
|
||||
const calls = traces.filter((entry) => entry.kind == "tool");
|
||||
|
||||
expect(calls).toHaveLength(2);
|
||||
expect(calls[1]).toMatchObject({ repeat_of: 0, duration_ms: 0 });
|
||||
});
|
||||
});
|
||||
|
||||
describe("runTextLoop trace", () => {
|
||||
test("keeps what it did as a trace: turns, tool calls and its own events", async () => {
|
||||
const { generate } = scripted([
|
||||
{
|
||||
text: "Noting that.",
|
||||
reasoning: "They told me what they drink.",
|
||||
tool_calls: [
|
||||
{ id: "c1", name: "remember", arguments: `{"note":"tea"}` },
|
||||
],
|
||||
usage: { prompt_tokens: 10, completion_tokens: 3 },
|
||||
finish_reason: "tool_calls",
|
||||
},
|
||||
{ text: "I'll remember you like tea.", finish_reason: "stop" },
|
||||
]);
|
||||
const traces: HarnessTrace[] = [];
|
||||
|
||||
const result = await runTextLoop({
|
||||
system: "You are a bot.",
|
||||
messages: [{ role: "user", content: "I like tea." }],
|
||||
tools: [remember],
|
||||
generate,
|
||||
resolveCandidates,
|
||||
trace: (entry) => {
|
||||
traces.push(entry);
|
||||
},
|
||||
});
|
||||
|
||||
expect(result.text).toBe("I'll remember you like tea.");
|
||||
expect(traces.map((entry) => entry.kind)).toEqual(["turn", "tool", "turn"]);
|
||||
expect(traces[0]).toMatchObject({
|
||||
kind: "turn",
|
||||
index: 0,
|
||||
text: "Noting that.",
|
||||
reasoning: "They told me what they drink.",
|
||||
model: "m",
|
||||
provider: null,
|
||||
tool_calls: [{ name: "remember", arguments: `{"note":"tea"}` }],
|
||||
usage: { prompt_tokens: 10, completion_tokens: 3 },
|
||||
finish_reason: "tool_calls",
|
||||
});
|
||||
expect(traces[1]).toMatchObject({
|
||||
kind: "tool",
|
||||
index: 0,
|
||||
name: "remember",
|
||||
arguments: `{"note":"tea"}`,
|
||||
result: "Saved.",
|
||||
ok: true,
|
||||
images: 0,
|
||||
repeat_of: null,
|
||||
});
|
||||
expect((traces[1] as { duration_ms: number }).duration_ms).toBeGreaterThanOrEqual(0);
|
||||
expect(traces[2]).toMatchObject({
|
||||
kind: "turn",
|
||||
index: 1,
|
||||
text: "I'll remember you like tea.",
|
||||
finish_reason: "stop",
|
||||
});
|
||||
});
|
||||
|
||||
test("a trace that can't be kept never fails the run", async () => {
|
||||
const { generate } = scripted([{ text: "Done." }]);
|
||||
|
||||
const result = await runTextLoop({
|
||||
system: "You are a bot.",
|
||||
messages: [{ role: "user", content: "Hello." }],
|
||||
generate,
|
||||
resolveCandidates,
|
||||
trace: () => {
|
||||
throw new Error("The database is full.");
|
||||
},
|
||||
});
|
||||
|
||||
expect(result.text).toBe("Done.");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -6,7 +6,9 @@ import resolveHarnessCandidates from "../resolve/resolve-harness-candidates";
|
||||
import loadToolsTool from "../tools/load-tools-tool";
|
||||
import repeatToolCallKey from "../tools/repeat-tool-call-key";
|
||||
import runToolCall from "../tools/run-tool-call";
|
||||
import type { ToolCallResult } from "../tools/run-tool-call";
|
||||
import toolDefinition from "../tools/tool-definition";
|
||||
import type { HarnessTrace, HarnessTracer } from "../trace/types";
|
||||
import type {
|
||||
HarnessCandidate,
|
||||
HarnessMessage,
|
||||
@@ -66,6 +68,14 @@ type Params = {
|
||||
* progress and checkpoints.
|
||||
*/
|
||||
onStep?: (step: TextLoopStep) => Promise<void> | void;
|
||||
/**
|
||||
* Where the run's detailed trace goes (`bot_job_traces`, the
|
||||
* conversation's debug view): every turn with what the model reasoned,
|
||||
* every tool call with its arguments and answer, and what the loop
|
||||
* itself did. Best effort: a trace that can't be kept never fails the
|
||||
* run.
|
||||
*/
|
||||
trace?: HarnessTracer;
|
||||
/**
|
||||
* The user's turns that arrived since the run started (and since the
|
||||
* last call), read after each round of tools and before an answer is
|
||||
@@ -261,6 +271,7 @@ export default async function runTextLoop({
|
||||
context_budget,
|
||||
signal = new AbortController().signal,
|
||||
onStep,
|
||||
trace,
|
||||
incoming,
|
||||
incoming_notes,
|
||||
review,
|
||||
@@ -361,6 +372,20 @@ export default async function runTextLoop({
|
||||
*/
|
||||
let used_wrap_turn = false;
|
||||
|
||||
/**
|
||||
* One trace entry, kept only when the run has somewhere to put it. A
|
||||
* trace is for reading afterwards, never a reason to fail the work.
|
||||
*/
|
||||
const traced = async (entry: HarnessTrace) => {
|
||||
if (!trace) return;
|
||||
|
||||
try {
|
||||
await trace(entry);
|
||||
} catch {
|
||||
/* the debug view is never worth a failed run */
|
||||
}
|
||||
};
|
||||
|
||||
for (let index = 0; index <= step_ceiling + 1 + WrapUpSavingTurns; index++) {
|
||||
if (signal.aborted) {
|
||||
throw new HarnessError({ message: `Cancelled.`, code: "aborted" });
|
||||
@@ -384,7 +409,7 @@ export default async function runTextLoop({
|
||||
if (wrap_up && !wrap_up_announced) {
|
||||
wrap_up_announced = true;
|
||||
|
||||
if (incoming_notes?.wrap_up) await takeIncoming({ note: incoming_notes.wrap_up });
|
||||
if (incoming_notes?.wrap_up) await takeIncoming({ note: incoming_notes.wrap_up, index });
|
||||
|
||||
pushUserTurn({
|
||||
transcript,
|
||||
@@ -395,6 +420,13 @@ export default async function runTextLoop({
|
||||
hand_off: wrap_up_saving ? hand_off_tools.map((tool) => tool.name) : [],
|
||||
}),
|
||||
});
|
||||
|
||||
await traced({
|
||||
kind: "event",
|
||||
index,
|
||||
name: "wrap_up",
|
||||
text: `${out_of_steps ? "Out of steps" : "Out of tokens"}. ${wrap_tools.length ? `It has one turn left with ${wrap_tools.map((tool) => tool.name).join(", ")}.` : "It has no tool left and must answer now."}`,
|
||||
});
|
||||
}
|
||||
|
||||
if (wrap_up_saving) saving_turns++;
|
||||
@@ -415,6 +447,8 @@ export default async function runTextLoop({
|
||||
tools_chars: JSON.stringify(definitions).length,
|
||||
});
|
||||
|
||||
const turn_started_at = Date.now();
|
||||
|
||||
const answer = await generate({
|
||||
messages: [{ role: "system", content: run_system }, ...transcript],
|
||||
tools: definitions.length ? definitions : undefined,
|
||||
@@ -466,11 +500,34 @@ export default async function runTextLoop({
|
||||
candidate: answer.candidate,
|
||||
});
|
||||
|
||||
await traced({
|
||||
kind: "turn",
|
||||
index,
|
||||
model: answer.candidate.model.name || answer.candidate.model.slug,
|
||||
provider: answer.candidate.provider.name || null,
|
||||
text: answer.text,
|
||||
reasoning: answer.reasoning ?? null,
|
||||
tool_calls: tool_calls.map((call) => ({ name: call.name, arguments: call.arguments })),
|
||||
usage: answer.usage ?? null,
|
||||
finish_reason: answer.finish_reason ?? null,
|
||||
duration_ms: Date.now() - turn_started_at,
|
||||
});
|
||||
|
||||
/**
|
||||
* An answer the user wrote past is drafted again. Not on the wrap
|
||||
* up: the run is out of steps, and a later reply picks them up.
|
||||
*/
|
||||
if (!tool_calls.length && !wrap_up && (await takeIncoming({ note: incoming_notes?.redraft || RedraftNote }))) {
|
||||
if (
|
||||
!tool_calls.length &&
|
||||
!wrap_up &&
|
||||
(await takeIncoming({ note: incoming_notes?.redraft || RedraftNote, index }))
|
||||
) {
|
||||
await traced({
|
||||
kind: "event",
|
||||
index,
|
||||
name: "redraft",
|
||||
text: "The user wrote again before this answer went out, so it was written again with that in mind.",
|
||||
});
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -480,6 +537,7 @@ export default async function runTextLoop({
|
||||
const note = await review({ text: answer.text || "", tool_uses }).catch(() => null);
|
||||
|
||||
if (note) {
|
||||
await traced({ kind: "event", index, name: "review", text: note });
|
||||
pushUserTurn({ transcript, content: note });
|
||||
continue;
|
||||
}
|
||||
@@ -506,11 +564,17 @@ export default async function runTextLoop({
|
||||
const repeat_key = repeatToolCallKey({ call });
|
||||
const already_read = repeat_key ? repeated_reads.get(repeat_key) : undefined;
|
||||
|
||||
const { text: content, images } =
|
||||
const result: ToolCallResult =
|
||||
already_read !== undefined
|
||||
? { text: alreadyRanToolNote({ name: call.name, step: already_read }), images: [] }
|
||||
? {
|
||||
text: alreadyRanToolNote({ name: call.name, step: already_read }),
|
||||
images: [],
|
||||
duration_ms: 0,
|
||||
}
|
||||
: await runToolCall({ call, tools: run_tools, signal });
|
||||
|
||||
const { text: content, images } = result;
|
||||
|
||||
/**
|
||||
* A deferred tool called without loading it ran all the same;
|
||||
* it stays loaded from here on.
|
||||
@@ -521,6 +585,18 @@ export default async function runTextLoop({
|
||||
|
||||
tool_uses.push({ name: call.name, ok: !content.startsWith("Error:") });
|
||||
|
||||
await traced({
|
||||
kind: "tool",
|
||||
index,
|
||||
name: call.name,
|
||||
arguments: call.arguments,
|
||||
result: content,
|
||||
ok: !content.startsWith("Error:"),
|
||||
images: images.length,
|
||||
duration_ms: result.duration_ms,
|
||||
repeat_of: already_read ?? null,
|
||||
});
|
||||
|
||||
if (!repeat_key) {
|
||||
repeated_reads.clear();
|
||||
} else if (already_read === undefined) {
|
||||
@@ -550,7 +626,7 @@ export default async function runTextLoop({
|
||||
});
|
||||
}
|
||||
|
||||
await takeIncoming({ note: incoming_notes?.working || IncomingMessagesNote });
|
||||
await takeIncoming({ note: incoming_notes?.working || IncomingMessagesNote, index });
|
||||
|
||||
/**
|
||||
* Steps left before the wrap up, once the next turn is taken.
|
||||
@@ -562,6 +638,7 @@ export default async function runTextLoop({
|
||||
if (!warned_steps && !isUnlimitedLimit(max_steps) && left <= warn_at) {
|
||||
warned_steps = true;
|
||||
pushUserTurn({ transcript, content: stepsLowNote({ left }) });
|
||||
await traced({ kind: "event", index, name: "steps_low", text: stepsLowNote({ left }) });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -571,7 +648,7 @@ export default async function runTextLoop({
|
||||
* Adds what the user wrote since the last look, after `note`. True when
|
||||
* there was anything.
|
||||
*/
|
||||
async function takeIncoming({ note }: { note: string }) {
|
||||
async function takeIncoming({ note, index }: { note: string; index: number }) {
|
||||
const turns = (await incoming?.()) || [];
|
||||
const user_turns = turns.filter((turn) => turn.role == "user");
|
||||
|
||||
@@ -583,6 +660,16 @@ export default async function runTextLoop({
|
||||
pushUserTurn({ transcript, content: turn.content });
|
||||
}
|
||||
|
||||
await traced({
|
||||
kind: "event",
|
||||
index,
|
||||
name: "incoming",
|
||||
text: user_turns
|
||||
.map((turn) => (typeof turn.content == "string" ? turn.content : ""))
|
||||
.filter(Boolean)
|
||||
.join("\n\n"),
|
||||
});
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,19 +3,26 @@ import stripThinkTags from "./strip-think-tags";
|
||||
|
||||
describe("stripThinkTags", () => {
|
||||
test("removes reasoning blocks", () => {
|
||||
expect(
|
||||
stripThinkTags({ text: "<think>plan\nmore</think>\n\nDone." }),
|
||||
).toBe("Done.");
|
||||
expect(
|
||||
stripThinkTags({ text: "A <THINK>x</THINK>B <think>y</think>C" }),
|
||||
).toBe("A B C");
|
||||
expect(stripThinkTags({ text: "\u003cthink\u003eplan\nmore\u003c/think\u003e\n\nDone." }).text).toBe("Done.");
|
||||
expect(stripThinkTags({ text: "A \u003cTHINK\u003ex\u003c/THINK\u003eB" }).text).toBe("A B");
|
||||
});
|
||||
|
||||
test("drops an unclosed block at the start", () => {
|
||||
expect(stripThinkTags({ text: "<think>never ends" })).toBe("");
|
||||
test("keeps what was reasoned, in order", () => {
|
||||
expect(
|
||||
stripThinkTags({ text: "\u003cthink\u003efirst\u003c/think\u003ea \u003cthink\u003esecond\u003c/think\u003eb" }).reasoning,
|
||||
).toBe("first\n\nsecond");
|
||||
expect(stripThinkTags({ text: "\u003cTHINK\u003ex\u003c/THINK\u003eB" }).reasoning).toBe("x");
|
||||
expect(stripThinkTags({ text: "no reasoning here" }).reasoning).toBe(null);
|
||||
});
|
||||
|
||||
test("drops an unclosed block at the start, keeping it as reasoning", () => {
|
||||
expect(stripThinkTags({ text: " \u003cthink\u003enever ends" })).toEqual({
|
||||
text: "",
|
||||
reasoning: "never ends",
|
||||
});
|
||||
});
|
||||
|
||||
test("leaves plain text alone", () => {
|
||||
expect(stripThinkTags({ text: " Hello " })).toBe("Hello");
|
||||
expect(stripThinkTags({ text: " Hello " })).toEqual({ text: "Hello", reasoning: null });
|
||||
});
|
||||
});
|
||||
|
||||
@@ -3,12 +3,30 @@ type Params = {
|
||||
};
|
||||
|
||||
/**
|
||||
* Removes the `<think>...</think>` reasoning some models write into their
|
||||
* answer, including an unclosed one at the start.
|
||||
* Splits a model's answer from the ` thinking...` reasoning some
|
||||
* models write into it, including an unclosed one at the start. The answer
|
||||
* is what the bot says; the reasoning goes only to the debug view.
|
||||
*/
|
||||
export default function stripThinkTags({ text }: Params) {
|
||||
return text
|
||||
.replace(/<think>[\s\S]*?<\/think>/gi, "")
|
||||
.replace(/^\s*<think>[\s\S]*$/i, "")
|
||||
export default function stripThinkTags({ text }: Params): { text: string; reasoning: string | null } {
|
||||
const thoughts: string[] = [];
|
||||
|
||||
let answer = text.replace(/<think[^>]*>([\s\S]*?)<\/think>/gi, (_block: string, reason: string) => {
|
||||
thoughts.push(reason);
|
||||
return "";
|
||||
});
|
||||
|
||||
const unclosed = /^\s*<think[^>]*>([\s\S]*)$/i.exec(answer);
|
||||
|
||||
if (unclosed) {
|
||||
thoughts.push(unclosed[1] || "");
|
||||
answer = answer.slice(0, unclosed.index);
|
||||
}
|
||||
|
||||
const reasoning = thoughts
|
||||
.map((thought) => thought.trim())
|
||||
.filter(Boolean)
|
||||
.join("\n\n")
|
||||
.trim();
|
||||
}
|
||||
|
||||
return { text: answer.trim(), reasoning: reasoning || null };
|
||||
}
|
||||
@@ -35,7 +35,14 @@ type Args = {
|
||||
* the answers come back as the user's next message. Once per run, so every
|
||||
* question goes on one card.
|
||||
*/
|
||||
export default function askUserTool({ user_id, bot_id, session_id, workspace_id, in_task, onAsk }: Params): HarnessTool<Args> {
|
||||
export default function askUserTool({
|
||||
user_id,
|
||||
bot_id,
|
||||
session_id,
|
||||
workspace_id,
|
||||
in_task,
|
||||
onAsk,
|
||||
}: Params): HarnessTool<Args> {
|
||||
let asked = false;
|
||||
|
||||
return {
|
||||
@@ -46,12 +53,23 @@ export default function askUserTool({ user_id, bot_id, session_id, workspace_id,
|
||||
: `: after asking, end your reply and wait; don't act on what you asked about until they answer.`
|
||||
}`,
|
||||
schema: z.object({
|
||||
title: z.string().trim().max(120).optional().describe("A short heading for the card, e.g. \"Before I deploy\""),
|
||||
questions: BotQuestionItemsSchema.describe("The questions, in the order to answer them"),
|
||||
title: z
|
||||
.string()
|
||||
.trim()
|
||||
.max(120)
|
||||
.optional()
|
||||
.describe(
|
||||
'A short heading for the card, e.g. "Before I deploy"',
|
||||
),
|
||||
questions: BotQuestionItemsSchema.describe(
|
||||
"The questions, in the order to answer them",
|
||||
),
|
||||
}),
|
||||
run: async ({ args }) => {
|
||||
if (asked) {
|
||||
throw new Error(`You already asked the user in this run. Put every question in one ask_user call, then wait for their answers.`);
|
||||
throw new Error(
|
||||
`You already asked the user in this run. Put every question in one ask_user call, then wait for their answers.`,
|
||||
);
|
||||
}
|
||||
|
||||
const id = await createBotQuestion({
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import commandTimeoutSeconds from "./command-timeout";
|
||||
|
||||
describe("commandTimeoutSeconds", () => {
|
||||
test("has no limit when nothing is asked and the install sets none", () => {
|
||||
expect(commandTimeoutSeconds({ max: 0 })).toBeNull();
|
||||
});
|
||||
|
||||
test("a bot's own timeout still applies with no install limit", () => {
|
||||
expect(commandTimeoutSeconds({ asked: 3600, max: 0 })).toBe(3600);
|
||||
});
|
||||
|
||||
test("rounds a bot's timeout up to whole seconds, at least one", () => {
|
||||
expect(commandTimeoutSeconds({ asked: 0.2, max: 0 })).toBe(1);
|
||||
expect(commandTimeoutSeconds({ asked: 12.1, max: 0 })).toBe(13);
|
||||
});
|
||||
|
||||
test("an install limit applies when the bot names none", () => {
|
||||
expect(commandTimeoutSeconds({ max: 270 })).toBe(270);
|
||||
});
|
||||
|
||||
test("an install limit caps what the bot asks for", () => {
|
||||
expect(commandTimeoutSeconds({ asked: 600, max: 270 })).toBe(270);
|
||||
expect(commandTimeoutSeconds({ asked: 60, max: 270 })).toBe(60);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,13 @@
|
||||
/**
|
||||
* How long a `computer_bash` call may run: the bot's own `timeout` when it
|
||||
* names one, else the install's limit (`AppData.ComputerCommandMaxSeconds`,
|
||||
* 0 for none). `null` means the command runs until it ends, the run is
|
||||
* stopped or its job ends.
|
||||
*/
|
||||
export default function commandTimeoutSeconds({ asked, max }: { asked?: number; max: number }): number | null {
|
||||
const asked_seconds = asked ? Math.max(1, Math.ceil(asked)) : null;
|
||||
|
||||
if (max <= 0) return asked_seconds;
|
||||
|
||||
return asked_seconds == null ? max : Math.min(max, asked_seconds);
|
||||
}
|
||||
@@ -6,6 +6,7 @@ import shellQuote from "@/src/utils/shell-quote";
|
||||
import type { HarnessTool } from "../../types";
|
||||
import computerWorkerAccount from "@/src/utils/computer-worker-account";
|
||||
import capToolOutput from "./cap-tool-output";
|
||||
import commandTimeoutSeconds from "./command-timeout";
|
||||
import computerDirsShell from "./computer-dirs-shell";
|
||||
import type { ComputerToolContext } from "./computer-tool-context";
|
||||
import { computerWorkspaceFullWarning } from "./computer-workspace-room";
|
||||
@@ -19,13 +20,18 @@ type Args = {
|
||||
/**
|
||||
* A bash command on the run's computer, from the run's folder (its
|
||||
* `HOME`), with the computer's envs loaded, as the worker's own account
|
||||
* (no sudo) or, for the coordinator, the computer's user (with sudo). Each call is its own shell,
|
||||
* stopped on the computer at its timeout (at most
|
||||
* `AppData.ComputerCommandMaxSeconds`) or when the run is stopped, so a
|
||||
* command that never ends can't block the computer.
|
||||
* (no sudo) or, for the coordinator, the computer's user (with sudo).
|
||||
* Each call is its own shell with no time limit of its own: it runs until
|
||||
* the command ends, the run is stopped, or it reaches the `timeout` the
|
||||
* bot named (`commandTimeoutSeconds`, capped by
|
||||
* `AppData.ComputerCommandMaxSeconds` when that is set), so a long script
|
||||
* is never cut short and nothing is left blocking the computer.
|
||||
*/
|
||||
export default function computerBashTool({ computer, dirs, shell_path, redact }: ComputerToolContext): HarnessTool<Args> {
|
||||
const max = AppData.ComputerCommandMaxSeconds;
|
||||
const timeout_note = max > 0
|
||||
? `Seconds before it is stopped, at most ${max} (${max} when left out).`
|
||||
: "Seconds before it is stopped. Left out, it has no time limit.";
|
||||
|
||||
return {
|
||||
name: "computer_bash",
|
||||
@@ -33,15 +39,20 @@ export default function computerBashTool({ computer, dirs, shell_path, redact }:
|
||||
dirs.run_as
|
||||
? `as your own account ${computerWorkerAccount({ bot_id: dirs.run_as.bot_id }).name}, without sudo: other bots' folders and the computer's own services are closed to you. Install Python and Node packages into your folder yourself (pip install --user ..., npm install -g ...: both land in ~/.local, on your PATH); for a system package (apt) or anything else that needs root, ask with request_install`
|
||||
: `as the user gem, with passwordless sudo: install what you need with sudo apt-get update && sudo apt-get install -y ..., or pip install. Worker bots' folders belong to their own accounts, so read or change them with sudo`
|
||||
}). It starts in your folder (${dirs.cwd}, also ~ and $HOME) with your envs set. Every call is a fresh shell (cd and export don't carry over), reads no input (anything waiting for a prompt fails at once: pass -y, a password through its env, and so on) and is stopped after timeout seconds (at most ${max}, ${max} when not given). Start longer work in the background (nohup ... > log 2>&1 &) and check its log in later calls. Output past ${Math.round(AppData.ComputerCommandMaxOutputChars / 1000)}k characters is cut in the middle, so filter it.`,
|
||||
}). It starts in your folder (${dirs.cwd}, also ~ and $HOME) with your envs set. Every call is a fresh shell (cd and export don't carry over), reads no input (anything waiting for a prompt fails at once: pass -y, a password through its env, and so on) and has no time limit${max > 0 ? ` unless you pass timeout seconds (at most ${max})` : ""}: it runs until the command ends, you stop it, or the run ends. Work that must outlive the run goes in the background (nohup ... > log 2>&1 &), checked in later calls. Output past ${Math.round(AppData.ComputerCommandMaxOutputChars / 1000)}k characters is cut in the middle, so filter it.`,
|
||||
/**
|
||||
* The command's own limit is what ends it: the harness's per-tool
|
||||
* deadline would cut a long script at 10 minutes.
|
||||
*/
|
||||
timeout_ms: null,
|
||||
schema: z.object({
|
||||
command: z.string().min(1).max(100_000),
|
||||
cwd: z.string().max(AppData.BotFilePathMaxChars).optional().describe("Where to start, inside your folders"),
|
||||
timeout: z.number().positive().optional().describe(`Seconds, at most ${max}`),
|
||||
timeout: z.number().positive().optional().describe(timeout_note),
|
||||
}),
|
||||
run: async ({ args, signal }) => {
|
||||
const cwd = args.cwd ? resolveComputerPath({ path: args.cwd, dirs }) : null;
|
||||
const seconds = Math.min(max, Math.max(1, Math.ceil(args.timeout || max)));
|
||||
const seconds = commandTimeoutSeconds({ asked: args.timeout, max });
|
||||
|
||||
const result = await runComputerCommand({
|
||||
computer,
|
||||
@@ -51,7 +62,7 @@ export default function computerBashTool({ computer, dirs, shell_path, redact }:
|
||||
cwd ? `cd ${shellQuote({ text: cwd })} && ` : "",
|
||||
args.command,
|
||||
].join(""),
|
||||
timeout_ms: seconds * 1000,
|
||||
timeout_ms: seconds == null ? null : seconds * 1000,
|
||||
run_as: dirs.run_as,
|
||||
signal,
|
||||
});
|
||||
@@ -68,7 +79,7 @@ export default function computerBashTool({ computer, dirs, shell_path, redact }:
|
||||
return [
|
||||
`Exit code: ${result.exit_code ?? "unknown"}`,
|
||||
output || "(no output)",
|
||||
result.timed_out ? `[Stopped after ${seconds}s: the command timed out. Run long work in the background and check its log.]` : "",
|
||||
result.timed_out ? `[Stopped after ${seconds ?? 0}s: the command timed out. Run long work in the background and check its log.]` : "",
|
||||
result.truncated ? `[The computer kept only the first part of a very long output.]` : "",
|
||||
full || "",
|
||||
]
|
||||
|
||||
@@ -6,6 +6,7 @@ import withTimeout from "@/src/utils/with-timeout";
|
||||
import HarnessError from "../harness-error";
|
||||
import unknownToolArgs from "./unknown-tool-args";
|
||||
import unknownToolMessage from "./unknown-tool-message";
|
||||
import toolTimeoutMs from "./tool-timeout-ms";
|
||||
import type { HarnessTool, HarnessToolCall, HarnessToolImage } from "../types";
|
||||
|
||||
/**
|
||||
@@ -29,6 +30,10 @@ export type ToolCallResult = {
|
||||
* marked `from_tool`, for the turn after the tool results.
|
||||
*/
|
||||
images: HarnessToolImage[];
|
||||
/**
|
||||
* How long the call took, for the debug view's trace.
|
||||
*/
|
||||
duration_ms: number;
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -37,15 +42,18 @@ export type ToolCallResult = {
|
||||
* can correct itself; only cancellation is thrown.
|
||||
*/
|
||||
export default async function runToolCall({ call, tools, signal }: Params): Promise<ToolCallResult> {
|
||||
const started_at = Date.now();
|
||||
const text = await runTool({ call, tools, signal });
|
||||
const duration_ms = Date.now() - started_at;
|
||||
|
||||
if (typeof text == "string") return { text, images: [] };
|
||||
if (typeof text == "string") return { text, images: [], duration_ms };
|
||||
|
||||
return {
|
||||
text: truncate({ text: text.text, name: call.name }),
|
||||
images: text.images
|
||||
.slice(0, AppData.HarnessToolMaxImages)
|
||||
.map((image) => ({ ...image, from_tool: true })),
|
||||
duration_ms,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -81,16 +89,22 @@ async function runTool({ call, tools, signal }: Params) {
|
||||
}
|
||||
|
||||
try {
|
||||
const output = await withTimeout({
|
||||
timeout_ms: AppData.HarnessToolTimeoutMs,
|
||||
signal,
|
||||
message: `${call.name} took too long and was stopped.`,
|
||||
task: (tool_signal) =>
|
||||
tool.run({
|
||||
args: parsed ? parsed.data : raw,
|
||||
signal: tool_signal,
|
||||
}),
|
||||
});
|
||||
const args = parsed ? parsed.data : raw;
|
||||
const timeout_ms = toolTimeoutMs({ tool });
|
||||
|
||||
/**
|
||||
* A tool with no deadline (`computer_bash`) runs until it ends, the
|
||||
* run is stopped or its job ends: the caller's signal alone cancels
|
||||
* it, so a long command isn't cut at a tool's own limit.
|
||||
*/
|
||||
const output = timeout_ms == null
|
||||
? await tool.run({ args, signal })
|
||||
: await withTimeout({
|
||||
timeout_ms,
|
||||
signal,
|
||||
message: `${call.name} took too long and was stopped.`,
|
||||
task: (tool_signal) => tool.run({ args, signal: tool_signal }),
|
||||
});
|
||||
|
||||
return typeof output == "string" ? truncate({ text: output, name: call.name }) : output;
|
||||
} catch (error: unknown) {
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
import toolTimeoutMs from "./tool-timeout-ms";
|
||||
import type { HarnessTool } from "../types";
|
||||
|
||||
function tool({ timeout_ms }: { timeout_ms?: number | null }): HarnessTool {
|
||||
return {
|
||||
name: "computer_bash",
|
||||
description: "test",
|
||||
...(timeout_ms === undefined ? {} : { timeout_ms }),
|
||||
run: async () => "done",
|
||||
};
|
||||
}
|
||||
|
||||
describe("toolTimeoutMs", () => {
|
||||
test("a tool with no opinion gets the install's cap", () => {
|
||||
expect(toolTimeoutMs({ tool: tool({}) })).toBe(AppData.HarnessToolTimeoutMs);
|
||||
});
|
||||
|
||||
test("a tool may ask for a larger deadline of its own", () => {
|
||||
expect(toolTimeoutMs({ tool: tool({ timeout_ms: 3_600_000 }) })).toBe(3_600_000);
|
||||
});
|
||||
|
||||
test("a tool may ask for no deadline at all", () => {
|
||||
expect(toolTimeoutMs({ tool: tool({ timeout_ms: null }) })).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,15 @@
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
import type { HarnessTool } from "../types";
|
||||
|
||||
/**
|
||||
* One tool call's deadline: the tool's own (`HarnessTool.timeout_ms`) when
|
||||
* it names one, `null` meaning none at all (`computer_bash`: a script may
|
||||
* run for hours), else the install's cap for every tool
|
||||
* (`AppData.HarnessToolTimeoutMs`). Only the run's own cancellation, the
|
||||
* job's deadline or Stop end a call with no deadline.
|
||||
*/
|
||||
export default function toolTimeoutMs({ tool }: { tool: HarnessTool<any> }): number | null {
|
||||
if (tool.timeout_ms === undefined) return AppData.HarnessToolTimeoutMs;
|
||||
|
||||
return tool.timeout_ms;
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import capTraceText from "./cap-trace-text";
|
||||
|
||||
describe("capTraceText", () => {
|
||||
test("keeps a text that fits whole", () => {
|
||||
expect(capTraceText({ text: "Saved.", max: 20 })).toBe("Saved.");
|
||||
});
|
||||
|
||||
test("is null when there's nothing to keep", () => {
|
||||
expect(capTraceText({ text: null, max: 20 })).toBeNull();
|
||||
expect(capTraceText({ text: "", max: 20 })).toBeNull();
|
||||
expect(capTraceText({ text: undefined, max: 20 })).toBeNull();
|
||||
});
|
||||
|
||||
test("keeps the start and says how much was cut", () => {
|
||||
const text = "a".repeat(120);
|
||||
|
||||
expect(capTraceText({ text, max: 100 })).toBe(
|
||||
`${"a".repeat(100)}\n[cut: 20 more characters not kept]`,
|
||||
);
|
||||
});
|
||||
|
||||
test("keeps exactly `max` characters without cutting", () => {
|
||||
const text = "b".repeat(40);
|
||||
|
||||
expect(capTraceText({ text, max: 40 })).toBe(text);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,20 @@
|
||||
type Params = {
|
||||
text: string | null | undefined;
|
||||
/**
|
||||
* How much of it is kept (`AppData.BotTrace*MaxChars`). A trace is
|
||||
* read, not replayed, so the start is enough.
|
||||
*/
|
||||
max: number;
|
||||
};
|
||||
|
||||
/**
|
||||
* One field of a trace, cut to what the debug view keeps of it. Null when
|
||||
* there's nothing to keep.
|
||||
*/
|
||||
export default function capTraceText({ text, max }: Params): string | null {
|
||||
if (!text) return null;
|
||||
|
||||
if (text.length <= max) return text;
|
||||
|
||||
return `${text.slice(0, max)}\n[cut: ${text.length - max} more characters not kept]`;
|
||||
}
|
||||
@@ -0,0 +1,169 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
import type { HarnessTrace } from "./types";
|
||||
import prepareTrace from "./prepare-trace";
|
||||
|
||||
describe("prepareTrace", () => {
|
||||
test("keeps a turn's numbers and tool names in its metadata", () => {
|
||||
const metadata = JSON.parse(
|
||||
prepareTrace({
|
||||
trace: {
|
||||
kind: "turn",
|
||||
index: 2,
|
||||
model: "openai/gpt-x",
|
||||
provider: "OpenRouter",
|
||||
text: "On it.",
|
||||
reasoning: "They asked for a report.",
|
||||
tool_calls: [
|
||||
{ name: "write_file", arguments: "{}" },
|
||||
{ name: "list_files", arguments: "{}" },
|
||||
],
|
||||
usage: { prompt_tokens: 10, completion_tokens: 4, cost: 0 },
|
||||
finish_reason: "tool_calls",
|
||||
duration_ms: 1200,
|
||||
},
|
||||
}).metadata || "{}",
|
||||
);
|
||||
|
||||
expect(metadata).toEqual({
|
||||
index: 2,
|
||||
model: "openai/gpt-x",
|
||||
provider: "OpenRouter",
|
||||
finish_reason: "tool_calls",
|
||||
duration_ms: 1200,
|
||||
tools: ["write_file", "list_files"],
|
||||
usage: { prompt_tokens: 10, completion_tokens: 4, cost: 0 },
|
||||
});
|
||||
});
|
||||
|
||||
test("keeps a turn's answer and reasoning, and no arguments", () => {
|
||||
const prepared = prepareTrace({
|
||||
trace: {
|
||||
kind: "turn",
|
||||
index: 0,
|
||||
model: null,
|
||||
provider: null,
|
||||
text: "Done.",
|
||||
reasoning: "Simple.",
|
||||
tool_calls: [],
|
||||
usage: null,
|
||||
finish_reason: "stop",
|
||||
duration_ms: 1,
|
||||
},
|
||||
});
|
||||
|
||||
expect(prepared).toMatchObject({
|
||||
kind: "turn",
|
||||
name: null,
|
||||
text: "Done.",
|
||||
reasoning: "Simple.",
|
||||
arguments: null,
|
||||
result: null,
|
||||
});
|
||||
});
|
||||
|
||||
test("keeps whether a tool call failed, and cuts its answer", () => {
|
||||
const long_answer = "x".repeat(AppData.BotTraceResultMaxChars + 10);
|
||||
|
||||
const prepared = prepareTrace({
|
||||
trace: {
|
||||
kind: "tool",
|
||||
index: 1,
|
||||
name: "computer_bash",
|
||||
arguments: `{"command":"ls"}`,
|
||||
result: long_answer,
|
||||
ok: false,
|
||||
images: 0,
|
||||
duration_ms: 40,
|
||||
},
|
||||
});
|
||||
|
||||
expect(JSON.parse(prepared.metadata || "{}")).toEqual({
|
||||
index: 1,
|
||||
ok: false,
|
||||
images: 0,
|
||||
duration_ms: 40,
|
||||
repeat_of: null,
|
||||
});
|
||||
expect(prepared.name).toBe("computer_bash");
|
||||
expect(prepared.result).toContain("[cut: 10 more characters not kept]");
|
||||
expect(prepared.text).toBeNull();
|
||||
expect(prepared.reasoning).toBeNull();
|
||||
});
|
||||
|
||||
test("keeps an event's name and note", () => {
|
||||
const prepared = prepareTrace({
|
||||
trace: { kind: "event", index: 4, name: "steps_low", text: "5 steps left." },
|
||||
});
|
||||
|
||||
expect(prepared).toMatchObject({
|
||||
kind: "event",
|
||||
name: "steps_low",
|
||||
text: "5 steps left.",
|
||||
reasoning: null,
|
||||
arguments: null,
|
||||
result: null,
|
||||
});
|
||||
expect(JSON.parse(prepared.metadata || "{}")).toEqual({ index: 4 });
|
||||
});
|
||||
|
||||
test("a call the loop skipped says which step answered it", () => {
|
||||
const prepared = prepareTrace({
|
||||
trace: {
|
||||
kind: "tool",
|
||||
index: 3,
|
||||
name: "read_file",
|
||||
arguments: "{}",
|
||||
result: "Already read.",
|
||||
ok: true,
|
||||
images: 0,
|
||||
duration_ms: 0,
|
||||
repeat_of: 1,
|
||||
},
|
||||
});
|
||||
|
||||
expect(JSON.parse(prepared.metadata || "{}").repeat_of).toBe(1);
|
||||
});
|
||||
|
||||
test("every trace kind carries a fragment of the same shape", () => {
|
||||
const traces: HarnessTrace[] = [
|
||||
{
|
||||
kind: "turn",
|
||||
index: 0,
|
||||
model: null,
|
||||
provider: null,
|
||||
text: null,
|
||||
reasoning: null,
|
||||
tool_calls: [],
|
||||
usage: null,
|
||||
finish_reason: null,
|
||||
duration_ms: 0,
|
||||
},
|
||||
{
|
||||
kind: "tool",
|
||||
index: 0,
|
||||
name: "x",
|
||||
arguments: "",
|
||||
result: "",
|
||||
ok: true,
|
||||
images: 0,
|
||||
duration_ms: 0,
|
||||
},
|
||||
{ kind: "event", index: 0, name: "e", text: null },
|
||||
];
|
||||
|
||||
for (const trace of traces) {
|
||||
const prepared = prepareTrace({ trace });
|
||||
|
||||
expect(Object.keys(prepared).sort()).toEqual([
|
||||
"arguments",
|
||||
"kind",
|
||||
"metadata",
|
||||
"name",
|
||||
"reasoning",
|
||||
"result",
|
||||
"text",
|
||||
]);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,74 @@
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
import capTraceText from "./cap-trace-text";
|
||||
import type { HarnessTrace } from "./types";
|
||||
|
||||
/**
|
||||
* A trace as `bot_job_traces` stores it: whole fields the debug view reads
|
||||
* straight, with only the numbers and names it shows beside them in
|
||||
* `metadata`.
|
||||
*/
|
||||
export type PreparedTrace = {
|
||||
kind: HarnessTrace["kind"];
|
||||
name: string | null;
|
||||
text: string | null;
|
||||
reasoning: string | null;
|
||||
arguments: string | null;
|
||||
result: string | null;
|
||||
metadata: string | null;
|
||||
};
|
||||
|
||||
/**
|
||||
* One trace, its text cut to the caps the debug view keeps
|
||||
* (`AppData.BotTraceTextMaxChars`, `BotTraceArgumentsMaxChars`,
|
||||
* `BotTraceResultMaxChars`). A turn's tool calls keep their names only:
|
||||
* the tool rows of the same step carry the arguments.
|
||||
*/
|
||||
export default function prepareTrace({ trace }: { trace: HarnessTrace }): PreparedTrace {
|
||||
if (trace.kind == "turn") {
|
||||
return {
|
||||
kind: "turn",
|
||||
name: null,
|
||||
text: capTraceText({ text: trace.text, max: AppData.BotTraceTextMaxChars }),
|
||||
reasoning: capTraceText({ text: trace.reasoning, max: AppData.BotTraceTextMaxChars }),
|
||||
arguments: null,
|
||||
result: null,
|
||||
metadata: JSON.stringify({
|
||||
index: trace.index,
|
||||
model: trace.model,
|
||||
provider: trace.provider,
|
||||
finish_reason: trace.finish_reason,
|
||||
duration_ms: trace.duration_ms,
|
||||
tools: trace.tool_calls.map((call) => call.name),
|
||||
usage: trace.usage || null,
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
if (trace.kind == "tool") {
|
||||
return {
|
||||
kind: "tool",
|
||||
name: trace.name,
|
||||
text: null,
|
||||
reasoning: null,
|
||||
arguments: capTraceText({ text: trace.arguments, max: AppData.BotTraceArgumentsMaxChars }),
|
||||
result: capTraceText({ text: trace.result, max: AppData.BotTraceResultMaxChars }),
|
||||
metadata: JSON.stringify({
|
||||
index: trace.index,
|
||||
ok: trace.ok,
|
||||
images: trace.images,
|
||||
duration_ms: trace.duration_ms,
|
||||
repeat_of: trace.repeat_of ?? null,
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
kind: "event",
|
||||
name: trace.name,
|
||||
text: capTraceText({ text: trace.text, max: AppData.BotTraceTextMaxChars }),
|
||||
reasoning: null,
|
||||
arguments: null,
|
||||
result: null,
|
||||
metadata: JSON.stringify({ index: trace.index }),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import redactSecrets from "@/src/utils/redact-secrets";
|
||||
import type { HarnessTrace } from "./types";
|
||||
import redactTrace from "./redact-trace";
|
||||
|
||||
const secrets = [{ key: "API_KEY", value: "sk-very-secret" }];
|
||||
const redact = (text: string) => redactSecrets({ text, secrets });
|
||||
|
||||
const turn: HarnessTrace = {
|
||||
kind: "turn",
|
||||
index: 0,
|
||||
model: "m",
|
||||
provider: "p",
|
||||
text: "Using sk-very-secret now.",
|
||||
reasoning: "The key is sk-very-secret.",
|
||||
tool_calls: [{ name: "bash", arguments: `{"cmd":"echo sk-very-secret"}` }],
|
||||
usage: null,
|
||||
finish_reason: "tool_calls",
|
||||
duration_ms: 5,
|
||||
};
|
||||
|
||||
describe("redactTrace", () => {
|
||||
test("blanks the secret out of a turn's answer, reasoning and tool calls", () => {
|
||||
const safe = redactTrace({ trace: turn, redact });
|
||||
|
||||
expect(safe).toEqual({
|
||||
...turn,
|
||||
text: "Using [API_KEY] now.",
|
||||
reasoning: "The key is [API_KEY].",
|
||||
tool_calls: [{ name: "bash", arguments: `{"cmd":"echo [API_KEY]"}` }],
|
||||
});
|
||||
});
|
||||
|
||||
test("blanks it out of a tool's arguments and answer", () => {
|
||||
const safe = redactTrace({
|
||||
trace: {
|
||||
kind: "tool",
|
||||
index: 0,
|
||||
name: "computer_bash",
|
||||
arguments: "export KEY=sk-very-secret",
|
||||
result: "sk-very-secret",
|
||||
ok: true,
|
||||
images: 0,
|
||||
duration_ms: 3,
|
||||
},
|
||||
redact,
|
||||
});
|
||||
|
||||
expect(safe).toMatchObject({
|
||||
arguments: "export KEY=[API_KEY]",
|
||||
result: "[API_KEY]",
|
||||
});
|
||||
});
|
||||
|
||||
test("blanks it out of an event's note", () => {
|
||||
expect(
|
||||
redactTrace({
|
||||
trace: { kind: "event", index: 1, name: "incoming", text: "sk-very-secret" },
|
||||
redact,
|
||||
}),
|
||||
).toMatchObject({ text: "[API_KEY]" });
|
||||
});
|
||||
|
||||
test("keeps a turn with no text as it was", () => {
|
||||
expect(
|
||||
redactTrace({
|
||||
trace: { ...turn, text: null, reasoning: null },
|
||||
redact,
|
||||
}),
|
||||
).toMatchObject({ text: null, reasoning: null });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,42 @@
|
||||
import type { HarnessTrace } from "./types";
|
||||
|
||||
type Params = {
|
||||
trace: HarnessTrace;
|
||||
/**
|
||||
* Blanks secret values out of the text (`redactSecrets`). A task run
|
||||
* passes its computer's, which also holds what the bot captured
|
||||
* (`capture_secret`) during this run.
|
||||
*/
|
||||
redact: (text: string) => string;
|
||||
};
|
||||
|
||||
/**
|
||||
* The same trace with every piece of text it carries redacted: a tool's
|
||||
* arguments and answer, a turn's answer and reasoning, an event's note.
|
||||
* The job's own trace is redacted with the run's envs whatever this does
|
||||
* (`insertBotJobTrace`), so this only adds the secrets the run discovered
|
||||
* as it went.
|
||||
*/
|
||||
export default function redactTrace({ trace, redact }: Params): HarnessTrace {
|
||||
if (trace.kind == "turn") {
|
||||
return {
|
||||
...trace,
|
||||
text: trace.text ? redact(trace.text) : trace.text,
|
||||
reasoning: trace.reasoning ? redact(trace.reasoning) : trace.reasoning,
|
||||
tool_calls: trace.tool_calls.map((call) => ({
|
||||
...call,
|
||||
arguments: redact(call.arguments),
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
if (trace.kind == "tool") {
|
||||
return {
|
||||
...trace,
|
||||
arguments: redact(trace.arguments),
|
||||
result: redact(trace.result),
|
||||
};
|
||||
}
|
||||
|
||||
return { ...trace, text: trace.text ? redact(trace.text) : trace.text };
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
import type { HarnessUsage } from "../types";
|
||||
|
||||
/**
|
||||
* One model turn as the debug view keeps it: what the model answered, what
|
||||
* it reasoned, the tools it asked for, and what the turn cost.
|
||||
*/
|
||||
export type HarnessTurnTrace = {
|
||||
kind: "turn";
|
||||
index: number;
|
||||
model: string | null;
|
||||
provider: string | null;
|
||||
text: string | null;
|
||||
reasoning: string | null;
|
||||
tool_calls: { name: string; arguments: string }[];
|
||||
usage: HarnessUsage | null;
|
||||
finish_reason: string | null;
|
||||
duration_ms: number;
|
||||
};
|
||||
|
||||
/**
|
||||
* One tool call as the debug view keeps it: the arguments the model wrote
|
||||
* and what the tool answered. Both are the model's own text, so both may
|
||||
* hold a secret value: a trace is redacted before it is stored
|
||||
* (`redactTrace`).
|
||||
*/
|
||||
export type HarnessToolTrace = {
|
||||
kind: "tool";
|
||||
index: number;
|
||||
name: string;
|
||||
arguments: string;
|
||||
result: string;
|
||||
ok: boolean;
|
||||
images: number;
|
||||
duration_ms: number;
|
||||
/**
|
||||
* The step whose identical read answered this call, when the loop
|
||||
* skipped it (`alreadyRanToolNote`).
|
||||
*/
|
||||
repeat_of?: number | null;
|
||||
};
|
||||
|
||||
/**
|
||||
* Something the loop itself did, that no turn or tool call shows: a
|
||||
* context trim, the wrap up, what the user wrote mid-run, an answer
|
||||
* `review` sent back.
|
||||
*/
|
||||
export type HarnessEventTrace = {
|
||||
kind: "event";
|
||||
index: number;
|
||||
name: string;
|
||||
text: string | null;
|
||||
};
|
||||
|
||||
export type HarnessTrace = HarnessTurnTrace | HarnessToolTrace | HarnessEventTrace;
|
||||
|
||||
/**
|
||||
* Where a run's detailed trace goes (`bot_job_traces`, read by the
|
||||
* conversation's debug view). Best effort: the loop never fails because a
|
||||
* trace couldn't be kept.
|
||||
*/
|
||||
export type HarnessTracer = (trace: HarnessTrace) => Promise<void> | void;
|
||||
@@ -107,6 +107,12 @@ export type HarnessTool<Args = any> = {
|
||||
* definitions would otherwise ride along on every turn.
|
||||
*/
|
||||
deferred?: boolean;
|
||||
/**
|
||||
* This call's deadline, overriding `AppData.HarnessToolTimeoutMs`: a
|
||||
* bigger one for a tool with its own slow work, `null` for none at all
|
||||
* (`computer_bash`, whose command may run for hours).
|
||||
*/
|
||||
timeout_ms?: number | null;
|
||||
run: (params: { args: Args; signal: AbortSignal }) => Promise<HarnessToolOutput>;
|
||||
};
|
||||
|
||||
@@ -229,6 +235,13 @@ export type HarnessChatResult = {
|
||||
tool_calls: HarnessToolCall[];
|
||||
finish_reason?: string;
|
||||
usage?: HarnessUsage;
|
||||
/**
|
||||
* What the model reasoned before answering, when its provider hands it
|
||||
* back (`reasoning`, `reasoning_content`) or it wrote it inline in
|
||||
* `text` (`stripThinkTags`). Only the debug view shows it: never the
|
||||
* bot's answer, history or prompt.
|
||||
*/
|
||||
reasoning?: string | null;
|
||||
};
|
||||
|
||||
export type HarnessAudioInput = {
|
||||
|
||||
@@ -11,6 +11,7 @@ import relayCreatedBots from "./relay-created-bots";
|
||||
import relayCreatedWorkspaces from "./relay-created-workspaces";
|
||||
import relayNewBotMessages from "./relay-new-bot-messages";
|
||||
import relayNewJobUpdates from "./relay-new-job-updates";
|
||||
import relayNewJobTraces from "./relay-new-job-traces";
|
||||
import type { LiveRelayCursor } from "./types";
|
||||
|
||||
/**
|
||||
@@ -27,7 +28,7 @@ export default async function liveRelay() {
|
||||
* A failed read starts the relay from the beginning instead of not
|
||||
* starting it: clients drop what they already have.
|
||||
*/
|
||||
const latest = async (table: "bot_messages" | "bots_queue_updates") => {
|
||||
const latest = async (table: "bot_messages" | "bots_queue_updates" | "bot_job_traces") => {
|
||||
try {
|
||||
return (
|
||||
Number(
|
||||
@@ -50,6 +51,7 @@ export default async function liveRelay() {
|
||||
const cursor: LiveRelayCursor = {
|
||||
message_id: await latest("bot_messages"),
|
||||
update_id: await latest("bots_queue_updates"),
|
||||
trace_id: await latest("bot_job_traces"),
|
||||
bots_at: Date.now(),
|
||||
sessions_at: Date.now(),
|
||||
};
|
||||
@@ -67,6 +69,7 @@ export default async function liveRelay() {
|
||||
|
||||
cursor.message_id = await relayNewBotMessages({ after_id: cursor.message_id, users });
|
||||
cursor.update_id = await relayNewJobUpdates({ after_id: cursor.update_id, users });
|
||||
cursor.trace_id = await relayNewJobTraces({ after_id: cursor.trace_id, users });
|
||||
|
||||
/**
|
||||
* Overlap one interval, so a change written in the same
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
import type { BotTraceData } from "@/src/types";
|
||||
import { sendToUser } from "@/src/websocket/(functions)/send-to-user";
|
||||
|
||||
type Params = {
|
||||
after_id: number;
|
||||
users: Set<string>;
|
||||
};
|
||||
|
||||
type Row = BotTraceData & { user_id: number; id: number };
|
||||
|
||||
/**
|
||||
* Pushes `server:bot-trace` for every session whose job kept a trace entry
|
||||
* newer than `after_id`, to the sockets on this process of the user the
|
||||
* job runs for. Only the job and its session travel: a debug view that's
|
||||
* open reads the entries it doesn't have. Returns the newest id read.
|
||||
*/
|
||||
export default async function relayNewJobTraces({ after_id, users }: Params) {
|
||||
const rows =
|
||||
(
|
||||
await BunSQLite.sql<Row>({
|
||||
sql: `SELECT MAX(t.id) AS id, t.bots_queue_id AS job_id, t.session_id, s.user_id
|
||||
FROM bot_job_traces t
|
||||
JOIN bot_sessions s ON s.id = t.session_id
|
||||
WHERE t.id > ?
|
||||
GROUP BY t.session_id
|
||||
ORDER BY id ASC
|
||||
LIMIT 500`,
|
||||
values: [after_id],
|
||||
})
|
||||
).payload || [];
|
||||
|
||||
for (const { user_id, ...trace } of rows) {
|
||||
if (!users.has(String(user_id))) continue;
|
||||
|
||||
sendToUser({
|
||||
user_id,
|
||||
data: {
|
||||
event: "server:bot-trace",
|
||||
data: {
|
||||
job_id: Number(trace.job_id),
|
||||
session_id: trace.session_id ? Number(trace.session_id) : null,
|
||||
} satisfies BotTraceData,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
return Number(rows[rows.length - 1]?.id) || after_id;
|
||||
}
|
||||
@@ -1,10 +1,11 @@
|
||||
/**
|
||||
* How far the relay has read: the newest message and job step it pushed,
|
||||
* and when it last looked for changed bots and sessions.
|
||||
* How far the relay has read: the newest message, job step and trace entry
|
||||
* it pushed, and when it last looked for changed bots and sessions.
|
||||
*/
|
||||
export type LiveRelayCursor = {
|
||||
message_id: number;
|
||||
update_id: number;
|
||||
trace_id: number;
|
||||
bots_at: number;
|
||||
sessions_at: number;
|
||||
};
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
import fetchApi from "@moduletrace/twui/utils/fetch/fetchApi";
|
||||
import type { APIResponseObject } from "@moduletrace/bunext/types";
|
||||
import type { BotTraceJob } from "@/src/types";
|
||||
|
||||
type Params = {
|
||||
message_id: number;
|
||||
/**
|
||||
* The room the message was posted in, when it came from a chatroom: its
|
||||
* run is read through the room's own access.
|
||||
*/
|
||||
chatroom_id?: number;
|
||||
};
|
||||
|
||||
/**
|
||||
* What the run behind one message did, in detail: the debug logs tab of
|
||||
* its Details modal. Read when that tab is opened rather than with the
|
||||
* details, since a long run's tool answers are the biggest thing the modal
|
||||
* would carry.
|
||||
*/
|
||||
export default async function fetchMessageTrace({ message_id, chatroom_id }: Params) {
|
||||
return await fetchApi<{ message_id: number; chatroom_id?: number }, APIResponseObject<BotTraceJob[]>>(
|
||||
"/api/admin/bots/message-trace",
|
||||
{ method: "POST", body: { message_id, ...(chatroom_id ? { chatroom_id } : {}) } },
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
import fetchApi from "@moduletrace/twui/utils/fetch/fetchApi";
|
||||
import type { APIResponseObject } from "@moduletrace/bunext/types";
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import useServerEvent from "@/src/hooks/use-server-event";
|
||||
import type { BotTraceData, BotTraceJob } from "@/src/types";
|
||||
|
||||
type Params = {
|
||||
/**
|
||||
* The session the conversation shows: its runs' traces are what the
|
||||
* debug view lists.
|
||||
*/
|
||||
session_id?: number | null;
|
||||
/**
|
||||
* The view is on screen. Nothing is read, and no push is taken, while
|
||||
* it's closed.
|
||||
*/
|
||||
open: boolean;
|
||||
};
|
||||
|
||||
/**
|
||||
* How long after the first push a reload waits, so a run that keeps
|
||||
* tracing through its tools reads once rather than once per step.
|
||||
*/
|
||||
const ReloadGapMs = 500;
|
||||
|
||||
/**
|
||||
* What a conversation's runs did in detail (`bot_job_traces`): read when
|
||||
* the debug view opens and on `server:bot-trace`, which names only the job
|
||||
* and its session, so the view reads the entries it doesn't have.
|
||||
*/
|
||||
export default function useBotTrace({ session_id, open }: Params) {
|
||||
const [jobs, setJobs] = useState<BotTraceJob[]>([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState<string>();
|
||||
const timer = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
|
||||
const load = useCallback(async () => {
|
||||
if (!session_id) return;
|
||||
|
||||
setLoading(true);
|
||||
setError(undefined);
|
||||
|
||||
const res = await fetchApi<{}, APIResponseObject<BotTraceJob[]>>(
|
||||
"/api/admin/bots/trace",
|
||||
{ method: "POST", body: { session_id } },
|
||||
).catch(() => null);
|
||||
|
||||
setLoading(false);
|
||||
|
||||
if (!res?.success) {
|
||||
setError(res?.msg || `Couldn't load the trace.`);
|
||||
return;
|
||||
}
|
||||
|
||||
setJobs(res.singleRes || []);
|
||||
}, [session_id]);
|
||||
|
||||
/**
|
||||
* One reload is enough for everything written while it was waiting.
|
||||
*/
|
||||
const schedule = useCallback(() => {
|
||||
if (timer.current) return;
|
||||
|
||||
timer.current = setTimeout(() => {
|
||||
timer.current = null;
|
||||
load().catch(() => {});
|
||||
}, ReloadGapMs);
|
||||
}, [load]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
|
||||
setJobs([]);
|
||||
load().catch(() => {});
|
||||
}, [open, session_id]);
|
||||
|
||||
useServerEvent({
|
||||
event: "server:bot-trace",
|
||||
onData: (data: BotTraceData) => {
|
||||
if (!open || data?.session_id != session_id) return;
|
||||
|
||||
schedule();
|
||||
},
|
||||
});
|
||||
|
||||
/**
|
||||
* A run that ends pushes its message, not a trace: the view reads once
|
||||
* more so its last entries and its status are right.
|
||||
*/
|
||||
useServerEvent({
|
||||
event: "server:bot-message",
|
||||
onData: (data: { session_id?: number } | undefined) => {
|
||||
if (!open || data?.session_id != session_id) return;
|
||||
|
||||
schedule();
|
||||
},
|
||||
});
|
||||
|
||||
useEffect(
|
||||
() => () => {
|
||||
if (timer.current) clearTimeout(timer.current);
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
return { jobs, loading, error, reload: load };
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import readDebugOpen from "@/src/functions/frontend/read-debug-open";
|
||||
import rememberDebugOpen from "@/src/functions/frontend/remember-debug-open";
|
||||
|
||||
type Params = {
|
||||
/**
|
||||
* Whose answer it is: the view belongs to the user, not to a bot, so
|
||||
* it stays as they left it in every conversation on this device.
|
||||
*/
|
||||
user_id?: number | string | null;
|
||||
};
|
||||
|
||||
/**
|
||||
* Whether the conversation's debug view is open, remembered per user on
|
||||
* this device (`readDebugOpen`). Read after the first render: the server
|
||||
* has no `localStorage`.
|
||||
*/
|
||||
export default function useDebugOpen({ user_id }: Params) {
|
||||
const [open, setOpenState] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
setOpenState(readDebugOpen({ user_id }));
|
||||
}, [user_id]);
|
||||
|
||||
const setOpen = useCallback(
|
||||
(next: boolean) => {
|
||||
setOpenState(next);
|
||||
rememberDebugOpen({ user_id, open: next });
|
||||
},
|
||||
[user_id],
|
||||
);
|
||||
|
||||
return { open, setOpen };
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import type { BotTraceJob } from "@/src/types";
|
||||
import fetchMessageTrace from "../(functions)/fetch-message-trace";
|
||||
|
||||
type Params = {
|
||||
message_id: number;
|
||||
/**
|
||||
* Set when the message was posted in a chatroom, so its run is read
|
||||
* through the room's access.
|
||||
*/
|
||||
chatroom_id?: number;
|
||||
/**
|
||||
* Read only once the debug logs tab is open, so the modal's first tab
|
||||
* doesn't wait on a long run's trace.
|
||||
*/
|
||||
enabled?: boolean;
|
||||
};
|
||||
|
||||
/**
|
||||
* The trace behind one message (`api/admin/bots/message-trace`), for the
|
||||
* debug logs tab of its Details modal. Read when that tab opens, and kept
|
||||
* while the modal is open.
|
||||
*/
|
||||
export default function useMessageTrace({ message_id, chatroom_id, enabled = true }: Params) {
|
||||
const [jobs, setJobs] = useState<BotTraceJob[]>();
|
||||
const [loading, set_loading] = useState(false);
|
||||
const [error, set_error] = useState<string>();
|
||||
|
||||
const load = useCallback(async () => {
|
||||
set_loading(true);
|
||||
set_error(undefined);
|
||||
|
||||
const res = await fetchMessageTrace({ message_id, chatroom_id }).catch(() => null);
|
||||
|
||||
set_loading(false);
|
||||
|
||||
if (!res?.success || !res.singleRes) {
|
||||
set_error(res?.msg || `Couldn't load this message's debug logs.`);
|
||||
return;
|
||||
}
|
||||
|
||||
setJobs(res.singleRes);
|
||||
}, [message_id, chatroom_id]);
|
||||
|
||||
useEffect(() => {
|
||||
if (enabled) load().catch(() => {});
|
||||
}, [enabled, load]);
|
||||
|
||||
return { jobs, loading, error, reload: load };
|
||||
}
|
||||
@@ -23,15 +23,17 @@ type Params = {
|
||||
/**
|
||||
* Keeps the thread from waiting on a push that never came: every return to
|
||||
* the page (`useRefocus`) reads the session's latest messages and the
|
||||
* bot's face, status line and active task, and while a reply is due it
|
||||
* does so every `AppData.BotReplyCatchUpMs` too. A missed message is
|
||||
* replayed as the `server:bot-message` it would have been, so the thread,
|
||||
* the rail and the unread flag all take it the usual way. The bot's face,
|
||||
* status line and active task are replayed as `server:bot-updated`, so a
|
||||
* reply that ended without a final message (its face push missed) can't
|
||||
* leave the bot thinking or a finished task on screen. Reading it even
|
||||
* when no reply is due is what lets a row stuck on a stale face or task
|
||||
* clear itself without a reload.
|
||||
* bot's face, status line, active task and the step its reply is on, and
|
||||
* while a reply is due it does so every `AppData.BotReplyCatchUpMs` too. A
|
||||
* missed message is replayed as the `server:bot-message` it would have been,
|
||||
* so the thread, the rail and the unread flag all take it the usual way. The
|
||||
* bot's face, status line and active task are replayed as
|
||||
* `server:bot-updated`, so a reply that ended without a final message (its
|
||||
* face push missed) can't leave the bot thinking or a finished task on
|
||||
* screen. The step is replayed as `server:bot-job-update`, so a run whose
|
||||
* steps were pushed while the page slept still shows the one it's on.
|
||||
* Reading it even when no reply is due is what lets a row stuck on a stale
|
||||
* face or task clear itself without a reload.
|
||||
*/
|
||||
export default function useReplyCatchUp({ session_id, awaiting_reply, last_message_id }: Params) {
|
||||
const last_message = useRef(Number(last_message_id) || 0);
|
||||
@@ -66,6 +68,13 @@ export default function useReplyCatchUp({ session_id, awaiting_reply, last_messa
|
||||
replay({ data: { event: "server:bot-message", data: message } });
|
||||
}
|
||||
|
||||
/**
|
||||
* The step the reply is on now, replayed as the push it would have
|
||||
* been: a row shows the line of the last step it heard of, and a
|
||||
* reload or a socket that dropped heard of none.
|
||||
*/
|
||||
if (res.step?.id) replay({ data: { event: "server:bot-job-update", data: res.step } });
|
||||
|
||||
/**
|
||||
* After the messages, so a reply that ended silently (its last
|
||||
* word an interim one) drops the row once its face moves on.
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { useRef, useState } from "react";
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import useServerEvent from "@/src/hooks/use-server-event";
|
||||
import type { BotJobUpdateData } from "@/src/types";
|
||||
import isNewerStep from "../(utils)/is-newer-step";
|
||||
|
||||
type Params = {
|
||||
bot_id: number;
|
||||
@@ -14,25 +15,55 @@ type Params = {
|
||||
* it.
|
||||
*/
|
||||
last_message_id?: number | null;
|
||||
/**
|
||||
* The step the server still has for the open reply, read with the
|
||||
* history: a page that just loaded shows what the run is doing at once
|
||||
* rather than only the row's label, waiting for its next push (the
|
||||
* catch-up replays the newer ones).
|
||||
*/
|
||||
seed?: BotJobUpdateData | null;
|
||||
};
|
||||
|
||||
type Step = {
|
||||
id: number;
|
||||
text: string;
|
||||
after_message_id: number | null;
|
||||
/**
|
||||
* The session it was read in: another one's step never shows here.
|
||||
*/
|
||||
session_id: number | null;
|
||||
};
|
||||
|
||||
/**
|
||||
* The latest step of the reply running in the open session (a
|
||||
* `bots_queue_updates` row's text, from `server:bot-job-update` without a
|
||||
* task), so a reply that works through tools shows what it's doing. Only
|
||||
* tool steps: the closing note is the answer itself.
|
||||
* tool steps: the closing note is the answer itself. The steps the server
|
||||
* still holds (the history's, the catch-up's replay) are taken the same
|
||||
* way, and never take the row back a line.
|
||||
*/
|
||||
export default function useReplyProgress({ bot_id, session_id, last_message_id }: Params) {
|
||||
export default function useReplyProgress({
|
||||
bot_id,
|
||||
session_id,
|
||||
last_message_id,
|
||||
seed,
|
||||
}: Params) {
|
||||
const [step, setStep] = useState<Step | null>(null);
|
||||
const last_message = useRef(last_message_id || null);
|
||||
|
||||
last_message.current = last_message_id || null;
|
||||
|
||||
const adopt = useCallback((update: BotJobUpdateData) => {
|
||||
const taken: Step = {
|
||||
id: Number(update.id),
|
||||
text: update.text as string,
|
||||
after_message_id: last_message.current,
|
||||
session_id: Number(update.session_id) || null,
|
||||
};
|
||||
|
||||
setStep((shown) => (isNewerStep({ shown, step: taken }) ? taken : shown));
|
||||
}, []);
|
||||
|
||||
useServerEvent({
|
||||
event: "server:bot-job-update",
|
||||
onData: (update: BotJobUpdateData) => {
|
||||
@@ -45,9 +76,23 @@ export default function useReplyProgress({ bot_id, session_id, last_message_id }
|
||||
if (update.kind == "note") return;
|
||||
if (!session_id || update.session_id != session_id) return;
|
||||
|
||||
setStep({ text: update.text, after_message_id: last_message.current });
|
||||
adopt(update);
|
||||
},
|
||||
});
|
||||
|
||||
return step && step.after_message_id == (last_message_id || null) ? step.text : null;
|
||||
}
|
||||
/**
|
||||
* Read again with the history, so it lands once the thread shows the
|
||||
* messages it belongs after (it's keyed to the last one).
|
||||
*/
|
||||
useEffect(() => {
|
||||
if (!seed?.id || !seed.text) return;
|
||||
|
||||
adopt(seed);
|
||||
}, [seed, last_message_id, adopt]);
|
||||
|
||||
return step &&
|
||||
step.session_id == (session_id || null) &&
|
||||
step.after_message_id == (last_message_id || null)
|
||||
? step.text
|
||||
: null;
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { renderToString } from "react-dom/server";
|
||||
import type { BotWithLastMessage } from "@/src/types";
|
||||
import BotThinkingRow from "./bot-thinking-row";
|
||||
|
||||
function bot(overrides: Partial<BotWithLastMessage>): BotWithLastMessage {
|
||||
return {
|
||||
id: 1,
|
||||
name: "Ember",
|
||||
color: "#c2410c",
|
||||
stone: "ember",
|
||||
face: "working",
|
||||
...overrides,
|
||||
} as BotWithLastMessage;
|
||||
}
|
||||
|
||||
/**
|
||||
* The row under the thread: its label, and the step of the work it shows.
|
||||
* The reply's step is the one a reload has to bring back, or the row sits
|
||||
* on its label until the run's next push.
|
||||
*/
|
||||
describe("BotThinkingRow", () => {
|
||||
test("a reply owed here shows the step it's on", () => {
|
||||
const html = renderToString(
|
||||
<BotThinkingRow bot={bot({})} awaiting_reply reply_progress="Reading the invoice" />,
|
||||
);
|
||||
|
||||
expect(html).toContain("Ember is thinking");
|
||||
expect(html).toContain("Reading the invoice");
|
||||
});
|
||||
|
||||
test("a task shows the step it's on", () => {
|
||||
const html = renderToString(
|
||||
<BotThinkingRow
|
||||
bot={bot({ status_line: "Working on a task" })}
|
||||
has_task
|
||||
progress="Using sandbox_execute_bash"
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(html).toContain("Ember is working");
|
||||
expect(html).toContain("Using sandbox_execute_bash");
|
||||
});
|
||||
|
||||
test("no step yet shows the label alone", () => {
|
||||
const html = renderToString(<BotThinkingRow bot={bot({})} awaiting_reply />);
|
||||
|
||||
expect(html).toContain("Ember is thinking");
|
||||
expect(html).not.toContain("Reading the invoice");
|
||||
});
|
||||
});
|
||||
@@ -1,12 +1,16 @@
|
||||
import Button from "@moduletrace/twui/layout/Button";
|
||||
import Row from "@moduletrace/twui/layout/Row";
|
||||
import Span from "@moduletrace/twui/layout/Span";
|
||||
import Stack from "@moduletrace/twui/layout/Stack";
|
||||
import { twMerge } from "tailwind-merge";
|
||||
import { Bug } from "lucide-react";
|
||||
import BotAvatar from "@/src/components/general/bot-avatar";
|
||||
import botStoneProps from "@/src/utils/bot-stone-props";
|
||||
import { BotGettingMessageStatusLine } from "@/src/dict/bot-queue-dict";
|
||||
import type { BotWithLastMessage } from "@/src/types";
|
||||
import botBusyState from "../(utils)/bot-busy-state";
|
||||
import StopBotButton from "./stop-bot-button";
|
||||
import TracePanel from "./trace-panel";
|
||||
|
||||
type Props = {
|
||||
bot: BotWithLastMessage;
|
||||
@@ -31,6 +35,19 @@ type Props = {
|
||||
* This session has an active task.
|
||||
*/
|
||||
has_task?: boolean;
|
||||
/**
|
||||
* The session's id: the debug logs read the run it's working on.
|
||||
*/
|
||||
session_id?: number | null;
|
||||
/**
|
||||
* The debug logs are open under the row. The conversation keeps that,
|
||||
* remembered per user.
|
||||
*/
|
||||
debug_open?: boolean;
|
||||
/**
|
||||
* Shows or hides the debug logs under the row.
|
||||
*/
|
||||
on_toggle_debug?: () => void;
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -41,7 +58,8 @@ type Props = {
|
||||
* reply shows from the thread alone: every user message queues one, so while
|
||||
* the user has the last word a reply is due here, even while the bot works
|
||||
* elsewhere. Only the waits (for a model, for its computer) come from the
|
||||
* face. While it shows, a stop button pulls the plug on the bot's work.
|
||||
* face. While it shows, a stop button pulls the plug on the bot's work, and
|
||||
* a bug button opens the run's debug logs under it (`TracePanel`).
|
||||
*/
|
||||
export default function BotThinkingRow({
|
||||
bot,
|
||||
@@ -50,6 +68,9 @@ export default function BotThinkingRow({
|
||||
awaiting_reply,
|
||||
receiving,
|
||||
has_task,
|
||||
session_id,
|
||||
debug_open,
|
||||
on_toggle_debug,
|
||||
}: Props) {
|
||||
const name = bot.name || "The bot";
|
||||
const { waiting, getting, thinking, working, busy, stoppable } = botBusyState({
|
||||
@@ -71,24 +92,47 @@ export default function BotThinkingRow({
|
||||
const detail = working ? progress : thinking ? reply_progress : null;
|
||||
|
||||
return (
|
||||
<Row role="status" className="w-full gap-3! flex-nowrap items-center">
|
||||
<BotAvatar
|
||||
image_media_id={bot.image_media_id}
|
||||
{...botStoneProps({ color: bot.color, stone: bot.stone, hue: bot.hue })}
|
||||
face={waiting ? "asleep" : "working"}
|
||||
size={28}
|
||||
/>
|
||||
<Stack className="min-w-0 gap-0! items-start">
|
||||
<Span className="text-sm leading-5 text-ink-secondary animate-pulse motion-reduce:animate-none">
|
||||
{label}
|
||||
</Span>
|
||||
{detail ? (
|
||||
<Span className="w-full text-xs leading-4 text-ink-secondary truncate">
|
||||
{detail}
|
||||
<Stack className="w-full gap-0! items-stretch">
|
||||
<Row role="status" className="w-full gap-3! flex-nowrap items-center">
|
||||
<BotAvatar
|
||||
image_media_id={bot.image_media_id}
|
||||
{...botStoneProps({ color: bot.color, stone: bot.stone, hue: bot.hue })}
|
||||
face={waiting ? "asleep" : "working"}
|
||||
size={28}
|
||||
/>
|
||||
<Stack className="min-w-0 grow gap-0! items-start">
|
||||
<Span className="text-sm leading-5 text-ink-secondary animate-pulse motion-reduce:animate-none">
|
||||
{label}
|
||||
</Span>
|
||||
{detail ? (
|
||||
<Span className="w-full text-xs leading-4 text-ink-secondary truncate">
|
||||
{detail}
|
||||
</Span>
|
||||
) : null}
|
||||
</Stack>
|
||||
{on_toggle_debug ? (
|
||||
<Button
|
||||
title={debug_open ? "Hide the debug logs" : "Show the debug logs"}
|
||||
aria-label={debug_open ? "Hide the debug logs" : "Show the debug logs"}
|
||||
aria-pressed={Boolean(debug_open)}
|
||||
type="button"
|
||||
variant="ghost"
|
||||
color="text"
|
||||
size="smaller"
|
||||
onClick={on_toggle_debug}
|
||||
className={twMerge(
|
||||
"shrink-0 p-1! text-ink-secondary dark:text-ink-secondary hover:text-ink hover:dark:text-ink hover:bg-sunken hover:dark:bg-sunken rounded-default transition-colors duration-[var(--m-fast)] focus-visible:ring-2 focus-visible:ring-ink",
|
||||
debug_open && "bg-sunken text-ink dark:text-ink",
|
||||
)}
|
||||
>
|
||||
<Bug size={14} aria-hidden />
|
||||
</Button>
|
||||
) : null}
|
||||
</Stack>
|
||||
<StopBotButton bot_name={bot.name} disabled={!stoppable} />
|
||||
</Row>
|
||||
<StopBotButton bot_name={bot.name} disabled={!stoppable} />
|
||||
</Row>
|
||||
{debug_open && on_toggle_debug ? (
|
||||
<TracePanel session_id={session_id} open={Boolean(debug_open)} />
|
||||
) : null}
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -70,7 +70,8 @@ type Props = {
|
||||
* instructions there and making it the admin there, its
|
||||
* settings and, while it works, stopping it. A
|
||||
* row that opens a modal closes the menu first, so the modal never sits
|
||||
* behind an open menu.
|
||||
* behind an open menu. The debug view is what the session's runs did in
|
||||
* detail, beside the thread.
|
||||
*/
|
||||
export default function ConversationHeaderMenu({
|
||||
bot,
|
||||
|
||||
@@ -42,10 +42,10 @@ type Props = {
|
||||
|
||||
/**
|
||||
* 64px header. Under the name, what the bot runs on: its model and the
|
||||
* computer it's on. On the right, one menu holding everything the header
|
||||
* used to show as icons: sessions, a new session, the computer, the models
|
||||
* and the bot's settings. Kept here so a save or a switch shows under the
|
||||
* name at once.
|
||||
* computer it's on. On the right, one menu
|
||||
* holding everything the header used to show as icons: sessions, a new
|
||||
* session, the computer, the models and the bot's settings. Kept here so a
|
||||
* save or a switch shows under the name at once.
|
||||
*/
|
||||
export default function ConversationHeader({
|
||||
bot,
|
||||
@@ -145,7 +145,7 @@ export default function ConversationHeader({
|
||||
</Row>
|
||||
</Stack>
|
||||
|
||||
<Row className="ml-auto shrink-0 flex-nowrap justify-end">
|
||||
<Row className="ml-auto shrink-0 flex-nowrap items-center justify-end gap-1!">
|
||||
<Dropdown
|
||||
position="bottom-right"
|
||||
externalOpen={open_menu}
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import Button from "@moduletrace/twui/layout/Button";
|
||||
import { Check, ClipboardCopy } from "lucide-react";
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
import copyPendingText from "@/src/utils/copy-pending-text";
|
||||
import type { BotTraceJob } from "@/src/types";
|
||||
import messageDebugLogsMarkdown from "../(utils)/message-debug-logs-markdown";
|
||||
|
||||
type Props = {
|
||||
message_id: number;
|
||||
/**
|
||||
* The runs behind the message, as the tab already read them.
|
||||
*/
|
||||
jobs: BotTraceJob[];
|
||||
};
|
||||
|
||||
/**
|
||||
* The debug logs tab's "Copy debug logs": puts the message's whole trace on
|
||||
* the clipboard as one markdown document (`messageDebugLogsMarkdown`),
|
||||
* every step it kept included. The row shows a check for a moment, then
|
||||
* goes back.
|
||||
*/
|
||||
export default function CopyDebugLogsButton({ message_id, jobs }: Props) {
|
||||
const [copied, set_copied] = useState(false);
|
||||
const timeout = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
if (timeout.current) clearTimeout(timeout.current);
|
||||
};
|
||||
}, []);
|
||||
|
||||
const copy = async () => {
|
||||
const text = Promise.resolve(messageDebugLogsMarkdown({ message_id, jobs, now: Date.now() }));
|
||||
|
||||
try {
|
||||
const worked = await copyPendingText({ text });
|
||||
|
||||
if (!worked) {
|
||||
window.alert("Couldn't copy the debug logs to the clipboard.");
|
||||
return;
|
||||
}
|
||||
|
||||
set_copied(true);
|
||||
timeout.current = setTimeout(() => set_copied(false), AppData.CopyConfirmationMs);
|
||||
} catch {
|
||||
window.alert("Couldn't copy the debug logs.");
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Button
|
||||
title={copied ? "Copied" : "Copy this message's debug logs as markdown"}
|
||||
type="button"
|
||||
variant="ghost"
|
||||
color="gray"
|
||||
size="small"
|
||||
beforeIcon={copied ? <Check size={14} aria-hidden /> : <ClipboardCopy size={14} aria-hidden />}
|
||||
disabled={copied}
|
||||
onClick={() => {
|
||||
if (!copied) void copy();
|
||||
}}
|
||||
className="shrink-0 px-2! text-[12px]"
|
||||
>
|
||||
{copied ? "Copied" : "Copy debug logs"}
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
import Button from "@moduletrace/twui/layout/Button";
|
||||
import Row from "@moduletrace/twui/layout/Row";
|
||||
import Span from "@moduletrace/twui/layout/Span";
|
||||
import Stack from "@moduletrace/twui/layout/Stack";
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
import useMessageTrace from "../(hooks)/use-message-trace";
|
||||
import CopyDebugLogsButton from "./copy-debug-logs-button";
|
||||
import TraceJobCard from "./trace-job-card";
|
||||
|
||||
type Props = {
|
||||
message_id: number;
|
||||
/**
|
||||
* Set when the message was posted in a chatroom, so its run is read
|
||||
* through the room's access.
|
||||
*/
|
||||
chatroom_id?: number;
|
||||
};
|
||||
|
||||
/**
|
||||
* The debug logs tab of a message's Details modal: what the run behind it
|
||||
* did, turn by turn and tool by tool, with the arguments it wrote and the
|
||||
* answers it read. Empty once the trace has been pruned (the app setting
|
||||
* `bot_trace_keep_days`), and for the messages the app writes itself (a
|
||||
* stop, a failure notice), which no run generated.
|
||||
*/
|
||||
export default function MessageDebugLogs({ message_id, chatroom_id }: Props) {
|
||||
const { jobs, loading, error, reload } = useMessageTrace({ message_id, chatroom_id });
|
||||
|
||||
if (error)
|
||||
return (
|
||||
<Stack className="w-full gap-1! items-start">
|
||||
<Span className="text-[13px] leading-[18px] text-ink-secondary">{error}</Span>
|
||||
<Button
|
||||
title="Read the debug logs again"
|
||||
type="button"
|
||||
variant="ghost"
|
||||
color="gray"
|
||||
size="smaller"
|
||||
onClick={() => {
|
||||
void reload();
|
||||
}}
|
||||
>
|
||||
Try again
|
||||
</Button>
|
||||
</Stack>
|
||||
);
|
||||
|
||||
if (!jobs)
|
||||
return (
|
||||
<Span className="text-[13px] leading-[18px] text-ink-secondary">
|
||||
{loading ? "Reading the run..." : "No debug logs were kept for this message."}
|
||||
</Span>
|
||||
);
|
||||
|
||||
if (!jobs.length)
|
||||
return (
|
||||
<Stack className="w-full gap-1! items-stretch">
|
||||
<Span className="text-[13px] leading-[18px] text-ink-secondary">
|
||||
No debug logs were kept for this message. The app writes some messages itself (a stop,
|
||||
a failed run's notice), and a run's logs are deleted after {AppData.BotTraceKeepDays}{" "}
|
||||
days.
|
||||
</Span>
|
||||
</Stack>
|
||||
);
|
||||
|
||||
return (
|
||||
<Stack className="w-full gap-4! items-stretch">
|
||||
<Row className="w-full flex-nowrap items-center justify-end">
|
||||
<CopyDebugLogsButton message_id={message_id} jobs={jobs} />
|
||||
</Row>
|
||||
<Stack className="w-full gap-6! items-stretch">
|
||||
{jobs.map((job) => (
|
||||
<TraceJobCard key={job.id} job={job} />
|
||||
))}
|
||||
</Stack>
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
@@ -1,14 +1,18 @@
|
||||
import { useState } from "react";
|
||||
import Divider from "@moduletrace/twui/layout/Divider";
|
||||
import Modal from "@moduletrace/twui/elements/Modal";
|
||||
import H2 from "@moduletrace/twui/layout/H2";
|
||||
import Row from "@moduletrace/twui/layout/Row";
|
||||
import Span from "@moduletrace/twui/layout/Span";
|
||||
import Spacer from "@moduletrace/twui/layout/Spacer";
|
||||
import Stack from "@moduletrace/twui/layout/Stack";
|
||||
import { Info } from "lucide-react";
|
||||
import useMessageDetails from "../(hooks)/use-message-details";
|
||||
import CopyMessageDetailsButton from "./copy-message-details-button";
|
||||
import MessageActionButton from "./message-action-button";
|
||||
import MessageDebugLogs from "./message-debug-logs";
|
||||
import MessageDetailsBody from "./message-details-body";
|
||||
import MessageDetailsTabButton from "./message-details-tab-button";
|
||||
|
||||
type Props = {
|
||||
message_id: number;
|
||||
@@ -28,10 +32,13 @@ type Props = {
|
||||
* 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.
|
||||
* cost - then, under "Debug logs", what the run did step by step (its
|
||||
* turns and what it reasoned, every tool call with its arguments and
|
||||
* answer), which is read only when that tab is opened.
|
||||
*/
|
||||
export default function MessageDetailsModal({ message_id, tool_log, chatroom_id }: Props) {
|
||||
const [open, set_open] = useState(false);
|
||||
const [tab, set_tab] = useState<"details" | "debug">("details");
|
||||
const { details, loading, error } = useMessageDetails({ message_id, enabled: open, chatroom_id });
|
||||
|
||||
return (
|
||||
@@ -44,27 +51,52 @@ export default function MessageDetailsModal({ message_id, tool_log, chatroom_id
|
||||
targetWrapperProps={{ className: "shrink-0" }}
|
||||
open={open}
|
||||
setOpen={set_open}
|
||||
className="max-w-xl bg-paper p-6"
|
||||
className="max-w-2xl bg-paper p-6"
|
||||
>
|
||||
<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} chatroom_id={chatroom_id} />
|
||||
</Row>
|
||||
<H2 className="text-lg! leading-6! tracking-normal! font-bold text-ink">Message details</H2>
|
||||
<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.
|
||||
How this answer was generated: the provider and model behind it, the settings they were called with,
|
||||
what it spent, and what its run did step by step.
|
||||
</Span>
|
||||
</Stack>
|
||||
|
||||
<Stack className="mt-4 max-h-[60vh] w-full gap-0! items-stretch overflow-y-auto">
|
||||
{details ? (
|
||||
<MessageDetailsBody details={details} tool_log={tool_log} />
|
||||
<Row className="mt-4 w-full gap-2! flex-nowrap items-center">
|
||||
<Row className="gap-0.5! p-0.5 flex-nowrap items-center rounded-default border border-solid border-hairline">
|
||||
<MessageDetailsTabButton
|
||||
label="Details"
|
||||
selected={tab == "details"}
|
||||
onSelect={() => set_tab("details")}
|
||||
/>
|
||||
<MessageDetailsTabButton
|
||||
label="Debug logs"
|
||||
selected={tab == "debug"}
|
||||
onSelect={() => set_tab("debug")}
|
||||
/>
|
||||
</Row>
|
||||
<Spacer />
|
||||
</Row>
|
||||
|
||||
<Divider className="mt-3 w-full border-hairline dark:border-hairline" />
|
||||
|
||||
<Stack className="mt-3 max-h-[60vh] w-full gap-0! items-stretch overflow-y-auto">
|
||||
{tab == "details" ? (
|
||||
<Stack className="w-full gap-3! items-stretch">
|
||||
<Row className="w-full flex-nowrap items-center justify-end">
|
||||
<CopyMessageDetailsButton message_id={message_id} chatroom_id={chatroom_id} />
|
||||
</Row>
|
||||
{details ? (
|
||||
<MessageDetailsBody details={details} tool_log={tool_log} />
|
||||
) : (
|
||||
<Span className="text-[13px] leading-[18px] text-ink-secondary">
|
||||
{loading || !error ? "Loading details..." : error}
|
||||
</Span>
|
||||
)}
|
||||
</Stack>
|
||||
) : (
|
||||
<Span className="text-[13px] leading-[18px] text-ink-secondary">
|
||||
{loading || !error ? "Loading details..." : error}
|
||||
</Span>
|
||||
<MessageDebugLogs message_id={message_id} chatroom_id={chatroom_id} />
|
||||
)}
|
||||
</Stack>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { renderToString } from "react-dom/server";
|
||||
import MessageDetailsTabButton from "./message-details-tab-button";
|
||||
|
||||
/**
|
||||
* The Details modal's tabs: the one showing is filled in ink with on-ink
|
||||
* text (readable in both themes), the other stays quiet.
|
||||
*/
|
||||
describe("MessageDetailsTabButton", () => {
|
||||
test("the selected tab is pressed and filled", () => {
|
||||
const html = renderToString(
|
||||
<MessageDetailsTabButton label="Debug logs" selected onSelect={() => {}} />,
|
||||
);
|
||||
|
||||
expect(html).toContain("Debug logs");
|
||||
expect(html).toContain("bg-ink");
|
||||
expect(html).toContain("text-on-ink");
|
||||
expect(html).toContain('aria-pressed="true"');
|
||||
});
|
||||
|
||||
test("the other tab is quiet until picked", () => {
|
||||
const html = renderToString(
|
||||
<MessageDetailsTabButton label="Details" selected={false} onSelect={() => {}} />,
|
||||
);
|
||||
|
||||
expect(html).toContain("Details");
|
||||
expect(html).not.toContain("text-on-ink");
|
||||
expect(html).toContain('aria-pressed="false"');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,37 @@
|
||||
import Button from "@moduletrace/twui/layout/Button";
|
||||
import { twMerge } from "tailwind-merge";
|
||||
|
||||
type Props = {
|
||||
label: string;
|
||||
selected: boolean;
|
||||
onSelect: () => void;
|
||||
};
|
||||
|
||||
/**
|
||||
* One tab of a message's Details modal: ink-filled while it is the one
|
||||
* showing, quiet otherwise (the way the usage page's range buttons read as
|
||||
* pressed), so the active tab is readable in both themes.
|
||||
*/
|
||||
export default function MessageDetailsTabButton({ label, selected, onSelect }: Props) {
|
||||
return (
|
||||
<Button
|
||||
title={label}
|
||||
type="button"
|
||||
size="small"
|
||||
variant="ghost"
|
||||
color="text"
|
||||
aria-pressed={selected}
|
||||
onClick={() => {
|
||||
if (!selected) onSelect();
|
||||
}}
|
||||
className={twMerge(
|
||||
"px-2.5! py-1! text-[12px]! rounded-default-xs",
|
||||
selected
|
||||
? "bg-ink dark:bg-ink hover:bg-ink dark:hover:bg-ink text-on-ink dark:text-on-ink cursor-default"
|
||||
: "text-ink-secondary dark:text-ink-secondary hover:bg-ink/5 dark:hover:bg-ink/5 hover:text-ink dark:hover:text-ink",
|
||||
)}
|
||||
>
|
||||
{label}
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
@@ -47,6 +47,19 @@ type Props = {
|
||||
* that doesn't wake the bot.
|
||||
*/
|
||||
no_reply_due?: boolean;
|
||||
/**
|
||||
* The session shown: the debug logs read the run it's working on.
|
||||
*/
|
||||
session_id?: number | null;
|
||||
/**
|
||||
* The debug logs under the thinking row, streaming what the run does.
|
||||
* The conversation keeps it, remembered per user.
|
||||
*/
|
||||
debug_open?: boolean;
|
||||
/**
|
||||
* Shows or hides the debug logs under the thinking row.
|
||||
*/
|
||||
on_toggle_debug?: () => void;
|
||||
/**
|
||||
* Shown after the messages, or in the middle of an empty thread, e.g.
|
||||
* that the bot has no model to answer with.
|
||||
@@ -98,6 +111,9 @@ export default function MessageThread({
|
||||
progress,
|
||||
reply_progress,
|
||||
receiving,
|
||||
session_id,
|
||||
debug_open,
|
||||
on_toggle_debug,
|
||||
has_task,
|
||||
moved_on,
|
||||
no_reply_due,
|
||||
@@ -171,6 +187,9 @@ export default function MessageThread({
|
||||
}
|
||||
receiving={receiving}
|
||||
has_task={has_task}
|
||||
session_id={session_id}
|
||||
debug_open={debug_open}
|
||||
on_toggle_debug={on_toggle_debug}
|
||||
/>
|
||||
</Stack>
|
||||
</Stack>
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { useContext } from "react";
|
||||
import Button from "@moduletrace/twui/layout/Button";
|
||||
import { twMerge } from "tailwind-merge";
|
||||
import { CircleStop } from "lucide-react";
|
||||
import { BotStopButtonLabel } from "@/src/dict/bot-queue-dict";
|
||||
import { StopBotContext } from "../(data)/stop-bot-context";
|
||||
@@ -56,6 +57,11 @@ export default function StopBotButton({ bot_name, menu, disabled }: Props) {
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* In the thinking row it's an icon beside the debug logs toggle, so the
|
||||
* row keeps its width for the line the bot is on; the menu still names
|
||||
* it.
|
||||
*/
|
||||
return (
|
||||
<Button
|
||||
title={title}
|
||||
@@ -67,13 +73,15 @@ export default function StopBotButton({ bot_name, menu, disabled }: Props) {
|
||||
disabled={off}
|
||||
loading={stopping}
|
||||
loadingIconSize="small"
|
||||
beforeIcon={<CircleStop size={14} aria-hidden />}
|
||||
onClick={() => {
|
||||
void stop();
|
||||
}}
|
||||
className="shrink-0 text-ink-secondary dark:text-ink-secondary hover:text-ink hover:dark:text-ink hover:bg-sunken hover:dark:bg-sunken rounded-default transition-colors duration-[var(--m-fast)] focus-visible:ring-2 focus-visible:ring-ink"
|
||||
className={twMerge(
|
||||
"shrink-0 p-1! text-ink-secondary dark:text-ink-secondary hover:text-ink hover:dark:text-ink hover:bg-sunken hover:dark:bg-sunken rounded-default transition-colors duration-[var(--m-fast)] focus-visible:ring-2 focus-visible:ring-ink",
|
||||
off && "opacity-40 cursor-not-allowed",
|
||||
)}
|
||||
>
|
||||
{BotStopButtonLabel}
|
||||
<CircleStop size={14} aria-hidden />
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
import { useState } from "react";
|
||||
import Button from "@moduletrace/twui/layout/Button";
|
||||
import CodeBlock from "@moduletrace/twui/elements/CodeBlock";
|
||||
import P from "@moduletrace/twui/layout/P";
|
||||
import Row from "@moduletrace/twui/layout/Row";
|
||||
import Span from "@moduletrace/twui/layout/Span";
|
||||
import Stack from "@moduletrace/twui/layout/Stack";
|
||||
import { twMerge } from "tailwind-merge";
|
||||
import { TracePreviewChars } from "../(utils)/trace-entry-view";
|
||||
|
||||
type Props = {
|
||||
/**
|
||||
* What the text is (why it reasoned, what it was sent, what it
|
||||
* answered), shown above it.
|
||||
*/
|
||||
label?: string;
|
||||
text: string;
|
||||
/**
|
||||
* Tool arguments and answers are code, so they keep their line breaks
|
||||
* and monospace; an answer or a note reads as prose.
|
||||
*/
|
||||
kind?: "text" | "code";
|
||||
};
|
||||
|
||||
/**
|
||||
* One block of text in a trace entry, cut after `TracePreviewChars` with a
|
||||
* way to open the rest: a tool's answer can be thousands of characters,
|
||||
* most of which nobody reads in a panel.
|
||||
*/
|
||||
export default function TraceBlock({ label, text, kind = "text" }: Props) {
|
||||
const [expanded, setExpanded] = useState(false);
|
||||
const long = text.length > TracePreviewChars;
|
||||
const shown = long && !expanded ? `${text.slice(0, TracePreviewChars)}` : text;
|
||||
|
||||
return (
|
||||
<Stack className="w-full gap-1 items-stretch">
|
||||
{label ? (
|
||||
<Span className="text-[11px] uppercase tracking-wide text-ink-secondary">
|
||||
{label}
|
||||
</Span>
|
||||
) : null}
|
||||
{kind == "code" ? (
|
||||
<CodeBlock>{shown}</CodeBlock>
|
||||
) : (
|
||||
<P className={twMerge("py-0 whitespace-pre-wrap text-sm text-ink")}>
|
||||
{shown}
|
||||
</P>
|
||||
)}
|
||||
{long ? (
|
||||
<Row className="w-full items-center gap-2">
|
||||
<Button
|
||||
title={expanded ? "Show less" : "Show the whole text"}
|
||||
type="button"
|
||||
variant="ghost"
|
||||
color="gray"
|
||||
size="smaller"
|
||||
onClick={() => setExpanded((open) => !open)}
|
||||
>
|
||||
{expanded
|
||||
? "Show less"
|
||||
: `Show all ${text.length.toLocaleString()} characters`}
|
||||
</Button>
|
||||
</Row>
|
||||
) : null}
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
import Row from "@moduletrace/twui/layout/Row";
|
||||
import Span from "@moduletrace/twui/layout/Span";
|
||||
import Stack from "@moduletrace/twui/layout/Stack";
|
||||
import type { BotTraceRow } from "@/src/types";
|
||||
import traceEntryView from "../(utils)/trace-entry-view";
|
||||
import TraceBlock from "./trace-block";
|
||||
import TraceMetaTag from "./trace-meta-tag";
|
||||
|
||||
type Props = {
|
||||
entry: BotTraceRow;
|
||||
};
|
||||
|
||||
/**
|
||||
* One thing a run did: a turn with what the model reasoned and answered,
|
||||
* a tool call with what it was sent and what it answered, or an event the
|
||||
* loop kept (it ran out of room, the answer was sent back, the user wrote
|
||||
* again).
|
||||
*/
|
||||
export default function TraceEntryRow({ entry }: Props) {
|
||||
const view = traceEntryView({ entry });
|
||||
|
||||
return (
|
||||
<Stack className="w-full gap-2 items-stretch">
|
||||
<Row className="w-full gap-1.5 items-center flex-wrap">
|
||||
<Span className="min-w-0 truncate text-sm font-medium leading-5 text-ink">
|
||||
{view.title}
|
||||
</Span>
|
||||
{view.meta.map((meta) => (
|
||||
<TraceMetaTag key={meta}>{meta}</TraceMetaTag>
|
||||
))}
|
||||
{view.failed ? (
|
||||
<TraceMetaTag color="error">failed</TraceMetaTag>
|
||||
) : null}
|
||||
</Row>
|
||||
{view.text ? <TraceBlock text={view.text} /> : null}
|
||||
{view.reasoning ? (
|
||||
<TraceBlock label="What it reasoned" text={view.reasoning} />
|
||||
) : null}
|
||||
{view.arguments ? (
|
||||
<TraceBlock label="What it was sent" kind="code" text={view.arguments} />
|
||||
) : null}
|
||||
{view.result ? (
|
||||
<TraceBlock label="What it answered" kind="code" text={view.result} />
|
||||
) : null}
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { renderToString } from "react-dom/server";
|
||||
import type { BotTraceRow } from "@/src/types";
|
||||
import TraceHoverDetails from "./trace-hover-details";
|
||||
|
||||
function row(overrides: Partial<BotTraceRow>): BotTraceRow {
|
||||
return {
|
||||
id: 1,
|
||||
created_at: 0,
|
||||
job_id: 1,
|
||||
bot_id: 1,
|
||||
kind: "tool",
|
||||
name: null,
|
||||
text: null,
|
||||
reasoning: null,
|
||||
arguments: null,
|
||||
result: null,
|
||||
metadata: null,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The strip cuts each step to one line; hovering reads it whole, from what
|
||||
* it was sent to what it answered.
|
||||
*/
|
||||
describe("TraceHoverDetails", () => {
|
||||
test("a tool call keeps its whole arguments and answer, uncut", () => {
|
||||
const long = "line\n".repeat(200);
|
||||
const html = renderToString(
|
||||
<TraceHoverDetails
|
||||
entry={row({
|
||||
name: "computer_bash",
|
||||
arguments: `{"command":"${long}"}`,
|
||||
result: `${long}done`,
|
||||
metadata: JSON.stringify({ index: 1, ok: true, duration_ms: 340 }),
|
||||
})}
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(html).toContain("computer_bash - 340ms");
|
||||
expect(html).toContain("Sent");
|
||||
expect(html).toContain("Answered");
|
||||
expect(html).toContain("done");
|
||||
expect(html).not.toContain("cut:");
|
||||
});
|
||||
|
||||
test("a turn shows what it reasoned before what it wrote", () => {
|
||||
const html = renderToString(
|
||||
<TraceHoverDetails
|
||||
entry={row({
|
||||
kind: "turn",
|
||||
reasoning: "Look at the tabs first.",
|
||||
text: "Two tabs are open.",
|
||||
metadata: JSON.stringify({ index: 0, tools: ["browser_tabs"] }),
|
||||
})}
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(html).toContain("Asked for: browser_tabs");
|
||||
expect(html).toContain("Reasoned");
|
||||
expect(html).toContain("Look at the tabs first.");
|
||||
expect(html).toContain("Wrote");
|
||||
expect(html).toContain("Two tabs are open.");
|
||||
expect(html.indexOf("Reasoned")).toBeLessThan(html.indexOf("Wrote"));
|
||||
});
|
||||
|
||||
test("a failed call says so in its title", () => {
|
||||
const html = renderToString(
|
||||
<TraceHoverDetails entry={row({ name: "read_file", result: "Error: gone", metadata: JSON.stringify({ ok: false }) })} />,
|
||||
);
|
||||
|
||||
expect(html).toContain("read_file (failed)");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,36 @@
|
||||
import Span from "@moduletrace/twui/layout/Span";
|
||||
import Stack from "@moduletrace/twui/layout/Stack";
|
||||
import type { BotTraceRow } from "@/src/types";
|
||||
import traceEntryView from "../(utils)/trace-entry-view";
|
||||
import TraceHoverSection from "./trace-hover-section";
|
||||
|
||||
type Props = {
|
||||
entry: BotTraceRow;
|
||||
};
|
||||
|
||||
/**
|
||||
* A step of the debug logs, whole: what the model reasoned before it
|
||||
* answered, what it wrote, what it asked the tools for, then what those
|
||||
* tools were sent and what they answered. The strip cuts each line to a
|
||||
* glance, so this is where the step is read in full (the card scrolls
|
||||
* rather than cutting anything).
|
||||
*/
|
||||
export default function TraceHoverDetails({ entry }: Props) {
|
||||
const view = traceEntryView({ entry });
|
||||
const summary = [view.failed ? `${view.title} (failed)` : view.title, view.duration].filter(Boolean).join(" - ");
|
||||
|
||||
return (
|
||||
<Stack className="w-full gap-2! items-stretch">
|
||||
<Span className="text-[11px] leading-4 font-medium text-ink">{summary}</Span>
|
||||
{view.tools?.length ? (
|
||||
<Span className="w-full text-[11px] leading-4 text-ink-secondary">{`Asked for: ${view.tools.join(", ")}`}</Span>
|
||||
) : null}
|
||||
{view.reasoning ? <TraceHoverSection label="Reasoned" text={view.reasoning} /> : null}
|
||||
{view.arguments ? <TraceHoverSection label="Sent" text={view.arguments} code /> : null}
|
||||
{view.text ? (
|
||||
<TraceHoverSection label={entry.kind == "event" ? "What happened" : "Wrote"} text={view.text} />
|
||||
) : null}
|
||||
{view.result ? <TraceHoverSection label="Answered" text={view.result} code /> : null}
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
import Span from "@moduletrace/twui/layout/Span";
|
||||
import Stack from "@moduletrace/twui/layout/Stack";
|
||||
import { twMerge } from "tailwind-merge";
|
||||
|
||||
type Props = {
|
||||
label: string;
|
||||
text: string;
|
||||
/**
|
||||
* Code is kept as written (indentation and all), in a monospaced face.
|
||||
*/
|
||||
code?: boolean;
|
||||
};
|
||||
|
||||
/**
|
||||
* One labelled part of a step in the debug logs' hover card: what it
|
||||
* reasoned, what it was sent, what it answered. Never cut: the card scrolls
|
||||
* instead.
|
||||
*/
|
||||
export default function TraceHoverSection({ label, text, code }: Props) {
|
||||
return (
|
||||
<Stack className="w-full gap-0.5! items-stretch">
|
||||
<Span className="text-[10px] leading-3 uppercase tracking-wide text-ink-secondary">{label}</Span>
|
||||
<Span
|
||||
className={twMerge(
|
||||
"w-full whitespace-pre-wrap break-words text-[11.5px] leading-4 text-ink",
|
||||
code && "font-mono",
|
||||
)}
|
||||
>
|
||||
{text}
|
||||
</Span>
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
import Row from "@moduletrace/twui/layout/Row";
|
||||
import Span from "@moduletrace/twui/layout/Span";
|
||||
import Stack from "@moduletrace/twui/layout/Stack";
|
||||
import type { BotTraceJob } from "@/src/types";
|
||||
import relativeTime from "@/src/utils/relative-time";
|
||||
import traceJobView from "../(utils)/trace-job-view";
|
||||
import TraceEntryRow from "./trace-entry-row";
|
||||
import TraceMetaTag from "./trace-meta-tag";
|
||||
|
||||
type Props = {
|
||||
job: BotTraceJob;
|
||||
};
|
||||
|
||||
/**
|
||||
* One traced run: what it was, when it started and the state it was left
|
||||
* in, over everything it did in order (its turns, their tool calls and the
|
||||
* loop's own events).
|
||||
*/
|
||||
export default function TraceJobCard({ job }: Props) {
|
||||
const view = traceJobView({ job });
|
||||
|
||||
return (
|
||||
<Stack className="w-full gap-2.5 items-stretch">
|
||||
<Row className="w-full gap-1.5 items-center flex-wrap">
|
||||
<Span className="min-w-0 truncate text-sm font-semibold leading-5 text-ink">
|
||||
{view.title}
|
||||
</Span>
|
||||
<TraceMetaTag>{view.kind_label}</TraceMetaTag>
|
||||
<TraceMetaTag color={view.status_color}>
|
||||
{view.status_label}
|
||||
</TraceMetaTag>
|
||||
<Span className="ml-auto shrink-0 text-[11px] leading-4 text-ink-secondary">
|
||||
{relativeTime({ at: job.created_at })}
|
||||
</Span>
|
||||
</Row>
|
||||
<Stack className="w-full gap-3 items-stretch">
|
||||
{job.traces.map((entry) => (
|
||||
<TraceEntryRow key={entry.id} entry={entry} />
|
||||
))}
|
||||
</Stack>
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { renderToString } from "react-dom/server";
|
||||
import type { BotTraceRow } from "@/src/types";
|
||||
import TraceLogLine from "./trace-log-line";
|
||||
|
||||
function row(overrides: Partial<BotTraceRow>): BotTraceRow {
|
||||
return {
|
||||
id: 1,
|
||||
created_at: 0,
|
||||
job_id: 1,
|
||||
bot_id: 1,
|
||||
kind: "tool",
|
||||
name: null,
|
||||
text: null,
|
||||
reasoning: null,
|
||||
arguments: null,
|
||||
result: null,
|
||||
metadata: null,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The debug logs stream one line per step: what ran, a glance at what it
|
||||
* answered, and how long it took, with the line cut rather than wrapped so
|
||||
* a long tool answer never pushes the next step off screen.
|
||||
*/
|
||||
describe("TraceLogLine", () => {
|
||||
test("a tool call reads as its name, a cut-down preview and its time", () => {
|
||||
const html = renderToString(
|
||||
<TraceLogLine
|
||||
entry={row({
|
||||
name: "computer_bash",
|
||||
arguments: `{"command":"ls"}`,
|
||||
result: "first line\nsecond line",
|
||||
metadata: JSON.stringify({ index: 1, ok: true, duration_ms: 340 }),
|
||||
})}
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(html).toContain("computer_bash");
|
||||
expect(html).toContain("first line second line");
|
||||
expect(html).toContain("340ms");
|
||||
expect(html).toContain("truncate");
|
||||
});
|
||||
|
||||
test("a turn with no text still takes a line, with its number", () => {
|
||||
const html = renderToString(
|
||||
<TraceLogLine entry={row({ kind: "turn", metadata: JSON.stringify({ index: 3 }) })} />,
|
||||
);
|
||||
|
||||
expect(html).toContain("Turn 4");
|
||||
expect(html).toContain("-");
|
||||
});
|
||||
|
||||
test("a failed call keeps its answer readable", () => {
|
||||
const html = renderToString(
|
||||
<TraceLogLine
|
||||
entry={row({
|
||||
name: "read_file",
|
||||
result: "Error: no such file",
|
||||
metadata: JSON.stringify({ index: 0, ok: false, duration_ms: 12 }),
|
||||
})}
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(html).toContain("Error: no such file");
|
||||
expect(html).toContain("12ms");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,68 @@
|
||||
import Popover from "@moduletrace/twui/elements/Popover";
|
||||
import Row from "@moduletrace/twui/layout/Row";
|
||||
import Span from "@moduletrace/twui/layout/Span";
|
||||
import { twMerge } from "tailwind-merge";
|
||||
import type { BotTraceRow } from "@/src/types";
|
||||
import traceEntryView from "../(utils)/trace-entry-view";
|
||||
import TraceHoverDetails from "./trace-hover-details";
|
||||
|
||||
type Props = {
|
||||
entry: BotTraceRow;
|
||||
};
|
||||
|
||||
/**
|
||||
* One line of the debug logs under the thinking row: what the run just did,
|
||||
* in the order it did it. Turn, tool and event names are fixed-width, so a
|
||||
* stream of them reads as a column, and the detail is cut to the line.
|
||||
*
|
||||
* Hovering the line opens the step whole (`TraceHoverDetails`): what the
|
||||
* model reasoned and wrote, what the tool was sent and what it answered,
|
||||
* which is more than a line can say and more than the running strip should
|
||||
* spend its height on.
|
||||
*
|
||||
* It is read by leaving the line and entering the card, so the card sits
|
||||
* against the line (`-mb-2` cancels the 8px gap twui leaves above a target)
|
||||
* and stays up for `debounce` after the pointer leaves either of them, long
|
||||
* enough to cross over. That delay is the closing one: twui opens on enter.
|
||||
*/
|
||||
export default function TraceLogLine({ entry }: Props) {
|
||||
const view = traceEntryView({ entry });
|
||||
const preview = (view.text || view.result || view.arguments || "").replace(/\s+/g, " ").trim();
|
||||
|
||||
return (
|
||||
<Popover
|
||||
trigger="hover"
|
||||
position="top"
|
||||
debounce={600}
|
||||
targetWrapperProps={{ className: "w-full shrink-0" }}
|
||||
target={
|
||||
<Row
|
||||
className={twMerge(
|
||||
"w-full flex-nowrap items-baseline gap-2! py-0.5",
|
||||
view.failed && "text-ink",
|
||||
)}
|
||||
>
|
||||
<Span
|
||||
className={twMerge(
|
||||
"shrink-0 w-[86px] truncate text-[11px] leading-4 text-ink-disabled",
|
||||
view.failed && "text-ink-secondary",
|
||||
)}
|
||||
>
|
||||
{view.title}
|
||||
</Span>
|
||||
<Span className="min-w-0 grow truncate text-xs leading-4 text-ink-secondary">
|
||||
{preview || "-"}
|
||||
</Span>
|
||||
{view.duration ? (
|
||||
<Span className="shrink-0 text-[11px] leading-4 text-ink-disabled">
|
||||
{view.duration}
|
||||
</Span>
|
||||
) : null}
|
||||
</Row>
|
||||
}
|
||||
className="w-[440px] max-w-[92vw] max-h-[320px] -mb-2 overflow-y-auto p-3 gap-2! bg-surface dark:bg-surface border-hairline dark:border-hairline rounded-default shadow-popover"
|
||||
>
|
||||
<TraceHoverDetails entry={entry} />
|
||||
</Popover>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
import type { ReactNode } from "react";
|
||||
import Tag from "@moduletrace/twui/elements/Tag";
|
||||
import type { TWUIButtonColorType } from "@moduletrace/twui/layout/Button";
|
||||
import { twMerge } from "tailwind-merge";
|
||||
|
||||
type Props = {
|
||||
children: ReactNode;
|
||||
color?: TWUIButtonColorType;
|
||||
};
|
||||
|
||||
/**
|
||||
* One of the small values a trace entry shows beside its title (the model,
|
||||
* how long it took, how many images a call returned).
|
||||
*/
|
||||
export default function TraceMetaTag({ children, color = "gray" }: Props) {
|
||||
return (
|
||||
<Tag
|
||||
color={color}
|
||||
variant="outlined"
|
||||
className={twMerge("shrink-0 text-[11px] leading-4 whitespace-nowrap")}
|
||||
>
|
||||
{children}
|
||||
</Tag>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { renderToString } from "react-dom/server";
|
||||
import TracePanel from "./trace-panel";
|
||||
|
||||
/**
|
||||
* The debug logs sit under the thinking row as a fixed-height strip, so the
|
||||
* thread above keeps its place while a run streams into it.
|
||||
*/
|
||||
describe("TracePanel", () => {
|
||||
test("a quarter-screen strip with nothing to stream yet", () => {
|
||||
const html = renderToString(<TracePanel session_id={null} open />);
|
||||
|
||||
expect(html).toContain("h-[250px]");
|
||||
expect(html).toContain('aria-label="Debug logs"');
|
||||
expect(html).toContain("Nothing is running here.");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,113 @@
|
||||
import { useEffect, useMemo, useRef, type RefObject } from "react";
|
||||
import Button from "@moduletrace/twui/layout/Button";
|
||||
import Row from "@moduletrace/twui/layout/Row";
|
||||
import Span from "@moduletrace/twui/layout/Span";
|
||||
import Stack from "@moduletrace/twui/layout/Stack";
|
||||
import useBotTrace from "../(hooks)/use-bot-trace";
|
||||
import TraceLogLine from "./trace-log-line";
|
||||
|
||||
type Props = {
|
||||
/**
|
||||
* The session the thinking row belongs to: the run it shows is one of
|
||||
* this session's jobs.
|
||||
*/
|
||||
session_id?: number | null;
|
||||
/**
|
||||
* The logs are on screen. Nothing is read, and no push is taken, while
|
||||
* it's closed.
|
||||
*/
|
||||
open: boolean;
|
||||
};
|
||||
|
||||
/**
|
||||
* How far from the bottom the logs still follow new lines: a little slack,
|
||||
* so a line that just landed doesn't stop them.
|
||||
*/
|
||||
const FollowSlackPx = 24;
|
||||
|
||||
/**
|
||||
* The debug logs under the thinking row: what the run working right now
|
||||
* did, turn by turn and tool by tool, as it goes. A quarter-screen tall
|
||||
* strip that follows its newest line while it's scrolled to the bottom,
|
||||
* and stays where the user scrolled when it isn't. Once the run ends the
|
||||
* strip goes with the thinking row, and its log is under the response's
|
||||
* Details > Debug logs (`grabMessageTraces`).
|
||||
*/
|
||||
export default function TracePanel({ session_id, open }: Props) {
|
||||
const { jobs, loading, error, reload } = useBotTrace({ session_id, open });
|
||||
const scroll_ref = useRef<HTMLDivElement | null>(null);
|
||||
const follow = useRef(true);
|
||||
|
||||
const job = useMemo(
|
||||
() => jobs.find((run) => run.status == "processing") || jobs.find((run) => run.status == "pending"),
|
||||
[jobs],
|
||||
);
|
||||
const entries = job?.traces || [];
|
||||
const newest = entries[entries.length - 1]?.id;
|
||||
|
||||
useEffect(() => {
|
||||
if (!follow.current) return;
|
||||
|
||||
const element = scroll_ref.current;
|
||||
|
||||
if (element) element.scrollTop = element.scrollHeight;
|
||||
}, [newest, open]);
|
||||
|
||||
return (
|
||||
<Stack
|
||||
role="region"
|
||||
aria-label="Debug logs"
|
||||
className="w-full h-[250px] mt-2 gap-0! items-stretch overflow-hidden rounded-default border border-solid border-hairline bg-surface"
|
||||
>
|
||||
<Row className="w-full shrink-0 flex-nowrap items-center gap-2! border-0 border-b border-solid border-hairline px-3 py-1.5">
|
||||
<Span className="text-[11px] leading-4 uppercase tracking-wide text-ink-secondary">
|
||||
Debug logs
|
||||
</Span>
|
||||
{job?.status == "processing" ? (
|
||||
<Span className="ml-auto text-[11px] leading-4 text-ink-disabled">Live</Span>
|
||||
) : null}
|
||||
</Row>
|
||||
<Stack
|
||||
componentRef={scroll_ref as RefObject<HTMLDivElement>}
|
||||
onScroll={() => {
|
||||
const element = scroll_ref.current;
|
||||
|
||||
if (!element) return;
|
||||
|
||||
follow.current =
|
||||
element.scrollHeight - element.scrollTop - element.clientHeight <=
|
||||
FollowSlackPx;
|
||||
}}
|
||||
className="grow min-h-0 gap-0! items-stretch overflow-y-auto overscroll-contain px-3 py-2"
|
||||
>
|
||||
{error ? (
|
||||
<Stack className="w-full gap-1! items-start">
|
||||
<Span className="text-xs leading-4 text-ink-secondary">{error}</Span>
|
||||
<Button
|
||||
title="Read the logs again"
|
||||
type="button"
|
||||
variant="ghost"
|
||||
color="gray"
|
||||
size="smaller"
|
||||
onClick={() => {
|
||||
void reload();
|
||||
}}
|
||||
>
|
||||
Try again
|
||||
</Button>
|
||||
</Stack>
|
||||
) : entries.length ? (
|
||||
entries.map((entry) => <TraceLogLine key={entry.id} entry={entry} />)
|
||||
) : (
|
||||
<Span className="text-xs leading-4 text-ink-secondary">
|
||||
{loading && !job
|
||||
? "Reading the run..."
|
||||
: job
|
||||
? "Waiting for the bot's first step..."
|
||||
: "Nothing is running here."}
|
||||
</Span>
|
||||
)}
|
||||
</Stack>
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import isAwaitingReply from "../(utils)/is-awaiting-reply";
|
||||
import Stack from "@moduletrace/twui/layout/Stack";
|
||||
import type { BotMessageReactionEmoji } from "@/src/dict/bot-dict";
|
||||
import type {
|
||||
BotJobUpdateData,
|
||||
BotMessageReactionData,
|
||||
BotMessageWithAttachments,
|
||||
} from "@/src/types";
|
||||
@@ -35,6 +36,7 @@ import useReplyCatchUp from "../(hooks)/use-reply-catch-up";
|
||||
import useSpeakMessage from "../(hooks)/use-speak-message";
|
||||
import useOlderMessages from "../(hooks)/use-older-messages";
|
||||
import ConversationHeader from "../(partials)/conversation-header";
|
||||
import useDebugOpen from "../(hooks)/use-debug-open";
|
||||
import MessageThread from "../(partials)/message-thread";
|
||||
import Composer, { type ComposerHandle } from "../(partials)/composer";
|
||||
import ComputerViewerModal from "../(partials)/computer-viewer-modal";
|
||||
@@ -75,6 +77,12 @@ export default function Conversation() {
|
||||
const [messages, setMessages] = useState<BotMessageWithAttachments[]>(
|
||||
[],
|
||||
);
|
||||
/**
|
||||
* The step the reply running when the history loaded is on, read with
|
||||
* it so a refreshed thread shows the run's line straight away instead
|
||||
* of only the thinking row's label until its next push.
|
||||
*/
|
||||
const [reply_step, setReplyStep] = useState<BotJobUpdateData | null>(null);
|
||||
/**
|
||||
* Messages sent here that the server hasn't confirmed yet, shown after
|
||||
* the saved ones so a slow connection never hides what was typed. They
|
||||
@@ -92,6 +100,14 @@ export default function Conversation() {
|
||||
*/
|
||||
const [moved_to_session_id, setMovedToSessionId] = useState<number | null>(null);
|
||||
const [has_other_unread, setHasOtherUnread] = useState(false);
|
||||
/**
|
||||
* The debug logs under the thinking row, which its bug button toggles.
|
||||
* Remembered per user, so it stays as they left it in every
|
||||
* conversation (`useDebugOpen`).
|
||||
*/
|
||||
const { open: debug_open, setOpen: set_debug_open } = useDebugOpen({
|
||||
user_id: pageProps?.user?.id,
|
||||
});
|
||||
/**
|
||||
* The text model the bot runs on here; none shows a notice in the
|
||||
* thread. A save in the models modal updates it.
|
||||
@@ -202,6 +218,7 @@ export default function Conversation() {
|
||||
previous_session_id: Number(history.session.previous_session_id) || null,
|
||||
});
|
||||
progress.reset({ task: history.task });
|
||||
setReplyStep(history.step || null);
|
||||
},
|
||||
});
|
||||
|
||||
@@ -228,6 +245,7 @@ export default function Conversation() {
|
||||
bot_id: bot?.id || 0,
|
||||
session_id,
|
||||
last_message_id: last_saved_id,
|
||||
seed: reply_step,
|
||||
});
|
||||
|
||||
useReplyCatchUp({
|
||||
@@ -443,6 +461,11 @@ export default function Conversation() {
|
||||
receiving={pending_messages.length > 0}
|
||||
has_task={Boolean(progress.task_id)}
|
||||
moved_on={Boolean(moved_to_session_id)}
|
||||
session_id={session_id}
|
||||
debug_open={debug_open}
|
||||
on_toggle_debug={() =>
|
||||
set_debug_open(!debug_open)
|
||||
}
|
||||
no_reply_due={no_reply_due}
|
||||
notice={
|
||||
!text_model && !history.loading ? (
|
||||
@@ -528,8 +551,6 @@ export default function Conversation() {
|
||||
);
|
||||
|
||||
return (
|
||||
<StopBotContext.Provider value={stop_state}>
|
||||
{thread}
|
||||
</StopBotContext.Provider>
|
||||
<StopBotContext.Provider value={stop_state}>{thread}</StopBotContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import isNewerStep from "./is-newer-step";
|
||||
|
||||
/**
|
||||
* A row that reloads mid-run reads the reply's step from the server while a
|
||||
* live push may already show a later one: the line only moves forward.
|
||||
*/
|
||||
describe("isNewerStep", () => {
|
||||
test("the first step is taken", () => {
|
||||
expect(isNewerStep({ shown: null, step: { id: 7 } })).toBe(true);
|
||||
});
|
||||
|
||||
test("a later step replaces the one shown", () => {
|
||||
expect(isNewerStep({ shown: { id: 7 }, step: { id: 8 } })).toBe(true);
|
||||
});
|
||||
|
||||
test("an older one read from the server leaves the newer push alone", () => {
|
||||
expect(isNewerStep({ shown: { id: 8 }, step: { id: 7 } })).toBe(false);
|
||||
});
|
||||
|
||||
test("the same step read again changes nothing", () => {
|
||||
expect(isNewerStep({ shown: { id: 8 }, step: { id: 8 } })).toBe(false);
|
||||
});
|
||||
|
||||
test("no step takes nothing", () => {
|
||||
expect(isNewerStep({ shown: { id: 8 }, step: null })).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,27 @@
|
||||
type Step = {
|
||||
id: number | string;
|
||||
};
|
||||
|
||||
type Params = {
|
||||
/**
|
||||
* The step the thinking row shows.
|
||||
*/
|
||||
shown: Step | null;
|
||||
/**
|
||||
* The step that arrived: pushed live, replayed by the catch-up, or
|
||||
* read with the history.
|
||||
*/
|
||||
step: Step | null;
|
||||
};
|
||||
|
||||
/**
|
||||
* Whether a step replaces the one on screen. Steps arrive by push and are
|
||||
* also read from the server (a reload's history, the catch-up's replay), so
|
||||
* one read just before a newer push reached the page must not take the
|
||||
* thinking row's line back: rows only ever move forward.
|
||||
*/
|
||||
export default function isNewerStep({ shown, step }: Params) {
|
||||
if (!step) return false;
|
||||
|
||||
return !shown || Number(step.id) > Number(shown.id);
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import type { BotTraceJob, BotTraceRow } from "@/src/types";
|
||||
import messageDebugLogsMarkdown from "./message-debug-logs-markdown";
|
||||
|
||||
function row(overrides: Partial<BotTraceRow>): BotTraceRow {
|
||||
return {
|
||||
id: 1,
|
||||
created_at: 0,
|
||||
job_id: 1,
|
||||
bot_id: 1,
|
||||
kind: "turn",
|
||||
name: null,
|
||||
text: null,
|
||||
reasoning: null,
|
||||
arguments: null,
|
||||
result: null,
|
||||
metadata: null,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function job(traces: BotTraceRow[], overrides: Partial<BotTraceJob> = {}): BotTraceJob {
|
||||
return { id: 1, kind: "reply", title: null, status: "completed", created_at: 0, traces, ...overrides };
|
||||
}
|
||||
|
||||
const format_time = (time: number) => `t${time}`;
|
||||
|
||||
describe("messageDebugLogsMarkdown", () => {
|
||||
test("names the message and every step in order", () => {
|
||||
const markdown = messageDebugLogsMarkdown({
|
||||
message_id: 485,
|
||||
now: 9,
|
||||
format_time,
|
||||
jobs: [
|
||||
job([
|
||||
row({
|
||||
kind: "turn",
|
||||
text: "Looking at the tabs.",
|
||||
reasoning: "Check the browser first.",
|
||||
metadata: JSON.stringify({
|
||||
index: 0,
|
||||
model: "gpt-x",
|
||||
duration_ms: 1200,
|
||||
tools: ["browser_tabs"],
|
||||
}),
|
||||
}),
|
||||
row({
|
||||
id: 2,
|
||||
kind: "tool",
|
||||
name: "browser_tabs",
|
||||
arguments: `{"action":"list"}`,
|
||||
result: "three tabs",
|
||||
metadata: JSON.stringify({ index: 0, ok: true, duration_ms: 340 }),
|
||||
}),
|
||||
]),
|
||||
],
|
||||
});
|
||||
|
||||
expect(markdown).toContain("# Debug logs");
|
||||
expect(markdown).toContain("- Message: #485");
|
||||
expect(markdown).toContain("## Reply (reply, finished)");
|
||||
expect(markdown).toContain("### Turn 1");
|
||||
expect(markdown).toContain("gpt-x, 1.2s, 1 tools");
|
||||
expect(markdown).toContain("Asked for: browser_tabs");
|
||||
expect(markdown).toContain("**Reasoned**");
|
||||
expect(markdown).toContain("Check the browser first.");
|
||||
expect(markdown).toContain("### browser_tabs");
|
||||
expect(markdown).toContain("**Arguments**");
|
||||
expect(markdown).toContain(`{"action":"list"}`);
|
||||
expect(markdown).toContain("three tabs");
|
||||
});
|
||||
|
||||
test("a failed call says so, and an empty run says it kept nothing", () => {
|
||||
const markdown = messageDebugLogsMarkdown({
|
||||
message_id: 7,
|
||||
now: 0,
|
||||
format_time,
|
||||
jobs: [
|
||||
job([row({ kind: "tool", name: "read_file", result: "Error: gone", metadata: JSON.stringify({ ok: false }) })]),
|
||||
job([], { id: 2, kind: "task", title: "The audit", status: "failed" }),
|
||||
],
|
||||
});
|
||||
|
||||
expect(markdown).toContain("### read_file (failed)");
|
||||
expect(markdown).toContain("Error: gone");
|
||||
expect(markdown).toContain("## The audit (task, failed)");
|
||||
expect(markdown).toContain("No steps were kept for this run.");
|
||||
});
|
||||
|
||||
test("text holding a fence of its own is fenced longer", () => {
|
||||
const markdown = messageDebugLogsMarkdown({
|
||||
message_id: 1,
|
||||
now: 0,
|
||||
format_time,
|
||||
jobs: [job([row({ kind: "tool", name: "read_file", result: "```js\nconst a = 1;\n```" })])],
|
||||
});
|
||||
|
||||
expect(markdown).toContain("````\n```js\nconst a = 1;\n```\n````");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,96 @@
|
||||
import type { BotTraceJob } from "@/src/types";
|
||||
import traceEntryView from "./trace-entry-view";
|
||||
import traceJobView from "./trace-job-view";
|
||||
|
||||
type Params = {
|
||||
/**
|
||||
* The message the logs belong to, named at the top.
|
||||
*/
|
||||
message_id: number;
|
||||
/**
|
||||
* The runs behind it, oldest first, as the debug logs tab reads them.
|
||||
*/
|
||||
jobs: BotTraceJob[];
|
||||
/**
|
||||
* When the copy was made.
|
||||
*/
|
||||
now: number;
|
||||
/**
|
||||
* A timestamp as the reader sees it; local time by default.
|
||||
*/
|
||||
format_time?: (time: number) => string;
|
||||
};
|
||||
|
||||
/**
|
||||
* A message's debug logs as one markdown document, for a bug report or a
|
||||
* note: every run behind it, then each step in order - what it was sent,
|
||||
* what it reasoned, what it asked the tools for and what they answered.
|
||||
*
|
||||
* Fences are made longer than any run of backticks in the text, so a
|
||||
* result that holds markdown code of its own never closes its block.
|
||||
*/
|
||||
export default function messageDebugLogsMarkdown({
|
||||
message_id,
|
||||
jobs,
|
||||
now,
|
||||
format_time = (time) =>
|
||||
new Date(time).toLocaleString(undefined, {
|
||||
dateStyle: "medium",
|
||||
timeStyle: "short",
|
||||
}),
|
||||
}: Params) {
|
||||
const out: string[] = [
|
||||
"# Debug logs",
|
||||
"",
|
||||
`- Message: #${message_id}`,
|
||||
`- Runs: ${jobs.length}`,
|
||||
`- Copied: ${format_time(now)}`,
|
||||
"",
|
||||
];
|
||||
|
||||
for (const job of jobs) {
|
||||
const view = traceJobView({ job });
|
||||
|
||||
out.push(`## ${view.title} (${view.kind_label}, ${view.status_label})`, "");
|
||||
|
||||
if (job.created_at) out.push(`Started ${format_time(job.created_at)}`, "");
|
||||
|
||||
if (!job.traces.length) out.push("No steps were kept for this run.", "");
|
||||
|
||||
for (const entry of job.traces) out.push(...entryLines({ entry, format_time }));
|
||||
}
|
||||
|
||||
return `${out.join("\n").trimEnd()}\n`;
|
||||
}
|
||||
|
||||
function entryLines({ entry, format_time }: { entry: BotTraceJob["traces"][number]; format_time: (time: number) => string }) {
|
||||
const view = traceEntryView({ entry });
|
||||
const out: string[] = [`### ${view.title}${view.failed ? " (failed)" : ""}`, ""];
|
||||
|
||||
if (entry.created_at) out.push(`At ${format_time(entry.created_at)}`, "");
|
||||
|
||||
if (view.meta.length) out.push(view.meta.join(", "), "");
|
||||
|
||||
if (view.tools?.length) out.push(`Asked for: ${view.tools.join(", ")}`, "");
|
||||
|
||||
if (view.reasoning) out.push("**Reasoned**", "", fence({ text: view.reasoning }), "");
|
||||
|
||||
if (view.text) out.push(entry.kind == "event" ? "**What happened**" : "**Answered**", "", fence({ text: view.text }), "");
|
||||
|
||||
if (view.arguments) out.push("**Arguments**", "", fence({ text: view.arguments, language: "json" }), "");
|
||||
|
||||
if (view.result) out.push("**Answer**", "", fence({ text: view.result }), "");
|
||||
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* The text in a fenced block, with a fence longer than any backticks it
|
||||
* holds.
|
||||
*/
|
||||
function fence({ text, language = "" }: { text: string; language?: string }) {
|
||||
const longest = Math.max(0, ...(text.match(/`+/g) || []).map((run) => run.length));
|
||||
const marker = "`".repeat(Math.max(3, longest + 1));
|
||||
|
||||
return `${marker}${language}\n${text}\n${marker}`;
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import type { BotTraceRow } from "@/src/types";
|
||||
import traceEntryView from "./trace-entry-view";
|
||||
|
||||
function row(overrides: Partial<BotTraceRow>): BotTraceRow {
|
||||
return {
|
||||
id: 1,
|
||||
created_at: 0,
|
||||
job_id: 1,
|
||||
bot_id: 1,
|
||||
kind: "turn",
|
||||
name: null,
|
||||
text: null,
|
||||
reasoning: null,
|
||||
arguments: null,
|
||||
result: null,
|
||||
metadata: null,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe("traceEntryView", () => {
|
||||
test("numbers a turn from its one-based step and shows the model, time and tools", () => {
|
||||
expect(
|
||||
traceEntryView({
|
||||
entry: row({
|
||||
metadata: JSON.stringify({
|
||||
index: 2,
|
||||
model: "gpt-x",
|
||||
duration_ms: 1200,
|
||||
tools: ["a", "b"],
|
||||
finish_reason: "length",
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
).toEqual({
|
||||
title: "Turn 3",
|
||||
meta: ["gpt-x", "1.2s", "2 tools", "length"],
|
||||
text: undefined,
|
||||
reasoning: undefined,
|
||||
duration: "1.2s",
|
||||
tools: ["a", "b"],
|
||||
failed: false,
|
||||
});
|
||||
});
|
||||
|
||||
test("leaves out a `stop` finish reason and a missing duration", () => {
|
||||
expect(
|
||||
traceEntryView({ entry: row({ metadata: JSON.stringify({ index: 0, finish_reason: "stop" }) }) }),
|
||||
).toMatchObject({ title: "Turn 1", meta: [], duration: undefined });
|
||||
});
|
||||
|
||||
test("a tool call is its name, marked failed only when the app said so", () => {
|
||||
expect(
|
||||
traceEntryView({
|
||||
entry: row({
|
||||
kind: "tool",
|
||||
name: "computer_bash",
|
||||
arguments: "{}",
|
||||
result: "Error: nope",
|
||||
metadata: JSON.stringify({ ok: false, duration_ms: 40 }),
|
||||
}),
|
||||
}),
|
||||
).toMatchObject({
|
||||
title: "computer_bash",
|
||||
arguments: "{}",
|
||||
result: "Error: nope",
|
||||
failed: true,
|
||||
meta: ["40ms"],
|
||||
});
|
||||
|
||||
expect(
|
||||
traceEntryView({
|
||||
entry: row({
|
||||
kind: "tool",
|
||||
name: "read_file",
|
||||
result: "ok",
|
||||
metadata: JSON.stringify({ ok: true, repeat_of: 2, images: 1 }),
|
||||
}),
|
||||
}),
|
||||
).toMatchObject({ failed: false, meta: ["1 images", "already read"] });
|
||||
});
|
||||
|
||||
test("an event reads as words, not as its name", () => {
|
||||
expect(
|
||||
traceEntryView({
|
||||
entry: row({ kind: "event", name: "wrap_up", text: "Out of steps." }),
|
||||
}),
|
||||
).toMatchObject({ title: "Out of room: last turn", text: "Out of steps." });
|
||||
|
||||
expect(
|
||||
traceEntryView({ entry: row({ kind: "event", name: "something_new" }) }),
|
||||
).toMatchObject({ title: "something_new" });
|
||||
});
|
||||
|
||||
test("a broken metadata blob is no metadata, never a crash", () => {
|
||||
expect(traceEntryView({ entry: row({ metadata: "{not json" }) })).toMatchObject({
|
||||
title: "Turn 1",
|
||||
meta: [],
|
||||
});
|
||||
});
|
||||
});
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user