Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ec999cccc3 | ||
|
|
352f11b5d1 | ||
|
|
0151ca6e55 | ||
|
|
baeb9a80d3 | ||
|
|
984ad702d6 | ||
|
|
09039bee22 |
@@ -95,20 +95,20 @@ Enables SQLite foreign keys (`enableForeignKeys`), `bunextInit()`, `ensureDocker
|
||||
- **Conversation loading:** pages render everything server-side (`grabConversationProps`) **except the history**, which the client loads (`api/admin/bots/conversation-history`, merged with what's already shown, refetched on bfcache restore) and pages older messages on scroll. Rail lists go through `railBots`/`railWorkspaces` (no prompts/memory, previews cut). 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; the gesture is a plain state machine in `(utils)/pull-to-refresh-gesture.ts`, its steps tested without a browser, which takes the pull's anchor the moment the thread reaches its end, so one swipe that runs out of conversation hands over instead of stopping dead, and reads the end with `AppData.PullToRefreshEndSlackPx` of slack through `atThreadEnd`, since a phone's fractional device pixel ratio leaves the content a hair short and demanding an exact zero made the whole gesture do nothing; `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, up to `BotMessageMaxCharsMax`), checked by the composer before it sends (the reason shows under the input) and again by the route (`messageTooLongMessage` says how far over it is and to attach the text as a file). Once stored, a message is never cut: it goes into every turn whole.
|
||||
- **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), `[plan:ID]` (a plan, as its card: steps, the one being worked, and the buttons to approve or change them), `[graphic:ID]` (a bot graphic, framed inline), `[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`. A chip reads its own row through `(utils)/ref-view-loader.ts`, which keeps only what it read: a read that failed or hung is retried (`AppData.BotRefViewRetryDelaysMs`, each after `BotRefViewTimeoutMs`), so a chip pushed with a run shows its steps or card without a reload. 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 another bot passed on keep working.
|
||||
- **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), `[plan:ID]` (a plan, as its card: steps, the one being worked, and the buttons to approve or change them), `[graphic:ID]` (a bot graphic, framed inline), `[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`. A chip reads its own row through `(utils)/ref-view-loader.ts`, which keeps only what it read: a read that failed or hung is retried (`AppData.BotRefViewRetryDelaysMs`, each after `BotRefViewTimeoutMs`), so a chip pushed with a run shows its steps or card without a reload, and a chip whose card the user just decided (`primeRefView`) tells every other chip naming the same ref, since a thread can carry the same card twice and the others otherwise went on saying "Waiting for you" until a reload (`subscribeRefView`; `useBotPlan` instead re-reads on `server:bot-plan`). 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 another bot passed on keep working.
|
||||
- **Message images:** a bot message shows the images it's about under its text (`MessageImages` in `(partials)/`, on `BotMessageLine` and `CrewMessageLine`): its image attachments plus every image `[file:ID]` it names (`liveFileRefIds`, which keeps the renderer's code rules), deduped when a named file is also attached (`file_id`). Each is a `MessageAttachment` thumbnail opening the shared `FilePreviewModal`; in a thread its gallery is the whole conversation (`sessionImageGallery` + `SessionGalleryContext` from `MessageThread`): every image in the session, bot and user, in message order, deduped by URL, falling back to the message's own images outside a thread. Non-image files and unreachable refs show nothing. Named files resolve through `useBotFile`/`useReferencedFiles` (page props first, then the cached `api/admin/bots/files` read shared with `FileRefChip`). A thumbnail URL serves the original when no smaller copy was made (`mediaServeWritePath`), since bot files keep no thumbnail.
|
||||
- **Task chips:** which tracker tasks a bot message is about is the app's record, not the bot's word: a run's task tools report each task they touch (`onTask`: `list_tasks` with `task_id`, `create_task`, `update_task`, `delete_task`, `delegate_task`'s hand-over), plus a handed-over job's `tracker_task_id`, into `bot_messages.task_ids` (also on its failure notice and its report relayed to the requester). The thread shows them under the message (`MessageTaskChips`) with title and status, read per viewer and only for tasks they reach (`grabMessagesTasks`; pushes carry them through `withMessageTasks`).
|
||||
- **File preview:** every file link (chips, attachments, files modal, task files, `/admin/files`) is a `FilePreviewLink`: a plain click opens `FilePreviewModal` (its header shows the size and the file's full path on the data volume, `full_path`, e.g. `bots/3/reports/q3.md`, absolute when outside it; every opener passes it; markdown rendered with the message elements, CSV/TSV as a table via `parseCsv`, images in `ImageViewer` (zoom buttons and keys, Ctrl/Cmd+wheel or pinch at the pointer, Fit, Fit width (a full-page screenshot opens that way and scrolls down), Actual size, double click, drag to pan; sized by the `width` attribute and centred with auto margins, never flex centring, which cuts off a tall picture's top), PDF/audio/video in place, HTML in a frame with `sandbox=""` (plus the media server's `sandbox` CSP), other text as code, the kind from `filePreviewKind`; Download and Open in a new tab), a modified click still opens a tab. Text is read up to `AppData.FilePreviewMaxTextBytes`. Never render a file's HTML on the app's origin or with scripts. Opened from a list (a folder, the files modal, a conversation's images), an image gets that list's images as its `gallery` (`imagePreviewGallery`): Previous/Next (side arrows at the far middle left/right, the header's stepper, and the arrow keys) step through them in the same modal, neighbours preloaded. Escape closes only the top modal of a stack (`useTopModalEscape`; twui closes every open one). The message elements and the preview import each other (through the file chips), so the preview merges `MessageMarkdownComponents` when it renders, never at module load.
|
||||
- **Copy chat** (header menu): the active session (the one on screen) as one markdown document (`api/admin/bots/conversation-export` -> `conversationMarkdown`, refs as names, message headings demoted). The clipboard write starts on the click with a pending `ClipboardItem` (`copyPendingText`), since Safari drops the gesture after a fetch. A message's Details modal has its own **Copy report** (`messageDetailsMarkdown`, the same pending write): that message's whole details, listing up to `AppData.MessageDetailsCopyMaxCalls` calls and failures (the route's `full=1`) instead of the modal's first `MessageDetailsMaxCalls`.
|
||||
- **Asking before acting:** `ask_user` (`QuestionsNote`) puts up to `AppData.BotQuestionMaxQuestions` multiple-choice questions (`single` = radios, `multiple` = checkboxes, optional typed "Other") on one card, once per run -> `bot_questions` -> `[question:ID]` chip opening `BotQuestionCard`; the message needs the user. Answers are checked against the questions (`checkBotQuestionAnswers`) and stored, then sent as the user's chat message (`botQuestionAnswersText`); Skip says so. **The card belongs to the conversation it was asked in:** the answer and skip routes post that message into the question's own session (`postBotQuestionAnswers`), never the page's bot (a card answered on the requester's page woke the wrong bot), and `stripQuestionRefs` takes `[question:ID]` out of text copied into another bot's conversation (`relayJobToRequester`, a crew request's outcome, an install request's answer), which would otherwise show the same card in two sessions, answered in one and left waiting in the other. Replies and user-started tasks only: never routines, hook calls or a crew request's run (no one sees those). The reply's `ask_user`/`suggest_next_steps` and `QuestionsNote` are gated on `attended` (`isHiddenSession`), and a task run's on `can_ask` (`isHiddenSession` checked there too): a question in a hidden session has no card the user would see (one reached the coordinator as a bare `[question:22]`, its answer never getting back).
|
||||
- **Suggested next steps:** `suggest_next_steps` puts up to `AppData.BotSuggestionMaxSteps` follow-ups under the answer, once per run -> `bot_suggestions` -> `[suggestion:ID]` rendered inline as buttons (`BotSuggestionsRef`); clicking one inserts it into the composer (`ComposerHandle.insertText`, never sends) and nothing waits on it, so it's `shown` in `withTakeOverRefs`, never `refs`, and never sets `needs_you`. For when the work is done and the bot offers follow-ups; when the answer decides what it does next, it's `ask_user`. Same runs as `ask_user`. Both are closing tools (`ClosingToolNames`, `src/harness/tools/closing-tool-names.ts`): the turn that writes the answer and puts the card up ends the run, after the usual `review`, because a reply is only the run's **last** message. Without that, a bot answered with the PR links the user asked for, then called `list_tasks` (which `TaskReminderNote` told it to do after answering), and the user was sent the short "still open" line alone.
|
||||
- **Asking before acting:** `ask_user` (`QuestionsNote`) puts up to `AppData.BotQuestionMaxQuestions` multiple-choice questions (`single` = radios, `multiple` = checkboxes, optional typed "Other") on one card, once per run (a second call returns the card already up instead of throwing: a refused re-ask read as a failed closing turn and the whole answer was thrown away) -> `bot_questions` -> `[question:ID]` chip opening `BotQuestionCard`; the message needs the user. Answers are checked against the questions (`checkBotQuestionAnswers`) and stored, then sent as the user's chat message (`botQuestionAnswersText`); Skip says so. **The card belongs to the conversation it was asked in:** the answer and skip routes post that message into the question's own session (`postBotQuestionAnswers`), never the page's bot (a card answered on the requester's page woke the wrong bot), and `stripQuestionRefs` takes `[question:ID]` out of text copied into another bot's conversation (`relayJobToRequester`, a crew request's outcome, an install request's answer), which would otherwise show the same card in two sessions, answered in one and left waiting in the other. Replies and user-started tasks only: never routines, hook calls or a crew request's run (no one sees those). The reply's `ask_user`/`suggest_next_steps` and `QuestionsNote` are gated on `attended` (`isHiddenSession`), and a task run's on `can_ask` (`isHiddenSession` checked there too): a question in a hidden session has no card the user would see (one reached the coordinator as a bare `[question:22]`, its answer never getting back).
|
||||
- **Suggested next steps:** `suggest_next_steps` puts up to `AppData.BotSuggestionMaxSteps` follow-ups under the answer, once per run (a second call returns the steps already attached instead of throwing) -> `bot_suggestions` -> `[suggestion:ID]` rendered inline as buttons (`BotSuggestionsRef`); clicking one inserts it into the composer (`ComposerHandle.insertText`, never sends) and nothing waits on it, so it's `shown` in `withTakeOverRefs`, never `refs`, and never sets `needs_you`. For when the work is done and the bot offers follow-ups; when the answer decides what it does next, it's `ask_user`. Same runs as `ask_user`. Both are closing tools (`ClosingToolNames`, `src/harness/tools/closing-tool-names.ts`): the turn that writes the answer and puts the card up ends the run, after the usual `review`, because a reply is only the run's **last** message. Without that, a bot answered with the PR links the user asked for, then called `list_tasks` (which `TaskReminderNote` told it to do after answering), and the user was sent the short "still open" line alone.
|
||||
- **Plans:** work with several pieces that build on each other is written down before it starts, and worked one step per reply, since a bot answering such a request in one message is how a reply turns into a wall of text. `create_plan` (title, goal, 3 to `AppData.BotPlanMaxSteps` steps) -> `bot_plans` (one open plan per conversation, `BotPlanOpenStates`) -> `[plan:ID]` (`BotPlanCard`); nothing of it runs until the user approves it there, and they change the steps first (`BotPlanEditModal` -> `save-plan`), though a step already worked stays at the top with its note (`planStepsRewriteProblem`). Approving queues the first step as an ordinary **reply** job with `params.plan_id`, in the same conversation, so it has the bot's tools, computers, memory and files; the run gets `PlanStepNote` and works that step alone, `complete_plan_step` marks it done with what it produced (the card checks it off, `pushBotPlan` -> `server:bot-plan`), and `continueBotPlan` (from `process-bot-job`, after the notice) queues the next one. It stops on its own when the user is needed (`needs_you`), when the reply handed work to a run (`WorkStartingTools`), or when an unanswered reply already waits in the session, and never counts an approval as a step: `done` is the app's call once no step is pending. A run that is a plan's step can't write or cancel a plan, only work it, change it (`update_plan`) or finish its step. An ordinary reply in a conversation whose plan is open gets `PlanWaitingNote`/`PlanActiveNote`/`PlanPausedNote` instead of plan tools, so a plan is only ever advanced by the app. A **routine** writes its plan with `approve: true` (`ScheduledPlanNote`): nobody is there to approve it, so it starts itself and the run works every step, reporting at the end. Plan tools are not closing tools: the card and one sentence about it are the reply. When a plan is one the work comes back to, the bot saves its steps with `update_memory` (`PlansNote`); a repeating job is a routine instead. `bot_plans` is deleted with its session (`deleteBotPlanRows`, from `deleteSessionRows`).
|
||||
- **Quoting:** selected text quotes into the composer through `quotableText`, which reads each ref chip as one inline label (`MarkdownLink` wraps chips with `QuoteInlineAttribute`; `Selection.toString()` broke a quote into a paragraph per chip).
|
||||
- **A user's own long message is cut:** the bubble shows the first twenty lines (`max-h-[25rem]`, the bubble's `leading-5`) with **Read more** under it, and **Show less** puts it back (`use-bubble-clamp.ts` measures the cut text in the browser: `bubbleOverflows`); a pasted prompt should not fill the screen. Only what's shown is cut, so the bot, Copy chat and the export still get every character.
|
||||
- **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 (`deleteAskRows`) 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.
|
||||
- **Running a reply again:** the bot's last word in a conversation (`MessageThread` reads its own last bot message, crew messages aside) offers Run again (`retry-reply-button.tsx` -> `api/admin/bots/retry-reply`, eligibility in `rerunReplyProblem`), whatever it was: an answer that went out, a stopped run's notice, a task run's failure. A failed reply's notice carries `bot_messages.failed_job_id` (set by `notifyBotJobFailed`, not an FK); while it still `needs_you`, its actions show Retry instead (the same action, worded for a failure, eligibility in `retryReplyProblem`), which clears the notice's `needs_you`. Either way the route queues a reply to the newest user message with `params.retry_of`, so `run-bot-reply` bypasses the silent finish gate (a reply run again doesn't look unanswered) and gets `RerunReplyNote`; the thread leaves that message out (only a bot message is hidden, `threadMessages`) and shows its thinking row until a newer bot message lands (`rerun_after_id` in `conversation.tsx`: the message it runs again is the last one and looks answered, and a stopped run's notice would say it stopped right above the row). A run that was stopped, or ended without a word, leaves the user's own message last with nothing on its way: the thread says so there and offers the same Run again on it (`unanswered-reply-row.tsx`; the route answers it when `rerunReplyProblem` sees it is the session's last message), instead of a thinking row that would never move (`awaits-reply.ts`, which holds the row back once the open replies are read as none). Failure notices are the app's record, never the bot's words, so `botMessagesToHarness` skips them.
|
||||
- **Running a reply again:** the bot's last word in a conversation (`MessageThread` reads its own last bot message, crew messages aside) offers Run again (`retry-reply-button.tsx` -> `api/admin/bots/retry-reply`, eligibility in `rerunReplyProblem`), whatever it was: an answer that went out, a stopped run's notice, a task run's failure. A failed reply's notice carries `bot_messages.failed_job_id` (set by `notifyBotJobFailed`, not an FK); while it still `needs_you`, its actions show Retry instead (the same action, worded for a failure, eligibility in `retryReplyProblem`), which clears the notice's `needs_you`. Either way the route queues a reply to the newest user message with `params.retry_of`, so `run-bot-reply` bypasses the silent finish gate (a reply run again doesn't look unanswered) and gets `RerunReplyNote`; a retry whose message carries `failed_job_id` also reads that job's `last_error` (`grabRetryFailure` -> `RetryFailureNote`), so it knows what the failed attempt claimed and never did instead of setting off on the same premise; the thread leaves that message out (only a bot message is hidden, `threadMessages`) and shows its thinking row until a newer bot message lands (`rerun_after_id` in `conversation.tsx`: the message it runs again is the last one and looks answered, and a stopped run's notice would say it stopped right above the row). A run that was stopped, or ended without a word, leaves the user's own message last with nothing on its way: the thread says so there and offers the same Run again on it (`unanswered-reply-row.tsx`; the route answers it when `rerunReplyProblem` sees it is the session's last message), instead of a thinking row that would never move (`awaits-reply.ts`, which holds the row back once the open replies are read as none). Failure notices are the app's record, never the bot's words, so `botMessagesToHarness` skips them.
|
||||
- **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 or a super admin). 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` (an argument's `path` survives whole, `toolArgumentPath`: a write's path is what a reader needs), 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`.
|
||||
@@ -126,16 +126,16 @@ Every run also gets `RequestScopeNote` (`src/data/harness-prompts.ts`): the user
|
||||
|
||||
- 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, 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`). 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: `queueBotTask` (a reply's `send_reply` work, or `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).
|
||||
- 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 job queued by a tool (`enqueueBotJob`, the `queueBotTask` path) wakes the queue and pushes `server:bot-updated` itself, so a run queued behind another on the same computer shows and starts at once instead of waiting for the poll; a failed run closes its own `bot_tasks` row (`notifyBotJobFailed`), since a row left `active` kept a conversation's progress on a run that had failed months before (a queued run creates it `active`; only complete, cancel and stop closed it before).
|
||||
- **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`). A plan that can't be written or read starts the run unplanned, never blocks it. **The wrap up is told what is on disk:** a task run passes `Params.wrap_up_note`, which runs `worktreeSummary` over the run's folders (`git status --porcelain` and `git diff --stat` per repository, nested ones included, at most 5) and puts the machine's own account in front of the wrap-up prompt, so the report is written from the tree and not from the run's memory of writing it. **The files the brief names are checked once, before the run starts** (`namedFilesNote`, over `namedFiles`): a path that isn't on the computer but is still in the bot's files is handed over as its `[file:ID]` with `export_file`, and one with no copy anywhere says plainly not to go looking through the machine or the user's accounts. It is the app's answer, not the run's guess: a source a rebuild took off the computer once cost a run thirty turns probing the container and then the user's own accounts for a copy the app was holding the whole time.
|
||||
- **A reply ends with `send_reply`:** a reply run's answer is not its prose. The last turn must be `send_reply({status:"done"|"working"|"blocked", work?})` with the message beside it, and assistant text with no tool call is a draft the loop returns to the model (`replyDraftNote`, up to `AppData.HarnessReplyDraftsMax`) rather than a message the user sees. A bare `send_reply` does not ship that draft on the first pass (`replyNoTextNote`): the model writes the whole message again in that turn, which is also the only turn that may call `suggest_next_steps` or `ask_user` beside it (any other tool is `replyClosingMixedNote` and unsent). A finished draft is carried only after that one reminder still gets no text (`draft_carried`); a draft that stops in a table, a fence or a bare marker (`unfinishedAnswerText`) is sent back once and never carried. A run that still ends with no message fails saying so rather than that its answer was wrong (`unsentAnswerMessage`). `status:"working"` must queue `work` (`{title,instructions,computer_id?,separate?,max_steps?}`, through `queueBotTask`, the same guards and brief as `start_task`) or follow a run already started from this reply, so a message that says work is running can only exist when the job does; `done` and `blocked` carry no work, and `work` beside either is refused. `start_task` is not a reply tool (it stays in task runs for a hand-off), `send_reply` is a closing tool beside `ask_user`/`suggest_next_steps`, and a task report ends the same way. If the run never closes, the job fails honestly and the thread offers Retry; work queued earlier in the run is cancelled with the unsent message. The review reads the status: a `done`/`blocked` message that says work is under way is faulted even when some unrelated run is open, and `hasOpenWork` takes the current `job_id` (`exclude_job_id`) so a task report can't count its own job as open work.
|
||||
- **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`, which shares the line shape with `appRecordLines`). Before a reply or a task report goes out, `reviewBotReply` (the loop's `review`, wired for both by `reviewRunAnswer`) sends it back when it names a `[file:ID]`/`[task:ID]`/`[graphic:ID]` that doesn't exist for the user, a task named in plain prose (`task #16`, `mentionedTaskIds`) whose row is gone (a row the user cannot open is left alone), a `[setting:...]` ref the app can't resolve (`unresolvedSettingRefs`), a `[suggestion:ID]`/`[question:ID]`/`[plan:ID]` ref it wrote itself (`AppCardRefTools`: the app adds those from the tool that made the card, so a written one is made up or copied from an earlier message and the user reads "not available"), or says work is under way, that a report will follow, or that it is about to do the work ("Let me check", "I'll connect and inspect", "next I'll", "Starting the conversion run now") (`claimsWorkUnderWay`, which reads a promise only when its own sentence is the commitment, so an offer waiting on the user is left alone) with no run this reply started and nothing open from the session: bots wrote "I'm scanning now" plus made-up results in one answer, and a reply promising to check the articles and then starting nothing left the user waiting for a report nobody would send. It also faults the app's own state described from nothing (`replyAppStateClaims`, skipped when `read_message_usage`/`read_settings` answered): how the model "routing" resolves or which model the tool sends, a run "killed" or "stopped" (Stop is the user's), and the model rest called unlimited or restart-only, each written by a bot that had only an `HTTP 404` to go on and told the user a model and a mechanism nobody had configured. Review runs on every answer it writes, up to `AppData.HarnessReviewRewrites` rewrites (a repeat of the faulted message is told so, `repeatedAnswerNote`); past that the answer is never sent and the job fails instead (`review_note` -> `BotJobFatalError`, a reply and a task report alike; a rewrite that lands on the wrap up is reviewed there and refused, not sent on), since a model that kept writing the same thing sends the claim anyway. **A fault must be something the bot can stop making:** only a whole line in the app's own record shape naming tools this reply didn't call is a forgery (`unsupportedAppRecordLines`) - the same text quoted inside a sentence is the bot naming its mistake, and job #468 faulted three rewrites in a row for that quote alone, so the lie stayed and the correction never reached the user. No fault note may itself contain the shape it faults or a `claimsWorkUnderWay` phrase. Tool names copied into a list (`WorkStartingTools`, `AppCardRefToolNames`, `WritingToolNames`, `WrapUp*ToolNames`) are pinned to the tools the harness declares by `src/harness/tools/tool-name-lists.test.ts` (`ask_crew` outlived its rename to `ask_bot`, so a reply that really had asked the crew was faulted for saying so). A long bot message whose run called no tools shows "No tools used" (`MessageNoToolsChip`).
|
||||
- **A reply ends with `send_reply`:** a reply run's answer is not its prose. The last turn must be `send_reply({status:"done"|"working"|"blocked", work?, message?})` with the message beside it or in its `message`/`text` argument (`replyTextFromCall`: a model that wrote the message into the call instead of the turn lost six production answers to "doesn't take text"), and assistant text with no tool call is a draft the loop returns to the model (`replyDraftNote`, up to `AppData.HarnessReplyDraftsMax`) rather than a message the user sees. A bare `send_reply` does not ship that draft on the first pass (`replyNoTextNote`): the model writes the whole message again in that turn, which is also the only turn that may call `suggest_next_steps` or `ask_user` beside it (any other tool is `replyClosingMixedNote` and unsent). A message written in the turn that put a card up (`ask_user`/`suggest_next_steps` with no `send_reply`) is kept as `card_text` and goes out with the call that closes it: that sentence is what the card belongs under, and asking for it again left the model with nothing to say (session 146). A review send-back clears `draft_text` and `card_text` and the reminder flag, so a refused answer is never carried again (the same faulted text went out on every bare `send_reply` and used up the rewrite budget). A draft that stops in a table, a fence or a bare marker (`unfinishedAnswerText`) is sent back once and never carried. A run that still ends with no message fails saying so rather than that its answer was wrong (`unsentAnswerMessage`). `status:"working"` must queue `work` (`{title,instructions,computer_id?,separate?,max_steps?}`, through `queueBotTask`, the same guards and brief as `start_task`) or follow a run already started from this reply, so a message that says work is running can only exist when the job does; `done` and `blocked` carry no work, and `work` beside either is refused. `start_task` is not a reply tool (it stays in task runs for a hand-off), `send_reply` is a closing tool beside `ask_user`/`suggest_next_steps`, and a task report ends the same way. If the run never closes, the job fails honestly and the thread offers Retry; work queued earlier in the run is cancelled with the unsent message. The review reads the status: a `done`/`blocked` message that says work is under way is faulted even when some unrelated run is open, and `hasOpenWork` takes the current `job_id` (`exclude_job_id`) so a task report can't count its own job as open work.
|
||||
- **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`, which shares the line shape with `appRecordLines`). Before a reply or a task report goes out, `reviewBotReply` (the loop's `review`, wired for both by `reviewRunAnswer`) sends it back when it names a `[file:ID]`/`[task:ID]`/`[graphic:ID]` that doesn't exist for the user, a task named in plain prose (`task #16`, `mentionedTaskIds`) whose row is gone (a row the user cannot open is left alone), a `[setting:...]` ref the app can't resolve (`unresolvedSettingRefs`), a `[suggestion:ID]`/`[question:ID]`/`[plan:ID]` ref it wrote itself (`AppCardRefTools`: the app adds those from the tool that made the card, so a written one is made up or copied from an earlier message and the user reads "not available"; `stripCardRefs` keeps them out of the answer and out of the model's own history, since the stored text carries the ref the app appended under it, which is how one began writing `[question:24]` at a card it never made), a `[proposal:]`/`[hook-proposal:]` ref no row backs (the model guessed `[proposal:19]` 85 s before that row existed, and the user was told three times a proposal had gone out when none had), or says work is under way, that a report will follow, or that it is about to do the work ("Let me check", "I'll connect and inspect", "next I'll", "Starting the conversion run now") (`claimsWorkUnderWay`, which reads a promise only when its own sentence is the commitment, so an offer waiting on the user is left alone) with no run this reply started and nothing open from the session: bots wrote "I'm scanning now" plus made-up results in one answer, and a reply promising to check the articles and then starting nothing left the user waiting for a report nobody would send. It also faults the app's own state described from nothing (`replyAppStateClaims`, skipped when `read_message_usage`/`read_settings` answered): how the model "routing" resolves or which model the tool sends, a run "killed" or "stopped" (Stop is the user's), and the model rest called unlimited or restart-only, each written by a bot that had only an `HTTP 404` to go on and told the user a model and a mechanism nobody had configured. Review runs on every answer it writes, up to `AppData.HarnessReviewRewrites` rewrites (a repeat of the faulted message is told so, `repeatedAnswerNote`); past that the answer is never sent and the job fails instead (`review_note` -> `BotJobFatalError`, a reply and a task report alike; a rewrite that lands on the wrap up is reviewed there and refused, not sent on), since a model that kept writing the same thing sends the claim anyway. **A fault must be something the bot can stop making:** only a whole line in the app's own record shape naming tools this reply didn't call is a forgery (`unsupportedAppRecordLines`) - the same text quoted inside a sentence is the bot naming its mistake, and job #468 faulted three rewrites in a row for that quote alone, so the lie stayed and the correction never reached the user. No fault note may itself contain the shape it faults or a `claimsWorkUnderWay` phrase. Tool names copied into a list (`WorkStartingTools`, `AppCardRefToolNames`, `WritingToolNames`, `WrapUp*ToolNames`) are pinned to the tools the harness declares by `src/harness/tools/tool-name-lists.test.ts` (`ask_crew` outlived its rename to `ask_bot`, so a reply that really had asked the crew was faulted for saying so). A long bot message whose run called no tools shows "No tools used" (`MessageNoToolsChip`).
|
||||
- **A reply's `send_reply` work and `start_task`/`delegate_task` jobs are runs, not tasks:** their results say `Run #<job id>` and that `list_tasks` doesn't show them (bots sent users to the tracker for them). `queueBotTask` refuses a second open run in its session on the same computer unless `separate` (it would only wait behind it) and says how many runs are ahead on that computer. Its `max_steps` (`params.max_steps`) caps the run below the install's limit; the brief alone never did. Nothing wakes a bot when a run ends, so different follow-up work is queued at once with `separate`, never promised for later (`send_reply`'s work, `start_task`, `chatReplyNote`).
|
||||
- **Replies take in messages sent mid-run** (`incoming`, `IncomingMessagesNote`, redraft); separate requests are acknowledged with `send_message` (interim). A queued reply finishes silently only when a finished reply already read every user message (`hasUnansweredMessage`), never by who wrote last; a retry (`params.retry_of`) always runs. **Task runs take them in too** (`taskIncoming`, only runs the user follows: no routines, hook calls or rooms): everything the user wrote since the run was queued, at the start, between steps, past a report not yet out and by the wrap up (`incoming_notes`, `TaskIncomingNote`); a correction changes the work, anything else is left to the chat, and crew messages to the reply they wake. A reply is told which runs open in its session hear the user (`openRunsNote`), so a correction never starts a second run.
|
||||
|
||||
### 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`, the debug view's `server:bot-trace` (just the job and its session), and a plan's card `server:bot-plan` (just its id and conversation). 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`, the debug view's `server:bot-trace` (just the job and its session), and a plan's card `server:bot-plan` (just its id and conversation). 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. A push's `task` is a list of every active task that user has on the bot (`grabActiveBotTasks`), and the conversation picks its own session's (`ownTask`), since sending only the newest one blanked the row whenever another conversation of the same bot had a run open; a page also keeps polling (`use-reply-catch-up` `running`) while its session has open jobs or an active task, not only until a reply lands, since a run queued behind another on the same computer starts much later (`queueBotTask` refuses a second one there, and the face then says which wait it is: `botWaitsOnComputer` picks `BotComputerBusyStatusLine` over `BotWaitingStatusLine`).
|
||||
|
||||
### Crew requests (`bot_asks`)
|
||||
|
||||
@@ -198,7 +198,8 @@ Set in Settings > Environment (super admin), not `.env`. `envs` (private; encryp
|
||||
|
||||
- Files live on the data volume, not on computers: `DATA_DIR/bots/<id>` and `DATA_DIR/workspaces/<id>`. Catalog `bot_files`, bytes in private `media` (`bot-file`) written by `recordBotFile`. Reach via `grabStorageScopes`; paths via `resolveBotPath` (no absolute, `..`, NUL, symlink escape); quota checked by `assertStorageRoom`.
|
||||
- Tools in `src/harness/tools/storage/` (every run). `attach` puts a file on the reply. `grabConversationFiles` must list the **whole** folder tree, or nested `[file:ID]` refs render dead. A workspace run saves to the bot's own folder unless it picks the workspace's, so a chip in a workspace conversation looks up both (`api/admin/bots/files?file_id=` with `bot_id` and `workspace_id`).
|
||||
- `import_file` copies from a computer through the agent's streaming `GET /api/files/download`, **never through its shell** (a shell's output is capped and once silently truncated imports). Size read first, the agent cuts a file that changes mid-send, length checked.
|
||||
- `import_file` copies from a computer through the agent's streaming `GET /api/files/download`, **never through its shell** (a shell's output is capped and once silently truncated imports). Size read first, the agent cuts a file that changes mid-send, length checked. A chat reply has it too (`grab-bot-chat-tools`, its computers to choose from), so what a reply made on a computer comes into its files the same way a task's does.
|
||||
- `list_files` with `search` matches names and paths in **every** folder (leaving `folder` out lists every folder too): scoping a search to the root hid `images/summit-hero-pil.png` and made a bot believe its file was never saved. `write_file` refuses a binary extension, since text saved under `.png` reached the user as a file that would not open.
|
||||
- **Only knowledgebases store text.** Bot files and uploads are never indexed and keep no extracted text (`media.text_content` only for knowledgebase documents); bots find files by name or path (`list_files` `search`) and read them with `read_file`, and the Files searches match names only. Text that should be searchable goes in a knowledgebase. `dropStoredFileText` clears what older versions stored, at boot, and vacuums when much of the file is free.
|
||||
- **Foreign keys are off per connection** unless `enableForeignKeys` ran (only `src/server.ts` does). Scripts never fire `ON DELETE CASCADE`, so **any helper that deletes a parent row must delete its children explicitly** (as `deleteBotFile`, `purgeStorage`, `deleteSkill` do). A leftover child fails the next `bun run db:schema` with a foreign key violation.
|
||||
|
||||
@@ -234,7 +235,7 @@ Read-only browser of every volume (`src/utils/storage-volumes.ts`: bots, workspa
|
||||
- **Generation settings follow the model:** a model takes only the parameters its provider advertises (`modelAdvertisesParameter`, `src/dict/harness-parameter-dict.ts`); a custom provider's `/models` lists ids only, so its models take none and the form hides the Model settings target. The wire sends only advertised parameters (`grabChatParams`), never a value saved on another model. Switching the model or the provider clears the saved generation settings and voice (`nextHarnessModelValue` / `nextHarnessProviderValue`), so a temperature tuned for one model never rides to another that rejects it.
|
||||
- **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 `send_reply` with work, or `start_task` in a task run (`unknownToolMessage`). Bot tools in `src/harness/tools/bot/` (memory, instructions, tasks, schedules, `read_settings`, `read_message_usage`, `send_reply`, `start_task`, `hand_over_task`, `update_requester` (an interim word to the bot that asked while a crew request is open), 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. A prompt-kind tool's filled template is the model's own input, so a secret env fills in as its `[KEY]` marker there, never its value (`runPromptTool`); http and script tools use secrets server-side, where the value never reaches the model. 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); knowledgebases are the exception it fills itself, since they live on the install (see Knowledgebases). 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).
|
||||
- **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); knowledgebases are the exception it fills itself, since they live on the install (see Knowledgebases). 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). A pending proposal for the same thing in the same conversation is replaced when another is made or one is confirmed (`replacePendingExtensionProposals`: a skill by `data.slug`, else the extension id, else the normalised name; `replacePendingHookProposals` by `hook_id`, then title), so a conversation carried into a new session no longer leaves a second card pending for the same skill (#41 stayed pending for ever while #42 made it, and the same target churned through #60-#63). Stdio servers are never proposed by bots (they run in the app container, which holds the docker socket).
|
||||
- **Check before and after acting** (`ActionCheckNote`): look for an existing record before creating one, verify every action took effect. Tools enforce it (read-back on memory saves, duplicate checks on bots, schedules, tasks, workspaces).
|
||||
|
||||
### Token usage
|
||||
|
||||
@@ -10,13 +10,24 @@ const base = {
|
||||
|
||||
describe("runCommand", () => {
|
||||
test("returns output in order and the exit code", async () => {
|
||||
const result = await runCommand({ ...base, command: "echo one; echo two >&2; exit 3" });
|
||||
const result = await runCommand({ ...base, command: "echo one; echo two; exit 3" });
|
||||
|
||||
expect(result.output).toBe("one\ntwo\n");
|
||||
expect(result.exit_code).toBe(3);
|
||||
expect(result.timed_out).toBe(false);
|
||||
});
|
||||
|
||||
/**
|
||||
* stdout and stderr are two pipes read as they arrive, so which of
|
||||
* them a line from each lands first is the scheduler's call: both come
|
||||
* back, each in its own order.
|
||||
*/
|
||||
test("brings stderr back together with stdout", async () => {
|
||||
const result = await runCommand({ ...base, command: "echo out; echo err >&2" });
|
||||
|
||||
expect(result.output.split("\n").filter(Boolean).sort()).toEqual(["err", "out"]);
|
||||
});
|
||||
|
||||
test("reads no input", async () => {
|
||||
const result = await runCommand({ ...base, command: "read -r line; echo \"got:$line:$?\"" });
|
||||
|
||||
|
||||
@@ -34,7 +34,9 @@ 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
|
||||
* come back together, each in its own order (they are two pipes, read as
|
||||
* they arrive, so neither is held back for the other), cut at
|
||||
* `max_output_bytes`. Past its
|
||||
* 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
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "cobble",
|
||||
"version": "0.24.8",
|
||||
"version": "0.25.2",
|
||||
"module": "index.ts",
|
||||
"type": "module",
|
||||
"private": true,
|
||||
|
||||
@@ -5,6 +5,7 @@ import type { HarnessContentPart, HarnessMessage, HarnessToolUse } from "@/src/h
|
||||
import type { BotMessageReaction, BotMessageWithAttachments } from "@/src/types";
|
||||
import describeMessageRefs, { type MessageRefNames } from "@/src/utils/describe-message-refs";
|
||||
import { AppRecordPrefix } from "@/src/utils/strip-app-records";
|
||||
import stripCardRefs from "@/src/utils/strip-card-refs";
|
||||
import describeAttachment from "./describe-attachment";
|
||||
import crewMessageBlock from "@/src/utils/crew-message-block";
|
||||
|
||||
@@ -106,8 +107,16 @@ function messageParts({
|
||||
}
|
||||
|
||||
const own = message.text?.trim() || "";
|
||||
/**
|
||||
* The refs of the app's own cards (`[question:]`, `[suggestion:]`,
|
||||
* `[plan:]`) are added to a stored message after the model wrote it, so
|
||||
* replaying them as the bot's own words is what taught it to write
|
||||
* `[question:24]` itself (session 146, job 785). They come out of the
|
||||
* bot's history here; the message the user reads keeps them.
|
||||
*/
|
||||
const said = role == "assistant" && own ? stripCardRefs({ text: own }) : own;
|
||||
const mentions = role == "user" && refs && own ? describeMessageRefs({ text: own, names: refs }) : "";
|
||||
const text = replyContext({ message, text: mentions ? `${own}\n\n${mentions}` : own });
|
||||
const text = replyContext({ message, text: mentions ? `${said}\n\n${mentions}` : said });
|
||||
const content: HarnessContentPart[] = text ? [{ type: "text", text }] : [];
|
||||
|
||||
if (role == "assistant") {
|
||||
|
||||
@@ -2,7 +2,7 @@ import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
import type { BUN_SQLITE_COBBLE_BOTS } from "@/db/types/db";
|
||||
import grabBotAudience from "@/src/functions/backend/db/access/grab-bot-audience";
|
||||
import { logError } from "@/src/functions/backend/logger";
|
||||
import grabActiveBotTask from "@/src/functions/backend/db/bots/grab-active-bot-task";
|
||||
import grabActiveBotTasks from "@/src/functions/backend/db/bots/grab-active-bot-tasks";
|
||||
import grabBotFace from "@/src/functions/backend/db/bots/grab-bot-face";
|
||||
import { sendToUser } from "@/src/websocket/(functions)/send-to-user";
|
||||
|
||||
@@ -89,6 +89,12 @@ async function push({
|
||||
for (const viewer_id of audience) {
|
||||
if (users && !users.has(String(viewer_id))) continue;
|
||||
|
||||
/**
|
||||
* Read per viewer, and every one of them: the push can't know which
|
||||
* conversation is open, so the page picks its own task out.
|
||||
*/
|
||||
const tasks = await grabActiveBotTasks({ bot_id, user_id: viewer_id });
|
||||
|
||||
sendToUser({
|
||||
user_id: viewer_id,
|
||||
data: {
|
||||
@@ -102,7 +108,8 @@ async function push({
|
||||
admin_workspace_ids,
|
||||
...(computer_id !== undefined ? { computer_id: computer_id || null } : {}),
|
||||
...(workspace_ids !== undefined ? { workspace_ids } : {}),
|
||||
task: await grabActiveBotTask({ bot_id, user_id: viewer_id }),
|
||||
task: tasks[0] || null,
|
||||
tasks,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
@@ -6,6 +6,8 @@ import assertUserReachesTask from "@/src/functions/backend/db/tasks/assert-user-
|
||||
import { taskRowSql } from "@/src/functions/backend/db/tasks/run-task-sql";
|
||||
import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
import grabBotGraphic from "@/src/functions/backend/db/bot-graphics/grab-bot-graphic";
|
||||
import grabExtensionProposal from "@/src/functions/backend/db/extension-proposals/grab-extension-proposal";
|
||||
import grabHookProposal from "@/src/functions/backend/db/hook-proposals/grab-hook-proposal";
|
||||
import describeToolUses from "@/src/harness/text/describe-tool-uses";
|
||||
import type { HarnessToolUse } from "@/src/harness/types";
|
||||
import type { ReplyStatus } from "@/src/dict/reply-status-dict";
|
||||
@@ -83,6 +85,28 @@ export default async function reviewBotReply({ text, tool_uses, bot_id, user_id,
|
||||
if (!(await grabBotGraphic({ graphic_id, user_id }))) missing_graphic_ids.push(graphic_id);
|
||||
}
|
||||
|
||||
/**
|
||||
* A proposal ref names the card it makes, so it only exists once that
|
||||
* card does: a number the model guessed describes a proposal the user
|
||||
* never got. A row made to someone else doesn't open for this user
|
||||
* either, so the lookup is by user, like the file check.
|
||||
*/
|
||||
const missing_proposal_ids: number[] = [];
|
||||
|
||||
for (const proposal_id of replyRefIds({ text, kind: "proposal" })) {
|
||||
const row = await grabExtensionProposal({ proposal_id, user_id }).catch(() => null);
|
||||
|
||||
if (!row) missing_proposal_ids.push(proposal_id);
|
||||
}
|
||||
|
||||
const missing_hook_proposal_ids: number[] = [];
|
||||
|
||||
for (const proposal_id of replyRefIds({ text, kind: "hook-proposal" })) {
|
||||
const row = await grabHookProposal({ proposal_id, user_id }).catch(() => null);
|
||||
|
||||
if (!row) missing_hook_proposal_ids.push(proposal_id);
|
||||
}
|
||||
|
||||
/**
|
||||
* The cards the app adds under the message itself: any ref of theirs in
|
||||
* the answer was written by the model, since the app's own refs are
|
||||
@@ -100,6 +124,8 @@ export default async function reviewBotReply({ text, tool_uses, bot_id, user_id,
|
||||
missing_mentioned_task_ids,
|
||||
unresolved_setting_refs: unresolvedSettingRefs({ text }),
|
||||
missing_graphic_ids,
|
||||
missing_proposal_ids,
|
||||
missing_hook_proposal_ids,
|
||||
written_card_refs,
|
||||
has_open_work: await hasOpenWork({ bot_id, session_id, exclude_job_id: job_id }),
|
||||
status,
|
||||
|
||||
@@ -13,6 +13,7 @@ import {
|
||||
botFilesNote,
|
||||
chatReplyNote,
|
||||
RerunReplyNote,
|
||||
RetryFailureNote,
|
||||
ComputerFilesNote,
|
||||
coordinatorReplyNote,
|
||||
longSessionNote,
|
||||
@@ -73,6 +74,7 @@ import hasUnansweredMessage from "./has-unanswered-message";
|
||||
import reviewRunAnswer from "./review-run-answer";
|
||||
import cancelBotJob from "@/src/functions/backend/db/bots-queue/cancel-bot-job";
|
||||
import grabAnsweredMessageId from "@/src/functions/backend/db/bots-queue/grab-answered-message-id";
|
||||
import grabRetryFailure from "@/src/functions/backend/db/bots-queue/grab-retry-failure";
|
||||
import markReplyAnswered from "@/src/functions/backend/db/bots-queue/mark-reply-answered";
|
||||
import sendMessageTool from "@/src/harness/tools/bot/send-message-tool";
|
||||
import updateRequesterTool from "@/src/harness/tools/bot/update-requester-tool";
|
||||
@@ -151,6 +153,14 @@ export default async function runBotReply({
|
||||
* session's last message and nothing looks unanswered.
|
||||
*/
|
||||
const is_retry = Number(job_params.retry_of) > 0;
|
||||
/**
|
||||
* Why the attempt before this one ended without an answer
|
||||
* (`grabRetryFailure`): what it claimed to have done may be exactly
|
||||
* what it never did, so the retry is told rather than repeating it.
|
||||
*/
|
||||
const retry_failure = is_retry
|
||||
? await grabRetryFailure({ message_id: Number(job_params.retry_of) }).catch(() => null)
|
||||
: null;
|
||||
|
||||
if (!on_plan_step && !is_retry && !hasUnansweredMessage({ history, answered_id })) {
|
||||
return { result: "", silent: true };
|
||||
@@ -369,6 +379,7 @@ export default async function runBotReply({
|
||||
led = admin;
|
||||
},
|
||||
onTask: ({ task_id }) => task_ids.push(task_id),
|
||||
onAttach: ({ media_id }) => attachments.push(media_id),
|
||||
});
|
||||
|
||||
/**
|
||||
@@ -465,8 +476,9 @@ export default async function runBotReply({
|
||||
long_session_note,
|
||||
chatReplyNote({ bot_id: bot.id }),
|
||||
is_retry ? RerunReplyNote : "",
|
||||
retry_failure ? RetryFailureNote({ reason: retry_failure.reason }) : "",
|
||||
botFilesNote({ bot_id: bot.id }),
|
||||
ComputerFilesNote({ computer_id: computers[0]?.id || 0, dirs, can_import: false }),
|
||||
ComputerFilesNote({ computer_id: computers[0]?.id || 0, dirs, can_import: computers.length > 0 }),
|
||||
TasksNote,
|
||||
TaskReminderNote,
|
||||
can_hand_over ? HandOverTaskNote : "",
|
||||
|
||||
@@ -182,6 +182,19 @@ export default async function runBotTask({
|
||||
try {
|
||||
const prompt = await grabBotPrompt({ bot_id: bot.id, user_id, workspace_id });
|
||||
const computers = await grabBotComputers({ bot_id: bot.id, workspace_id });
|
||||
/**
|
||||
* `import_file` reads only the computer this run works on: what it
|
||||
* made is there. The row is read again when the list no longer has
|
||||
* it, so the tool still names the job's computer.
|
||||
*/
|
||||
const job_computers = job.computer_id
|
||||
? computers.filter((row) => Number(row.id) == Number(job.computer_id))
|
||||
: [];
|
||||
const import_computers = job_computers.length
|
||||
? job_computers
|
||||
: job.computer_id
|
||||
? [{ id: job.computer_id }]
|
||||
: [];
|
||||
|
||||
/**
|
||||
* What the bot's types let it do here. A coordinator's task can
|
||||
@@ -395,7 +408,7 @@ export default async function runBotTask({
|
||||
...(job.computer_id
|
||||
? [
|
||||
importFileTool({
|
||||
computer_id: job.computer_id,
|
||||
computers: import_computers,
|
||||
scopes,
|
||||
bot_id: bot.id,
|
||||
user_id,
|
||||
|
||||
@@ -24,6 +24,7 @@ import {
|
||||
PlanActiveNote,
|
||||
PlanPausedNote,
|
||||
ScheduledPlanNote,
|
||||
RetryFailureNote,
|
||||
} from "./harness-prompts";
|
||||
import computerRunDirs from "@/src/utils/computer-work-dirs";
|
||||
|
||||
@@ -96,6 +97,26 @@ describe("harness prompts", () => {
|
||||
expect(TasksNote).not.toContain("[folder:bot:");
|
||||
expect(TasksNote).not.toContain("[bot:");
|
||||
});
|
||||
|
||||
test("a retry is told why the attempt before it failed", () => {
|
||||
const note = RetryFailureNote({ reason: "The answer didn't hold up against the app's record." });
|
||||
|
||||
expect(note).toContain("The answer didn't hold up against the app's record.");
|
||||
expect(note).toContain("list_files");
|
||||
expect(note).toContain("correct the premise first");
|
||||
});
|
||||
|
||||
test("a retry outside the few hundred characters that matter keeps the start of the failure", () => {
|
||||
const reason = `${"first".repeat(80)}${"last".repeat(10)}`;
|
||||
const note = RetryFailureNote({ reason });
|
||||
|
||||
expect(note).toContain(`first${"first".repeat(78)}`);
|
||||
expect(note).not.toContain("lastlastlastlast");
|
||||
});
|
||||
|
||||
test("a retry with no reason recorded still reads as a failure", () => {
|
||||
expect(RetryFailureNote({ reason: "" })).toContain("It ended without sending an answer.");
|
||||
});
|
||||
});
|
||||
|
||||
describe("openRunsNote", () => {
|
||||
|
||||
@@ -68,7 +68,8 @@ export const chatReplyNote = ({ bot_id }: { bot_id: number | string }) => `# Rep
|
||||
|
||||
You are chatting with the user. Answer their latest messages directly and briefly, in markdown.
|
||||
|
||||
- Every reply ends with send_reply. The text beside it is the message the user reads; a turn that writes text without it is a draft and is never sent.
|
||||
- Every reply ends with send_reply. Write the message beside it, or pass it as its message argument; a turn that writes text without it is a draft and is never sent.
|
||||
- A card's ref ([question:], [suggestion:], [plan:], [proposal:]) is written by the app from the tool that made the card, never by you. A ref you type names no card, and the user reads "not available": call ask_user, suggest_next_steps, create_plan or the propose_ tool and say in words what you mean. A proposal exists only once that tool returned one.
|
||||
- send_reply({status:"done"}) for a quick answer or a small change that needs nothing after it.
|
||||
- send_reply({status:"working", work:{title, instructions, computer_id?}}) for work that takes more than a moment, or anything on a computer (running commands, editing files, browsing). The app queues the run before your message goes out; a task you start is your own work, so never say you handed it to anyone else. Its result is posted here when it's done.
|
||||
- send_reply({status:"blocked"}) when the work can't go on; say why in the message.
|
||||
@@ -88,7 +89,7 @@ You are chatting with the user. Answer their latest messages directly and briefl
|
||||
|
||||
Be proactive. Follow where the conversation is heading and, once you've answered, offer the next step with ask_user, not as a question in your text: one question whose options are the concrete next steps, the one you'd suggest first and marked as suggested, e.g. "Draft the reply as well (suggested)" and "Check the other two accounts the same way". Base them on what the user is trying to get done, not on generic options, and keep it to two to four. Skip it when you've already called ask_user in this reply, when you've just queued a run (its result will offer what's next), or when the user is clearly wrapping up.
|
||||
|
||||
Your answer and that card go out together: send_reply is what sends the message, and ask_user or suggest_next_steps beside it in the same turn go with it. Anything else you call after writing an answer carries on the run instead, and only the last message of it is sent, so an answer written before that never reaches the user.
|
||||
Your answer and that card go out together: send_reply is what sends the message, and ask_user or suggest_next_steps beside it in the same turn go with it. If the card was put up in the turn that wrote the message, that message is kept, so send_reply needs no text beside it. Anything else you call after writing an answer carries on the run instead, and only the last message of it is sent, so an answer written before that never reaches the user.
|
||||
|
||||
## Ending the reply
|
||||
|
||||
@@ -115,6 +116,19 @@ The user asked for this reply again. Work from their latest messages and write i
|
||||
- If the answer did go out, write it again for what they asked, as if it were the first time. The earlier one stays in the thread, so don't repeat it word for word if you have something better to say, and don't assume they missed it.
|
||||
- Start the work now, in this reply or with send_reply status "working" and work: never answer that you'll look into it.`;
|
||||
|
||||
/**
|
||||
* Added beside `RerunReplyNote` when the attempt before this one failed:
|
||||
* `reason` is the job's `last_error` (`grabRetryFailure`), so the run knows
|
||||
* what went wrong instead of starting from the same wrong premise. Cut
|
||||
* short: the note is guidance, not the failure log.
|
||||
*/
|
||||
export const RetryFailureNote = ({ reason }: { reason: string }) => `# The attempt before this one
|
||||
|
||||
It ended without sending an answer${reason ? `: ${reason.slice(0, 400)}` : "."}
|
||||
|
||||
- Check what that attempt actually left on record before you repeat it: list_files for what it says it saved, and the computer's own folders for what it says it made there. Take its word for nothing.
|
||||
- If it set off on a premise that wasn't true (a file that wasn't saved, a script that never existed), correct the premise first: that is the reason this attempt exists.`;
|
||||
|
||||
export const botFilesNote = ({ bot_id }: { bot_id: number | string }) => `# Your files
|
||||
|
||||
You have a folder of your own, kept with the app (not on a computer), and it stays between runs and conversations.
|
||||
@@ -136,8 +150,9 @@ You have a folder of your own, kept with the app (not on a computer), and it sta
|
||||
|
||||
/**
|
||||
* Added to a run that has a computer: what it leaves there is not in its
|
||||
* files, but the user can still open it. `can_import` is false in a chat
|
||||
* reply, where the import only happens inside a task.
|
||||
* files, but the user can still open it. `can_import` is false when the run
|
||||
* has no computer to read from (a reply whose bot has none): then file work
|
||||
* on one is a task.
|
||||
*
|
||||
* A folder ref is always a folder, so a file left on the computer is named
|
||||
* by the folder that holds it, never by the file's own path.
|
||||
@@ -507,20 +522,20 @@ export const closingNoTextNote = `The card you just put up has no message beside
|
||||
* never queued. Bounded by `AppData.HarnessReplyDraftsMax`, then the run
|
||||
* fails honestly rather than sending it.
|
||||
*/
|
||||
export const replyDraftNote = `That message was not sent: a reply ends with send_reply, and text on its own is a draft. Write the whole message again in the same turn as send_reply: status "done" when nothing is running after it, "working" with work (or after a run you already started) when something is, or "blocked" when it can't go on. A call with no text beside it sends nothing, and an earlier draft is not filled in for you. In that same turn, and only then, call suggest_next_steps or ask_user when one of them belongs with the answer. The text beside the call is what the user reads, so finish every table, list and code fence before you send it.`;
|
||||
export const replyDraftNote = `That message was not sent: a reply ends with send_reply, and text on its own is a draft. Write the whole message again in the same turn as send_reply, beside it or as its message argument: status "done" when nothing is running after it, "working" with work (or after a run you already started) when something is, or "blocked" when it can't go on. In that same turn, and only then, call suggest_next_steps or ask_user when one of them belongs with the answer. The text beside the call is what the user reads, so finish every table, list and code fence before you send it.`;
|
||||
|
||||
/**
|
||||
* Told when `send_reply` worked but the turn said nothing beside it: the
|
||||
* user would get an empty line, and the status alone is not a message.
|
||||
*/
|
||||
export const replyNoTextNote = `The send_reply call went through, but there is no message beside it, so nothing was sent. An earlier draft is not the message: write the whole message again beside send_reply and call it again, status "done", "working" (with work, or after a run you started) or "blocked". suggest_next_steps or ask_user may share that turn when one of them belongs with the answer. Finish every table, list and code fence in the text you write there.`;
|
||||
export const replyNoTextNote = `The send_reply call went through, but there is no message beside it, so nothing was sent. Nothing written in an earlier turn is sent in its place: write the whole message again beside send_reply, or pass it as its message argument, and call it again with status "done", "working" (with work, or after a run you started) or "blocked". suggest_next_steps or ask_user may share that turn when one of them belongs with the answer. Finish every table, list and code fence in the text you write there.`;
|
||||
|
||||
/**
|
||||
* Told when a turn tried to end without `send_reply` at all: a card alone or
|
||||
* a closing tool that isn't `send_reply` doesn't say whether work is
|
||||
* running, and its text is a draft.
|
||||
*/
|
||||
export const replyClosingRequiredNote = `That turn ended without send_reply, so no message was sent. A reply ends with send_reply and the text beside it: status "done" when nothing follows, "working" with work when something does, or "blocked" with why. A card alone doesn't say whether work is running.`;
|
||||
export const replyClosingRequiredNote = `That turn ended without send_reply, so no message was sent. A reply ends with send_reply and the text beside it: status "done" when nothing follows, "working" with work when something does, or "blocked" with why. A card alone doesn't say whether work is running. A message you wrote in that same turn as the card is kept, so send_reply alone sends it.`;
|
||||
|
||||
/**
|
||||
* Told when a turn called `send_reply` beside other tools: only its own turn
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { Database } from "bun:sqlite";
|
||||
import type { StorageScope } from "@/src/utils/storage-access";
|
||||
import botFilesFilter from "./bot-files-filter";
|
||||
|
||||
/**
|
||||
* `list_files` with a search looked only at the root, so a bot that had
|
||||
* just saved `images/summit-hero-pil.png` was told it had no matching file,
|
||||
* believed its own save had never happened, and sent a task hunting the
|
||||
* filesystem for it. A search now looks through every folder.
|
||||
*/
|
||||
const db = new Database(":memory:");
|
||||
|
||||
db.run(`CREATE TABLE bot_files (id INTEGER PRIMARY KEY, scope TEXT, owner_id INTEGER, folder TEXT, name TEXT, path TEXT)`);
|
||||
db.run(
|
||||
`INSERT INTO bot_files VALUES
|
||||
(1, 'bot', 20, '', 'root.md', 'root.md'),
|
||||
(2, 'bot', 20, 'images', 'summit-hero-pil.png', 'images/summit-hero-pil.png'),
|
||||
(3, 'bot', 20, 'scripts', 'render-hero.py', 'scripts/render-hero.py'),
|
||||
(4, 'bot', 20, 'reports', 'render.md', 'reports/render.md'),
|
||||
(5, 'bot', 21, 'images', 'summit-hero-pil.png', 'images/summit-hero-pil.png'),
|
||||
(6, 'workspace', 2, 'shared', 'summit-hero-pil.png', 'shared/summit-hero-pil.png')`,
|
||||
);
|
||||
|
||||
const scopes: StorageScope[] = [{ scope: "bot", owner_id: 20 }];
|
||||
|
||||
function ids({ folder, recursive, search }: { folder?: string | null; recursive?: boolean; search?: string | null }) {
|
||||
const { where, values } = botFilesFilter({ scopes, folder, recursive, search });
|
||||
|
||||
return db
|
||||
.query(`SELECT id FROM bot_files WHERE ${where.join(" AND ")} ORDER BY id`)
|
||||
.all(...values)
|
||||
.map((row) => (row as { id: number }).id);
|
||||
}
|
||||
|
||||
describe("the file listing filter", () => {
|
||||
test("a search with no folder finds a file saved in a subfolder", () => {
|
||||
expect(ids({ search: "summit-hero" })).toEqual([2]);
|
||||
});
|
||||
|
||||
test("a search across folders finds every match, wherever it is saved", () => {
|
||||
expect(ids({ search: "render" })).toEqual([3, 4]);
|
||||
});
|
||||
|
||||
test("a named empty folder is still only that folder's own files", () => {
|
||||
expect(ids({ folder: "" })).toEqual([1]);
|
||||
});
|
||||
|
||||
test("a named folder lists what it holds", () => {
|
||||
expect(ids({ folder: "images" })).toEqual([2]);
|
||||
});
|
||||
|
||||
test("a named folder searched looks through it, not the rest of the tree", () => {
|
||||
expect(ids({ folder: "images", search: "render" })).toEqual([]);
|
||||
});
|
||||
|
||||
test("a recursive folder takes everything under it", () => {
|
||||
expect(ids({ folder: "reports", recursive: true })).toEqual([4]);
|
||||
expect(ids({ folder: "bot", recursive: true })).toEqual([]);
|
||||
});
|
||||
|
||||
test("another bot's file with the same name is never in it", () => {
|
||||
expect(ids({ search: "summit-hero" })).not.toContain(5);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,43 @@
|
||||
import type { StorageScope } from "@/src/utils/storage-access";
|
||||
|
||||
type Params = {
|
||||
scopes: StorageScope[];
|
||||
folder?: string | null;
|
||||
recursive?: boolean;
|
||||
search?: string | null;
|
||||
};
|
||||
|
||||
/**
|
||||
* The WHERE clause listing a run's files: its directories, one folder (or
|
||||
* its whole tree), and a name or path match. A search with no folder looks
|
||||
* through every folder, which is what a bot means by "list_files search":
|
||||
* scoping it to the root hid `images/summit-hero-pil.png` from the bot that
|
||||
* had just written it, and the bot went on to say the file was never saved.
|
||||
*/
|
||||
export default function botFilesFilter({ scopes, folder, recursive, search }: Params) {
|
||||
const owner_sql = scopes.map(() => `(scope = ? AND owner_id = ?)`).join(" OR ");
|
||||
const where = [owner_sql];
|
||||
const values: (string | number)[] = scopes.flatMap((s) => [s.scope, s.owner_id]);
|
||||
|
||||
const target = (folder || "").trim().replace(/\\/g, "/").replace(/^\/+|\/+$/g, "");
|
||||
|
||||
if (target) {
|
||||
where.push(recursive ? `(folder = ? OR folder LIKE ?)` : `folder = ?`);
|
||||
values.push(target);
|
||||
|
||||
if (recursive) values.push(`${target}/%`);
|
||||
} else if (typeof folder == "string" && !recursive) {
|
||||
/**
|
||||
* A folder was named (even as ""), so this is that folder's own
|
||||
* listing. No folder at all means every folder, not just the root.
|
||||
*/
|
||||
where.push(`(folder = '' OR folder IS NULL)`);
|
||||
}
|
||||
|
||||
if (search?.trim()) {
|
||||
where.push(`(name LIKE ? OR path LIKE ?)`);
|
||||
values.push(`%${search.trim()}%`, `%${search.trim()}%`);
|
||||
}
|
||||
|
||||
return { where, values };
|
||||
}
|
||||
@@ -2,17 +2,18 @@ import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
import type { BUN_SQLITE_COBBLE_BOT_FILES } from "@/db/types/db";
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
import type { StorageScope } from "@/src/utils/storage-access";
|
||||
import botFilesFilter from "./bot-files-filter";
|
||||
|
||||
type Params = {
|
||||
scopes: StorageScope[];
|
||||
/**
|
||||
* Only this directory's files (a folder path), or, with `recursive`,
|
||||
* everything under it.
|
||||
* Only this folder's files (a folder path), or, with `recursive`,
|
||||
* everything under it. Left out, every folder is listed.
|
||||
*/
|
||||
folder?: string | null;
|
||||
recursive?: boolean;
|
||||
/**
|
||||
* Match the name or the path, case-insensitive.
|
||||
* Match the name or the path, case-insensitive, in every folder.
|
||||
*/
|
||||
search?: string | null;
|
||||
limit?: number;
|
||||
@@ -31,32 +32,7 @@ export default async function listBotFiles({
|
||||
}: Params): Promise<BUN_SQLITE_COBBLE_BOT_FILES[]> {
|
||||
if (!scopes.length) return [];
|
||||
|
||||
const target = (folder || "").trim().replace(/\\/g, "/").replace(/^\/+|\/+$/g, "");
|
||||
|
||||
const owner_sql = scopes.map(() => `(scope = ? AND owner_id = ?)`).join(" OR ");
|
||||
const owner_values = scopes.flatMap((s) => [s.scope, s.owner_id]);
|
||||
|
||||
const where = [owner_sql];
|
||||
const values: (string | number)[] = [...owner_values];
|
||||
|
||||
if (target) {
|
||||
where.push(
|
||||
recursive
|
||||
? `(folder = ? OR folder LIKE ?)`
|
||||
: `folder = ?`,
|
||||
);
|
||||
|
||||
values.push(target);
|
||||
|
||||
if (recursive) values.push(`${target}/%`);
|
||||
} else if (!recursive) {
|
||||
where.push(`(folder = '' OR folder IS NULL)`);
|
||||
}
|
||||
|
||||
if (search?.trim()) {
|
||||
where.push(`(name LIKE ? OR path LIKE ?)`);
|
||||
values.push(`%${search.trim()}%`, `%${search.trim()}%`);
|
||||
}
|
||||
const { where, values } = botFilesFilter({ scopes, folder, recursive, search });
|
||||
|
||||
const res = await BunSQLite.sql<BUN_SQLITE_COBBLE_BOT_FILES>({
|
||||
sql: `SELECT * FROM bot_files WHERE ${where.join(" AND ")} ORDER BY updated_at DESC, id DESC LIMIT ?`,
|
||||
|
||||
@@ -6,7 +6,10 @@ import type {
|
||||
} from "@/db/types/db";
|
||||
import type { BotFilePurpose, BotFileScope, BotFileSource } from "@/src/dict/bot-file-dict";
|
||||
import type { MediaType } from "@/src/types";
|
||||
import AppError from "@/src/utils/app-error";
|
||||
import extensionOf from "@/src/utils/extension-of";
|
||||
import grabDirNames from "@/src/utils/grab-dir-names";
|
||||
import looksLikeImage from "@/src/utils/looks-like-image";
|
||||
import resolveBotPath from "@/src/utils/resolve-bot-path";
|
||||
import assertStorageRoom from "./assert-storage-room";
|
||||
import grabStorageDir from "./grab-storage-dir";
|
||||
@@ -71,6 +74,24 @@ export default async function recordBotFile({
|
||||
const existing = await grabBotFileRow({ scope, owner_id, path: resolved.relative });
|
||||
const previous_size = Number(existing?.size) || 0;
|
||||
|
||||
/**
|
||||
* What `write_file` saved as an image has to look like one: text under
|
||||
* `.png` became a 2.6 KB "image" the user could not open, while the
|
||||
* reply said a 1376x768 PNG was attached. Other writers make real bytes
|
||||
* (`generate_image`, an import, an upload), so only a bot's own write is
|
||||
* checked here.
|
||||
*/
|
||||
if (
|
||||
media_type_resolved == "image" &&
|
||||
source == "bot-write" &&
|
||||
extensionOf({ name: resolved.name }) != "svg" &&
|
||||
!looksLikeImage({ bytes })
|
||||
) {
|
||||
throw new AppError(
|
||||
`${resolved.relative} isn't an image: it was saved as text, so the user would get a file that does not open. Make it with generate_image (or transform_image), or bring it in with import_file.`,
|
||||
);
|
||||
}
|
||||
|
||||
await assertStorageRoom({
|
||||
scope,
|
||||
owner_id,
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import type { BUN_SQLITE_COBBLE_BOTS_QUEUE } from "@/db/types/db";
|
||||
import { BotWaitingStatusLine } from "@/src/dict/bot-queue-dict";
|
||||
import { BotComputerBusyStatusLine, BotWaitingStatusLine } from "@/src/dict/bot-queue-dict";
|
||||
import setBotFace from "../bots/set-bot-face";
|
||||
import answeringAskFace from "./answering-ask-face";
|
||||
import botWaitsOnComputer from "./bot-waits-on-computer";
|
||||
import countOpenBotJobs from "./count-open-bot-jobs";
|
||||
import grabRunningBotJobFace from "./grab-running-bot-job-face";
|
||||
|
||||
@@ -42,14 +43,16 @@ export default async function botFaceAfterJob({ bot_id, user_id, kind }: Params)
|
||||
}
|
||||
|
||||
/**
|
||||
* Jobs are open for this user but none is running (`deferBotJob` put
|
||||
* them back while every model rests, or they wait in the queue): the
|
||||
* bot waits, rather than showing work that isn't happening.
|
||||
* Jobs are open for this user but none is running: they wait in the
|
||||
* queue, behind another run on the same computer or while every model
|
||||
* rests (`deferBotJob`). The line says which, since "waiting for a free
|
||||
* model" over a run that is only second in line on a computer sends the
|
||||
* user looking at the wrong thing.
|
||||
*/
|
||||
return await setBotFace({
|
||||
bot_id,
|
||||
user_id,
|
||||
face: "asleep",
|
||||
status_line: BotWaitingStatusLine,
|
||||
status_line: (await botWaitsOnComputer({ bot_id, user_id })) ? BotComputerBusyStatusLine : BotWaitingStatusLine,
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
import { Database } from "bun:sqlite";
|
||||
import { beforeEach, describe, expect, test } from "bun:test";
|
||||
import { botWaitsOnComputerSql } from "./bot-waits-on-computer";
|
||||
|
||||
/**
|
||||
* Real SQLite: the face says "Waiting for its computer" only while a run
|
||||
* of this bot's user's is queued behind another task on that same
|
||||
* computer. Anything looser reads every queued run as a computer wait.
|
||||
*/
|
||||
const db = new Database(":memory:");
|
||||
|
||||
beforeEach(() => {
|
||||
db.run(`DROP TABLE IF EXISTS bots_queue`);
|
||||
db.run(`DROP TABLE IF EXISTS bot_sessions`);
|
||||
db.run(`DROP TABLE IF EXISTS bot_hooks`);
|
||||
db.run(`CREATE TABLE bots_queue (
|
||||
id INTEGER PRIMARY KEY,
|
||||
kind TEXT,
|
||||
status TEXT,
|
||||
bot_id INTEGER,
|
||||
session_id INTEGER,
|
||||
computer_id INTEGER
|
||||
)`);
|
||||
db.run(`CREATE TABLE bot_sessions (id INTEGER PRIMARY KEY, user_id INTEGER, ask_id INTEGER, hook_id INTEGER)`);
|
||||
db.run(`CREATE TABLE bot_hooks (id INTEGER PRIMARY KEY, silent INTEGER)`);
|
||||
});
|
||||
|
||||
function job(row: { id: number; kind: string; status: string; session_id: number; computer_id?: number | null }) {
|
||||
db.run(`INSERT INTO bots_queue (id, kind, status, bot_id, session_id, computer_id) VALUES (?, ?, ?, 1, ?, ?)`, [
|
||||
row.id,
|
||||
row.kind,
|
||||
row.status,
|
||||
row.session_id,
|
||||
row.computer_id ?? null,
|
||||
]);
|
||||
}
|
||||
|
||||
const waits = () => {
|
||||
const { sql, values } = botWaitsOnComputerSql({ bot_id: 1, user_id: 1 });
|
||||
|
||||
return db.query(sql).all(...values).length > 0;
|
||||
};
|
||||
|
||||
describe("botWaitsOnComputerSql", () => {
|
||||
test("a queued run behind a task on the same computer is waiting on it", () => {
|
||||
db.run(`INSERT INTO bot_sessions VALUES (10, 1, NULL, NULL)`);
|
||||
job({ id: 1, kind: "task", status: "processing", session_id: 10, computer_id: 4 });
|
||||
job({ id: 2, kind: "task", status: "pending", session_id: 10, computer_id: 4 });
|
||||
|
||||
expect(waits()).toBe(true);
|
||||
});
|
||||
|
||||
test("a queued run on another computer is not", () => {
|
||||
db.run(`INSERT INTO bot_sessions VALUES (10, 1, NULL, NULL)`);
|
||||
job({ id: 1, kind: "task", status: "processing", session_id: 10, computer_id: 4 });
|
||||
job({ id: 2, kind: "task", status: "pending", session_id: 10, computer_id: 5 });
|
||||
|
||||
expect(waits()).toBe(false);
|
||||
});
|
||||
|
||||
test("no reason yet is not a computer wait", () => {
|
||||
db.run(`INSERT INTO bot_sessions VALUES (10, 1, NULL, NULL)`);
|
||||
job({ id: 1, kind: "task", status: "processing", session_id: 10, computer_id: 4 });
|
||||
job({ id: 2, kind: "reply", status: "pending", session_id: 10, computer_id: null });
|
||||
|
||||
expect(waits()).toBe(false);
|
||||
});
|
||||
|
||||
test("another user's queue does not show on this face", () => {
|
||||
db.run(`INSERT INTO bot_sessions VALUES (10, 2, NULL, NULL)`);
|
||||
job({ id: 1, kind: "task", status: "processing", session_id: 10, computer_id: 4 });
|
||||
job({ id: 2, kind: "task", status: "pending", session_id: 10, computer_id: 4 });
|
||||
|
||||
expect(waits()).toBe(false);
|
||||
});
|
||||
|
||||
test("a queued run in a crew request or a silent hook's thread is not the user's wait", () => {
|
||||
db.run(`INSERT INTO bot_sessions VALUES (10, 1, NULL, NULL)`);
|
||||
db.run(`INSERT INTO bot_sessions VALUES (11, 1, 3, NULL)`);
|
||||
db.run(`INSERT INTO bot_hooks VALUES (2, 1)`);
|
||||
db.run(`INSERT INTO bot_sessions VALUES (12, 1, NULL, 2)`);
|
||||
job({ id: 1, kind: "task", status: "processing", session_id: 10, computer_id: 4 });
|
||||
job({ id: 2, kind: "task", status: "pending", session_id: 11, computer_id: 4 });
|
||||
job({ id: 3, kind: "task", status: "pending", session_id: 12, computer_id: 4 });
|
||||
|
||||
expect(waits()).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,43 @@
|
||||
import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
import followedSessionSql from "../bot-sessions/followed-session-sql";
|
||||
|
||||
type Params = {
|
||||
bot_id: number | string;
|
||||
/**
|
||||
* Only jobs in this user's conversations.
|
||||
*/
|
||||
user_id: number | string;
|
||||
};
|
||||
|
||||
/**
|
||||
* Whether a run of the bot's is queued behind another on the same computer.
|
||||
* `claimBotJobs` takes one task run per computer at a time, so a second one
|
||||
* waits for the first to end, however long that takes: with no job
|
||||
* processing, the bot's face said "waiting for a free model" when what it
|
||||
* waits on is the computer. Only jobs the user follows count, since a crew
|
||||
* request's or a silent hook's run never shows on the face.
|
||||
*/
|
||||
export default async function botWaitsOnComputer({ bot_id, user_id }: Params): Promise<boolean> {
|
||||
const res = await BunSQLite.sql<{ waiting: number }>(botWaitsOnComputerSql({ bot_id, user_id }));
|
||||
|
||||
return Boolean(res.payload?.[0]?.waiting);
|
||||
}
|
||||
|
||||
/**
|
||||
* The statement itself, checked against real SQLite
|
||||
* (`bot-waits-on-computer.test.ts`).
|
||||
*/
|
||||
export function botWaitsOnComputerSql({ bot_id, user_id }: Params) {
|
||||
return {
|
||||
sql: `SELECT 1 AS waiting FROM bots_queue AS queued
|
||||
WHERE queued.bot_id = ? AND queued.status = 'pending'
|
||||
AND queued.session_id IN (SELECT id FROM bot_sessions WHERE user_id = ? AND ${followedSessionSql()})
|
||||
AND EXISTS (
|
||||
SELECT 1 FROM bots_queue AS running
|
||||
WHERE running.status = 'processing' AND running.kind = 'task'
|
||||
AND running.computer_id = queued.computer_id
|
||||
)
|
||||
LIMIT 1`,
|
||||
values: [bot_id, user_id],
|
||||
};
|
||||
}
|
||||
@@ -9,6 +9,8 @@ import AppError from "@/src/utils/app-error";
|
||||
import grabUserBot from "../bots/grab-user-bot";
|
||||
import grabBotComputers from "../computers/grab-bot-computers";
|
||||
import grabUserBotSession from "../bot-sessions/grab-user-bot-session";
|
||||
import wakeBotsQueue from "@/src/bots-queue/wake-bots-queue";
|
||||
import pushBotUpdated from "@/src/bots-queue/push-bot-updated";
|
||||
|
||||
type Params = {
|
||||
/**
|
||||
@@ -160,6 +162,18 @@ export default async function enqueueBotJob({
|
||||
throw new Error(`Couldn't queue the job: ${res.msg || res.error}`);
|
||||
}
|
||||
|
||||
/**
|
||||
* The queue starts on this job now instead of at its next tick, and the
|
||||
* user is told about the run straight away: the bot's face and every
|
||||
* active task are pushed, so a queued run shows as one instead of
|
||||
* appearing when the queue happens to claim it (a run waiting behind
|
||||
* another on the same computer waits for that one to end). Best effort:
|
||||
* the push logs its own failure, and a queue not running in this process
|
||||
* picks the job up on its next poll.
|
||||
*/
|
||||
wakeBotsQueue();
|
||||
await pushBotUpdated({ bot_id: Number(bot.id), user_id: Number(user_id) });
|
||||
|
||||
return job_id;
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
|
||||
type Params = {
|
||||
/**
|
||||
* The bot message the retry runs again: a failure notice carries the
|
||||
* job that ended without an answer (`failed_job_id`).
|
||||
*/
|
||||
message_id: number | string;
|
||||
};
|
||||
|
||||
type Row = {
|
||||
failed_job_id: number | null;
|
||||
last_error: string | null;
|
||||
};
|
||||
|
||||
/**
|
||||
* Why the run behind a message ended without sending its answer: its
|
||||
* `failed_job_id` and that job's `last_error`. A retry reads it so it
|
||||
* doesn't set off on the same wrong premise a second time (the failure
|
||||
* notices themselves are app records, left out of the history the run
|
||||
* reads).
|
||||
*/
|
||||
export default async function grabRetryFailure({ message_id }: Params): Promise<{ job_id: number; reason: string } | null> {
|
||||
const res = await BunSQLite.sql<Row>({
|
||||
sql: `SELECT m.failed_job_id, q.last_error
|
||||
FROM bot_messages m
|
||||
LEFT JOIN bots_queue q ON q.id = m.failed_job_id
|
||||
WHERE m.id = ?
|
||||
LIMIT 1`,
|
||||
values: [Number(message_id) || 0],
|
||||
});
|
||||
|
||||
const row = res.payload?.[0];
|
||||
if (!row?.failed_job_id) return null;
|
||||
|
||||
return {
|
||||
job_id: Number(row.failed_job_id),
|
||||
reason: String(row.last_error || "").trim(),
|
||||
};
|
||||
}
|
||||
@@ -25,9 +25,8 @@ type Params = {
|
||||
|
||||
/**
|
||||
* Wraps up a job that is out of attempts: stamps `finished_at` (so it's
|
||||
* reported once), tells the user in the bot's conversation and sets the
|
||||
* bot to needs-you for that user. Its task stays active, since the work isn't done. A
|
||||
* handed-over job's failure also goes to the bot that handed it over, and
|
||||
* reported once), closes its own `bot_tasks` row, tells the user in the
|
||||
* bot's conversation and sets the bot to needs-you for that user. A handed-over job's failure also goes to the bot that handed it over, and
|
||||
* blocks the handed-over task it worked on (`noteTrackerTask`). A hook run's
|
||||
* calls keep why it failed (`recordHookCallResponse`). A job working a crew request ends it
|
||||
* (`onAskJobEnded`) and leaves the bot's face alone.
|
||||
@@ -45,6 +44,20 @@ export default async function notifyBotJobFailed({
|
||||
values: [Date.now(), job.id],
|
||||
});
|
||||
|
||||
/**
|
||||
* The run's own row is over too: left active it is the task every read
|
||||
* of `grabActiveBotTask` returns for that user, so the conversation
|
||||
* keeps showing a run that ended (one failed task in October was still
|
||||
* the active task of its conversation months later), and no later run's
|
||||
* progress could show in its place.
|
||||
*/
|
||||
if (job.task_id) {
|
||||
await BunSQLite.sql({
|
||||
sql: `UPDATE bot_tasks SET status = 'done', updated_at = ? WHERE id = ?`,
|
||||
values: [Date.now(), job.task_id],
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* A handed-over task's failed run links to that task.
|
||||
*/
|
||||
|
||||
@@ -1,10 +1,7 @@
|
||||
import type {
|
||||
BUN_SQLITE_COBBLE_BOT_TASK_STEPS,
|
||||
BUN_SQLITE_COBBLE_BOT_TASKS,
|
||||
} from "@/db/types/db";
|
||||
import type { BUN_SQLITE_COBBLE_BOT_TASKS } from "@/db/types/db";
|
||||
import type { BotTaskWithSteps } from "@/src/types";
|
||||
import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
import grabBotJobUpdates from "../bots-queue/grab-bot-job-updates";
|
||||
import withBotTaskSteps from "./with-bot-task-steps";
|
||||
|
||||
type Params = {
|
||||
bot_id: number | string;
|
||||
@@ -21,7 +18,9 @@ type Params = {
|
||||
/**
|
||||
* The bot's most recent active task (in one session or one user's
|
||||
* conversations, when given), its
|
||||
* steps and what its job has done so far, for the working-on panel.
|
||||
* steps and what its job has done so far, for the working-on panel. A push
|
||||
* sends every active task instead (`grabActiveBotTasks`), since this one
|
||||
* may belong to a conversation the viewer isn't reading.
|
||||
*/
|
||||
export default async function grabActiveBotTask({
|
||||
bot_id,
|
||||
@@ -42,14 +41,5 @@ export default async function grabActiveBotTask({
|
||||
return null;
|
||||
}
|
||||
|
||||
const steps_res = await BunSQLite.sql<BUN_SQLITE_COBBLE_BOT_TASK_STEPS>({
|
||||
sql: `SELECT * FROM bot_task_steps WHERE task_id = ? ORDER BY position ASC, id ASC`,
|
||||
values: [task.id],
|
||||
});
|
||||
|
||||
return {
|
||||
...task,
|
||||
steps: steps_res.payload || [],
|
||||
updates: await grabBotJobUpdates({ task_id: task.id }),
|
||||
};
|
||||
}
|
||||
return withBotTaskSteps({ task });
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
import type { BUN_SQLITE_COBBLE_BOT_TASKS } from "@/db/types/db";
|
||||
import type { BotTaskWithSteps } from "@/src/types";
|
||||
import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
import withBotTaskSteps from "./with-bot-task-steps";
|
||||
|
||||
type Params = {
|
||||
bot_id: number | string;
|
||||
/**
|
||||
* Only tasks in this user's conversations.
|
||||
*/
|
||||
user_id?: number | string | null;
|
||||
};
|
||||
|
||||
/**
|
||||
* How many active tasks a push carries. A bot has at most one run per
|
||||
* computer and one reply per session, so a handful of conversations are
|
||||
* ever running at once; the newest few are enough for a viewer to find its
|
||||
* own, and a list that grows with the whole crew's history is not.
|
||||
*/
|
||||
const BotActiveTasksShown = 10;
|
||||
|
||||
/**
|
||||
* Every active task the user has with the bot, newest first. A push can't
|
||||
* know which conversation the viewer is looking at, and sending only the
|
||||
* newest left the one they were reading with no task at all whenever
|
||||
* another run was open elsewhere (`use-task-progress` drops a task from
|
||||
* another session), so the page is sent them all and picks its own.
|
||||
*/
|
||||
export default async function grabActiveBotTasks({ bot_id, user_id }: Params): Promise<BotTaskWithSteps[]> {
|
||||
const res = await BunSQLite.sql<BUN_SQLITE_COBBLE_BOT_TASKS>({
|
||||
sql: `SELECT * FROM bot_tasks WHERE bot_id = ? AND status = 'active'
|
||||
${user_id ? `AND session_id IN (SELECT id FROM bot_sessions WHERE user_id = ?)` : ""}
|
||||
ORDER BY created_at DESC, id DESC LIMIT ${BotActiveTasksShown}`,
|
||||
values: [bot_id, ...(user_id ? [user_id] : [])],
|
||||
});
|
||||
|
||||
const tasks = res.payload || [];
|
||||
|
||||
return await Promise.all(tasks.map((task) => withBotTaskSteps({ task })));
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
import type { BUN_SQLITE_COBBLE_BOT_TASK_STEPS, BUN_SQLITE_COBBLE_BOT_TASKS } from "@/db/types/db";
|
||||
import type { BotTaskWithSteps } from "@/src/types";
|
||||
import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
import grabBotJobUpdates from "../bots-queue/grab-bot-job-updates";
|
||||
|
||||
type Params = {
|
||||
task: BUN_SQLITE_COBBLE_BOT_TASKS;
|
||||
};
|
||||
|
||||
/**
|
||||
* A `bot_tasks` row with its steps and what its job has done so far, for
|
||||
* the working-on panel: what one active task is read as, whether it's the
|
||||
* newest of its bot or one of several in different conversations.
|
||||
*/
|
||||
export default async function withBotTaskSteps({ task }: Params): Promise<BotTaskWithSteps> {
|
||||
const steps_res = await BunSQLite.sql<BUN_SQLITE_COBBLE_BOT_TASK_STEPS>({
|
||||
sql: `SELECT * FROM bot_task_steps WHERE task_id = ? ORDER BY position ASC, id ASC`,
|
||||
values: [Number(task.id)],
|
||||
});
|
||||
|
||||
return {
|
||||
...task,
|
||||
steps: steps_res.payload || [],
|
||||
updates: await grabBotJobUpdates({ task_id: Number(task.id) }),
|
||||
};
|
||||
}
|
||||
@@ -15,6 +15,7 @@ import checkProposalData from "./check-proposal-data";
|
||||
import claimExtensionProposal from "./claim-extension-proposal";
|
||||
import grabExtensionProposal from "./grab-extension-proposal";
|
||||
import grabProposalEnvs from "./grab-proposal-envs";
|
||||
import replacePendingExtensionProposals from "./replace-pending-extension-proposals";
|
||||
|
||||
type Params = {
|
||||
user_id: number | string;
|
||||
@@ -34,6 +35,24 @@ export default async function confirmExtensionProposal({ user_id, proposal_id }:
|
||||
|
||||
await claimExtensionProposal({ proposal, status: "confirmed" });
|
||||
|
||||
/**
|
||||
* Every other pending card for the same thing is replaced now that one
|
||||
* was confirmed: a card left pending can still be pressed, and its
|
||||
* outcome is already written (proposal #41 dangled a day after #42
|
||||
* made the same skill).
|
||||
*/
|
||||
await replacePendingExtensionProposals({
|
||||
proposal_id: proposal.id,
|
||||
user_id: proposal.user_id,
|
||||
bot_id: proposal.bot_id,
|
||||
workspace_id: proposal.workspace_id,
|
||||
kind: proposal.kind,
|
||||
slug: proposal.kind == "skill" ? proposal.data.slug : null,
|
||||
extension_id: proposal.extension_id,
|
||||
name: proposal.data.name,
|
||||
reason: `Replaced by proposal #${proposal.id}, which was confirmed.`,
|
||||
});
|
||||
|
||||
try {
|
||||
if (proposal.kind == "skill") {
|
||||
const current = proposal.extension_id ? await grabSkill({ skill_id: proposal.extension_id }) : null;
|
||||
|
||||
@@ -3,6 +3,7 @@ import type { BUN_SQLITE_COBBLE_EXTENSION_PROPOSALS, BunSQLiteTables } from "@/d
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
import type { SaveCustomToolRequest, SaveMcpServerRequest, SaveSkillRequest } from "@/src/schemas/extension-schema";
|
||||
import checkProposalData from "./check-proposal-data";
|
||||
import replacePendingExtensionProposals from "./replace-pending-extension-proposals";
|
||||
|
||||
type Params = {
|
||||
user_id: number | string;
|
||||
@@ -21,9 +22,9 @@ type Params = {
|
||||
* Stores what a bot proposes adding or changing (an MCP server, a tool or
|
||||
* a skill), pending until the user
|
||||
* confirms it from the chat. Nothing is saved, connected or run here. A
|
||||
* proposal it makes again for the same server or tool in the same
|
||||
* conversation replaces the one before, so only the latest card can be
|
||||
* confirmed. Returns its id.
|
||||
* proposal it makes again for the same thing in the same conversation
|
||||
* replaces the one before, so only the latest card can be confirmed.
|
||||
* Returns its id.
|
||||
*/
|
||||
export default async function createExtensionProposal(params: Params) {
|
||||
if (params.kind != "skill") checkProposalData(params);
|
||||
@@ -61,19 +62,15 @@ export default async function createExtensionProposal(params: Params) {
|
||||
|
||||
if (!res.success || !id) throw new Error(`Couldn't store the proposal: ${res.msg}`);
|
||||
|
||||
await BunSQLite.sql({
|
||||
sql: `UPDATE extension_proposals SET status = 'replaced', outcome = ?, decided_at = ?, updated_at = ?
|
||||
WHERE session_id = ? AND kind = ? AND status = 'pending' AND id != ?
|
||||
AND (${extension_id ? "extension_id = ?" : "extension_id IS NULL AND name = ? COLLATE NOCASE"})`,
|
||||
values: [
|
||||
`Replaced by proposal #${id}.`,
|
||||
now,
|
||||
now,
|
||||
Number(params.session_id),
|
||||
params.kind,
|
||||
id,
|
||||
extension_id || params.data.name,
|
||||
],
|
||||
await replacePendingExtensionProposals({
|
||||
proposal_id: id,
|
||||
user_id: params.user_id,
|
||||
bot_id: params.bot_id,
|
||||
workspace_id: params.workspace_id,
|
||||
kind: params.kind,
|
||||
slug: params.kind == "skill" ? params.data.slug : null,
|
||||
extension_id,
|
||||
name: params.data.name,
|
||||
});
|
||||
|
||||
return id;
|
||||
|
||||
@@ -28,6 +28,7 @@ export type ExtensionProposalRecord = {
|
||||
user_id: number;
|
||||
bot_id: number;
|
||||
session_id: number;
|
||||
workspace_id: number | null;
|
||||
} & (
|
||||
| { kind: "mcp"; data: SaveMcpServerRequest }
|
||||
| { kind: "tool"; data: SaveCustomToolRequest }
|
||||
@@ -54,6 +55,7 @@ export default function parseProposalRow({ row }: Params): ExtensionProposalReco
|
||||
user_id: Number(row.user_id),
|
||||
bot_id: Number(row.bot_id),
|
||||
session_id: Number(row.session_id),
|
||||
workspace_id: row.workspace_id ? Number(row.workspace_id) : null,
|
||||
};
|
||||
|
||||
if (kind == "mcp") return { ...base, kind, data: parseWithSchema({ schema: SaveMcpServerRequestSchema, data: raw }) };
|
||||
|
||||
+145
@@ -0,0 +1,145 @@
|
||||
import { Database, type SQLQueryBindings } from "bun:sqlite";
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { replacePendingExtensionProposalsSql } from "./replace-pending-extension-proposals";
|
||||
|
||||
/**
|
||||
* Run against real SQLite: the point of the statement is which rows it
|
||||
* leaves alone. Production kept proposal #41 (Co-Marketing, session 145)
|
||||
* pending for ever while #42 made the same skill in session 146, and
|
||||
* RevOps was proposed four times under two names, all slug `revops`.
|
||||
*/
|
||||
function fresh() {
|
||||
const db = new Database(":memory:");
|
||||
|
||||
db.run(`CREATE TABLE extension_proposals (
|
||||
id INTEGER PRIMARY KEY,
|
||||
name TEXT,
|
||||
data TEXT,
|
||||
extension_id INTEGER,
|
||||
kind TEXT,
|
||||
status TEXT,
|
||||
outcome TEXT,
|
||||
decided_at INTEGER,
|
||||
updated_at INTEGER,
|
||||
user_id INTEGER,
|
||||
bot_id INTEGER,
|
||||
session_id INTEGER,
|
||||
workspace_id INTEGER
|
||||
)`);
|
||||
|
||||
const insert = db.prepare(`INSERT INTO extension_proposals
|
||||
(id, name, data, extension_id, kind, status, user_id, bot_id, session_id, workspace_id)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`);
|
||||
|
||||
insert.run(41, "Co-Marketing", `{"slug":"co-marketing"}`, null, "skill", "pending", 1, 1, 145, null);
|
||||
insert.run(42, "Co-Marketing", `{"slug":"co-marketing"}`, null, "skill", "confirmed", 1, 1, 146, null);
|
||||
insert.run(43, "Referrals & Affiliates", `{"slug":"referrals"}`, null, "skill", "confirmed", 1, 1, 145, null);
|
||||
insert.run(44, "Referrals", `{"slug":"referrals"}`, null, "skill", "failed", 1, 1, 146, null);
|
||||
insert.run(62, "RevOps", `{"slug":"revops"}`, null, "skill", "pending", 1, 1, 146, null);
|
||||
insert.run(63, "Revenue Operations (RevOps)", `{"slug":"revops"}`, null, "skill", "confirmed", 1, 1, 146, null);
|
||||
insert.run(70, "Lead Magnets", `{"slug":"lead-magnets"}`, null, "skill", "pending", 1, 1, 146, null);
|
||||
insert.run(71, "Link Building", `{"slug":"link-building"}`, 12, "skill", "pending", 1, 1, 146, null);
|
||||
insert.run(72, "Some Server", `{}`, null, "mcp", "pending", 1, 1, 146, null);
|
||||
insert.run(73, "Some Server", `{}`, null, "mcp", "pending", 2, 1, 146, null);
|
||||
insert.run(74, "Some Server", `{}`, null, "mcp", "pending", 1, 1, 146, 3);
|
||||
insert.run(75, "Fetch Tool", `{}`, null, "tool", "pending", 1, 1, 146, null);
|
||||
insert.run(76, "Changed Tool", `{}`, 9, "tool", "pending", 1, 1, 146, null);
|
||||
insert.run(77, "Another Tool", `{}`, 10, "tool", "pending", 1, 1, 146, null);
|
||||
|
||||
return db;
|
||||
}
|
||||
|
||||
function replace(
|
||||
db: Database,
|
||||
params: Parameters<typeof replacePendingExtensionProposalsSql>[0],
|
||||
) {
|
||||
const { sql, values } = replacePendingExtensionProposalsSql(params);
|
||||
|
||||
db.run(sql, values as SQLQueryBindings[]);
|
||||
}
|
||||
|
||||
const statuses = (db: Database) =>
|
||||
Object.fromEntries(
|
||||
(db.query(`SELECT id, status FROM extension_proposals`).all() as { id: number; status: string }[]).map((row) => [
|
||||
row.id,
|
||||
row.status,
|
||||
]),
|
||||
);
|
||||
|
||||
describe("replacePendingExtensionProposalsSql", () => {
|
||||
test("replaces a skill proposed again in a later session of the same conversation", () => {
|
||||
const db = fresh();
|
||||
|
||||
replace(db, {
|
||||
proposal_id: 63,
|
||||
user_id: 1,
|
||||
bot_id: 1,
|
||||
kind: "skill",
|
||||
slug: "revops",
|
||||
name: "Revenue Operations (RevOps)",
|
||||
});
|
||||
|
||||
const status = statuses(db);
|
||||
|
||||
expect(status[62]).toBe("replaced");
|
||||
expect(status[63]).toBe("confirmed");
|
||||
expect(status[70]).toBe("pending");
|
||||
expect(status[41]).toBe("pending");
|
||||
});
|
||||
|
||||
test("does not mark a skill's proposal replaced by another skill's", () => {
|
||||
const db = fresh();
|
||||
|
||||
replace(db, {
|
||||
proposal_id: 70,
|
||||
user_id: 1,
|
||||
bot_id: 1,
|
||||
kind: "skill",
|
||||
slug: "lead-magnets",
|
||||
name: "Lead Magnets",
|
||||
});
|
||||
|
||||
const status = statuses(db);
|
||||
|
||||
expect(status[62]).toBe("pending");
|
||||
expect(status[71]).toBe("pending");
|
||||
expect(Object.values(status).filter((value) => value == "replaced")).toEqual([]);
|
||||
});
|
||||
|
||||
test("a server compares the name when the proposal changes nothing yet", () => {
|
||||
const db = fresh();
|
||||
|
||||
replace(db, {
|
||||
proposal_id: 78,
|
||||
user_id: 1,
|
||||
bot_id: 1,
|
||||
kind: "mcp",
|
||||
name: "Some Server",
|
||||
});
|
||||
|
||||
const status = statuses(db);
|
||||
|
||||
expect(status[72]).toBe("replaced");
|
||||
expect(status[73]).toBe("pending");
|
||||
expect(status[74]).toBe("pending");
|
||||
});
|
||||
|
||||
test("a tool compares the extension it changes", () => {
|
||||
const db = fresh();
|
||||
|
||||
replace(db, {
|
||||
proposal_id: 78,
|
||||
user_id: 1,
|
||||
bot_id: 1,
|
||||
kind: "tool",
|
||||
extension_id: 9,
|
||||
name: "Changed Tool",
|
||||
});
|
||||
|
||||
const status = statuses(db);
|
||||
|
||||
expect(status[76]).toBe("replaced");
|
||||
expect(status[75]).toBe("pending");
|
||||
expect(status[77]).toBe("pending");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,122 @@
|
||||
import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
|
||||
type Params = {
|
||||
/** The proposal just stored, or just confirmed. */
|
||||
proposal_id: number | string;
|
||||
user_id: number | string;
|
||||
bot_id: number | string;
|
||||
workspace_id?: number | string | null;
|
||||
kind: "mcp" | "tool" | "skill";
|
||||
/**
|
||||
* A skill's slug: it names the one skill a proposal is about, including
|
||||
* one that doesn't exist yet, and is what makes two of them the same.
|
||||
*/
|
||||
slug?: string | null;
|
||||
/**
|
||||
* The extension a proposal changes; a new one has none.
|
||||
*/
|
||||
extension_id?: number | string | null;
|
||||
name: string;
|
||||
/**
|
||||
* What the replaced card says, when it wasn't a newer proposal that
|
||||
* took its place.
|
||||
*/
|
||||
reason?: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* Marks every pending proposal for the same thing replaced, in the same
|
||||
* conversation: only the latest card can be confirmed, and an older one
|
||||
* left pending is a card the user can still press whose outcome is already
|
||||
* written. Scoped by user, bot and workspace rather than by session, since
|
||||
* a conversation that carries on into a new session keeps proposing into
|
||||
* it: proposal #41 (Co-Marketing, session 145) was made again 36 seconds
|
||||
* later in session 146 and confirmed there, and #41 stayed pending for
|
||||
* ever. For a skill the slug decides it (RevOps was proposed four times
|
||||
* under two names, all slug `revops`); for a server or tool it is the
|
||||
* extension itself, else the name.
|
||||
*/
|
||||
export default async function replacePendingExtensionProposals({
|
||||
proposal_id,
|
||||
user_id,
|
||||
bot_id,
|
||||
workspace_id,
|
||||
kind,
|
||||
slug,
|
||||
extension_id,
|
||||
name,
|
||||
reason,
|
||||
}: Params) {
|
||||
const { sql, values } = replacePendingExtensionProposalsSql({
|
||||
proposal_id,
|
||||
user_id,
|
||||
bot_id,
|
||||
workspace_id,
|
||||
kind,
|
||||
slug,
|
||||
extension_id,
|
||||
name,
|
||||
reason,
|
||||
});
|
||||
|
||||
await BunSQLite.sql({ sql, values });
|
||||
}
|
||||
|
||||
/**
|
||||
* The statement itself, so the conditions are checked against real SQLite
|
||||
* (`replace-pending-extension-proposals.test.ts`): a wrong one either
|
||||
* leaves a card the user can still press or replaces a different skill's.
|
||||
*/
|
||||
export function replacePendingExtensionProposalsSql({
|
||||
proposal_id,
|
||||
user_id,
|
||||
bot_id,
|
||||
workspace_id,
|
||||
kind,
|
||||
slug,
|
||||
extension_id,
|
||||
name,
|
||||
reason,
|
||||
}: Params) {
|
||||
const now = Date.now();
|
||||
const target = targetSql({ slug, extension_id, name });
|
||||
|
||||
return {
|
||||
sql: `UPDATE extension_proposals SET status = 'replaced', outcome = ?, decided_at = ?, updated_at = ?
|
||||
WHERE user_id = ? AND bot_id = ? AND COALESCE(workspace_id, 0) = ? AND kind = ?
|
||||
AND status = 'pending' AND id != ?
|
||||
AND ${target.sql}`,
|
||||
values: [
|
||||
reason || `Replaced by proposal #${proposal_id}.`,
|
||||
now,
|
||||
now,
|
||||
Number(user_id),
|
||||
Number(bot_id),
|
||||
Number(workspace_id) || 0,
|
||||
kind,
|
||||
Number(proposal_id),
|
||||
target.value,
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* What makes two proposals about the same thing: a skill's slug, the
|
||||
* extension being changed, or a new one's name compared with spaces,
|
||||
* hyphens and underscores taken out ("Rev Ops" and "rev-ops" are one name).
|
||||
*/
|
||||
function targetSql({ slug, extension_id, name }: { slug?: string | null; extension_id?: number | string | null; name: string }) {
|
||||
const skill_slug = slug?.trim().toLowerCase() || "";
|
||||
|
||||
if (skill_slug) return { sql: "lower(json_extract(data, '$.slug')) = ?", value: skill_slug };
|
||||
|
||||
if (extension_id) return { sql: "extension_id = ?", value: Number(extension_id) };
|
||||
|
||||
return {
|
||||
sql: "extension_id IS NULL AND lower(replace(replace(replace(trim(name), ' ', ''), '-', ''), '_', '')) = ?",
|
||||
value: name
|
||||
.trim()
|
||||
.toLowerCase()
|
||||
.replace(/[ _-]+/g, ""),
|
||||
};
|
||||
}
|
||||
@@ -6,6 +6,7 @@ import updateBotHook from "../bot-hooks/update-bot-hook";
|
||||
import checkHookProposal from "./check-hook-proposal";
|
||||
import claimHookProposal from "./claim-hook-proposal";
|
||||
import grabHookProposal from "./grab-hook-proposal";
|
||||
import replacePendingHookProposals from "./replace-pending-hook-proposals";
|
||||
|
||||
type Params = {
|
||||
user_id: number | string;
|
||||
@@ -27,6 +28,16 @@ export default async function confirmHookProposal({ user_id, proposal_id }: Para
|
||||
|
||||
await claimHookProposal({ proposal, status: "confirmed" });
|
||||
|
||||
await replacePendingHookProposals({
|
||||
proposal_id: proposal.id,
|
||||
user_id: proposal.user_id,
|
||||
bot_id: proposal.bot_id,
|
||||
workspace_id: proposal.workspace_id,
|
||||
hook_id: proposal.hook_id,
|
||||
title: proposal.title,
|
||||
reason: `Replaced by proposal #${proposal.id}, which was confirmed.`,
|
||||
});
|
||||
|
||||
let token: string | undefined;
|
||||
|
||||
try {
|
||||
|
||||
@@ -3,6 +3,7 @@ import type { BUN_SQLITE_COBBLE_HOOK_PROPOSALS, BunSQLiteTables } from "@/db/typ
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
import type { HookProposalData } from "@/src/schemas/bot-hook-schema";
|
||||
import checkHookProposal from "./check-hook-proposal";
|
||||
import replacePendingHookProposals from "./replace-pending-hook-proposals";
|
||||
|
||||
type Params = {
|
||||
user_id: number | string;
|
||||
@@ -60,18 +61,13 @@ export default async function createHookProposal({
|
||||
|
||||
if (!res.success || !id) throw new Error(`Couldn't store the proposal: ${res.msg}`);
|
||||
|
||||
await BunSQLite.sql({
|
||||
sql: `UPDATE hook_proposals SET status = 'replaced', outcome = ?, decided_at = ?, updated_at = ?
|
||||
WHERE session_id = ? AND status = 'pending' AND id != ?
|
||||
AND (${checked.current?.id ? "hook_id = ?" : "hook_id IS NULL AND title = ? COLLATE NOCASE"})`,
|
||||
values: [
|
||||
`Replaced by proposal #${id}.`,
|
||||
now,
|
||||
now,
|
||||
Number(session_id),
|
||||
id,
|
||||
checked.current?.id || checked.title,
|
||||
],
|
||||
await replacePendingHookProposals({
|
||||
proposal_id: id,
|
||||
user_id,
|
||||
bot_id,
|
||||
workspace_id,
|
||||
hook_id: checked.current?.id,
|
||||
title: checked.title,
|
||||
});
|
||||
|
||||
return id;
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
import { Database, type SQLQueryBindings } from "bun:sqlite";
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { replacePendingHookProposalsSql } from "./replace-pending-hook-proposals";
|
||||
|
||||
/**
|
||||
* A conversation carried into a new session keeps proposing into it, so a
|
||||
* pending card for the same hook (or the same new name) is marked replaced
|
||||
* across sessions, never left for the user to press after its outcome was
|
||||
* written.
|
||||
*/
|
||||
function fresh() {
|
||||
const db = new Database(":memory:");
|
||||
|
||||
db.run(`CREATE TABLE hook_proposals (
|
||||
id INTEGER PRIMARY KEY,
|
||||
hook_id INTEGER,
|
||||
title TEXT,
|
||||
status TEXT,
|
||||
outcome TEXT,
|
||||
decided_at INTEGER,
|
||||
updated_at INTEGER,
|
||||
user_id INTEGER,
|
||||
bot_id INTEGER,
|
||||
session_id INTEGER,
|
||||
workspace_id INTEGER
|
||||
)`);
|
||||
|
||||
const insert = db.prepare(`INSERT INTO hook_proposals
|
||||
(id, hook_id, title, status, user_id, bot_id, session_id, workspace_id)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?)`);
|
||||
|
||||
insert.run(1, null, "Inbox Digest", "pending", 1, 1, 145, null);
|
||||
insert.run(2, null, "inbox digest", "pending", 1, 1, 146, null);
|
||||
insert.run(3, null, "Inbox Digest", "confirmed", 1, 1, 146, null);
|
||||
insert.run(4, 7, "Nightly Build", "pending", 1, 1, 146, null);
|
||||
insert.run(5, 8, "Nightly Build", "pending", 1, 1, 146, null);
|
||||
insert.run(6, null, "Inbox Digest", "pending", 2, 1, 146, null);
|
||||
|
||||
return db;
|
||||
}
|
||||
|
||||
function replace(db: Database, params: Parameters<typeof replacePendingHookProposalsSql>[0]) {
|
||||
const { sql, values } = replacePendingHookProposalsSql(params);
|
||||
|
||||
db.run(sql, values as SQLQueryBindings[]);
|
||||
}
|
||||
|
||||
const statuses = (db: Database) =>
|
||||
Object.fromEntries(
|
||||
(db.query(`SELECT id, status FROM hook_proposals`).all() as { id: number; status: string }[]).map((row) => [
|
||||
row.id,
|
||||
row.status,
|
||||
]),
|
||||
);
|
||||
|
||||
describe("replacePendingHookProposalsSql", () => {
|
||||
test("replaces a new hook proposed again under the same name in a later session", () => {
|
||||
const db = fresh();
|
||||
|
||||
replace(db, { proposal_id: 2, user_id: 1, bot_id: 1, title: "inbox digest" });
|
||||
|
||||
const status = statuses(db);
|
||||
|
||||
expect(status[1]).toBe("replaced");
|
||||
expect(status[3]).toBe("confirmed");
|
||||
expect(status[6]).toBe("pending");
|
||||
expect(status[4]).toBe("pending");
|
||||
});
|
||||
|
||||
test("a hook that exists is compared by the hook, not by its title", () => {
|
||||
const db = fresh();
|
||||
|
||||
replace(db, { proposal_id: 9, user_id: 1, bot_id: 1, hook_id: 7, title: "Nightly Build" });
|
||||
|
||||
const status = statuses(db);
|
||||
|
||||
expect(status[4]).toBe("replaced");
|
||||
expect(status[5]).toBe("pending");
|
||||
expect(status[1]).toBe("pending");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,79 @@
|
||||
import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
|
||||
type Params = {
|
||||
/** The proposal just stored, or just confirmed. */
|
||||
proposal_id: number | string;
|
||||
user_id: number | string;
|
||||
bot_id: number | string;
|
||||
workspace_id?: number | string | null;
|
||||
/**
|
||||
* The hook it changes; none for a new one.
|
||||
*/
|
||||
hook_id?: number | string | null;
|
||||
title: string;
|
||||
/**
|
||||
* What the replaced card says, when it wasn't a newer proposal that
|
||||
* took its place.
|
||||
*/
|
||||
reason?: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* Marks every pending hook proposal for the same hook, or the same new
|
||||
* name, replaced: only the latest card can be confirmed. Scoped by user,
|
||||
* bot and workspace rather than by session, the same way an extension
|
||||
* proposal is (`replacePendingExtensionProposals`), since a conversation
|
||||
* carried into a new session keeps proposing into it.
|
||||
*/
|
||||
export default async function replacePendingHookProposals({
|
||||
proposal_id,
|
||||
user_id,
|
||||
bot_id,
|
||||
workspace_id,
|
||||
hook_id,
|
||||
title,
|
||||
reason,
|
||||
}: Params) {
|
||||
await BunSQLite.sql(
|
||||
replacePendingHookProposalsSql({ proposal_id, user_id, bot_id, workspace_id, hook_id, title, reason }),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* The statement itself, checked against real SQLite
|
||||
* (`replace-pending-hook-proposals.test.ts`).
|
||||
*/
|
||||
export function replacePendingHookProposalsSql({
|
||||
proposal_id,
|
||||
user_id,
|
||||
bot_id,
|
||||
workspace_id,
|
||||
hook_id,
|
||||
title,
|
||||
reason,
|
||||
}: Params) {
|
||||
const now = Date.now();
|
||||
const changed = Boolean(Number(hook_id));
|
||||
|
||||
return {
|
||||
sql: `UPDATE hook_proposals SET status = 'replaced', outcome = ?, decided_at = ?, updated_at = ?
|
||||
WHERE user_id = ? AND bot_id = ? AND COALESCE(workspace_id, 0) = ?
|
||||
AND status = 'pending' AND id != ?
|
||||
AND (${changed ? "hook_id = ?" : "hook_id IS NULL AND lower(replace(replace(replace(trim(title), ' ', ''), '-', ''), '_', '')) = ?"})`,
|
||||
values: [
|
||||
reason || `Replaced by proposal #${proposal_id}.`,
|
||||
now,
|
||||
now,
|
||||
Number(user_id),
|
||||
Number(bot_id),
|
||||
Number(workspace_id) || 0,
|
||||
Number(proposal_id),
|
||||
changed
|
||||
? Number(hook_id)
|
||||
: title
|
||||
.trim()
|
||||
.toLowerCase()
|
||||
.replace(/[ _-]+/g, ""),
|
||||
],
|
||||
};
|
||||
}
|
||||
@@ -29,10 +29,6 @@ mock.module("./provider-request", () => ({
|
||||
},
|
||||
}));
|
||||
|
||||
mock.module("../grab-provider-preset", () => ({
|
||||
default: () => ({ title: "TestProvider", video_path: "/videos" }),
|
||||
}));
|
||||
|
||||
const { default: generateVideo } = await import("./generate-video");
|
||||
|
||||
afterAll(() => mock.restore());
|
||||
|
||||
@@ -1786,12 +1786,14 @@ describe("runTextLoop closing tools", () => {
|
||||
});
|
||||
|
||||
describe("runTextLoop required send_reply", () => {
|
||||
const sendReply: HarnessTool<{ status: "done" | "working" | "blocked"; work?: unknown }> = {
|
||||
const sendReply: HarnessTool<{ status?: "done" | "working" | "blocked"; work?: unknown; message?: string; text?: string }> = {
|
||||
name: "send_reply",
|
||||
description: "Sends the message.",
|
||||
schema: z.object({
|
||||
status: z.enum(["done", "working", "blocked"]),
|
||||
status: z.enum(["done", "working", "blocked"]).optional(),
|
||||
work: z.unknown().optional(),
|
||||
message: z.string().optional(),
|
||||
text: z.string().optional(),
|
||||
}),
|
||||
run: async () => "Sent.",
|
||||
};
|
||||
@@ -2165,6 +2167,125 @@ describe("runTextLoop required send_reply", () => {
|
||||
expect(seen[1]!.tools!.map((tool) => tool.name)).toEqual(["send_reply"]);
|
||||
expect(result.text).toBe("Report.");
|
||||
});
|
||||
|
||||
test("send_reply with text in tool arguments sends the message directly", async () => {
|
||||
const { generate } = scripted([
|
||||
{
|
||||
tool_calls: [
|
||||
{
|
||||
id: "s1",
|
||||
name: "send_reply",
|
||||
arguments: JSON.stringify({ status: "done", text: "Here is your skill." }),
|
||||
},
|
||||
],
|
||||
},
|
||||
]);
|
||||
|
||||
const result = await runTextLoop({
|
||||
system: "s",
|
||||
messages: [{ role: "user", content: "Install skill." }],
|
||||
tools: [sendReply],
|
||||
generate,
|
||||
resolveCandidates,
|
||||
require_closing_answer: true,
|
||||
});
|
||||
|
||||
expect(result.text).toBe("Here is your skill.");
|
||||
expect(result.steps).toBe(1);
|
||||
});
|
||||
|
||||
test("send_reply with message in tool arguments and no status defaults to done and sends the message", async () => {
|
||||
const { generate } = scripted([
|
||||
{
|
||||
tool_calls: [
|
||||
{
|
||||
id: "s1",
|
||||
name: "send_reply",
|
||||
arguments: JSON.stringify({ message: "Link-building next, as you picked." }),
|
||||
},
|
||||
],
|
||||
},
|
||||
]);
|
||||
|
||||
const result = await runTextLoop({
|
||||
system: "s",
|
||||
messages: [{ role: "user", content: "What next?" }],
|
||||
tools: [sendReply],
|
||||
generate,
|
||||
resolveCandidates,
|
||||
require_closing_answer: true,
|
||||
});
|
||||
|
||||
expect(result.text).toBe("Link-building next, as you picked.");
|
||||
expect(result.steps).toBe(1);
|
||||
});
|
||||
|
||||
test("a message written beside a card goes out when send_reply follows alone", async () => {
|
||||
/**
|
||||
* Session 146, job 795: the model wrote the whole answer in the
|
||||
* turn that put the question up, the loop asked for `send_reply`,
|
||||
* and the next turn had nothing left to say. The sentence beside
|
||||
* the card is that card's sentence, so it is kept.
|
||||
*/
|
||||
asked.length = 0;
|
||||
const { generate } = scripted([
|
||||
{
|
||||
text: "RevOps is proposed. Which skill should I take next?",
|
||||
tool_calls: [{ id: "q1", name: "ask_user", arguments: `{"question":"Which skill next?"}` }],
|
||||
},
|
||||
{ tool_calls: [{ id: "s1", name: "send_reply", arguments: `{"status":"done"}` }] },
|
||||
]);
|
||||
|
||||
const result = await runTextLoop({
|
||||
system: "s",
|
||||
messages: [{ role: "user", content: "Propose RevOps, then ask me." }],
|
||||
tools: [askUser, sendReply],
|
||||
generate,
|
||||
resolveCandidates,
|
||||
require_closing_answer: true,
|
||||
});
|
||||
|
||||
expect(result.text).toBe("RevOps is proposed. Which skill should I take next?");
|
||||
expect(result.steps).toBe(2);
|
||||
expect(asked).toEqual(["Which skill next?"]);
|
||||
});
|
||||
|
||||
test("an answer the review sends back is never carried a second time", async () => {
|
||||
/**
|
||||
* Session 146, job 785: the refused draft stayed held, so every
|
||||
* later bare `send_reply` re-sent the same faulted text and used up
|
||||
* the whole rewrite budget. It is dropped with the refusal.
|
||||
*/
|
||||
const reviewed: string[] = [];
|
||||
const notes = ["You named [proposal:999], which was never made."];
|
||||
const { generate } = scripted([
|
||||
{ text: "Proposed [proposal:999] for you." },
|
||||
{ tool_calls: [{ id: "s1", name: "send_reply", arguments: `{"status":"done"}` }] },
|
||||
{ tool_calls: [{ id: "s2", name: "send_reply", arguments: `{"status":"done"}` }] },
|
||||
{
|
||||
text: "The proposal is up for you.",
|
||||
tool_calls: [{ id: "s3", name: "send_reply", arguments: `{"status":"done"}` }],
|
||||
},
|
||||
]);
|
||||
|
||||
const result = await runTextLoop({
|
||||
system: "s",
|
||||
messages: [{ role: "user", content: "Propose it." }],
|
||||
tools: [sendReply],
|
||||
generate,
|
||||
resolveCandidates,
|
||||
require_closing_answer: true,
|
||||
review: async ({ text }) => {
|
||||
reviewed.push(text);
|
||||
|
||||
return notes.shift() || null;
|
||||
},
|
||||
});
|
||||
|
||||
expect(result.text).toBe("The proposal is up for you.");
|
||||
expect(result.steps).toBe(4);
|
||||
expect(reviewed).toEqual(["Proposed [proposal:999] for you.", "The proposal is up for you."]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("runTextLoop answer not sent", () => {
|
||||
|
||||
@@ -301,15 +301,35 @@ const wrapUpToolsPrompt = ({
|
||||
};
|
||||
|
||||
/**
|
||||
* The status a `send_reply` call declared, for the review: a call whose
|
||||
* arguments don't parse or name an unknown status is left undefined, and
|
||||
* the tool's own schema refuses it before this matters.
|
||||
* The status a `send_reply` call declared, for the review: defaults to "working"
|
||||
* when work is passed, otherwise "done". A call whose arguments don't parse or name an
|
||||
* unknown status is left undefined.
|
||||
*/
|
||||
const replyStatusFromCall = ({ call }: { call: HarnessToolCall }): ReplyStatus | undefined => {
|
||||
try {
|
||||
const args = JSON.parse(call.arguments || "{}");
|
||||
const status = args?.status || (args?.work ? "working" : "done");
|
||||
|
||||
return ReplyStatuses.includes(args?.status) ? (args.status as ReplyStatus) : undefined;
|
||||
return ReplyStatuses.includes(status) ? (status as ReplyStatus) : undefined;
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Message or text passed in send_reply's arguments, when the model placed the
|
||||
* reply content in the tool call rather than assistant prose.
|
||||
*/
|
||||
const replyTextFromCall = ({ call }: { call: HarnessToolCall }): string | undefined => {
|
||||
try {
|
||||
const args = JSON.parse(call.arguments || "{}");
|
||||
if (typeof args?.message === "string" && args.message.trim()) {
|
||||
return args.message.trim();
|
||||
}
|
||||
if (typeof args?.text === "string" && args.text.trim()) {
|
||||
return args.text.trim();
|
||||
}
|
||||
return undefined;
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
@@ -533,6 +553,16 @@ export default async function runTextLoop({
|
||||
* left for the follow-up (session 130, message 874).
|
||||
*/
|
||||
let draft_text = "";
|
||||
/**
|
||||
* The message a turn wrote beside a card but without `send_reply`
|
||||
* (`closing_required`). That prose is the sentence the card belongs
|
||||
* under, not a draft about something else, so a later bare `send_reply`
|
||||
* carries it instead of making the model write the whole answer again.
|
||||
* Session 146 lost six answers this way: the text went out with
|
||||
* `ask_user`, the loop asked for `send_reply`, and the next turn had
|
||||
* nothing left to say.
|
||||
*/
|
||||
let card_text = "";
|
||||
/**
|
||||
* A run whose prompt no longer fits the working context, with nothing
|
||||
* trimmable left, has been told, once (`oversizedRequestNote`).
|
||||
@@ -800,6 +830,11 @@ export default async function runTextLoop({
|
||||
const tool_calls = offered.filter((call) => !wrap_up || wrap_tools.some((tool) => tool.name == call.name));
|
||||
const reply_call = tool_calls.filter((call) => call.name === SendReplyToolName).at(-1);
|
||||
const reply_status = reply_call ? replyStatusFromCall({ call: reply_call }) : undefined;
|
||||
const call_text = reply_call ? replyTextFromCall({ call: reply_call }) : undefined;
|
||||
|
||||
if (!answer.text && call_text) {
|
||||
answer.text = call_text;
|
||||
}
|
||||
|
||||
/**
|
||||
* What the app would never show as its own word comes out before
|
||||
@@ -913,6 +948,7 @@ export default async function runTextLoop({
|
||||
if (!(wrap_up && !wrap_up_saving) && reply_drafts < AppData.HarnessReplyDraftsMax) {
|
||||
reply_drafts += 1;
|
||||
draft_text = answer.text || "";
|
||||
card_text = "";
|
||||
pushUserTurn({ transcript, content: replyDraftNote });
|
||||
await traced({ kind: "event", index, name: "reply_draft", text: replyDraftNote });
|
||||
continue;
|
||||
@@ -982,7 +1018,20 @@ export default async function runTextLoop({
|
||||
};
|
||||
}
|
||||
|
||||
if (check.verdict === "sent_back") continue;
|
||||
if (check.verdict === "sent_back") {
|
||||
/**
|
||||
* The answer is being written again, so nothing held from
|
||||
* the refused one may go out in its place: a draft or a
|
||||
* card's sentence re-sent unchanged is a fault again, and
|
||||
* three of those cost the user the answer (session 146).
|
||||
* The reminder flag goes with it, so the rewrite can be
|
||||
* told to write beside the call once more.
|
||||
*/
|
||||
draft_text = "";
|
||||
card_text = "";
|
||||
told_closing_text = false;
|
||||
continue;
|
||||
}
|
||||
|
||||
/**
|
||||
* A wrap-up rewrite the review let through is the answer. The
|
||||
@@ -1163,7 +1212,7 @@ export default async function runTextLoop({
|
||||
* has been told to write it again and still sent nothing, and only
|
||||
* when that draft is a finished message.
|
||||
*/
|
||||
const written_text = (answer.text || "").trim();
|
||||
const written_text = (answer.text || call_text || "").trim();
|
||||
/**
|
||||
* A card is never paired with an older sentence: the card asked
|
||||
* something, and the draft was about something else. Filling it in
|
||||
@@ -1172,11 +1221,29 @@ export default async function runTextLoop({
|
||||
const asked_something = tool_calls.some(
|
||||
(call) => call.name !== SendReplyToolName && isClosingTool({ name: call.name }),
|
||||
);
|
||||
/**
|
||||
* The sentence a card turn wrote is the one that card belongs under,
|
||||
* so it is held for the `send_reply` that closes it, whether that
|
||||
* turn is the next one or shares the card. No second reminder is
|
||||
* needed: the loop already asked for the call, not the message. An
|
||||
* earlier draft is not held that way: it was about something else,
|
||||
* and pairing it with "Which date rule?" put "I checked the date
|
||||
* rules." under it.
|
||||
*/
|
||||
const carry_card = Boolean(card_text.trim()) && !unfinishedAnswerText({ text: card_text });
|
||||
const carry_draft =
|
||||
told_closing_text && !asked_something && !unfinishedAnswerText({ text: draft_text });
|
||||
const message_text = written_text || (carry_draft ? draft_text : "");
|
||||
const message_text = written_text || (carry_card ? card_text : carry_draft ? draft_text : "");
|
||||
|
||||
if (called_card && (closing_failed || !closing || !closing_required)) {
|
||||
/**
|
||||
* A turn that put a card up and wrote the message beside it, but
|
||||
* ended without `send_reply`, has written the reply: the next
|
||||
* turn is asked for the call, not the whole message again.
|
||||
*/
|
||||
if (closing && !closing_failed && !called_send_reply && written_text) {
|
||||
card_text = written_text;
|
||||
}
|
||||
/**
|
||||
* Bounded: past the retries a card-only turn ends on the answer
|
||||
* it wrote, reviewed like any reply, rather than looping on a
|
||||
@@ -1270,7 +1337,9 @@ export default async function runTextLoop({
|
||||
kind: "event",
|
||||
index,
|
||||
name: "draft_carried",
|
||||
text: "The message was written in an earlier turn. send_reply had no text beside it after one reminder, so that finished draft went out.",
|
||||
text: carry_card
|
||||
? "The message was written beside a card in an earlier turn. send_reply had no text beside it after one reminder, so that message went out with the card under it."
|
||||
: "The message was written in an earlier turn. send_reply had no text beside it after one reminder, so that finished draft went out.",
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1280,6 +1349,7 @@ export default async function runTextLoop({
|
||||
if (!told_unfinished && !(wrap_up && !wrap_up_saving)) {
|
||||
told_unfinished = true;
|
||||
draft_text = "";
|
||||
card_text = "";
|
||||
pushUserTurn({ transcript, content: unfinished });
|
||||
await traced({ kind: "event", index, name: "unfinished", text: unfinished });
|
||||
continue;
|
||||
@@ -1338,7 +1408,17 @@ export default async function runTextLoop({
|
||||
};
|
||||
}
|
||||
|
||||
if (check.verdict === "sent_back") continue;
|
||||
if (check.verdict === "sent_back") {
|
||||
/**
|
||||
* Nothing held from the refused message may go out in its
|
||||
* place, and the reminder flag goes with it so the rewrite
|
||||
* can be asked for the text beside the call once more.
|
||||
*/
|
||||
draft_text = "";
|
||||
card_text = "";
|
||||
told_closing_text = false;
|
||||
continue;
|
||||
}
|
||||
|
||||
return {
|
||||
text: message_text,
|
||||
|
||||
@@ -4,6 +4,7 @@ import grabCrewWorkers from "@/src/functions/backend/db/bots/grab-crew-workers";
|
||||
import type { StorageScope } from "@/src/utils/storage-access";
|
||||
import type { HarnessTool } from "../../types";
|
||||
import askToTakeOverTool from "../computer/ask-to-take-over-tool";
|
||||
import importFileTool from "../computer/import-file-tool";
|
||||
import searchComputersTool from "../computer/search-computers-tool";
|
||||
import addBotToWorkspaceTool from "./add-bot-to-workspace-tool";
|
||||
import assignComputerTool from "./assign-computer-tool";
|
||||
@@ -103,13 +104,19 @@ type Params = {
|
||||
* posts links to it (`bot_messages.task_ids`).
|
||||
*/
|
||||
onTask?: (params: { task_id: number }) => void;
|
||||
/**
|
||||
* Called with a file the reply sent, so the message carries it.
|
||||
*/
|
||||
onAttach?: (params: { media_id: number; name: string }) => void;
|
||||
};
|
||||
|
||||
/**
|
||||
* The tools a bot replies in chat with: its own (memory, instructions, and
|
||||
* in a workspace switching its default computer), send_reply for the message
|
||||
* and the longer work it queues, search_computers to find what's on its computers,
|
||||
* ask_user_to_take_over when only the user can do something on one, and
|
||||
* and the longer work it queues, search_computers to find what's on its
|
||||
* computers, import_file to keep a file one of them made (an image, a PDF,
|
||||
* an export) in its own files, ask_user_to_take_over when only the user can
|
||||
* do something on one, and
|
||||
* for the coordinator (the super admin's alone) create_workspace and
|
||||
* update_workspace (a workspace and its shared context, which
|
||||
* find_workspace reads back wherever the coordinator works), create_bot to
|
||||
@@ -129,8 +136,9 @@ type Params = {
|
||||
* workspace admin, in the workspace it leads, gets
|
||||
* `grabWorkspaceAdminTools`. A worker gets no work to hand out, but it may
|
||||
* pass on a task of its own to a bot it could ask (`hand_over_task`). Every
|
||||
* gate reads the bot's types (`powers`), never `bots.kind`. Anything else on
|
||||
* a computer goes through a task, never mid-reply.
|
||||
* gate reads the bot's types (`powers`), never `bots.kind`. Longer work on
|
||||
* a computer, and anything that changes it, still goes through a task,
|
||||
* never mid-reply.
|
||||
*/
|
||||
export default async function grabBotChatTools({
|
||||
bot,
|
||||
@@ -149,8 +157,10 @@ export default async function grabBotChatTools({
|
||||
onPropose,
|
||||
onWorkspaceAdmin,
|
||||
onTask,
|
||||
onAttach,
|
||||
}: Params): Promise<HarnessTool[]> {
|
||||
const bot_id = bot.id || 0;
|
||||
const dirs = computerRunDirs({ bot_id, bot_kind: bot.kind, user_id, workspace_id });
|
||||
const tools = [
|
||||
...(await grabBotTools({
|
||||
user_id,
|
||||
@@ -182,7 +192,15 @@ export default async function grabBotChatTools({
|
||||
user_id,
|
||||
computers,
|
||||
workspace_id,
|
||||
dirs: computerRunDirs({ bot_id, bot_kind: bot.kind, user_id, workspace_id }),
|
||||
dirs,
|
||||
}),
|
||||
importFileTool({
|
||||
computers,
|
||||
scopes,
|
||||
bot_id,
|
||||
user_id,
|
||||
dirs,
|
||||
onAttach,
|
||||
}),
|
||||
askToTakeOverTool({ computers, onAsk: (params) => onTakeOver?.(params) }),
|
||||
]
|
||||
|
||||
@@ -1,9 +1,24 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import askUserTool from "./ask-user-tool";
|
||||
import { afterAll, describe, expect, mock, test } from "bun:test";
|
||||
|
||||
let created = 0;
|
||||
let next_id = 41;
|
||||
|
||||
mock.module("@/src/functions/backend/db/bot-questions/create-bot-question", () => ({
|
||||
default: async () => {
|
||||
created++;
|
||||
return next_id++;
|
||||
},
|
||||
}));
|
||||
|
||||
const { default: askUserTool } = await import("./ask-user-tool");
|
||||
|
||||
afterAll(() => {
|
||||
mock.restore();
|
||||
});
|
||||
|
||||
const tool = askUserTool({ user_id: 1, bot_id: 2, session_id: 3, onAsk: () => {} });
|
||||
|
||||
const question = { question: "Which environment?", kind: "single", options: ["Staging", "Production"] };
|
||||
const question = { question: "Which environment?", kind: "single" as const, options: ["Staging", "Production"] };
|
||||
|
||||
describe("askUserTool", () => {
|
||||
test("takes a set of questions", () => {
|
||||
@@ -23,4 +38,26 @@ describe("askUserTool", () => {
|
||||
test("caps how many questions one card holds", () => {
|
||||
expect(tool.schema?.safeParse({ questions: Array.from({ length: 7 }, () => question) }).success).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
test("asks once per run, so a second call points at the card already up", async () => {
|
||||
/**
|
||||
* A model that re-asked while the loop asked it for `send_reply`
|
||||
* was refused by a thrown error, which the loop read as a failed
|
||||
* closing call: session 146 lost its whole answer to it. The card
|
||||
* is up either way, so the second call just says so.
|
||||
*/
|
||||
created = 0;
|
||||
const refs: string[] = [];
|
||||
const once = askUserTool({ user_id: 1, bot_id: 2, session_id: 3, onAsk: ({ ref }) => refs.push(ref) });
|
||||
const signal = new AbortController().signal;
|
||||
|
||||
const first = await once.run({ args: { questions: [question] }, signal });
|
||||
const second = await once.run({ args: { questions: [question] }, signal });
|
||||
|
||||
expect(created).toBe(1);
|
||||
expect(refs).toHaveLength(1);
|
||||
expect(String(first)).toContain("Asked the user 1 question");
|
||||
expect(String(second)).toContain("already asked");
|
||||
expect(String(second)).toContain("send_reply");
|
||||
});
|
||||
});
|
||||
@@ -67,9 +67,7 @@ export default function askUserTool({
|
||||
}),
|
||||
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.`,
|
||||
);
|
||||
return `The questions are already asked and will go out with your message. Finish your reply with send_reply.`;
|
||||
}
|
||||
|
||||
const id = await createBotQuestion({
|
||||
@@ -94,7 +92,7 @@ export default function askUserTool({
|
||||
return `Asked the user ${count} question${count == 1 ? "" : "s"}: the card is on your message. ${
|
||||
in_task
|
||||
? `Stop working on what you asked about and finish with your report (if you asked to settle something before going on, say you're waiting for their answers).`
|
||||
: `End your reply now with a short line saying what you need settled; their answers arrive as their next message.`
|
||||
: `End your reply now: write the short line saying what you need settled beside send_reply; their answers arrive as their next message.`
|
||||
} Don't repeat the questions or options in your text.`;
|
||||
},
|
||||
};
|
||||
|
||||
@@ -142,4 +142,21 @@ describe("sendReplyTool", () => {
|
||||
expect(result).toContain("what stopped the work");
|
||||
expect(queued).toHaveLength(0);
|
||||
});
|
||||
|
||||
test("accepts text and message in arguments and defaults status to done", async () => {
|
||||
const result = await tool().run({ args: { message: "Here is your skill." }, signal });
|
||||
|
||||
expect(result).toContain("marked done");
|
||||
expect(queued).toHaveLength(0);
|
||||
});
|
||||
|
||||
test("infers status working when work is passed without status", async () => {
|
||||
const result = await tool().run({
|
||||
args: { work: { title: "Look up files", instructions: "Inspect them." } },
|
||||
signal,
|
||||
});
|
||||
|
||||
expect(result).toContain("Run #100 queued");
|
||||
expect(queued).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
@@ -27,13 +27,15 @@ type Params = {
|
||||
};
|
||||
|
||||
type Args = {
|
||||
status: (typeof ReplyStatuses)[number];
|
||||
status?: (typeof ReplyStatuses)[number];
|
||||
work?: BotTaskWork;
|
||||
message?: string;
|
||||
text?: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* The one way a reply or a task report ends. The text written beside this
|
||||
* call is the message the user gets; the call declares what happens after
|
||||
* call or passed in message/text is the message the user gets; the call declares what happens after
|
||||
* it, so the app never has to guess intent from prose.
|
||||
*
|
||||
* `done` says nothing runs once the message is out. `working` says a run
|
||||
@@ -60,13 +62,16 @@ export default function sendReplyTool({
|
||||
|
||||
return {
|
||||
name: "send_reply",
|
||||
description: `End every reply with this call, in the same turn as the message. The text you write beside it is what the user gets; a call with no text sends nothing, and a message from an earlier turn is not filled in. This call only says what happens after it. status done: nothing runs once the message goes out, so the text must not say work is under way. status working: a run is carrying the work on and its result will be posted here; pass work to queue it now, or it must already be open. status blocked: the work cannot go on, and the text says why. Never write a message that says work is under way and end with done. In this same turn, and no other, you may also call suggest_next_steps or ask_user when one of them belongs with the answer. No other tool shares this turn. A message sent without this call is a draft and never reaches the user. Finish every table, list and code fence in the text. ${
|
||||
description: `End every reply with this call, in the same turn as the message. The text you write beside it, or in message/text, is what the user gets; a call with neither sends nothing. A message written beside a card in an earlier turn is kept for the send_reply that closes it; anything else written earlier is not filled in. This call only says what happens after it. status done: nothing runs once the message goes out, so the text must not say work is under way. status working: a run is carrying the work on and its result will be posted here; pass work to queue it now, or it must already be open. status blocked: the work cannot go on, and the text says why. Never write a message that says work is under way and end with done. In this same turn, and no other, you may also call suggest_next_steps or ask_user when one of them belongs with the answer. No other tool shares this turn. A message sent without this call is a draft and never reaches the user. Finish every table, list and code fence in the text. ${
|
||||
computers.length
|
||||
? `Computers you can use: ${listed}. Defaults to ${computers[0]!.id}, the one you're on.`
|
||||
: `You have no computer, so work that needs one can't run.`
|
||||
}`,
|
||||
schema: z.object({
|
||||
status: z.enum(ReplyStatuses).describe("done: nothing runs after this message. working: a run carries the work on. blocked: the work cannot go on."),
|
||||
status: z
|
||||
.enum(ReplyStatuses)
|
||||
.default("done")
|
||||
.describe("done: nothing runs after this message. working: a run carries the work on. blocked: the work cannot go on."),
|
||||
work: z
|
||||
.object({
|
||||
title: z.string().min(1).max(80).describe("A short label, e.g. \"Check the backup logs\""),
|
||||
@@ -88,13 +93,23 @@ export default function sendReplyTool({
|
||||
})
|
||||
.optional()
|
||||
.describe("The run to start with this message. Required when status is working and no run of yours is open here."),
|
||||
message: z
|
||||
.string()
|
||||
.optional()
|
||||
.describe("The message to send the user with this reply, when not written directly in the assistant turn."),
|
||||
text: z
|
||||
.string()
|
||||
.optional()
|
||||
.describe("Alias for message: the message to send the user with this reply."),
|
||||
}),
|
||||
run: async ({ args }) => {
|
||||
if (args.status !== "working" && args.work) {
|
||||
const status = args.status ?? (args.work ? "working" : "done");
|
||||
|
||||
if (status !== "working" && args.work) {
|
||||
throw new Error(`work can only be passed with status "working": it queues a run, so the message must say that work is under way. Nothing was sent.`);
|
||||
}
|
||||
|
||||
if (args.status === "working") {
|
||||
if (status === "working") {
|
||||
if (args.work) {
|
||||
if (!queued) {
|
||||
queued = await queueBotTask({
|
||||
@@ -129,7 +144,7 @@ export default function sendReplyTool({
|
||||
return `A run of yours is still open here, so status "working" holds. Your message beside this call goes out with it: say what it's doing, in one sentence, and that its result will be posted here.`;
|
||||
}
|
||||
|
||||
if (args.status === "blocked") {
|
||||
if (status === "blocked") {
|
||||
return `Your message beside this call goes out, marked blocked. Say plainly what stopped the work and what you need from the user to go on.`;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,20 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import suggestNextStepsTool from "./suggest-next-steps-tool";
|
||||
import { afterAll, describe, expect, mock, test } from "bun:test";
|
||||
|
||||
let created = 0;
|
||||
let next_id = 7;
|
||||
|
||||
mock.module("@/src/functions/backend/db/bot-suggestions/create-bot-suggestion", () => ({
|
||||
default: async () => {
|
||||
created++;
|
||||
return next_id++;
|
||||
},
|
||||
}));
|
||||
|
||||
const { default: suggestNextStepsTool } = await import("./suggest-next-steps-tool");
|
||||
|
||||
afterAll(() => {
|
||||
mock.restore();
|
||||
});
|
||||
|
||||
const refs: string[] = [];
|
||||
const tool = suggestNextStepsTool({ user_id: 1, bot_id: 2, session_id: 3, onSuggest: ({ ref }) => refs.push(ref) });
|
||||
@@ -20,4 +35,20 @@ describe("suggestNextStepsTool", () => {
|
||||
expect(tool.schema?.safeParse({ steps: Array.from({ length: 5 }, (_, i) => `Step ${i}`) }).success).toBe(false);
|
||||
expect(tool.schema?.safeParse({ steps: ["x".repeat(121)] }).success).toBe(false);
|
||||
});
|
||||
|
||||
test("suggests once per run, so a second call points at the buttons already up", async () => {
|
||||
created = 0;
|
||||
const seen: string[] = [];
|
||||
const once = suggestNextStepsTool({ user_id: 1, bot_id: 2, session_id: 3, onSuggest: ({ ref }) => seen.push(ref) });
|
||||
const signal = new AbortController().signal;
|
||||
|
||||
const first = await once.run({ args: { steps: ["Write the report"] }, signal });
|
||||
const second = await once.run({ args: { steps: ["Write the report"] }, signal });
|
||||
|
||||
expect(created).toBe(1);
|
||||
expect(seen).toHaveLength(1);
|
||||
expect(String(first)).toContain("Suggested 1 next step");
|
||||
expect(String(second)).toContain("already attached");
|
||||
expect(String(second)).toContain("send_reply");
|
||||
});
|
||||
});
|
||||
@@ -49,7 +49,7 @@ export default function suggestNextStepsTool({ user_id, bot_id, session_id, work
|
||||
}),
|
||||
run: async ({ args }) => {
|
||||
if (suggested) {
|
||||
throw new Error(`You already suggested next steps in this run. Put every suggestion in one suggest_next_steps call.`);
|
||||
return `The suggested steps are already attached to your message. Finish your reply with send_reply.`;
|
||||
}
|
||||
|
||||
const id = await createBotSuggestion({
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import pickImportComputer from "./import-computer";
|
||||
|
||||
/**
|
||||
* A reply now imports from a computer, and a bot may reach several: the one
|
||||
* it names wins, and one it does not have is refused rather than quietly
|
||||
* reading the first machine's folder.
|
||||
*/
|
||||
const computers = [
|
||||
{ id: 4, name: "Main" },
|
||||
{ id: 9, name: "Build" },
|
||||
];
|
||||
|
||||
describe("picking the computer to import from", () => {
|
||||
test("no computer is null", () => {
|
||||
expect(pickImportComputer({ computers: [] })).toBeNull();
|
||||
});
|
||||
|
||||
test("nothing named means the first one", () => {
|
||||
expect(pickImportComputer({ computers })?.id).toEqual(4);
|
||||
expect(pickImportComputer({ computers, wanted: " " })?.id).toEqual(4);
|
||||
});
|
||||
|
||||
test("an id picks that computer", () => {
|
||||
expect(pickImportComputer({ computers, wanted: 9 })?.id).toEqual(9);
|
||||
expect(pickImportComputer({ computers, wanted: "9" })?.id).toEqual(9);
|
||||
});
|
||||
|
||||
test("a computer ref picks it too", () => {
|
||||
expect(pickImportComputer({ computers, wanted: "computer:9" })?.id).toEqual(9);
|
||||
});
|
||||
|
||||
test("one it does not have is null, not the first one", () => {
|
||||
expect(pickImportComputer({ computers, wanted: 2 })).toBeNull();
|
||||
expect(pickImportComputer({ computers, wanted: "elsewhere" })).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,26 @@
|
||||
type ComputerLike = {
|
||||
id?: number | string | null;
|
||||
name?: string | null;
|
||||
};
|
||||
|
||||
/**
|
||||
* Which computer an import reads from: the one the bot named (an id, or a
|
||||
* `computer:<id>` ref), else the first it has. Null when it named one it
|
||||
* does not have, so the tool says so instead of reading the wrong machine.
|
||||
*/
|
||||
export default function pickImportComputer<T extends ComputerLike>({
|
||||
computers,
|
||||
wanted,
|
||||
}: {
|
||||
computers: T[];
|
||||
wanted?: number | string | null;
|
||||
}): T | null {
|
||||
if (!computers.length) return null;
|
||||
|
||||
if (wanted === undefined || wanted === null || String(wanted).trim() == "") return computers[0] ?? null;
|
||||
|
||||
const id = Number(String(wanted).trim().replace(/^computer:/, ""));
|
||||
if (!Number.isFinite(id)) return null;
|
||||
|
||||
return computers.find((computer) => Number(computer.id) == id) ?? null;
|
||||
}
|
||||
@@ -20,12 +20,14 @@ import downloadComputerFile, { type ComputerDownload } from "@/src/functions/bac
|
||||
import runComputerCommand from "@/src/functions/backend/computers/run-computer-command";
|
||||
import shellQuote from "@/src/utils/shell-quote";
|
||||
import walkRegularFiles from "@/src/utils/walk-regular-files";
|
||||
import pickImportComputer from "./import-computer";
|
||||
|
||||
type Params = {
|
||||
/**
|
||||
* The computer the run is on: what it made is in its workspace.
|
||||
* The computers the run reaches (`grabBotComputers`), the current one
|
||||
* first: the import reads from the one the bot names, else this one.
|
||||
*/
|
||||
computer_id: number | string;
|
||||
computers: { id?: number | string | null; name?: string | null }[];
|
||||
/**
|
||||
* The directories the run may write to (`grabStorageScopes`): the first
|
||||
* is where an import lands.
|
||||
@@ -44,13 +46,18 @@ type Params = {
|
||||
type Args = {
|
||||
path: string;
|
||||
name?: string;
|
||||
/**
|
||||
* Which of the run's computers to read from (its id); the first one
|
||||
* when left out.
|
||||
*/
|
||||
computer?: number | string;
|
||||
attach?: boolean;
|
||||
};
|
||||
|
||||
/**
|
||||
* Copies what a bot made on its computer into its own files: one file, or
|
||||
* a whole folder (taken as a gzipped tar and unpacked into one row per
|
||||
* file). The copies are kept with the app, stay after the computer is
|
||||
* Copies what a bot made on one of its computers into its own files: one
|
||||
* file, or a whole folder (taken as a gzipped tar and unpacked into one row
|
||||
* per file). The copies are kept with the app, stay after the computer is
|
||||
* rebuilt, and are readable at once; the originals stay on the computer,
|
||||
* where the message's folder ref points at the folder holding them.
|
||||
*
|
||||
@@ -60,7 +67,7 @@ type Args = {
|
||||
* import at 30,047 characters.
|
||||
*/
|
||||
export default function importFileTool({
|
||||
computer_id,
|
||||
computers,
|
||||
scopes,
|
||||
bot_id,
|
||||
user_id,
|
||||
@@ -69,10 +76,20 @@ export default function importFileTool({
|
||||
}: Params): HarnessTool<Args> {
|
||||
const own = scopes[0];
|
||||
const max_mb = Math.round(AppData.BotFileImportMaxBytes / (1024 * 1024));
|
||||
const first = computers[0];
|
||||
const choices = computers
|
||||
.map((computer) => `${computer.id}${computer.name ? ` (${computer.name})` : ""}`)
|
||||
.join(", ");
|
||||
|
||||
return {
|
||||
name: "import_file",
|
||||
description: `Copy a file or folder from this computer into your own files, so it is kept with the app and stays after the computer is rebuilt. Give its path on the computer, relative to your folder there (${dirs.cwd}), e.g. "seo/coderank/raw/crawl.json" or "seo/coderank/raw"; a folder comes in as it is, in one go. Up to ${max_mb} MB. Check with list_files and the computer's own tools what you already imported: importing the same thing twice just writes over the copy, so do it once.${
|
||||
description: `Copy a file or folder from one of your computers into your own files, so it is kept with the app and stays after the computer is rebuilt.${
|
||||
computers.length > 1
|
||||
? ` Your computers: ${choices}; "computer" picks one, the first by default.`
|
||||
: first
|
||||
? ` It reads computer ${first.id}${first.name ? ` (${first.name})` : ""}.`
|
||||
: ""
|
||||
} Give its path on the computer, relative to your folder there (${dirs.cwd}), e.g. "seo/coderank/raw/crawl.json" or "seo/coderank/raw"; a folder comes in as it is, in one go. Up to ${max_mb} MB. Check with list_files and the computer's own tools what you already imported: importing the same thing twice just writes over the copy, so do it once.${
|
||||
own?.scope == "workspace" ? " The copies land in the workspace's shared files." : ""
|
||||
} Imports are readable at once. Name a copy with its [file:ID] ref. Import the report you wrote before the last long steps of a run, so it is never lost to the step limit. The other direction is export_file, which puts one of your own files back on the computer.`,
|
||||
schema: z.object({
|
||||
@@ -86,11 +103,23 @@ export default function importFileTool({
|
||||
.max(AppData.BotFilePathMaxChars)
|
||||
.optional()
|
||||
.describe(`Where to save it in your files, e.g. "reports/coderank-audit.md"`),
|
||||
computer: z
|
||||
.union([z.string(), z.number()])
|
||||
.optional()
|
||||
.describe(`Which of your computers (its id); the first one when left out`),
|
||||
attach: z.boolean().optional().describe(`Also send it to the user with this reply`),
|
||||
}),
|
||||
run: async ({ args, signal }) => {
|
||||
if (!own) return `You have no files folder to import into.`;
|
||||
|
||||
const chosen = pickImportComputer({ computers, wanted: args.computer });
|
||||
|
||||
if (!chosen) {
|
||||
return computers.length
|
||||
? `That isn't one of your computers. Yours: ${choices}.`
|
||||
: `You have no computer to import from.`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Workspace-relative from here on, which is what a folder ref
|
||||
* names.
|
||||
@@ -100,6 +129,7 @@ export default function importFileTool({
|
||||
|
||||
if (!source) return `Give a file or folder inside your folder, e.g. "seo/coderank/raw".`;
|
||||
|
||||
const computer_id = chosen.id || 0;
|
||||
const target = await grabComputerMcpUrl({ computer_id });
|
||||
|
||||
if (!target) return `Computer #${computer_id} has no container to copy from.`;
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import binaryWriteProblem from "./binary-write-problem";
|
||||
|
||||
/**
|
||||
* A `.png` path and a truncated base64 string became a 2.6 KB "image" the
|
||||
* user could not open, while the reply said a 1376x768 PNG was attached.
|
||||
* `write_file` saves text: a binary extension is refused, with the tool that
|
||||
* makes the real file named.
|
||||
*/
|
||||
describe("writing a binary file as text", () => {
|
||||
test("an image is refused", () => {
|
||||
expect(binaryWriteProblem({ path: "images/summit-hero.png" })).toContain("binary file (.png)");
|
||||
});
|
||||
|
||||
test("the refusal names a way to make it", () => {
|
||||
const problem = binaryWriteProblem({ path: "report.pdf" }) || "";
|
||||
|
||||
expect(problem).toContain("generate_image");
|
||||
expect(problem).toContain("make_pdf");
|
||||
expect(problem).toContain("import_file");
|
||||
});
|
||||
|
||||
test("an uppercase extension is refused too", () => {
|
||||
expect(binaryWriteProblem({ path: "SCREENSHOT.PNG" })).toContain(".png");
|
||||
});
|
||||
|
||||
test("a zip, an office document and a font are refused", () => {
|
||||
for (const path of ["bundle.zip", "notes.docx", "font.woff2"]) {
|
||||
expect(binaryWriteProblem({ path })).toBeTruthy();
|
||||
}
|
||||
});
|
||||
|
||||
test("text files pass", () => {
|
||||
for (const path of ["notes.md", "data.csv", "run.py", "page.svg", "README"]) {
|
||||
expect(binaryWriteProblem({ path })).toBeNull();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,57 @@
|
||||
import { BotImageFileExtensions } from "@/src/dict/bot-file-dict";
|
||||
import { extensionOf } from "@/src/functions/backend/db/bot-files/media-type-for-file";
|
||||
|
||||
/**
|
||||
* Extensions that hold bytes rather than text. `write_file` stores what the
|
||||
* model passes as it is, so a `.png` path and a truncated `base64` string
|
||||
* became a 2.6 KB "image" the user could not open, while the reply said a
|
||||
* 1376x768 PNG was attached. SVG stays out: it is text, and a bot can write
|
||||
* one by hand.
|
||||
*/
|
||||
export const BinaryWriteExtensions = [
|
||||
...BotImageFileExtensions.filter((extension) => extension != "svg"),
|
||||
"pdf",
|
||||
"doc",
|
||||
"docx",
|
||||
"xls",
|
||||
"xlsx",
|
||||
"ppt",
|
||||
"pptx",
|
||||
"zip",
|
||||
"gz",
|
||||
"tgz",
|
||||
"tar",
|
||||
"7z",
|
||||
"rar",
|
||||
"mp3",
|
||||
"wav",
|
||||
"m4a",
|
||||
"ogg",
|
||||
"flac",
|
||||
"mp4",
|
||||
"mov",
|
||||
"mkv",
|
||||
"avi",
|
||||
"webm",
|
||||
"sqlite",
|
||||
"db",
|
||||
"exe",
|
||||
"bin",
|
||||
"woff",
|
||||
"woff2",
|
||||
"ttf",
|
||||
"otf",
|
||||
];
|
||||
|
||||
/**
|
||||
* Why `write_file` refuses a path, or null when it can save it: a binary
|
||||
* extension would turn text into a file that does not open, and the tool
|
||||
* that makes the real one is one of the named ones.
|
||||
*/
|
||||
export default function binaryWriteProblem({ path }: { path: string }) {
|
||||
const extension = extensionOf({ name: path });
|
||||
|
||||
if (!extension || !BinaryWriteExtensions.includes(extension)) return null;
|
||||
|
||||
return `write_file saves text, and ${path} is a binary file (.${extension}): the text would be stored as it is, so the user would get a file that does not open. Make an image with generate_image (or transform_image), a PDF with make_pdf, a video with generate_video, or build the file on a computer and bring it in with import_file.`;
|
||||
}
|
||||
@@ -22,7 +22,7 @@ type Args = {
|
||||
export default function listFilesTool(context: StorageToolContext): HarnessTool<Args> {
|
||||
return {
|
||||
name: "list_files",
|
||||
description: `List the files you have saved, newest first: one folder's with "folder", everything with "recursive", or the ones whose name or path has "search". Each line has its path, size and [file:ID] ref (e.g. [file:12]) to read it. The answer also names the folder as a folder ref, which opens it in Files without downloading anything: a file is a [file:ID] ref, a folder is a [folder:...] ref.`,
|
||||
description: `List the files you have saved, newest first: one folder's with "folder", everything with "recursive", or the ones whose name or path has "search" (in every folder, so a file saved deep in a tree is found). Each line has its path, size and [file:ID] ref (e.g. [file:12]) to read it. The answer also names the folder as a folder ref, which opens it in Files without downloading anything: a file is a [file:ID] ref, a folder is a [folder:...] ref.`,
|
||||
schema: z.object({
|
||||
folder: z.string().max(AppData.BotFilePathMaxChars).optional(),
|
||||
search: z.string().max(120).optional(),
|
||||
@@ -34,18 +34,23 @@ export default function listFilesTool(context: StorageToolContext): HarnessTool<
|
||||
}),
|
||||
run: async ({ args }) => {
|
||||
const folder = args.folder?.trim() || "";
|
||||
const search = args.search?.trim() || "";
|
||||
|
||||
const files = await listBotFiles({
|
||||
scopes: context.scopes,
|
||||
folder,
|
||||
folder: folder || undefined,
|
||||
recursive: args.recursive,
|
||||
search: args.search,
|
||||
search: search || undefined,
|
||||
});
|
||||
|
||||
if (!files.length) {
|
||||
return folder
|
||||
? `Nothing in ${folder}.`
|
||||
: `You have no files yet. Write one with write_file.`;
|
||||
if (folder) return `Nothing in ${folder}.`;
|
||||
|
||||
if (search) {
|
||||
return `Nothing matches "${search}" in your files. Try a shorter name, or list_files with no arguments to see everything.`;
|
||||
}
|
||||
|
||||
return `You have no files yet. Write one with write_file.`;
|
||||
}
|
||||
|
||||
const lines = files.map((file) => {
|
||||
|
||||
@@ -3,6 +3,7 @@ import { AppData } from "@/src/data/app-data";
|
||||
import type { BotFilePurpose } from "@/src/dict/bot-file-dict";
|
||||
import recordBotFile from "@/src/functions/backend/db/bot-files/record-bot-file";
|
||||
import type { HarnessTool } from "../../types";
|
||||
import binaryWriteProblem from "./binary-write-problem";
|
||||
import {
|
||||
describeScope,
|
||||
fileRef,
|
||||
@@ -22,7 +23,8 @@ type Args = {
|
||||
/**
|
||||
* Writes a text file (markdown, CSV, JSON, code, plain text) into one of
|
||||
* the bot's directories, making folders as needed. The file stays for
|
||||
* later runs.
|
||||
* later runs. A binary extension is refused: text saved under `.png`
|
||||
* reached the user as a file that would not open.
|
||||
*/
|
||||
export default function writeFileTool(context: StorageToolContext): HarnessTool<Args> {
|
||||
const own = context.scopes[0];
|
||||
@@ -31,7 +33,7 @@ export default function writeFileTool(context: StorageToolContext): HarnessTool<
|
||||
name: "write_file",
|
||||
description: `Save a text file for later: markdown, CSV, JSON, code or plain text. Give it a path like "reports/q3.md"; folders are made as needed. Files belong to ${
|
||||
own?.scope == "workspace" ? "the workspace you're working in" : "you"
|
||||
} and stay between runs: write a file before telling the user something is saved, and list_files (by name or path) to find one you wrote before. It is readable at once.${
|
||||
} and stay between runs: write a file before telling the user something is saved, and list_files (by name or path) to find one you wrote before. It is readable at once. It saves text only: an image comes from generate_image, a PDF from make_pdf, and a file a computer made from import_file, never from writing base64 here.${
|
||||
context.scopes.length > 1
|
||||
? ` "scope" picks a directory: ${context.scopes.map((s) => `${s.scope}:${s.owner_id}`).join(", ")}.`
|
||||
: ""
|
||||
@@ -62,6 +64,9 @@ export default function writeFileTool(context: StorageToolContext): HarnessTool<
|
||||
.join(", ")}.`;
|
||||
}
|
||||
|
||||
const binary = binaryWriteProblem({ path: args.path });
|
||||
if (binary) return binary;
|
||||
|
||||
const file = await recordBotFile({
|
||||
bot_id: context.bot_id,
|
||||
scope: named.scope,
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import type { BotQuestionView } from "@/src/types";
|
||||
import loadRefView, { primeRefView } from "../(utils)/ref-view-loader";
|
||||
import loadRefView, { primeRefView, subscribeRefView } from "../(utils)/ref-view-loader";
|
||||
|
||||
type Params = {
|
||||
question_id: number;
|
||||
@@ -11,7 +11,8 @@ type Params = {
|
||||
* when the chip renders, so it shows whether they're still waiting. Only
|
||||
* the user they were asked of can read them; anyone else gets null. A
|
||||
* read that failed or hung is tried again (`loadRefView`) instead of
|
||||
* leaving the card unopenable until the page is reloaded.
|
||||
* leaving the card unopenable until the page is reloaded, and answering
|
||||
* one card tells the thread's other cards of the same question.
|
||||
*/
|
||||
export default function useBotQuestion({ question_id }: Params) {
|
||||
const [view, setViewState] = useState<BotQuestionView | null>(null);
|
||||
@@ -19,11 +20,21 @@ export default function useBotQuestion({ question_id }: Params) {
|
||||
|
||||
useEffect(() => {
|
||||
let live = true;
|
||||
const key = `question:${question_id}`;
|
||||
|
||||
setLoading(true);
|
||||
|
||||
const unsubscribe = subscribeRefView({
|
||||
key,
|
||||
listener: (next) => {
|
||||
if (!live) return;
|
||||
setViewState(next as BotQuestionView);
|
||||
setLoading(false);
|
||||
},
|
||||
});
|
||||
|
||||
loadRefView<BotQuestionView>({
|
||||
key: `question:${question_id}`,
|
||||
key,
|
||||
url: `/api/admin/bot-questions/get-question?question_id=${question_id}`,
|
||||
}).then((result) => {
|
||||
if (!live) return;
|
||||
@@ -33,6 +44,7 @@ export default function useBotQuestion({ question_id }: Params) {
|
||||
|
||||
return () => {
|
||||
live = false;
|
||||
unsubscribe();
|
||||
};
|
||||
}, [question_id]);
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import type { ExtensionProposalView } from "@/src/types";
|
||||
import loadRefView, { primeRefView } from "../(utils)/ref-view-loader";
|
||||
import loadRefView, { primeRefView, subscribeRefView } from "../(utils)/ref-view-loader";
|
||||
|
||||
type Params = {
|
||||
proposal_id: number;
|
||||
@@ -12,7 +12,8 @@ type Params = {
|
||||
* waiting. Only the super admin it was proposed to can read it; anyone
|
||||
* else gets null. A read that failed or hung is tried again
|
||||
* (`loadRefView`), so the card isn't unopenable until the page is
|
||||
* reloaded.
|
||||
* reloaded, and deciding on one card tells the thread's other cards of
|
||||
* the same proposal, so none of them goes on saying "Waiting for you".
|
||||
*/
|
||||
export default function useExtensionProposal({ proposal_id }: Params) {
|
||||
const [view, setViewState] = useState<ExtensionProposalView | null>(null);
|
||||
@@ -20,11 +21,21 @@ export default function useExtensionProposal({ proposal_id }: Params) {
|
||||
|
||||
useEffect(() => {
|
||||
let live = true;
|
||||
const key = `extension-proposal:${proposal_id}`;
|
||||
|
||||
setLoading(true);
|
||||
|
||||
const unsubscribe = subscribeRefView({
|
||||
key,
|
||||
listener: (next) => {
|
||||
if (!live) return;
|
||||
setViewState(next as ExtensionProposalView);
|
||||
setLoading(false);
|
||||
},
|
||||
});
|
||||
|
||||
loadRefView<ExtensionProposalView>({
|
||||
key: `extension-proposal:${proposal_id}`,
|
||||
key,
|
||||
url: `/api/admin/extension-proposals/get-proposal?proposal_id=${proposal_id}`,
|
||||
}).then((result) => {
|
||||
if (!live) return;
|
||||
@@ -34,6 +45,7 @@ export default function useExtensionProposal({ proposal_id }: Params) {
|
||||
|
||||
return () => {
|
||||
live = false;
|
||||
unsubscribe();
|
||||
};
|
||||
}, [proposal_id]);
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import type { HookProposalView } from "@/src/types";
|
||||
import loadRefView, { primeRefView } from "../(utils)/ref-view-loader";
|
||||
import loadRefView, { primeRefView, subscribeRefView } from "../(utils)/ref-view-loader";
|
||||
|
||||
type Params = {
|
||||
proposal_id: number;
|
||||
@@ -11,7 +11,8 @@ type Params = {
|
||||
* card: read when the chip renders, so it shows whether it's still
|
||||
* waiting. Only the user it was proposed to can read it; anyone else gets
|
||||
* null. A read that failed or hung is tried again (`loadRefView`), so the
|
||||
* card isn't unopenable until the page is reloaded.
|
||||
* card isn't unopenable until the page is reloaded, and deciding on one
|
||||
* card tells the thread's other cards of the same proposal.
|
||||
*/
|
||||
export default function useHookProposal({ proposal_id }: Params) {
|
||||
const [view, setViewState] = useState<HookProposalView | null>(null);
|
||||
@@ -19,11 +20,21 @@ export default function useHookProposal({ proposal_id }: Params) {
|
||||
|
||||
useEffect(() => {
|
||||
let live = true;
|
||||
const key = `hook-proposal:${proposal_id}`;
|
||||
|
||||
setLoading(true);
|
||||
|
||||
const unsubscribe = subscribeRefView({
|
||||
key,
|
||||
listener: (next) => {
|
||||
if (!live) return;
|
||||
setViewState(next as HookProposalView);
|
||||
setLoading(false);
|
||||
},
|
||||
});
|
||||
|
||||
loadRefView<HookProposalView>({
|
||||
key: `hook-proposal:${proposal_id}`,
|
||||
key,
|
||||
url: `/api/admin/hook-proposals/get-proposal?proposal_id=${proposal_id}`,
|
||||
}).then((result) => {
|
||||
if (!live) return;
|
||||
@@ -33,6 +44,7 @@ export default function useHookProposal({ proposal_id }: Params) {
|
||||
|
||||
return () => {
|
||||
live = false;
|
||||
unsubscribe();
|
||||
};
|
||||
}, [proposal_id]);
|
||||
|
||||
|
||||
@@ -14,6 +14,12 @@ type Params = {
|
||||
* The thread's last message is the user's, so a reply is due.
|
||||
*/
|
||||
awaiting_reply: boolean;
|
||||
/**
|
||||
* Something of this session's is still to show its work here (a queued
|
||||
* run, or one working on a computer): a reply that already landed says
|
||||
* nothing about it, so the poll keeps reading until it's done.
|
||||
*/
|
||||
running?: boolean;
|
||||
/**
|
||||
* The thread's last message: only newer ones are replayed.
|
||||
*/
|
||||
@@ -46,6 +52,7 @@ type Params = {
|
||||
export default function useReplyCatchUp({
|
||||
session_id,
|
||||
awaiting_reply,
|
||||
running,
|
||||
last_message_id,
|
||||
on_open_jobs,
|
||||
}: Params) {
|
||||
@@ -114,16 +121,19 @@ export default function useReplyCatchUp({
|
||||
useRefocus({ onRefocus: () => void check() });
|
||||
|
||||
/**
|
||||
* While a reply is due, a poll covers a reply whose push was missed
|
||||
* while the page stayed in front (a socket that dropped silently).
|
||||
* While a reply is due, or something of this session's is still running,
|
||||
* a poll covers a push that was missed while the page stayed in front (a
|
||||
* socket that dropped silently). A run queued behind another on the same
|
||||
* computer shows nothing at all without it: its reply already landed, so
|
||||
* no reply is due, and nothing else would read the session again.
|
||||
*/
|
||||
useEffect(() => {
|
||||
if (!awaiting_reply || !session_id) return;
|
||||
if ((!awaiting_reply && !running) || !session_id) return;
|
||||
|
||||
const timer = setInterval(() => void check(), AppData.BotReplyCatchUpMs);
|
||||
|
||||
return () => clearInterval(timer);
|
||||
}, [awaiting_reply, session_id, check]);
|
||||
}, [awaiting_reply, running, session_id, check]);
|
||||
|
||||
/**
|
||||
* The socket was down while the page stayed open: going back online or
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import type { SecretRequestView } from "@/src/types";
|
||||
import loadRefView, { primeRefView } from "../(utils)/ref-view-loader";
|
||||
import loadRefView, { primeRefView, subscribeRefView } from "../(utils)/ref-view-loader";
|
||||
|
||||
type Params = {
|
||||
request_id: number;
|
||||
@@ -11,7 +11,8 @@ type Params = {
|
||||
* read when the chip renders, so it shows whether it's still waiting.
|
||||
* Only the user it was asked of can read it; anyone else gets null. A
|
||||
* read that failed or hung is tried again (`loadRefView`), so the card
|
||||
* isn't unopenable until the page is reloaded.
|
||||
* isn't unopenable until the page is reloaded, and answering one card
|
||||
* tells the thread's other cards of the same request.
|
||||
*/
|
||||
export default function useSecretRequest({ request_id }: Params) {
|
||||
const [view, setViewState] = useState<SecretRequestView | null>(null);
|
||||
@@ -19,11 +20,21 @@ export default function useSecretRequest({ request_id }: Params) {
|
||||
|
||||
useEffect(() => {
|
||||
let live = true;
|
||||
const key = `secret-request:${request_id}`;
|
||||
|
||||
setLoading(true);
|
||||
|
||||
const unsubscribe = subscribeRefView({
|
||||
key,
|
||||
listener: (next) => {
|
||||
if (!live) return;
|
||||
setViewState(next as SecretRequestView);
|
||||
setLoading(false);
|
||||
},
|
||||
});
|
||||
|
||||
loadRefView<SecretRequestView>({
|
||||
key: `secret-request:${request_id}`,
|
||||
key,
|
||||
url: `/api/admin/secret-requests/get-request?request_id=${request_id}`,
|
||||
}).then((result) => {
|
||||
if (!live) return;
|
||||
@@ -33,6 +44,7 @@ export default function useSecretRequest({ request_id }: Params) {
|
||||
|
||||
return () => {
|
||||
live = false;
|
||||
unsubscribe();
|
||||
};
|
||||
}, [request_id]);
|
||||
|
||||
|
||||
@@ -26,6 +26,25 @@ function fromTask({ task }: { task: BotTaskWithSteps | null }): Progress {
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The task of the session on screen, out of every task the push carries:
|
||||
* the newest of them all is often a run in another conversation, and taking
|
||||
* that one left this thread with nothing (`task` alone, when the push has no
|
||||
* list).
|
||||
*/
|
||||
function ownTask({
|
||||
data,
|
||||
session_id,
|
||||
}: {
|
||||
data: Pick<BotUpdatedData, "task" | "tasks">;
|
||||
session_id?: number | null;
|
||||
}): BotTaskWithSteps | null {
|
||||
const tasks = data.tasks || (data.task ? [data.task] : []);
|
||||
const mine = session_id ? tasks.find((task) => task.session_id == session_id) : tasks[0];
|
||||
|
||||
return mine || null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The open session's active task and its latest step (a
|
||||
* `bots_queue_updates` row's text), kept current from
|
||||
@@ -54,7 +73,7 @@ export default function useTaskProgress({ bot_id, session_id, task }: Params) {
|
||||
* The user's active task with the bot may be in another of
|
||||
* their conversations with it.
|
||||
*/
|
||||
const task = data.task && (!session_id || data.task.session_id == session_id) ? data.task : null;
|
||||
const task = ownTask({ data, session_id });
|
||||
|
||||
setProgress((prev) => ((task?.id || null) == prev.task_id ? prev : fromTask({ task })));
|
||||
},
|
||||
|
||||
@@ -271,6 +271,12 @@ export default function Conversation() {
|
||||
useReplyCatchUp({
|
||||
session_id,
|
||||
awaiting_reply,
|
||||
/**
|
||||
* A queued or running task of this session keeps the poll going after
|
||||
* the reply that queued it landed: nothing else reads it again, so a
|
||||
* run waiting behind another on its computer would never show.
|
||||
*/
|
||||
running: Boolean(progress.task_id) || Boolean(open_reply_jobs),
|
||||
last_message_id: last_saved_id,
|
||||
on_open_jobs: ({ open_jobs }) => setOpenReplyJobs(open_jobs),
|
||||
});
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import loadRefView, { primeRefView } from "./ref-view-loader";
|
||||
import loadRefView, { primeRefView, subscribeRefView } from "./ref-view-loader";
|
||||
|
||||
/**
|
||||
* A read standing in for the app's: one answer per call, in order, and a
|
||||
@@ -100,4 +100,65 @@ describe("loadRefView", () => {
|
||||
|
||||
expect(asked).toEqual(["/get-question?question_id=15", "/get-suggestion?suggestion_id=15"]);
|
||||
});
|
||||
});
|
||||
});
|
||||
describe("subscribeRefView", () => {
|
||||
test("tells every chip naming a view when one of them changes it", () => {
|
||||
const first: unknown[] = [];
|
||||
const second: unknown[] = [];
|
||||
|
||||
const stopFirst = subscribeRefView({ key: "test:shared-chip", listener: (view) => first.push(view) });
|
||||
const stopSecond = subscribeRefView({ key: "test:shared-chip", listener: (view) => second.push(view) });
|
||||
|
||||
primeRefView({ key: "test:shared-chip", view: { id: 21, status: "confirmed" } });
|
||||
|
||||
expect(first).toEqual([{ id: 21, status: "confirmed" }]);
|
||||
expect(second).toEqual([{ id: 21, status: "confirmed" }]);
|
||||
|
||||
stopFirst();
|
||||
stopSecond();
|
||||
});
|
||||
|
||||
test("tells only the chips naming that view", () => {
|
||||
const mine: unknown[] = [];
|
||||
const other: unknown[] = [];
|
||||
|
||||
const stopMine = subscribeRefView({ key: "test:mine", listener: (view) => mine.push(view) });
|
||||
const stopOther = subscribeRefView({ key: "test:other", listener: (view) => other.push(view) });
|
||||
|
||||
primeRefView({ key: "test:mine", view: { id: 23 } });
|
||||
|
||||
expect(mine).toEqual([{ id: 23 }]);
|
||||
expect(other).toEqual([]);
|
||||
|
||||
stopMine();
|
||||
stopOther();
|
||||
});
|
||||
|
||||
test("stops following once the chip is gone", () => {
|
||||
const seen: unknown[] = [];
|
||||
|
||||
const stop = subscribeRefView({ key: "test:unsubscribed", listener: (view) => seen.push(view) });
|
||||
|
||||
stop();
|
||||
primeRefView({ key: "test:unsubscribed", view: { id: 25 } });
|
||||
|
||||
expect(seen).toEqual([]);
|
||||
});
|
||||
|
||||
test("tells the chips already showing it when a read lands", async () => {
|
||||
const seen: unknown[] = [];
|
||||
|
||||
const stop = subscribeRefView({ key: "test:read-lands", listener: (view) => seen.push(view) });
|
||||
|
||||
await loadRefView({
|
||||
key: "test:read-lands",
|
||||
url: "/get?id=27",
|
||||
readOnce: async () => ({ id: 27 }),
|
||||
retryDelaysMs: [],
|
||||
});
|
||||
|
||||
expect(seen).toEqual([{ id: 27 }]);
|
||||
|
||||
stop();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -31,12 +31,48 @@ type Params = {
|
||||
const known = new Map<string, unknown>();
|
||||
const inFlight = new Map<string, Promise<unknown | null>>();
|
||||
|
||||
type RefViewListener = (view: RefView) => void;
|
||||
|
||||
/**
|
||||
* Who is showing one view on the page now, by key. A bot's message can
|
||||
* carry the same card twice (the one that made it, and a later one saying
|
||||
* it's still waiting), and each chip keeps its own state, so without this
|
||||
* the other card went on saying "Waiting for you" after the user decided
|
||||
* on it, until a reload.
|
||||
*/
|
||||
const listeners = new Map<string, Set<RefViewListener>>();
|
||||
|
||||
/**
|
||||
* Follows one view, so a change another chip made reaches this one:
|
||||
* returns the unsubscribe. Called before the read, since a card decided
|
||||
* while it loads must not be overwritten by the answer already in flight.
|
||||
*/
|
||||
export function subscribeRefView({ key, listener }: { key: string; listener: RefViewListener }) {
|
||||
const listening = listeners.get(key) || new Set<RefViewListener>();
|
||||
|
||||
listening.add(listener);
|
||||
listeners.set(key, listening);
|
||||
|
||||
return () => {
|
||||
listening.delete(listener);
|
||||
|
||||
if (!listening.size) listeners.delete(key);
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Keeps a view the page already has (a question answered in its card, its
|
||||
* chip now saying so) without asking the app for it again.
|
||||
* chip now saying so) without asking the app for it again, and tells every
|
||||
* chip naming it, so they all say so.
|
||||
*/
|
||||
export function primeRefView({ key, view }: { key: string; view: unknown }) {
|
||||
remember({ key, view });
|
||||
}
|
||||
|
||||
function remember({ key, view }: { key: string; view: unknown }) {
|
||||
known.set(key, view);
|
||||
|
||||
for (const listener of listeners.get(key) || []) listener(view as RefView);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -64,7 +100,7 @@ export default async function loadRefView<T extends RefView>({
|
||||
.then((view) => {
|
||||
inFlight.delete(key);
|
||||
|
||||
if (view) known.set(key, view);
|
||||
if (view) remember({ key, view });
|
||||
|
||||
return view as T | null;
|
||||
})
|
||||
|
||||
@@ -54,7 +54,11 @@ export const handler: BunextAPIRouteHandler<SessionMessagesResponse> = async ({
|
||||
bot: {
|
||||
id: bot_id,
|
||||
...(await grabBotFace({ bot_id, user_id: user.id })),
|
||||
task: await grabActiveBotTask({ bot_id, user_id: user.id }),
|
||||
/**
|
||||
* The task of this session: the newest active one may be a
|
||||
* run in another conversation, which the page would drop.
|
||||
*/
|
||||
task: await grabActiveBotTask({ bot_id, user_id: user.id, session_id: session.id }),
|
||||
},
|
||||
step: await grabSessionReplyStep({ session_id: session.id }),
|
||||
open_jobs: await grabSessionOpenReplies({ session_id: session.id }),
|
||||
|
||||
@@ -695,7 +695,17 @@ export type BotUpdatedData = {
|
||||
id: number;
|
||||
face: BotFace;
|
||||
status_line: string;
|
||||
/**
|
||||
* The newest of the user's active tasks, null when there is none. Kept
|
||||
* for a reader that wants one; `tasks` has them all, since the newest
|
||||
* may be in another conversation.
|
||||
*/
|
||||
task: BotTaskWithSteps | null;
|
||||
/**
|
||||
* Every active task the user has with the bot, newest first: the
|
||||
* conversation picks the one from its own session.
|
||||
*/
|
||||
tasks?: BotTaskWithSteps[];
|
||||
/**
|
||||
* The computer the bot is on, when the push knows it (a switch, or the
|
||||
* live relay). Null means its main one.
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import looksLikeImage from "./looks-like-image";
|
||||
|
||||
const bytes = (...values: number[]) => new Uint8Array(values);
|
||||
|
||||
/**
|
||||
* A real PNG, JPEG, GIF, WEBP and BMP pass; text does not. The check exists
|
||||
* because a truncated base64 string saved under `.png` was attached as a
|
||||
* 1376x768 image and the user got a file that would not open.
|
||||
*/
|
||||
describe("reading image bytes", () => {
|
||||
test("a PNG", () => {
|
||||
expect(looksLikeImage({ bytes: bytes(0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a) })).toBe(true);
|
||||
});
|
||||
|
||||
test("a JPEG", () => {
|
||||
expect(looksLikeImage({ bytes: bytes(0xff, 0xd8, 0xff, 0xe0) })).toBe(true);
|
||||
});
|
||||
|
||||
test("a GIF", () => {
|
||||
expect(looksLikeImage({ bytes: bytes(0x47, 0x49, 0x46, 0x38, 0x39, 0x61) })).toBe(true);
|
||||
});
|
||||
|
||||
test("a WEBP", () => {
|
||||
expect(
|
||||
looksLikeImage({
|
||||
bytes: bytes(0x52, 0x49, 0x46, 0x46, 1, 2, 3, 4, 0x57, 0x45, 0x42, 0x50),
|
||||
}),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
test("a BMP", () => {
|
||||
expect(looksLikeImage({ bytes: bytes(0x42, 0x4d, 0, 0) })).toBe(true);
|
||||
});
|
||||
|
||||
test("a RIFF that isn't WEBP is not an image", () => {
|
||||
expect(
|
||||
looksLikeImage({
|
||||
bytes: bytes(0x52, 0x49, 0x46, 0x46, 1, 2, 3, 4, 0x57, 0x41, 0x56, 0x45),
|
||||
}),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
test("base64 text is not an image", () => {
|
||||
expect(looksLikeImage({ bytes: new TextEncoder().encode("iVBORw0KGgo=") })).toBe(false);
|
||||
});
|
||||
|
||||
test("nothing at all is not an image", () => {
|
||||
expect(looksLikeImage({ bytes: new Uint8Array() })).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,18 @@
|
||||
/**
|
||||
* Whether bytes start like a real image, by its signature. Enough to catch
|
||||
* text saved under an image's name (a truncated base64 string once reached
|
||||
* the user as a 2.6 KB "PNG" that would not open): a real PNG, JPEG, GIF,
|
||||
* WEBP or BMP always starts with its own magic. SVG is text and is checked
|
||||
* by the caller's extension, not here.
|
||||
*/
|
||||
export default function looksLikeImage({ bytes }: { bytes: Uint8Array }) {
|
||||
const head = bytes.subarray(0, 12);
|
||||
const starts = (...expected: number[]) => expected.every((byte, index) => head[index] == byte);
|
||||
|
||||
if (starts(0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a)) return true;
|
||||
if (starts(0xff, 0xd8, 0xff)) return true;
|
||||
if (starts(0x47, 0x49, 0x46, 0x38)) return true;
|
||||
if (starts(0x42, 0x4d)) return true;
|
||||
|
||||
return starts(0x52, 0x49, 0x46, 0x46) && head[8] == 0x57 && head[9] == 0x45 && head[10] == 0x42 && head[11] == 0x50;
|
||||
}
|
||||
@@ -287,6 +287,43 @@ I'll report what the run actually finds when it reports back.`;
|
||||
expect(problems[0]).toContain("list_graphics");
|
||||
});
|
||||
|
||||
test("names a proposal that was never made", () => {
|
||||
/**
|
||||
* Session 146: the model wrote `[proposal:19]` before proposal 19
|
||||
* existed (it guessed the next number), and the user read "I didn't
|
||||
* get the proposal" four times. Only the tool's own ref may appear.
|
||||
*/
|
||||
const problems = replyClaimProblems({
|
||||
text: "Proposed as [proposal:19]: Co-Marketing.",
|
||||
tool_uses: [{ name: "send_reply", ok: true }],
|
||||
missing_proposal_ids: [19],
|
||||
missing_hook_proposal_ids: [4],
|
||||
});
|
||||
|
||||
expect(problems.length).toBe(1);
|
||||
expect(problems[0]).toContain("[proposal:19]");
|
||||
expect(problems[0]).toContain("was ever made");
|
||||
|
||||
expect(
|
||||
replyClaimProblems({
|
||||
text: "Proposed as [proposal:19]: Co-Marketing.",
|
||||
tool_uses: [{ name: "propose_skill", ok: true }],
|
||||
}),
|
||||
).toEqual([]);
|
||||
});
|
||||
|
||||
test("names a hook proposal that was never made", () => {
|
||||
const problems = replyClaimProblems({
|
||||
text: "The hook is on the card: [hook-proposal:4]",
|
||||
tool_uses: [{ name: "send_reply", ok: true }],
|
||||
missing_hook_proposal_ids: [4],
|
||||
});
|
||||
|
||||
expect(problems.length).toBe(1);
|
||||
expect(problems[0]).toContain("[hook-proposal:4]");
|
||||
expect(problems[0]).toContain("was ever made");
|
||||
});
|
||||
|
||||
test("an answer that holds up has no problems", () => {
|
||||
expect(replyClaimProblems({ text: "Task #20 is cancelled.", tool_uses: [] })).toEqual([]);
|
||||
});
|
||||
|
||||
@@ -41,6 +41,14 @@ type Params = {
|
||||
* hand-written one is made up or copied from an earlier message.
|
||||
*/
|
||||
written_card_refs?: string[];
|
||||
/**
|
||||
* `[proposal:ID]` / `[hook-proposal:ID]` refs in the text that name no
|
||||
* proposal the user was ever made: the model guessed the next id and
|
||||
* described a card nobody got ("I didn't get the proposal", four times
|
||||
* in one conversation).
|
||||
*/
|
||||
missing_proposal_ids?: number[];
|
||||
missing_hook_proposal_ids?: number[];
|
||||
/**
|
||||
* A run of the bot's, a job it handed over or a room it asked, still
|
||||
* open from this conversation: its result is still to come.
|
||||
@@ -98,6 +106,8 @@ export default function replyClaimProblems({
|
||||
unresolved_setting_refs = [],
|
||||
missing_graphic_ids = [],
|
||||
written_card_refs = [],
|
||||
missing_proposal_ids = [],
|
||||
missing_hook_proposal_ids = [],
|
||||
has_open_work,
|
||||
status,
|
||||
}: Params): string[] {
|
||||
@@ -133,6 +143,22 @@ export default function replyClaimProblems({
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* A proposal ref that names nothing the user was made: a guessed number.
|
||||
* The card only exists once the tool that proposes returned it, so a
|
||||
* ref written beside the answer describes one nobody got.
|
||||
*/
|
||||
if (missing_proposal_ids.length || missing_hook_proposal_ids.length) {
|
||||
const refs = [
|
||||
...missing_proposal_ids.map((id) => `[proposal:${id}]`),
|
||||
...missing_hook_proposal_ids.map((id) => `[hook-proposal:${id}]`),
|
||||
];
|
||||
|
||||
problems.push(
|
||||
`It names ${refs.join(", ")}, and no such proposal was ever made to the user. A proposal exists only once the tool that proposes one returned its ref (propose_skill, propose_browser, propose_hook and the like); the app puts that ref under your message itself, so never write one or guess the next number. Call the tool again if the proposal should be made now.`,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* A card ref the model wrote itself: the app adds every one of these
|
||||
* from the tool that made the card, so a written one is a card that was
|
||||
|
||||
@@ -3,7 +3,7 @@ type Params = {
|
||||
/**
|
||||
* The ref's kind, as in `[file:12]`, `[task:20]` or `[suggestion:4]`.
|
||||
*/
|
||||
kind: "file" | "task" | "suggestion" | "question" | "plan" | "graphic";
|
||||
kind: "file" | "task" | "suggestion" | "question" | "plan" | "graphic" | "proposal" | "hook-proposal";
|
||||
};
|
||||
|
||||
/**
|
||||
|
||||
@@ -1,14 +1,16 @@
|
||||
import stripAppRecords from "./strip-app-records";
|
||||
import stripCardRefs from "./strip-card-refs";
|
||||
import stripUnresolvedSettingRefs from "./strip-unresolved-setting-refs";
|
||||
|
||||
/**
|
||||
* What the app takes out of an answer before anything reads it: a
|
||||
* `[setting:...]` pill that leads nowhere and an app record line the run's
|
||||
* own tools don't support. Both are text the app would never show as its
|
||||
* own word, so they are removed rather than sent back for a rewrite: three
|
||||
* faults in one run used to cost the user an answer that was otherwise
|
||||
* right (`reviewBotReply`).
|
||||
* `[setting:...]` pill that leads nowhere, an app record line the run's
|
||||
* own tools don't support, and the ref of a card the app adds itself
|
||||
* (`[question:]`, `[suggestion:]`, `[plan:]`). All are text the app would
|
||||
* never show as its own word, so they are removed rather than sent back for
|
||||
* a rewrite: three faults in one run used to cost the user an answer that
|
||||
* was otherwise right (`reviewBotReply`).
|
||||
*/
|
||||
export default function sanitizeAnswerText({ text }: { text: string }) {
|
||||
return stripAppRecords({ text: stripUnresolvedSettingRefs({ text }) });
|
||||
return stripCardRefs({ text: stripAppRecords({ text: stripUnresolvedSettingRefs({ text }) }) });
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
import { AppCardRefTools, type AppCardRefKind } from "./reply-claim-problems";
|
||||
|
||||
type Params = {
|
||||
text: string;
|
||||
};
|
||||
|
||||
const CardRefKinds = Object.keys(AppCardRefTools) as AppCardRefKind[];
|
||||
|
||||
/**
|
||||
* One card ref alone in its code span (which still links), with the span.
|
||||
*/
|
||||
const codeSpan = ({ kind }: { kind: AppCardRefKind }) => new RegExp(`\`\\s*\\[${kind}:\\d+\\]\\s*\`[ \\t]?`, "gi");
|
||||
|
||||
/**
|
||||
* A ref between words leaves one space behind, never two: `[ \t]*` around it
|
||||
* stays on the same line, so paragraph breaks survive.
|
||||
*/
|
||||
const inline = ({ kind }: { kind: AppCardRefKind }) => new RegExp(`[ \\t]*\\[${kind}:\\d+\\][ \\t]*`, "gi");
|
||||
|
||||
/**
|
||||
* A bot's own text with the refs of the cards the app adds under a message
|
||||
* taken out (`[question:24]`, `[suggestion:7]`, `[plan:3]`). The app writes
|
||||
* every one of those from the tool that made the card, so one in the model's
|
||||
* text was written by hand, and the user reads it as a card that was never
|
||||
* made ("not available") or as a second copy of one. Taken out rather than
|
||||
* sent back for a rewrite: three faults in one run cost the user an answer,
|
||||
* and a model that sees the ref in its own history learns to write it again
|
||||
* (session 146: a whole thread of `[question:N]` refs it had never made).
|
||||
*/
|
||||
export default function stripCardRefs({ text }: Params): string {
|
||||
if (!CardRefKinds.some((kind) => new RegExp(`\\[${kind}:\\d+\\]`, "i").test(text))) return text;
|
||||
|
||||
let stripped = text;
|
||||
|
||||
for (const kind of CardRefKinds) {
|
||||
stripped = stripped.replace(codeSpan({ kind }), "").replace(inline({ kind }), " ");
|
||||
}
|
||||
|
||||
return stripped
|
||||
.replace(/[ \t]+$/gm, "")
|
||||
.replace(/\n{3,}/g, "\n\n")
|
||||
.trim();
|
||||
}
|
||||
Reference in New Issue
Block a user