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.
This commit is contained in:
2026-11-18 15:22:07 +01:00
parent 2df1cccc5d
commit 1ae6be803c
9 changed files with 238 additions and 2 deletions
+2 -2
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.
@@ -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.
@@ -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(() => {}),
);