Compare commits

...
3 Commits
Author SHA1 Message Date
tben 3980e37f7a 0.24.4
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
2026-11-18 15:23:59 +01:00
tben eb35cce55f Read the promise a bot makes as it starts the work
The reply review refused "Converting both articles ... I'll report back
with the conversion results" and the rewrite answered "You're right - I
didn't call start_task. Starting the conversion run now." with no tool
call at all. That rewrite passed, because the detector only read "I'll"
and "Let me" openers: the work named as starting, in the present tense
with a closer, matched nothing.

claimsWorkUnderWay now reads "Starting the conversion run now", "Kicking
off the build now", "I'm reading the digests, then I'll build one" and
"I am ..." as well as "I'm ...". The present-tense rule is anchored to
the sentence's opening, so a table cell quoting the user ("I am telling
you the same day") stays silent.

Over 1,732 bot messages in three production exports this flags 8 more,
every one a real claim with no run; the 3 that had called start_task stay
exempt.
2026-11-18 15:22:13 +01:00
tben 1ae6be803c Give a silent hook's thread back to the user who writes in it
A silent hook's thread is left out of the rail, unread, pushes and the
face on purpose, so its runs show only in the thread. Since hook threads
became ordinary, chat-able sessions, a conversation a user had inside one
(a chat that ran on from a hook's report) was caught by that rule and
stopped updating live: no message pushed, no thinking row, no face, no
unread.

A human message now takes a silent hook's thread from the hook
(adoptHookSession, from insertUserMessage, so a chat message and a
question's answer alike), and the hook opens a fresh thread next time.
adoptChattedHookSessions does the same at boot for threads earlier
versions left that way, one holding a human's message or left active.
2026-11-18 15:22:07 +01:00
13 changed files with 321 additions and 8 deletions
+3 -3
View File
@@ -88,7 +88,7 @@ Enables SQLite foreign keys (`enableForeignKeys`), `bunextInit()`, `ensureDocker
### Bots, sessions, chat
- **Tables:** `bots` (`kind`, `color` `#rrggbb`, `stone`, `role`, `system_prompt`; `hue` is a legacy fallback), `bot_user_faces`, `bot_sessions`, `bot_messages`, `bot_tasks`, `bot_task_steps` (unused yet), `bot_plans` (a plan a bot wrote for work in pieces, its steps and their state), `bot_job_traces` (a run's debug view, 7 days by default). Enums in `src/dict/bot-dict.ts` and `src/dict/bot-plan-dict.ts`.
- **Sessions:** one thread per user per bot in its own chat plus one per workspace; split into `bot_sessions` (rollover at the app setting `bot_session_max_messages`, default `AppData.BotSessionMaxMessages`, via `grabBotSessionMaxMessages`; titled and summarised by `name-bot-session.ts` from the session's opening after a reply or a task (a session with no user message, work handed to the bot, is named from the bot's own messages; `grabSessionOpening`; `grabBotMessages` reads the latest; each opening message is cut to `AppData.BotSessionNameMessageChars`, so a pasted brief of tens of thousands of characters costs one naming call, not a second copy of itself), summary carried into the next session only when they're linked by `previous_session_id`, which only a carry-over sets; older implicit links are cleared at boot by `clearImplicitSessionLinks`). New session (`startBotSession`) and a conversation with no active session always start fresh. The rollover carries over like the bot does (`rollOverBotSession` -> `continueBotSession`, falling back to the stored summary; kept for the next message while a job is open in the full session or there's nothing to carry), inside send-message, so the user's message lands under the summary. A routine and a hook each keep a thread of their own, never the chat that happens to be active: `bot_sessions.routine_id` and `hook_id` mark it, `ensureRoutineSession`/`ensureHookSession` open it `closed` (so it takes nothing over) with the routine's or hook's title, roll it over at the same session max into a new linked session (`rollOverLinkedSession`, `previous_session_id`, the summary opening the new one), and it is read and chatted in with `?session_id=` like any session. A deleted routine or hook detaches its thread (`routine_id`/`hook_id` set to null) and keeps the messages; a silent hook's thread is the one exception to being followed (`followedSessionSql`: no rail row, no unread, no push, no face change), while a hook that isn't silent makes its thread the conversation's active session for its run. Helpers in `src/functions/backend/db/bot-sessions/`. Job results land in the job's own session, even after it closes, except a reply that called `continue_in_new_session` (`carryOverBotSession`; the menu's and sessions modal's Continue in new session does the same through `continueBotSession`, the model writing title and summary, refused while a job is open in the session): its summary is kept on the closed session and opens the new one as a bot message (`carried_from_session_id`), the job's `session_id` moves so the answer follows, the new session is titled by the bot then (it has no first exchange to be named from), and the old one can never be reopened (`reopenBotSession` refuses; a thread showing it swaps its composer for a link to the new one). Session lists (rail, sessions modal) reopen a session on click, as before; a carried-over one can't be, so it opens to read (`?session_id=`, `conversationHref`). The page tells them which session it shows (`announceShownSession` -> `useShownSession`): they reload, mark it Current (greyed out; without `?session_id=` the active one is), list it even when it's older than the rail's latest, and the active row then leads back. From half the session length the reply prompt suggests moving on (`longSessionNote`). Earlier sessions never enter the prompt (only the last one's summary): the thread can open them above a session (`useOlderMessages.loadPrevious`, a divider per session, quote and reply as usual), and replies get `search_past_sessions`/`read_past_session` (scoped to that user, bot and place, never the current session) when the conversation has any.
- **Sessions:** one thread per user per bot in its own chat plus one per workspace; split into `bot_sessions` (rollover at the app setting `bot_session_max_messages`, default `AppData.BotSessionMaxMessages`, via `grabBotSessionMaxMessages`; titled and summarised by `name-bot-session.ts` from the session's opening after a reply or a task (a session with no user message, work handed to the bot, is named from the bot's own messages; `grabSessionOpening`; `grabBotMessages` reads the latest; each opening message is cut to `AppData.BotSessionNameMessageChars`, so a pasted brief of tens of thousands of characters costs one naming call, not a second copy of itself), summary carried into the next session only when they're linked by `previous_session_id`, which only a carry-over sets; older implicit links are cleared at boot by `clearImplicitSessionLinks`). New session (`startBotSession`) and a conversation with no active session always start fresh. The rollover carries over like the bot does (`rollOverBotSession` -> `continueBotSession`, falling back to the stored summary; kept for the next message while a job is open in the full session or there's nothing to carry), inside send-message, so the user's message lands under the summary. A routine and a hook each keep a thread of their own, never the chat that happens to be active: `bot_sessions.routine_id` and `hook_id` mark it, `ensureRoutineSession`/`ensureHookSession` open it `closed` (so it takes nothing over) with the routine's or hook's title, roll it over at the same session max into a new linked session (`rollOverLinkedSession`, `previous_session_id`, the summary opening the new one), and it is read and chatted in with `?session_id=` like any session. A deleted routine or hook detaches its thread (`routine_id`/`hook_id` set to null) and keeps the messages; a silent hook's thread is the one exception to being followed (`followedSessionSql`: no rail row, no unread, no push, no face change) **until the user writes in it**: a human message takes the thread from the hook (`adoptHookSession`, from `insertUserMessage`, so a chat message and a question's answer alike), so the thread is theirs from then on and the hook opens a new one next time, while a hook that isn't silent makes its thread the conversation's active session for its run. Helpers in `src/functions/backend/db/bot-sessions/`. Job results land in the job's own session, even after it closes, except a reply that called `continue_in_new_session` (`carryOverBotSession`; the menu's and sessions modal's Continue in new session does the same through `continueBotSession`, the model writing title and summary, refused while a job is open in the session): its summary is kept on the closed session and opens the new one as a bot message (`carried_from_session_id`), the job's `session_id` moves so the answer follows, the new session is titled by the bot then (it has no first exchange to be named from), and the old one can never be reopened (`reopenBotSession` refuses; a thread showing it swaps its composer for a link to the new one). Session lists (rail, sessions modal) reopen a session on click, as before; a carried-over one can't be, so it opens to read (`?session_id=`, `conversationHref`). The page tells them which session it shows (`announceShownSession` -> `useShownSession`): they reload, mark it Current (greyed out; without `?session_id=` the active one is), list it even when it's older than the rail's latest, and the active row then leads back. From half the session length the reply prompt suggests moving on (`longSessionNote`). Earlier sessions never enter the prompt (only the last one's summary): the thread can open them above a session (`useOlderMessages.loadPrevious`, a divider per session, quote and reply as usual), and replies get `search_past_sessions`/`read_past_session` (scoped to that user, bot and place, never the current session) when the conversation has any.
- **Coordinator:** exactly one, the super admin's alone, created idempotently by `ensureCoordinatorBot`. Default prompt `src/data/coordinator-system-prompt.ts`, backfilled only when empty.
- **Routes:** `/admin/bots` reopens the last visited bot's own chat (cookie `cobble_last_visited_bot_id`, `<bot>` or `<bot>:<workspace>`; the landing uses only the bot) if still reachable, else coordinator (super admin) / latest bot / first workspace / empty. Workspace and conversation pages record the visit per user (`recordWorkspaceVisit`/`workspace_user_visits`, `recordBotVisit`/`bot_user_visits`) and the rail lists both latest visited first (`last_visited_at`, `orderByLastVisit`; recorded before the crew is read, so the conversation opened is already on top in that render, and its bot leads whatever the visits say (`pinned_id`); a workspace nobody visited yet ranks by its creation, so a new one leads); it never decides the landing. Settings and the rail pages get the cookie's conversation, workspace included, as root prop `last_conversation` (`grabLastConversation`, access-checked, only on those paths: `isPagesRailPath`), shown above their rail list as the way back (`RailLastConversation`). `/admin/bots/[bot_id]` conversation (header, thread and composer at 760px, no right panel; `?session_id=` opens another of the user's sessions there: a closed one is reopened, except a carried-over one, which shows with `SessionMovedBar` instead of the composer, pointing where the conversation went on); `/admin/bots/[bot_id]/models`; `/admin/workspaces/[id]` dashboard; `/admin/workspaces/[id]/bots/[bot_id]` same conversation scoped to the workspace.
- **No model:** while the bot has no text model there (`bot_text_model` null, kept live by the models modal), the thread shows `NoModelNotice` (centred when empty): super admins get Connect a provider / Guided setup, others are told the super admin sets it up.
@@ -128,7 +128,7 @@ Every run also gets `RequestScopeNote` (`src/data/harness-prompts.ts`): the user
- 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: `start_task` refuses it and a task run on it fails at once.
- Every model turn is a step in `bots_queue_updates` (tool names, never arguments; `describe-job-step.ts`, labels in `JobStepToolLabels`), pushed as `server:bot-job-update` by the live relay only. Steps feed the live working row alone: the `clear-job-steps` cron deletes them `AppData.BotJobStepsKeepMs` after the job ends, however it ended, keeping their count on `bots_queue.steps`. Never delete them the moment a job ends (the relay would miss the last ones).
- **A task run plans before it starts:** `planBotTask` (from `run-bot-task`) spends one turn, no tools, on the very system prompt the run then sends, so the provider's cache serves it and it costs little more than the plan. The answer is a bounded JSON plan (`BotTaskPlanSchema`, caps in `AppData.BotTaskPlan*`) that opens the run as `taskPlanNote` and shows as its first step line; `shouldPlanBotTask` keeps it off short runs (`AppData.BotTaskPlanMinSteps`). 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 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 goes out, `reviewBotReply` (the loop's `review`) sends it back when it names a `[file:ID]`/`[task:ID]`/`[graphic:ID]` that doesn't exist for the user, 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") (`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 `start_task`/`delegate_task`/`ask_bot` this reply 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. 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 reply job fails instead (`review_note` -> `BotJobFatalError`), 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 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 goes out, `reviewBotReply` (the loop's `review`) sends it back when it names a `[file:ID]`/`[task:ID]`/`[graphic:ID]` that doesn't exist for the user, 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 `start_task`/`delegate_task`/`ask_bot` this reply 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. 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 reply job fails instead (`review_note` -> `BotJobFatalError`), 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`).
- **`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). `start_task` 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 (`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.
@@ -168,7 +168,7 @@ A folder on the host machine shared with bots (super admin, Settings > Host dire
### Hooks (`bot_hooks`)
A secret URL, `POST /api/hooks/<token>` (`src/pages/api/hooks/[token].ts`, public, no session), that queues a hook's brief plus the raw body as a task, per user and bot like a routine (runs act as the owner, who must still reach the bot and not be read-only). Only the token's prefix and SHA-256 are stored (shown once; "New URL" rotates it); an optional HMAC-SHA256 signing secret is stored encrypted (`verifyHookSignature`). Order in the route: rate limit per IP, lookup (same 404 for every miss), rate limit per hook, signature, then `fireBotHook`. Calls are recorded in `bot_hook_events` with idempotency on the sender's delivery header; when a run ends (completed, failed, lost, stopped, cancelled) every call it took in gets its `response` and turns `done`/`failed` (`recordHookCallResponse`, called from the job helpers, not the handler). Calls are searchable by payload/response (`searchHookCallsSql`; Calls view, bot tools `search_hook_calls`/`read_hook_call`) and pruned daily after the app setting `hook_events_keep_days` (default `AppData.BotHookEventsKeepDays`). The caller only ever gets `202 Queued`. A call while the last run is still pending and untried joins its brief (`mergeHookCallSql`) instead of queueing another. The payload is fenced data (`hookPayloadBlock`), and `HookRunNote` tells the bot never to take instructions from it. Failed runs retry like routines and keep why in `last_error`. Users make hooks in the conversation's Hooks modal and manage all of theirs on `/admin/routines`. **A hook keeps its runs in a thread of its own** (`bot_sessions.hook_id`, `ensureHookSession`: one per place, created `closed`, rolled over at the session max, linked from its card and chattable with `?session_id=`). `bot_hooks.silent` decides whether it takes the conversation over: silent (the form's "Run silently"; every hook made before this setting existed is made silent at boot by `migrateHookSilence`) leaves the thread out of the rail, unread and pushes, changes no face and names nothing (`isUnattendedHookSession`, `followedSessionSql`), so its runs show only in the thread and `last_error`; a hook that isn't silent makes its thread the conversation's active session for its run, and its report is pushed and notified like any message. Calls stay in `bot_hook_events` (`HookDetailModal`, opened from a hook's title; live through `server:hook-call-updated` from the relay) and are pruned daily, while the thread's messages stay. `bot_hooks.session_id` is unused. Deleting a hook detaches its thread (`detachHookSessions`: `hook_id` null, status `closed`) and keeps the messages. Moving a hook is refused while a run is open; the computer is kept only if reachable there. **A bot never makes or changes a hook on its own:** `list_hooks`, `search_hook_calls`, `read_hook_call`, `pause_hook` and `delete_hook` act directly (they only read or take away); a new hook, or a new name, brief or filter, or switching one back on, goes through `propose_hook` -> `hook_proposals` -> `[hook-proposal:ID]` card, described from the data and confirmed by that user (`checkHookProposal` runs again on confirm). What calls a hook, its computers and its signing are never proposed. A new hook's URL shows on the card only, never in the outcome the bot is told. Only chat replies propose; a hook call's own run gets no hook tools.
A secret URL, `POST /api/hooks/<token>` (`src/pages/api/hooks/[token].ts`, public, no session), that queues a hook's brief plus the raw body as a task, per user and bot like a routine (runs act as the owner, who must still reach the bot and not be read-only). Only the token's prefix and SHA-256 are stored (shown once; "New URL" rotates it); an optional HMAC-SHA256 signing secret is stored encrypted (`verifyHookSignature`). Order in the route: rate limit per IP, lookup (same 404 for every miss), rate limit per hook, signature, then `fireBotHook`. Calls are recorded in `bot_hook_events` with idempotency on the sender's delivery header; when a run ends (completed, failed, lost, stopped, cancelled) every call it took in gets its `response` and turns `done`/`failed` (`recordHookCallResponse`, called from the job helpers, not the handler). Calls are searchable by payload/response (`searchHookCallsSql`; Calls view, bot tools `search_hook_calls`/`read_hook_call`) and pruned daily after the app setting `hook_events_keep_days` (default `AppData.BotHookEventsKeepDays`). The caller only ever gets `202 Queued`. A call while the last run is still pending and untried joins its brief (`mergeHookCallSql`) instead of queueing another. The payload is fenced data (`hookPayloadBlock`), and `HookRunNote` tells the bot never to take instructions from it. Failed runs retry like routines and keep why in `last_error`. Users make hooks in the conversation's Hooks modal and manage all of theirs on `/admin/routines`. **A hook keeps its runs in a thread of its own** (`bot_sessions.hook_id`, `ensureHookSession`: one per place, created `closed`, rolled over at the session max, linked from its card and chattable with `?session_id=`). `bot_hooks.silent` decides whether it takes the conversation over: silent (the form's "Run silently"; every hook made before this setting existed is made silent at boot by `migrateHookSilence`) leaves the thread out of the rail, unread and pushes, changes no face and names nothing (`isUnattendedHookSession`, `followedSessionSql`), so its runs show only in the thread and `last_error`; **the thread stops being the hook's the moment the user writes in it** (`adoptHookSession`: it becomes an ordinary conversation, pushed and counted, and the next call opens a fresh thread; `adoptChattedHookSessions` does the same at boot for threads earlier versions left that way, one holding a human's message or left active by them); a hook that isn't silent makes its thread the conversation's active session for its run, and its report is pushed and notified like any message. Calls stay in `bot_hook_events` (`HookDetailModal`, opened from a hook's title; live through `server:hook-call-updated` from the relay) and are pruned daily, while the thread's messages stay. `bot_hooks.session_id` is unused. Deleting a hook detaches its thread (`detachHookSessions`: `hook_id` null, status `closed`) and keeps the messages. Moving a hook is refused while a run is open; the computer is kept only if reachable there. **A bot never makes or changes a hook on its own:** `list_hooks`, `search_hook_calls`, `read_hook_call`, `pause_hook` and `delete_hook` act directly (they only read or take away); a new hook, or a new name, brief or filter, or switching one back on, goes through `propose_hook` -> `hook_proposals` -> `[hook-proposal:ID]` card, described from the data and confirmed by that user (`checkHookProposal` runs again on confirm). What calls a hook, its computers and its signing are never proposed. A new hook's URL shows on the card only, never in the outcome the bot is told. Only chat replies propose; a hook call's own run gets no hook tools.
**Browser notifications:** a hook with `source = browser_notifications` is called by a watcher on `watch_computer_id` instead of an outside service. The watcher (`src/data/notify-watch-script.ts`, Python + GLib, run as `gem` from `~/.cobble/`) owns `org.freedesktop.Notifications` on the computer's session bus (started by the agent; Chrome's pid and bus are in `/run/cobble/browser.pid|json`), so Chrome hands it every notification, push ones included, instead of its silent built-in message center, and it posts each as JSON (`origin`, `title`, `body`) to the URLs in `~/.cobble/notify-hooks`. Chrome only looks for that service when it starts, so `syncComputerNotifyWatch` restarts Chrome once after starting the watcher (the agent brings it back), never while a task works on that computer. The hook's token is kept encrypted (`watch_token`) to rewrite that list after a container is recreated; `sync-notify-watchers` (every 5 minutes) and every change to such a hook resync it. `watch_filter` keeps only matching notifications (others are recorded as `ignored`). Computers reach the app at `COMPUTER_APP_URL` (an app setting; needed for a dev server outside docker), else the app container's name on the docker network. Sites still need notification permission in that computer's browser (on the computer's screen: `chrome://settings/content/notifications`; a `Browser.grantPermissions` over CDP lasts only for that CDP session). Anything on the computer can read the list and call those hooks, which is one more reason payloads are only data.
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "cobble",
"version": "0.24.3",
"version": "0.24.4",
"module": "index.ts",
"type": "module",
"private": true,
@@ -0,0 +1,69 @@
import { Database } from "bun:sqlite";
import { beforeAll, describe, expect, test } from "bun:test";
import adoptChattedHookSessionsSql from "./adopt-chatted-hook-sessions-sql";
/**
* Run against real SQLite: the boot repair has to take exactly the threads
* the user was chatting in and leave the hook's own runs (silent, no user
* in them) and every hook that isn't silent alone.
*/
const db = new Database(":memory:");
beforeAll(() => {
db.run(`CREATE TABLE bot_hooks (id INTEGER PRIMARY KEY, silent INTEGER)`);
db.run(`CREATE TABLE bot_sessions (id INTEGER PRIMARY KEY, hook_id INTEGER, status TEXT, updated_at INTEGER)`);
db.run(
`CREATE TABLE bot_messages (id INTEGER PRIMARY KEY, session_id INTEGER, author TEXT, from_ask_id INTEGER, from_install_request_id INTEGER)`,
);
db.run(`INSERT INTO bot_hooks VALUES (1, 1), (2, 0)`);
db.run(`INSERT INTO bot_sessions VALUES
(10, 1, 'active', 0),
(11, 1, 'closed', 0),
(12, 1, 'closed', 0),
(13, 1, 'closed', 0),
(14, 1, 'closed', 0),
(15, 2, 'active', 0),
(16, NULL, 'active', 0),
(17, 1, 'closed', 0)`);
db.run(`INSERT INTO bot_messages VALUES
(100, 11, 'user', NULL, NULL),
(101, 12, 'bot', NULL, NULL),
(102, 13, 'user', 4, NULL),
(103, 14, 'user', NULL, 2),
(104, 15, 'user', NULL, NULL),
(105, 16, 'user', NULL, NULL),
(106, 17, 'user', NULL, NULL),
(107, 17, 'bot', NULL, NULL)`);
});
function adopt() {
const { sql, values } = adoptChattedHookSessionsSql({ now: 42 });
return (db.query(sql).all(...values) as { id: number }[]).map((row) => row.id).sort((a, b) => a - b);
}
function hookOf(session_id: number) {
return (db.query(`SELECT hook_id FROM bot_sessions WHERE id = ?`).get(session_id) as {
hook_id: number | null;
}).hook_id;
}
describe("adoptChattedHookSessionsSql", () => {
test("hands back the threads the user was in, and only those", () => {
expect(adopt()).toEqual([10, 11, 17]);
expect(hookOf(10)).toBeNull();
expect(hookOf(11)).toBeNull();
expect(hookOf(17)).toBeNull();
expect(hookOf(12)).toBe(1);
expect(hookOf(13)).toBe(1);
expect(hookOf(14)).toBe(1);
expect(hookOf(15)).toBe(2);
expect(hookOf(16)).toBeNull();
});
test("changes nothing on the next boot", () => {
expect(adopt()).toEqual([]);
});
});
@@ -0,0 +1,30 @@
type Params = {
now: number;
};
/**
* The threads that versions before this one left with a silent hook while
* the user was chatting in them: the ones holding the user's own words, and
* the ones the user has on screen (a silent hook's thread is only ever
* active because the user was in it). Handing them back at boot makes those
* conversations reach their user again (pushed, unread, the bot's face),
* and each hook opens a fresh thread on its next call.
*/
export default function adoptChattedHookSessionsSql({ now }: Params) {
return {
sql: `UPDATE bot_sessions SET hook_id = NULL, updated_at = ?
WHERE hook_id IN (SELECT id FROM bot_hooks WHERE silent = 1)
AND (
status = 'active'
OR EXISTS (
SELECT 1 FROM bot_messages m
WHERE m.session_id = bot_sessions.id
AND m.author = 'user'
AND m.from_ask_id IS NULL
AND m.from_install_request_id IS NULL
)
)
RETURNING id`,
values: [now] as (string | number)[],
};
}
@@ -0,0 +1,19 @@
import BunSQLite from "@moduletrace/bun-sqlite";
import adoptChattedHookSessionsSql from "./adopt-chatted-hook-sessions-sql";
/**
* Repairs an install that kept the user's real conversation in a silent
* hook's thread: those threads become the user's own at boot, so their
* messages reach the user's tabs again and count as activity, while the
* hook keeps a thread of its own for its next call. Runs once per boot and
* changes nothing when there is nothing to hand back.
*/
export default async function adoptChattedHookSessions() {
const { sql, values } = adoptChattedHookSessionsSql({ now: Date.now() });
const res = await BunSQLite.sql<{ id: number }>({ sql, values });
if (!res.success) {
throw new Error(`Couldn't hand the hooks' used threads to their users: ${res.msg || res.error}`);
}
}
@@ -0,0 +1,55 @@
import { Database } from "bun:sqlite";
import { beforeAll, describe, expect, test } from "bun:test";
import adoptHookSessionSql from "./adopt-hook-session-sql";
/**
* Run against real SQLite: a wrong condition would either leave the user's
* own conversation unattended (pushed nowhere, no unread, no face) or take
* a hook that isn't silent out of the conversation it is meant to be in.
*/
const db = new Database(":memory:");
beforeAll(() => {
db.run(`CREATE TABLE bot_hooks (id INTEGER PRIMARY KEY, silent INTEGER)`);
db.run(`CREATE TABLE bot_sessions (id INTEGER PRIMARY KEY, hook_id INTEGER, updated_at INTEGER)`);
db.run(`INSERT INTO bot_hooks VALUES (1, 1), (2, 0)`);
db.run(`INSERT INTO bot_sessions VALUES
(10, 1, 0),
(11, 2, 0),
(12, NULL, 0),
(13, 99, 0)`);
});
function adopt(session_id: number) {
const { sql, values } = adoptHookSessionSql({ session_id, now: 42 });
return db.query(sql).all(...values).length > 0;
}
function hookOf(session_id: number) {
return (db.query(`SELECT hook_id FROM bot_sessions WHERE id = ?`).get(session_id) as {
hook_id: number | null;
}).hook_id;
}
describe("adoptHookSessionSql", () => {
test("takes a silent hook's thread from the hook", () => {
expect(adopt(10)).toBe(true);
expect(hookOf(10)).toBeNull();
expect(db.query(`SELECT updated_at FROM bot_sessions WHERE id = 10`).get()).toEqual({ updated_at: 42 });
});
test("leaves a hook that isn't silent in its thread: the thread is the conversation", () => {
expect(adopt(11)).toBe(false);
expect(hookOf(11)).toBe(2);
});
test("leaves a session that belongs to no hook", () => {
expect(adopt(12)).toBe(false);
});
test("leaves a session whose hook is gone", () => {
expect(adopt(13)).toBe(false);
expect(hookOf(13)).toBe(99);
});
});
@@ -0,0 +1,21 @@
type Params = {
session_id: number;
now: number;
};
/**
* Hands a session to the user who wrote in it. A silent hook's thread is
* the hook's only until the user types there; from then on it is an
* ordinary conversation, so its messages reach the user's tabs, its unread
* counts and the bot's face moves like anywhere else, while the hook's next
* call opens a thread of its own. `RETURNING id` says whether the session
* was a silent hook's.
*/
export default function adoptHookSessionSql({ session_id, now }: Params) {
return {
sql: `UPDATE bot_sessions SET hook_id = NULL, updated_at = ?
WHERE id = ? AND hook_id IN (SELECT id FROM bot_hooks WHERE silent = 1)
RETURNING id`,
values: [now, session_id] as (string | number)[],
};
}
@@ -0,0 +1,26 @@
import BunSQLite from "@moduletrace/bun-sqlite";
import adoptHookSessionSql from "./adopt-hook-session-sql";
type Params = {
session_id: number;
};
/**
* A silent hook's thread stops being the hook's the moment the user writes
* in it: the thread on screen is theirs to chat in, so it becomes an
* ordinary conversation (its messages pushed and counted, the bot's face
* set while it answers), and the hook's next call opens a thread of its
* own (`ensureHookSession`). Returns whether the session was one of a
* silent hook's.
*/
export default async function adoptHookSession({ session_id }: Params): Promise<boolean> {
const { sql, values } = adoptHookSessionSql({ session_id, now: Date.now() });
const res = await BunSQLite.sql<{ id: number }>({ sql, values });
if (!res.success) {
throw new Error(`Couldn't take the session over from its hook: ${res.msg || res.error}`);
}
return Boolean(res.payload?.length);
}
@@ -5,6 +5,7 @@ import type {
} from "@/db/types/db";
import type { BotMessageWithAttachments } from "@/src/types";
import BunSQLite from "@moduletrace/bun-sqlite";
import adoptHookSession from "../bot-sessions/adopt-hook-session";
import mediaToAttachment from "./media-to-attachment";
type Params = {
@@ -61,6 +62,17 @@ export default async function insertUserMessage({
}: Params): Promise<BotMessageWithAttachments> {
const now = Date.now();
/**
* The user writing in a silent hook's thread makes it theirs before
* anything is pushed: the message is theirs to see arrive, and their
* conversation's, not the hook's runs'. A crew request's outcome and an
* install request's answer ride the user's side of a conversation but
* are not the user writing, so they leave the thread where it is.
*/
if (!from_ask_id && !from_install_request_id) {
await adoptHookSession({ session_id });
}
const res = await BunSQLite.insert<
BUN_SQLITE_COBBLE_BOT_MESSAGES,
(typeof BunSQLiteTables)[number]
+4
View File
@@ -14,6 +14,7 @@ import migrateLlmLogs from "./functions/backend/db/logs/migrate-llm-logs";
import clearImplicitSessionLinks from "./functions/backend/db/bot-sessions/clear-implicit-session-links";
import migrateChatroomsToAsks from "./functions/backend/db/bot-sessions/migrate-chatrooms-to-asks";
import migrateHookSilence from "./functions/backend/db/bot-hooks/migrate-hook-silence";
import adoptChattedHookSessions from "./functions/backend/db/bot-hooks/adopt-chatted-hook-sessions";
import dropStoredFileText from "./functions/backend/db/stored-text/drop-stored-file-text";
import syncKnowledgebaseFts from "./functions/backend/db/knowledgebases/fts/sync-knowledgebase-fts";
import flushBootLogs from "./functions/backend/backups/flush-boot-logs";
@@ -56,6 +57,9 @@ await migrateChatroomsToAsks().catch((error) =>
await migrateHookSilence().catch((error) =>
logError({ title: "Could not make the existing hooks silent", error }).catch(() => {}),
);
await adoptChattedHookSessions().catch((error) =>
logError({ title: "Could not hand the hooks' used threads to their users", error }).catch(() => {}),
);
await dropStoredFileText().catch((error) =>
logError({ title: "Could not drop the stored file text", error }).catch(() => {}),
);
+31
View File
@@ -107,4 +107,35 @@ describe("claimsWorkUnderWay", () => {
expect(claimsWorkUnderWay({ text })).toBe(false);
}
});
/**
* The same promise one step later, from the two runs that went out
* with nothing started: sent back for promising a run, the bot
* apologised and named the run as starting anyway ("Starting the
* conversion run now."), and a task it meant to start came out as
* text around a written-out call ("I am starting a task to do that.").
* Wrote "I am" where every pattern read "I'm", or named the moment
* instead of the promise.
*/
test("catches work named as starting now", () => {
for (const text of [
"You're right - I didn't call `start_task`. Starting the conversion run now.",
"You asked me to search for Canva templates. I am starting a task to do that.",
"I'm reading the four existing digests to extract the exact format, then I'll build one sample for your approval.",
"Kicking off the build now.",
"Starting the audit right away.",
]) {
expect(claimsWorkUnderWay({ text })).toBe(true);
}
for (const text of [
"Starting a task on a busy computer waits behind the open run.",
"Starting the container takes about ten seconds.",
"I'm reading that as `bots/1/site`, so say so if you meant something else.",
"I am sorry, that contest isn't open any more.",
"The run starts in a moment, once you say go.",
]) {
expect(claimsWorkUnderWay({ text })).toBe(false);
}
});
});
+38 -4
View File
@@ -2,6 +2,13 @@ type Params = {
text: string;
};
/**
* "I'm" and "I am": a weaker model writes the long form, and "I am
* starting a task to do that." went out with no run behind it while every
* pattern here read the contraction alone.
*/
const IAm = "(?:i(?:'|’)?m|i am)";
/**
* How an answer says work is going on after it, or that a report will
* follow: the line a reply writes once it started a run ("I'm browsing
@@ -33,9 +40,12 @@ const UnderWayPatterns = [
* promised report the patterns above need. Only `start_task` starts
* one, so the app's record decides whether it's true.
*/
/\bI(?:'|’)?m\s+(?:now\s+|just\s+)?(?:starting|beginning|kicking off|launching|queueing|queuing|firing off|spinning up)\b[^.!?\n]{0,120}\b(?:run|task|job|work|scan|audit|recon|build|pass)\b/i,
/\bI(?:'|’)ve\s+(?:now\s+|just\s+)?(?:started|begun|kicked off|launched|queued|fired off|spun up)\b/i,
/\bI(?:'|’)?m\s+(?:now\s+|just\s+)?(?:starting|beginning|kicking off)\s+(?:it|this|that)\b/i,
new RegExp(
`\\b${IAm}\\s+(?:now\\s+|just\\s+)?(?:starting|beginning|kicking off|launching|queueing|queuing|firing off|spinning up)\\b[^.!?\\n]{0,120}\\b(?:run|task|job|work|scan|audit|recon|build|pass)\\b`,
"i",
),
new RegExp(`\\bI(?:'|’)ve\\s+(?:now\\s+|just\\s+)?(?:started|begun|kicked off|launched|queued|fired off|spun up)\\b`, "i"),
new RegExp(`\\b${IAm}\\s+(?:now\\s+|just\\s+)?(?:starting|beginning|kicking off)\\s+(?:it|this|that)\\b`, "i"),
/(?:^|[.!?\n]\s*)(?:starting|beginning|kicking off)\s+(?:it|that|the (?:run|job|task|work|scan|audit|build))\b/i,
];
@@ -71,7 +81,31 @@ const PromisePatterns = [
`^\\s*(?:once|when|after|as soon as)\\b[^,.]{0,80},\\s*(?:then\\s+)?I(?:(?:'|’)ll| will) (?:also |now |just )?${WorkVerb}\\b`,
"i",
),
new RegExp(`\\bI(?:'|’)?m (?:going|about) to ${WorkVerb}\\b`, "i"),
new RegExp(`\\b${IAm} (?:going|about) to ${WorkVerb}\\b`, "i"),
/**
* "I am checking the inbox now." The wide "I'm ... ing ... now" above
* reads the whole reply, so adding "I am" there faulted a table cell
* quoting a line ("I am telling you the same day", with "is now a
* follow-up" further along). Read a sentence at a time, only its own
* opening counts.
*/
new RegExp(`^\\s*${IAm}\\s+(?:now\\s+)?[a-z]+ing\\b[^.!?\\n]{0,160}\\bnow\\b`, "i"),
/**
* Work named as happening this moment rather than promised: "Starting
* the conversion run now.", written after the app sent the reply back
* for promising it, and "I'm reading the four digests, then I'll
* build one sample". The sentence has to say it is happening, with a
* closer, so "Starting a task on a busy computer waits behind the open
* run" explains the app instead of claiming a run.
*/
new RegExp(
`^\\s*(?:starting|beginning|kicking off|launching)\\s+(?:(?:the|a|an|this|that|my|both)\\s+)?(?:[\\w-]+\\s+){0,3}(?:run|job|task|work|scan|audit|build|conversion|review|pass)\\b[^.!?\\n]{0,40}\\b(?:now|right away|immediately|for you|as we speak)\\b`,
"i",
),
new RegExp(
`^\\s*${IAm}\\s+(?:now\\s+|just\\s+)?${WorkVerb}ing\\b[^.!?\\n]{0,200}\\b(?:then\\s+)?(?:i(?:'|’)ll|i will)\\b`,
"i",
),
];
/**
+12
View File
@@ -46,6 +46,18 @@ describe("replyClaimProblems", () => {
expect(replyClaimProblems({ text: promised, tool_uses: [{ name: "start_task", ok: true }] })).toEqual([]);
});
/**
* The rewrite the review bought: told its promise started nothing, the
* bot apologised and named the run as starting anyway, and called no
* tool. Nothing was running, and the user was left waiting again.
*/
test("faults a reply that apologised and named the run as starting anyway", () => {
const promised = "You're right - I didn't call `start_task`. Starting the conversion run now.";
expect(replyClaimProblems({ text: promised, tool_uses: [] }).length).toBe(1);
expect(replyClaimProblems({ text: promised, tool_uses: [{ name: "start_task", ok: true }] })).toEqual([]);
});
test("names files and tasks that don't exist", () => {
const problems = replyClaimProblems({
text: "Saved in [file:301]; see [task:20].",