Compare commits
5
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
fd823f39e8 | ||
|
|
ea0e3fa014 | ||
|
|
69919fcd77 | ||
|
|
403688e455 | ||
|
|
1a68dd7e19 |
@@ -89,21 +89,21 @@ Enables SQLite foreign keys (`enableForeignKeys`), `bunextInit()`, `ensureDocker
|
||||
### Bots, sessions, chat
|
||||
|
||||
- **Tables:** `bots` (`kind`, `color` `#rrggbb`, `stone`, `role`, `system_prompt`; `hue` is a legacy fallback), `bot_user_faces`, `bot_sessions`, `bot_messages`, `bot_tasks`, `bot_task_steps` (unused yet), `bot_plans` (a plan a bot wrote for work in pieces, its steps and their state), `bot_job_traces` (a run's debug view, 7 days by default). Enums in `src/dict/bot-dict.ts` and `src/dict/bot-plan-dict.ts`.
|
||||
- **Sessions:** one thread per user per bot in its own chat plus one per workspace; split into `bot_sessions` (rollover at the app setting `bot_session_max_messages`, default `AppData.BotSessionMaxMessages`, via `grabBotSessionMaxMessages`; titled and summarised by `name-bot-session.ts` from the session's opening after a reply or a task (a session with no user message, work handed to the bot, is named from the bot's own messages; `grabSessionOpening`; `grabBotMessages` reads the latest; each opening message is cut to `AppData.BotSessionNameMessageChars`, so a pasted brief of tens of thousands of characters costs one naming call, not a second copy of itself), summary carried into the next session only when they're linked by `previous_session_id`, which only a carry-over sets; older implicit links are cleared at boot by `clearImplicitSessionLinks`). New session (`startBotSession`) and a conversation with no active session always start fresh. The rollover carries over like the bot does (`rollOverBotSession` -> `continueBotSession`, falling back to the stored summary; kept for the next message while a job is open in the full session or there's nothing to carry), inside send-message, so the user's message lands under the summary. A routine and a hook each keep a thread of their own, never the chat that happens to be active: `bot_sessions.routine_id` and `hook_id` mark it, `ensureRoutineSession`/`ensureHookSession` open it `closed` (so it takes nothing over) with the routine's or hook's title, roll it over at the same session max into a new linked session (`rollOverLinkedSession`, `previous_session_id`, the summary opening the new one), and it is read and chatted in with `?session_id=` like any session. A deleted routine or hook detaches its thread (`routine_id`/`hook_id` set to null) and keeps the messages; a silent hook's thread is the one exception to being followed (`followedSessionSql`: no rail row, no unread, no push, no face change) **until the user writes in it**: a human message takes the thread from the hook (`adoptHookSession`, from `insertUserMessage`, so a chat message and a question's answer alike), so the thread is theirs from then on and the hook opens a new one next time, while a hook that isn't silent makes its thread the conversation's active session for its run. Helpers in `src/functions/backend/db/bot-sessions/`. Job results land in the job's own session, even after it closes, except a reply that called `continue_in_new_session` (`carryOverBotSession`; the menu's and sessions modal's Continue in new session does the same through `continueBotSession`, the model writing title and summary, refused while a job is open in the session): its summary is kept on the closed session and opens the new one as a bot message (`carried_from_session_id`), the job's `session_id` moves so the answer follows, the new session is titled by the bot then (it has no first exchange to be named from), and the old one can never be reopened (`reopenBotSession` refuses; a thread showing it swaps its composer for a link to the new one). Session lists (rail, sessions modal) reopen a session on click, as before; a carried-over one can't be, so it opens to read (`?session_id=`, `conversationHref`). The page tells them which session it shows (`announceShownSession` -> `useShownSession`): they reload, mark it Current (greyed out; without `?session_id=` the active one is), list it even when it's older than the rail's latest, and the active row then leads back. From half the session length the reply prompt suggests moving on (`longSessionNote`). Earlier sessions never enter the prompt (only the last one's summary): the thread can open them above a session (`useOlderMessages.loadPrevious`, a divider per session, quote and reply as usual), and replies get `search_past_sessions`/`read_past_session` (scoped to that user, bot and place, never the current session) when the conversation has any.
|
||||
- **Sessions:** one thread per user per bot in its own chat plus one per workspace; split into `bot_sessions` (rollover at the app setting `bot_session_max_messages`, default `AppData.BotSessionMaxMessages`, via `grabBotSessionMaxMessages`; titled and summarised by `name-bot-session.ts` from the session's opening after a reply or a task (a session with no user message, work handed to the bot, is named from the bot's own messages; `grabSessionOpening`; `grabBotMessages` reads the latest; each opening message is cut to `AppData.BotSessionNameMessageChars`, so a pasted brief of tens of thousands of characters costs one naming call, not a second copy of itself), summary carried into the next session only when they're linked by `previous_session_id`, which only a carry-over sets; older implicit links are cleared at boot by `clearImplicitSessionLinks`). New session (`startBotSession`) and a conversation with no active session always start fresh. The rollover carries over like the bot does (`rollOverBotSession` -> `continueBotSession`, falling back to the stored summary; kept for the next message while a job is open in the full session or there's nothing to carry), inside send-message, so the user's message lands under the summary. Sending a message and answering a question card both hold the conversation's lock (`conversationLock`, `src/functions/backend/db/bot-sessions/conversation-lock.ts`, a `createKeyLock` per user, bot and workspace), since two sends 78 ms apart both read the same full session and one then wrote into the session the other had just closed; when its own rollover writes nothing, `rollOverBotSession` returns the conversation's current active session rather than the stale one. The composer holds its send until it answers (`sending`), so a double tap sends once. An open plan follows its conversation across a rollover (`carry-over-bot-session` moves `bot_plans.session_id`). A routine and a hook each keep a thread of their own, never the chat that happens to be active: `bot_sessions.routine_id` and `hook_id` mark it, `ensureRoutineSession`/`ensureHookSession` open it `closed` (so it takes nothing over) with the routine's or hook's title, roll it over at the same session max into a new linked session (`rollOverLinkedSession`, `previous_session_id`, the summary opening the new one), and it is read and chatted in with `?session_id=` like any session. A deleted routine or hook detaches its thread (`routine_id`/`hook_id` set to null) and keeps the messages; a silent hook's thread is the one exception to being followed (`followedSessionSql`: no rail row, no unread, no push, no face change) **until the user writes in it**: a human message takes the thread from the hook (`adoptHookSession`, from `insertUserMessage`, so a chat message and a question's answer alike), so the thread is theirs from then on and the hook opens a new one next time, while a hook that isn't silent makes its thread the conversation's active session for its run. Helpers in `src/functions/backend/db/bot-sessions/`. Job results land in the job's own session, even after it closes, except a reply that called `continue_in_new_session` (`carryOverBotSession`; the menu's and sessions modal's Continue in new session does the same through `continueBotSession`, the model writing title and summary, refused while a job is open in the session): its summary is kept on the closed session and opens the new one as a bot message (`carried_from_session_id`), the job's `session_id` moves so the answer follows, the new session is titled by the bot then (it has no first exchange to be named from), and the old one can never be reopened (`reopenBotSession` refuses; a thread showing it swaps its composer for a link to the new one). Session lists (rail, sessions modal) reopen a session on click, as before; a carried-over one can't be, so it opens to read (`?session_id=`, `conversationHref`). The page tells them which session it shows (`announceShownSession` -> `useShownSession`): they reload, mark it Current (greyed out; without `?session_id=` the active one is), list it even when it's older than the rail's latest, and the active row then leads back. From half the session length the reply prompt suggests moving on (`longSessionNote`). Earlier sessions never enter the prompt (only the last one's summary): the thread can open them above a session (`useOlderMessages.loadPrevious`, a divider per session, quote and reply as usual), and replies get `search_past_sessions`/`read_past_session` (scoped to that user, bot and place, never the current session) when the conversation has any.
|
||||
- **Coordinator:** exactly one, the super admin's alone, created idempotently by `ensureCoordinatorBot`. Default prompt `src/data/coordinator-system-prompt.ts`, backfilled only when empty.
|
||||
- **Routes:** `/admin/bots` reopens the last visited bot's own chat (cookie `cobble_last_visited_bot_id`, `<bot>` or `<bot>:<workspace>`; the landing uses only the bot) if still reachable, else coordinator (super admin) / latest bot / first workspace / empty. Workspace and conversation pages record the visit per user (`recordWorkspaceVisit`/`workspace_user_visits`, `recordBotVisit`/`bot_user_visits`) and the rail lists both latest visited first (`last_visited_at`, `orderByLastVisit`; recorded before the crew is read, so the conversation opened is already on top in that render, and its bot leads whatever the visits say (`pinned_id`); a workspace nobody visited yet ranks by its creation, so a new one leads); it never decides the landing. Settings and the rail pages get the cookie's conversation, workspace included, as root prop `last_conversation` (`grabLastConversation`, access-checked, only on those paths: `isPagesRailPath`), shown above their rail list as the way back (`RailLastConversation`). `/admin/bots/[bot_id]` conversation (header, thread and composer at 760px, the bot panel (`BotPanel`) sliding in from the right when its avatar or its name is tapped, or a phone swipes that way, over the conversation rather than taking width; `?session_id=` opens another of the user's sessions there: a closed one is reopened, except a carried-over one, which shows with `SessionMovedBar` instead of the composer, pointing where the conversation went on); `/admin/bots/[bot_id]/models`; `/admin/workspaces/[id]` dashboard; `/admin/workspaces/[id]/bots/[bot_id]` same conversation scoped to the workspace.
|
||||
- **No model:** while the bot has no text model there (`bot_text_model` null, kept live by the models modal), the thread shows `NoModelNotice` (centred when empty): super admins get Connect a provider / Guided setup, others are told the super admin sets it up.
|
||||
- **Conversation loading:** pages render everything server-side (`grabConversationProps`) **except the history**, which the client loads (`api/admin/bots/conversation-history`, merged with what's already shown, refetched on bfcache restore) and pages older messages on scroll. Rail lists go through `railBots`/`railWorkspaces` (no prompts/memory, previews cut). Every return to the page (window focus, a hidden tab visible, back online: `use-refocus`, `AppData.RefocusGapMs`) reads the crew again (`use-live-crew-refresh` -> `api/admin/bots/live-crew` -> `cobble:live-crew-refreshed`, taken by `useLiveBots`/`useLiveWorkspaces`) and the session's latest messages plus its bot's face, 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. The thread follows new messages while it sits at its bottom and offers "Jump to latest" (`ScrollToBottomButton`) when scrolled up; End does what that button does and Home goes back to the top of the messages loaded so far, both keeping away from a field being typed in, an open menu and an open modal (`typingInField`, `scrollThreadToTop`). 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. A message sent in **Plan mode** (`bot_messages.plan_mode`, turned on by Tab anywhere on the conversation page or the composer's Plan button, remembered per conversation in `localStorage`) is answered by a planning run: `run-bot-reply` gates every tool outside `PlanModeToolNames` (`gatePlanModeTools`: the write tools stay listed with their own name, description and schema, and calling one throws the Plan mode reason, never "there is no tool called ...", since only `run` is replaced; `load_tools` is gated too, so a deferred MCP or browser tool can't be pulled in), `send_reply` refuses `work` and `working`, and the computer and browser notes are left out; Retry and Run again copy the flag from the message they answer. **Answering or skipping an `ask_user` card is not a way out:** the card carries `bot_questions.plan_mode` from the run that asked, and `postBotQuestionAnswers` runs the answer as a Plan mode reply too (only Tab, or approving a plan, turns the mode off). A reply that ran in it carries `bot_messages.plan_mode` (`jobPlanMode` over the job's params) and shows `PlanModeOffButton` under it while the mode is still on: one click turns it off and puts "Plan mode is off, go ahead." in the composer (`turnOffPlanMode`, never sends), which is the click the bot's answer asks for. A Plan mode reply whose result belongs in a file or another place outside the chat may not paste it or say a write tool is missing: it says the mode stops the save and either writes a plan they approve or tells them to turn Plan mode off, and `planModeFileEscape` sends a reply back when it hands the save to the user instead.
|
||||
- **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]`, `[secret:ID]` (masked env, Reveal/Copy), `[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). A plan, questions, a proposal, a hook proposal and a secret request show in full under the message, as the card the user acts on, never behind a chip: they are blocks, so `MarkdownParagraph` (`(partials)/markdown-paragraph.tsx`) lifts those refs out of the paragraph they were written in (`isCardRefHref` in `(utils)/card-ref-href.ts`), which React would otherwise refuse inside a `p`. 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.
|
||||
- **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]` (the card that opens the computer on its own line), `[secret:ID]` (masked env, Reveal/Copy), `[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). A plan, questions, a proposal, a hook proposal, a secret request and a take-over show in full under the message, as the card the user acts on, never behind a chip: they are blocks, so `MarkdownParagraph` (`(partials)/markdown-paragraph.tsx`) lifts those refs out of the paragraph they were written in (`isCardRefHref` in `(utils)/card-ref-href.ts`), which React would otherwise refuse inside a `p`. 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 (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]` (its card in the message, not a chip); 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 or picking a paused plan back up ends Plan mode in that conversation (`announcePlanModeOff`): the user asked for the work to start, and its steps write, which the toggle otherwise promises nothing of. 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. A step's reply is held to the step (`planStepReviewNote`): one that neither finished it, asked the user, changed the plan nor handed work on is sent back, and a `blocked` step or a `send_reply` that queued work stops the plan instead of advancing over it (`started_work`). 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. **A plan stays one click away however far the thread moves on:** while it is open a bar sits under the conversation header (`SessionPlanBar`: title, status, step x of y) and opens it in a modal (`BotPlanModal`), and every message that belongs to it (the one that wrote it, each step report) carries a Plan chip that opens the same card. The link is `bot_messages.plan_id`, the app's record written when the message is saved (the plan it wrote, or the step it worked), since the job that made it is pruned; a finished plan's bar goes, its chips stay. The history read carries the open plan (`history.plan`), and `server:bot-plan` keeps it current (`useSessionPlan`), so the bar never waits on another read. `bot_plans` is deleted with its session (`deleteBotPlanRows`, from `deleteSessionRows`).
|
||||
- **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 or picking a paused plan back up ends Plan mode in that conversation (`announcePlanModeOff`): the user asked for the work to start, and its steps write, which the toggle otherwise promises nothing of. Approving, or picking a paused plan back up, queues the current 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, and `complete_plan_step` marks it done with what it produced (the card checks it off, `pushBotPlan` -> `server:bot-plan`). **Every finished step ends on an `ask_user` card**, in the same turn as its report: one question, "Continue with the plan?", whose first option is the next step (or "Finish the plan") and whose second is "Pause the plan". `planStepReviewNote` sends a step's reply back until it finishes the step and puts that card up (finishing it alone no longer passes), and once the rewrites are spent the job fails rather than moving the plan on. The card is `bot_questions.plan_id`; answering Continue (`planContinueAnswer`, the first option) queues the next step (`enqueuePlanStep`), and anything else (Pause, a typed answer, a skip) pauses the plan. A step job that fails pauses it too (`pauseFailedPlanStep`, from `notify-bot-job-failed`), so its card offers Resume and the notice offers Retry. Nothing advances a plan on its own, and a `blocked` reply or one that handed work to a run ends the step honestly (`ask_user`, `update_plan` and `PlanWorkStartingTools` end it). `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`, and no `complete_plan_step` (`grabBotPlanTools` gives it only to a step's own run): it can't finish a step with no card under its report, so a plan is only ever advanced from a card. A plan already running whose step isn't (a carried-over plan, one whose work stopped) has Continue on its card, which wakes the bot for that step like a resume; `enqueuePlanStep` queues nothing while a step of that plan is already open, so Continue twice starts one run. A **task run** started for a step (`send_reply`'s or `start_task`'s `plan_id`, `params.plan_id`) gets `PlanStepNote`, the plan tools and the same review, and its report carries the card. 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. **A plan stays one click away however far the thread moves on:** while it is open a bar sits under the conversation header (`SessionPlanBar`: title, status, step x of y) and opens it in a modal (`BotPlanModal`), and every message that belongs to it (the one that wrote it, each step report) carries a Plan chip that opens the same card. The link is `bot_messages.plan_id`, the app's record written when the message is saved (the plan it wrote, or the step it worked), since the job that made it is pruned; a finished plan's bar goes, its chips stay. The history read carries the open plan (`history.plan`), and `server:bot-plan` keeps it current (`useSessionPlan`), so the bar never waits on another read. `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.
|
||||
@@ -236,7 +236,7 @@ Read-only browser of every volume (`src/utils/storage-volumes.ts`: bots, workspa
|
||||
- **Providers** (`src/dict/harness-provider-dict.ts`): OpenRouter default plus OpenAI-compatible ones; one adapter today (`src/harness/providers/openai-compatible/`). Keys encrypted in private `harness_providers`, falling back to the preset env.
|
||||
- **Catalog:** `harness_models`, synced hourly. OpenRouter "free" means `:free` or `openrouter/free`, never zero prices. Auto picks: `rank-auto-models`. A custom provider's `/models` lists ids and nothing else, so its form takes a **context window** (`harness_providers.context_length`) and the sync writes it into every model that reports none of its own (`modelContextLength`); leaving it empty leaves them unknown, and a run then works to `AppData.HarnessUnknownContextWindow` (1,000,000) less the answer reserve. That guess is not silent: the model picker marks a model with no declared window, and a provider that refuses the prompt for size stops the run with its own message and the fix (`fatal`, below). Never learn a smaller window into the constant: the provider has the last word.
|
||||
- **Calling:** `resolveHarnessCandidates` -> `withCandidates` with process-wide cooldowns; errors are `HarnessError`. Order: the pick, the text setting's fallback models (`fallback_model_ids` in its options, up to `AppData.HarnessTextFallbackModelsMax`, any provider), then the free automatic picks (when `fallback` is on). Every failure is logged (`logCandidateFailure`) and benches its model (or provider, for a key or credits) for the model rest (app setting `harness_model_rest_seconds`, Settings > General run limits, default `AppData.HarnessModelRestMs`, or until the setting changes and the app restarts when the rest is unlimited; the bench lives on a `globalCache` slot (`cobble.harnessCooldowns`) so a run-limits save clears the copy the queue reads, and that save, like queue startup, wakes the jobs a rest had parked ahead of time (`releaseRestingBotJobs`)), never longer, even past a `Retry-After`: one failure once left every reply on a weak free model for an hour. A message answered by a model in place of the one ahead of it shows the fallback on its usage chip (`fell_back_from`/`resting` in `token_usages.settings`). A call that only reaches benched models records a failed-call row for each resting candidate (`recordHarnessFailure`, no re-log of the outage) so the message shows why nothing was tried, and its error names Settings > Models; a resting call says how long the wait is ("The next try is possible in 27s."), since told only "trying again shortly" a bot told the user the models were benched until a restart. A failure carries the model the candidate ran on, the request's method and address, and a hint when a 404/405 came back with an empty body (no endpoint there), so the tool's message names the pick instead of leaving the bot to guess it: with only "HTTP 404", a production bot invented a model and its routing. Entry points under `text/`, `media/`, `audio/`, `image/`, `embeddings/`. `run-text-loop.ts` sticks to one model (an automatic pick only until the pick or a fallback model has rested), caps steps (`grabHarnessMaxToolSteps`, `grabReplyMaxToolSteps`; routines and hook calls `grabUnattendedMaxToolSteps`, all unlimited by default, so a run's job deadline and its prompt-token budget are what end it; every run limit reads as `RunLimit` in `src/utils/run-limit.ts`, `number` or `"unlimited"`, saved as `-1` on the settings form and `"unlimited"` in `app_settings`; a run is told once, `stepsLowWarningLeft` steps before the wrap up, to save its report, and the wrap up keeps `WrapUpToolNames` (`write_file`, `import_file`, and `send_reply` for a reply's answer or `start_task` for work a task run can't finish: a 20-step reply used for research otherwise left the writing undone and the next reply had the same budget) for a saving-or-answer turn before the last turn with no tools, since runs measured to their last step with the report unwritten) and the prompt tokens one run may spend (`grabRunMaxPromptTokens`, 4M by default: at 40M one task run spent 195 turns and 30M tokens re-reading its own notes with the ceiling never in reach; a run is told once, a quarter in and only while it has produced nothing (`commitEarlyNote`, `isWritingTool`, `AppData.HarnessRunTokensCommitShare`), to land one piece of the work, then once at `AppData.HarnessRunTokensWarnShare` of it to land the rest, `tokensLowNote`, then the wrap up). Results are cut keeping their start and their end (`run-tool-call.ts`, `capToolOutput`), never the start alone: a `du`/`find` sweep's totals are its last lines. A read the run already made is answered from that answer (`RepeatableToolNames`, `repeatToolCallKey`, `alreadyRanToolNote`): calling `read_file`, `list_files`, `search_knowledgebase`, `list_tasks` and the like again with the same arguments returns a pointer to the output above instead of running again, and works. So a run whose brief can be wrong is told the tree wins over the brief, and told that handing the rest on with `start_task` is following the plan. `computer_bash` whose command provably only reads (`isReadOnlyCommand`: an allow-listed program and no redirect, no `tee`/`xargs`, no writing git subcommand) is a read here too; any other tool (a write, a bash command that isn't one) clears what was remembered, so a file read, edited and read again is read again. A call that failed is answered from that failure the same way, past one retry (`toolCallKey`, `AppData.HarnessSameFailureRetries`, `failedToolCallNote`): five identical failing commands once cost five turns, each resending the whole transcript. A turn that wrote a message and then called any other tool is told once that the message never went out (`answerNotSentNote`), since only the last one is sent: a run that doesn't know ends with the tail of an answer it already wrote.
|
||||
- **Token use:** every turn resends the system prompt, tool definitions and whole transcript, so a run's cost grows with its length squared (production lost 39M tokens on one routine run on a 1M-window model that never trimmed). Keep turns small: the working context is the model's declared window less the room its answer needs (`workingContextTokens`: `max_output_tokens` when declared, else a tenth of the window clamped to 8,000-64,000), capped by `grabContextBudgetTokens` when the install sets one (unlimited by default, so the window decides, never a flat share of a guessed window); `fitTranscriptToContext` trims to it, cutting in one block down to 60% so the cached prefix holds between cuts, and a trimmed tool result keeps its start and its end (`TrimmedKeepChars`) instead of being replaced whole: the old note said "call it again if you still need it", so runs did, paying twice for the same output, and a result under `TrimmedKeepChars * 4` is never cut at all (the same note once replaced a 14-character shell answer and the run read nothing for thirty steps); the newest turn's results are cut last, only once everything older is gone; every `AppData.HarnessTrimNoteEvery` trimmed turns the run is told its earlier readings were cut (`contextTrimmedNote`, traced as `trimmed`), since trimming is otherwise invisible and a run re-reads what it thinks it never saw; **the user's own text is never trimmed** (a request can't be lost mid-run), so a run whose prompt is still over the working context after everything trimmable was cut is told once (`oversizedRequestNote`, which says how much of the overage is the app's own instructions and tools and how much is the conversation: work in pieces, don't paste more in, say what it could not reach), and `fitTranscriptToContext` reports it as `over_budget: "request"`; when the system prompt and tool definitions alone pass the working context it is `over_budget: "static"` instead and `runTextLoop` stops at once with a `HarnessError` (`fatal: true`, `staticPromptOverBudgetNote`: the arithmetic, Settings > Models, a bigger-window model, fewer extensions) rather than trimming every turn and answering from nothing. Only the newest `browser_snapshot` and `browser_find` per browser stay (`supersedeToolOutputs`); browser results are capped lower (`HarnessBrowserResultMaxChars`); MCP, connector and user-browser tools are `deferred` (listed by name in the prompt, loaded with `load_tools`) once their definitions pass `HarnessDeferToolsMinChars`, and so are the bot's own tools by family (`groupTools` over `ToolGroups`, `HarnessTool.group`, once they pass `HarnessDeferBuiltinToolsMinChars` and `HarnessDeferBuiltinToolsShare` of the working context, since they are ~100k characters every turn: `load_tools` takes exact names, a family's name or `<prefix>*`, and `WrapUpToolNames`, the closing tools and `load_tools` itself are never deferred); loaded ones appended last. Don't rewrite earlier transcript messages every turn (it breaks providers' prompt caches); `token_usages.cached_tokens` shows what was served from cache. Models that can't take an image/audio part get it read by vision/transcription first (`prepareMessagesForModel`, per candidate). Tool images (screenshots, `read_file` images) are never read by the tool: tools return `{ text, images }`, the loop shows them in a user turn after the results (`toolImagesTurn`, fenced as tool output), and `prepareMessagesForModel` decides. A text model looks at images itself (attachments too) only when its text setting has "Use the model's own media reading" on (`sees_images` in the text harness options, per default/bot/workspace row, `textSeesImages`) and it takes image input: the catalog's `input_modalities` decide, so a custom provider's bare model id gets `guessModelModalities`, which says text-only for anything it doesn't recognise and then `sees_images` reads nothing (the Models page says so under the checkbox, `HarnessSeesImagesNote`, since the setting is otherwise silently useless). Otherwise the vision harness reads them (with the tool's `focus` and `redact`; pixels a seeing model gets can't be redacted). Readings are kept across runs by `MediaReadings` (`HarnessMediaReadingsCached`), keyed by `imageReadingKey`, so the same image is read once rather than once per reply; a reading made to `redact` a secret is never kept there. Only the newest `AppData.HarnessToolImagesKept` stay (`dropOldToolImages`).
|
||||
- **Token use:** every turn resends the system prompt, tool definitions and whole transcript, so a run's cost grows with its length squared (production lost 39M tokens on one routine run on a 1M-window model that never trimmed). Keep turns small: the working context is the model's declared window less the room its answer needs (`workingContextTokens`: `max_output_tokens` when declared, else a tenth of the window clamped to 8,000-64,000), capped by `grabContextBudgetTokens` when the install sets one (unlimited by default, so the window decides, never a flat share of a guessed window); `fitTranscriptToContext` trims to it, cutting in one block down to 60% so the cached prefix holds between cuts, and a trimmed tool result keeps its start and its end (`TrimmedKeepChars`) instead of being replaced whole: the old note said "call it again if you still need it", so runs did, paying twice for the same output, and a result under `TrimmedKeepChars * 4` is never cut at all (the same note once replaced a 14-character shell answer and the run read nothing for thirty steps); the newest turn's results are cut last, only once everything older is gone; every `AppData.HarnessTrimNoteEvery` trimmed turns the run is told its earlier readings were cut (`contextTrimmedNote`, traced as `trimmed`), since trimming is otherwise invisible and a run re-reads what it thinks it never saw; **the user's own text is never trimmed** (a request can't be lost mid-run), so a run whose prompt is still over the working context after everything trimmable was cut is told once (`oversizedRequestNote`, which says how much of the overage is the app's own instructions and tools and how much is the conversation: work in pieces, don't paste more in, say what it could not reach), and `fitTranscriptToContext` reports it as `over_budget: "request"`; when the system prompt and tool definitions alone pass the working context it is `over_budget: "static"` instead and `runTextLoop` stops at once with a `HarnessError` (`fatal: true`, `staticPromptOverBudgetNote`: the arithmetic, Settings > Models, a bigger-window model, fewer extensions) rather than trimming every turn and answering from nothing. Only the newest `browser_snapshot` and `browser_find` per browser stay (`supersedeToolOutputs`); browser results are capped lower (`HarnessBrowserResultMaxChars`); MCP, connector and user-browser tools are `deferred` (listed by name in the prompt, loaded with `load_tools`) once their definitions pass `HarnessDeferToolsMinChars` (a namespace of `HarnessDeferredNamespaceMin` tools or more is listed by name alone on one line: one GitHub connection's 905 tools were 148,000 characters of descriptions on every turn), and so are the bot's own tools by family (`groupTools` over `ToolGroups`, `HarnessTool.group`, once they pass `HarnessDeferBuiltinToolsMinChars` and `HarnessDeferBuiltinToolsShare` of the working context, since they are ~100k characters every turn: `load_tools` takes exact names, a family's name or `<prefix>*`, and `WrapUpToolNames`, the closing tools and `load_tools` itself are never deferred); loaded ones appended last. Don't rewrite earlier transcript messages every turn (it breaks providers' prompt caches); `token_usages.cached_tokens` shows what was served from cache. Models that can't take an image/audio part get it read by vision/transcription first (`prepareMessagesForModel`, per candidate). Tool images (screenshots, `read_file` images) are never read by the tool: tools return `{ text, images }`, the loop shows them in a user turn after the results (`toolImagesTurn`, fenced as tool output), and `prepareMessagesForModel` decides. A text model looks at images itself (attachments too) only when its text setting has "Use the model's own media reading" on (`sees_images` in the text harness options, per default/bot/workspace row, `textSeesImages`) and it takes image input: the catalog's `input_modalities` decide, so a custom provider's bare model id gets `guessModelModalities`, which says text-only for anything it doesn't recognise and then `sees_images` reads nothing (the Models page says so under the checkbox, `HarnessSeesImagesNote`, since the setting is otherwise silently useless). Otherwise the vision harness reads them (with the tool's `focus` and `redact`; pixels a seeing model gets can't be redacted). Readings are kept across runs by `MediaReadings` (`HarnessMediaReadingsCached`), keyed by `imageReadingKey`, so the same image is read once rather than once per reply; a reading made to `redact` a secret is never kept there. Only the newest `AppData.HarnessToolImagesKept` stay (`dropOldToolImages`).
|
||||
- **Per-bot models:** workspace row > bot row > default; the coordinator always uses the defaults. Every entry point takes `bot_id` and passes it on. **Embeddings are install-wide** (`install_wide` in `Harnesses`, `isInstallWideHarness`): `grabHarnessSetting` ignores bot/workspace rows for them, the per-bot/workspace forms don't list them and saving one is refused, so every stored vector comes from one model. Shared form `settings/models/(partials)/harness-settings-form.tsx`. A provider that embeds a passage and a query differently (NVIDIA's asymmetric models) is told which through `input_type`, from `embedText`'s `purpose`; `embed.ts` finds that out on the first 400 that names the field and remembers it per provider and model for the process. A provider that caps a batch below `AppData.EmbeddingBatchSize` (Alibaba's Model Studio: "batch size is invalid, it should not be larger than 20") is answered by retrying the refused batch at the size it named, remembered per provider and model (`smaller-batch-limit.ts`), so one document's large batch no longer fails the whole ingest.
|
||||
- **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`).
|
||||
|
||||
@@ -2012,6 +2012,11 @@ const schema: BUN_SQLITE_DatabaseSchemaType = {
|
||||
dataType: "INTEGER",
|
||||
defaultValue: 0,
|
||||
},
|
||||
{
|
||||
fieldName: "plan_id",
|
||||
fieldDescription: `The plan whose step ended on this card: its first option continues the plan, anything else pauses it. Empty for an ordinary question. Not a foreign key`,
|
||||
dataType: "INTEGER",
|
||||
},
|
||||
],
|
||||
indexes: [
|
||||
{
|
||||
|
||||
@@ -1305,6 +1305,10 @@ export type BUN_SQLITE_COBBLE_BOT_QUESTIONS = {
|
||||
* Asked in a Plan mode reply: their answer and skip are run in Plan mode too, since answering is not a way out of the mode
|
||||
*/
|
||||
plan_mode?: number | "";
|
||||
/**
|
||||
* The plan whose step ended on this card: its first option continues the plan, anything else pauses it. Empty for an ordinary question. Not a foreign key
|
||||
*/
|
||||
plan_id?: number | "";
|
||||
}
|
||||
|
||||
export type BUN_SQLITE_COBBLE_BOT_SUGGESTIONS = {
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "cobble",
|
||||
"version": "0.27.10",
|
||||
"version": "0.27.11",
|
||||
"module": "index.ts",
|
||||
"type": "module",
|
||||
"private": true,
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import planStepReviewNote from "./plan-step-review";
|
||||
|
||||
const plan = { id: 3, title: "Open the shop", current_step: 1 };
|
||||
const plan = { id: 3, title: "Open the shop", current_step: 1, total_steps: 3 };
|
||||
|
||||
const note = ({ on_step = true, uses = [], status }: { on_step?: boolean; uses?: { name: string; ok: boolean }[]; status?: "done" | "working" | "blocked" }) =>
|
||||
planStepReviewNote({ plan, on_step, tool_uses: uses, status });
|
||||
@@ -12,12 +12,37 @@ describe("planStepReviewNote", () => {
|
||||
expect(note({ uses: [{ name: "write_file", ok: true }] })).toContain("complete_plan_step");
|
||||
});
|
||||
|
||||
test("finishing the step passes", () => {
|
||||
expect(note({ uses: [{ name: "complete_plan_step", ok: true }] })).toBeNull();
|
||||
test("a finished step without its card is sent back for the card", () => {
|
||||
const fault = note({ uses: [{ name: "complete_plan_step", ok: true }] });
|
||||
|
||||
expect(fault).toContain("ask_user");
|
||||
expect(fault).toContain("Continue to step 3");
|
||||
expect(fault).toContain("Pause the plan");
|
||||
});
|
||||
|
||||
test("finishing the step and putting the card up passes", () => {
|
||||
const uses = [
|
||||
{ name: "complete_plan_step", ok: true },
|
||||
{ name: "ask_user", ok: true },
|
||||
];
|
||||
|
||||
expect(note({ uses })).toBeNull();
|
||||
});
|
||||
|
||||
test("the last step's card offers to finish the plan", () => {
|
||||
const last = { ...plan, current_step: 2 };
|
||||
|
||||
expect(
|
||||
planStepReviewNote({
|
||||
plan: last,
|
||||
on_step: true,
|
||||
tool_uses: [{ name: "complete_plan_step", ok: true }],
|
||||
}),
|
||||
).toContain("Finish the plan");
|
||||
});
|
||||
|
||||
test("a failed finish does not pass", () => {
|
||||
expect(note({ uses: [{ name: "complete_plan_step", ok: false }] })).toContain("did not finish it");
|
||||
expect(note({ uses: [{ name: "complete_plan_step", ok: false }] })).toContain("complete_plan_step");
|
||||
});
|
||||
|
||||
test("asking, changing the plan or handing work on ends the step honestly", () => {
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
import type { ReplyStatus } from "@/src/dict/reply-status-dict";
|
||||
import type { HarnessToolUse } from "@/src/harness/types";
|
||||
import { WorkStartingTools } from "@/src/utils/should-continue-plan";
|
||||
import PlanWorkStartingTools from "@/src/utils/plan-work-starting-tools";
|
||||
|
||||
type PlanStep = {
|
||||
id: number;
|
||||
title: string;
|
||||
current_step: number | null;
|
||||
total_steps: number;
|
||||
};
|
||||
|
||||
type Params = {
|
||||
@@ -22,35 +23,35 @@ type Params = {
|
||||
};
|
||||
|
||||
/**
|
||||
* The tools that end a step without finishing it, and are meant to: the run
|
||||
* asks the user, changes the plan, or hands work on whose report comes
|
||||
* later. A run that did none of these and never called
|
||||
* `complete_plan_step` did something else entirely (a step of its own, a
|
||||
* plan written to a file), and the app would otherwise carry the plan on
|
||||
* past the step it never did.
|
||||
* The tools that end a step without its card, and are meant to: the run
|
||||
* asks the user (the card itself), changes the plan (its card takes over),
|
||||
* or hands work on whose report comes later. Anything else that ends a step
|
||||
* leaves the plan waiting on nothing, and the user has to say "move on".
|
||||
*/
|
||||
const EndingTools = ["ask_user", "update_plan", ...WorkStartingTools];
|
||||
const EndingTools = ["ask_user", "update_plan", ...PlanWorkStartingTools];
|
||||
|
||||
/**
|
||||
* Checks a plan step's reply before it goes out: the run works one step,
|
||||
* and must either finish it or say why it can't. Returns a note that sends
|
||||
* the answer back to the model, or null when the reply ends the step the
|
||||
* way the plan expects.
|
||||
* Checks a plan step's reply before it goes out: the step ends on a card
|
||||
* whose first option continues the plan, so the plan moves on from the card
|
||||
* in front of the user, never from the bot remembering to ask. A reply that
|
||||
* reports the step and ends is sent back.
|
||||
*/
|
||||
export default function planStepReviewNote({ plan, on_step, tool_uses, status }: Params) {
|
||||
if (!on_step || !plan || plan.current_step == null) return null;
|
||||
|
||||
/**
|
||||
* A reply that started work or says what stopped it already ends the
|
||||
* step honestly; the plan waits on the user or the run it started.
|
||||
* A reply that says what stopped it, or hands the work to a run of its
|
||||
* own, ends the step where the user can see it.
|
||||
*/
|
||||
if (status == "working" || status == "blocked") return null;
|
||||
|
||||
const ended = tool_uses.some((use) => use.ok && (use.name == "complete_plan_step" || EndingTools.includes(use.name)));
|
||||
const ended = tool_uses.some((use) => use.ok && EndingTools.includes(use.name));
|
||||
|
||||
if (ended) return null;
|
||||
|
||||
const step = plan.current_step + 1;
|
||||
const next = step + 1;
|
||||
const last_step = next > plan.total_steps;
|
||||
|
||||
return `This reply works step ${step} of Plan #${plan.id} ("${plan.title}") and did not finish it. Do that step, not another: finish it with complete_plan_step and what it produced, then report it in two or three sentences. If it needs the user, ask with ask_user. If the plan itself is wrong, change it with update_plan. If the work has to be handed on, start it. Don't write a plan of your own in a file, and don't answer with a different piece of the work.`;
|
||||
return `This reply works step ${step} of Plan #${plan.id} ("${plan.title}") and ended without the step's card, so the plan has nothing to move on from. Do that step, not another: finish it with complete_plan_step and what it produced, then report it in two or three sentences, and put the card up in the same turn with ask_user. The card asks "Continue with the plan?": first option "${last_step ? "Finish the plan" : `Continue to step ${next}`}", second option "Pause the plan", then any choice the step really needs. If it needs the user for something else, ask that on the card too. If the plan itself is wrong, change it with update_plan. If the work has to be handed on, start it. Don't write a plan of your own in a file, and don't answer with a different piece of the work.`;
|
||||
}
|
||||
@@ -31,8 +31,6 @@ import grabJobUserId from "@/src/functions/backend/db/bots-queue/grab-job-user-i
|
||||
import runBotJob from "./run-bot-job";
|
||||
import parseJobJson from "./parse-job-json";
|
||||
import nameBotSession from "./name-bot-session";
|
||||
import wakeBotsQueue from "./wake-bots-queue";
|
||||
import continueBotPlan from "@/src/functions/backend/db/bot-plans/continue-bot-plan";
|
||||
import pushBotSession from "./push-bot-session";
|
||||
import grabSessionAskId from "@/src/functions/backend/db/bot-sessions/grab-session-ask-id";
|
||||
import { registerJobAbort, unregisterJobAbort } from "./job-abort-registry";
|
||||
@@ -325,24 +323,6 @@ export default async function processBotJob({
|
||||
|
||||
await pushBotNotice({ bot_id, ...completion });
|
||||
|
||||
/**
|
||||
* A run that worked a step of a plan hands it on: the next step is
|
||||
* queued here, once this reply is out, so each step is its own
|
||||
* message (`continueBotPlan` holds it when the user is needed or
|
||||
* the run started work of its own).
|
||||
*/
|
||||
if (outcome.plan_id) {
|
||||
await continueBotPlan({
|
||||
plan_id: outcome.plan_id,
|
||||
session_id: Number(completion.message?.session_id || job.session_id),
|
||||
needs_you: Boolean(outcome.needs_you),
|
||||
started_work: Boolean(outcome.started_work),
|
||||
tool_names: (outcome.tool_log || []).map((use) => use.name),
|
||||
}).then((job_id) => {
|
||||
if (job_id) wakeBotsQueue();
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Once the first exchange is sent, the bot names the session and
|
||||
* previews it. After the reply is pushed, so it never waits on it;
|
||||
|
||||
@@ -416,6 +416,7 @@ export default async function runBotReply({
|
||||
onTask: ({ task_id }) => task_ids.push(task_id),
|
||||
onAttach: ({ media_id }) => attachments.push(media_id),
|
||||
plan_mode,
|
||||
plan_id: on_plan_step ? plan?.id : null,
|
||||
});
|
||||
|
||||
/**
|
||||
@@ -591,6 +592,12 @@ export default async function runBotReply({
|
||||
* when it was asked in it (`postBotQuestionAnswers`).
|
||||
*/
|
||||
plan_mode,
|
||||
/**
|
||||
* The plan whose step this reply works, when it does:
|
||||
* the card it ends on is the plan's next move
|
||||
* (`postBotQuestionAnswers`).
|
||||
*/
|
||||
plan_id: on_plan_step ? plan?.id : null,
|
||||
onAsk: ({ ref }) => proposals.push(ref),
|
||||
redact: redact_reply,
|
||||
}),
|
||||
@@ -806,11 +813,9 @@ export default async function runBotReply({
|
||||
* on while its reports said something else.
|
||||
*/
|
||||
needs_you: answer_parts.needs_you || result.status == "blocked" || undefined,
|
||||
started_work: result.status == "working" || undefined,
|
||||
attachments: attachments.length ? attachments : undefined,
|
||||
tool_log: result.tool_uses,
|
||||
task_ids,
|
||||
plan_id: on_plan_step ? plan?.id : undefined,
|
||||
plan_message_id: message_plan_id ?? (on_plan_step ? plan?.id : undefined),
|
||||
/**
|
||||
* A reply handed a tracker task (`params.tracker_task_id`) that
|
||||
|
||||
@@ -29,6 +29,7 @@ import {
|
||||
TaskWrapUpIncomingNote,
|
||||
taskPlanNote,
|
||||
wrapUpWorktreeNote,
|
||||
PlanStepNote,
|
||||
} from "@/src/data/harness-prompts";
|
||||
import {
|
||||
grabContextBudgetTokens,
|
||||
@@ -38,6 +39,8 @@ import {
|
||||
} from "@/src/functions/backend/db/app-settings/grab-run-limits";
|
||||
import grabBotComputers from "@/src/functions/backend/db/computers/grab-bot-computers";
|
||||
import grabBotPrompt from "@/src/functions/backend/db/bots/grab-bot-prompt";
|
||||
import grabBotPlan from "@/src/functions/backend/db/bot-plans/grab-bot-plan";
|
||||
import toBotPlanView from "@/src/functions/backend/db/bot-plans/to-bot-plan-view";
|
||||
import grabUserWorkspaces from "@/src/functions/backend/db/workspaces/grab-user-workspaces";
|
||||
import runTextLoop from "@/src/harness/text/run-text-loop";
|
||||
import redactTrace from "@/src/harness/trace/redact-trace";
|
||||
@@ -86,6 +89,7 @@ import stripAppRecords from "@/src/utils/strip-app-records";
|
||||
import ScheduledRunFailedError from "./scheduled-run-failed-error";
|
||||
import BotJobFatalError from "./bot-job-fatal-error";
|
||||
import reviewRunAnswer from "./review-run-answer";
|
||||
import planStepReviewNote from "./plan-step-review";
|
||||
import deleteBotQuestion from "@/src/functions/backend/db/bot-questions/delete-bot-question";
|
||||
import type { BotJobContext, BotJobOutcome } from "./types";
|
||||
import computerRunDirs from "@/src/utils/computer-work-dirs";
|
||||
@@ -256,6 +260,22 @@ export default async function runBotTask({
|
||||
* request's run works in a session nobody reads from this bot's chat.
|
||||
*/
|
||||
const can_ask = Boolean(session_id) && !scheduled && !hooked && !hidden;
|
||||
/**
|
||||
* The plan whose step queued this run (`send_reply`'s work or
|
||||
* `start_task`, both carrying `params.plan_id`): a long step is
|
||||
* exactly where a bot forgets the plan, so the run works that step
|
||||
* and its report ends on the card that moves the plan on.
|
||||
*/
|
||||
const plan_row = Number(params.plan_id)
|
||||
? await grabBotPlan({ plan_id: Number(params.plan_id) }).catch(() => null)
|
||||
: null;
|
||||
const plan = plan_row ? toBotPlanView({ row: plan_row }) : null;
|
||||
/**
|
||||
* Only a run the user follows can end on the plan's card, so only
|
||||
* one of those is held to it: a routine's or a hook's run has no
|
||||
* card to put up and reports as usual.
|
||||
*/
|
||||
const on_plan_step = can_ask && Boolean(plan && plan.status == "active" && plan.current_step != null);
|
||||
/**
|
||||
* The coordinator weighing a worker's install request
|
||||
* (`request_install`): it answers it with answer_install_request.
|
||||
@@ -301,6 +321,21 @@ export default async function runBotTask({
|
||||
onTask: ({ task_id }) => task_ids.push(task_id),
|
||||
})),
|
||||
...admin_tools,
|
||||
/**
|
||||
* The plan's own step: it finishes the step, or says the plan
|
||||
* is wrong. Writing or cancelling a plan is a reply's job, never
|
||||
* a run's, so those stay out.
|
||||
*/
|
||||
...(on_plan_step
|
||||
? grabBotPlanTools({
|
||||
user_id,
|
||||
bot_id: bot.id,
|
||||
session_id: session_id!,
|
||||
workspace_id,
|
||||
on_step: true,
|
||||
onPlan: ({ ref }) => shown.push(ref),
|
||||
})
|
||||
: []),
|
||||
/**
|
||||
* Part of a crew request (`start_task`/`delegate_task` in an
|
||||
* answer session): the bot can send the asker an interim word
|
||||
@@ -387,6 +422,7 @@ export default async function runBotTask({
|
||||
session_id,
|
||||
workspace_id,
|
||||
in_task: true,
|
||||
plan_id: on_plan_step ? plan?.id : null,
|
||||
onAsk: ({ ref }) => take_overs.push(ref),
|
||||
redact: redact_text,
|
||||
}),
|
||||
@@ -622,6 +658,12 @@ export default async function runBotTask({
|
||||
ComputerFilesNote({ computer_id: job.computer_id || 0, dirs }),
|
||||
named_files_note,
|
||||
TasksNote,
|
||||
/**
|
||||
* The plan's step this run works: it finishes that step, or asks
|
||||
* the user on the card, and the report says which. This is the
|
||||
* note a long step would otherwise lose the plan without.
|
||||
*/
|
||||
on_plan_step && plan ? PlanStepNote({ plan }) : "",
|
||||
ActionCheckNote,
|
||||
RequestScopeNote({ can_ask }),
|
||||
can_ask ? QuestionsNote : "",
|
||||
@@ -714,6 +756,7 @@ export default async function runBotTask({
|
||||
message_id: job.message_id || undefined,
|
||||
job_id: job.id,
|
||||
run_kind: browser_run_kind,
|
||||
plan_id: on_plan_step ? plan?.id : null,
|
||||
onQueue: ({ job_id }) => queued_jobs.push(job_id),
|
||||
}),
|
||||
startTaskTool({
|
||||
@@ -723,6 +766,7 @@ export default async function runBotTask({
|
||||
computers,
|
||||
message_id: job.message_id || undefined,
|
||||
run_kind: browser_run_kind,
|
||||
plan_id: on_plan_step ? plan?.id : null,
|
||||
}),
|
||||
...extensions.tools,
|
||||
...browsers.tools,
|
||||
@@ -775,8 +819,21 @@ export default async function runBotTask({
|
||||
* is where a report names a file or task that isn't there, or
|
||||
* says work is under way when none is. A note sends it back;
|
||||
* one the review keeps faulting is never posted.
|
||||
*
|
||||
* A report of a plan's step is also held to the step's ending:
|
||||
* the plan moves on from its card, so a report without one
|
||||
* leaves the plan waiting on the user to say "move on".
|
||||
*/
|
||||
review: reviewRunAnswer({ bot_id: bot.id, user_id, session_id, scopes, job_id: job.id }),
|
||||
review: ({ text, tool_uses, status }) =>
|
||||
reviewRunAnswer({ bot_id: bot.id, user_id, session_id, scopes, job_id: job.id })({
|
||||
text,
|
||||
tool_uses,
|
||||
status,
|
||||
}).then((note) => {
|
||||
if (note) return note;
|
||||
|
||||
return planStepReviewNote({ plan, on_step: on_plan_step, tool_uses, status });
|
||||
}),
|
||||
/**
|
||||
* A report goes out only through `send_reply`, so it can't say
|
||||
* work is under way with the run's own open job behind it.
|
||||
@@ -846,6 +903,7 @@ export default async function runBotTask({
|
||||
attachments: attachments.length ? attachments : undefined,
|
||||
tool_log: result.tool_uses,
|
||||
task_ids,
|
||||
plan_message_id: on_plan_step ? plan?.id : undefined,
|
||||
/**
|
||||
* The wrap up was announced (`steps` counts its turns), so the
|
||||
* run never got to the end of the work it was given.
|
||||
|
||||
+3
-15
@@ -74,25 +74,13 @@ export type BotJobOutcome = {
|
||||
* (`noteTrackerTask`).
|
||||
*/
|
||||
exhausted?: boolean;
|
||||
/**
|
||||
* The plan this run worked a step of (`params.plan_id`): the app queues
|
||||
* its next step once the reply is out (`continueBotPlan`), unless the
|
||||
* run asked for the user or started work that runs on its own.
|
||||
*/
|
||||
plan_id?: number;
|
||||
/**
|
||||
* The plan the reply's message belongs to: the step it worked, or the
|
||||
* one it wrote. Kept on the message as a chip (`bot_messages.plan_id`),
|
||||
* separately from `plan_id`, since a plan that is only written is not
|
||||
* worked on.
|
||||
* one it wrote. Kept on the message as a chip (`bot_messages.plan_id`).
|
||||
* A plan never queues its own next step: that starts from the card under
|
||||
* the step's report, answered by the user.
|
||||
*/
|
||||
plan_message_id?: number;
|
||||
/**
|
||||
* The closing `send_reply` queued a run (`status: "working"`): its report
|
||||
* is still to come, so the plan waits for it instead of queueing its
|
||||
* next step (`continueBotPlan`).
|
||||
*/
|
||||
started_work?: boolean;
|
||||
};
|
||||
|
||||
export type BotJobRunner = (context: BotJobContext) => Promise<BotJobOutcome>;
|
||||
|
||||
@@ -7,6 +7,7 @@ import Stack from "@moduletrace/twui/layout/Stack";
|
||||
import type { ComputerViewMode } from "@/src/dict/computer-dict";
|
||||
import ComputerRestartButton from "./computer-restart-button";
|
||||
import ComputerView from "./computer-view";
|
||||
import { twMerge } from "tailwind-merge";
|
||||
|
||||
type Props = {
|
||||
open: boolean;
|
||||
@@ -56,7 +57,12 @@ export default function ComputerViewerModal({
|
||||
}}
|
||||
className="max-w-[95vw]! h-[90vh] p-0 bg-paper flex flex-col overflow-hidden"
|
||||
>
|
||||
<Row className="w-full gap-3! flex-nowrap items-center pl-5 pr-14 py-3 border-0 border-b border-solid border-hairline">
|
||||
<Row
|
||||
className={twMerge(
|
||||
"w-full gap-3! xl:flex-nowrap pl-5 pr-5 xl:pr-14 py-3 border-0 border-b border-solid border-hairline",
|
||||
"items-start xl:items-center flex-col xl:flex-row",
|
||||
)}
|
||||
>
|
||||
<Stack className="min-w-0 gap-0! items-start">
|
||||
<H2 className="text-base! leading-6! tracking-normal! font-bold text-ink truncate w-full">
|
||||
{name}
|
||||
|
||||
@@ -755,6 +755,13 @@ export const AppData = {
|
||||
* shows.
|
||||
*/
|
||||
HarnessDeferredToolLineChars: 140,
|
||||
/**
|
||||
* Tools of one namespace (one connector's, one MCP server's) past which
|
||||
* the list names them without their descriptions: one GitHub account's
|
||||
* 905 tools came to 148,000 characters that way, sent with every turn
|
||||
* of every run.
|
||||
*/
|
||||
HarnessDeferredNamespaceMin: 40,
|
||||
/**
|
||||
* Images one tool call may hand back (the rest are dropped), and how
|
||||
* many of the newest tool images stay in a run's transcript: every
|
||||
|
||||
@@ -323,13 +323,20 @@ describe("plan notes", () => {
|
||||
expect(PlansNote).toContain("nothing of it starts until the user approves it");
|
||||
});
|
||||
|
||||
test("tells the run to work its step only, then report in two or three sentences", () => {
|
||||
test("tells the run to work its step only, report briefly, then put the card up", () => {
|
||||
const note = PlanStepNote({ plan });
|
||||
|
||||
expect(note).toContain("This reply works step 2 only: Score them");
|
||||
expect(note).toContain("One step per reply");
|
||||
expect(note).toContain("This run works step 2 only: Score them");
|
||||
expect(note).toContain("One step per run");
|
||||
expect(note).toContain("two or three sentences");
|
||||
expect(note).toContain("complete_plan_step");
|
||||
expect(note).toContain("Every finished step ends on a card");
|
||||
expect(note).toContain('"Continue to step 3"');
|
||||
expect(note).toContain('"Pause the plan"');
|
||||
});
|
||||
|
||||
test("the last step's card offers to finish the plan", () => {
|
||||
expect(PlanStepNote({ plan: { ...plan, current_step: 2 } })).toContain('"Finish the plan"');
|
||||
});
|
||||
|
||||
test("lists the steps with where each one stands and what it produced", () => {
|
||||
|
||||
@@ -1034,6 +1034,8 @@ Plan #${plan.id} "${plan.title}" is on its card in this conversation, waiting fo
|
||||
export const PlanStepNote = ({ plan }: { plan: PlanPrompt }) => {
|
||||
const index = plan.current_step ?? 0;
|
||||
const step = plan.steps[index];
|
||||
const next = index + 2;
|
||||
const next_label = next > plan.steps.length ? "Finish the plan" : `Continue to step ${next}`;
|
||||
|
||||
return `# Your plan, step ${index + 1} of ${plan.steps.length}
|
||||
|
||||
@@ -1041,13 +1043,14 @@ Plan #${plan.id} "${plan.title}".${plan.goal ? ` Goal: ${plan.goal}` : ""}
|
||||
|
||||
${planStepLines({ plan })}
|
||||
|
||||
This reply works step ${index + 1} only: ${step?.text || ""}
|
||||
This run works step ${index + 1} only: ${step?.text || ""}
|
||||
|
||||
- One step per reply. The app wakes you for the next one when this finishes, so don't start it now and don't do two.
|
||||
- One step per run. The next step starts when the user answers this report's card, so don't start it now and don't do two.
|
||||
- Finish it with complete_plan_step: one or two lines on what it produced (the number, the path, the link). Then write your report to the user.
|
||||
- Your report is two or three sentences: what this step did and what it produced. No heading, no recap of the plan, and never "next, I'll...". The card above the report shows the plan and the step after this one, so repeating it only makes the reply longer than it needs to be.
|
||||
- If the step can't be done from here (it needs the user, a login or a decision they alone can make), don't finish it: ask one question with ask_user and say the plan is holding at this step.
|
||||
- If what you found means the rest of the plan is wrong, change it with update_plan, in the same reply, and say what changed.`;
|
||||
- **Every finished step ends on a card.** Call ask_user in the same turn as the report (beside the send_reply that sends it): one question, "Continue with the plan?", whose first option is "${next_label}", whose second is "Pause the plan", after those any choice this step really needs. The user answers in one click and the app starts the next step, so nothing waits on them typing "move on": a report without the card is sent back.
|
||||
- If the step can't be done from here (it needs the user, a login or a decision they alone can make), don't finish it: ask that question on the card, and say the plan is holding at this step.
|
||||
- If what you found means the rest of the plan is wrong, change it with update_plan, in the same run, and say what changed.`;
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -1063,7 +1066,7 @@ Plan #${plan.id} "${plan.title}" is approved and in progress${index == null ? ""
|
||||
|
||||
${planStepLines({ plan })}
|
||||
|
||||
- If the user's message is about this plan's work, work that step and only that step, then complete_plan_step with what it produced, then a short report.
|
||||
- Its steps are worked one per reply, each ending on a card the user answers to start the next one. This reply isn't working a step, so don't work one here: if they ask you to carry on, say the next step is step ${(index ?? 0) + 1} and they start it from the plan's card (Continue on the plan, under the report above), then answer whatever else they asked.
|
||||
- If they asked something else, answer that and leave the plan where it is: it carries on from there.
|
||||
- The steps are theirs to change on the card. If the work moved on from one of them, update_plan and say what changed.`;
|
||||
};
|
||||
|
||||
@@ -1,66 +0,0 @@
|
||||
import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
import currentPlanStepIndex from "@/src/utils/current-plan-step-index";
|
||||
import parseBotPlanSteps from "@/src/utils/parse-bot-plan-steps";
|
||||
import shouldContinuePlan from "@/src/utils/should-continue-plan";
|
||||
import enqueuePlanStep from "./enqueue-plan-step";
|
||||
import grabBotPlan from "./grab-bot-plan";
|
||||
|
||||
type Params = {
|
||||
plan_id: number | string;
|
||||
session_id: number | string;
|
||||
/**
|
||||
* The reply asked the user something (`ask_user`), so it waits on them
|
||||
* rather than carrying on.
|
||||
*/
|
||||
needs_you?: boolean;
|
||||
/**
|
||||
* The tools the run called: one that starts work (a task, a hand-over,
|
||||
* a request to another bot) has a report still to come, so the plan
|
||||
* waits for it instead of talking over it.
|
||||
*/
|
||||
tool_names?: string[];
|
||||
/**
|
||||
* The reply queued a run (`send_reply` with work), whose report is still
|
||||
* to come: the plan waits for it rather than working over it.
|
||||
*/
|
||||
started_work?: boolean;
|
||||
};
|
||||
|
||||
/**
|
||||
* Carries a plan on after a run finished a step: the bot reports the step it
|
||||
* finished, and this wakes it for the next one, so the work runs through the
|
||||
* plan step by step without the user nudging it each time.
|
||||
*
|
||||
* Nothing is queued when the run is waiting on the user, when it started
|
||||
* work whose report is still to come, when the plan was paused or cancelled
|
||||
* meanwhile, or when the conversation already has a reply waiting (a message
|
||||
* the user sent mid-step, whose own run picks the plan up from there).
|
||||
*/
|
||||
export default async function continueBotPlan({ plan_id, session_id, needs_you, tool_names, started_work }: Params) {
|
||||
const row = await grabBotPlan({ plan_id });
|
||||
const steps = parseBotPlanSteps({ text: row.steps });
|
||||
|
||||
const waiting = (
|
||||
await BunSQLite.sql<{ id: number }>({
|
||||
sql: `SELECT id FROM bots_queue
|
||||
WHERE session_id = ? AND kind = 'reply' AND status IN ('pending', 'processing')
|
||||
LIMIT 1`,
|
||||
values: [Number(session_id)],
|
||||
})
|
||||
).payload?.[0];
|
||||
|
||||
const carry_on = shouldContinuePlan({
|
||||
status: row.status || "",
|
||||
needs_you,
|
||||
tool_names,
|
||||
started_work,
|
||||
plan_session_id: row.session_id,
|
||||
session_id,
|
||||
has_pending_step: currentPlanStepIndex({ steps }) != null,
|
||||
has_waiting_reply: Boolean(waiting),
|
||||
});
|
||||
|
||||
if (!carry_on) return null;
|
||||
|
||||
return await enqueuePlanStep({ plan_id: row.id });
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
import { BotReplyJobTitle } from "@/src/dict/bot-queue-dict";
|
||||
import currentPlanStepIndex from "@/src/utils/current-plan-step-index";
|
||||
import parseBotPlanSteps from "@/src/utils/parse-bot-plan-steps";
|
||||
@@ -27,6 +28,17 @@ export default async function enqueuePlanStep({ plan_id }: Params) {
|
||||
|
||||
if (currentPlanStepIndex({ steps }) == null) return null;
|
||||
|
||||
/**
|
||||
* A step is already queued or running for this plan: Continue twice, or
|
||||
* Continue while the step works, must not start a second run on it.
|
||||
*/
|
||||
const open = await BunSQLite.sql<{ id: number }>({
|
||||
sql: `SELECT id FROM bots_queue WHERE session_id = ? AND status IN ('pending', 'processing') AND json_extract(params, '$.plan_id') = ? LIMIT 1`,
|
||||
values: [Number(row.session_id), Number(row.id)],
|
||||
});
|
||||
|
||||
if ((open.payload || []).length > 0) return null;
|
||||
|
||||
const user_id = Number(row.user_id);
|
||||
|
||||
const job_id = await enqueueBotJob({
|
||||
|
||||
@@ -18,21 +18,26 @@ type Params = {
|
||||
* changes nothing and a finished plan never comes back.
|
||||
*
|
||||
* Returns the row as it now stands and whether it just started, which is
|
||||
* when the bot is woken for its first step.
|
||||
* when the bot is woken for the step it stands on.
|
||||
*/
|
||||
export default async function setBotPlanStatus({ plan_id, user_id, status }: Params) {
|
||||
const row = await grabBotPlan({ plan_id, user_id });
|
||||
const current = row.status as BotPlanState;
|
||||
|
||||
if (current == status) return { row, started: false };
|
||||
const steps = parseBotPlanSteps({ text: row.steps });
|
||||
const caught_up = currentPlanStepIndex({ steps }) == null;
|
||||
|
||||
/**
|
||||
* Already where it's being sent: nothing changes, but "active" is also
|
||||
* how the user starts a step that isn't running (Continue on the card),
|
||||
* so it wakes the bot when a step is still left.
|
||||
*/
|
||||
if (current == status) return { row, started: status == "active" && !caught_up };
|
||||
|
||||
if (current == "done" || current == "cancelled") {
|
||||
throw new AppError(`This plan is ${current}: it can't be picked up again.`);
|
||||
}
|
||||
|
||||
const steps = parseBotPlanSteps({ text: row.steps });
|
||||
const caught_up = currentPlanStepIndex({ steps }) == null;
|
||||
|
||||
if (status == "active") {
|
||||
if (current != "planned" && current != "paused") {
|
||||
throw new AppError(`This plan is ${current}: it isn't paused.`);
|
||||
|
||||
@@ -11,6 +11,11 @@ type Params = {
|
||||
* Asked in a Plan mode reply: the answers are run in Plan mode too.
|
||||
*/
|
||||
plan_mode?: boolean;
|
||||
/**
|
||||
* The plan whose step ended on these questions: its first option
|
||||
* continues the plan, anything else pauses it.
|
||||
*/
|
||||
plan_id?: number | string | null;
|
||||
title: string;
|
||||
questions: BotQuestionItem[];
|
||||
};
|
||||
@@ -19,7 +24,7 @@ type Params = {
|
||||
* Stores questions a bot asks the user, pending until they answer or skip
|
||||
* them in its card. Returns its id.
|
||||
*/
|
||||
export default async function createBotQuestion({ user_id, bot_id, session_id, workspace_id, plan_mode, title, questions }: Params) {
|
||||
export default async function createBotQuestion({ user_id, bot_id, session_id, workspace_id, plan_mode, plan_id, title, questions }: Params) {
|
||||
const res = await BunSQLite.insert<BUN_SQLITE_COBBLE_BOT_QUESTIONS, (typeof BunSQLiteTables)[number]>({
|
||||
table: "bot_questions",
|
||||
data: [
|
||||
@@ -32,6 +37,7 @@ export default async function createBotQuestion({ user_id, bot_id, session_id, w
|
||||
session_id: Number(session_id),
|
||||
workspace_id: workspace_id ? Number(workspace_id) : undefined,
|
||||
plan_mode: plan_mode ? 1 : 0,
|
||||
plan_id: plan_id ? Number(plan_id) : undefined,
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
@@ -11,9 +11,17 @@ import type { BotQuestionView } from "@/src/types";
|
||||
* The side-effect helpers are mocked; the branch under test is the one that
|
||||
* carries the mode from the card onto the message and the job.
|
||||
*/
|
||||
let question: { bot_id: number; session_id: number; workspace_id: number | null; plan_mode: number };
|
||||
let question: {
|
||||
bot_id: number;
|
||||
session_id: number;
|
||||
workspace_id: number | null;
|
||||
plan_mode: number;
|
||||
plan_id?: number | null;
|
||||
};
|
||||
let inserted: Array<Record<string, unknown>> = [];
|
||||
let enqueued: Array<Record<string, unknown>> = [];
|
||||
let step_jobs: number[] = [];
|
||||
let paused: Array<Record<string, unknown>> = [];
|
||||
let pushed: number[] = [];
|
||||
|
||||
mock.module("@/src/functions/backend/db/bot-questions/grab-bot-question", () => ({
|
||||
@@ -47,6 +55,21 @@ mock.module("@/src/bots-queue/push-bot-notice", () => ({
|
||||
pushed.push(message.id);
|
||||
},
|
||||
}));
|
||||
mock.module("@/src/functions/backend/db/bot-plans/enqueue-plan-step", () => ({
|
||||
default: async ({ plan_id }: { plan_id: number }) => {
|
||||
step_jobs.push(plan_id);
|
||||
return 900;
|
||||
},
|
||||
}));
|
||||
mock.module("@/src/functions/backend/db/bot-plans/set-bot-plan-status", () => ({
|
||||
default: async (params: Record<string, unknown>) => {
|
||||
paused.push(params);
|
||||
return { row: { id: params.plan_id }, started: false };
|
||||
},
|
||||
}));
|
||||
mock.module("@/src/bots-queue/push-bot-plan", () => ({
|
||||
default: async () => {},
|
||||
}));
|
||||
mock.module("@/src/bots-queue/wake-bots-queue", () => ({
|
||||
default: () => {},
|
||||
}));
|
||||
@@ -68,9 +91,11 @@ const view = {
|
||||
} as unknown as BotQuestionView;
|
||||
|
||||
beforeEach(() => {
|
||||
question = { bot_id: 1, session_id: 135, workspace_id: null, plan_mode: 0 };
|
||||
question = { bot_id: 1, session_id: 135, workspace_id: null, plan_mode: 0, plan_id: null };
|
||||
inserted = [];
|
||||
enqueued = [];
|
||||
step_jobs = [];
|
||||
paused = [];
|
||||
pushed = [];
|
||||
});
|
||||
|
||||
@@ -93,4 +118,40 @@ describe("postBotQuestionAnswers", () => {
|
||||
expect(inserted[0]!.plan_mode).toBe(false);
|
||||
expect(enqueued[0]!.params).toBeUndefined();
|
||||
});
|
||||
|
||||
test("a plan's card answered Continue starts the next step, with no other reply", async () => {
|
||||
question.plan_id = 3;
|
||||
|
||||
await postBotQuestionAnswers({ view, user_id: 1 });
|
||||
|
||||
expect(step_jobs).toEqual([3]);
|
||||
expect(enqueued).toHaveLength(0);
|
||||
expect(paused).toHaveLength(0);
|
||||
});
|
||||
|
||||
test("any other answer to a plan's card pauses the plan and still answers", async () => {
|
||||
question.plan_id = 3;
|
||||
|
||||
await postBotQuestionAnswers({
|
||||
view: { ...view, answers: [{ choices: [1], other: "" }] } as unknown as BotQuestionView,
|
||||
user_id: 1,
|
||||
});
|
||||
|
||||
expect(paused).toHaveLength(1);
|
||||
expect(paused[0]!.status).toBe("paused");
|
||||
expect(step_jobs).toEqual([]);
|
||||
expect(enqueued).toHaveLength(1);
|
||||
});
|
||||
|
||||
test("a skipped plan card holds the plan rather than moving it on", async () => {
|
||||
question.plan_id = 3;
|
||||
|
||||
await postBotQuestionAnswers({
|
||||
view: { ...view, status: "skipped" } as unknown as BotQuestionView,
|
||||
user_id: 1,
|
||||
});
|
||||
|
||||
expect(step_jobs).toEqual([]);
|
||||
expect(paused).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
@@ -1,13 +1,18 @@
|
||||
import type { BUN_SQLITE_COBBLE_BOT_QUESTIONS, BUN_SQLITE_COBBLE_BOT_SESSIONS } from "@/db/types/db";
|
||||
import { logError } from "@/src/functions/backend/logger";
|
||||
import pushBotNotice from "@/src/bots-queue/push-bot-notice";
|
||||
import pushBotPlan from "@/src/bots-queue/push-bot-plan";
|
||||
import wakeBotsQueue from "@/src/bots-queue/wake-bots-queue";
|
||||
import type { BotQuestionView } from "@/src/types";
|
||||
import botQuestionAnswersText from "@/src/utils/bot-question-answers-text";
|
||||
import planContinueAnswer from "@/src/utils/plan-continue-answer";
|
||||
import conversationLock from "../bot-sessions/conversation-lock";
|
||||
import ensureBotSession from "../bot-sessions/ensure-bot-session";
|
||||
import grabUserBotSession from "../bot-sessions/grab-user-bot-session";
|
||||
import insertUserMessage from "../bots/insert-user-message";
|
||||
import enqueueBotReply from "../bots-queue/enqueue-bot-reply";
|
||||
import setBotPlanStatus from "../bot-plans/set-bot-plan-status";
|
||||
import enqueuePlanStep from "../bot-plans/enqueue-plan-step";
|
||||
import grabBotQuestion from "./grab-bot-question";
|
||||
|
||||
type Params = {
|
||||
@@ -21,6 +26,11 @@ type Params = {
|
||||
* which wakes it. The route posts this, not the card's page: the same
|
||||
* conversation can be on screen in several places, and an answer belongs
|
||||
* where the question was asked, never to whichever bot's page was open.
|
||||
*
|
||||
* A card a plan's step ended on is the plan's own next move: Continue
|
||||
* starts its next step, and anything else pauses it, so the plan never
|
||||
* waits on the user to say "move on" in the chat.
|
||||
*
|
||||
* Best effort: a failure is logged and never undoes the answer.
|
||||
*/
|
||||
export default async function postBotQuestionAnswers({ view, user_id }: Params) {
|
||||
@@ -29,34 +39,74 @@ export default async function postBotQuestionAnswers({ view, user_id }: Params)
|
||||
|
||||
if (!row.bot_id) return;
|
||||
|
||||
const session = await pickSession({ row, user_id });
|
||||
const workspace_id = row.workspace_id || null;
|
||||
const bot_id = Number(row.bot_id);
|
||||
|
||||
/**
|
||||
* Asked in Plan mode, answered and skipped in it: a question is
|
||||
* about what to plan, so its answer must not unlock the write
|
||||
* tools (the only ways out are Tab and approving a plan).
|
||||
*/
|
||||
const plan_mode = Boolean(row.plan_mode);
|
||||
await conversationLock.run({
|
||||
key: `${user_id}:${bot_id}:${workspace_id || 0}`,
|
||||
task: async () => {
|
||||
const session = await pickSession({ row, user_id });
|
||||
|
||||
const message = await insertUserMessage({
|
||||
bot_id: Number(row.bot_id),
|
||||
session_id: Number(session.id),
|
||||
workspace_id: session.workspace_id || null,
|
||||
text: botQuestionAnswersText({ view }),
|
||||
plan_mode,
|
||||
/**
|
||||
* Asked in Plan mode, answered and skipped in it: a question
|
||||
* is about what to plan, so its answer must not unlock the
|
||||
* write tools (the only ways out are Tab and approving a
|
||||
* plan).
|
||||
*/
|
||||
const plan_mode = Boolean(row.plan_mode);
|
||||
|
||||
const message = await insertUserMessage({
|
||||
bot_id,
|
||||
session_id: Number(session.id),
|
||||
workspace_id,
|
||||
text: botQuestionAnswersText({ view }),
|
||||
plan_mode,
|
||||
});
|
||||
|
||||
await pushBotNotice({ bot_id, message });
|
||||
|
||||
const plan_id = Number(row.plan_id) || 0;
|
||||
const continue_plan = plan_id > 0 && planContinueAnswer({ view });
|
||||
|
||||
if (plan_id > 0 && !continue_plan) {
|
||||
await setBotPlanStatus({ plan_id, user_id, status: "paused" })
|
||||
.then(async () => {
|
||||
await pushBotPlan({
|
||||
plan_id,
|
||||
session_id: Number(session.id),
|
||||
bot_id,
|
||||
});
|
||||
})
|
||||
.catch(() => null);
|
||||
}
|
||||
|
||||
if (continue_plan) {
|
||||
const step_job = await enqueuePlanStep({ plan_id }).catch(() => null);
|
||||
|
||||
/**
|
||||
* The plan runs its step as its own run, which reads the
|
||||
* answer above in the conversation. Only when that can't
|
||||
* be queued does the answer get an ordinary reply, so it
|
||||
* is never left unanswered.
|
||||
*/
|
||||
if (step_job) {
|
||||
wakeBotsQueue();
|
||||
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
await enqueueBotReply({
|
||||
user_id,
|
||||
bot_id,
|
||||
session_id: Number(session.id),
|
||||
message_id: Number(message.id),
|
||||
...(plan_mode ? { params: { plan_mode: true } } : {}),
|
||||
});
|
||||
|
||||
wakeBotsQueue();
|
||||
},
|
||||
});
|
||||
|
||||
await pushBotNotice({ bot_id: row.bot_id, message });
|
||||
|
||||
await enqueueBotReply({
|
||||
user_id,
|
||||
bot_id: row.bot_id,
|
||||
session_id: Number(session.id),
|
||||
message_id: Number(message.id),
|
||||
...(plan_mode ? { params: { plan_mode: true } } : {}),
|
||||
});
|
||||
|
||||
wakeBotsQueue();
|
||||
} catch (error: unknown) {
|
||||
await logError({
|
||||
title: `A bot's question answers didn't reach it`,
|
||||
|
||||
@@ -163,5 +163,16 @@ export default async function carryOverBotSession({
|
||||
values: [next.id!, active.id],
|
||||
});
|
||||
|
||||
/**
|
||||
* The plan comes with the conversation. A step and its card are read
|
||||
* from the session the plan is filed under, so one left on the closed
|
||||
* session leaves the thread the user is in with no plan, no bar and no
|
||||
* card to answer, and the bot forgets the work it was in the middle of.
|
||||
*/
|
||||
await BunSQLite.sql({
|
||||
sql: `UPDATE bot_plans SET session_id = ?, updated_at = ? WHERE session_id = ? AND status IN ('planned', 'active', 'paused')`,
|
||||
values: [next.id!, now, active.id],
|
||||
});
|
||||
|
||||
return message;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
import createKeyLock from "@/src/utils/create-key-lock";
|
||||
|
||||
/**
|
||||
* One conversation's writes go one at a time. Reading the active session,
|
||||
* storing the message and queueing its reply belong together: two sends in
|
||||
* flight together (a double submit, a retry firing beside the first) both
|
||||
* read the same full session, one rolls the conversation over, and the
|
||||
* other writes into the session that was just closed, where the user never
|
||||
* sees it.
|
||||
*/
|
||||
const conversationLock = createKeyLock();
|
||||
|
||||
export default conversationLock;
|
||||
@@ -49,7 +49,16 @@ export default async function rollOverBotSession({
|
||||
}).catch(() => null);
|
||||
});
|
||||
|
||||
if (!message) return active;
|
||||
if (!message) {
|
||||
/**
|
||||
* The conversation may have moved on under this call (a send that
|
||||
* rolled it over first): the message goes into the session that is
|
||||
* current now, never the closed one it was about to be written in.
|
||||
*/
|
||||
const current = await grabActiveBotSession({ user_id, bot_id, workspace_id });
|
||||
|
||||
return current?.id ? current : active;
|
||||
}
|
||||
|
||||
await pushBotNotice({ bot_id, message, quiet_push: true });
|
||||
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
import type { HarnessTool } from "../types";
|
||||
import deferredToolsNote from "./deferred-tools-note";
|
||||
|
||||
function tool({ name, group }: { name: string; group?: string }) {
|
||||
return { name, description: `Does ${name}.`, group } as unknown as HarnessTool;
|
||||
}
|
||||
|
||||
describe("deferredToolsNote", () => {
|
||||
test("a big namespace is one line of names, not a line per description", () => {
|
||||
const count = AppData.HarnessDeferredNamespaceMin;
|
||||
const tools = Array.from({ length: count }, (_, index) => tool({ name: `github__TOOL_${index}` }));
|
||||
const note = deferredToolsNote({ tools });
|
||||
|
||||
expect(note).toContain(`- github (${count} tools): github__TOOL_0, github__TOOL_1,`);
|
||||
expect(note).not.toContain("Does github__TOOL_0.");
|
||||
expect(note.split("\n")).toHaveLength(2);
|
||||
});
|
||||
|
||||
test("a small namespace still names each tool", () => {
|
||||
const note = deferredToolsNote({ tools: [tool({ name: "gmail__SEND" }), tool({ name: "gmail__FETCH" })] });
|
||||
|
||||
expect(note).toContain("- gmail__SEND: Does gmail__SEND.");
|
||||
expect(note).toContain("- gmail__FETCH: Does gmail__FETCH.");
|
||||
});
|
||||
|
||||
test("a family and a tool with no namespace are listed as before", () => {
|
||||
const note = deferredToolsNote({
|
||||
tools: [tool({ name: "read_file", group: "files" }), tool({ name: "browser_click" })],
|
||||
});
|
||||
|
||||
expect(note).toContain("- files: read_file (load the family by its name)");
|
||||
expect(note).toContain("- browser_click: Does browser_click.");
|
||||
});
|
||||
});
|
||||
@@ -7,23 +7,35 @@ import { LoadToolsToolName } from "../tools/load-tools-tool";
|
||||
* bot's own tools by family, each with the names in it, and every extension
|
||||
* tool by name with the start of its description, so the model knows what is
|
||||
* there without every definition riding along on each turn.
|
||||
*
|
||||
* A namespace (one connector's or MCP server's tools) that offers many
|
||||
* tools is listed by name alone, on one line: one GitHub account's 905 tools
|
||||
* came to 148,000 characters with their descriptions, sent with every turn
|
||||
* of every run. Their names still cost 34,000 characters, which is the price
|
||||
* of a bot finding the one tool it needs without loading 905 definitions.
|
||||
*/
|
||||
export default function deferredToolsNote({ tools }: { tools: HarnessTool[] }) {
|
||||
const families = new Map<string, string[]>();
|
||||
const loose: HarnessTool[] = [];
|
||||
const loose = new Map<string, HarnessTool[]>();
|
||||
|
||||
for (const tool of tools) {
|
||||
if (!tool.group) {
|
||||
loose.push(tool);
|
||||
if (tool.group) {
|
||||
families.set(tool.group, [...(families.get(tool.group) ?? []), tool.name]);
|
||||
continue;
|
||||
}
|
||||
|
||||
families.set(tool.group, [...(families.get(tool.group) ?? []), tool.name]);
|
||||
const prefix = tool.name.includes("__") ? tool.name.slice(0, tool.name.indexOf("__")) : "";
|
||||
|
||||
loose.set(prefix, [...(loose.get(prefix) ?? []), tool]);
|
||||
}
|
||||
|
||||
const lines = [
|
||||
...[...families].map(([group, names]) => `- ${group}: ${names.join(", ")} (load the family by its name)`),
|
||||
...loose.map((tool) => `- ${tool.name}: ${shortDescription({ text: tool.description })}`),
|
||||
...[...loose].flatMap(([prefix, names]) =>
|
||||
prefix && names.length >= AppData.HarnessDeferredNamespaceMin
|
||||
? [`- ${prefix} (${names.length} tools): ${names.map((tool) => tool.name).join(", ")}`]
|
||||
: names.map((tool) => `- ${tool.name}: ${shortDescription({ text: tool.description })}`),
|
||||
),
|
||||
];
|
||||
|
||||
return `Tools you can load: these are available to you but not loaded yet, to keep each step small. Call ${LoadToolsToolName} with what you need (one call can load several), then call them: exact names, a family's name for all of it, or "<prefix>*". Don't load what you won't use.\n${lines.join("\n")}`;
|
||||
@@ -34,4 +46,4 @@ function shortDescription({ text }: { text: string }) {
|
||||
const max = AppData.HarnessDeferredToolLineChars;
|
||||
|
||||
return line.length > max ? `${line.slice(0, max - 3).trimEnd()}...` : line;
|
||||
}
|
||||
}
|
||||
@@ -113,6 +113,12 @@ type Params = {
|
||||
* refuses work, and `run-bot-reply` gates the tools to the allowlist.
|
||||
*/
|
||||
plan_mode?: boolean;
|
||||
/**
|
||||
* The plan whose step this reply works: the work its `send_reply` queues
|
||||
* carries the plan, so that run's report ends on the card that moves the
|
||||
* plan on.
|
||||
*/
|
||||
plan_id?: number | null;
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -164,6 +170,7 @@ export default async function grabBotChatTools({
|
||||
onTask,
|
||||
onAttach,
|
||||
plan_mode,
|
||||
plan_id,
|
||||
}: Params): Promise<HarnessTool[]> {
|
||||
const bot_id = bot.id || 0;
|
||||
const dirs = computerRunDirs({ bot_id, bot_kind: bot.kind, user_id, workspace_id });
|
||||
@@ -191,6 +198,7 @@ export default async function grabBotChatTools({
|
||||
run_kind,
|
||||
onQueue,
|
||||
plan_mode,
|
||||
plan_id,
|
||||
}),
|
||||
...(computers.length
|
||||
? [
|
||||
|
||||
@@ -22,8 +22,9 @@ type Args = {
|
||||
|
||||
/**
|
||||
* The plan's current step is finished: the card checks it off with what it
|
||||
* produced, and the app wakes the bot for the next one after this reply.
|
||||
* A step is only ever finished by a run that did the work, one at a time.
|
||||
* produced. The next step starts when the user answers the card the report
|
||||
* ends on, so a step is only ever finished by a run that did the work, one
|
||||
* at a time.
|
||||
*/
|
||||
export default function completePlanStepTool({ bot_id, session_id, in_run }: Params): HarnessTool<Args> {
|
||||
let completed = false;
|
||||
@@ -74,7 +75,7 @@ export default function completePlanStepTool({ bot_id, session_id, in_run }: Par
|
||||
return `Step ${done.index + 1} is done: the card shows it. Carry on with step ${(done.next_step ?? 0) + 1}: ${next?.text || ""}. Save your report for the end, when every step is done.`;
|
||||
}
|
||||
|
||||
return `Step ${done.index + 1} is done: the card shows it. The next step starts on its own after this reply (step ${(done.next_step ?? 0) + 1}: ${next?.text || ""}), so don't start it now. Write your report: two or three sentences on what this step produced.`;
|
||||
return `Step ${done.index + 1} is done: the card shows it. The next step (step ${(done.next_step ?? 0) + 1}: ${next?.text || ""}) starts when the user answers the card on your report, so don't start it now. Write your report: two or three sentences on what this step produced, and put the card up beside it.`;
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -5,7 +5,9 @@ import grabBotPlanTools from "./grab-bot-plan-tools";
|
||||
* A run working a plan's step may only work it: writing another plan, or
|
||||
* cancelling the one it was woken for, is the user's call on the card. A
|
||||
* scheduled run has no card to approve anything on, so its plan starts
|
||||
* itself and nothing is left for the bot to cancel.
|
||||
* itself and nothing is left for the bot to cancel. A reply that isn't a
|
||||
* step can't finish one either, or the plan would sit active with no card
|
||||
* to start the next step from.
|
||||
*/
|
||||
const names = (tools: { name: string }[]) => tools.map((tool) => tool.name);
|
||||
|
||||
@@ -20,8 +22,8 @@ const build = (overrides: Parameters<typeof grabBotPlanTools>[0] | {} = {}) =>
|
||||
});
|
||||
|
||||
describe("grabBotPlanTools", () => {
|
||||
test("a chat reply can write a plan, change it, end it and finish its steps", () => {
|
||||
expect(names(build())).toEqual(["create_plan", "cancel_plan", "update_plan", "complete_plan_step"]);
|
||||
test("a chat reply can write a plan, change it and end it, but not finish a step", () => {
|
||||
expect(names(build())).toEqual(["create_plan", "cancel_plan", "update_plan"]);
|
||||
});
|
||||
|
||||
test("a run working a step can only change the plan and finish its step", () => {
|
||||
|
||||
@@ -35,6 +35,10 @@ type Params = {
|
||||
* A run that is itself working a plan gets neither `create_plan` (the
|
||||
* conversation already has one open) nor `cancel_plan` (whether the plan
|
||||
* stands is the user's call), so the only thing it can do is work it.
|
||||
*
|
||||
* Only a step's own run can finish a step: a reply that isn't one would
|
||||
* finish it with no card under its report, and the plan would sit active
|
||||
* with nothing to start the next one.
|
||||
*/
|
||||
export default function grabBotPlanTools({ user_id, bot_id, session_id, workspace_id, on_step, approve, onPlan }: Params) {
|
||||
const tools: HarnessTool[] = [];
|
||||
@@ -48,7 +52,8 @@ export default function grabBotPlanTools({ user_id, bot_id, session_id, workspac
|
||||
}
|
||||
|
||||
tools.push(updatePlanTool({ user_id, bot_id, session_id, onPlan }));
|
||||
tools.push(completePlanStepTool({ bot_id, session_id, in_run: approve }));
|
||||
|
||||
if (on_step || approve) tools.push(completePlanStepTool({ bot_id, session_id, in_run: approve }));
|
||||
|
||||
return tools;
|
||||
}
|
||||
@@ -18,6 +18,11 @@ type Params = {
|
||||
* approved plan is).
|
||||
*/
|
||||
plan_mode?: boolean;
|
||||
/**
|
||||
* The plan whose step this run works, when the card ends that step: its
|
||||
* first option continues the plan, anything else pauses it.
|
||||
*/
|
||||
plan_id?: number | null;
|
||||
/**
|
||||
* Whether the run is a task, which stops and reports rather than waits.
|
||||
*/
|
||||
@@ -53,6 +58,7 @@ export default function askUserTool({
|
||||
session_id,
|
||||
workspace_id,
|
||||
plan_mode,
|
||||
plan_id,
|
||||
in_task,
|
||||
onAsk,
|
||||
redact = (text) => text,
|
||||
@@ -90,6 +96,7 @@ export default function askUserTool({
|
||||
session_id,
|
||||
workspace_id,
|
||||
plan_mode: Boolean(plan_mode),
|
||||
plan_id,
|
||||
title: args.title?.trim() ? redact(args.title.trim()) : "",
|
||||
questions: args.questions.map((item) => ({
|
||||
question: redact(item.question),
|
||||
|
||||
@@ -23,6 +23,11 @@ type Params = {
|
||||
computers: BUN_SQLITE_COBBLE_COMPUTERS[];
|
||||
message_id?: number | string;
|
||||
run_kind?: BrowserRunKind;
|
||||
/**
|
||||
* The plan whose step this work is: the run works that step and its
|
||||
* report ends on the card that moves the plan on.
|
||||
*/
|
||||
plan_id?: number | null;
|
||||
work: BotTaskWork;
|
||||
/**
|
||||
* The tool that asked, so a refusal tells the model to call that tool
|
||||
@@ -47,6 +52,7 @@ export default async function queueBotTask({
|
||||
computers,
|
||||
message_id,
|
||||
run_kind,
|
||||
plan_id,
|
||||
work,
|
||||
tool_name,
|
||||
}: Params): Promise<{ job_id: number; ahead: number; ask_id?: number }> {
|
||||
@@ -94,6 +100,7 @@ export default async function queueBotTask({
|
||||
params: {
|
||||
...(work.max_steps ? { max_steps: work.max_steps } : {}),
|
||||
...(run_kind ? { run_kind } : {}),
|
||||
...(plan_id ? { plan_id: Number(plan_id) } : {}),
|
||||
...(ask?.id ? { ask_id: Number(ask.id) } : {}),
|
||||
},
|
||||
});
|
||||
|
||||
@@ -30,6 +30,11 @@ type Params = {
|
||||
* can't queue the work it was only meant to plan.
|
||||
*/
|
||||
plan_mode?: boolean;
|
||||
/**
|
||||
* The plan whose step this reply works: the work it queues carries the
|
||||
* plan, so its report ends on the card that moves the plan on.
|
||||
*/
|
||||
plan_id?: number | null;
|
||||
};
|
||||
|
||||
type Args = {
|
||||
@@ -60,6 +65,7 @@ export default function sendReplyTool({
|
||||
run_kind,
|
||||
onQueue,
|
||||
plan_mode,
|
||||
plan_id,
|
||||
}: Params): HarnessTool<Args> {
|
||||
let queued: { job_id: number; ahead: number; ask_id?: number } | null = null;
|
||||
|
||||
@@ -149,6 +155,7 @@ export default function sendReplyTool({
|
||||
computers,
|
||||
message_id,
|
||||
run_kind,
|
||||
plan_id,
|
||||
tool_name: "send_reply",
|
||||
work: args.work,
|
||||
});
|
||||
|
||||
@@ -25,6 +25,11 @@ type Params = {
|
||||
* hidden session's reply queues never reaches the user's real browsers.
|
||||
*/
|
||||
run_kind?: BrowserRunKind;
|
||||
/**
|
||||
* The plan whose step this work is (a task run that hands its step on):
|
||||
* the child run's report ends on the card that moves the plan on.
|
||||
*/
|
||||
plan_id?: number | null;
|
||||
};
|
||||
|
||||
type Args = {
|
||||
@@ -59,6 +64,7 @@ export default function startTaskTool({
|
||||
computers,
|
||||
message_id,
|
||||
run_kind,
|
||||
plan_id,
|
||||
}: Params): HarnessTool<Args> {
|
||||
const listed = computers
|
||||
.map((computer) => `${computer.id} (${computer.name || computer.kind})`)
|
||||
@@ -97,6 +103,7 @@ export default function startTaskTool({
|
||||
computers,
|
||||
message_id,
|
||||
run_kind,
|
||||
plan_id,
|
||||
tool_name: "start_task",
|
||||
work: {
|
||||
title: args.title,
|
||||
|
||||
@@ -4,6 +4,7 @@ import { WrapUpHandOffToolNames, WrapUpSaveToolNames } from "@/src/harness/text/
|
||||
import { WritingToolNames } from "./writing-tool-names";
|
||||
import { AppCardRefToolNames, WorkStartingTools } from "@/src/utils/reply-claim-problems";
|
||||
import { AppStateTools } from "@/src/utils/reply-app-state-claims";
|
||||
import PlanWorkStartingTools from "@/src/utils/plan-work-starting-tools";
|
||||
import { PlanModeToolNames } from "./bot/plan-mode-tools";
|
||||
|
||||
/**
|
||||
@@ -44,6 +45,7 @@ async function declaredToolNames() {
|
||||
|
||||
const Lists: Record<string, readonly string[]> = {
|
||||
WorkStartingTools,
|
||||
PlanWorkStartingTools,
|
||||
AppCardRefToolNames,
|
||||
AppStateTools,
|
||||
WritingToolNames,
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
import { createContext } from "react";
|
||||
|
||||
/**
|
||||
* The id of the user's newest message in the thread, and the id of the
|
||||
* message being rendered. An ask written in a message (a take-over) is
|
||||
* waiting for them only while no user message follows it, so handing the
|
||||
* computer back - a chat message - ends the wait. Both are null outside a
|
||||
* thread, where neither is known and nothing is said to be waiting.
|
||||
*/
|
||||
export const LastUserMessageContext = createContext<number | null>(null);
|
||||
export const MessageIdContext = createContext<number | null>(null);
|
||||
@@ -6,14 +6,14 @@ import type { BotPlanView } from "@/src/types";
|
||||
type Params = {
|
||||
plan_id: number;
|
||||
/**
|
||||
* Approve it, pick it back up, pause it, or end it.
|
||||
* Approve it, pick it back up, start its next step, pause it, or end it.
|
||||
*/
|
||||
status: Extract<BotPlanState, "active" | "paused" | "cancelled">;
|
||||
};
|
||||
|
||||
/**
|
||||
* Moves a plan from its card. Approving it (or picking it back up) wakes
|
||||
* the bot for the step it stands on, so the plan carries on by itself.
|
||||
* Moves a plan from its card. Approving it, picking it back up, or Continue
|
||||
* wakes the bot for the step it stands on.
|
||||
*/
|
||||
export default async function setBotPlanState({ plan_id, status }: Params) {
|
||||
return await fetchApi<Params, APIResponseObject<BotPlanView>>(`/api/admin/bot-plans/set-plan-status`, {
|
||||
|
||||
@@ -21,8 +21,8 @@ type Params = {
|
||||
/**
|
||||
* A reply step pushed for the open session (`server:bot-job-update` with no
|
||||
* task) means a reply is due here, even when the bot has the last word: the
|
||||
* app queues a plan's next step itself, so nothing in the thread's last
|
||||
* message says it is coming.
|
||||
* app queues a plan's step itself on approval and on the card under the last
|
||||
* one, so nothing in the thread's last message says it is coming.
|
||||
*/
|
||||
export default function useOpenReplyJobs({ bot_id, session_id, on_open_jobs }: Params) {
|
||||
useServerEvent({
|
||||
|
||||
@@ -6,6 +6,7 @@ import Stack from "@moduletrace/twui/layout/Stack";
|
||||
import type { BotMessageWithAttachments } from "@/src/types";
|
||||
import linkComputerRefs from "@/src/utils/link-computer-refs";
|
||||
import { BotMessageActionsContext } from "../(data)/message-actions-context";
|
||||
import { MessageIdContext } from "../(data)/message-answer-context";
|
||||
import { MessageMarkdownComponents } from "../(data)/message-markdown-components";
|
||||
import { QuotableAttribute } from "../(hooks)/use-message-selection";
|
||||
import CarriedOverChip from "./carried-over-chip";
|
||||
@@ -79,12 +80,14 @@ function BotMessageLine({ message, bot_name, at, rerun }: Props) {
|
||||
{...{ [QuotableAttribute]: "" }}
|
||||
className="w-full gap-2.5! items-start wrap-anywhere [&>*]:max-w-full"
|
||||
>
|
||||
<Markdown
|
||||
remarkPlugins={RemarkPlugins}
|
||||
components={MessageMarkdownComponents}
|
||||
>
|
||||
{linkComputerRefs({ text: message.text || "" })}
|
||||
</Markdown>
|
||||
<MessageIdContext.Provider value={Number(message.id) || null}>
|
||||
<Markdown
|
||||
remarkPlugins={RemarkPlugins}
|
||||
components={MessageMarkdownComponents}
|
||||
>
|
||||
{linkComputerRefs({ text: message.text || "" })}
|
||||
</Markdown>
|
||||
</MessageIdContext.Provider>
|
||||
</Stack>
|
||||
<MessageImages message={message} />
|
||||
{message.plan_mode ? (
|
||||
|
||||
@@ -121,6 +121,19 @@ export default function BotPlanCard({ plan_id }: Props) {
|
||||
</Button>
|
||||
) : null}
|
||||
|
||||
{view.status == "active" ? (
|
||||
<Button
|
||||
title={`Start step ${(view.current_step ?? 0) + 1}`}
|
||||
type="button"
|
||||
size="smaller"
|
||||
loading={busy == "active"}
|
||||
disabled={Boolean(busy)}
|
||||
onClick={() => void move({ status: "active" })}
|
||||
>
|
||||
Continue
|
||||
</Button>
|
||||
) : null}
|
||||
|
||||
{view.status == "active" ? (
|
||||
<Button
|
||||
title="Pause the plan"
|
||||
|
||||
@@ -162,7 +162,10 @@ export default function Composer({
|
||||
*/
|
||||
const temp_id = useRef(0);
|
||||
const latest_text = useRef(text);
|
||||
const send_lock = useRef(false);
|
||||
/**
|
||||
* A send still on its way: no second one starts until it answers.
|
||||
*/
|
||||
const sending = useRef(false);
|
||||
|
||||
latest_text.current = text;
|
||||
|
||||
@@ -303,99 +306,105 @@ export default function Composer({
|
||||
* response swaps the bubble for the saved message, or takes it back.
|
||||
*/
|
||||
async function send() {
|
||||
if (!can_send || !bot.id || send_lock.current) return;
|
||||
|
||||
/** Only for this tick: the cleared editor lands by the next one. */
|
||||
send_lock.current = true;
|
||||
setTimeout(() => {
|
||||
send_lock.current = false;
|
||||
}, 0);
|
||||
|
||||
setError(undefined);
|
||||
if (!can_send || !bot.id || sending.current) return;
|
||||
|
||||
/**
|
||||
* A message over the limit stays in the input, untouched, with the
|
||||
* reason under it, instead of flashing into the thread and back.
|
||||
* Held until this send comes back: a second click while the first is
|
||||
* still on its way (a double tap, Enter twice, a phone that fires
|
||||
* both) queued a second message with its own id, and the two raced
|
||||
* the conversation's rollover against each other.
|
||||
*/
|
||||
const limit = max_chars || AppData.BotMessageMaxChars;
|
||||
const length = text.trim().length;
|
||||
sending.current = true;
|
||||
|
||||
if (length > limit) {
|
||||
setError(messageTooLongMessage({ length, max_chars: limit }));
|
||||
return;
|
||||
}
|
||||
try {
|
||||
setError(undefined);
|
||||
|
||||
temp_id.current -= 1;
|
||||
/**
|
||||
* A message over the limit stays in the input, untouched, with the
|
||||
* reason under it, instead of flashing into the thread and back.
|
||||
*/
|
||||
const limit = max_chars || AppData.BotMessageMaxChars;
|
||||
const length = text.trim().length;
|
||||
|
||||
const client_id = temp_id.current;
|
||||
/**
|
||||
* The text goes as the server will store it, trimmed: a message
|
||||
* with a trailing newline was saved without it, and the bubble
|
||||
* waiting for it never matched the saved one.
|
||||
*/
|
||||
const text_sent = text.trim();
|
||||
/**
|
||||
* The server's own handle for this send, so a send whose answer
|
||||
* never arrived is recognised as the message already stored. Not
|
||||
* the thread's temp id: that restarts after a reload and would
|
||||
* match an older message of the same conversation.
|
||||
*/
|
||||
const request_id = crypto.randomUUID();
|
||||
const media_ids = files.media_ids;
|
||||
const attachments = files.pending.flatMap((item) =>
|
||||
item.status == "ready" && item.attachment ? [item.attachment] : [],
|
||||
);
|
||||
if (length > limit) {
|
||||
setError(messageTooLongMessage({ length, max_chars: limit }));
|
||||
return;
|
||||
}
|
||||
|
||||
onSendStart({
|
||||
message: {
|
||||
id: client_id,
|
||||
temp_id.current -= 1;
|
||||
|
||||
const client_id = temp_id.current;
|
||||
/**
|
||||
* The text goes as the server will store it, trimmed: a message
|
||||
* with a trailing newline was saved without it, and the bubble
|
||||
* waiting for it never matched the saved one.
|
||||
*/
|
||||
const text_sent = text.trim();
|
||||
/**
|
||||
* The server's own handle for this send, so a send whose answer
|
||||
* never arrived is recognised as the message already stored. Not
|
||||
* the thread's temp id: that restarts after a reload and would
|
||||
* match an older message of the same conversation.
|
||||
*/
|
||||
const request_id = crypto.randomUUID();
|
||||
const media_ids = files.media_ids;
|
||||
const attachments = files.pending.flatMap((item) =>
|
||||
item.status == "ready" && item.attachment ? [item.attachment] : [],
|
||||
);
|
||||
|
||||
onSendStart({
|
||||
message: {
|
||||
id: client_id,
|
||||
bot_id: bot.id,
|
||||
workspace_id: workspace_id || undefined,
|
||||
author: "user",
|
||||
text: text_sent,
|
||||
created_at: Date.now(),
|
||||
updated_at: Date.now(),
|
||||
attachments,
|
||||
reply_to: reply_to
|
||||
? {
|
||||
id: Number(reply_to.id),
|
||||
author: reply_to.author == "bot" ? "bot" : "user",
|
||||
text: reply_to.text || "",
|
||||
}
|
||||
: null,
|
||||
},
|
||||
});
|
||||
|
||||
/**
|
||||
* The message takes the quote with it, so a new one typed while it
|
||||
* is on its way doesn't inherit it.
|
||||
*/
|
||||
onCancelReply?.();
|
||||
|
||||
setText("");
|
||||
history.reset();
|
||||
input.clear();
|
||||
files.clear();
|
||||
|
||||
const res = await sendBotMessage({
|
||||
bot_id: bot.id,
|
||||
workspace_id: workspace_id || undefined,
|
||||
author: "user",
|
||||
workspace_id,
|
||||
text: text_sent,
|
||||
created_at: Date.now(),
|
||||
updated_at: Date.now(),
|
||||
attachments,
|
||||
reply_to: reply_to
|
||||
? {
|
||||
id: Number(reply_to.id),
|
||||
author: reply_to.author == "bot" ? "bot" : "user",
|
||||
text: reply_to.text || "",
|
||||
}
|
||||
: null,
|
||||
},
|
||||
});
|
||||
media_ids,
|
||||
reply_to_message_id: reply_to?.id || null,
|
||||
session_id: session_id || null,
|
||||
client_id: request_id,
|
||||
plan_mode,
|
||||
});
|
||||
|
||||
/**
|
||||
* The message takes the quote with it, so a new one typed while it
|
||||
* is on its way doesn't inherit it.
|
||||
*/
|
||||
onCancelReply?.();
|
||||
if (!res.success || !res.singleRes) {
|
||||
setError(res.msg || "Message not sent");
|
||||
restore({ lost_text: text_sent, attachments });
|
||||
onSendFailed({ temp_id: client_id });
|
||||
return;
|
||||
}
|
||||
|
||||
setText("");
|
||||
history.reset();
|
||||
input.clear();
|
||||
files.clear();
|
||||
|
||||
const res = await sendBotMessage({
|
||||
bot_id: bot.id,
|
||||
workspace_id,
|
||||
text: text_sent,
|
||||
media_ids,
|
||||
reply_to_message_id: reply_to?.id || null,
|
||||
session_id: session_id || null,
|
||||
client_id: request_id,
|
||||
plan_mode,
|
||||
});
|
||||
|
||||
if (!res.success || !res.singleRes) {
|
||||
setError(res.msg || "Message not sent");
|
||||
restore({ lost_text: text_sent, attachments });
|
||||
onSendFailed({ temp_id: client_id });
|
||||
return;
|
||||
onSent({ message: res.singleRes });
|
||||
} finally {
|
||||
sending.current = false;
|
||||
}
|
||||
|
||||
onSent({ message: res.singleRes });
|
||||
}
|
||||
|
||||
send_ref.current = send;
|
||||
|
||||
@@ -7,9 +7,9 @@ const TextClassName = "w-full text-sm leading-5 text-ink";
|
||||
|
||||
/**
|
||||
* A paragraph of a bot message. A card ref (a plan, questions, a proposal,
|
||||
* a hook proposal, a secret request) is a block, which React refuses
|
||||
* inside a `p`, so the paragraph is split around it: the text stays in
|
||||
* paragraphs and each card gets a line of its own, still in the message's
|
||||
* a hook proposal, a secret request, a take-over) is a block, which React
|
||||
* refuses inside a `p`, so the paragraph is split around it: the text stays
|
||||
* in paragraphs and each card gets a line of its own, still in the message's
|
||||
* reading order.
|
||||
*/
|
||||
export default function MarkdownParagraph({ children }: { children?: ReactNode }) {
|
||||
|
||||
@@ -12,6 +12,7 @@ import usePullToRefresh from "../(hooks)/use-pull-to-refresh";
|
||||
import useSessionGallery from "../(hooks)/use-session-gallery";
|
||||
import useThreadScroll from "../(hooks)/use-thread-scroll";
|
||||
import { SessionGalleryContext } from "../(data)/session-gallery-context";
|
||||
import { LastUserMessageContext } from "../(data)/message-answer-context";
|
||||
import groupMessages from "../(utils)/group-messages";
|
||||
import threadMessages from "../(utils)/thread-messages";
|
||||
import BotThinkingRow from "./bot-thinking-row";
|
||||
@@ -160,6 +161,20 @@ export default function MessageThread({
|
||||
return Number(newest.id) || null;
|
||||
}, [shown]);
|
||||
const session_gallery = useSessionGallery({ messages: shown });
|
||||
/**
|
||||
* The user's newest message answers every ask above it: a take-over
|
||||
* card stops waiting for them once they've written, which is how they
|
||||
* hand the computer back.
|
||||
*/
|
||||
const last_user_id = useMemo(() => {
|
||||
for (let index = shown.length - 1; index >= 0; index--) {
|
||||
const message = shown[index];
|
||||
|
||||
if (message?.author == "user") return Number(message.id) || null;
|
||||
}
|
||||
|
||||
return null;
|
||||
}, [shown]);
|
||||
/**
|
||||
* The user's own message the thread ends on, with nothing on its way: a
|
||||
* stopped run, or one that ended without a word, leaves it waiting
|
||||
@@ -210,14 +225,16 @@ export default function MessageThread({
|
||||
/>
|
||||
) : null}
|
||||
<SessionGalleryContext.Provider value={session_gallery}>
|
||||
{groups.map((group) => (
|
||||
<MessageGroupBlock
|
||||
key={group.key}
|
||||
bot={bot}
|
||||
group={group}
|
||||
last_bot_id={last_bot_id}
|
||||
/>
|
||||
))}
|
||||
<LastUserMessageContext.Provider value={last_user_id}>
|
||||
{groups.map((group) => (
|
||||
<MessageGroupBlock
|
||||
key={group.key}
|
||||
bot={bot}
|
||||
group={group}
|
||||
last_bot_id={last_bot_id}
|
||||
/>
|
||||
))}
|
||||
</LastUserMessageContext.Provider>
|
||||
</SessionGalleryContext.Provider>
|
||||
{notice}
|
||||
<BotThinkingRow
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { renderToString } from "react-dom/server";
|
||||
import type { BUN_SQLITE_COBBLE_COMPUTERS } from "@/db/types/db";
|
||||
import { BotComputersContext } from "../(data)/bot-computers-context";
|
||||
import { LastUserMessageContext, MessageIdContext } from "../(data)/message-answer-context";
|
||||
import TakeOverCard from "./take-over-card";
|
||||
|
||||
type RenderProps = {
|
||||
message_id: number | null;
|
||||
last_user_id: number | null;
|
||||
};
|
||||
|
||||
const computers = {
|
||||
computers: [{ id: 1, name: "Main computer" } as BUN_SQLITE_COBBLE_COMPUTERS],
|
||||
switchComputer: async () => {},
|
||||
openComputer: () => {},
|
||||
closeComputer: () => {},
|
||||
};
|
||||
|
||||
function render({ message_id, last_user_id }: RenderProps) {
|
||||
return renderToString(
|
||||
<BotComputersContext.Provider value={computers}>
|
||||
<LastUserMessageContext.Provider value={last_user_id}>
|
||||
<MessageIdContext.Provider value={message_id}>
|
||||
<TakeOverCard computer_id={1} mode="browser" />
|
||||
</MessageIdContext.Provider>
|
||||
</LastUserMessageContext.Provider>
|
||||
</BotComputersContext.Provider>,
|
||||
);
|
||||
}
|
||||
|
||||
describe("TakeOverCard", () => {
|
||||
test("waits while no user message follows the ask", () => {
|
||||
const html = render({ message_id: 10, last_user_id: 5 });
|
||||
|
||||
expect(html).toContain("Waiting for you");
|
||||
});
|
||||
|
||||
test("stops waiting once the user has written after it", () => {
|
||||
const html = render({ message_id: 10, last_user_id: 12 });
|
||||
|
||||
expect(html).not.toContain("Waiting for you");
|
||||
expect(html).toContain("Browser");
|
||||
});
|
||||
|
||||
test("claims nothing outside a thread", () => {
|
||||
expect(render({ message_id: null, last_user_id: null })).not.toContain("Waiting for you");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,82 @@
|
||||
import { useContext } from "react";
|
||||
import Button from "@moduletrace/twui/layout/Button";
|
||||
import Span from "@moduletrace/twui/layout/Span";
|
||||
import { Computer, Hand, Monitor, MonitorCog, MonitorDot } from "lucide-react";
|
||||
import {
|
||||
ComputerViewModes,
|
||||
type ComputerViewMode,
|
||||
} from "@/src/dict/computer-dict";
|
||||
import { BotComputersContext } from "../(data)/bot-computers-context";
|
||||
import {
|
||||
LastUserMessageContext,
|
||||
MessageIdContext,
|
||||
} from "../(data)/message-answer-context";
|
||||
import RefCardShell from "./ref-card-shell";
|
||||
import Center from "@moduletrace/twui/layout/Center";
|
||||
import Stack from "@moduletrace/twui/layout/Stack";
|
||||
import Divider from "@moduletrace/twui/layout/Divider";
|
||||
|
||||
type Props = {
|
||||
computer_id: number;
|
||||
mode: ComputerViewMode;
|
||||
};
|
||||
|
||||
/**
|
||||
* The bot asked the user to take over a computer (`takeOverRef`): the card
|
||||
* that opens it in the viewer, in the mode the bot asked for. It's a block
|
||||
* of its own in the message (`isCardRefHref`), so a request buried in a long
|
||||
* answer still stands out. It waits for them only while no user message
|
||||
* follows the one it was written in, so handing the computer back ends it.
|
||||
* A computer the bot can't use (any more) is shown by name only.
|
||||
*/
|
||||
export default function TakeOverCard({ computer_id, mode }: Props) {
|
||||
const { computers, openComputer } = useContext(BotComputersContext);
|
||||
const last_user_id = useContext(LastUserMessageContext);
|
||||
const message_id = useContext(MessageIdContext);
|
||||
|
||||
const computer = computers.find((c) => c.id == computer_id);
|
||||
const name = computer?.name || `computer ${computer_id}`;
|
||||
const mode_title =
|
||||
ComputerViewModes.find((m) => m.value == mode)?.title || mode;
|
||||
const waiting = Boolean(
|
||||
message_id && last_user_id && message_id > last_user_id,
|
||||
);
|
||||
|
||||
if (!computer) {
|
||||
return <Span className="font-bold">{name}</Span>;
|
||||
}
|
||||
|
||||
return (
|
||||
<Stack
|
||||
className="cursor-pointer w-full hover:opacity-70"
|
||||
onClick={() => openComputer({ computer_id, mode, take_over: true })}
|
||||
>
|
||||
<RefCardShell
|
||||
icon={<Hand size={14} aria-hidden />}
|
||||
title={`Take over ${name}`}
|
||||
status={waiting ? "Waiting for you" : mode_title}
|
||||
tone={waiting ? "warning" : "gray"}
|
||||
description={
|
||||
waiting
|
||||
? `The bot is waiting for you to do this on its ${mode_title.toLowerCase()} screen. Do what's needed, then hand it back from the viewer and the bot carries on.`
|
||||
: `What the bot needed you to do on its ${mode_title.toLowerCase()} screen.`
|
||||
}
|
||||
>
|
||||
<Center className="p-10">
|
||||
<Monitor opacity={0.2} size={60} strokeWidth={1} />
|
||||
</Center>
|
||||
<Divider />
|
||||
<Button
|
||||
type="button"
|
||||
size="small"
|
||||
title={`Open ${name} (${mode_title}) and take over`}
|
||||
beforeIcon={<Hand size={14} aria-hidden />}
|
||||
className="w-full"
|
||||
variant="ghost"
|
||||
>
|
||||
{`Open ${name}`}
|
||||
</Button>
|
||||
</RefCardShell>
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
@@ -1,47 +0,0 @@
|
||||
import { useContext } from "react";
|
||||
import { twMerge } from "tailwind-merge";
|
||||
import Button from "@moduletrace/twui/layout/Button";
|
||||
import Span from "@moduletrace/twui/layout/Span";
|
||||
import { Hand } from "lucide-react";
|
||||
import { ComputerViewModes, type ComputerViewMode } from "@/src/dict/computer-dict";
|
||||
import { BotComputersContext } from "../(data)/bot-computers-context";
|
||||
|
||||
type Props = {
|
||||
computer_id: number;
|
||||
mode: ComputerViewMode;
|
||||
};
|
||||
|
||||
/**
|
||||
* The bot asked the user to take over a computer (`takeOverRef`): a
|
||||
* button that opens it in the viewer, in the mode the bot asked for. A
|
||||
* computer the bot can't use (any more) is shown by name only.
|
||||
*/
|
||||
export default function TakeOverChip({ computer_id, mode }: Props) {
|
||||
const { computers, openComputer } = useContext(BotComputersContext);
|
||||
|
||||
const computer = computers.find((c) => c.id == computer_id);
|
||||
const name = computer?.name || `computer ${computer_id}`;
|
||||
const mode_title = ComputerViewModes.find((m) => m.value == mode)?.title || mode;
|
||||
|
||||
if (!computer) {
|
||||
return <Span className="font-bold">{name}</Span>;
|
||||
}
|
||||
|
||||
return (
|
||||
<Button
|
||||
type="button"
|
||||
variant="outlined"
|
||||
color="gray"
|
||||
size="smaller"
|
||||
title={`Open ${name} (${mode_title}) and take over`}
|
||||
onClick={() => openComputer({ computer_id, mode, take_over: true })}
|
||||
className={twMerge(
|
||||
"inline-flex h-6 max-w-full gap-1.5! flex-nowrap align-middle px-2! text-[13px] font-bold text-ink whitespace-nowrap",
|
||||
"[&_.twui-button-content-wrapper]:min-w-0",
|
||||
)}
|
||||
>
|
||||
<Hand size={14} aria-hidden className="shrink-0" />
|
||||
<Span className="min-w-0 truncate">{`Take over ${name} · ${mode_title}`}</Span>
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
@@ -6,6 +6,10 @@ describe("isCardRefHref", () => {
|
||||
expect(isCardRefHref({ href: "#connect-4" })).toBe(true);
|
||||
});
|
||||
|
||||
test("a take-over ref is a card", () => {
|
||||
expect(isCardRefHref({ href: "#take-over-3-browser" })).toBe(true);
|
||||
});
|
||||
|
||||
test("a file ref stays on the line", () => {
|
||||
expect(isCardRefHref({ href: "#file-4" })).toBe(false);
|
||||
});
|
||||
|
||||
@@ -1,13 +1,19 @@
|
||||
import { ConnectRefHrefPrefix, HookProposalRefHrefPrefix, ProposalRefHrefPrefix, SecretRequestRefHrefPrefix } from "@/src/utils/link-computer-refs";
|
||||
import {
|
||||
ConnectRefHrefPrefix,
|
||||
HookProposalRefHrefPrefix,
|
||||
ProposalRefHrefPrefix,
|
||||
SecretRequestRefHrefPrefix,
|
||||
TakeOverRefHrefPrefix,
|
||||
} from "@/src/utils/link-computer-refs";
|
||||
import { botPlanRefId } from "@/src/utils/bot-plan-ref";
|
||||
import { botQuestionRefId } from "@/src/utils/bot-question-ref";
|
||||
|
||||
/**
|
||||
* Whether a ref link stands for a card shown in full under the message (a
|
||||
* plan, questions, a proposal, a hook proposal, a secret request) rather
|
||||
* than a chip on the line. Those cards are blocks, so the message's
|
||||
* paragraph has to lift them out of itself (React refuses a block inside a
|
||||
* `p`).
|
||||
* plan, questions, a proposal, a hook proposal, a secret request, a
|
||||
* take-over) rather than a chip on the line. Those cards are blocks, so the
|
||||
* message's paragraph has to lift them out of itself (React refuses a block
|
||||
* inside a `p`).
|
||||
*/
|
||||
export function isCardRefHref({ href }: { href?: string }): boolean {
|
||||
if (!href) return false;
|
||||
@@ -18,6 +24,7 @@ export function isCardRefHref({ href }: { href?: string }): boolean {
|
||||
href.startsWith(ProposalRefHrefPrefix) ||
|
||||
href.startsWith(HookProposalRefHrefPrefix) ||
|
||||
href.startsWith(SecretRequestRefHrefPrefix) ||
|
||||
href.startsWith(ConnectRefHrefPrefix),
|
||||
href.startsWith(ConnectRefHrefPrefix) ||
|
||||
href.startsWith(TakeOverRefHrefPrefix),
|
||||
);
|
||||
}
|
||||
@@ -6,10 +6,9 @@ type Params = {
|
||||
|
||||
/**
|
||||
* Whether this plan change means a reply is on its way in its conversation.
|
||||
* An active plan is one the app advances by itself: approving it, picking it
|
||||
* back up or finishing a step queues the next step with no user message
|
||||
* before it, so the thread must show the thinking row at once instead of
|
||||
* waiting for the run's first step push.
|
||||
* Approving an active plan or picking it back up queues its step with no
|
||||
* user message before it, so the thread must show the thinking row at once
|
||||
* instead of waiting for the run's first step push.
|
||||
*/
|
||||
export default function planMarksReplyDue({ plan }: Params) {
|
||||
return plan?.status == "active";
|
||||
|
||||
@@ -34,14 +34,14 @@ import ProposalRefCard from "../(partials)/proposal-ref-card";
|
||||
import SecretRefChip from "../(partials)/secret-ref-chip";
|
||||
import SecretRequestRefCard from "../(partials)/secret-request-ref-card";
|
||||
import SettingRefChip from "../(partials)/setting-ref-chip";
|
||||
import TakeOverChip from "../(partials)/take-over-chip";
|
||||
import TakeOverCard from "../(partials)/take-over-card";
|
||||
import TaskRefChip from "../(partials)/task-ref-chip";
|
||||
import AskRefChip from "../(partials)/ask-ref-chip";
|
||||
import WorkspaceRefChip from "../(partials)/workspace-ref-chip";
|
||||
|
||||
/**
|
||||
* The chip a ref link in a bot message stands for (`linkComputerRefs`): a
|
||||
* computer its switch button, a take-over request a button that opens the
|
||||
* computer its switch button, a take-over request the card that opens the
|
||||
* computer, a bot or workspace a link to it, a file a chip that previews
|
||||
* it, a folder a chip that opens it in the files browser, a proposal a chip
|
||||
* that opens the confirm card, a secret a masked chip, a secret request or
|
||||
@@ -63,7 +63,7 @@ export default function refChipForHref({ href }: { href?: string }): ReactNode |
|
||||
|
||||
if (computer_id) {
|
||||
return (
|
||||
<TakeOverChip
|
||||
<TakeOverCard
|
||||
computer_id={computer_id}
|
||||
mode={(known ? mode : ComputerViewModes[0].value) as ComputerViewMode}
|
||||
/>
|
||||
|
||||
@@ -0,0 +1,133 @@
|
||||
import { useState, type Dispatch, type SetStateAction } from "react";
|
||||
import Modal from "@moduletrace/twui/elements/Modal";
|
||||
import SearchSelect from "@moduletrace/twui/form/SearchSelect";
|
||||
import Button from "@moduletrace/twui/layout/Button";
|
||||
import H2 from "@moduletrace/twui/layout/H2";
|
||||
import Row from "@moduletrace/twui/layout/Row";
|
||||
import Span from "@moduletrace/twui/layout/Span";
|
||||
import Stack from "@moduletrace/twui/layout/Stack";
|
||||
import { Plus } from "lucide-react";
|
||||
import type { HarnessModelOption, HarnessProviderChoice } from "@/src/types";
|
||||
import harnessFallbackModelOptions from "../(utils)/harness-fallback-model-options";
|
||||
import HarnessProviderSelect from "./harness-provider-select";
|
||||
|
||||
type Props = {
|
||||
id: string;
|
||||
providers: HarnessProviderChoice[];
|
||||
models: HarnessModelOption[];
|
||||
/**
|
||||
* The pick and the backups already saved.
|
||||
*/
|
||||
taken: number[];
|
||||
/**
|
||||
* The list is full.
|
||||
*/
|
||||
disabled: boolean;
|
||||
onAdd: (model_id: number) => void;
|
||||
};
|
||||
|
||||
/**
|
||||
* "Add a backup": a provider, then one of its models, added to the list
|
||||
* when the button is pressed.
|
||||
*/
|
||||
export default function HarnessFallbackModelModal({ id, providers, models, taken, disabled, onAdd }: Props) {
|
||||
const [open, set_open] = useState(false);
|
||||
const [provider_id, set_provider_id] = useState<number | null>(null);
|
||||
const [model_id, set_model_id] = useState<number | null>(null);
|
||||
|
||||
const offered = provider_id ? models.filter((model) => model.provider_id == provider_id) : models;
|
||||
|
||||
const close = () => {
|
||||
set_open(false);
|
||||
set_provider_id(null);
|
||||
set_model_id(null);
|
||||
};
|
||||
|
||||
/**
|
||||
* Anything but a close (the backdrop, the escape key, a click on the
|
||||
* target) goes through here, so a cancelled pick is never left behind.
|
||||
*/
|
||||
const setOpen: Dispatch<SetStateAction<boolean>> = (next) => {
|
||||
const value = typeof next == "function" ? next(open) : next;
|
||||
|
||||
if (value) set_open(true);
|
||||
else close();
|
||||
};
|
||||
|
||||
return (
|
||||
<Modal
|
||||
target={
|
||||
<Button
|
||||
title={disabled ? "The backup list is full" : "Add a backup model"}
|
||||
type="button"
|
||||
variant="outlined"
|
||||
color="gray"
|
||||
size="small"
|
||||
disabled={disabled}
|
||||
onClick={() => set_open(true)}
|
||||
>
|
||||
<Plus size={16} aria-hidden />
|
||||
Add backup
|
||||
</Button>
|
||||
}
|
||||
targetWrapperProps={{ className: "self-end" }}
|
||||
open={open}
|
||||
setOpen={setOpen}
|
||||
className="max-w-lg bg-paper p-6"
|
||||
>
|
||||
<Stack className="w-full gap-1! items-stretch pb-2">
|
||||
<H2 className="text-lg! leading-6! tracking-normal! font-bold text-ink">Add a backup model</H2>
|
||||
<Span className="text-[13px] leading-[18px] text-ink-secondary">
|
||||
Pick its provider and model. It is tried after the backups already on the list.
|
||||
</Span>
|
||||
</Stack>
|
||||
<Stack className="w-full gap-4! items-stretch">
|
||||
<HarnessProviderSelect
|
||||
id={`${id}-backup-provider`}
|
||||
providers={providers}
|
||||
provider_id={provider_id}
|
||||
onChange={(next) => {
|
||||
set_provider_id(next.provider_id);
|
||||
set_model_id(null);
|
||||
}}
|
||||
/>
|
||||
<SearchSelect
|
||||
key={`${provider_id || "any"}-${model_id ?? "none"}`}
|
||||
id={`${id}-backup-model`}
|
||||
title="Model"
|
||||
label="Model"
|
||||
showLabel
|
||||
placeholder="Search models"
|
||||
options={harnessFallbackModelOptions({
|
||||
models: offered,
|
||||
model_id: model_id ?? undefined,
|
||||
taken,
|
||||
})}
|
||||
defaultValues={model_id ? [String(model_id)] : []}
|
||||
changeHandler={(value) => {
|
||||
const picked = Array.isArray(value) ? value[0] : value;
|
||||
set_model_id(picked ? Number(picked) : null);
|
||||
}}
|
||||
/>
|
||||
</Stack>
|
||||
<Row className="w-full gap-2! items-center justify-end pt-4">
|
||||
<Button title="Cancel" type="button" variant="ghost" color="gray" size="small" onClick={close}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
title="Add backup"
|
||||
type="button"
|
||||
size="small"
|
||||
disabled={!model_id}
|
||||
onClick={() => {
|
||||
if (!model_id) return;
|
||||
onAdd(model_id);
|
||||
close();
|
||||
}}
|
||||
>
|
||||
Add backup
|
||||
</Button>
|
||||
</Row>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
import Row from "@moduletrace/twui/layout/Row";
|
||||
import Span from "@moduletrace/twui/layout/Span";
|
||||
import Stack from "@moduletrace/twui/layout/Stack";
|
||||
import { X } from "lucide-react";
|
||||
import RowIconButton from "@/src/components/general/row-icon-button";
|
||||
|
||||
type Props = {
|
||||
name: string;
|
||||
provider_name: string;
|
||||
onRemove: () => void;
|
||||
};
|
||||
|
||||
/**
|
||||
* One saved backup: the model and its provider, with the way to take it
|
||||
* off the list.
|
||||
*/
|
||||
export default function HarnessFallbackModelRow({ name, provider_name, onRemove }: Props) {
|
||||
return (
|
||||
<Row className="w-full gap-3! items-center justify-between rounded-default border border-solid border-hairline px-3 py-2">
|
||||
<Stack className="gap-0! min-w-0">
|
||||
<Span className="truncate text-sm text-ink">{name}</Span>
|
||||
<Span className="truncate text-xs text-ink-secondary">{provider_name}</Span>
|
||||
</Stack>
|
||||
<RowIconButton icon={X} title={`Remove ${name}`} onClick={onRemove} />
|
||||
</Row>
|
||||
);
|
||||
}
|
||||
@@ -1,37 +0,0 @@
|
||||
import SearchSelect from "@moduletrace/twui/form/SearchSelect";
|
||||
import type { HarnessModelOption } from "@/src/types";
|
||||
import harnessFallbackModelOptions, { NoFallbackValue } from "../(utils)/harness-fallback-model-options";
|
||||
|
||||
type Props = {
|
||||
id: string;
|
||||
/**
|
||||
* 0-based place in the fallback order.
|
||||
*/
|
||||
index: number;
|
||||
models: HarnessModelOption[];
|
||||
model_id?: number;
|
||||
taken: number[];
|
||||
onChange: (params: { index: number; model_id: number | null }) => void;
|
||||
};
|
||||
|
||||
/**
|
||||
* One fallback model slot: a searchable pick from every provider, or none.
|
||||
*/
|
||||
export default function HarnessFallbackModelSelect({ id, index, models, model_id, taken, onChange }: Props) {
|
||||
return (
|
||||
<SearchSelect
|
||||
id={`${id}-${index}`}
|
||||
title={`Fallback model ${index + 1}`}
|
||||
label={`Fallback model ${index + 1}`}
|
||||
showLabel
|
||||
placeholder="Search models"
|
||||
options={harnessFallbackModelOptions({ models, model_id, taken })}
|
||||
defaultValues={[model_id ? String(model_id) : NoFallbackValue]}
|
||||
changeHandler={(value) => {
|
||||
const picked = Array.isArray(value) ? value[0] : value;
|
||||
|
||||
onChange({ index, model_id: !picked || picked == NoFallbackValue ? null : Number(picked) });
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -1,17 +1,23 @@
|
||||
import Row from "@moduletrace/twui/layout/Row";
|
||||
import Span from "@moduletrace/twui/layout/Span";
|
||||
import Stack from "@moduletrace/twui/layout/Stack";
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
import type { HarnessModelOption } from "@/src/types";
|
||||
import HarnessFallbackModelSelect from "./harness-fallback-model-select";
|
||||
import type { HarnessModelOption, HarnessProviderChoice } from "@/src/types";
|
||||
import HarnessFallbackModelModal from "./harness-fallback-model-modal";
|
||||
import HarnessFallbackModelRow from "./harness-fallback-model-row";
|
||||
|
||||
type Props = {
|
||||
id: string;
|
||||
/**
|
||||
* The providers that have a model for this harness.
|
||||
*/
|
||||
providers: HarnessProviderChoice[];
|
||||
/**
|
||||
* Every model that can do the job, on any provider.
|
||||
*/
|
||||
models: HarnessModelOption[];
|
||||
/**
|
||||
* The pick, which can't also be a fallback.
|
||||
* The pick, which can't also be a backup.
|
||||
*/
|
||||
model_id: number;
|
||||
fallback_model_ids: number[];
|
||||
@@ -20,37 +26,43 @@ type Props = {
|
||||
|
||||
/**
|
||||
* The models tried, in order, when the pick fails or rests, before the
|
||||
* automatic free picks: the filled slots plus one empty one, up to
|
||||
* `AppData.HarnessTextFallbackModelsMax`. Clearing a slot closes the gap.
|
||||
* automatic free picks: the saved backups, and "Add backup" up to
|
||||
* `AppData.HarnessTextFallbackModelsMax`.
|
||||
*/
|
||||
export default function HarnessFallbackModels({ id, models, model_id, fallback_model_ids, onChange }: Props) {
|
||||
export default function HarnessFallbackModels({ id, providers, models, model_id, fallback_model_ids, onChange }: Props) {
|
||||
const ids = fallback_model_ids.filter((fallback_id) => fallback_id != model_id);
|
||||
const slots: (number | undefined)[] =
|
||||
ids.length < AppData.HarnessTextFallbackModelsMax ? [...ids, undefined] : ids;
|
||||
const backups = ids.map((backup_id) => {
|
||||
const model = models.find((option) => option.id == backup_id);
|
||||
|
||||
const change = ({ index, model_id: picked }: { index: number; model_id: number | null }) => {
|
||||
const next: (number | null)[] = [...ids];
|
||||
|
||||
next[index] = picked;
|
||||
onChange(next.filter((value): value is number => Boolean(value)));
|
||||
};
|
||||
return {
|
||||
id: backup_id,
|
||||
name: model?.name || `Model #${backup_id}`,
|
||||
provider_name: model?.provider_name || "No longer offered",
|
||||
};
|
||||
});
|
||||
const full = ids.length >= AppData.HarnessTextFallbackModelsMax;
|
||||
|
||||
return (
|
||||
<Stack className="w-full gap-2! items-stretch">
|
||||
<Span className="text-[13px] leading-[18px] text-ink-secondary">
|
||||
{`When the model above fails or is resting, these are tried in order before the free automatic picks. Pick up to ${AppData.HarnessTextFallbackModelsMax}, from any provider.`}
|
||||
{`When the model above fails or is resting, these are tried in order before the free automatic picks. Add up to ${AppData.HarnessTextFallbackModelsMax}, from any provider.`}
|
||||
</Span>
|
||||
{slots.map((slot, index) => (
|
||||
<HarnessFallbackModelSelect
|
||||
key={`${index}-${slot ?? "none"}-${ids.join(",")}`}
|
||||
id={`${id}-fallback`}
|
||||
index={index}
|
||||
models={models}
|
||||
model_id={slot}
|
||||
taken={[model_id, ...ids.filter((_, other) => other != index)]}
|
||||
onChange={change}
|
||||
{backups.map((backup) => (
|
||||
<HarnessFallbackModelRow
|
||||
key={backup.id}
|
||||
name={backup.name}
|
||||
provider_name={backup.provider_name}
|
||||
onRemove={() => onChange(ids.filter((other) => other != backup.id))}
|
||||
/>
|
||||
))}
|
||||
<HarnessFallbackModelModal
|
||||
id={id}
|
||||
providers={providers}
|
||||
models={models}
|
||||
taken={[model_id, ...ids]}
|
||||
disabled={full}
|
||||
onAdd={(added) => onChange([...ids, added])}
|
||||
/>
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -19,6 +19,7 @@ export default function HarnessTextFallbacks({ id, harness, value, onChange }: P
|
||||
return (
|
||||
<HarnessFallbackModels
|
||||
id={id}
|
||||
providers={harness.providers}
|
||||
models={harness.models}
|
||||
model_id={value.model_id}
|
||||
fallback_model_ids={value.fallback_model_ids || []}
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
import { expect, test } from "bun:test";
|
||||
import type { HarnessModelOption } from "@/src/types";
|
||||
import harnessFallbackModelOptions from "./harness-fallback-model-options";
|
||||
|
||||
const models: HarnessModelOption[] = [
|
||||
{ id: 1, provider_id: 10, provider_name: "One", slug: "alpha", name: "Alpha", free: false },
|
||||
{ id: 2, provider_id: 20, provider_name: "Two", slug: "beta", name: "Beta", free: true },
|
||||
];
|
||||
|
||||
test("offers every model except the ones taken elsewhere", () => {
|
||||
const options = harnessFallbackModelOptions({ models, taken: [1] });
|
||||
|
||||
expect(options.map((option) => option.value)).toEqual(["2"]);
|
||||
expect(options[0]!.title).toBe("Beta · Two · free");
|
||||
});
|
||||
|
||||
test("names a free model that already says so only once, and marks the pick", () => {
|
||||
const options = harnessFallbackModelOptions({
|
||||
models: [{ id: 3, provider_id: 10, provider_name: "One", slug: "gamma", name: "Gamma (free)", free: true }],
|
||||
model_id: 3,
|
||||
taken: [],
|
||||
});
|
||||
|
||||
expect(options[0]!.title).toBe("Gamma (free) · One");
|
||||
expect(options[0]!.default).toBe(true);
|
||||
});
|
||||
@@ -1,37 +1,31 @@
|
||||
import type { TWUISelectOptionObject } from "@moduletrace/twui/form/Select";
|
||||
import type { HarnessModelOption } from "@/src/types";
|
||||
|
||||
export const NoFallbackValue = "none";
|
||||
|
||||
type Params = {
|
||||
/**
|
||||
* Every model that can do the job, on any provider.
|
||||
*/
|
||||
models: HarnessModelOption[];
|
||||
/**
|
||||
* This slot's model, if any.
|
||||
* The model picked in this picker, if any.
|
||||
*/
|
||||
model_id?: number;
|
||||
/**
|
||||
* The pick and the other slots' models, left out here.
|
||||
* The pick and the backups already saved, left out here.
|
||||
*/
|
||||
taken: number[];
|
||||
};
|
||||
|
||||
/**
|
||||
* One fallback slot's options: none, then every model that can do the
|
||||
* job on any provider (named with its provider), except the ones already
|
||||
* picked elsewhere.
|
||||
* A backup picker's options: every model that can do the job on any
|
||||
* provider (named with its provider), except the ones taken elsewhere.
|
||||
*/
|
||||
export default function harnessFallbackModelOptions({ models, model_id, taken }: Params): TWUISelectOptionObject[] {
|
||||
return [
|
||||
{ value: NoFallbackValue, title: "None", default: !model_id },
|
||||
...models
|
||||
.filter((model) => model.id == model_id || !taken.includes(model.id))
|
||||
.map((model) => ({
|
||||
value: String(model.id),
|
||||
title: `${model.name} · ${model.provider_name}${model.free && !/free/i.test(model.name) ? " · free" : ""}`,
|
||||
default: model.id == model_id,
|
||||
})),
|
||||
];
|
||||
}
|
||||
return models
|
||||
.filter((model) => !taken.includes(model.id))
|
||||
.map((model) => ({
|
||||
value: String(model.id),
|
||||
title: `${model.name} · ${model.provider_name}${model.free && !/free/i.test(model.name) ? " · free" : ""}`,
|
||||
default: model.id == model_id,
|
||||
}));
|
||||
}
|
||||
@@ -14,9 +14,9 @@ import type { APIResponseObject, BunextAPIRouteHandler } from "@moduletrace/bune
|
||||
|
||||
/**
|
||||
* The user moved a plan from its card: approved it (or picked it back up),
|
||||
* paused it, or ended it. Approving and resuming wake the bot for the step
|
||||
* it stands on, so the plan carries on by itself; pausing and cancelling
|
||||
* only stop it, since the run between two steps is what queues the next.
|
||||
* paused it, or ended it. Approving, resuming and Continue wake the bot for
|
||||
* the step it stands on, so the plan carries on by itself; pausing and
|
||||
* cancelling only stop it.
|
||||
*/
|
||||
export const handler: BunextAPIRouteHandler<APIResponseObject<BotPlanView>> = async ({ req, body }) => {
|
||||
try {
|
||||
|
||||
@@ -3,6 +3,7 @@ import grabUserConversation from "@/src/functions/backend/db/bot-sessions/grab-u
|
||||
import grabUserBotSession from "@/src/functions/backend/db/bot-sessions/grab-user-bot-session";
|
||||
import reopenBotSession from "@/src/functions/backend/db/bot-sessions/reopen-bot-session";
|
||||
import ensureBotSession from "@/src/functions/backend/db/bot-sessions/ensure-bot-session";
|
||||
import conversationLock from "@/src/functions/backend/db/bot-sessions/conversation-lock";
|
||||
import insertUserMessage from "@/src/functions/backend/db/bots/insert-user-message";
|
||||
import grabUserBotMessage from "@/src/functions/backend/db/bots/grab-user-bot-message";
|
||||
import grabMessageIdByClientId from "@/src/functions/backend/db/bots/grab-message-id-by-client-id";
|
||||
@@ -122,84 +123,102 @@ export const handler: BunextAPIRouteHandler<APIResponseObject> = async ({
|
||||
const media = await grabAttachableMedia({ user_id: Number(user.id), media_ids });
|
||||
|
||||
/**
|
||||
* The thread on screen is where the message goes: a routine's or a
|
||||
* hook's session is chatted in by reopening it first (which closes
|
||||
* the conversation's active one), never by posting into whichever
|
||||
* session happened to be active. A session of another conversation
|
||||
* is ignored, as the page does.
|
||||
* The send is one write against the conversation: a second one in
|
||||
* flight beside it would read the same active session and, when it
|
||||
* is full, roll it over a second time - writing into the session
|
||||
* the first call just closed, where the user never sees the message
|
||||
* or its reply.
|
||||
*/
|
||||
const shown = session_id
|
||||
? await grabUserBotSession({ session_id, user_id: user.id })
|
||||
: null;
|
||||
const message = await conversationLock.run({
|
||||
key: `${user.id}:${bot.id}:${conversation.workspace_id || 0}`,
|
||||
task: async () => {
|
||||
/**
|
||||
* The thread on screen is where the message goes: a routine's
|
||||
* or a hook's session is chatted in by reopening it first
|
||||
* (which closes the conversation's active one), never by
|
||||
* posting into whichever session happened to be active. A
|
||||
* session of another conversation is ignored, as the page
|
||||
* does.
|
||||
*/
|
||||
const shown = session_id
|
||||
? await grabUserBotSession({ session_id, user_id: user.id })
|
||||
: null;
|
||||
|
||||
if (
|
||||
shown?.id &&
|
||||
!shown.ask_id &&
|
||||
Number(shown.bot_id) == Number(bot.id) &&
|
||||
(Number(shown.workspace_id) || null) == (Number(conversation.workspace_id) || null) &&
|
||||
shown.status != "active"
|
||||
) {
|
||||
await reopenBotSession({ session_id: shown.id!, user_id: user.id });
|
||||
}
|
||||
if (
|
||||
shown?.id &&
|
||||
!shown.ask_id &&
|
||||
Number(shown.bot_id) == Number(bot.id) &&
|
||||
(Number(shown.workspace_id) || null) ==
|
||||
(Number(conversation.workspace_id) || null) &&
|
||||
shown.status != "active"
|
||||
) {
|
||||
await reopenBotSession({ session_id: shown.id!, user_id: user.id });
|
||||
}
|
||||
|
||||
const session = await ensureBotSession({
|
||||
user_id: user.id,
|
||||
bot_id: bot.id,
|
||||
workspace_id: conversation.workspace_id,
|
||||
rollover: true,
|
||||
const session = await ensureBotSession({
|
||||
user_id: user.id,
|
||||
bot_id: bot.id,
|
||||
workspace_id: conversation.workspace_id,
|
||||
rollover: true,
|
||||
});
|
||||
|
||||
/**
|
||||
* The quoted message only has to be in this conversation, not
|
||||
* in the session the message lands in: sending can roll over
|
||||
* to a new one, or the thread may have moved on.
|
||||
*/
|
||||
const reply_to = reply_to_message_id
|
||||
? await grabUserBotMessage({
|
||||
user_id: user.id,
|
||||
message_id: reply_to_message_id,
|
||||
}).catch(() => null)
|
||||
: null;
|
||||
|
||||
if (
|
||||
reply_to_message_id &&
|
||||
(!reply_to ||
|
||||
reply_to.bot_id != bot.id ||
|
||||
(reply_to.workspace_id || null) != (conversation.workspace_id || null))
|
||||
) {
|
||||
throw new AppError(`That message is no longer in this conversation.`);
|
||||
}
|
||||
|
||||
const stored = await insertUserMessage({
|
||||
bot_id: bot.id,
|
||||
session_id: Number(session.id),
|
||||
workspace_id: conversation.workspace_id,
|
||||
text,
|
||||
reply_to,
|
||||
media,
|
||||
client_id,
|
||||
plan_mode,
|
||||
});
|
||||
|
||||
try {
|
||||
await enqueueBotReply({
|
||||
user_id: user.id,
|
||||
bot_id: bot.id,
|
||||
session_id: Number(session.id),
|
||||
message_id: stored.id || 0,
|
||||
params: plan_mode ? { plan_mode: true } : undefined,
|
||||
});
|
||||
} catch (error: unknown) {
|
||||
/**
|
||||
* A message with no reply queued would sit in the thread
|
||||
* with nothing ever answering it, while the composer has
|
||||
* already taken its pending bubble down: it is taken back
|
||||
* out, so the send fails where the user can see it and
|
||||
* send it again.
|
||||
*/
|
||||
await deleteBotMessage({ message_id: Number(stored.id) }).catch(() => null);
|
||||
|
||||
throw error;
|
||||
}
|
||||
|
||||
return stored;
|
||||
},
|
||||
});
|
||||
|
||||
/**
|
||||
* The quoted message only has to be in this conversation, not in
|
||||
* the session the message lands in: sending can roll over to a new
|
||||
* one, or the thread may have moved on.
|
||||
*/
|
||||
const reply_to = reply_to_message_id
|
||||
? await grabUserBotMessage({ user_id: user.id, message_id: reply_to_message_id }).catch(
|
||||
() => null,
|
||||
)
|
||||
: null;
|
||||
|
||||
if (
|
||||
reply_to_message_id &&
|
||||
(!reply_to ||
|
||||
reply_to.bot_id != bot.id ||
|
||||
(reply_to.workspace_id || null) != (conversation.workspace_id || null))
|
||||
) {
|
||||
throw new AppError(`That message is no longer in this conversation.`);
|
||||
}
|
||||
|
||||
const message = await insertUserMessage({
|
||||
bot_id: bot.id,
|
||||
session_id: Number(session.id),
|
||||
workspace_id: conversation.workspace_id,
|
||||
text,
|
||||
reply_to,
|
||||
media,
|
||||
client_id,
|
||||
plan_mode,
|
||||
});
|
||||
|
||||
try {
|
||||
await enqueueBotReply({
|
||||
user_id: user.id,
|
||||
bot_id: bot.id,
|
||||
session_id: Number(session.id),
|
||||
message_id: message.id || 0,
|
||||
params: plan_mode ? { plan_mode: true } : undefined,
|
||||
});
|
||||
} catch (error: unknown) {
|
||||
/**
|
||||
* A message with no reply queued would sit in the thread with
|
||||
* nothing ever answering it, while the composer has already
|
||||
* taken its pending bubble down: it is taken back out, so the
|
||||
* send fails where the user can see it and send it again.
|
||||
*/
|
||||
await deleteBotMessage({ message_id: Number(message.id) }).catch(() => null);
|
||||
|
||||
throw error;
|
||||
}
|
||||
|
||||
/**
|
||||
* The files join the conversation's folder, so a later run can
|
||||
* search what the user sent now. The message and its reply are
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import type { BotQuestionView } from "@/src/types";
|
||||
import planContinueAnswer from "./plan-continue-answer";
|
||||
|
||||
function view({ status, choices }: { status: BotQuestionView["status"]; choices?: number[] }) {
|
||||
return {
|
||||
status,
|
||||
answers: choices ? [{ choices }] : undefined,
|
||||
} as unknown as BotQuestionView;
|
||||
}
|
||||
|
||||
describe("planContinueAnswer", () => {
|
||||
test("the first option answers continue", () => {
|
||||
expect(planContinueAnswer({ view: view({ status: "answered", choices: [0] }) })).toBe(true);
|
||||
});
|
||||
|
||||
test("pause, a second choice or a typed answer holds the plan", () => {
|
||||
expect(planContinueAnswer({ view: view({ status: "answered", choices: [1] }) })).toBe(false);
|
||||
expect(planContinueAnswer({ view: view({ status: "answered", choices: [] }) })).toBe(false);
|
||||
expect(planContinueAnswer({ view: view({ status: "answered" }) })).toBe(false);
|
||||
});
|
||||
|
||||
test("a card still waiting, or skipped, holds it", () => {
|
||||
expect(planContinueAnswer({ view: view({ status: "pending" }) })).toBe(false);
|
||||
expect(planContinueAnswer({ view: view({ status: "skipped" }) })).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,13 @@
|
||||
import type { BotQuestionView } from "@/src/types";
|
||||
|
||||
/**
|
||||
* Whether the answer to a plan's card said to carry on. The plan's step
|
||||
* ends with a card whose first option is Continue (`PlanStepNote`), so
|
||||
* only that picked option moves the plan: Pause, an answer typed into
|
||||
* "Other", a skip or a plain answer all leave it where it is.
|
||||
*/
|
||||
export default function planContinueAnswer({ view }: { view: BotQuestionView }) {
|
||||
if (view.status != "answered") return false;
|
||||
|
||||
return Boolean(view.answers?.[0]?.choices?.includes(0));
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
/**
|
||||
* Tools that hand work to a run of its own. A plan step's reply that used
|
||||
* one has already put the next move in front of the user (the run's own
|
||||
* report), so it ends the step without the plan's card.
|
||||
*/
|
||||
const PlanWorkStartingTools = ["start_task", "delegate_task", "ask_bot", "hand_over_task"];
|
||||
|
||||
export default PlanWorkStartingTools;
|
||||
@@ -1,58 +0,0 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import shouldContinuePlan from "./should-continue-plan";
|
||||
|
||||
/**
|
||||
* A plan carries on by itself after each step, and stops for a reason that
|
||||
* really happened in between: the user was asked something, work was handed
|
||||
* off, the plan was paused or ended, it has nothing left to work, or another
|
||||
* reply already waits in that conversation. Anything else queues the next
|
||||
* step.
|
||||
*/
|
||||
const go = {
|
||||
status: "active" as const,
|
||||
needs_you: false,
|
||||
tool_names: ["computer_read_file", "complete_plan_step"],
|
||||
plan_session_id: 7,
|
||||
session_id: 7,
|
||||
has_pending_step: true,
|
||||
has_waiting_reply: false,
|
||||
};
|
||||
|
||||
describe("shouldContinuePlan", () => {
|
||||
test("carries on once a step finished", () => {
|
||||
expect(shouldContinuePlan(go)).toBe(true);
|
||||
});
|
||||
|
||||
test("stops while the user is needed", () => {
|
||||
expect(shouldContinuePlan({ ...go, needs_you: true })).toBe(false);
|
||||
});
|
||||
|
||||
test("stops when the run handed work off, whose report is still to come", () => {
|
||||
for (const name of ["start_task", "delegate_task", "ask_bot", "hand_over_task"]) {
|
||||
expect(shouldContinuePlan({ ...go, tool_names: [name] })).toBe(false);
|
||||
}
|
||||
});
|
||||
|
||||
test("stops when send_reply queued a run of its own", () => {
|
||||
expect(shouldContinuePlan({ ...go, started_work: true })).toBe(false);
|
||||
});
|
||||
|
||||
test("stops when the plan was paused or ended mid-step", () => {
|
||||
expect(shouldContinuePlan({ ...go, status: "paused" })).toBe(false);
|
||||
expect(shouldContinuePlan({ ...go, status: "cancelled" })).toBe(false);
|
||||
expect(shouldContinuePlan({ ...go, status: "done" })).toBe(false);
|
||||
});
|
||||
|
||||
test("stops once nothing is left to work", () => {
|
||||
expect(shouldContinuePlan({ ...go, has_pending_step: false })).toBe(false);
|
||||
});
|
||||
|
||||
test("stops when a reply already waits in the conversation", () => {
|
||||
expect(shouldContinuePlan({ ...go, has_waiting_reply: true })).toBe(false);
|
||||
});
|
||||
|
||||
test("never queues a step into another conversation", () => {
|
||||
expect(shouldContinuePlan({ ...go, plan_session_id: "12", session_id: 7 })).toBe(false);
|
||||
expect(shouldContinuePlan({ ...go, plan_session_id: "7", session_id: 7 })).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -1,79 +0,0 @@
|
||||
import type { BotPlanState } from "@/src/dict/bot-plan-dict";
|
||||
|
||||
type Params = {
|
||||
/**
|
||||
* The plan as it stands when the step's run ended: nothing is queued
|
||||
* when the user paused or ended it meanwhile. A row the schema gave no
|
||||
* status is not active, so it goes nowhere.
|
||||
*/
|
||||
status: BotPlanState | "";
|
||||
/**
|
||||
* The reply asked the user something (`ask_user`), so the plan waits on
|
||||
* them rather than carrying on.
|
||||
*/
|
||||
needs_you?: boolean;
|
||||
/**
|
||||
* The tools the run called: one that starts work (a task, a hand-over, a
|
||||
* request to another bot) has a report still to come, so the plan waits
|
||||
* for it instead of talking over it.
|
||||
*/
|
||||
tool_names?: string[];
|
||||
/**
|
||||
* The closing `send_reply` queued a run (`status: "working"`), whose
|
||||
* report comes later: the plan waits for it just as it does for a
|
||||
* `start_task`.
|
||||
*/
|
||||
started_work?: boolean;
|
||||
/**
|
||||
* The plan's session and the finished step's: a step job is queued for
|
||||
* the conversation it belongs to, never another one's.
|
||||
*/
|
||||
plan_session_id: number | string;
|
||||
session_id: number | string;
|
||||
/**
|
||||
* Every step is behind it: there is nothing left to queue.
|
||||
*/
|
||||
has_pending_step: boolean;
|
||||
/**
|
||||
* A reply already waits in the conversation (a message the user sent
|
||||
* mid-step): its own run picks the plan up from there.
|
||||
*/
|
||||
has_waiting_reply: boolean;
|
||||
};
|
||||
|
||||
/**
|
||||
* The tools whose work reports back later: a run that called one has handed
|
||||
* something off, and the plan's next step would only cross it.
|
||||
*/
|
||||
export const WorkStartingTools = ["start_task", "delegate_task", "ask_bot", "hand_over_task"];
|
||||
|
||||
/**
|
||||
* Whether a plan's next step should be queued now that the run finished one.
|
||||
* Each reason to stop is one thing that happened in between: the user was
|
||||
* asked something, work was handed off, the plan was paused or ended, it has
|
||||
* no step left, or another reply is already queued in that conversation.
|
||||
*/
|
||||
export default function shouldContinuePlan({
|
||||
status,
|
||||
needs_you,
|
||||
tool_names,
|
||||
started_work,
|
||||
plan_session_id,
|
||||
session_id,
|
||||
has_pending_step,
|
||||
has_waiting_reply,
|
||||
}: Params) {
|
||||
if (needs_you) return false;
|
||||
|
||||
if (started_work) return false;
|
||||
|
||||
if ((tool_names || []).some((name) => WorkStartingTools.includes(name))) return false;
|
||||
|
||||
if (Number(plan_session_id) != Number(session_id)) return false;
|
||||
|
||||
if (status != "active") return false;
|
||||
|
||||
if (!has_pending_step) return false;
|
||||
|
||||
return !has_waiting_reply;
|
||||
}
|
||||
@@ -7,7 +7,7 @@ type Params = {
|
||||
|
||||
/**
|
||||
* How a bot asks the user to take over one of its computers in a message:
|
||||
* `[take-over:3:browser]`. The chat shows it as a button that opens the
|
||||
* `[take-over:3:browser]`. The chat shows it as a card that opens the
|
||||
* computer in that mode.
|
||||
*/
|
||||
export default function takeOverRef({ id, mode }: Params) {
|
||||
|
||||
Reference in New Issue
Block a user