Keep routine and hook runs in threads of their own

This commit is contained in:
2026-11-18 14:18:32 +01:00
parent fb944b5185
commit 44f2abf9de
68 changed files with 883 additions and 322 deletions
+5 -5
View File
File diff suppressed because one or more lines are too long
+21 -2
View File
@@ -480,7 +480,12 @@ const schema: BUN_SQLITE_DatabaseSchemaType = {
},
{
fieldName: "hook_id",
fieldDescription: `The hook whose runs this session holds. Such sessions (status \`hook\`) never show in the bot's conversation, rails or session lists: their results are read in the hook's thread. Not a foreign key: a run can outlast its hook. Null: an ordinary session`,
fieldDescription: `The hook whose runs this session holds. Not a foreign key: a run can outlast its hook. Null: a session no hook owns`,
dataType: "INTEGER",
},
{
fieldName: "routine_id",
fieldDescription: `The routine (\`cron_jobs\`) whose runs this session holds. Not a foreign key: its runs outlast the routine. Null: a session no routine owns`,
dataType: "INTEGER",
},
{
@@ -507,6 +512,14 @@ const schema: BUN_SQLITE_DatabaseSchemaType = {
indexName: "idx_bot_sessions_ask_id",
indexTableFields: ["ask_id"],
},
{
indexName: "idx_bot_sessions_hook_id",
indexTableFields: ["hook_id"],
},
{
indexName: "idx_bot_sessions_routine_id",
indexTableFields: ["routine_id"],
},
{
indexName: "idx_bot_sessions_bot_id_workspace_id",
indexTableFields: ["bot_id", "workspace_id", "status"],
@@ -1477,9 +1490,15 @@ const schema: BUN_SQLITE_DatabaseSchemaType = {
},
{
fieldName: "session_id",
fieldDescription: `No longer used: runs land in the hook's own hidden session (\`bot_sessions.hook_id\`)`,
fieldDescription: `No longer used: runs land in the hook's own session (\`bot_sessions.hook_id\`)`,
dataType: "INTEGER",
},
{
fieldName: "silent",
fieldDescription: `0: its runs take over the conversation, landing in a session the user sees and can chat in. 1: they stay in the hook's own thread, pushed nowhere. Null only until the first start after this setting existed, which makes every existing hook silent`,
dataType: "INTEGER",
options: [0, 1],
},
{
fieldName: "title",
dataType: "TEXT",
+10 -2
View File
@@ -371,9 +371,13 @@ export type BUN_SQLITE_COBBLE_BOT_SESSIONS = {
*/
ask_id?: number | "";
/**
* The hook whose runs this session holds. Such sessions (status `hook`) never show in the bot's conversation, rails or session lists: their results are read in the hook's thread. Not a foreign key: a run can outlast its hook. Null: an ordinary session
* The hook whose runs this session holds. Not a foreign key: a run can outlast its hook. Null: a session no hook owns
*/
hook_id?: number | "";
/**
* The routine (`cron_jobs`) whose runs this session holds. Not a foreign key: its runs outlast the routine. Null: a session no routine owns
*/
routine_id?: number | "";
/**
* One active session per conversation; `ask` for a bot's part of a crew request, `hook` for a hook's runs
*/
@@ -932,9 +936,13 @@ export type BUN_SQLITE_COBBLE_BOT_HOOKS = {
*/
workspace_id?: number | "";
/**
* No longer used: runs land in the hook's own hidden session (`bot_sessions.hook_id`)
* No longer used: runs land in the hook's own session (`bot_sessions.hook_id`)
*/
session_id?: number | "";
/**
* 0: its runs take over the conversation, landing in a session the user sees and can chat in. 1: they stay in the hook's own thread, pushed nowhere. Null only until the first start after this setting existed, which makes every existing hook silent
*/
silent?: 0 | 1 | "";
title?: string;
/**
* The brief each run gets (markdown); the call's payload is added below it as data
+9 -7
View File
@@ -13,7 +13,7 @@ import withTimeout from "@/src/utils/with-timeout";
import HarnessError from "@/src/harness/harness-error";
import deferBotJob from "@/src/functions/backend/db/bots-queue/defer-bot-job";
import recordBotHookFailure from "@/src/functions/backend/db/bot-hooks/record-bot-hook-failure";
import grabSessionHookId from "@/src/functions/backend/db/bot-hooks/grab-session-hook-id";
import isUnattendedHookSession from "@/src/functions/backend/db/bot-hooks/is-unattended-hook-session";
import recordCronJobFailure from "@/src/functions/backend/db/cron-jobs/record-cron-job-failure";
import scheduledRunRetryAt from "@/src/utils/scheduled-run-retry-at";
import {
@@ -101,14 +101,16 @@ export default async function processBotJob({
const user_id = await grabJobUserId({ job }).catch(() => null);
/**
* A crew request's session and a hook's run are hidden: neither is
* ever named. A hook's run changes no face (nobody follows it); a
* request's does, so the bot it was passed to shows its work.
* A crew request's session is hidden and is never named. A silent
* hook's thread is followed by nobody either: its runs change no face
* (a hook that isn't silent takes the conversation over, so its runs
* show like any other); a request's does, so the bot it was passed to
* shows its work.
*/
const in_ask = Boolean(
await grabSessionAskId({ session_id: Number(job.session_id) }).catch(() => null),
);
const in_hook = Boolean(await grabSessionHookId({ session_id: job.session_id }).catch(() => null));
const unattended = await isUnattendedHookSession({ session_id: job.session_id }).catch(() => false);
if (controller.signal.aborted) {
unregisterJobAbort({ job_id });
@@ -132,7 +134,7 @@ export default async function processBotJob({
* leave a bot that shows work with nothing behind it.
*/
const setFace = async (face: Omit<Parameters<typeof setBotFace>[0], "bot_id" | "user_id">) => {
if (!user_id || in_hook || controller.signal.aborted) return;
if (!user_id || unattended || controller.signal.aborted) return;
await pushBotNotice({ bot_id, bot: await setBotFace({ bot_id, user_id, ...face }) });
};
@@ -346,7 +348,7 @@ export default async function processBotJob({
* job to name. Tasks name too: a session the coordinator's
* delegation or a routine opened has no reply to name it.
*/
if (!in_ask && !in_hook && completion.message?.session_id) {
if (!in_ask && completion.message?.session_id) {
/**
* The message's session, not the job's as it was claimed: a
* reply that moved the conversation on answered in the new one.
+9 -8
View File
@@ -7,7 +7,7 @@ import pushBotUpdated from "./push-bot-updated";
import pushToSessionUser from "./push-to-session-user";
import withSessionMessageTasks from "./with-session-message-tasks";
import grabSessionAskId from "@/src/functions/backend/db/bot-sessions/grab-session-ask-id";
import grabSessionHookId from "@/src/functions/backend/db/bot-hooks/grab-session-hook-id";
import isUnattendedHookSession from "@/src/functions/backend/db/bot-hooks/is-unattended-hook-session";
type Params = {
bot_id: number | string;
@@ -33,9 +33,10 @@ type Params = {
* Pushes a new bot message to the open tabs of the user whose
* conversation it's in, and a face change to the user it's for
* (`pushBotUpdated`). A relayed report goes to the conversation it was
* posted in. A message in a hidden session (a crew request's, a hook's) is
* pushed nowhere: those are read in their own place. Best effort: a push
* that fails is logged and never fails the job that made the change.
* posted in. A message in a hidden session (a crew request's, or a silent
* hook's thread) is pushed nowhere: those are read in their own place.
* Best effort: a push that fails is logged and never fails the job that
* made the change.
*/
export default async function pushBotNotice({ bot_id, message, bot, relay, quiet_push }: Params) {
try {
@@ -52,14 +53,14 @@ export default async function pushBotNotice({ bot_id, message, bot, relay, quiet
async function push({ bot_id, message, bot, relay, quiet_push }: Params) {
/**
* A message in a hidden session goes to no conversation and no
* notification: a hook run's result is read in the hook's thread
* (which reloads from `server:hook-call-updated`), and a crew request's
* is read by the bots working it.
* notification: a silent hook's result is read in its thread (which
* reloads from `server:hook-call-updated`), and a crew request's is
* read by the bots working it.
*/
const hidden =
message &&
(Boolean(await grabSessionAskId({ session_id: Number(message.session_id) })) ||
Boolean(await grabSessionHookId({ session_id: message.session_id })));
(await isUnattendedHookSession({ session_id: message.session_id })));
if (message && !hidden) {
await pushToSessionUser({
+1 -1
View File
@@ -256,7 +256,7 @@ export default async function runBotReply({
const has_past_sessions = Boolean(
(
await BunSQLite.sql({
sql: `SELECT id FROM bot_sessions WHERE user_id = ? AND bot_id = ? AND workspace_id IS ? AND id != ? AND ask_id IS NULL AND hook_id IS NULL LIMIT 1`,
sql: `SELECT id FROM bot_sessions WHERE user_id = ? AND bot_id = ? AND workspace_id IS ? AND id != ? AND ask_id IS NULL LIMIT 1`,
values: [user_id, bot.id!, workspace_id ? Number(workspace_id) : null, session_id],
})
).payload?.[0],
+17 -4
View File
@@ -20,14 +20,19 @@ type Props = {
};
/**
* One session in the sessions modal: its title, the summary or last
* message, how long and how recent. The one on screen is
* Current (greyed out); any other opens on click (reopening a closed one,
* going back to the active one).
* One session in the sessions modal: its title (tagged Routine or Hook
* when one owns it), the summary or last message, how long and how
* recent. The one on screen is Current (greyed out); any other opens on
* click (reopening a closed one, going back to the active one).
*/
export default function BotSessionRow({ session, loading, disabled, onOpen, current }: Props) {
const preview = session.summary || session.last_message_text || "";
const at = session.last_activity_at || session.created_at;
const tag = session.routine_title
? { title: `A routine's thread: ${session.routine_title}`, label: "Routine" }
: session.hook_title
? { title: `A hook's thread: ${session.hook_title}`, label: "Hook" }
: null;
return (
<Button
@@ -60,6 +65,14 @@ export default function BotSessionRow({ session, loading, disabled, onOpen, curr
>
{session.title || "Untitled session"}
</Span>
{tag ? (
<Span
title={tag.title}
className="shrink-0 rounded-default bg-ink/5 px-1.5 text-[11px] leading-4 text-ink-secondary"
>
{tag.label}
</Span>
) : null}
{session.unread && !current ? (
<Span className="shrink-0 text-[11px] font-bold leading-4 text-ink">New</Span>
) : null}
+28 -4
View File
@@ -1,9 +1,11 @@
import Button from "@moduletrace/twui/layout/Button";
import Link from "@moduletrace/twui/layout/Link";
import Row from "@moduletrace/twui/layout/Row";
import Span from "@moduletrace/twui/layout/Span";
import Stack from "@moduletrace/twui/layout/Stack";
import AddModalShell from "@/src/layouts/bots/(partials)/add-modal-shell";
import type { BotHookWithNames } from "@/src/types";
import conversationHref from "@/src/utils/conversation-href";
import relativeTime from "@/src/utils/relative-time";
import HookCallText from "./hook-call-text";
import HookCalls from "./hook-calls";
@@ -19,13 +21,20 @@ type Props = {
};
/**
* A hook opened from a list in a modal of its own: what it is, and its
* thread, every call with what its run answered. Results only ever show
* here, never in a chat.
* A hook opened from a list in a modal of its own: what it is, then its
* every call with what its run answered, and the way to its thread (the
* session its runs leave their messages in, chatted in like any other).
*/
export default function HookDetailModal({ hook, onClose, onEdit }: Props) {
const runs = Number(hook?.run_count || 0);
const watching = hook?.source == "browser_notifications";
const thread_url = hook?.latest_session_id
? conversationHref({
bot_id: hook.bot_id!,
workspace_id: hook.workspace_id,
session_id: hook.latest_session_id,
})
: null;
return (
<AddModalShell
@@ -46,7 +55,22 @@ export default function HookDetailModal({ hook, onClose, onEdit }: Props) {
? "Its URL, signed calls only"
: "Its URL"}
</TaskFactRow>
<TaskFactRow label="State">{hook.enabled ? "On" : "Paused"}</TaskFactRow>
<TaskFactRow label="State">
{hook.enabled ? (hook.silent ? "On, silent" : "On") : "Paused"}
</TaskFactRow>
<TaskFactRow label="Thread">
{thread_url ? (
<Link
href={thread_url}
title="Open the session its latest call left its messages in"
className="text-ink underline underline-offset-2"
>
Its latest session
</Link>
) : (
"No run yet"
)}
</TaskFactRow>
<TaskFactRow label="Runs">{runs}</TaskFactRow>
<TaskFactRow label="Last called">
{hook.last_called_at ? relativeTime({ at: Number(hook.last_called_at) }) : "Never"}
+12 -1
View File
@@ -54,7 +54,8 @@ type Props = {
* its workspaces), what calls it (its URL, or a computer's browser
* notifications, chosen once when it's made), and then either whether its
* calls must be signed (the secret, the header it comes in and how it's
* written) or which notifications it takes. Makes a hook or edits one; a
* written) or which notifications it takes, and whether its runs take
* over the conversation or stay in the hook's own thread. Makes a hook or edits one; a
* saved secret is never shown again, so leaving it blank keeps it.
*/
export default function HookForm({
@@ -77,6 +78,7 @@ export default function HookForm({
const [title, setTitle] = useState(hook?.title || "");
const [instructions, setInstructions] = useState(hook?.instructions || "");
const [signed, setSigned] = useState(Boolean(hook?.has_signing_secret));
const [silent, setSilent] = useState(Boolean(hook?.silent));
const [secret, setSecret] = useState("");
const [header, setHeader] = useState(
hook?.signature_header || "X-Hub-Signature-256",
@@ -121,6 +123,7 @@ export default function HookForm({
title,
instructions,
workspace_id: place.workspace_id,
silent,
...signing,
...(watching ? { watch_filter } : {}),
},
@@ -132,6 +135,7 @@ export default function HookForm({
workspace_id: place.workspace_id,
title,
instructions,
silent,
source,
...signing,
...(watching ? { watch_computer_id, watch_filter } : {}),
@@ -231,6 +235,13 @@ export default function HookForm({
onChange={(e) => setWatchFilter(e.target.value)}
/>
) : null}
<Checkbox
title="Run silently"
label="Keep its runs in the hook's own thread: they never take over the conversation or notify me. Read them from the hook, or in the bot's sessions."
checked={silent}
changeHandler={setSilent}
labelProps={{ className: "w-full" }}
/>
{watching ? null : (
<>
<Checkbox
+4 -3
View File
@@ -26,8 +26,9 @@ type Props = {
};
/**
* One hook: its bot's avatar, its name (Paused when it is), which opens
* it, what calls it, how often it ran and when it was last called, then Pause or Resume,
* One hook: its bot's avatar, its name (Paused, Silent when it is silent
* about its runs), which opens it, what calls it, how often it ran and
* when it was last called, then Pause or Resume,
* Edit, Calls, New URL (not for notification hooks: their URL is never
* shown) and Delete.
*/
@@ -45,7 +46,7 @@ export default function HookRow({ hook, busy, onOpen, onToggle, onEdit, onCalls,
}
title={title}
onOpen={onOpen}
badge={hook.enabled ? undefined : "Paused"}
badge={hook.enabled ? (hook.silent ? "Silent" : undefined) : "Paused"}
subtitle={hookSubtitle({ hook, show_bot: !compact, show_workspace: !compact })}
>
<SettingsRowAction
+21 -5
View File
@@ -4,6 +4,7 @@ import type { CronJobWithNames } from "@/src/types";
import SettingsListRow from "@/src/pages/admin/settings/(partials)/settings-list-row";
import SettingsRowAction from "@/src/pages/admin/settings/(partials)/settings-row-action";
import routineSubtitle from "@/src/utils/routine-subtitle";
import conversationHref from "@/src/utils/conversation-href";
import BotAvatar from "./bot-avatar";
type Props = {
@@ -25,15 +26,23 @@ type Props = {
/**
* One routine: its bot's avatar, its name (Paused or Done when it is),
* whose it is and when it runs, then Chat, Pause or Resume, Edit, Hand
* over, Delete.
* whose it is and when it runs, then Thread (the session its latest run
* left its messages in), Chat, Pause or Resume, Edit, Hand over, Delete.
*/
export default function RoutineRow({ cron_job, busy, onToggle, onEdit, onDelete, onHandOver, compact }: Props) {
const title = cron_job.title || `Routine ${cron_job.id}`;
const done = Boolean(cron_job.max_runs && Number(cron_job.run_count || 0) >= cron_job.max_runs);
const chat_url = cron_job.workspace_id
? `/admin/workspaces/${cron_job.workspace_id}/bots/${cron_job.bot_id}`
: `/admin/bots/${cron_job.bot_id}`;
const chat_url = conversationHref({
bot_id: cron_job.bot_id!,
workspace_id: cron_job.workspace_id,
});
const thread_url = cron_job.latest_session_id
? conversationHref({
bot_id: cron_job.bot_id!,
workspace_id: cron_job.workspace_id,
session_id: cron_job.latest_session_id,
})
: null;
return (
<SettingsListRow
@@ -52,6 +61,13 @@ export default function RoutineRow({ cron_job, busy, onToggle, onEdit, onDelete,
show_workspace: !compact,
})}
>
{thread_url ? (
<SettingsRowAction
title={`Open ${title}'s latest thread: what its runs left there, where you can chat with ${cron_job.bot_name || "the bot"}`}
label="Thread"
href={thread_url}
/>
) : null}
{compact ? null : (
<SettingsRowAction title={`Chat with ${cron_job.bot_name || "the bot"}`} label="Chat" href={chat_url} />
)}
+6 -25
View File
@@ -1,36 +1,17 @@
import BunSQLite from "@moduletrace/bun-sqlite";
import deleteHookSessionRows from "@/src/functions/backend/db/bot-hooks/delete-hook-session-rows";
import detachHookSessions from "@/src/functions/backend/db/bot-hooks/detach-hook-sessions";
import { grabHookEventsKeepDays } from "@/src/functions/backend/db/app-settings/grab-hook-events-keep-days";
import deleteUnlinkedAttachmentMedia from "@/src/functions/backend/db/media/delete-unlinked-attachment-media";
/**
* Deletes hook calls (with their responses) older than the install's
* retention (`grabHookEventsKeepDays`), the messages their runs left in
* hooks' hidden sessions, and the sessions of hooks that are gone. Messages
* a call posted into a chat before hooks had their own thread stay.
* Deletes hook calls older than the install's retention
* (`grabHookEventsKeepDays`) and lets go of the sessions of hooks that are
* gone. The messages those calls left in a hook's thread stay: it's the
* user's own session now, read and chatted in like any other.
*/
export default async function pruneBotHookEvents() {
const cutoff = Date.now() - (await grabHookEventsKeepDays()) * 24 * 60 * 60 * 1000;
const messages = `SELECT m.id FROM bot_messages m JOIN bot_sessions s ON s.id = m.session_id
WHERE s.hook_id IS NOT NULL AND m.id IN (SELECT response_message_id FROM bot_hook_events WHERE created_at < ?)`;
await BunSQLite.sql({ sql: `DELETE FROM bot_message_reactions WHERE message_id IN (${messages})`, values: [cutoff] });
/**
* The call's uploads go with its messages: their `media` row is what
* the deleted link was the only way to reach.
*/
const uploads = await BunSQLite.sql<{ media_id: number }>({
sql: `SELECT media_id FROM bot_message_media WHERE message_id IN (${messages})`,
values: [cutoff],
});
await BunSQLite.sql({ sql: `DELETE FROM bot_message_media WHERE message_id IN (${messages})`, values: [cutoff] });
await deleteUnlinkedAttachmentMedia({ media_ids: (uploads.payload || []).map((row) => Number(row.media_id)) }).catch(() => []);
await BunSQLite.sql({ sql: `DELETE FROM bot_messages WHERE id IN (${messages})`, values: [cutoff] });
await deleteHookSessionRows({});
await detachHookSessions({});
return await BunSQLite.sql({
sql: `DELETE FROM bot_hook_events WHERE created_at < ? RETURNING id`,
@@ -45,10 +45,6 @@ export default async function createAsk({
throw new AppError(`That request doesn't come from this bot's conversation.`);
}
if (origin.hook_id) {
throw new AppError(`A hook call can't ask the crew.`);
}
const workspace_id = origin.workspace_id || null;
const askable = await askableBots({
user_id,
@@ -9,8 +9,8 @@ type Params = {
/**
* The session one bot keeps its part of an ask in: the coordinator's review,
* then the asked bot's incoming brief and answer. Hidden from every
* conversation and session list (`visibleSessionSql`), and never opened by a
* user.
* conversation and session list (`isHiddenSession`, and the `ask_id IS NULL`
* in `followedSessionSql`), and never opened by a user.
*/
export default async function ensureAskSession({ ask, bot_id }: Params): Promise<BUN_SQLITE_COBBLE_BOT_SESSIONS> {
const existing = await BunSQLite.sql<BUN_SQLITE_COBBLE_BOT_SESSIONS>({
@@ -40,12 +40,18 @@ type Params = {
source?: BotHookSource;
watch_computer_id?: number | string | null;
watch_filter?: string | null;
/**
* Its runs stay in its own thread, pushed nowhere, instead of taking
* over the conversation (see `updateBotHook`).
*/
silent?: boolean;
};
/**
* Gives one of the user's bots a hook: a secret URL whose calls each queue
* the brief, with the call's payload, as a task there (`fireBotHook`), in
* the hook's own thread, never in a chat. Returns the hook and its token, which is shown
* the hook's own thread: the conversation's active one unless it's silent,
* where the thread stays its own. Returns the hook and its token, which is shown
* this once: only its hash is kept. A browser-notification hook needs a
* computer both the user and the bot reach; its token is kept encrypted
* for that computer's watcher, set up before this returns
@@ -64,6 +70,7 @@ export default async function createBotHook({
source = "url",
watch_computer_id,
watch_filter,
silent,
}: Params): Promise<BotHookWithToken> {
const conversation = await grabUserConversation({ user_id, bot_id, workspace_id });
const bot_id_num = conversation.bot.id;
@@ -109,6 +116,7 @@ export default async function createBotHook({
signature_format: secret ? signature_format || "sha256=hex" : undefined,
enabled: 1,
run_count: 0,
silent: silent ? 1 : 0,
},
],
});
@@ -1,5 +1,5 @@
import BunSQLite from "@moduletrace/bun-sqlite";
import deleteHookSessionRows from "./delete-hook-session-rows";
import detachHookSessions from "./detach-hook-sessions";
import grabUserBotHook from "./grab-user-bot-hook";
import syncComputerNotifyWatch from "./sync-computer-notify-watch";
@@ -9,9 +9,10 @@ type Params = {
};
/**
* Deletes one of the user's hooks, its recorded calls and its hidden
* sessions (foreign keys are off outside the server, so they go first,
* explicitly). A run already queued carries on. A notification hook's URL is taken off its
* Deletes one of the user's hooks and its recorded calls. Its sessions
* stay: they're ordinary threads once no hook owns them
* (`detachHookSessions`), so the user keeps their history. A run already
* queued carries on. A notification hook's URL is taken off its
* computer's watcher.
*/
export default async function deleteBotHook({ user_id, hook_id }: Params) {
@@ -22,7 +23,7 @@ export default async function deleteBotHook({ user_id, hook_id }: Params) {
values: [hook.id!],
});
await deleteHookSessionRows({ hook_id: hook.id! });
await detachHookSessions({ hook_id: hook.id! });
const res = await BunSQLite.sql({
sql: `DELETE FROM bot_hooks WHERE id = ?`,
@@ -1,51 +0,0 @@
import BunSQLite from "@moduletrace/bun-sqlite";
import deleteUnlinkedAttachmentMedia from "../media/delete-unlinked-attachment-media";
type Params = {
/**
* Only this hook's. Left out: every hidden session whose hook is gone.
*/
hook_id?: number | string;
};
/**
* Deletes hooks' hidden sessions with what's in them. Explicitly, child
* rows first, since foreign keys are off outside the server process. A
* session with a run still open stays until that run ends (a deleted
* hook's run carries on), and the daily prune takes it then.
*/
export default async function deleteHookSessionRows({ hook_id }: Params) {
const res = await BunSQLite.sql<{ id: number }>({
sql: `SELECT s.id FROM bot_sessions s WHERE s.hook_id IS NOT NULL
AND ${hook_id ? `s.hook_id = ?` : `s.hook_id NOT IN (SELECT id FROM bot_hooks)`}
AND NOT EXISTS (SELECT 1 FROM bots_queue q WHERE q.session_id = s.id AND q.status IN ('pending', 'processing'))`,
values: hook_id ? [Number(hook_id)] : [],
});
const list = (res.payload || []).map((row) => Number(row.id)).join(", ");
if (!list) return;
const messages = `SELECT id FROM bot_messages WHERE session_id IN (${list})`;
await BunSQLite.sql({
sql: `DELETE FROM bots_queue_updates WHERE bots_queue_id IN (SELECT id FROM bots_queue WHERE session_id IN (${list}))`,
});
await BunSQLite.sql({ sql: `DELETE FROM bots_queue WHERE session_id IN (${list})` });
await BunSQLite.sql({ sql: `DELETE FROM bot_tasks WHERE session_id IN (${list})` });
await BunSQLite.sql({ sql: `DELETE FROM bot_message_reactions WHERE message_id IN (${messages})` });
/**
* An upload's bytes are its `media` row, which the message's link was
* the only way to reach.
*/
const uploads = await BunSQLite.sql<{ media_id: number }>({
sql: `SELECT media_id FROM bot_message_media WHERE message_id IN (${messages})`,
});
await BunSQLite.sql({ sql: `DELETE FROM bot_message_media WHERE message_id IN (${messages})` });
await deleteUnlinkedAttachmentMedia({ media_ids: (uploads.payload || []).map((row) => Number(row.media_id)) }).catch(() => []);
await BunSQLite.sql({ sql: `DELETE FROM bot_messages WHERE session_id IN (${list})` });
await BunSQLite.sql({ sql: `DELETE FROM bot_sessions WHERE id IN (${list})` });
}
@@ -0,0 +1,31 @@
import BunSQLite from "@moduletrace/bun-sqlite";
type Params = {
/**
* The hook being deleted. Left out: every session whose hook is
* already gone.
*/
hook_id?: number | string | null;
};
/**
* Lets a hook's sessions go without deleting them: they're the user's own
* threads now (`hook_id` null, a `hook` status row closed like any other),
* so they stay in the session list and can be reopened. A run already
* queued carries on there.
*/
export default async function detachHookSessions({ hook_id }: Params = {}) {
const res = await BunSQLite.sql({
sql: `UPDATE bot_sessions SET
hook_id = NULL,
status = CASE WHEN status = 'hook' THEN 'closed' ELSE status END,
updated_at = ?
WHERE hook_id IS NOT NULL
${hook_id ? "AND hook_id = ?" : "AND NOT EXISTS (SELECT 1 FROM bot_hooks h WHERE h.id = bot_sessions.hook_id)"}`,
values: hook_id ? [Date.now(), Number(hook_id)] : [Date.now()],
});
if (!res.success) {
throw new Error(`Couldn't detach the hook's sessions: ${res.error}`);
}
}
@@ -1,37 +1,84 @@
import type {
BUN_SQLITE_COBBLE_BOT_HOOKS,
BUN_SQLITE_COBBLE_BOT_SESSIONS,
} from "@/db/types/db";
import BunSQLite from "@moduletrace/bun-sqlite";
import type { BUN_SQLITE_COBBLE_BOT_HOOKS } from "@/db/types/db";
import { grabBotSessionMaxMessages } from "../app-settings/grab-bot-session-max-messages";
import activateBotSession from "../bot-sessions/activate-bot-session";
import createBotSession from "../bot-sessions/create-bot-session";
import grabUserBotSession from "../bot-sessions/grab-user-bot-session";
import rollOverLinkedSession from "../bot-sessions/roll-over-linked-session";
type Params = {
hook: BUN_SQLITE_COBBLE_BOT_HOOKS;
bot_id: number;
workspace_id: number | null;
bot_id: number | string;
workspace_id?: number | string | null;
};
/**
* The hidden session a hook's runs work in where it runs now (status
* `hook`, in no conversation or list), started on its first call there.
* Every session query that lists or picks a conversation leaves these out
* (`hook_id IS NULL`); their results are read in the hook's thread.
* The session a hook's call works in: the hook's own thread, never the
* conversation's active session by itself. Started closed when the hook has
* none, so a run never lands in a chat the user was having; once it's full
* (`grabBotSessionMaxMessages`) it carries on in a new linked session
* (`rollOverLinkedSession`). A hook that isn't silent takes the
* conversation over: its thread becomes the active session first, so the
* user sees the run and can chat there (`activateBotSession`). Returns the
* session's id.
*/
export default async function ensureHookSession({ hook, bot_id, workspace_id }: Params): Promise<number> {
const existing = (
await BunSQLite.sql<{ id: number }>({
sql: `SELECT id FROM bot_sessions WHERE hook_id = ? AND bot_id = ? AND workspace_id IS ? ORDER BY id DESC LIMIT 1`,
values: [hook.id!, bot_id, workspace_id],
})
).payload?.[0];
const user_id = hook.user_id!;
const workspace = workspace_id ? Number(workspace_id) : null;
if (existing?.id) return Number(existing.id);
const session = await createBotSession({
user_id: hook.user_id!,
bot_id,
workspace_id,
status: "hook",
hook_id: Number(hook.id),
title: `Hook: ${hook.title || hook.id}`,
const res = await BunSQLite.sql<BUN_SQLITE_COBBLE_BOT_SESSIONS>({
sql: `SELECT s.* FROM bot_sessions s
WHERE s.hook_id = ? AND s.user_id = ? AND s.bot_id = ? AND s.workspace_id IS ?
ORDER BY s.id DESC LIMIT 1`,
values: [hook.id!, user_id, bot_id, workspace],
});
let session = res.payload?.[0];
if (!session?.id) {
session = await createBotSession({
user_id,
bot_id,
workspace_id: workspace,
status: "closed",
hook_id: Number(hook.id!),
title: `Hook: ${hook.title || hook.id}`,
});
} else {
const count =
Number(
(
await BunSQLite.sql<{ n: number }>({
sql: `SELECT COUNT(*) AS n FROM bot_messages WHERE session_id = ?`,
values: [session.id!],
})
).payload?.[0]?.n,
) || 0;
if (count >= (await grabBotSessionMaxMessages())) {
const next = await rollOverLinkedSession({
session,
user_id,
bot_id: Number(bot_id),
workspace_id: workspace,
});
const carried = next ? await grabUserBotSession({ session_id: next, user_id }) : null;
if (carried?.id) session = carried;
}
}
if (!session?.id) {
throw new Error(`Couldn't open a session for the hook ${hook.id}.`);
}
if (!hook.silent && session.status != "active") {
session = await activateBotSession({ session });
}
return Number(session.id);
}
}
@@ -49,7 +49,8 @@ export type FireBotHookResult = {
/**
* Takes one call to a hook: records it, then gives it to its bot as a task
* in the hook's own hidden session (`ensureHookSession`). A call while the hook's last run is
* in the hook's own thread (`ensureHookSession`: silent hooks keep it out of
* sight, the others take the conversation over for the run). A call while the hook's last run is
* still waiting (queued, never tried) joins that run's brief instead, up
* to `AppData.BotHookMaxEventsPerRun` calls, so a burst makes one run and
* none is lost; once a run has started, the next call queues a new one.
@@ -22,7 +22,8 @@ type Params = {
/**
* The user's hooks with their bot (its face as the user sees it) and
* workspace names, the most recently called first. Never their token hash
* workspace names, the most recently called first, each with the id of the
* session its latest call left its messages in. Never their token hash
* or signing secret, nor a notification hook's stored token.
*/
export default async function grabBotHooks({
@@ -55,7 +56,8 @@ export default async function grabBotHooks({
const res = await BunSQLite.sql<BotHookWithNames>({
sql: `SELECT h.id, h.created_at, h.updated_at, h.user_id, h.bot_id, h.workspace_id, h.title,
h.instructions, h.computer_id, h.token_prefix, h.signature_header, h.signature_format,
h.enabled, h.run_count, h.last_called_at, h.last_job_id, h.last_error,
h.enabled, h.run_count, h.last_called_at, h.last_job_id, h.last_error, h.silent,
(SELECT r.id FROM bot_sessions r WHERE r.hook_id = h.id ORDER BY r.id DESC LIMIT 1) AS latest_session_id,
h.source, h.watch_computer_id, h.watch_filter, wc.name AS watch_computer_name,
(COALESCE(h.signing_secret, '') != '') AS has_signing_secret,
b.name AS bot_name, b.kind AS bot_kind, b.hue AS bot_hue, b.color AS bot_color, b.stone AS bot_stone, ${face.sql},
@@ -1,21 +0,0 @@
import BunSQLite from "@moduletrace/bun-sqlite";
type Params = {
session_id?: number | string | null;
};
/**
* The hook whose runs a session holds, or null for any other session.
*/
export default async function grabSessionHookId({ session_id }: Params) {
if (!session_id) return null;
const hook_id = (
await BunSQLite.sql<{ hook_id: number | null }>({
sql: `SELECT hook_id FROM bot_sessions WHERE id = ? LIMIT 1`,
values: [session_id],
})
).payload?.[0]?.hook_id;
return hook_id ? Number(hook_id) : null;
}
@@ -0,0 +1,24 @@
import BunSQLite from "@moduletrace/bun-sqlite";
type Params = {
session_id?: number | string | null;
};
/**
* Whether a session is a silent hook's thread. Its runs are followed by
* nobody: they change no face and are pushed nowhere. A hook that isn't
* silent takes the conversation over instead, so its runs show like any
* other and this is false for them.
*/
export default async function isUnattendedHookSession({ session_id }: Params) {
if (!session_id) return false;
const res = await BunSQLite.sql<{ unattended: number }>({
sql: `SELECT (h.id IS NOT NULL AND h.silent = 1) AS unattended
FROM bot_sessions s LEFT JOIN bot_hooks h ON h.id = s.hook_id
WHERE s.id = ? LIMIT 1`,
values: [Number(session_id)],
});
return res.payload?.[0]?.unattended == 1;
}
@@ -0,0 +1,17 @@
import BunSQLite from "@moduletrace/bun-sqlite";
/**
* Hooks from before `silent` existed run silently from now on: an install
* that updates shouldn't have its hooks start taking over conversations
* unasked. New hooks are asked about it when they're made, and the flag is
* only null until this runs once.
*/
export default async function migrateHookSilence() {
const res = await BunSQLite.sql({
sql: `UPDATE bot_hooks SET silent = 1 WHERE silent IS NULL`,
});
if (!res.success) {
throw new Error(`Couldn't set the existing hooks silent: ${res.error}`);
}
}
@@ -27,6 +27,12 @@ type Params = {
* A browser-notification hook's filter; empty takes them all.
*/
watch_filter?: string;
/**
* True: its runs stay in its own thread, pushed nowhere and off the
* bot's face. False: each run takes over the conversation, in a
* session the user sees and can chat in.
*/
silent?: boolean;
/**
* Where it runs from now, with the same bot: one of its
* workspaces, or null for its own chat.
@@ -38,7 +44,8 @@ type Params = {
/**
* Changes one of the user's hooks: its name and brief, pauses or resumes
* it, sets how its calls are signed or, for browser notifications, which
* ones it takes, or moves it to another of its bot's places. Its token stays (rotate it with `rotateBotHookToken`). A move
* ones it takes, whether its runs take over the conversation or stay in
* their own thread, or moves it to another of its bot's places. Its token stays (rotate it with `rotateBotHookToken`). A move
* is refused while its last run is open (a call could still join it
* there); its computer stays only if the bot reaches it in the new place,
* and a notification hook can't go where its watched computer isn't.
@@ -64,6 +71,8 @@ export default async function updateBotHook({ user_id, hook_id, data }: Params)
if (data.enabled) set("last_error", null);
}
if (data.silent !== undefined) set("silent", data.silent ? 1 : 0);
const watching = hook.source == "browser_notifications";
if (data.watch_filter !== undefined) {
@@ -0,0 +1,47 @@
import type { BUN_SQLITE_COBBLE_BOT_SESSIONS } from "@/db/types/db";
import BunSQLite from "@moduletrace/bun-sqlite";
import deleteSessionRows from "./delete-session-rows";
type Params = {
/**
* The user's session to make the conversation's active one.
*/
session: BUN_SQLITE_COBBLE_BOT_SESSIONS;
};
/**
* Makes a session the active one of its conversation: the session that was
* active is closed, and one of its own that is still empty is deleted
* instead, together with its rows (`deleteSessionRows`), since a job it
* holds would otherwise point at a session that is gone. The caller checks
* whatever must be refused first. Returns the session, active.
*/
export default async function activateBotSession({
session,
}: Params): Promise<BUN_SQLITE_COBBLE_BOT_SESSIONS> {
const now = Date.now();
const workspace_id = session.workspace_id || null;
const emptied = (
await BunSQLite.sql<{ id: number }>({
sql: `SELECT id FROM bot_sessions WHERE user_id = ? AND bot_id = ? AND workspace_id IS ? AND status = 'active'
AND NOT EXISTS (SELECT 1 FROM bot_messages m WHERE m.session_id = bot_sessions.id)`,
values: [session.user_id!, session.bot_id!, workspace_id],
})
).payload || [];
await deleteSessionRows({ session_ids: emptied.map((row) => Number(row.id)) });
await BunSQLite.sql({
sql: `UPDATE bot_sessions SET status = 'closed', unread = 0, updated_at = ?
WHERE user_id = ? AND bot_id = ? AND workspace_id IS ? AND status = 'active'`,
values: [now, session.user_id!, session.bot_id!, workspace_id],
});
await BunSQLite.sql({
sql: `UPDATE bot_sessions SET status = 'active', updated_at = ? WHERE id = ?`,
values: [now, session.id!],
});
return { ...session, status: "active", updated_at: now };
}
@@ -5,11 +5,13 @@ import AppError from "@/src/utils/app-error";
import insertBotMessage from "../bots/insert-bot-message";
import createBotSession from "./create-bot-session";
import grabActiveBotSession from "./grab-active-bot-session";
import grabUserBotSession from "./grab-user-bot-session";
type Params = {
/**
* The session the bot is answering in: it must be the conversation's
* active one.
* active one, unless `allow_inactive` moves a routine's or a silent
* hook's own thread, which never is.
*/
session_id: number | string;
user_id: number | string;
@@ -30,6 +32,18 @@ type Params = {
* summary.
*/
job_id?: number | null;
/**
* Move the given session even when it isn't the conversation's active
* one: a routine's or a silent hook's own thread.
*/
allow_inactive?: boolean;
/**
* The new session's status. `active` (default) moves the conversation
* on; `closed` keeps a routine's or a silent hook's thread beside the
* conversation, so its next run continues there without taking the
* chat over.
*/
next_status?: "active" | "closed";
};
/**
@@ -39,6 +53,9 @@ type Params = {
* the next prompt as written) and opens the new one as a bot message
* (`carried_from_session_id`), and the reply's own answer follows it
* there. The new session is titled by the bot (else after the old one).
* The same carries a routine's or a hook's own thread into its next
* session (`allow_inactive`, `next_status` closed), keeping the link to
* the routine or hook and the conversation's active session untouched.
* Returns that first message, for the caller to push.
*/
export default async function carryOverBotSession({
@@ -49,15 +66,28 @@ export default async function carryOverBotSession({
summary,
title,
job_id,
allow_inactive,
next_status = "active",
}: Params): Promise<BUN_SQLITE_COBBLE_BOT_MESSAGES> {
const text = summary.trim().slice(0, AppData.BotSessionSummaryMaxChars);
if (!text) throw new AppError(`The summary is empty.`);
const active = await grabActiveBotSession({ user_id, bot_id, workspace_id });
const active = allow_inactive
? await grabUserBotSession({ session_id, user_id })
: await grabActiveBotSession({ user_id, bot_id, workspace_id });
if (!active?.id || active.id != Number(session_id)) {
throw new AppError(`This session isn't the conversation's current one, so it can't be moved on from.`);
if (
!active?.id ||
active.id != Number(session_id) ||
Number(active.bot_id) != Number(bot_id) ||
(Number(active.workspace_id) || null) != (Number(workspace_id) || null)
) {
throw new AppError(
allow_inactive
? `That session isn't part of this conversation, so it can't be moved on from.`
: `This session isn't the conversation's current one, so it can't be moved on from.`,
);
}
const message_count =
@@ -93,6 +123,9 @@ export default async function carryOverBotSession({
bot_id,
workspace_id,
previous_session_id: active.id,
status: next_status,
hook_id: Number(active.hook_id) || null,
routine_id: Number(active.routine_id) || null,
title:
title?.replace(/\s+/g, " ").trim().slice(0, AppData.BotSessionTitleMaxChars) ||
active.title ||
@@ -1,15 +1,9 @@
import type { BUN_SQLITE_COBBLE_BOT_MESSAGES } from "@/db/types/db";
import { AppData } from "@/src/data/app-data";
import { SessionContinuePrompt } from "@/src/data/harness-prompts";
import parseSessionName from "@/src/bots-queue/parse-session-name";
import sessionNameTranscript from "@/src/bots-queue/session-name-transcript";
import generateText from "@/src/harness/text/generate-text";
import { runWithHarnessUsageScope } from "@/src/harness/usage/harness-usage-scope";
import AppError from "@/src/utils/app-error";
import grabBotMessages from "../bots/grab-bot-messages";
import carryOverBotSession from "./carry-over-bot-session";
import grabActiveBotSession from "./grab-active-bot-session";
import hasOpenSessionJob from "./has-open-session-job";
import writeSessionContinuation from "./write-session-continuation";
type Params = {
user_id: number | string;
@@ -22,10 +16,11 @@ type Params = {
* menu (and the automatic rollover, `rollOverBotSession`): does what the
* bot does with `continue_in_new_session`. The bot's
* text model writes the new session's title and the summary from the
* session's latest messages, then `carryOverBotSession` closes this
* session for good and opens the new one with the summary. Refused while
* the bot is still working in the session, since its answer would land in
* the closed one. Returns the summary's message, for the caller to push.
* session's latest messages (`writeSessionContinuation`), then
* `carryOverBotSession` closes this session for good and opens the new one
* with the summary. Refused while the bot is still working in the session,
* since its answer would land in the closed one. Returns the summary's
* message, for the caller to push.
*/
export default async function continueBotSession({
user_id,
@@ -40,35 +35,13 @@ export default async function continueBotSession({
throw new AppError(`The bot is still working in this session. Wait for it to finish, or stop it, then continue.`);
}
const messages = await grabBotMessages({
const written = await writeSessionContinuation({
session_id: active.id,
limit: AppData.BotSessionSummaryMessages,
user_id,
bot_id,
workspace_id,
});
if (!messages.length) throw new AppError(`This session has no messages yet: it's already fresh.`);
const result = await runWithHarnessUsageScope({
scope: {
user_id,
bot_id,
workspace_id: workspace_id || null,
session_id: active.id,
job_id: null,
message_id: null,
},
task: () =>
generateText({
messages: [
{ role: "system", content: SessionContinuePrompt },
{ role: "user", content: sessionNameTranscript({ messages }) },
],
bot_id,
workspace_id,
}),
});
const written = parseSessionName({ text: result.text });
if (!written?.summary) {
throw new AppError(`Couldn't write the summary to carry over. Try again.`);
}
@@ -81,4 +54,4 @@ export default async function continueBotSession({
summary: written.summary,
title: written.title,
});
}
}
@@ -25,6 +25,10 @@ type Params = {
* The hook whose runs it holds (status `hook`).
*/
hook_id?: number | null;
/**
* The routine (`cron_jobs`) whose runs it holds.
*/
routine_id?: number | null;
title?: string | null;
};
@@ -39,6 +43,7 @@ export default async function createBotSession({
previous_session_id,
status = "active",
hook_id,
routine_id,
title,
}: Params): Promise<BUN_SQLITE_COBBLE_BOT_SESSIONS> {
const now = Date.now();
@@ -50,6 +55,7 @@ export default async function createBotSession({
previous_session_id: previous_session_id || undefined,
status,
hook_id: hook_id || undefined,
routine_id: routine_id || undefined,
title: title || undefined,
unread: 0,
last_activity_at: now,
@@ -0,0 +1,70 @@
import type {
BUN_SQLITE_COBBLE_BOT_SESSIONS,
BUN_SQLITE_COBBLE_CRON_JOBS,
} from "@/db/types/db";
import BunSQLite from "@moduletrace/bun-sqlite";
import { grabBotSessionMaxMessages } from "../app-settings/grab-bot-session-max-messages";
import createBotSession from "./create-bot-session";
import rollOverLinkedSession from "./roll-over-linked-session";
type Params = {
cron_job: BUN_SQLITE_COBBLE_CRON_JOBS;
};
/**
* The session a routine's run works in: the routine's own thread, not the
* conversation's active session, so a run's messages never land in a chat
* the user was having. Started closed when the routine has none, so it
* doesn't take the conversation over; the user opens it from the routine
* or the sessions list and can chat there. Once it's full
* (`grabBotSessionMaxMessages`) it carries on in a new linked session
* (`rollOverLinkedSession`). Returns the session's id.
*/
export default async function ensureRoutineSession({ cron_job }: Params): Promise<number> {
const user_id = cron_job.user_id!;
const bot_id = Number(cron_job.bot_id);
const workspace_id = Number(cron_job.workspace_id) || null;
const res = await BunSQLite.sql<BUN_SQLITE_COBBLE_BOT_SESSIONS>({
sql: `SELECT s.* FROM bot_sessions s
WHERE s.routine_id = ? AND s.user_id = ? AND s.bot_id = ? AND s.workspace_id IS ?
ORDER BY s.id DESC LIMIT 1`,
values: [cron_job.id!, user_id, bot_id, workspace_id],
});
const latest = res.payload?.[0];
if (!latest?.id) {
const created = await createBotSession({
user_id,
bot_id,
workspace_id,
status: "closed",
routine_id: Number(cron_job.id!),
title: cron_job.title || "Scheduled task",
});
return Number(created.id);
}
const count =
Number(
(
await BunSQLite.sql<{ n: number }>({
sql: `SELECT COUNT(*) AS n FROM bot_messages WHERE session_id = ?`,
values: [latest.id!],
})
).payload?.[0]?.n,
) || 0;
if (count < (await grabBotSessionMaxMessages())) return Number(latest.id);
const next = await rollOverLinkedSession({
session: latest,
user_id,
bot_id,
workspace_id,
});
return next || Number(latest.id);
}
@@ -0,0 +1,53 @@
import { Database } from "bun:sqlite";
import { describe, expect, test } from "bun:test";
import followedSessionSql from "./followed-session-sql";
/**
* What counts as the user's own activity: every session but a crew
* request's and a silent hook's thread. Run against real SQLite, since the
* rule is the SQL itself.
*/
const db = new Database(":memory:");
db.run(
`CREATE TABLE bot_hooks (id INTEGER PRIMARY KEY, silent INTEGER)`,
);
db.run(`INSERT INTO bot_hooks VALUES (4, 1), (5, 0)`);
db.run(
`CREATE TABLE bot_sessions (id INTEGER PRIMARY KEY, title TEXT, ask_id INTEGER, hook_id INTEGER, routine_id INTEGER)`,
);
db.run(`INSERT INTO bot_sessions VALUES
(1, 'The chat', NULL, NULL, NULL),
(2, 'A crew request', 3, NULL, NULL),
(3, 'A silent hook', NULL, 4, NULL),
(4, 'A hook that talks', NULL, 5, NULL),
(5, 'A routine', NULL, NULL, 9)`);
function ids(alias?: string) {
const sql = `SELECT id FROM bot_sessions${alias ? ` ${alias}` : ""} WHERE ${followedSessionSql(alias ? { alias } : {})} ORDER BY id`;
return (db.query(sql).all() as { id: number }[]).map((row) => row.id);
}
describe("followedSessionSql", () => {
test("keeps the chat, a routine's thread and a hook that isn't silent", () => {
expect(ids()).toEqual([1, 4, 5]);
});
test("leaves out a crew request and a silent hook's thread", () => {
expect(ids()).not.toContain(2);
expect(ids()).not.toContain(3);
});
test("reads the alias it's given, for queries that join sessions", () => {
expect(ids("s")).toEqual([1, 4, 5]);
});
test("a session whose hook is gone is the user's again", () => {
db.run(`INSERT INTO bot_sessions VALUES (6, 'A detached hook thread', NULL, 99, NULL)`);
expect(ids()).toEqual([1, 4, 5, 6]);
db.run(`DELETE FROM bot_sessions WHERE id = 6`);
});
});
@@ -0,0 +1,20 @@
import BunSQLite from "@moduletrace/bun-sqlite";
type Params = {
/**
* The table alias to test, for queries that join sessions.
*/
alias?: string;
};
/**
* The sessions a user follows: every one but a crew request's (status
* `ask`, read by the bots working it) and a silent hook's thread (its runs
* are pushed nowhere and read where the hook is). Used where a session
* should count as the user's activity: unread marks, the rail, the
* dashboard and the bot's face. Routine threads and a hook that isn't
* silent always count.
*/
export default function followedSessionSql({ alias = "bot_sessions" }: Params = {}) {
return `(${alias}.ask_id IS NULL AND NOT EXISTS (SELECT 1 FROM bot_hooks h WHERE h.id = ${alias}.hook_id AND h.silent = 1))`;
}
@@ -1,6 +1,8 @@
import BunSQLite from "@moduletrace/bun-sqlite";
import { AppData } from "@/src/data/app-data";
import type { BotSessionListItem } from "@/src/types";
import followedSessionSql from "./followed-session-sql";
import visibleSessionSql from "./visible-session-sql";
type Params = {
/**
@@ -18,12 +20,19 @@ type Params = {
* How many to return; a page by default.
*/
limit?: number;
/**
* Leave out a silent hook's thread, which the rail doesn't list (it's
* read in the sessions modal and on the hook itself).
*/
attended_only?: boolean;
};
/**
* A user's conversation's sessions for the sessions modal, latest activity first,
* each with its message count and latest message. Empty sessions are left
* out unless active.
* A user's conversation's sessions for the sessions modal, latest activity
* first, each with its message count, latest message and the routine or
* hook that runs in it. Empty sessions are left out unless active. A
* routine's and a hook's threads are ordinary sessions, so the user can
* open and chat in them; only a crew request's is hidden.
*/
export default async function grabBotSessions({
user_id,
@@ -32,6 +41,7 @@ export default async function grabBotSessions({
query,
page = 1,
limit,
attended_only,
}: Params): Promise<BotSessionListItem[]> {
const search = query?.trim();
const like = search ? `%${search.replace(/[\\%_]/g, (c) => `\\${c}`)}%` : null;
@@ -41,9 +51,14 @@ export default async function grabBotSessions({
sql += `SELECT s.*,\n`;
sql += ` (SELECT COUNT(*) FROM bot_messages m WHERE m.session_id = s.id) AS message_count,\n`;
sql += ` (SELECT m.text FROM bot_messages m WHERE m.session_id = s.id ORDER BY m.created_at DESC, m.id DESC LIMIT 1) AS last_message_text\n`;
sql += ` (SELECT m.text FROM bot_messages m WHERE m.session_id = s.id ORDER BY m.created_at DESC, m.id DESC LIMIT 1) AS last_message_text,\n`;
sql += ` (SELECT c.title FROM cron_jobs c WHERE c.id = s.routine_id) AS routine_title,\n`;
sql += ` (SELECT h.title FROM bot_hooks h WHERE h.id = s.hook_id) AS hook_title\n`;
sql += `FROM bot_sessions s\n`;
sql += `WHERE s.user_id = ? AND s.bot_id = ? AND s.workspace_id IS ? AND s.ask_id IS NULL AND s.hook_id IS NULL\n`;
sql += `WHERE s.user_id = ? AND s.bot_id = ? AND s.workspace_id IS ?\n`;
sql += `AND ${attended_only ? followedSessionSql({ alias: "s" }) : visibleSessionSql({ alias: "s" })}\n`;
sql += `AND (s.status = 'active' OR EXISTS (SELECT 1 FROM bot_messages m WHERE m.session_id = s.id))\n`;
if (like) {
@@ -59,7 +59,6 @@ export default async function grabConversationHistory({
const in_conversation =
asked?.id &&
!asked.ask_id &&
!asked.hook_id &&
Number(asked.bot_id) == Number(open_bot_id) &&
(asked.workspace_id ? Number(asked.workspace_id) : null) ==
(conversation_workspace_id ? Number(conversation_workspace_id) : null);
@@ -72,7 +72,7 @@ export default async function grabPastSessionMessages({
const session = (
await BunSQLite.sql<BUN_SQLITE_COBBLE_BOT_SESSIONS>({
sql: `SELECT id, title, previous_session_id FROM bot_sessions
WHERE id = ? AND user_id = ? AND bot_id = ? AND workspace_id IS ? AND id != ? AND ask_id IS NULL AND hook_id IS NULL LIMIT 1`,
WHERE id = ? AND user_id = ? AND bot_id = ? AND workspace_id IS ? AND id != ? AND ask_id IS NULL LIMIT 1`,
values: [
target_session_id,
user_id,
@@ -5,11 +5,13 @@ type Params = {
};
/**
* Whether a session is a crew request's or a hook's, which nobody follows.
* Whether a session is a crew request's (status `ask`), which nobody
* follows. A routine's or a hook's thread isn't hidden: the user can open
* it and chat there.
*/
export default async function isHiddenSession({ session_id }: Params) {
const res = await BunSQLite.sql<{ hidden: number }>({
sql: `SELECT (ask_id IS NOT NULL OR hook_id IS NOT NULL) AS hidden FROM bot_sessions WHERE id = ?`,
sql: `SELECT (ask_id IS NOT NULL) AS hidden FROM bot_sessions WHERE id = ?`,
values: [Number(session_id)],
});
@@ -33,7 +33,8 @@ db.run(`ALTER TABLE bot_sessions ADD COLUMN ask_id INTEGER`);
db.run(`INSERT INTO bot_sessions (id, user_id, bot_id, workspace_id, title, ask_id) VALUES (6, 1, 10, NULL, 'A crew request', 3)`);
db.run(`INSERT INTO bot_messages (id, session_id, author, text) VALUES (9, 6, 'bot', 'Acme invoice asked in a crew request')`);
/**
* A hook's hidden session: read in its thread, never a past session.
* A hook's thread: an ordinary session of the conversation now, so a
* search can read it too.
*/
db.run(`ALTER TABLE bot_sessions ADD COLUMN hook_id INTEGER`);
db.run(`INSERT INTO bot_sessions (id, user_id, bot_id, workspace_id, title, hook_id) VALUES (7, 1, 10, NULL, 'A hook', 4)`);
@@ -53,7 +54,7 @@ function ids(params: Partial<SearchPastSessionsParams>) {
describe("searchPastSessionsSql", () => {
test("finds only this conversation's earlier sessions, newest first", () => {
expect(ids({ query: "acme invoice" })).toEqual([2, 1]);
expect(ids({ query: "acme invoice" })).toEqual([10, 2, 1]);
});
test("keeps the workspace's conversation apart from the bot's own chat", () => {
@@ -63,7 +63,6 @@ export default function searchPastSessionsSql({
`s.workspace_id IS ?`,
`s.id != ?`,
`s.ask_id IS NULL`,
`s.hook_id IS NULL`,
];
for (const word of words) {
@@ -1,8 +1,8 @@
import type { BUN_SQLITE_COBBLE_BOT_SESSIONS } from "@/db/types/db";
import BunSQLite from "@moduletrace/bun-sqlite";
import AppError from "@/src/utils/app-error";
import activateBotSession from "./activate-bot-session";
import grabUserBotSession from "./grab-user-bot-session";
import deleteSessionRows from "./delete-session-rows";
type Params = {
session_id: number | string;
@@ -12,8 +12,8 @@ type Params = {
/**
* Makes a closed session of one of the user's conversations the active
* one again, so the bot carries on from where it left off. The session
* that was active is closed (an empty one is deleted). A session the bot
* moved the conversation on from is never reopened.
* that was active is closed (an empty one is deleted, `activateBotSession`).
* A session the bot moved the conversation on from is never reopened.
*/
export default async function reopenBotSession({
session_id,
@@ -30,7 +30,7 @@ export default async function reopenBotSession({
/**
* A bot's part of a crew request is only ever read there.
*/
if (session.ask_id || session.hook_id) {
if (session.ask_id) {
throw new AppError(`Session not found.`);
}
@@ -50,33 +50,5 @@ export default async function reopenBotSession({
throw new AppError(`This conversation moved on to a newer session, so this one stays closed. You can still read it.`);
}
const now = Date.now();
const workspace_id = session.workspace_id || null;
/**
* The empty one goes with its own rows (`deleteSessionRows`): a job it
* still held would otherwise point at a session that is gone.
*/
const emptied = (
await BunSQLite.sql<{ id: number }>({
sql: `SELECT id FROM bot_sessions WHERE user_id = ? AND bot_id = ? AND workspace_id IS ? AND status = 'active'
AND NOT EXISTS (SELECT 1 FROM bot_messages m WHERE m.session_id = bot_sessions.id)`,
values: [session.user_id!, session.bot_id!, workspace_id],
})
).payload || [];
await deleteSessionRows({ session_ids: emptied.map((row) => Number(row.id)) });
await BunSQLite.sql({
sql: `UPDATE bot_sessions SET status = 'closed', unread = 0, updated_at = ?
WHERE user_id = ? AND bot_id = ? AND workspace_id IS ? AND status = 'active'`,
values: [now, session.user_id!, session.bot_id!, workspace_id],
});
await BunSQLite.sql({
sql: `UPDATE bot_sessions SET status = 'active', updated_at = ? WHERE id = ?`,
values: [now, session.id],
});
return { ...session, status: "active", updated_at: now };
}
return await activateBotSession({ session });
}
@@ -0,0 +1,64 @@
import type { BUN_SQLITE_COBBLE_BOT_SESSIONS } from "@/db/types/db";
import { logError } from "@/src/functions/backend/logger";
import carryOverBotSession from "./carry-over-bot-session";
import hasOpenSessionJob from "./has-open-session-job";
import writeSessionContinuation from "./write-session-continuation";
type Params = {
/**
* The routine's or hook's latest session, full to the app setting.
*/
session: BUN_SQLITE_COBBLE_BOT_SESSIONS;
user_id: number | string;
bot_id: number;
workspace_id?: number | null;
};
/**
* Carries a routine's or a silent hook's own thread into its next session
* once it's full (`writeSessionContinuation`), like Continue in a new
* session does for the conversation: the summary opens the new session as
* its first message and `previous_session_id` links it, with the same
* routine or hook attached, still closed so no run takes the chat over.
* Null when it can't move (the bot still has work in it) or there is
* nothing to carry (the model wrote no summary and none was stored): the
* run then lands in the full session, which never blocks it.
*/
export default async function rollOverLinkedSession({
session,
user_id,
bot_id,
workspace_id,
}: Params): Promise<number | null> {
if (!session.id || (await hasOpenSessionJob({ session_id: session.id }))) return null;
const written = await writeSessionContinuation({
session_id: session.id,
user_id,
bot_id,
workspace_id,
}).catch((error: unknown) => {
logError({ title: "Couldn't write the summary to carry a session over", error }).catch(() => {});
return null;
});
const summary = written?.summary || session.summary?.trim();
if (!summary) return null;
const message = await carryOverBotSession({
session_id: session.id,
user_id,
bot_id,
workspace_id,
summary,
title: written?.title,
allow_inactive: true,
next_status: "closed",
}).catch((error: unknown) => {
logError({ title: "Couldn't carry a session over", error }).catch(() => {});
return null;
});
return message ? Number(message.session_id) : null;
}
@@ -9,10 +9,11 @@ type Params = {
/**
* The one test for "a session a user can open": not one bot's part of a
* crew request (`ask_id`, status `ask`) and not a hook's runs (`hook_id`,
* status `hook`). Every query that lists or picks a conversation adds it,
* or a hidden session leaks into the rail, a session list or the prompt.
* crew request (`ask_id`, status `ask`). Every query that lists or picks a
* conversation adds it, or a hidden session leaks into the rail, a session
* list or the prompt. A routine's and a hook's threads are ordinary
* sessions: they show and can be chatted in.
*/
export default function visibleSessionSql({ alias = "bot_sessions" }: Params = {}) {
return `(${alias}.ask_id IS NULL AND ${alias}.hook_id IS NULL)`;
}
return `(${alias}.ask_id IS NULL)`;
}
@@ -0,0 +1,59 @@
import { AppData } from "@/src/data/app-data";
import { SessionContinuePrompt } from "@/src/data/harness-prompts";
import parseSessionName from "@/src/bots-queue/parse-session-name";
import sessionNameTranscript from "@/src/bots-queue/session-name-transcript";
import generateText from "@/src/harness/text/generate-text";
import { runWithHarnessUsageScope } from "@/src/harness/usage/harness-usage-scope";
import grabBotMessages from "../bots/grab-bot-messages";
type Params = {
session_id: number | string;
user_id: number | string;
bot_id: number;
workspace_id?: number | null;
};
/**
* Has the bot's text model write what a session's next one needs to carry
* on: its title and a summary of its latest messages (`SessionContinuePrompt`).
* Null when the session has no messages or the model wrote no summary.
* `continueBotSession` and the rollover of a routine's or hook's own
* thread both carry this into a new session.
*/
export default async function writeSessionContinuation({
session_id,
user_id,
bot_id,
workspace_id,
}: Params): Promise<{ summary: string; title: string } | null> {
const messages = await grabBotMessages({
session_id,
limit: AppData.BotSessionSummaryMessages,
});
if (!messages.length) return null;
const result = await runWithHarnessUsageScope({
scope: {
user_id,
bot_id,
workspace_id: workspace_id || null,
session_id: Number(session_id),
job_id: null,
message_id: null,
},
task: () =>
generateText({
messages: [
{ role: "system", content: SessionContinuePrompt },
{ role: "user", content: sessionNameTranscript({ messages }) },
],
bot_id,
workspace_id,
}),
});
const written = parseSessionName({ text: result.text });
return written?.summary ? written : null;
}
@@ -18,7 +18,7 @@ import { logError } from "@/src/functions/backend/logger";
import type { HarnessToolUse } from "@/src/harness/types";
import grabSessionAskId from "../bot-sessions/grab-session-ask-id";
import onAskJobEnded from "../asks/on-ask-job-ended";
import grabSessionHookId from "../bot-hooks/grab-session-hook-id";
import isUnattendedHookSession from "../bot-hooks/is-unattended-hook-session";
import settleInstallRequest from "../install-requests/settle-install-request";
import jobTrackerTaskId from "./job-tracker-task-id";
@@ -170,10 +170,11 @@ export default async function completeBotJob({
const user_id = await grabJobUserId({ job });
/**
* A hook's run is followed by nobody, so it never shows on the bot's
* face. A crew request's does: the bot answering it is working.
* A silent hook's run is followed by nobody, so it never shows on the
* bot's face. A crew request's does, and so does a hook that isn't
* silent: the bot answering it is working.
*/
const in_hook = Boolean(await grabSessionHookId({ session_id: job.session_id }));
const unattended = await isUnattendedHookSession({ session_id: job.session_id });
/**
* The job is done and its answer saved, so what is left is clearing up:
@@ -185,7 +186,7 @@ export default async function completeBotJob({
try {
bot =
!user_id || in_hook
!user_id || unattended
? null
: needs_you
? await setBotFace({
@@ -1,4 +1,5 @@
import BunSQLite from "@moduletrace/bun-sqlite";
import followedSessionSql from "../bot-sessions/followed-session-sql";
type Params = {
bot_id: number | string;
@@ -7,8 +8,8 @@ type Params = {
*/
user_id: number | string;
/**
* Leave out jobs in hidden sessions (a crew request's, a hook's),
* which never show on the bot's face.
* Leave out jobs the user doesn't follow (a crew request's, a silent
* hook's), which never show on the bot's face.
*/
conversations_only?: boolean;
};
@@ -19,8 +20,8 @@ type Params = {
export default async function countOpenBotJobs({ bot_id, user_id, conversations_only }: Params) {
const res = await BunSQLite.sql<{ open: number }>({
sql: `SELECT COUNT(*) AS open FROM bots_queue WHERE bot_id = ? AND status IN ('pending', 'processing')
AND session_id IN (SELECT id FROM bot_sessions WHERE user_id = ? AND hook_id IS NULL${
conversations_only ? " AND ask_id IS NULL" : ""
AND session_id IN (SELECT id FROM bot_sessions WHERE user_id = ?${
conversations_only ? ` AND ${followedSessionSql()}` : " AND ask_id IS NULL AND hook_id IS NULL"
})`,
values: [bot_id, user_id],
});
@@ -2,6 +2,7 @@ import BunSQLite from "@moduletrace/bun-sqlite";
import type { BotFace } from "@/src/dict/bot-dict";
import { BotReplyJobTitle } from "@/src/dict/bot-queue-dict";
import taskStatusLine from "@/src/utils/task-status-line";
import followedSessionSql from "../bot-sessions/followed-session-sql";
type Params = {
bot_id: number | string;
@@ -16,7 +17,7 @@ type Params = {
* still running: thinking while a reply runs (it's short, and its chat
* needs the row), else working on a task (in its workspace, if it runs in
* one). Null when none is running. Work in a crew request's hidden session
* or a hook's thread never counts: it shows there, never on the face.
* or a silent hook's thread never counts: it shows there, never on the face.
*/
export default async function grabRunningBotJobFace({
bot_id,
@@ -27,7 +28,7 @@ export default async function grabRunningBotJobFace({
sql: `SELECT q.kind, w.name AS workspace_name FROM bots_queue q
LEFT JOIN workspaces w ON w.id = q.workspace_id
WHERE q.bot_id = ? AND q.status = 'processing'
AND q.session_id IN (SELECT id FROM bot_sessions WHERE user_id = ? AND hook_id IS NULL AND ask_id IS NULL)
AND q.session_id IN (SELECT id FROM bot_sessions WHERE user_id = ? AND ${followedSessionSql()})
ORDER BY q.id`,
values: [bot_id, user_id],
})
@@ -10,7 +10,7 @@ import grabJobUserId from "./grab-job-user-id";
import { BotNeedsYouStatusLine } from "@/src/dict/bot-queue-dict";
import grabSessionAskId from "../bot-sessions/grab-session-ask-id";
import onAskJobEnded from "../asks/on-ask-job-ended";
import grabSessionHookId from "../bot-hooks/grab-session-hook-id";
import isUnattendedHookSession from "../bot-hooks/is-unattended-hook-session";
import settleInstallRequest from "../install-requests/settle-install-request";
import jobTrackerTaskId from "./job-tracker-task-id";
import pauseFailedPlanStep from "../bot-plans/pause-failed-plan-step";
@@ -91,12 +91,13 @@ export default async function notifyBotJobFailed({
if (paused_plan) await pushBotPlan(paused_plan);
/**
* A hook's run is followed by nobody, so it never shows on the bot's
* face. A crew request's does: the bot answering it is working.
* A silent hook's run is followed by nobody, so it never shows on the
* bot's face. A crew request's does, and so does a hook that isn't
* silent: the bot answering it is working.
*/
const in_hook = Boolean(await grabSessionHookId({ session_id: job.session_id }));
const unattended = await isUnattendedHookSession({ session_id: job.session_id });
const bot = user_id && !in_hook
const bot = user_id && !unattended
? await setBotFace({
bot_id: job.bot_id,
user_id,
@@ -13,7 +13,7 @@ import parseJobJson from "@/src/bots-queue/parse-job-json";
import stopAsk from "../asks/stop-ask";
import stopAsks from "../asks/stop-asks";
import grabOpenAskBySession from "../asks/grab-open-ask-by-session";
import grabSessionHookId from "../bot-hooks/grab-session-hook-id";
import isUnattendedHookSession from "../bot-hooks/is-unattended-hook-session";
import settleInstallRequest from "../install-requests/settle-install-request";
import attachJobTracesToMessage from "./attach-job-traces-to-message";
@@ -181,10 +181,10 @@ export default async function stopBotJobs({ bot_id, user_id }: Params): Promise<
for (const [session_id, job] of pickReportedJobs({ jobs })) {
/**
* A hook's call says it was stopped in its thread
* (`recordHookCallResponse`).
* A silent hook's call says it was stopped in its thread
* (`recordHookCallResponse`), nowhere the user reads.
*/
if (await grabSessionHookId({ session_id })) continue;
if (await isUnattendedHookSession({ session_id })) continue;
const message = await insertBotMessage({
bot_id: Number(bot_id),
+3 -2
View File
@@ -4,6 +4,7 @@ import chatBotsSql from "@/src/utils/crew-access/chat-bots-sql";
import workspaceBotsSql from "@/src/utils/crew-access/workspace-bots-sql";
import botFaceSql from "@/src/utils/bot-face-sql";
import grabCrewRole from "../access/grab-crew-role";
import followedSessionSql from "../bot-sessions/followed-session-sql";
type Params = {
user_id: number | string;
@@ -47,11 +48,11 @@ export default async function grabBots({
sql += `FROM bots b\n`;
sql += `LEFT JOIN (\n`;
sql += ` SELECT bot_id, MAX(unread) AS unread, MAX(last_activity_at) AS last_activity_at\n`;
sql += ` FROM bot_sessions WHERE workspace_id IS ? AND user_id = ? AND ask_id IS NULL AND hook_id IS NULL GROUP BY bot_id\n`;
sql += ` FROM bot_sessions WHERE workspace_id IS ? AND user_id = ? AND ${followedSessionSql()} GROUP BY bot_id\n`;
sql += `) t ON t.bot_id = b.id\n`;
sql += `LEFT JOIN bot_messages lm ON lm.id = (\n`;
sql += ` SELECT m.id FROM bot_messages m JOIN bot_sessions s ON s.id = m.session_id\n`;
sql += ` WHERE m.bot_id = b.id AND m.workspace_id IS ? AND s.user_id = ? AND s.ask_id IS NULL AND s.hook_id IS NULL\n`;
sql += ` WHERE m.bot_id = b.id AND m.workspace_id IS ? AND s.user_id = ? AND ${followedSessionSql({ alias: "s" })}\n`;
sql += ` ORDER BY m.created_at DESC, m.id DESC\n`;
sql += ` LIMIT 1\n`;
sql += `)\n`;
@@ -12,10 +12,21 @@ type Params = {
/**
* Deletes one of the user's schedules. A run already queued carries on.
* The sessions its runs held stay, as the user's own threads (they're
* ordinary sessions once no routine owns them).
*/
export default async function deleteCronJob({ user_id, cron_job_id, bot_id }: Params) {
const cron_job = await grabUserCronJob({ user_id, cron_job_id, bot_id });
const detached = await BunSQLite.sql({
sql: `UPDATE bot_sessions SET routine_id = NULL, updated_at = ? WHERE routine_id = ?`,
values: [Date.now(), cron_job.id!],
});
if (!detached.success) {
throw new Error(`Couldn't detach the routine's sessions: ${detached.error}`);
}
const res = await BunSQLite.sql({
sql: `DELETE FROM cron_jobs WHERE id = ?`,
values: [cron_job.id!],
@@ -26,4 +37,4 @@ export default async function deleteCronJob({ user_id, cron_job_id, bot_id }: Pa
}
return cron_job;
}
}
@@ -4,7 +4,7 @@ import wakeBotsQueue from "@/src/bots-queue/wake-bots-queue";
import logEvent, { logError } from "@/src/functions/backend/logger";
import nextCronRun from "@/src/utils/next-cron-run";
import safeErrorMessage from "@/src/utils/safe-error-message";
import ensureBotSession from "../bot-sessions/ensure-bot-session";
import ensureRoutineSession from "../bot-sessions/ensure-routine-session";
import enqueueBotJob from "../bots-queue/enqueue-bot-job";
import isBotJobOpen from "../bots-queue/is-bot-job-open";
import grabBotComputers from "../computers/grab-bot-computers";
@@ -17,7 +17,8 @@ type Params = {
/**
* Runs one due schedule: moves it to its next run (claimed atomically, so
* a run is never queued twice), then queues its brief as a task in the
* bot's active session there, on its computer or the bot's current one.
* routine's own session there (`ensureRoutineSession`, never the active
* chat), on its computer or the bot's current one.
* A run is skipped while the last one is still queued or working. It
* turns itself off once it has no next run or has done its `max_runs`.
* Why a run couldn't be queued is kept in `last_error`.
@@ -48,11 +49,7 @@ export default async function fireCronJob({ cron_job, now = Date.now() }: Params
return;
}
const session = await ensureBotSession({
user_id: cron_job.user_id!,
bot_id: cron_job.bot_id!,
workspace_id: cron_job.workspace_id || null,
});
const session_id = await ensureRoutineSession({ cron_job });
const computer_id =
cron_job.computer_id ||
@@ -66,7 +63,7 @@ export default async function fireCronJob({ cron_job, now = Date.now() }: Params
const job_id = await enqueueBotJob({
user_id: cron_job.user_id!,
bot_id: cron_job.bot_id!,
session_id: session.id!,
session_id,
title: cron_job.title || "Scheduled task",
instructions: `${cron_job.instructions || ""}\n\nThis is a scheduled run of your schedule #${id} (\`${schedule}\`, UTC). Do the work; don't create another schedule for it.`,
params: { schedule_id: id, schedule, run: Number(cron_job.run_count || 0) + 1 },
@@ -23,7 +23,8 @@ type Params = {
/**
* The user's schedules with their bot (its face as the user sees it) and
* workspace names, the next to run first and paused ones last. Given a
* workspace names, the next to run first and paused ones last, each with
* the id of the session its latest run left its messages in. Given a
* `bot_id` and a `workspace_id` (null for its own chat) it is one
* conversation's: the routines that run right there.
*/
@@ -56,7 +57,8 @@ export default async function grabCronJobs({
const res = await BunSQLite.sql<CronJobWithNames>({
sql: `SELECT c.*, b.name AS bot_name, b.kind AS bot_kind, b.hue AS bot_hue, b.color AS bot_color, b.stone AS bot_stone, ${face.sql},
b.image_media_id AS bot_image_media_id, w.name AS workspace_name
b.image_media_id AS bot_image_media_id, w.name AS workspace_name,
(SELECT r.id FROM bot_sessions r WHERE r.routine_id = c.id ORDER BY r.id DESC LIMIT 1) AS latest_session_id
FROM cron_jobs c
JOIN bots b ON b.id = c.bot_id
LEFT JOIN workspaces w ON w.id = c.workspace_id
@@ -108,6 +108,11 @@ export default async function handOverCronJob({
throw new AppError(`Couldn't hand the routine over: ${res.msg || res.error}`);
}
await BunSQLite.sql({
sql: `UPDATE bot_sessions SET routine_id = NULL, updated_at = ? WHERE routine_id = ?`,
values: [Date.now(), cron_job.id!],
});
const session = await ensureBotSession({ user_id, bot_id: bot.id, workspace_id: run_workspace_id });
await pushBotNotice({
@@ -2,6 +2,7 @@ import BunSQLite from "@moduletrace/bun-sqlite";
import type { WorkspaceWithActivity } from "@/src/types";
import workspacesSql from "@/src/utils/crew-access/workspaces-sql";
import grabCrewRole from "../access/grab-crew-role";
import followedSessionSql from "../bot-sessions/followed-session-sql";
type Params = {
user_id: number | string;
@@ -19,8 +20,8 @@ export default async function grabUserWorkspaces({
const res = await BunSQLite.sql<WorkspaceWithActivity>({
sql: `SELECT w.*,
COALESCE((SELECT MAX(s.unread) FROM bot_sessions s WHERE s.workspace_id = w.id AND s.user_id = ? AND s.ask_id IS NULL AND s.hook_id IS NULL), 0) AS unread,
(SELECT MAX(s.last_activity_at) FROM bot_sessions s WHERE s.workspace_id = w.id AND s.user_id = ? AND s.ask_id IS NULL AND s.hook_id IS NULL) AS last_activity_at,
COALESCE((SELECT MAX(s.unread) FROM bot_sessions s WHERE s.workspace_id = w.id AND s.user_id = ? AND ${followedSessionSql({ alias: "s" })}), 0) AS unread,
(SELECT MAX(s.last_activity_at) FROM bot_sessions s WHERE s.workspace_id = w.id AND s.user_id = ? AND ${followedSessionSql({ alias: "s" })}) AS last_activity_at,
(SELECT v.visited_at FROM workspace_user_visits v WHERE v.workspace_id = w.id AND v.user_id = ?) AS last_visited_at
FROM workspaces w
WHERE w.archived = 0 AND ${access.sql}
@@ -2,6 +2,7 @@ import BunSQLite from "@moduletrace/bun-sqlite";
import { AppData } from "@/src/data/app-data";
import type { WorkspaceActivityItem } from "@/src/types";
import botFaceSql from "@/src/utils/bot-face-sql";
import followedSessionSql from "../bot-sessions/followed-session-sql";
type Params = {
user_id: number | string;
@@ -32,7 +33,7 @@ export default async function grabWorkspaceActivity({
(SELECT m.text FROM bot_messages m WHERE m.session_id = s.id ORDER BY m.created_at ASC, m.id ASC LIMIT 1) AS first_message_text
FROM bot_sessions s
JOIN bots b ON b.id = s.bot_id
WHERE s.workspace_id = ? AND s.user_id = ? AND s.ask_id IS NULL AND s.hook_id IS NULL
WHERE s.workspace_id = ? AND s.user_id = ? AND ${followedSessionSql({ alias: "s" })}
AND EXISTS (SELECT 1 FROM bot_messages m WHERE m.session_id = s.id)
AND (b.kind = 'coordinator' OR EXISTS (
SELECT 1 FROM workspace_bots wb WHERE wb.workspace_id = s.workspace_id AND wb.bot_id = s.bot_id
+8 -3
View File
@@ -15,6 +15,11 @@ type Params = {
* How many to load, latest first; the modal leaves it out for a page.
*/
limit?: number;
/**
* Leave out a silent hook's thread: the rail lists only what the user
* follows.
*/
attended_only?: boolean;
/**
* Reloads the list whenever it changes (the session the page shows,
* which loading it may have reopened).
@@ -56,7 +61,7 @@ function belongsToConversation({
* session started in the conversation (or named once its first reply is
* in) shows without a reload.
*/
export default function useBotSessions({ bot_id, workspace_id, open, limit, refresh_key }: Params) {
export default function useBotSessions({ bot_id, workspace_id, open, limit, attended_only, refresh_key }: Params) {
const [query, setQuery] = useState("");
const [sessions, setSessions] = useState<BotSessionListItem[]>([]);
const [loading, setLoading] = useState(false);
@@ -97,7 +102,7 @@ export default function useBotSessions({ bot_id, workspace_id, open, limit, refr
const res = await postSessionApi<BotSessionListItem>({
path: "list-sessions",
body: { bot_id, workspace_id, query: query.trim() || undefined, limit },
body: { bot_id, workspace_id, query: query.trim() || undefined, limit, attended_only },
}).catch(() => null);
if (stale) return;
@@ -116,7 +121,7 @@ export default function useBotSessions({ bot_id, workspace_id, open, limit, refr
stale = true;
clearTimeout(timer);
};
}, [open, query, bot_id, workspace_id, limit, revision, refresh_key]);
}, [open, query, bot_id, workspace_id, limit, attended_only, revision, refresh_key]);
const act = async ({ id, path, body }: { id: number | "new"; path: "new-session" | "reopen-session"; body: Record<string, unknown> }) => {
if (busy_id) return;
@@ -28,6 +28,7 @@ export default function RailBotSessions({ bot, workspace_id }: Props) {
workspace_id,
open: true,
limit: AppData.RailRecentSessions + 1,
attended_only: true,
refresh_key: on_screen ? `${on_screen.id}:${on_screen.status}` : null,
});
const recent = sessions.sessions.slice(0, AppData.RailRecentSessions);
+1 -1
View File
@@ -23,7 +23,7 @@ export default async function relayChangedSessions({ since, users }: Params) {
const sessions =
(
await BunSQLite.sql<BUN_SQLITE_COBBLE_BOT_SESSIONS>({
sql: `SELECT id, user_id, bot_id, workspace_id FROM bot_sessions WHERE updated_at > ? AND ask_id IS NULL AND hook_id IS NULL`,
sql: `SELECT id, user_id, bot_id, workspace_id FROM bot_sessions WHERE updated_at > ? AND ask_id IS NULL`,
values: [since],
})
).payload || [];
@@ -9,6 +9,7 @@ export default async function sendBotMessage({
text,
media_ids,
reply_to_message_id,
session_id,
client_id,
}: SendBotMessageRequest) {
return await fetchApi<
@@ -16,6 +17,6 @@ export default async function sendBotMessage({
APIResponseObject<BotMessageWithAttachments>
>(`/api/admin/bots/send-message`, {
method: "POST",
body: { bot_id, workspace_id, text, media_ids, reply_to_message_id, client_id },
body: { bot_id, workspace_id, text, media_ids, reply_to_message_id, session_id, client_id },
});
}
@@ -82,6 +82,11 @@ type Props = {
* and Down arrows walk them.
*/
previous_messages?: BotMessageWithAttachments[];
/**
* The session the thread shows, so the message lands in it rather than
* in whichever session is active (a routine's or a hook's thread).
*/
session_id?: number | null;
/**
* The message the next one quotes, if the user picked one.
*/
@@ -125,6 +130,7 @@ export default function Composer({
has_browsers,
max_chars,
previous_messages,
session_id,
reply_to,
onCancelReply,
onSendStart,
@@ -368,6 +374,7 @@ export default function Composer({
text: text_sent,
media_ids,
reply_to_message_id: reply_to?.id || null,
session_id: session_id || null,
client_id: request_id,
});
@@ -557,6 +557,7 @@ export default function Conversation() {
voice={pageProps?.bot_voice}
has_browsers={Boolean(pageProps?.has_browsers)}
max_chars={pageProps?.message_max_chars}
session_id={session_id}
previous_messages={thread_messages}
reply_to={reply_to}
onCancelReply={() => setReplyTo(null)}
@@ -108,7 +108,7 @@ export default function HooksSection() {
id: hook.id,
path: "hooks/delete-hook",
body: { hook_id: hook.id },
confirm: `Delete the hook "${hook.title}"? Its URL stops working; a run already started carries on.`,
confirm: `Delete the hook "${hook.title}"? Its URL stops working, and its calls are forgotten; a run already started carries on, and its thread stays in the bot's sessions.`,
})
}
/>
@@ -46,7 +46,7 @@ export default function RoutinesSection() {
return (
<SettingsGroup
title="Your routines"
description={`Ask any bot to set one up, e.g. "Every weekday at 9, sum up my inbox." Each run is a task, and its result lands in that bot's chat.`}
description={`Ask any bot to set one up, e.g. "Every weekday at 9, sum up my inbox." Each run is a task, and its messages land in the routine's own thread, which you can open and chat in like any session.`}
>
<SettingsList is_empty={!items.length} empty="No routines yet.">
{items.map((cron_job) => (
@@ -62,7 +62,7 @@ export default function RoutinesSection() {
id: cron_job.id,
path: "routines/delete-routine",
body: { cron_job_id: cron_job.id },
confirm: `Delete the routine "${cron_job.title}"? A run already started carries on.`,
confirm: `Delete the routine "${cron_job.title}"? A run already started carries on, and its thread stays in the bot's sessions.`,
})
}
/>
@@ -82,7 +82,7 @@ export default function RoutinesSection() {
open={Boolean(handing)}
setOpen={(open) => !open && setHanding(undefined)}
title={`Hand over ${handing?.title || "the routine"}`}
description="It keeps its schedule and where it runs; its results land in the new bot's conversation."
description="It keeps its schedule and where it runs. Its thread stays with the bot it was in; the new bot starts a thread of its own."
>
{handing ? (
<HandOverForm<CronJobWithNames>
+4 -2
View File
@@ -13,7 +13,8 @@ import type {
/**
* The sessions of one of the session user's conversations, latest first,
* searched by title, summary or message text.
* searched by title, summary or message text. `attended_only` leaves out a
* silent hook's thread, for the rail.
*/
export const handler: BunextAPIRouteHandler<
APIResponseObject<BotSessionListItem>
@@ -29,7 +30,7 @@ export const handler: BunextAPIRouteHandler<
return { success: false, msg: `Unauthorized`, logoutUser: true };
}
const { bot_id, workspace_id, query, page, limit } = parseWithSchema({
const { bot_id, workspace_id, query, page, limit, attended_only } = parseWithSchema({
schema: ListBotSessionsRequestSchema,
data: body,
});
@@ -45,6 +46,7 @@ export const handler: BunextAPIRouteHandler<
query,
page,
limit,
attended_only,
}),
};
} catch (error: unknown) {
+29 -4
View File
@@ -1,5 +1,7 @@
import userAuth from "@/src/functions/backend/auth/user-auth";
import grabUserConversation from "@/src/functions/backend/db/bot-sessions/grab-user-conversation";
import grabUserBotSession from "@/src/functions/backend/db/bot-sessions/grab-user-bot-session";
import reopenBotSession from "@/src/functions/backend/db/bot-sessions/reopen-bot-session";
import ensureBotSession from "@/src/functions/backend/db/bot-sessions/ensure-bot-session";
import insertUserMessage from "@/src/functions/backend/db/bots/insert-user-message";
import grabUserBotMessage from "@/src/functions/backend/db/bots/grab-user-bot-message";
@@ -27,9 +29,10 @@ import type {
* Posts a message from the session user to a bot they chat with, in its
* own chat or in a workspace, and queues the bot's reply, which
* arrives over the WebSocket. The message goes in the conversation's
* active session (the next one when it's full) and also to the user's
* other open tabs. Files are uploaded first (`upload-attachment`) and
* sent as `media_ids`.
* active session (the thread the page shows, reopening it when it isn't
* active; the next one when it's full) and also to the user's other open
* tabs. Files are uploaded first (`upload-attachment`) and sent as
* `media_ids`.
*/
export const handler: BunextAPIRouteHandler<APIResponseObject> = async ({
req,
@@ -54,7 +57,7 @@ export const handler: BunextAPIRouteHandler<APIResponseObject> = async ({
throw new AppError(`This user can only read records.`);
}
const { bot_id, workspace_id, text, media_ids, reply_to_message_id, client_id } =
const { bot_id, workspace_id, text, media_ids, reply_to_message_id, session_id, client_id } =
parseWithSchema({
schema: SendBotMessageRequestSchema,
data: body,
@@ -108,6 +111,28 @@ export const handler: BunextAPIRouteHandler<APIResponseObject> = async ({
}
const media = await grabAttachableMedia({ user_id: Number(user.id), media_ids });
/**
* The thread on screen is where the message goes: a routine's or a
* hook's session is chatted in by reopening it first (which closes
* the conversation's active one), never by posting into whichever
* session happened to be active. A session of another conversation
* is ignored, as the page does.
*/
const shown = session_id
? await grabUserBotSession({ session_id, user_id: user.id })
: null;
if (
shown?.id &&
!shown.ask_id &&
Number(shown.bot_id) == Number(bot.id) &&
(Number(shown.workspace_id) || null) == (Number(conversation.workspace_id) || null) &&
shown.status != "active"
) {
await reopenBotSession({ session_id: shown.id!, user_id: user.id });
}
const session = await ensureBotSession({
user_id: user.id,
bot_id: bot.id,
+10
View File
@@ -29,6 +29,11 @@ export const CreateBotHookRequestSchema = z.object({
source: SourceField.optional(),
watch_computer_id: z.coerce.number().int().positive().nullable().optional(),
watch_filter: WatchFilterField.nullable().optional(),
/**
* Its runs stay in its own thread instead of taking over the
* conversation.
*/
silent: z.boolean().optional(),
});
export type CreateBotHookRequest = z.infer<typeof CreateBotHookRequestSchema>;
@@ -45,6 +50,11 @@ export const UpdateBotHookRequestSchema = z.object({
signature_header: SignatureHeaderField.optional(),
signature_format: SignatureFormatField.optional(),
watch_filter: WatchFilterField.optional(),
/**
* Its runs stay in its own thread instead of taking over the
* conversation.
*/
silent: z.boolean().optional(),
/**
* Where it runs from now (same bot); `null` for the bot's own chat.
*/
+12
View File
@@ -63,6 +63,13 @@ export const SendBotMessageRequestSchema = z.object({
* The message this one replies to, quoted above it.
*/
reply_to_message_id: z.coerce.number().int().positive().nullish(),
/**
* The session the thread shows (`?session_id=`), when it isn't the
* conversation's active one: the message lands there, reopening it
* first, so a routine's or a hook's thread is chatted in as shown
* rather than in whichever session was active.
*/
session_id: z.coerce.number().int().positive().nullish(),
/**
* The composer's own id for this send, so a send whose answer never
* arrived is recognised as the message already stored instead of
@@ -174,6 +181,11 @@ export const ListBotSessionsRequestSchema = BotConversationRequestSchema.extend(
* A handful for the rail's sub-list; the modal leaves it out for a page.
*/
limit: z.coerce.number().int().positive().max(AppData.BotSessionsPageSize).optional(),
/**
* Leave out a silent hook's thread: the rail lists only sessions the
* user follows. The sessions modal lists them all.
*/
attended_only: z.boolean().optional(),
});
export type ListBotSessionsRequest = z.infer<typeof ListBotSessionsRequestSchema>;
+4
View File
@@ -13,6 +13,7 @@ import migrateBotTypes from "./functions/backend/db/bot-types/migrate-bot-types"
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 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";
@@ -52,6 +53,9 @@ await clearImplicitSessionLinks().catch((error) =>
await migrateChatroomsToAsks().catch((error) =>
logError({ title: "Could not delete the sessions of old chatrooms", error }).catch(() => {}),
);
await migrateHookSilence().catch((error) =>
logError({ title: "Could not make the existing hooks silent", error }).catch(() => {}),
);
await dropStoredFileText().catch((error) =>
logError({ title: "Could not drop the stored file text", error }).catch(() => {}),
);
+17
View File
@@ -125,6 +125,10 @@ export type CronJobWithNames = BUN_SQLITE_COBBLE_CRON_JOBS & {
bot_face?: string | null;
bot_image_media_id?: number | null;
workspace_name?: string | null;
/**
* The session its latest run left its messages in, for its thread.
*/
latest_session_id?: number | null;
};
/**
@@ -146,6 +150,10 @@ export type BotHookWithNames = Omit<BUN_SQLITE_COBBLE_BOT_HOOKS, "token_hash" |
bot_face?: string | null;
bot_image_media_id?: number | null;
workspace_name?: string | null;
/**
* The session its latest call left its messages in, for its thread.
*/
latest_session_id?: number | null;
};
/**
@@ -293,6 +301,15 @@ export type TaskDetail = TaskWithNames & {
export type BotSessionListItem = BUN_SQLITE_COBBLE_BOT_SESSIONS & {
message_count: number;
last_message_text?: string | null;
/**
* The routine that runs in this session, when one does: its name, shown
* as a tag on the row.
*/
routine_title?: string | null;
/**
* The hook that runs in this session, when one does.
*/
hook_title?: string | null;
};
/**