Compare commits

...
4 Commits
Author SHA1 Message Date
tben 0151ca6e55 0.25.0
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
2026-11-20 08:19:08 +01:00
tben baeb9a80d3 Keep a reply whose message the model wrote in the call or beside a card
deepseek wrote the answer as plain text in an earlier turn or as send_reply's
own argument, and every path deleted it: the text became a draft, a card turn
lost it, and a bare send_reply kept carrying a faulted draft until the
rewrites ran out. Six production replies failed that way.

- send_reply takes the message itself (message, or text as an alias), so the
  shape a model reaches for is the one that works
- a message written beside a card goes out with the call that closes it
- a review send-back clears the held text and the reminder, so a refused
  answer is never sent again
- ask_user and suggest_next_steps answer a repeat call instead of throwing,
  which read as a failed closing turn and lost the whole answer
- card refs the app appended are stripped from answers and from history, the
  way the model learned to write [question:24] itself
- the review faults [proposal:] and [hook-proposal:] refs no row backs
- a pending proposal for the same target is replaced across a conversation,
  not just its session, and confirming one replaces the others
- a run queued by a tool wakes the queue and pushes, every active task is
  pushed and a conversation keeps polling, so a queued run is not silent
- a failed run closes its bot_tasks row, so it cannot shadow later progress
2026-11-20 08:19:02 +01:00
tben 984ad702d6 Stop promising an order between a command's two pipes
stdout and stderr are separate pipes read as they arrive, so a line from
one can land before a line the other already had. The test asked for
stdout first every time and lost that race on CI; it now checks one
stream's order and that stderr comes back beside stdout.
2026-11-19 17:08:47 +01:00
tben 09039bee22 Stop the video test stubbing the provider preset
The stub replaced the shared grab-provider-preset module for every file
that ran after it, which left generate-image with no image_path and broke
the DashScope image tests on CI. It was never needed: the real custom
preset already has video_path /videos.
2026-11-19 17:05:38 +01:00
44 changed files with 1294 additions and 117 deletions
+7 -7
View File
@@ -100,8 +100,8 @@ Enables SQLite foreign keys (`enableForeignKeys`), `bunextInit()`, `ensureDocker
- **Task chips:** which tracker tasks a bot message is about is the app's record, not the bot's word: a run's task tools report each task they touch (`onTask`: `list_tasks` with `task_id`, `create_task`, `update_task`, `delete_task`, `delegate_task`'s hand-over), plus a handed-over job's `tracker_task_id`, into `bot_messages.task_ids` (also on its failure notice and its report relayed to the requester). The thread shows them under the message (`MessageTaskChips`) with title and status, read per viewer and only for tasks they reach (`grabMessagesTasks`; pushes carry them through `withMessageTasks`).
- **File preview:** every file link (chips, attachments, files modal, task files, `/admin/files`) is a `FilePreviewLink`: a plain click opens `FilePreviewModal` (its header shows the size and the file's full path on the data volume, `full_path`, e.g. `bots/3/reports/q3.md`, absolute when outside it; every opener passes it; markdown rendered with the message elements, CSV/TSV as a table via `parseCsv`, images in `ImageViewer` (zoom buttons and keys, Ctrl/Cmd+wheel or pinch at the pointer, Fit, Fit width (a full-page screenshot opens that way and scrolls down), Actual size, double click, drag to pan; sized by the `width` attribute and centred with auto margins, never flex centring, which cuts off a tall picture's top), PDF/audio/video in place, HTML in a frame with `sandbox=""` (plus the media server's `sandbox` CSP), other text as code, the kind from `filePreviewKind`; Download and Open in a new tab), a modified click still opens a tab. Text is read up to `AppData.FilePreviewMaxTextBytes`. Never render a file's HTML on the app's origin or with scripts. Opened from a list (a folder, the files modal, a conversation's images), an image gets that list's images as its `gallery` (`imagePreviewGallery`): Previous/Next (side arrows at the far middle left/right, the header's stepper, and the arrow keys) step through them in the same modal, neighbours preloaded. Escape closes only the top modal of a stack (`useTopModalEscape`; twui closes every open one). The message elements and the preview import each other (through the file chips), so the preview merges `MessageMarkdownComponents` when it renders, never at module load.
- **Copy chat** (header menu): the active session (the one on screen) as one markdown document (`api/admin/bots/conversation-export` -> `conversationMarkdown`, refs as names, message headings demoted). The clipboard write starts on the click with a pending `ClipboardItem` (`copyPendingText`), since Safari drops the gesture after a fetch. A message's Details modal has its own **Copy report** (`messageDetailsMarkdown`, the same pending write): that message's whole details, listing up to `AppData.MessageDetailsCopyMaxCalls` calls and failures (the route's `full=1`) instead of the modal's first `MessageDetailsMaxCalls`.
- **Asking before acting:** `ask_user` (`QuestionsNote`) puts up to `AppData.BotQuestionMaxQuestions` multiple-choice questions (`single` = radios, `multiple` = checkboxes, optional typed "Other") on one card, once per run -> `bot_questions` -> `[question:ID]` chip opening `BotQuestionCard`; the message needs the user. Answers are checked against the questions (`checkBotQuestionAnswers`) and stored, then sent as the user's chat message (`botQuestionAnswersText`); Skip says so. **The card belongs to the conversation it was asked in:** the answer and skip routes post that message into the question's own session (`postBotQuestionAnswers`), never the page's bot (a card answered on the requester's page woke the wrong bot), and `stripQuestionRefs` takes `[question:ID]` out of text copied into another bot's conversation (`relayJobToRequester`, a crew request's outcome, an install request's answer), which would otherwise show the same card in two sessions, answered in one and left waiting in the other. Replies and user-started tasks only: never routines, hook calls or a crew request's run (no one sees those). The reply's `ask_user`/`suggest_next_steps` and `QuestionsNote` are gated on `attended` (`isHiddenSession`), and a task run's on `can_ask` (`isHiddenSession` checked there too): a question in a hidden session has no card the user would see (one reached the coordinator as a bare `[question:22]`, its answer never getting back).
- **Suggested next steps:** `suggest_next_steps` puts up to `AppData.BotSuggestionMaxSteps` follow-ups under the answer, once per run -> `bot_suggestions` -> `[suggestion:ID]` rendered inline as buttons (`BotSuggestionsRef`); clicking one inserts it into the composer (`ComposerHandle.insertText`, never sends) and nothing waits on it, so it's `shown` in `withTakeOverRefs`, never `refs`, and never sets `needs_you`. For when the work is done and the bot offers follow-ups; when the answer decides what it does next, it's `ask_user`. Same runs as `ask_user`. Both are closing tools (`ClosingToolNames`, `src/harness/tools/closing-tool-names.ts`): the turn that writes the answer and puts the card up ends the run, after the usual `review`, because a reply is only the run's **last** message. Without that, a bot answered with the PR links the user asked for, then called `list_tasks` (which `TaskReminderNote` told it to do after answering), and the user was sent the short "still open" line alone.
- **Asking before acting:** `ask_user` (`QuestionsNote`) puts up to `AppData.BotQuestionMaxQuestions` multiple-choice questions (`single` = radios, `multiple` = checkboxes, optional typed "Other") on one card, once per run (a second call returns the card already up instead of throwing: a refused re-ask read as a failed closing turn and the whole answer was thrown away) -> `bot_questions` -> `[question:ID]` chip opening `BotQuestionCard`; the message needs the user. Answers are checked against the questions (`checkBotQuestionAnswers`) and stored, then sent as the user's chat message (`botQuestionAnswersText`); Skip says so. **The card belongs to the conversation it was asked in:** the answer and skip routes post that message into the question's own session (`postBotQuestionAnswers`), never the page's bot (a card answered on the requester's page woke the wrong bot), and `stripQuestionRefs` takes `[question:ID]` out of text copied into another bot's conversation (`relayJobToRequester`, a crew request's outcome, an install request's answer), which would otherwise show the same card in two sessions, answered in one and left waiting in the other. Replies and user-started tasks only: never routines, hook calls or a crew request's run (no one sees those). The reply's `ask_user`/`suggest_next_steps` and `QuestionsNote` are gated on `attended` (`isHiddenSession`), and a task run's on `can_ask` (`isHiddenSession` checked there too): a question in a hidden session has no card the user would see (one reached the coordinator as a bare `[question:22]`, its answer never getting back).
- **Suggested next steps:** `suggest_next_steps` puts up to `AppData.BotSuggestionMaxSteps` follow-ups under the answer, once per run (a second call returns the steps already attached instead of throwing) -> `bot_suggestions` -> `[suggestion:ID]` rendered inline as buttons (`BotSuggestionsRef`); clicking one inserts it into the composer (`ComposerHandle.insertText`, never sends) and nothing waits on it, so it's `shown` in `withTakeOverRefs`, never `refs`, and never sets `needs_you`. For when the work is done and the bot offers follow-ups; when the answer decides what it does next, it's `ask_user`. Same runs as `ask_user`. Both are closing tools (`ClosingToolNames`, `src/harness/tools/closing-tool-names.ts`): the turn that writes the answer and puts the card up ends the run, after the usual `review`, because a reply is only the run's **last** message. Without that, a bot answered with the PR links the user asked for, then called `list_tasks` (which `TaskReminderNote` told it to do after answering), and the user was sent the short "still open" line alone.
- **Plans:** work with several pieces that build on each other is written down before it starts, and worked one step per reply, since a bot answering such a request in one message is how a reply turns into a wall of text. `create_plan` (title, goal, 3 to `AppData.BotPlanMaxSteps` steps) -> `bot_plans` (one open plan per conversation, `BotPlanOpenStates`) -> `[plan:ID]` (`BotPlanCard`); nothing of it runs until the user approves it there, and they change the steps first (`BotPlanEditModal` -> `save-plan`), though a step already worked stays at the top with its note (`planStepsRewriteProblem`). Approving queues the first step as an ordinary **reply** job with `params.plan_id`, in the same conversation, so it has the bot's tools, computers, memory and files; the run gets `PlanStepNote` and works that step alone, `complete_plan_step` marks it done with what it produced (the card checks it off, `pushBotPlan` -> `server:bot-plan`), and `continueBotPlan` (from `process-bot-job`, after the notice) queues the next one. It stops on its own when the user is needed (`needs_you`), when the reply handed work to a run (`WorkStartingTools`), or when an unanswered reply already waits in the session, and never counts an approval as a step: `done` is the app's call once no step is pending. A run that is a plan's step can't write or cancel a plan, only work it, change it (`update_plan`) or finish its step. An ordinary reply in a conversation whose plan is open gets `PlanWaitingNote`/`PlanActiveNote`/`PlanPausedNote` instead of plan tools, so a plan is only ever advanced by the app. A **routine** writes its plan with `approve: true` (`ScheduledPlanNote`): nobody is there to approve it, so it starts itself and the run works every step, reporting at the end. Plan tools are not closing tools: the card and one sentence about it are the reply. When a plan is one the work comes back to, the bot saves its steps with `update_memory` (`PlansNote`); a repeating job is a routine instead. `bot_plans` is deleted with its session (`deleteBotPlanRows`, from `deleteSessionRows`).
- **Quoting:** selected text quotes into the composer through `quotableText`, which reads each ref chip as one inline label (`MarkdownLink` wraps chips with `QuoteInlineAttribute`; `Selection.toString()` broke a quote into a paragraph per chip).
- **A user's own long message is cut:** the bubble shows the first twenty lines (`max-h-[25rem]`, the bubble's `leading-5`) with **Read more** under it, and **Show less** puts it back (`use-bubble-clamp.ts` measures the cut text in the browser: `bubbleOverflows`); a pasted prompt should not fill the screen. Only what's shown is cut, so the bot, Copy chat and the export still get every character.
@@ -126,16 +126,16 @@ Every run also gets `RequestScopeNote` (`src/data/harness-prompts.ts`): the user
- Kinds (`BotJobKinds`): `reply` (chat answer, no task row) and `task` (long work, usually on a computer). bun-sqlite `isQueue` table. Helpers in `src/functions/backend/db/bots-queue/`: `enqueueBotJob`, `claimBotJobs` (kind-filtered atomic claim), `updateBotJob` (false once lost/cancelled), `completeBotJob`, `failBotJob` (backoff or fatal), `deferBotJob` (all models resting: attempt refunded, face `asleep`), `cancelBotJob`, `stop-bot-jobs`.
- Handler `src/bots-queue/index.ts`: separate reply/task slots, heartbeat, a per-attempt deadline for replies (`AppData.BotJobAttemptTimeoutMs`; a task run has none, since its script may run for hours, and Stop ends it), one task per computer and one reply per session (`createKeyLock`). Work in `run-bot-job.ts` -> `run-bot-reply.ts` / `run-bot-task.ts`. Throw `BotJobFatalError` for failures retrying can't fix. A computer that's down (`isComputerDown`: failed, dead, exited) is one: `queueBotTask` (a reply's `send_reply` work, or `start_task`) refuses it and a task run on it fails at once.
- Every model turn is a step in `bots_queue_updates` (tool names, never arguments; `describe-job-step.ts`, labels in `JobStepToolLabels`), pushed as `server:bot-job-update` by the live relay only. Steps feed the live working row alone: the `clear-job-steps` cron deletes them `AppData.BotJobStepsKeepMs` after the job ends, however it ended, keeping their count on `bots_queue.steps`. Never delete them the moment a job ends (the relay would miss the last ones).
- Every model turn is a step in `bots_queue_updates` (tool names, never arguments; `describe-job-step.ts`, labels in `JobStepToolLabels`), pushed as `server:bot-job-update` by the live relay only. Steps feed the live working row alone: the `clear-job-steps` cron deletes them `AppData.BotJobStepsKeepMs` after the job ends, however it ended, keeping their count on `bots_queue.steps`. Never delete them the moment a job ends (the relay would miss the last ones). A job queued by a tool (`enqueueBotJob`, the `queueBotTask` path) wakes the queue and pushes `server:bot-updated` itself, so a run queued behind another on the same computer shows and starts at once instead of waiting for the poll; a failed run closes its own `bot_tasks` row (`notifyBotJobFailed`), since a row left `active` kept a conversation's progress on a run that had failed months before (a queued run creates it `active`; only complete, cancel and stop closed it before).
- **A task run plans before it starts:** `planBotTask` (from `run-bot-task`) spends one turn, no tools, on the very system prompt the run then sends, so the provider's cache serves it and it costs little more than the plan. The answer is a bounded JSON plan (`BotTaskPlanSchema`, caps in `AppData.BotTaskPlan*`) that opens the run as `taskPlanNote` and shows as its first step line; `shouldPlanBotTask` keeps it off short runs (`AppData.BotTaskPlanMinSteps`). A plan that can't be written or read starts the run unplanned, never blocks it. **The wrap up is told what is on disk:** a task run passes `Params.wrap_up_note`, which runs `worktreeSummary` over the run's folders (`git status --porcelain` and `git diff --stat` per repository, nested ones included, at most 5) and puts the machine's own account in front of the wrap-up prompt, so the report is written from the tree and not from the run's memory of writing it. **The files the brief names are checked once, before the run starts** (`namedFilesNote`, over `namedFiles`): a path that isn't on the computer but is still in the bot's files is handed over as its `[file:ID]` with `export_file`, and one with no copy anywhere says plainly not to go looking through the machine or the user's accounts. It is the app's answer, not the run's guess: a source a rebuild took off the computer once cost a run thirty turns probing the container and then the user's own accounts for a copy the app was holding the whole time.
- **A reply ends with `send_reply`:** a reply run's answer is not its prose. The last turn must be `send_reply({status:"done"|"working"|"blocked", work?})` with the message beside it, and assistant text with no tool call is a draft the loop returns to the model (`replyDraftNote`, up to `AppData.HarnessReplyDraftsMax`) rather than a message the user sees. A bare `send_reply` does not ship that draft on the first pass (`replyNoTextNote`): the model writes the whole message again in that turn, which is also the only turn that may call `suggest_next_steps` or `ask_user` beside it (any other tool is `replyClosingMixedNote` and unsent). A finished draft is carried only after that one reminder still gets no text (`draft_carried`); a draft that stops in a table, a fence or a bare marker (`unfinishedAnswerText`) is sent back once and never carried. A run that still ends with no message fails saying so rather than that its answer was wrong (`unsentAnswerMessage`). `status:"working"` must queue `work` (`{title,instructions,computer_id?,separate?,max_steps?}`, through `queueBotTask`, the same guards and brief as `start_task`) or follow a run already started from this reply, so a message that says work is running can only exist when the job does; `done` and `blocked` carry no work, and `work` beside either is refused. `start_task` is not a reply tool (it stays in task runs for a hand-off), `send_reply` is a closing tool beside `ask_user`/`suggest_next_steps`, and a task report ends the same way. If the run never closes, the job fails honestly and the thread offers Retry; work queued earlier in the run is cancelled with the unsent message. The review reads the status: a `done`/`blocked` message that says work is under way is faulted even when some unrelated run is open, and `hasOpenWork` takes the current `job_id` (`exclude_job_id`) so a task report can't count its own job as open work.
- **A bot can't vouch for itself:** a run's tool calls (`tool_uses`, names and ok, never arguments) go to the wrap-up turn when steps run out and onto the result message as `bot_messages.tool_log`; history follows each recorded bot message with an `[App record: ...]` line (`botMessagesToHarness`), and copies of that line in an answer are stripped (`stripAppRecords`, which shares the line shape with `appRecordLines`). Before a reply or a task report goes out, `reviewBotReply` (the loop's `review`, wired for both by `reviewRunAnswer`) sends it back when it names a `[file:ID]`/`[task:ID]`/`[graphic:ID]` that doesn't exist for the user, a task named in plain prose (`task #16`, `mentionedTaskIds`) whose row is gone (a row the user cannot open is left alone), a `[setting:...]` ref the app can't resolve (`unresolvedSettingRefs`), a `[suggestion:ID]`/`[question:ID]`/`[plan:ID]` ref it wrote itself (`AppCardRefTools`: the app adds those from the tool that made the card, so a written one is made up or copied from an earlier message and the user reads "not available"), or says work is under way, that a report will follow, or that it is about to do the work ("Let me check", "I'll connect and inspect", "next I'll", "Starting the conversion run now") (`claimsWorkUnderWay`, which reads a promise only when its own sentence is the commitment, so an offer waiting on the user is left alone) with no run this reply started and nothing open from the session: bots wrote "I'm scanning now" plus made-up results in one answer, and a reply promising to check the articles and then starting nothing left the user waiting for a report nobody would send. It also faults the app's own state described from nothing (`replyAppStateClaims`, skipped when `read_message_usage`/`read_settings` answered): how the model "routing" resolves or which model the tool sends, a run "killed" or "stopped" (Stop is the user's), and the model rest called unlimited or restart-only, each written by a bot that had only an `HTTP 404` to go on and told the user a model and a mechanism nobody had configured. Review runs on every answer it writes, up to `AppData.HarnessReviewRewrites` rewrites (a repeat of the faulted message is told so, `repeatedAnswerNote`); past that the answer is never sent and the job fails instead (`review_note` -> `BotJobFatalError`, a reply and a task report alike; a rewrite that lands on the wrap up is reviewed there and refused, not sent on), since a model that kept writing the same thing sends the claim anyway. **A fault must be something the bot can stop making:** only a whole line in the app's own record shape naming tools this reply didn't call is a forgery (`unsupportedAppRecordLines`) - the same text quoted inside a sentence is the bot naming its mistake, and job #468 faulted three rewrites in a row for that quote alone, so the lie stayed and the correction never reached the user. No fault note may itself contain the shape it faults or a `claimsWorkUnderWay` phrase. Tool names copied into a list (`WorkStartingTools`, `AppCardRefToolNames`, `WritingToolNames`, `WrapUp*ToolNames`) are pinned to the tools the harness declares by `src/harness/tools/tool-name-lists.test.ts` (`ask_crew` outlived its rename to `ask_bot`, so a reply that really had asked the crew was faulted for saying so). A long bot message whose run called no tools shows "No tools used" (`MessageNoToolsChip`).
- **A reply ends with `send_reply`:** a reply run's answer is not its prose. The last turn must be `send_reply({status:"done"|"working"|"blocked", work?, message?})` with the message beside it or in its `message`/`text` argument (`replyTextFromCall`: a model that wrote the message into the call instead of the turn lost six production answers to "doesn't take text"), and assistant text with no tool call is a draft the loop returns to the model (`replyDraftNote`, up to `AppData.HarnessReplyDraftsMax`) rather than a message the user sees. A bare `send_reply` does not ship that draft on the first pass (`replyNoTextNote`): the model writes the whole message again in that turn, which is also the only turn that may call `suggest_next_steps` or `ask_user` beside it (any other tool is `replyClosingMixedNote` and unsent). A message written in the turn that put a card up (`ask_user`/`suggest_next_steps` with no `send_reply`) is kept as `card_text` and goes out with the call that closes it: that sentence is what the card belongs under, and asking for it again left the model with nothing to say (session 146). A review send-back clears `draft_text` and `card_text` and the reminder flag, so a refused answer is never carried again (the same faulted text went out on every bare `send_reply` and used up the rewrite budget). A draft that stops in a table, a fence or a bare marker (`unfinishedAnswerText`) is sent back once and never carried. A run that still ends with no message fails saying so rather than that its answer was wrong (`unsentAnswerMessage`). `status:"working"` must queue `work` (`{title,instructions,computer_id?,separate?,max_steps?}`, through `queueBotTask`, the same guards and brief as `start_task`) or follow a run already started from this reply, so a message that says work is running can only exist when the job does; `done` and `blocked` carry no work, and `work` beside either is refused. `start_task` is not a reply tool (it stays in task runs for a hand-off), `send_reply` is a closing tool beside `ask_user`/`suggest_next_steps`, and a task report ends the same way. If the run never closes, the job fails honestly and the thread offers Retry; work queued earlier in the run is cancelled with the unsent message. The review reads the status: a `done`/`blocked` message that says work is under way is faulted even when some unrelated run is open, and `hasOpenWork` takes the current `job_id` (`exclude_job_id`) so a task report can't count its own job as open work.
- **A bot can't vouch for itself:** a run's tool calls (`tool_uses`, names and ok, never arguments) go to the wrap-up turn when steps run out and onto the result message as `bot_messages.tool_log`; history follows each recorded bot message with an `[App record: ...]` line (`botMessagesToHarness`), and copies of that line in an answer are stripped (`stripAppRecords`, which shares the line shape with `appRecordLines`). Before a reply or a task report goes out, `reviewBotReply` (the loop's `review`, wired for both by `reviewRunAnswer`) sends it back when it names a `[file:ID]`/`[task:ID]`/`[graphic:ID]` that doesn't exist for the user, a task named in plain prose (`task #16`, `mentionedTaskIds`) whose row is gone (a row the user cannot open is left alone), a `[setting:...]` ref the app can't resolve (`unresolvedSettingRefs`), a `[suggestion:ID]`/`[question:ID]`/`[plan:ID]` ref it wrote itself (`AppCardRefTools`: the app adds those from the tool that made the card, so a written one is made up or copied from an earlier message and the user reads "not available"; `stripCardRefs` keeps them out of the answer and out of the model's own history, since the stored text carries the ref the app appended under it, which is how one began writing `[question:24]` at a card it never made), a `[proposal:]`/`[hook-proposal:]` ref no row backs (the model guessed `[proposal:19]` 85 s before that row existed, and the user was told three times a proposal had gone out when none had), or says work is under way, that a report will follow, or that it is about to do the work ("Let me check", "I'll connect and inspect", "next I'll", "Starting the conversion run now") (`claimsWorkUnderWay`, which reads a promise only when its own sentence is the commitment, so an offer waiting on the user is left alone) with no run this reply started and nothing open from the session: bots wrote "I'm scanning now" plus made-up results in one answer, and a reply promising to check the articles and then starting nothing left the user waiting for a report nobody would send. It also faults the app's own state described from nothing (`replyAppStateClaims`, skipped when `read_message_usage`/`read_settings` answered): how the model "routing" resolves or which model the tool sends, a run "killed" or "stopped" (Stop is the user's), and the model rest called unlimited or restart-only, each written by a bot that had only an `HTTP 404` to go on and told the user a model and a mechanism nobody had configured. Review runs on every answer it writes, up to `AppData.HarnessReviewRewrites` rewrites (a repeat of the faulted message is told so, `repeatedAnswerNote`); past that the answer is never sent and the job fails instead (`review_note` -> `BotJobFatalError`, a reply and a task report alike; a rewrite that lands on the wrap up is reviewed there and refused, not sent on), since a model that kept writing the same thing sends the claim anyway. **A fault must be something the bot can stop making:** only a whole line in the app's own record shape naming tools this reply didn't call is a forgery (`unsupportedAppRecordLines`) - the same text quoted inside a sentence is the bot naming its mistake, and job #468 faulted three rewrites in a row for that quote alone, so the lie stayed and the correction never reached the user. No fault note may itself contain the shape it faults or a `claimsWorkUnderWay` phrase. Tool names copied into a list (`WorkStartingTools`, `AppCardRefToolNames`, `WritingToolNames`, `WrapUp*ToolNames`) are pinned to the tools the harness declares by `src/harness/tools/tool-name-lists.test.ts` (`ask_crew` outlived its rename to `ask_bot`, so a reply that really had asked the crew was faulted for saying so). A long bot message whose run called no tools shows "No tools used" (`MessageNoToolsChip`).
- **A reply's `send_reply` work and `start_task`/`delegate_task` jobs are runs, not tasks:** their results say `Run #<job id>` and that `list_tasks` doesn't show them (bots sent users to the tracker for them). `queueBotTask` refuses a second open run in its session on the same computer unless `separate` (it would only wait behind it) and says how many runs are ahead on that computer. Its `max_steps` (`params.max_steps`) caps the run below the install's limit; the brief alone never did. Nothing wakes a bot when a run ends, so different follow-up work is queued at once with `separate`, never promised for later (`send_reply`'s work, `start_task`, `chatReplyNote`).
- **Replies take in messages sent mid-run** (`incoming`, `IncomingMessagesNote`, redraft); separate requests are acknowledged with `send_message` (interim). A queued reply finishes silently only when a finished reply already read every user message (`hasUnansweredMessage`), never by who wrote last; a retry (`params.retry_of`) always runs. **Task runs take them in too** (`taskIncoming`, only runs the user follows: no routines, hook calls or rooms): everything the user wrote since the run was queued, at the start, between steps, past a report not yet out and by the wrap up (`incoming_notes`, `TaskIncomingNote`); a correction changes the work, anything else is left to the chat, and crew messages to the reply they wake. A reply is told which runs open in its session hear the user (`openRunsNote`), so a correction never starts a second run.
### Live updates
Server push only. `pushBotNotice` (`server:bot-message`, `server:bot-updated`), `pushBotUpdated` (to the bot's whole audience), `server:bot-created|removed`, `server:workspace-created|updated|removed`, `server:computer-updated`, the debug view's `server:bot-trace` (just the job and its session), and a plan's card `server:bot-plan` (just its id and conversation). Deletions push to the audience read **before** the delete. `liveRelay` (`src/live-relay/`) polls the DB every `AppData.LiveRelayPollMs` so work from other processes shows; clients dedupe by id. `useLiveBots` keeps rail and header current.
Server push only. `pushBotNotice` (`server:bot-message`, `server:bot-updated`), `pushBotUpdated` (to the bot's whole audience), `server:bot-created|removed`, `server:workspace-created|updated|removed`, `server:computer-updated`, the debug view's `server:bot-trace` (just the job and its session), and a plan's card `server:bot-plan` (just its id and conversation). Deletions push to the audience read **before** the delete. `liveRelay` (`src/live-relay/`) polls the DB every `AppData.LiveRelayPollMs` so work from other processes shows; clients dedupe by id. `useLiveBots` keeps rail and header current. A push's `task` is a list of every active task that user has on the bot (`grabActiveBotTasks`), and the conversation picks its own session's (`ownTask`), since sending only the newest one blanked the row whenever another conversation of the same bot had a run open; a page also keeps polling (`use-reply-catch-up` `running`) while its session has open jobs or an active task, not only until a reply lands, since a run queued behind another on the same computer starts much later (`queueBotTask` refuses a second one there, and the face then says which wait it is: `botWaitsOnComputer` picks `BotComputerBusyStatusLine` over `BotWaitingStatusLine`).
### Crew requests (`bot_asks`)
@@ -234,7 +234,7 @@ Read-only browser of every volume (`src/utils/storage-volumes.ts`: bots, workspa
- **Generation settings follow the model:** a model takes only the parameters its provider advertises (`modelAdvertisesParameter`, `src/dict/harness-parameter-dict.ts`); a custom provider's `/models` lists ids only, so its models take none and the form hides the Model settings target. The wire sends only advertised parameters (`grabChatParams`), never a value saved on another model. Switching the model or the provider clears the saved generation settings and voice (`nextHarnessModelValue` / `nextHarnessProviderValue`), so a temperature tuned for one model never rides to another that rejects it.
- **Tools:** `HarnessTool` built per run; own tools validate with zod. `run-tool-call.ts` reports errors back to the model and caps each call at the tool's `timeout_ms` (its own, else `AppData.HarnessToolTimeoutMs`; `null` means no cap, as `computer_bash` has); a `computer_*`/`browser_*` call from a run without them (a reply) is told to use `send_reply` with work, or `start_task` in a task run (`unknownToolMessage`). Bot tools in `src/harness/tools/bot/` (memory, instructions, tasks, schedules, `read_settings`, `read_message_usage`, `send_reply`, `start_task`, `hand_over_task`, `update_requester` (an interim word to the bot that asked while a crew request is open), coordinator's crew management, `delegate_task` and `hand_over_schedule`, with results relayed back by `relayJobToRequester`).
- **Extensions:** MCP servers (`mcp_servers`, remote or stdio), custom tools (`custom_tools`: http, script, prompt) and skills (`skills`, runbooks loaded with `load_skill`). Given per bot / per workspace (`botExtensionsSql`); `all_bots` only decides what new bots get. Templates `{{args.x}}`/`{{env.KEY}}` via `fillTemplate`; secrets redacted from results. A prompt-kind tool's filled template is the model's own input, so a secret env fills in as its `[KEY]` marker there, never its value (`runPromptTool`); http and script tools use secrets server-side, where the value never reaches the model. stdio servers run in a per-process pool. Skill body limits are app settings (`grabSkillBodyMaxChars`, `grabSkillBodyShownChars`). A skill proposal says what it changes (`skillProposalChanges`) to the bot and in the confirm outcome, takes no unknown keys (a misnamed `body` would re-propose the saved runbook) and is refused when it changes nothing.
- **Bots never add or repoint extensions or set envs.** The coordinator may only change what can't alter where data is sent (name, description, on/off, access); knowledgebases are the exception it fills itself, since they live on the install (see Knowledgebases). Its extension tools (`grabCoordinatorExtensionTools`) come wherever it works, a workspace as much as its own chat. New skills, servers, tools, or changes to a URL, headers, kind, config or a skill's runbook go through `propose_*` -> `extension_proposals` -> `[proposal:ID]` card, which the app describes from the config itself (never from what the bot says) and the super admin confirms (`checkProposalData` re-checks). Stdio servers are never proposed by bots (they run in the app container, which holds the docker socket).
- **Bots never add or repoint extensions or set envs.** The coordinator may only change what can't alter where data is sent (name, description, on/off, access); knowledgebases are the exception it fills itself, since they live on the install (see Knowledgebases). Its extension tools (`grabCoordinatorExtensionTools`) come wherever it works, a workspace as much as its own chat. New skills, servers, tools, or changes to a URL, headers, kind, config or a skill's runbook go through `propose_*` -> `extension_proposals` -> `[proposal:ID]` card, which the app describes from the config itself (never from what the bot says) and the super admin confirms (`checkProposalData` re-checks). A pending proposal for the same thing in the same conversation is replaced when another is made or one is confirmed (`replacePendingExtensionProposals`: a skill by `data.slug`, else the extension id, else the normalised name; `replacePendingHookProposals` by `hook_id`, then title), so a conversation carried into a new session no longer leaves a second card pending for the same skill (#41 stayed pending for ever while #42 made it, and the same target churned through #60-#63). Stdio servers are never proposed by bots (they run in the app container, which holds the docker socket).
- **Check before and after acting** (`ActionCheckNote`): look for an existing record before creating one, verify every action took effect. Tools enforce it (read-back on memory saves, duplicate checks on bots, schedules, tasks, workspaces).
### Token usage
+12 -1
View File
@@ -10,13 +10,24 @@ const base = {
describe("runCommand", () => {
test("returns output in order and the exit code", async () => {
const result = await runCommand({ ...base, command: "echo one; echo two >&2; exit 3" });
const result = await runCommand({ ...base, command: "echo one; echo two; exit 3" });
expect(result.output).toBe("one\ntwo\n");
expect(result.exit_code).toBe(3);
expect(result.timed_out).toBe(false);
});
/**
* stdout and stderr are two pipes read as they arrive, so which of
* them a line from each lands first is the scheduler's call: both come
* back, each in its own order.
*/
test("brings stderr back together with stdout", async () => {
const result = await runCommand({ ...base, command: "echo out; echo err >&2" });
expect(result.output.split("\n").filter(Boolean).sort()).toEqual(["err", "out"]);
});
test("reads no input", async () => {
const result = await runCommand({ ...base, command: "read -r line; echo \"got:$line:$?\"" });
+3 -1
View File
@@ -34,7 +34,9 @@ export type CommandResult = {
/**
* Runs one command in its own `bash -c`, in its own process group, with
* no input (a prompt fails at once instead of waiting). stdout and stderr
* come back together, in order, cut at `max_output_bytes`. Past its
* come back together, each in its own order (they are two pipes, read as
* they arrive, so neither is held back for the other), cut at
* `max_output_bytes`. Past its
* timeout (when it has one), or when aborted, the whole group gets TERM,
* then KILL 5s later. It resolves when bash exits, not when every pipe
* closes, so work left in the background (`nohup ... &`) keeps running
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "cobble",
"version": "0.24.8",
"version": "0.25.0",
"module": "index.ts",
"type": "module",
"private": true,
+10 -1
View File
@@ -5,6 +5,7 @@ import type { HarnessContentPart, HarnessMessage, HarnessToolUse } from "@/src/h
import type { BotMessageReaction, BotMessageWithAttachments } from "@/src/types";
import describeMessageRefs, { type MessageRefNames } from "@/src/utils/describe-message-refs";
import { AppRecordPrefix } from "@/src/utils/strip-app-records";
import stripCardRefs from "@/src/utils/strip-card-refs";
import describeAttachment from "./describe-attachment";
import crewMessageBlock from "@/src/utils/crew-message-block";
@@ -106,8 +107,16 @@ function messageParts({
}
const own = message.text?.trim() || "";
/**
* The refs of the app's own cards (`[question:]`, `[suggestion:]`,
* `[plan:]`) are added to a stored message after the model wrote it, so
* replaying them as the bot's own words is what taught it to write
* `[question:24]` itself (session 146, job 785). They come out of the
* bot's history here; the message the user reads keeps them.
*/
const said = role == "assistant" && own ? stripCardRefs({ text: own }) : own;
const mentions = role == "user" && refs && own ? describeMessageRefs({ text: own, names: refs }) : "";
const text = replyContext({ message, text: mentions ? `${own}\n\n${mentions}` : own });
const text = replyContext({ message, text: mentions ? `${said}\n\n${mentions}` : said });
const content: HarnessContentPart[] = text ? [{ type: "text", text }] : [];
if (role == "assistant") {
+9 -2
View File
@@ -2,7 +2,7 @@ import BunSQLite from "@moduletrace/bun-sqlite";
import type { BUN_SQLITE_COBBLE_BOTS } from "@/db/types/db";
import grabBotAudience from "@/src/functions/backend/db/access/grab-bot-audience";
import { logError } from "@/src/functions/backend/logger";
import grabActiveBotTask from "@/src/functions/backend/db/bots/grab-active-bot-task";
import grabActiveBotTasks from "@/src/functions/backend/db/bots/grab-active-bot-tasks";
import grabBotFace from "@/src/functions/backend/db/bots/grab-bot-face";
import { sendToUser } from "@/src/websocket/(functions)/send-to-user";
@@ -89,6 +89,12 @@ async function push({
for (const viewer_id of audience) {
if (users && !users.has(String(viewer_id))) continue;
/**
* Read per viewer, and every one of them: the push can't know which
* conversation is open, so the page picks its own task out.
*/
const tasks = await grabActiveBotTasks({ bot_id, user_id: viewer_id });
sendToUser({
user_id: viewer_id,
data: {
@@ -102,7 +108,8 @@ async function push({
admin_workspace_ids,
...(computer_id !== undefined ? { computer_id: computer_id || null } : {}),
...(workspace_ids !== undefined ? { workspace_ids } : {}),
task: await grabActiveBotTask({ bot_id, user_id: viewer_id }),
task: tasks[0] || null,
tasks,
},
},
});
+26
View File
@@ -6,6 +6,8 @@ import assertUserReachesTask from "@/src/functions/backend/db/tasks/assert-user-
import { taskRowSql } from "@/src/functions/backend/db/tasks/run-task-sql";
import BunSQLite from "@moduletrace/bun-sqlite";
import grabBotGraphic from "@/src/functions/backend/db/bot-graphics/grab-bot-graphic";
import grabExtensionProposal from "@/src/functions/backend/db/extension-proposals/grab-extension-proposal";
import grabHookProposal from "@/src/functions/backend/db/hook-proposals/grab-hook-proposal";
import describeToolUses from "@/src/harness/text/describe-tool-uses";
import type { HarnessToolUse } from "@/src/harness/types";
import type { ReplyStatus } from "@/src/dict/reply-status-dict";
@@ -83,6 +85,28 @@ export default async function reviewBotReply({ text, tool_uses, bot_id, user_id,
if (!(await grabBotGraphic({ graphic_id, user_id }))) missing_graphic_ids.push(graphic_id);
}
/**
* A proposal ref names the card it makes, so it only exists once that
* card does: a number the model guessed describes a proposal the user
* never got. A row made to someone else doesn't open for this user
* either, so the lookup is by user, like the file check.
*/
const missing_proposal_ids: number[] = [];
for (const proposal_id of replyRefIds({ text, kind: "proposal" })) {
const row = await grabExtensionProposal({ proposal_id, user_id }).catch(() => null);
if (!row) missing_proposal_ids.push(proposal_id);
}
const missing_hook_proposal_ids: number[] = [];
for (const proposal_id of replyRefIds({ text, kind: "hook-proposal" })) {
const row = await grabHookProposal({ proposal_id, user_id }).catch(() => null);
if (!row) missing_hook_proposal_ids.push(proposal_id);
}
/**
* The cards the app adds under the message itself: any ref of theirs in
* the answer was written by the model, since the app's own refs are
@@ -100,6 +124,8 @@ export default async function reviewBotReply({ text, tool_uses, bot_id, user_id,
missing_mentioned_task_ids,
unresolved_setting_refs: unresolvedSettingRefs({ text }),
missing_graphic_ids,
missing_proposal_ids,
missing_hook_proposal_ids,
written_card_refs,
has_open_work: await hasOpenWork({ bot_id, session_id, exclude_job_id: job_id }),
status,
+6 -5
View File
@@ -68,7 +68,8 @@ export const chatReplyNote = ({ bot_id }: { bot_id: number | string }) => `# Rep
You are chatting with the user. Answer their latest messages directly and briefly, in markdown.
- Every reply ends with send_reply. The text beside it is the message the user reads; a turn that writes text without it is a draft and is never sent.
- Every reply ends with send_reply. Write the message beside it, or pass it as its message argument; a turn that writes text without it is a draft and is never sent.
- A card's ref ([question:], [suggestion:], [plan:], [proposal:]) is written by the app from the tool that made the card, never by you. A ref you type names no card, and the user reads "not available": call ask_user, suggest_next_steps, create_plan or the propose_ tool and say in words what you mean. A proposal exists only once that tool returned one.
- send_reply({status:"done"}) for a quick answer or a small change that needs nothing after it.
- send_reply({status:"working", work:{title, instructions, computer_id?}}) for work that takes more than a moment, or anything on a computer (running commands, editing files, browsing). The app queues the run before your message goes out; a task you start is your own work, so never say you handed it to anyone else. Its result is posted here when it's done.
- send_reply({status:"blocked"}) when the work can't go on; say why in the message.
@@ -88,7 +89,7 @@ You are chatting with the user. Answer their latest messages directly and briefl
Be proactive. Follow where the conversation is heading and, once you've answered, offer the next step with ask_user, not as a question in your text: one question whose options are the concrete next steps, the one you'd suggest first and marked as suggested, e.g. "Draft the reply as well (suggested)" and "Check the other two accounts the same way". Base them on what the user is trying to get done, not on generic options, and keep it to two to four. Skip it when you've already called ask_user in this reply, when you've just queued a run (its result will offer what's next), or when the user is clearly wrapping up.
Your answer and that card go out together: send_reply is what sends the message, and ask_user or suggest_next_steps beside it in the same turn go with it. Anything else you call after writing an answer carries on the run instead, and only the last message of it is sent, so an answer written before that never reaches the user.
Your answer and that card go out together: send_reply is what sends the message, and ask_user or suggest_next_steps beside it in the same turn go with it. If the card was put up in the turn that wrote the message, that message is kept, so send_reply needs no text beside it. Anything else you call after writing an answer carries on the run instead, and only the last message of it is sent, so an answer written before that never reaches the user.
## Ending the reply
@@ -507,20 +508,20 @@ export const closingNoTextNote = `The card you just put up has no message beside
* never queued. Bounded by `AppData.HarnessReplyDraftsMax`, then the run
* fails honestly rather than sending it.
*/
export const replyDraftNote = `That message was not sent: a reply ends with send_reply, and text on its own is a draft. Write the whole message again in the same turn as send_reply: status "done" when nothing is running after it, "working" with work (or after a run you already started) when something is, or "blocked" when it can't go on. A call with no text beside it sends nothing, and an earlier draft is not filled in for you. In that same turn, and only then, call suggest_next_steps or ask_user when one of them belongs with the answer. The text beside the call is what the user reads, so finish every table, list and code fence before you send it.`;
export const replyDraftNote = `That message was not sent: a reply ends with send_reply, and text on its own is a draft. Write the whole message again in the same turn as send_reply, beside it or as its message argument: status "done" when nothing is running after it, "working" with work (or after a run you already started) when something is, or "blocked" when it can't go on. In that same turn, and only then, call suggest_next_steps or ask_user when one of them belongs with the answer. The text beside the call is what the user reads, so finish every table, list and code fence before you send it.`;
/**
* Told when `send_reply` worked but the turn said nothing beside it: the
* user would get an empty line, and the status alone is not a message.
*/
export const replyNoTextNote = `The send_reply call went through, but there is no message beside it, so nothing was sent. An earlier draft is not the message: write the whole message again beside send_reply and call it again, status "done", "working" (with work, or after a run you started) or "blocked". suggest_next_steps or ask_user may share that turn when one of them belongs with the answer. Finish every table, list and code fence in the text you write there.`;
export const replyNoTextNote = `The send_reply call went through, but there is no message beside it, so nothing was sent. Nothing written in an earlier turn is sent in its place: write the whole message again beside send_reply, or pass it as its message argument, and call it again with status "done", "working" (with work, or after a run you started) or "blocked". suggest_next_steps or ask_user may share that turn when one of them belongs with the answer. Finish every table, list and code fence in the text you write there.`;
/**
* Told when a turn tried to end without `send_reply` at all: a card alone or
* a closing tool that isn't `send_reply` doesn't say whether work is
* running, and its text is a draft.
*/
export const replyClosingRequiredNote = `That turn ended without send_reply, so no message was sent. A reply ends with send_reply and the text beside it: status "done" when nothing follows, "working" with work when something does, or "blocked" with why. A card alone doesn't say whether work is running.`;
export const replyClosingRequiredNote = `That turn ended without send_reply, so no message was sent. A reply ends with send_reply and the text beside it: status "done" when nothing follows, "working" with work when something does, or "blocked" with why. A card alone doesn't say whether work is running. A message you wrote in that same turn as the card is kept, so send_reply alone sends it.`;
/**
* Told when a turn called `send_reply` beside other tools: only its own turn
@@ -1,7 +1,8 @@
import type { BUN_SQLITE_COBBLE_BOTS_QUEUE } from "@/db/types/db";
import { BotWaitingStatusLine } from "@/src/dict/bot-queue-dict";
import { BotComputerBusyStatusLine, BotWaitingStatusLine } from "@/src/dict/bot-queue-dict";
import setBotFace from "../bots/set-bot-face";
import answeringAskFace from "./answering-ask-face";
import botWaitsOnComputer from "./bot-waits-on-computer";
import countOpenBotJobs from "./count-open-bot-jobs";
import grabRunningBotJobFace from "./grab-running-bot-job-face";
@@ -42,14 +43,16 @@ export default async function botFaceAfterJob({ bot_id, user_id, kind }: Params)
}
/**
* Jobs are open for this user but none is running (`deferBotJob` put
* them back while every model rests, or they wait in the queue): the
* bot waits, rather than showing work that isn't happening.
* Jobs are open for this user but none is running: they wait in the
* queue, behind another run on the same computer or while every model
* rests (`deferBotJob`). The line says which, since "waiting for a free
* model" over a run that is only second in line on a computer sends the
* user looking at the wrong thing.
*/
return await setBotFace({
bot_id,
user_id,
face: "asleep",
status_line: BotWaitingStatusLine,
status_line: (await botWaitsOnComputer({ bot_id, user_id })) ? BotComputerBusyStatusLine : BotWaitingStatusLine,
});
}
@@ -0,0 +1,88 @@
import { Database } from "bun:sqlite";
import { beforeEach, describe, expect, test } from "bun:test";
import { botWaitsOnComputerSql } from "./bot-waits-on-computer";
/**
* Real SQLite: the face says "Waiting for its computer" only while a run
* of this bot's user's is queued behind another task on that same
* computer. Anything looser reads every queued run as a computer wait.
*/
const db = new Database(":memory:");
beforeEach(() => {
db.run(`DROP TABLE IF EXISTS bots_queue`);
db.run(`DROP TABLE IF EXISTS bot_sessions`);
db.run(`DROP TABLE IF EXISTS bot_hooks`);
db.run(`CREATE TABLE bots_queue (
id INTEGER PRIMARY KEY,
kind TEXT,
status TEXT,
bot_id INTEGER,
session_id INTEGER,
computer_id INTEGER
)`);
db.run(`CREATE TABLE bot_sessions (id INTEGER PRIMARY KEY, user_id INTEGER, ask_id INTEGER, hook_id INTEGER)`);
db.run(`CREATE TABLE bot_hooks (id INTEGER PRIMARY KEY, silent INTEGER)`);
});
function job(row: { id: number; kind: string; status: string; session_id: number; computer_id?: number | null }) {
db.run(`INSERT INTO bots_queue (id, kind, status, bot_id, session_id, computer_id) VALUES (?, ?, ?, 1, ?, ?)`, [
row.id,
row.kind,
row.status,
row.session_id,
row.computer_id ?? null,
]);
}
const waits = () => {
const { sql, values } = botWaitsOnComputerSql({ bot_id: 1, user_id: 1 });
return db.query(sql).all(...values).length > 0;
};
describe("botWaitsOnComputerSql", () => {
test("a queued run behind a task on the same computer is waiting on it", () => {
db.run(`INSERT INTO bot_sessions VALUES (10, 1, NULL, NULL)`);
job({ id: 1, kind: "task", status: "processing", session_id: 10, computer_id: 4 });
job({ id: 2, kind: "task", status: "pending", session_id: 10, computer_id: 4 });
expect(waits()).toBe(true);
});
test("a queued run on another computer is not", () => {
db.run(`INSERT INTO bot_sessions VALUES (10, 1, NULL, NULL)`);
job({ id: 1, kind: "task", status: "processing", session_id: 10, computer_id: 4 });
job({ id: 2, kind: "task", status: "pending", session_id: 10, computer_id: 5 });
expect(waits()).toBe(false);
});
test("no reason yet is not a computer wait", () => {
db.run(`INSERT INTO bot_sessions VALUES (10, 1, NULL, NULL)`);
job({ id: 1, kind: "task", status: "processing", session_id: 10, computer_id: 4 });
job({ id: 2, kind: "reply", status: "pending", session_id: 10, computer_id: null });
expect(waits()).toBe(false);
});
test("another user's queue does not show on this face", () => {
db.run(`INSERT INTO bot_sessions VALUES (10, 2, NULL, NULL)`);
job({ id: 1, kind: "task", status: "processing", session_id: 10, computer_id: 4 });
job({ id: 2, kind: "task", status: "pending", session_id: 10, computer_id: 4 });
expect(waits()).toBe(false);
});
test("a queued run in a crew request or a silent hook's thread is not the user's wait", () => {
db.run(`INSERT INTO bot_sessions VALUES (10, 1, NULL, NULL)`);
db.run(`INSERT INTO bot_sessions VALUES (11, 1, 3, NULL)`);
db.run(`INSERT INTO bot_hooks VALUES (2, 1)`);
db.run(`INSERT INTO bot_sessions VALUES (12, 1, NULL, 2)`);
job({ id: 1, kind: "task", status: "processing", session_id: 10, computer_id: 4 });
job({ id: 2, kind: "task", status: "pending", session_id: 11, computer_id: 4 });
job({ id: 3, kind: "task", status: "pending", session_id: 12, computer_id: 4 });
expect(waits()).toBe(false);
});
});
@@ -0,0 +1,43 @@
import BunSQLite from "@moduletrace/bun-sqlite";
import followedSessionSql from "../bot-sessions/followed-session-sql";
type Params = {
bot_id: number | string;
/**
* Only jobs in this user's conversations.
*/
user_id: number | string;
};
/**
* Whether a run of the bot's is queued behind another on the same computer.
* `claimBotJobs` takes one task run per computer at a time, so a second one
* waits for the first to end, however long that takes: with no job
* processing, the bot's face said "waiting for a free model" when what it
* waits on is the computer. Only jobs the user follows count, since a crew
* request's or a silent hook's run never shows on the face.
*/
export default async function botWaitsOnComputer({ bot_id, user_id }: Params): Promise<boolean> {
const res = await BunSQLite.sql<{ waiting: number }>(botWaitsOnComputerSql({ bot_id, user_id }));
return Boolean(res.payload?.[0]?.waiting);
}
/**
* The statement itself, checked against real SQLite
* (`bot-waits-on-computer.test.ts`).
*/
export function botWaitsOnComputerSql({ bot_id, user_id }: Params) {
return {
sql: `SELECT 1 AS waiting FROM bots_queue AS queued
WHERE queued.bot_id = ? AND queued.status = 'pending'
AND queued.session_id IN (SELECT id FROM bot_sessions WHERE user_id = ? AND ${followedSessionSql()})
AND EXISTS (
SELECT 1 FROM bots_queue AS running
WHERE running.status = 'processing' AND running.kind = 'task'
AND running.computer_id = queued.computer_id
)
LIMIT 1`,
values: [bot_id, user_id],
};
}
@@ -9,6 +9,8 @@ import AppError from "@/src/utils/app-error";
import grabUserBot from "../bots/grab-user-bot";
import grabBotComputers from "../computers/grab-bot-computers";
import grabUserBotSession from "../bot-sessions/grab-user-bot-session";
import wakeBotsQueue from "@/src/bots-queue/wake-bots-queue";
import pushBotUpdated from "@/src/bots-queue/push-bot-updated";
type Params = {
/**
@@ -160,6 +162,18 @@ export default async function enqueueBotJob({
throw new Error(`Couldn't queue the job: ${res.msg || res.error}`);
}
/**
* The queue starts on this job now instead of at its next tick, and the
* user is told about the run straight away: the bot's face and every
* active task are pushed, so a queued run shows as one instead of
* appearing when the queue happens to claim it (a run waiting behind
* another on the same computer waits for that one to end). Best effort:
* the push logs its own failure, and a queue not running in this process
* picks the job up on its next poll.
*/
wakeBotsQueue();
await pushBotUpdated({ bot_id: Number(bot.id), user_id: Number(user_id) });
return job_id;
}
@@ -25,9 +25,8 @@ type Params = {
/**
* Wraps up a job that is out of attempts: stamps `finished_at` (so it's
* reported once), tells the user in the bot's conversation and sets the
* bot to needs-you for that user. Its task stays active, since the work isn't done. A
* handed-over job's failure also goes to the bot that handed it over, and
* reported once), closes its own `bot_tasks` row, tells the user in the
* bot's conversation and sets the bot to needs-you for that user. A handed-over job's failure also goes to the bot that handed it over, and
* blocks the handed-over task it worked on (`noteTrackerTask`). A hook run's
* calls keep why it failed (`recordHookCallResponse`). A job working a crew request ends it
* (`onAskJobEnded`) and leaves the bot's face alone.
@@ -45,6 +44,20 @@ export default async function notifyBotJobFailed({
values: [Date.now(), job.id],
});
/**
* The run's own row is over too: left active it is the task every read
* of `grabActiveBotTask` returns for that user, so the conversation
* keeps showing a run that ended (one failed task in October was still
* the active task of its conversation months later), and no later run's
* progress could show in its place.
*/
if (job.task_id) {
await BunSQLite.sql({
sql: `UPDATE bot_tasks SET status = 'done', updated_at = ? WHERE id = ?`,
values: [Date.now(), job.task_id],
});
}
/**
* A handed-over task's failed run links to that task.
*/
@@ -1,10 +1,7 @@
import type {
BUN_SQLITE_COBBLE_BOT_TASK_STEPS,
BUN_SQLITE_COBBLE_BOT_TASKS,
} from "@/db/types/db";
import type { BUN_SQLITE_COBBLE_BOT_TASKS } from "@/db/types/db";
import type { BotTaskWithSteps } from "@/src/types";
import BunSQLite from "@moduletrace/bun-sqlite";
import grabBotJobUpdates from "../bots-queue/grab-bot-job-updates";
import withBotTaskSteps from "./with-bot-task-steps";
type Params = {
bot_id: number | string;
@@ -21,7 +18,9 @@ type Params = {
/**
* The bot's most recent active task (in one session or one user's
* conversations, when given), its
* steps and what its job has done so far, for the working-on panel.
* steps and what its job has done so far, for the working-on panel. A push
* sends every active task instead (`grabActiveBotTasks`), since this one
* may belong to a conversation the viewer isn't reading.
*/
export default async function grabActiveBotTask({
bot_id,
@@ -42,14 +41,5 @@ export default async function grabActiveBotTask({
return null;
}
const steps_res = await BunSQLite.sql<BUN_SQLITE_COBBLE_BOT_TASK_STEPS>({
sql: `SELECT * FROM bot_task_steps WHERE task_id = ? ORDER BY position ASC, id ASC`,
values: [task.id],
});
return {
...task,
steps: steps_res.payload || [],
updates: await grabBotJobUpdates({ task_id: task.id }),
};
}
return withBotTaskSteps({ task });
}
@@ -0,0 +1,40 @@
import type { BUN_SQLITE_COBBLE_BOT_TASKS } from "@/db/types/db";
import type { BotTaskWithSteps } from "@/src/types";
import BunSQLite from "@moduletrace/bun-sqlite";
import withBotTaskSteps from "./with-bot-task-steps";
type Params = {
bot_id: number | string;
/**
* Only tasks in this user's conversations.
*/
user_id?: number | string | null;
};
/**
* How many active tasks a push carries. A bot has at most one run per
* computer and one reply per session, so a handful of conversations are
* ever running at once; the newest few are enough for a viewer to find its
* own, and a list that grows with the whole crew's history is not.
*/
const BotActiveTasksShown = 10;
/**
* Every active task the user has with the bot, newest first. A push can't
* know which conversation the viewer is looking at, and sending only the
* newest left the one they were reading with no task at all whenever
* another run was open elsewhere (`use-task-progress` drops a task from
* another session), so the page is sent them all and picks its own.
*/
export default async function grabActiveBotTasks({ bot_id, user_id }: Params): Promise<BotTaskWithSteps[]> {
const res = await BunSQLite.sql<BUN_SQLITE_COBBLE_BOT_TASKS>({
sql: `SELECT * FROM bot_tasks WHERE bot_id = ? AND status = 'active'
${user_id ? `AND session_id IN (SELECT id FROM bot_sessions WHERE user_id = ?)` : ""}
ORDER BY created_at DESC, id DESC LIMIT ${BotActiveTasksShown}`,
values: [bot_id, ...(user_id ? [user_id] : [])],
});
const tasks = res.payload || [];
return await Promise.all(tasks.map((task) => withBotTaskSteps({ task })));
}
@@ -0,0 +1,26 @@
import type { BUN_SQLITE_COBBLE_BOT_TASK_STEPS, BUN_SQLITE_COBBLE_BOT_TASKS } from "@/db/types/db";
import type { BotTaskWithSteps } from "@/src/types";
import BunSQLite from "@moduletrace/bun-sqlite";
import grabBotJobUpdates from "../bots-queue/grab-bot-job-updates";
type Params = {
task: BUN_SQLITE_COBBLE_BOT_TASKS;
};
/**
* A `bot_tasks` row with its steps and what its job has done so far, for
* the working-on panel: what one active task is read as, whether it's the
* newest of its bot or one of several in different conversations.
*/
export default async function withBotTaskSteps({ task }: Params): Promise<BotTaskWithSteps> {
const steps_res = await BunSQLite.sql<BUN_SQLITE_COBBLE_BOT_TASK_STEPS>({
sql: `SELECT * FROM bot_task_steps WHERE task_id = ? ORDER BY position ASC, id ASC`,
values: [Number(task.id)],
});
return {
...task,
steps: steps_res.payload || [],
updates: await grabBotJobUpdates({ task_id: Number(task.id) }),
};
}
@@ -15,6 +15,7 @@ import checkProposalData from "./check-proposal-data";
import claimExtensionProposal from "./claim-extension-proposal";
import grabExtensionProposal from "./grab-extension-proposal";
import grabProposalEnvs from "./grab-proposal-envs";
import replacePendingExtensionProposals from "./replace-pending-extension-proposals";
type Params = {
user_id: number | string;
@@ -34,6 +35,24 @@ export default async function confirmExtensionProposal({ user_id, proposal_id }:
await claimExtensionProposal({ proposal, status: "confirmed" });
/**
* Every other pending card for the same thing is replaced now that one
* was confirmed: a card left pending can still be pressed, and its
* outcome is already written (proposal #41 dangled a day after #42
* made the same skill).
*/
await replacePendingExtensionProposals({
proposal_id: proposal.id,
user_id: proposal.user_id,
bot_id: proposal.bot_id,
workspace_id: proposal.workspace_id,
kind: proposal.kind,
slug: proposal.kind == "skill" ? proposal.data.slug : null,
extension_id: proposal.extension_id,
name: proposal.data.name,
reason: `Replaced by proposal #${proposal.id}, which was confirmed.`,
});
try {
if (proposal.kind == "skill") {
const current = proposal.extension_id ? await grabSkill({ skill_id: proposal.extension_id }) : null;
@@ -3,6 +3,7 @@ import type { BUN_SQLITE_COBBLE_EXTENSION_PROPOSALS, BunSQLiteTables } from "@/d
import { AppData } from "@/src/data/app-data";
import type { SaveCustomToolRequest, SaveMcpServerRequest, SaveSkillRequest } from "@/src/schemas/extension-schema";
import checkProposalData from "./check-proposal-data";
import replacePendingExtensionProposals from "./replace-pending-extension-proposals";
type Params = {
user_id: number | string;
@@ -21,9 +22,9 @@ type Params = {
* Stores what a bot proposes adding or changing (an MCP server, a tool or
* a skill), pending until the user
* confirms it from the chat. Nothing is saved, connected or run here. A
* proposal it makes again for the same server or tool in the same
* conversation replaces the one before, so only the latest card can be
* confirmed. Returns its id.
* proposal it makes again for the same thing in the same conversation
* replaces the one before, so only the latest card can be confirmed.
* Returns its id.
*/
export default async function createExtensionProposal(params: Params) {
if (params.kind != "skill") checkProposalData(params);
@@ -61,19 +62,15 @@ export default async function createExtensionProposal(params: Params) {
if (!res.success || !id) throw new Error(`Couldn't store the proposal: ${res.msg}`);
await BunSQLite.sql({
sql: `UPDATE extension_proposals SET status = 'replaced', outcome = ?, decided_at = ?, updated_at = ?
WHERE session_id = ? AND kind = ? AND status = 'pending' AND id != ?
AND (${extension_id ? "extension_id = ?" : "extension_id IS NULL AND name = ? COLLATE NOCASE"})`,
values: [
`Replaced by proposal #${id}.`,
now,
now,
Number(params.session_id),
params.kind,
id,
extension_id || params.data.name,
],
await replacePendingExtensionProposals({
proposal_id: id,
user_id: params.user_id,
bot_id: params.bot_id,
workspace_id: params.workspace_id,
kind: params.kind,
slug: params.kind == "skill" ? params.data.slug : null,
extension_id,
name: params.data.name,
});
return id;
@@ -28,6 +28,7 @@ export type ExtensionProposalRecord = {
user_id: number;
bot_id: number;
session_id: number;
workspace_id: number | null;
} & (
| { kind: "mcp"; data: SaveMcpServerRequest }
| { kind: "tool"; data: SaveCustomToolRequest }
@@ -54,6 +55,7 @@ export default function parseProposalRow({ row }: Params): ExtensionProposalReco
user_id: Number(row.user_id),
bot_id: Number(row.bot_id),
session_id: Number(row.session_id),
workspace_id: row.workspace_id ? Number(row.workspace_id) : null,
};
if (kind == "mcp") return { ...base, kind, data: parseWithSchema({ schema: SaveMcpServerRequestSchema, data: raw }) };
@@ -0,0 +1,145 @@
import { Database, type SQLQueryBindings } from "bun:sqlite";
import { describe, expect, test } from "bun:test";
import { replacePendingExtensionProposalsSql } from "./replace-pending-extension-proposals";
/**
* Run against real SQLite: the point of the statement is which rows it
* leaves alone. Production kept proposal #41 (Co-Marketing, session 145)
* pending for ever while #42 made the same skill in session 146, and
* RevOps was proposed four times under two names, all slug `revops`.
*/
function fresh() {
const db = new Database(":memory:");
db.run(`CREATE TABLE extension_proposals (
id INTEGER PRIMARY KEY,
name TEXT,
data TEXT,
extension_id INTEGER,
kind TEXT,
status TEXT,
outcome TEXT,
decided_at INTEGER,
updated_at INTEGER,
user_id INTEGER,
bot_id INTEGER,
session_id INTEGER,
workspace_id INTEGER
)`);
const insert = db.prepare(`INSERT INTO extension_proposals
(id, name, data, extension_id, kind, status, user_id, bot_id, session_id, workspace_id)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`);
insert.run(41, "Co-Marketing", `{"slug":"co-marketing"}`, null, "skill", "pending", 1, 1, 145, null);
insert.run(42, "Co-Marketing", `{"slug":"co-marketing"}`, null, "skill", "confirmed", 1, 1, 146, null);
insert.run(43, "Referrals & Affiliates", `{"slug":"referrals"}`, null, "skill", "confirmed", 1, 1, 145, null);
insert.run(44, "Referrals", `{"slug":"referrals"}`, null, "skill", "failed", 1, 1, 146, null);
insert.run(62, "RevOps", `{"slug":"revops"}`, null, "skill", "pending", 1, 1, 146, null);
insert.run(63, "Revenue Operations (RevOps)", `{"slug":"revops"}`, null, "skill", "confirmed", 1, 1, 146, null);
insert.run(70, "Lead Magnets", `{"slug":"lead-magnets"}`, null, "skill", "pending", 1, 1, 146, null);
insert.run(71, "Link Building", `{"slug":"link-building"}`, 12, "skill", "pending", 1, 1, 146, null);
insert.run(72, "Some Server", `{}`, null, "mcp", "pending", 1, 1, 146, null);
insert.run(73, "Some Server", `{}`, null, "mcp", "pending", 2, 1, 146, null);
insert.run(74, "Some Server", `{}`, null, "mcp", "pending", 1, 1, 146, 3);
insert.run(75, "Fetch Tool", `{}`, null, "tool", "pending", 1, 1, 146, null);
insert.run(76, "Changed Tool", `{}`, 9, "tool", "pending", 1, 1, 146, null);
insert.run(77, "Another Tool", `{}`, 10, "tool", "pending", 1, 1, 146, null);
return db;
}
function replace(
db: Database,
params: Parameters<typeof replacePendingExtensionProposalsSql>[0],
) {
const { sql, values } = replacePendingExtensionProposalsSql(params);
db.run(sql, values as SQLQueryBindings[]);
}
const statuses = (db: Database) =>
Object.fromEntries(
(db.query(`SELECT id, status FROM extension_proposals`).all() as { id: number; status: string }[]).map((row) => [
row.id,
row.status,
]),
);
describe("replacePendingExtensionProposalsSql", () => {
test("replaces a skill proposed again in a later session of the same conversation", () => {
const db = fresh();
replace(db, {
proposal_id: 63,
user_id: 1,
bot_id: 1,
kind: "skill",
slug: "revops",
name: "Revenue Operations (RevOps)",
});
const status = statuses(db);
expect(status[62]).toBe("replaced");
expect(status[63]).toBe("confirmed");
expect(status[70]).toBe("pending");
expect(status[41]).toBe("pending");
});
test("does not mark a skill's proposal replaced by another skill's", () => {
const db = fresh();
replace(db, {
proposal_id: 70,
user_id: 1,
bot_id: 1,
kind: "skill",
slug: "lead-magnets",
name: "Lead Magnets",
});
const status = statuses(db);
expect(status[62]).toBe("pending");
expect(status[71]).toBe("pending");
expect(Object.values(status).filter((value) => value == "replaced")).toEqual([]);
});
test("a server compares the name when the proposal changes nothing yet", () => {
const db = fresh();
replace(db, {
proposal_id: 78,
user_id: 1,
bot_id: 1,
kind: "mcp",
name: "Some Server",
});
const status = statuses(db);
expect(status[72]).toBe("replaced");
expect(status[73]).toBe("pending");
expect(status[74]).toBe("pending");
});
test("a tool compares the extension it changes", () => {
const db = fresh();
replace(db, {
proposal_id: 78,
user_id: 1,
bot_id: 1,
kind: "tool",
extension_id: 9,
name: "Changed Tool",
});
const status = statuses(db);
expect(status[76]).toBe("replaced");
expect(status[75]).toBe("pending");
expect(status[77]).toBe("pending");
});
});
@@ -0,0 +1,122 @@
import BunSQLite from "@moduletrace/bun-sqlite";
type Params = {
/** The proposal just stored, or just confirmed. */
proposal_id: number | string;
user_id: number | string;
bot_id: number | string;
workspace_id?: number | string | null;
kind: "mcp" | "tool" | "skill";
/**
* A skill's slug: it names the one skill a proposal is about, including
* one that doesn't exist yet, and is what makes two of them the same.
*/
slug?: string | null;
/**
* The extension a proposal changes; a new one has none.
*/
extension_id?: number | string | null;
name: string;
/**
* What the replaced card says, when it wasn't a newer proposal that
* took its place.
*/
reason?: string;
};
/**
* Marks every pending proposal for the same thing replaced, in the same
* conversation: only the latest card can be confirmed, and an older one
* left pending is a card the user can still press whose outcome is already
* written. Scoped by user, bot and workspace rather than by session, since
* a conversation that carries on into a new session keeps proposing into
* it: proposal #41 (Co-Marketing, session 145) was made again 36 seconds
* later in session 146 and confirmed there, and #41 stayed pending for
* ever. For a skill the slug decides it (RevOps was proposed four times
* under two names, all slug `revops`); for a server or tool it is the
* extension itself, else the name.
*/
export default async function replacePendingExtensionProposals({
proposal_id,
user_id,
bot_id,
workspace_id,
kind,
slug,
extension_id,
name,
reason,
}: Params) {
const { sql, values } = replacePendingExtensionProposalsSql({
proposal_id,
user_id,
bot_id,
workspace_id,
kind,
slug,
extension_id,
name,
reason,
});
await BunSQLite.sql({ sql, values });
}
/**
* The statement itself, so the conditions are checked against real SQLite
* (`replace-pending-extension-proposals.test.ts`): a wrong one either
* leaves a card the user can still press or replaces a different skill's.
*/
export function replacePendingExtensionProposalsSql({
proposal_id,
user_id,
bot_id,
workspace_id,
kind,
slug,
extension_id,
name,
reason,
}: Params) {
const now = Date.now();
const target = targetSql({ slug, extension_id, name });
return {
sql: `UPDATE extension_proposals SET status = 'replaced', outcome = ?, decided_at = ?, updated_at = ?
WHERE user_id = ? AND bot_id = ? AND COALESCE(workspace_id, 0) = ? AND kind = ?
AND status = 'pending' AND id != ?
AND ${target.sql}`,
values: [
reason || `Replaced by proposal #${proposal_id}.`,
now,
now,
Number(user_id),
Number(bot_id),
Number(workspace_id) || 0,
kind,
Number(proposal_id),
target.value,
],
};
}
/**
* What makes two proposals about the same thing: a skill's slug, the
* extension being changed, or a new one's name compared with spaces,
* hyphens and underscores taken out ("Rev Ops" and "rev-ops" are one name).
*/
function targetSql({ slug, extension_id, name }: { slug?: string | null; extension_id?: number | string | null; name: string }) {
const skill_slug = slug?.trim().toLowerCase() || "";
if (skill_slug) return { sql: "lower(json_extract(data, '$.slug')) = ?", value: skill_slug };
if (extension_id) return { sql: "extension_id = ?", value: Number(extension_id) };
return {
sql: "extension_id IS NULL AND lower(replace(replace(replace(trim(name), ' ', ''), '-', ''), '_', '')) = ?",
value: name
.trim()
.toLowerCase()
.replace(/[ _-]+/g, ""),
};
}
@@ -6,6 +6,7 @@ import updateBotHook from "../bot-hooks/update-bot-hook";
import checkHookProposal from "./check-hook-proposal";
import claimHookProposal from "./claim-hook-proposal";
import grabHookProposal from "./grab-hook-proposal";
import replacePendingHookProposals from "./replace-pending-hook-proposals";
type Params = {
user_id: number | string;
@@ -27,6 +28,16 @@ export default async function confirmHookProposal({ user_id, proposal_id }: Para
await claimHookProposal({ proposal, status: "confirmed" });
await replacePendingHookProposals({
proposal_id: proposal.id,
user_id: proposal.user_id,
bot_id: proposal.bot_id,
workspace_id: proposal.workspace_id,
hook_id: proposal.hook_id,
title: proposal.title,
reason: `Replaced by proposal #${proposal.id}, which was confirmed.`,
});
let token: string | undefined;
try {
@@ -3,6 +3,7 @@ import type { BUN_SQLITE_COBBLE_HOOK_PROPOSALS, BunSQLiteTables } from "@/db/typ
import { AppData } from "@/src/data/app-data";
import type { HookProposalData } from "@/src/schemas/bot-hook-schema";
import checkHookProposal from "./check-hook-proposal";
import replacePendingHookProposals from "./replace-pending-hook-proposals";
type Params = {
user_id: number | string;
@@ -60,18 +61,13 @@ export default async function createHookProposal({
if (!res.success || !id) throw new Error(`Couldn't store the proposal: ${res.msg}`);
await BunSQLite.sql({
sql: `UPDATE hook_proposals SET status = 'replaced', outcome = ?, decided_at = ?, updated_at = ?
WHERE session_id = ? AND status = 'pending' AND id != ?
AND (${checked.current?.id ? "hook_id = ?" : "hook_id IS NULL AND title = ? COLLATE NOCASE"})`,
values: [
`Replaced by proposal #${id}.`,
now,
now,
Number(session_id),
id,
checked.current?.id || checked.title,
],
await replacePendingHookProposals({
proposal_id: id,
user_id,
bot_id,
workspace_id,
hook_id: checked.current?.id,
title: checked.title,
});
return id;
@@ -0,0 +1,81 @@
import { Database, type SQLQueryBindings } from "bun:sqlite";
import { describe, expect, test } from "bun:test";
import { replacePendingHookProposalsSql } from "./replace-pending-hook-proposals";
/**
* A conversation carried into a new session keeps proposing into it, so a
* pending card for the same hook (or the same new name) is marked replaced
* across sessions, never left for the user to press after its outcome was
* written.
*/
function fresh() {
const db = new Database(":memory:");
db.run(`CREATE TABLE hook_proposals (
id INTEGER PRIMARY KEY,
hook_id INTEGER,
title TEXT,
status TEXT,
outcome TEXT,
decided_at INTEGER,
updated_at INTEGER,
user_id INTEGER,
bot_id INTEGER,
session_id INTEGER,
workspace_id INTEGER
)`);
const insert = db.prepare(`INSERT INTO hook_proposals
(id, hook_id, title, status, user_id, bot_id, session_id, workspace_id)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)`);
insert.run(1, null, "Inbox Digest", "pending", 1, 1, 145, null);
insert.run(2, null, "inbox digest", "pending", 1, 1, 146, null);
insert.run(3, null, "Inbox Digest", "confirmed", 1, 1, 146, null);
insert.run(4, 7, "Nightly Build", "pending", 1, 1, 146, null);
insert.run(5, 8, "Nightly Build", "pending", 1, 1, 146, null);
insert.run(6, null, "Inbox Digest", "pending", 2, 1, 146, null);
return db;
}
function replace(db: Database, params: Parameters<typeof replacePendingHookProposalsSql>[0]) {
const { sql, values } = replacePendingHookProposalsSql(params);
db.run(sql, values as SQLQueryBindings[]);
}
const statuses = (db: Database) =>
Object.fromEntries(
(db.query(`SELECT id, status FROM hook_proposals`).all() as { id: number; status: string }[]).map((row) => [
row.id,
row.status,
]),
);
describe("replacePendingHookProposalsSql", () => {
test("replaces a new hook proposed again under the same name in a later session", () => {
const db = fresh();
replace(db, { proposal_id: 2, user_id: 1, bot_id: 1, title: "inbox digest" });
const status = statuses(db);
expect(status[1]).toBe("replaced");
expect(status[3]).toBe("confirmed");
expect(status[6]).toBe("pending");
expect(status[4]).toBe("pending");
});
test("a hook that exists is compared by the hook, not by its title", () => {
const db = fresh();
replace(db, { proposal_id: 9, user_id: 1, bot_id: 1, hook_id: 7, title: "Nightly Build" });
const status = statuses(db);
expect(status[4]).toBe("replaced");
expect(status[5]).toBe("pending");
expect(status[1]).toBe("pending");
});
});
@@ -0,0 +1,79 @@
import BunSQLite from "@moduletrace/bun-sqlite";
type Params = {
/** The proposal just stored, or just confirmed. */
proposal_id: number | string;
user_id: number | string;
bot_id: number | string;
workspace_id?: number | string | null;
/**
* The hook it changes; none for a new one.
*/
hook_id?: number | string | null;
title: string;
/**
* What the replaced card says, when it wasn't a newer proposal that
* took its place.
*/
reason?: string;
};
/**
* Marks every pending hook proposal for the same hook, or the same new
* name, replaced: only the latest card can be confirmed. Scoped by user,
* bot and workspace rather than by session, the same way an extension
* proposal is (`replacePendingExtensionProposals`), since a conversation
* carried into a new session keeps proposing into it.
*/
export default async function replacePendingHookProposals({
proposal_id,
user_id,
bot_id,
workspace_id,
hook_id,
title,
reason,
}: Params) {
await BunSQLite.sql(
replacePendingHookProposalsSql({ proposal_id, user_id, bot_id, workspace_id, hook_id, title, reason }),
);
}
/**
* The statement itself, checked against real SQLite
* (`replace-pending-hook-proposals.test.ts`).
*/
export function replacePendingHookProposalsSql({
proposal_id,
user_id,
bot_id,
workspace_id,
hook_id,
title,
reason,
}: Params) {
const now = Date.now();
const changed = Boolean(Number(hook_id));
return {
sql: `UPDATE hook_proposals SET status = 'replaced', outcome = ?, decided_at = ?, updated_at = ?
WHERE user_id = ? AND bot_id = ? AND COALESCE(workspace_id, 0) = ?
AND status = 'pending' AND id != ?
AND (${changed ? "hook_id = ?" : "hook_id IS NULL AND lower(replace(replace(replace(trim(title), ' ', ''), '-', ''), '_', '')) = ?"})`,
values: [
reason || `Replaced by proposal #${proposal_id}.`,
now,
now,
Number(user_id),
Number(bot_id),
Number(workspace_id) || 0,
Number(proposal_id),
changed
? Number(hook_id)
: title
.trim()
.toLowerCase()
.replace(/[ _-]+/g, ""),
],
};
}
@@ -29,10 +29,6 @@ mock.module("./provider-request", () => ({
},
}));
mock.module("../grab-provider-preset", () => ({
default: () => ({ title: "TestProvider", video_path: "/videos" }),
}));
const { default: generateVideo } = await import("./generate-video");
afterAll(() => mock.restore());
+123 -2
View File
@@ -1786,12 +1786,14 @@ describe("runTextLoop closing tools", () => {
});
describe("runTextLoop required send_reply", () => {
const sendReply: HarnessTool<{ status: "done" | "working" | "blocked"; work?: unknown }> = {
const sendReply: HarnessTool<{ status?: "done" | "working" | "blocked"; work?: unknown; message?: string; text?: string }> = {
name: "send_reply",
description: "Sends the message.",
schema: z.object({
status: z.enum(["done", "working", "blocked"]),
status: z.enum(["done", "working", "blocked"]).optional(),
work: z.unknown().optional(),
message: z.string().optional(),
text: z.string().optional(),
}),
run: async () => "Sent.",
};
@@ -2165,6 +2167,125 @@ describe("runTextLoop required send_reply", () => {
expect(seen[1]!.tools!.map((tool) => tool.name)).toEqual(["send_reply"]);
expect(result.text).toBe("Report.");
});
test("send_reply with text in tool arguments sends the message directly", async () => {
const { generate } = scripted([
{
tool_calls: [
{
id: "s1",
name: "send_reply",
arguments: JSON.stringify({ status: "done", text: "Here is your skill." }),
},
],
},
]);
const result = await runTextLoop({
system: "s",
messages: [{ role: "user", content: "Install skill." }],
tools: [sendReply],
generate,
resolveCandidates,
require_closing_answer: true,
});
expect(result.text).toBe("Here is your skill.");
expect(result.steps).toBe(1);
});
test("send_reply with message in tool arguments and no status defaults to done and sends the message", async () => {
const { generate } = scripted([
{
tool_calls: [
{
id: "s1",
name: "send_reply",
arguments: JSON.stringify({ message: "Link-building next, as you picked." }),
},
],
},
]);
const result = await runTextLoop({
system: "s",
messages: [{ role: "user", content: "What next?" }],
tools: [sendReply],
generate,
resolveCandidates,
require_closing_answer: true,
});
expect(result.text).toBe("Link-building next, as you picked.");
expect(result.steps).toBe(1);
});
test("a message written beside a card goes out when send_reply follows alone", async () => {
/**
* Session 146, job 795: the model wrote the whole answer in the
* turn that put the question up, the loop asked for `send_reply`,
* and the next turn had nothing left to say. The sentence beside
* the card is that card's sentence, so it is kept.
*/
asked.length = 0;
const { generate } = scripted([
{
text: "RevOps is proposed. Which skill should I take next?",
tool_calls: [{ id: "q1", name: "ask_user", arguments: `{"question":"Which skill next?"}` }],
},
{ tool_calls: [{ id: "s1", name: "send_reply", arguments: `{"status":"done"}` }] },
]);
const result = await runTextLoop({
system: "s",
messages: [{ role: "user", content: "Propose RevOps, then ask me." }],
tools: [askUser, sendReply],
generate,
resolveCandidates,
require_closing_answer: true,
});
expect(result.text).toBe("RevOps is proposed. Which skill should I take next?");
expect(result.steps).toBe(2);
expect(asked).toEqual(["Which skill next?"]);
});
test("an answer the review sends back is never carried a second time", async () => {
/**
* Session 146, job 785: the refused draft stayed held, so every
* later bare `send_reply` re-sent the same faulted text and used up
* the whole rewrite budget. It is dropped with the refusal.
*/
const reviewed: string[] = [];
const notes = ["You named [proposal:999], which was never made."];
const { generate } = scripted([
{ text: "Proposed [proposal:999] for you." },
{ tool_calls: [{ id: "s1", name: "send_reply", arguments: `{"status":"done"}` }] },
{ tool_calls: [{ id: "s2", name: "send_reply", arguments: `{"status":"done"}` }] },
{
text: "The proposal is up for you.",
tool_calls: [{ id: "s3", name: "send_reply", arguments: `{"status":"done"}` }],
},
]);
const result = await runTextLoop({
system: "s",
messages: [{ role: "user", content: "Propose it." }],
tools: [sendReply],
generate,
resolveCandidates,
require_closing_answer: true,
review: async ({ text }) => {
reviewed.push(text);
return notes.shift() || null;
},
});
expect(result.text).toBe("The proposal is up for you.");
expect(result.steps).toBe(4);
expect(reviewed).toEqual(["Proposed [proposal:999] for you.", "The proposal is up for you."]);
});
});
describe("runTextLoop answer not sent", () => {
+89 -9
View File
@@ -301,15 +301,35 @@ const wrapUpToolsPrompt = ({
};
/**
* The status a `send_reply` call declared, for the review: a call whose
* arguments don't parse or name an unknown status is left undefined, and
* the tool's own schema refuses it before this matters.
* The status a `send_reply` call declared, for the review: defaults to "working"
* when work is passed, otherwise "done". A call whose arguments don't parse or name an
* unknown status is left undefined.
*/
const replyStatusFromCall = ({ call }: { call: HarnessToolCall }): ReplyStatus | undefined => {
try {
const args = JSON.parse(call.arguments || "{}");
const status = args?.status || (args?.work ? "working" : "done");
return ReplyStatuses.includes(args?.status) ? (args.status as ReplyStatus) : undefined;
return ReplyStatuses.includes(status) ? (status as ReplyStatus) : undefined;
} catch {
return undefined;
}
};
/**
* Message or text passed in send_reply's arguments, when the model placed the
* reply content in the tool call rather than assistant prose.
*/
const replyTextFromCall = ({ call }: { call: HarnessToolCall }): string | undefined => {
try {
const args = JSON.parse(call.arguments || "{}");
if (typeof args?.message === "string" && args.message.trim()) {
return args.message.trim();
}
if (typeof args?.text === "string" && args.text.trim()) {
return args.text.trim();
}
return undefined;
} catch {
return undefined;
}
@@ -533,6 +553,16 @@ export default async function runTextLoop({
* left for the follow-up (session 130, message 874).
*/
let draft_text = "";
/**
* The message a turn wrote beside a card but without `send_reply`
* (`closing_required`). That prose is the sentence the card belongs
* under, not a draft about something else, so a later bare `send_reply`
* carries it instead of making the model write the whole answer again.
* Session 146 lost six answers this way: the text went out with
* `ask_user`, the loop asked for `send_reply`, and the next turn had
* nothing left to say.
*/
let card_text = "";
/**
* A run whose prompt no longer fits the working context, with nothing
* trimmable left, has been told, once (`oversizedRequestNote`).
@@ -800,6 +830,11 @@ export default async function runTextLoop({
const tool_calls = offered.filter((call) => !wrap_up || wrap_tools.some((tool) => tool.name == call.name));
const reply_call = tool_calls.filter((call) => call.name === SendReplyToolName).at(-1);
const reply_status = reply_call ? replyStatusFromCall({ call: reply_call }) : undefined;
const call_text = reply_call ? replyTextFromCall({ call: reply_call }) : undefined;
if (!answer.text && call_text) {
answer.text = call_text;
}
/**
* What the app would never show as its own word comes out before
@@ -913,6 +948,7 @@ export default async function runTextLoop({
if (!(wrap_up && !wrap_up_saving) && reply_drafts < AppData.HarnessReplyDraftsMax) {
reply_drafts += 1;
draft_text = answer.text || "";
card_text = "";
pushUserTurn({ transcript, content: replyDraftNote });
await traced({ kind: "event", index, name: "reply_draft", text: replyDraftNote });
continue;
@@ -982,7 +1018,20 @@ export default async function runTextLoop({
};
}
if (check.verdict === "sent_back") continue;
if (check.verdict === "sent_back") {
/**
* The answer is being written again, so nothing held from
* the refused one may go out in its place: a draft or a
* card's sentence re-sent unchanged is a fault again, and
* three of those cost the user the answer (session 146).
* The reminder flag goes with it, so the rewrite can be
* told to write beside the call once more.
*/
draft_text = "";
card_text = "";
told_closing_text = false;
continue;
}
/**
* A wrap-up rewrite the review let through is the answer. The
@@ -1163,7 +1212,7 @@ export default async function runTextLoop({
* has been told to write it again and still sent nothing, and only
* when that draft is a finished message.
*/
const written_text = (answer.text || "").trim();
const written_text = (answer.text || call_text || "").trim();
/**
* A card is never paired with an older sentence: the card asked
* something, and the draft was about something else. Filling it in
@@ -1172,11 +1221,29 @@ export default async function runTextLoop({
const asked_something = tool_calls.some(
(call) => call.name !== SendReplyToolName && isClosingTool({ name: call.name }),
);
/**
* The sentence a card turn wrote is the one that card belongs under,
* so it is held for the `send_reply` that closes it, whether that
* turn is the next one or shares the card. No second reminder is
* needed: the loop already asked for the call, not the message. An
* earlier draft is not held that way: it was about something else,
* and pairing it with "Which date rule?" put "I checked the date
* rules." under it.
*/
const carry_card = Boolean(card_text.trim()) && !unfinishedAnswerText({ text: card_text });
const carry_draft =
told_closing_text && !asked_something && !unfinishedAnswerText({ text: draft_text });
const message_text = written_text || (carry_draft ? draft_text : "");
const message_text = written_text || (carry_card ? card_text : carry_draft ? draft_text : "");
if (called_card && (closing_failed || !closing || !closing_required)) {
/**
* A turn that put a card up and wrote the message beside it, but
* ended without `send_reply`, has written the reply: the next
* turn is asked for the call, not the whole message again.
*/
if (closing && !closing_failed && !called_send_reply && written_text) {
card_text = written_text;
}
/**
* Bounded: past the retries a card-only turn ends on the answer
* it wrote, reviewed like any reply, rather than looping on a
@@ -1270,7 +1337,9 @@ export default async function runTextLoop({
kind: "event",
index,
name: "draft_carried",
text: "The message was written in an earlier turn. send_reply had no text beside it after one reminder, so that finished draft went out.",
text: carry_card
? "The message was written beside a card in an earlier turn. send_reply had no text beside it after one reminder, so that message went out with the card under it."
: "The message was written in an earlier turn. send_reply had no text beside it after one reminder, so that finished draft went out.",
});
}
@@ -1280,6 +1349,7 @@ export default async function runTextLoop({
if (!told_unfinished && !(wrap_up && !wrap_up_saving)) {
told_unfinished = true;
draft_text = "";
card_text = "";
pushUserTurn({ transcript, content: unfinished });
await traced({ kind: "event", index, name: "unfinished", text: unfinished });
continue;
@@ -1338,7 +1408,17 @@ export default async function runTextLoop({
};
}
if (check.verdict === "sent_back") continue;
if (check.verdict === "sent_back") {
/**
* Nothing held from the refused message may go out in its
* place, and the reminder flag goes with it so the rewrite
* can be asked for the text beside the call once more.
*/
draft_text = "";
card_text = "";
told_closing_text = false;
continue;
}
return {
text: message_text,
@@ -1,9 +1,24 @@
import { describe, expect, test } from "bun:test";
import askUserTool from "./ask-user-tool";
import { afterAll, describe, expect, mock, test } from "bun:test";
let created = 0;
let next_id = 41;
mock.module("@/src/functions/backend/db/bot-questions/create-bot-question", () => ({
default: async () => {
created++;
return next_id++;
},
}));
const { default: askUserTool } = await import("./ask-user-tool");
afterAll(() => {
mock.restore();
});
const tool = askUserTool({ user_id: 1, bot_id: 2, session_id: 3, onAsk: () => {} });
const question = { question: "Which environment?", kind: "single", options: ["Staging", "Production"] };
const question = { question: "Which environment?", kind: "single" as const, options: ["Staging", "Production"] };
describe("askUserTool", () => {
test("takes a set of questions", () => {
@@ -23,4 +38,26 @@ describe("askUserTool", () => {
test("caps how many questions one card holds", () => {
expect(tool.schema?.safeParse({ questions: Array.from({ length: 7 }, () => question) }).success).toBe(false);
});
});
test("asks once per run, so a second call points at the card already up", async () => {
/**
* A model that re-asked while the loop asked it for `send_reply`
* was refused by a thrown error, which the loop read as a failed
* closing call: session 146 lost its whole answer to it. The card
* is up either way, so the second call just says so.
*/
created = 0;
const refs: string[] = [];
const once = askUserTool({ user_id: 1, bot_id: 2, session_id: 3, onAsk: ({ ref }) => refs.push(ref) });
const signal = new AbortController().signal;
const first = await once.run({ args: { questions: [question] }, signal });
const second = await once.run({ args: { questions: [question] }, signal });
expect(created).toBe(1);
expect(refs).toHaveLength(1);
expect(String(first)).toContain("Asked the user 1 question");
expect(String(second)).toContain("already asked");
expect(String(second)).toContain("send_reply");
});
});
@@ -67,9 +67,7 @@ export default function askUserTool({
}),
run: async ({ args }) => {
if (asked) {
throw new Error(
`You already asked the user in this run. Put every question in one ask_user call, then wait for their answers.`,
);
return `The questions are already asked and will go out with your message. Finish your reply with send_reply.`;
}
const id = await createBotQuestion({
@@ -94,7 +92,7 @@ export default function askUserTool({
return `Asked the user ${count} question${count == 1 ? "" : "s"}: the card is on your message. ${
in_task
? `Stop working on what you asked about and finish with your report (if you asked to settle something before going on, say you're waiting for their answers).`
: `End your reply now with a short line saying what you need settled; their answers arrive as their next message.`
: `End your reply now: write the short line saying what you need settled beside send_reply; their answers arrive as their next message.`
} Don't repeat the questions or options in your text.`;
},
};
@@ -142,4 +142,21 @@ describe("sendReplyTool", () => {
expect(result).toContain("what stopped the work");
expect(queued).toHaveLength(0);
});
test("accepts text and message in arguments and defaults status to done", async () => {
const result = await tool().run({ args: { message: "Here is your skill." }, signal });
expect(result).toContain("marked done");
expect(queued).toHaveLength(0);
});
test("infers status working when work is passed without status", async () => {
const result = await tool().run({
args: { work: { title: "Look up files", instructions: "Inspect them." } },
signal,
});
expect(result).toContain("Run #100 queued");
expect(queued).toHaveLength(1);
});
});
+22 -7
View File
@@ -27,13 +27,15 @@ type Params = {
};
type Args = {
status: (typeof ReplyStatuses)[number];
status?: (typeof ReplyStatuses)[number];
work?: BotTaskWork;
message?: string;
text?: string;
};
/**
* The one way a reply or a task report ends. The text written beside this
* call is the message the user gets; the call declares what happens after
* call or passed in message/text is the message the user gets; the call declares what happens after
* it, so the app never has to guess intent from prose.
*
* `done` says nothing runs once the message is out. `working` says a run
@@ -60,13 +62,16 @@ export default function sendReplyTool({
return {
name: "send_reply",
description: `End every reply with this call, in the same turn as the message. The text you write beside it is what the user gets; a call with no text sends nothing, and a message from an earlier turn is not filled in. This call only says what happens after it. status done: nothing runs once the message goes out, so the text must not say work is under way. status working: a run is carrying the work on and its result will be posted here; pass work to queue it now, or it must already be open. status blocked: the work cannot go on, and the text says why. Never write a message that says work is under way and end with done. In this same turn, and no other, you may also call suggest_next_steps or ask_user when one of them belongs with the answer. No other tool shares this turn. A message sent without this call is a draft and never reaches the user. Finish every table, list and code fence in the text. ${
description: `End every reply with this call, in the same turn as the message. The text you write beside it, or in message/text, is what the user gets; a call with neither sends nothing. A message written beside a card in an earlier turn is kept for the send_reply that closes it; anything else written earlier is not filled in. This call only says what happens after it. status done: nothing runs once the message goes out, so the text must not say work is under way. status working: a run is carrying the work on and its result will be posted here; pass work to queue it now, or it must already be open. status blocked: the work cannot go on, and the text says why. Never write a message that says work is under way and end with done. In this same turn, and no other, you may also call suggest_next_steps or ask_user when one of them belongs with the answer. No other tool shares this turn. A message sent without this call is a draft and never reaches the user. Finish every table, list and code fence in the text. ${
computers.length
? `Computers you can use: ${listed}. Defaults to ${computers[0]!.id}, the one you're on.`
: `You have no computer, so work that needs one can't run.`
}`,
schema: z.object({
status: z.enum(ReplyStatuses).describe("done: nothing runs after this message. working: a run carries the work on. blocked: the work cannot go on."),
status: z
.enum(ReplyStatuses)
.default("done")
.describe("done: nothing runs after this message. working: a run carries the work on. blocked: the work cannot go on."),
work: z
.object({
title: z.string().min(1).max(80).describe("A short label, e.g. \"Check the backup logs\""),
@@ -88,13 +93,23 @@ export default function sendReplyTool({
})
.optional()
.describe("The run to start with this message. Required when status is working and no run of yours is open here."),
message: z
.string()
.optional()
.describe("The message to send the user with this reply, when not written directly in the assistant turn."),
text: z
.string()
.optional()
.describe("Alias for message: the message to send the user with this reply."),
}),
run: async ({ args }) => {
if (args.status !== "working" && args.work) {
const status = args.status ?? (args.work ? "working" : "done");
if (status !== "working" && args.work) {
throw new Error(`work can only be passed with status "working": it queues a run, so the message must say that work is under way. Nothing was sent.`);
}
if (args.status === "working") {
if (status === "working") {
if (args.work) {
if (!queued) {
queued = await queueBotTask({
@@ -129,7 +144,7 @@ export default function sendReplyTool({
return `A run of yours is still open here, so status "working" holds. Your message beside this call goes out with it: say what it's doing, in one sentence, and that its result will be posted here.`;
}
if (args.status === "blocked") {
if (status === "blocked") {
return `Your message beside this call goes out, marked blocked. Say plainly what stopped the work and what you need from the user to go on.`;
}
@@ -1,5 +1,20 @@
import { describe, expect, test } from "bun:test";
import suggestNextStepsTool from "./suggest-next-steps-tool";
import { afterAll, describe, expect, mock, test } from "bun:test";
let created = 0;
let next_id = 7;
mock.module("@/src/functions/backend/db/bot-suggestions/create-bot-suggestion", () => ({
default: async () => {
created++;
return next_id++;
},
}));
const { default: suggestNextStepsTool } = await import("./suggest-next-steps-tool");
afterAll(() => {
mock.restore();
});
const refs: string[] = [];
const tool = suggestNextStepsTool({ user_id: 1, bot_id: 2, session_id: 3, onSuggest: ({ ref }) => refs.push(ref) });
@@ -20,4 +35,20 @@ describe("suggestNextStepsTool", () => {
expect(tool.schema?.safeParse({ steps: Array.from({ length: 5 }, (_, i) => `Step ${i}`) }).success).toBe(false);
expect(tool.schema?.safeParse({ steps: ["x".repeat(121)] }).success).toBe(false);
});
test("suggests once per run, so a second call points at the buttons already up", async () => {
created = 0;
const seen: string[] = [];
const once = suggestNextStepsTool({ user_id: 1, bot_id: 2, session_id: 3, onSuggest: ({ ref }) => seen.push(ref) });
const signal = new AbortController().signal;
const first = await once.run({ args: { steps: ["Write the report"] }, signal });
const second = await once.run({ args: { steps: ["Write the report"] }, signal });
expect(created).toBe(1);
expect(seen).toHaveLength(1);
expect(String(first)).toContain("Suggested 1 next step");
expect(String(second)).toContain("already attached");
expect(String(second)).toContain("send_reply");
});
});
@@ -49,7 +49,7 @@ export default function suggestNextStepsTool({ user_id, bot_id, session_id, work
}),
run: async ({ args }) => {
if (suggested) {
throw new Error(`You already suggested next steps in this run. Put every suggestion in one suggest_next_steps call.`);
return `The suggested steps are already attached to your message. Finish your reply with send_reply.`;
}
const id = await createBotSuggestion({
@@ -14,6 +14,12 @@ type Params = {
* The thread's last message is the user's, so a reply is due.
*/
awaiting_reply: boolean;
/**
* Something of this session's is still to show its work here (a queued
* run, or one working on a computer): a reply that already landed says
* nothing about it, so the poll keeps reading until it's done.
*/
running?: boolean;
/**
* The thread's last message: only newer ones are replayed.
*/
@@ -46,6 +52,7 @@ type Params = {
export default function useReplyCatchUp({
session_id,
awaiting_reply,
running,
last_message_id,
on_open_jobs,
}: Params) {
@@ -114,16 +121,19 @@ export default function useReplyCatchUp({
useRefocus({ onRefocus: () => void check() });
/**
* While a reply is due, a poll covers a reply whose push was missed
* while the page stayed in front (a socket that dropped silently).
* While a reply is due, or something of this session's is still running,
* a poll covers a push that was missed while the page stayed in front (a
* socket that dropped silently). A run queued behind another on the same
* computer shows nothing at all without it: its reply already landed, so
* no reply is due, and nothing else would read the session again.
*/
useEffect(() => {
if (!awaiting_reply || !session_id) return;
if ((!awaiting_reply && !running) || !session_id) return;
const timer = setInterval(() => void check(), AppData.BotReplyCatchUpMs);
return () => clearInterval(timer);
}, [awaiting_reply, session_id, check]);
}, [awaiting_reply, running, session_id, check]);
/**
* The socket was down while the page stayed open: going back online or
@@ -26,6 +26,25 @@ function fromTask({ task }: { task: BotTaskWithSteps | null }): Progress {
};
}
/**
* The task of the session on screen, out of every task the push carries:
* the newest of them all is often a run in another conversation, and taking
* that one left this thread with nothing (`task` alone, when the push has no
* list).
*/
function ownTask({
data,
session_id,
}: {
data: Pick<BotUpdatedData, "task" | "tasks">;
session_id?: number | null;
}): BotTaskWithSteps | null {
const tasks = data.tasks || (data.task ? [data.task] : []);
const mine = session_id ? tasks.find((task) => task.session_id == session_id) : tasks[0];
return mine || null;
}
/**
* The open session's active task and its latest step (a
* `bots_queue_updates` row's text), kept current from
@@ -54,7 +73,7 @@ export default function useTaskProgress({ bot_id, session_id, task }: Params) {
* The user's active task with the bot may be in another of
* their conversations with it.
*/
const task = data.task && (!session_id || data.task.session_id == session_id) ? data.task : null;
const task = ownTask({ data, session_id });
setProgress((prev) => ((task?.id || null) == prev.task_id ? prev : fromTask({ task })));
},
@@ -271,6 +271,12 @@ export default function Conversation() {
useReplyCatchUp({
session_id,
awaiting_reply,
/**
* A queued or running task of this session keeps the poll going after
* the reply that queued it landed: nothing else reads it again, so a
* run waiting behind another on its computer would never show.
*/
running: Boolean(progress.task_id) || Boolean(open_reply_jobs),
last_message_id: last_saved_id,
on_open_jobs: ({ open_jobs }) => setOpenReplyJobs(open_jobs),
});
+5 -1
View File
@@ -54,7 +54,11 @@ export const handler: BunextAPIRouteHandler<SessionMessagesResponse> = async ({
bot: {
id: bot_id,
...(await grabBotFace({ bot_id, user_id: user.id })),
task: await grabActiveBotTask({ bot_id, user_id: user.id }),
/**
* The task of this session: the newest active one may be a
* run in another conversation, which the page would drop.
*/
task: await grabActiveBotTask({ bot_id, user_id: user.id, session_id: session.id }),
},
step: await grabSessionReplyStep({ session_id: session.id }),
open_jobs: await grabSessionOpenReplies({ session_id: session.id }),
+10
View File
@@ -695,7 +695,17 @@ export type BotUpdatedData = {
id: number;
face: BotFace;
status_line: string;
/**
* The newest of the user's active tasks, null when there is none. Kept
* for a reader that wants one; `tasks` has them all, since the newest
* may be in another conversation.
*/
task: BotTaskWithSteps | null;
/**
* Every active task the user has with the bot, newest first: the
* conversation picks the one from its own session.
*/
tasks?: BotTaskWithSteps[];
/**
* The computer the bot is on, when the push knows it (a switch, or the
* live relay). Null means its main one.
+37
View File
@@ -287,6 +287,43 @@ I'll report what the run actually finds when it reports back.`;
expect(problems[0]).toContain("list_graphics");
});
test("names a proposal that was never made", () => {
/**
* Session 146: the model wrote `[proposal:19]` before proposal 19
* existed (it guessed the next number), and the user read "I didn't
* get the proposal" four times. Only the tool's own ref may appear.
*/
const problems = replyClaimProblems({
text: "Proposed as [proposal:19]: Co-Marketing.",
tool_uses: [{ name: "send_reply", ok: true }],
missing_proposal_ids: [19],
missing_hook_proposal_ids: [4],
});
expect(problems.length).toBe(1);
expect(problems[0]).toContain("[proposal:19]");
expect(problems[0]).toContain("was ever made");
expect(
replyClaimProblems({
text: "Proposed as [proposal:19]: Co-Marketing.",
tool_uses: [{ name: "propose_skill", ok: true }],
}),
).toEqual([]);
});
test("names a hook proposal that was never made", () => {
const problems = replyClaimProblems({
text: "The hook is on the card: [hook-proposal:4]",
tool_uses: [{ name: "send_reply", ok: true }],
missing_hook_proposal_ids: [4],
});
expect(problems.length).toBe(1);
expect(problems[0]).toContain("[hook-proposal:4]");
expect(problems[0]).toContain("was ever made");
});
test("an answer that holds up has no problems", () => {
expect(replyClaimProblems({ text: "Task #20 is cancelled.", tool_uses: [] })).toEqual([]);
});
+26
View File
@@ -41,6 +41,14 @@ type Params = {
* hand-written one is made up or copied from an earlier message.
*/
written_card_refs?: string[];
/**
* `[proposal:ID]` / `[hook-proposal:ID]` refs in the text that name no
* proposal the user was ever made: the model guessed the next id and
* described a card nobody got ("I didn't get the proposal", four times
* in one conversation).
*/
missing_proposal_ids?: number[];
missing_hook_proposal_ids?: number[];
/**
* A run of the bot's, a job it handed over or a room it asked, still
* open from this conversation: its result is still to come.
@@ -98,6 +106,8 @@ export default function replyClaimProblems({
unresolved_setting_refs = [],
missing_graphic_ids = [],
written_card_refs = [],
missing_proposal_ids = [],
missing_hook_proposal_ids = [],
has_open_work,
status,
}: Params): string[] {
@@ -133,6 +143,22 @@ export default function replyClaimProblems({
);
}
/**
* A proposal ref that names nothing the user was made: a guessed number.
* The card only exists once the tool that proposes returned it, so a
* ref written beside the answer describes one nobody got.
*/
if (missing_proposal_ids.length || missing_hook_proposal_ids.length) {
const refs = [
...missing_proposal_ids.map((id) => `[proposal:${id}]`),
...missing_hook_proposal_ids.map((id) => `[hook-proposal:${id}]`),
];
problems.push(
`It names ${refs.join(", ")}, and no such proposal was ever made to the user. A proposal exists only once the tool that proposes one returned its ref (propose_skill, propose_browser, propose_hook and the like); the app puts that ref under your message itself, so never write one or guess the next number. Call the tool again if the proposal should be made now.`,
);
}
/**
* A card ref the model wrote itself: the app adds every one of these
* from the tool that made the card, so a written one is a card that was
+1 -1
View File
@@ -3,7 +3,7 @@ type Params = {
/**
* The ref's kind, as in `[file:12]`, `[task:20]` or `[suggestion:4]`.
*/
kind: "file" | "task" | "suggestion" | "question" | "plan" | "graphic";
kind: "file" | "task" | "suggestion" | "question" | "plan" | "graphic" | "proposal" | "hook-proposal";
};
/**
+8 -6
View File
@@ -1,14 +1,16 @@
import stripAppRecords from "./strip-app-records";
import stripCardRefs from "./strip-card-refs";
import stripUnresolvedSettingRefs from "./strip-unresolved-setting-refs";
/**
* What the app takes out of an answer before anything reads it: a
* `[setting:...]` pill that leads nowhere and an app record line the run's
* own tools don't support. Both are text the app would never show as its
* own word, so they are removed rather than sent back for a rewrite: three
* faults in one run used to cost the user an answer that was otherwise
* right (`reviewBotReply`).
* `[setting:...]` pill that leads nowhere, an app record line the run's
* own tools don't support, and the ref of a card the app adds itself
* (`[question:]`, `[suggestion:]`, `[plan:]`). All are text the app would
* never show as its own word, so they are removed rather than sent back for
* a rewrite: three faults in one run used to cost the user an answer that
* was otherwise right (`reviewBotReply`).
*/
export default function sanitizeAnswerText({ text }: { text: string }) {
return stripAppRecords({ text: stripUnresolvedSettingRefs({ text }) });
return stripCardRefs({ text: stripAppRecords({ text: stripUnresolvedSettingRefs({ text }) }) });
}
+43
View File
@@ -0,0 +1,43 @@
import { AppCardRefTools, type AppCardRefKind } from "./reply-claim-problems";
type Params = {
text: string;
};
const CardRefKinds = Object.keys(AppCardRefTools) as AppCardRefKind[];
/**
* One card ref alone in its code span (which still links), with the span.
*/
const codeSpan = ({ kind }: { kind: AppCardRefKind }) => new RegExp(`\`\\s*\\[${kind}:\\d+\\]\\s*\`[ \\t]?`, "gi");
/**
* A ref between words leaves one space behind, never two: `[ \t]*` around it
* stays on the same line, so paragraph breaks survive.
*/
const inline = ({ kind }: { kind: AppCardRefKind }) => new RegExp(`[ \\t]*\\[${kind}:\\d+\\][ \\t]*`, "gi");
/**
* A bot's own text with the refs of the cards the app adds under a message
* taken out (`[question:24]`, `[suggestion:7]`, `[plan:3]`). The app writes
* every one of those from the tool that made the card, so one in the model's
* text was written by hand, and the user reads it as a card that was never
* made ("not available") or as a second copy of one. Taken out rather than
* sent back for a rewrite: three faults in one run cost the user an answer,
* and a model that sees the ref in its own history learns to write it again
* (session 146: a whole thread of `[question:N]` refs it had never made).
*/
export default function stripCardRefs({ text }: Params): string {
if (!CardRefKinds.some((kind) => new RegExp(`\\[${kind}:\\d+\\]`, "i").test(text))) return text;
let stripped = text;
for (const kind of CardRefKinds) {
stripped = stripped.replace(codeSpan({ kind }), "").replace(inline({ kind }), " ");
}
return stripped
.replace(/[ \t]+$/gm, "")
.replace(/\n{3,}/g, "\n\n")
.trim();
}