Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
95c8ee7c39 | ||
|
|
edd451342e | ||
|
|
b635eeb543 | ||
|
|
4cadde55e2 | ||
|
|
e000b09898 |
@@ -89,7 +89,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. Sending a message and answering a question card both hold the conversation's lock (`conversationLock`, `src/functions/backend/db/bot-sessions/conversation-lock.ts`, a `createKeyLock` per user, bot and workspace), since two sends 78 ms apart both read the same full session and one then wrote into the session the other had just closed; when its own rollover writes nothing, `rollOverBotSession` returns the conversation's current active session rather than the stale one. The composer holds its send until it answers (`sending`), so a double tap sends once. An open plan follows its conversation across a rollover (`carry-over-bot-session` moves `bot_plans.session_id`). A routine and a hook each keep a thread of their own, marked by `bot_sessions.routine_id` and `hook_id`, with the routine's or hook's title, rolled over at the same session max into a new linked session (`rollOverLinkedSession`, `previous_session_id`, the summary opening the new one), and read and chatted in with `?session_id=` like any session. `ensureRoutineSession`/`ensureHookSession` open it `closed` and then make it the conversation's active session (`activateBotSession`, a routine and a non-silent hook alike), so a run takes the chat over instead of landing in a sidebar; a silent hook is the opt-out (`bot_hooks.silent`). A deleted routine or hook detaches its thread (`routine_id`/`hook_id` set to null) and keeps the messages; a silent hook's thread is the one exception to being followed (`followedSessionSql`: no rail row, no unread, no push, no face change) **until the user writes in it**: a human message takes the thread from the hook (`adoptHookSession`, from `insertUserMessage`, so a chat message and a question's answer alike), so the thread is theirs from then on and the hook opens a new one next time, while a hook that isn't silent makes its thread the conversation's active session for its run. Helpers in `src/functions/backend/db/bot-sessions/`. Job results land in the job's own session, even after it closes, except a reply that called `continue_in_new_session` (`carryOverBotSession`; the menu's and sessions modal's Continue in new session does the same through `continueBotSession`, the model writing title and summary, refused while a job is open in the session): its summary is kept on the closed session and opens the new one as a bot message (`carried_from_session_id`), the job's `session_id` moves so the answer follows, the new session is titled by the bot then (it has no first exchange to be named from), and the old one can never be reopened (`reopenBotSession` refuses; a thread showing it swaps its composer for a link to the new one). Session lists (rail, sessions modal) reopen a session on click, as before; a carried-over one can't be, so it opens to read (`?session_id=`, `conversationHref`). The page tells them which session it shows (`announceShownSession` -> `useShownSession`): they reload, mark it Current (greyed out; without `?session_id=` the active one is), list it even when it's older than the rail's latest, and the active row then leads back. From half the session length the reply prompt suggests moving on (`longSessionNote`). Earlier sessions never enter the prompt (only the last one's summary): the thread can open them above a session (`useOlderMessages.loadPrevious`, a divider per session, quote and reply as usual), and replies get `search_past_sessions`/`read_past_session` (scoped to that user, bot and place, never the current session) when the conversation has any.
|
||||
- **Sessions:** one thread per user per bot in its own chat plus one per workspace; split into `bot_sessions` (rollover at the app setting `bot_session_max_messages`, default `AppData.BotSessionMaxMessages`, via `grabBotSessionMaxMessages`; titled and summarised by `name-bot-session.ts` from the session's opening after a reply or a task (a session with no user message, work handed to the bot, is named from the bot's own messages; `grabSessionOpening`; `grabBotMessages` reads the latest; each opening message is cut to `AppData.BotSessionNameMessageChars`, so a pasted brief of tens of thousands of characters costs one naming call, not a second copy of itself), summary carried into the next session only when they're linked by `previous_session_id`, which only a carry-over sets; older implicit links are cleared at boot by `clearImplicitSessionLinks`). New session (`startBotSession`) and a conversation with no active session always start fresh. The rollover carries over like the bot does (`rollOverBotSession` -> `continueBotSession`, falling back to the stored summary; kept for the next message while a job is open in the full session or there's nothing to carry), inside send-message, so the user's message lands under the summary. Sending a message and answering a question card both hold the conversation's lock (`conversationLock`, `src/functions/backend/db/bot-sessions/conversation-lock.ts`, a `createKeyLock` per user, bot and workspace), since two sends 78 ms apart both read the same full session and one then wrote into the session the other had just closed; when its own rollover writes nothing, `rollOverBotSession` returns the conversation's current active session rather than the stale one. The composer holds its send until it answers (`sending`), so a double tap sends once. An open plan follows its conversation across a rollover (`carry-over-bot-session` moves `bot_plans.session_id`). A routine and a hook each keep a thread of their own, marked by `bot_sessions.routine_id` and `hook_id`, with the routine's or hook's title, rolled over at the same session max into a new linked session (`rollOverLinkedSession`, `previous_session_id`, the summary opening the new one), and read and chatted in with `?session_id=` like any session. `ensureRoutineSession`/`ensureHookSession` open it `closed` and then make it the conversation's active session (`activateBotSession`, a routine and a non-silent hook alike), so a run takes the chat over instead of landing in a sidebar; a silent hook is the opt-out (`bot_hooks.silent`). 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 sessions modal deletes a session too (`delete-session` -> `deleteBotSession` -> `deleteSessionRows`), refused while a run is open in it; deleting the active one starts the conversation a fresh session. The page tells them which session it shows (`announceShownSession` -> `useShownSession`): they reload, mark it Current (greyed out; without `?session_id=` the active one is), list it even when it's older than the rail's latest, and the active row then leads back. From half the session length the reply prompt suggests moving on (`longSessionNote`). Earlier sessions never enter the prompt (only the last one's summary): the thread can open them above a session (`useOlderMessages.loadPrevious`, a divider per session, quote and reply as usual), and replies get `search_past_sessions`/`read_past_session` (scoped to that user, bot and place, never the current session) when the conversation has any.
|
||||
- **Coordinator:** exactly one, the super admin's alone, created idempotently by `ensureCoordinatorBot`. Default prompt `src/data/coordinator-system-prompt.ts`, backfilled only when empty.
|
||||
- **Routes:** `/admin/bots` reopens the last visited bot's own chat (cookie `cobble_last_visited_bot_id`, `<bot>` or `<bot>:<workspace>`; the landing uses only the bot) if still reachable, else coordinator (super admin) / latest bot / first workspace / empty. Workspace and conversation pages record the visit per user (`recordWorkspaceVisit`/`workspace_user_visits`, `recordBotVisit`/`bot_user_visits`) and the rail lists both latest visited first (`last_visited_at`, `orderByLastVisit`; recorded before the crew is read, so the conversation opened is already on top in that render, and its bot leads whatever the visits say (`pinned_id`); a workspace nobody visited yet ranks by its creation, so a new one leads); it never decides the landing. Settings and the rail pages get the cookie's conversation, workspace included, as root prop `last_conversation` (`grabLastConversation`, access-checked, only on those paths: `isPagesRailPath`), shown above their rail list as the way back (`RailLastConversation`). `/admin/bots/[bot_id]` conversation (header, thread and composer at 760px, the bot panel (`BotPanel`) sliding in from the right when its stone (beside the name or beside its messages in the thread) or its name is tapped, or a phone swipes that way, over the conversation rather than taking width; `?session_id=` opens another of the user's sessions there: a closed one is reopened, except a carried-over one, which shows with `SessionMovedBar` instead of the composer, pointing where the conversation went on); `/admin/bots/[bot_id]/models`; `/admin/workspaces/[id]` dashboard; `/admin/workspaces/[id]/bots/[bot_id]` same conversation scoped to the workspace.
|
||||
- **No model:** while the bot has no text model there (`bot_text_model` null, kept live by the models modal), the thread shows `NoModelNotice` (centred when empty): super admins get Connect a provider / Guided setup, others are told the super admin sets it up.
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "cobble",
|
||||
"version": "0.28.3",
|
||||
"version": "0.28.4",
|
||||
"module": "index.ts",
|
||||
"type": "module",
|
||||
"private": true,
|
||||
|
||||
@@ -2,16 +2,23 @@ import Button from "@moduletrace/twui/layout/Button";
|
||||
import Row from "@moduletrace/twui/layout/Row";
|
||||
import Span from "@moduletrace/twui/layout/Span";
|
||||
import Stack from "@moduletrace/twui/layout/Stack";
|
||||
import { Trash2 } from "lucide-react";
|
||||
import { twMerge } from "tailwind-merge";
|
||||
import type { BotSessionListItem } from "@/src/types";
|
||||
import messagePreview from "@/src/utils/message-preview";
|
||||
import relativeTime from "@/src/utils/relative-time";
|
||||
import RowIconButton from "./row-icon-button";
|
||||
|
||||
type Props = {
|
||||
session: BotSessionListItem;
|
||||
loading?: boolean;
|
||||
disabled?: boolean;
|
||||
onOpen: () => void;
|
||||
/**
|
||||
* Deletes the session and its messages; left out where sessions can't be
|
||||
* deleted (the rail).
|
||||
*/
|
||||
onDelete?: () => void;
|
||||
/**
|
||||
* The session the page shows (`?session_id=`, else the active one):
|
||||
* marked Current and greyed out.
|
||||
@@ -25,7 +32,7 @@ type Props = {
|
||||
* 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) {
|
||||
export default function BotSessionRow({ session, loading, disabled, onOpen, onDelete, current }: Props) {
|
||||
const preview = session.summary || session.last_message_text || "";
|
||||
const at = session.last_activity_at || session.created_at;
|
||||
const tag = session.routine_title
|
||||
@@ -35,56 +42,66 @@ export default function BotSessionRow({ session, loading, disabled, onOpen, curr
|
||||
: null;
|
||||
|
||||
return (
|
||||
<Button
|
||||
title={
|
||||
current
|
||||
? "This is the session on screen"
|
||||
: session.status == "active"
|
||||
? "Go back to the active session"
|
||||
: `Reopen "${session.title || "Untitled"}"`
|
||||
}
|
||||
type="button"
|
||||
variant="ghost"
|
||||
color="text"
|
||||
loading={loading}
|
||||
disabled={current || disabled}
|
||||
onClick={onOpen}
|
||||
buttonContentProps={{ className: "w-full min-w-0 flex-nowrap" }}
|
||||
className={twMerge(
|
||||
"w-full justify-start! items-start! gap-0! px-3! py-2.5! rounded-default text-left text-ink dark:text-ink hover:bg-ink/5 hover:dark:bg-ink/5 focus-visible:ring-2 focus-visible:ring-ink",
|
||||
current && "bg-sunken hover:bg-sunken hover:dark:bg-sunken opacity-100!",
|
||||
)}
|
||||
>
|
||||
<Stack className="w-full min-w-0 gap-0.5! items-stretch">
|
||||
<Row className="w-full gap-2! flex-nowrap items-center">
|
||||
<Span
|
||||
className={twMerge(
|
||||
"grow min-w-0 truncate text-sm font-bold leading-5",
|
||||
current ? "text-ink-secondary" : "text-ink",
|
||||
)}
|
||||
>
|
||||
{session.title || "Untitled session"}
|
||||
</Span>
|
||||
{tag ? (
|
||||
<Row className="w-full flex-nowrap items-center gap-1">
|
||||
<Button
|
||||
title={
|
||||
current
|
||||
? "This is the session on screen"
|
||||
: session.status == "active"
|
||||
? "Go back to the active session"
|
||||
: `Reopen "${session.title || "Untitled"}"`
|
||||
}
|
||||
type="button"
|
||||
variant="ghost"
|
||||
color="text"
|
||||
loading={loading}
|
||||
disabled={current || disabled}
|
||||
onClick={onOpen}
|
||||
buttonContentProps={{ className: "w-full min-w-0 flex-nowrap" }}
|
||||
className={twMerge(
|
||||
"grow min-w-0 justify-start! items-start! gap-0! px-3! py-2.5! rounded-default text-left text-ink dark:text-ink hover:bg-ink/5 hover:dark:bg-ink/5 focus-visible:ring-2 focus-visible:ring-ink",
|
||||
current && "bg-sunken hover:bg-sunken hover:dark:bg-sunken opacity-100!",
|
||||
)}
|
||||
>
|
||||
<Stack className="w-full min-w-0 gap-0.5! items-stretch">
|
||||
<Row className="w-full gap-2! flex-nowrap items-center">
|
||||
<Span
|
||||
title={tag.title}
|
||||
className="shrink-0 rounded-default bg-ink/5 px-1.5 text-[11px] leading-4 text-ink-secondary"
|
||||
className={twMerge(
|
||||
"grow min-w-0 truncate text-sm font-bold leading-5",
|
||||
current ? "text-ink-secondary" : "text-ink",
|
||||
)}
|
||||
>
|
||||
{tag.label}
|
||||
{session.title || "Untitled session"}
|
||||
</Span>
|
||||
) : null}
|
||||
{session.unread && !current ? (
|
||||
<Span className="shrink-0 text-[11px] font-bold leading-4 text-ink">New</Span>
|
||||
) : null}
|
||||
<Span className="shrink-0 text-[11px] leading-4 text-ink-secondary">
|
||||
{current ? "Current" : at ? relativeTime({ at: Number(at) }) : ""}
|
||||
{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}
|
||||
<Span className="shrink-0 text-[11px] leading-4 text-ink-secondary">
|
||||
{current ? "Current" : at ? relativeTime({ at: Number(at) }) : ""}
|
||||
</Span>
|
||||
</Row>
|
||||
<Span className="w-full truncate text-xs leading-4 text-ink-secondary">
|
||||
{`${session.message_count} message${session.message_count == 1 ? "" : "s"}`}
|
||||
{preview ? ` · ${messagePreview({ text: preview })}` : ""}
|
||||
</Span>
|
||||
</Row>
|
||||
<Span className="w-full truncate text-xs leading-4 text-ink-secondary">
|
||||
{`${session.message_count} message${session.message_count == 1 ? "" : "s"}`}
|
||||
{preview ? ` · ${messagePreview({ text: preview })}` : ""}
|
||||
</Span>
|
||||
</Stack>
|
||||
</Button>
|
||||
</Stack>
|
||||
</Button>
|
||||
{onDelete ? (
|
||||
<RowIconButton
|
||||
icon={Trash2}
|
||||
title={`Delete "${session.title || "Untitled"}"`}
|
||||
disabled={Boolean(loading) || disabled}
|
||||
onClick={onDelete}
|
||||
/>
|
||||
) : null}
|
||||
</Row>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -43,7 +43,7 @@ type Props = {
|
||||
* The sessions icon (or another target) that opens a conversation's
|
||||
* sessions. A conversation is split into sessions so a bot's context never
|
||||
* grows without bound; this lists them, searches them, starts a fresh one,
|
||||
* or reopens an old one to carry on.
|
||||
* reopens an old one to carry on, or deletes one.
|
||||
*/
|
||||
export default function BotSessionsModal({
|
||||
bot,
|
||||
@@ -139,22 +139,42 @@ export default function BotSessionsModal({
|
||||
</Span>
|
||||
) : null}
|
||||
<Stack className="w-full mt-2 max-h-[60vh] overflow-y-auto gap-0! items-stretch">
|
||||
{sessions.sessions.map((session) => (
|
||||
<BotSessionRow
|
||||
key={session.id}
|
||||
session={session}
|
||||
loading={sessions.busy_id == session.id}
|
||||
disabled={Boolean(sessions.busy_id)}
|
||||
current={on_screen?.id ? on_screen.id == session.id : session.status == "active"}
|
||||
onOpen={() =>
|
||||
session.status == "active"
|
||||
? window.location.assign(conversationHref({ bot_id: Number(bot.id), workspace_id }))
|
||||
: sessions.reopenSession({
|
||||
session_id: Number(session.id),
|
||||
})
|
||||
}
|
||||
/>
|
||||
))}
|
||||
{sessions.sessions.map((session) => {
|
||||
const is_current = on_screen?.id
|
||||
? on_screen.id == session.id
|
||||
: session.status == "active";
|
||||
|
||||
return (
|
||||
<BotSessionRow
|
||||
key={session.id}
|
||||
session={session}
|
||||
loading={sessions.busy_id == session.id}
|
||||
disabled={Boolean(sessions.busy_id)}
|
||||
current={is_current}
|
||||
onOpen={() =>
|
||||
session.status == "active"
|
||||
? window.location.assign(conversationHref({ bot_id: Number(bot.id), workspace_id }))
|
||||
: sessions.reopenSession({
|
||||
session_id: Number(session.id),
|
||||
})
|
||||
}
|
||||
onDelete={() => {
|
||||
if (
|
||||
!window.confirm(
|
||||
`Delete "${session.title || "this session"}"? Its messages go with it, and this can't be undone.`,
|
||||
)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
sessions.deleteSession({
|
||||
session_id: Number(session.id),
|
||||
current: is_current,
|
||||
});
|
||||
}}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
{sessions.loading ? (
|
||||
<LoadingBlock className="w-full h-[300px]" />
|
||||
) : !sessions.sessions.length ? (
|
||||
|
||||
@@ -193,8 +193,9 @@ export default function HookForm({
|
||||
};
|
||||
|
||||
return (
|
||||
// shrink-0: a capped flex column (the modal) would squash the form and clip the buttons away.
|
||||
<Form
|
||||
className="w-full gap-4! items-stretch pt-4 overflow-hidden px-1"
|
||||
className="w-full shrink-0 gap-4! items-stretch pt-4 overflow-hidden px-1"
|
||||
onSubmit={submit}
|
||||
>
|
||||
<Input
|
||||
|
||||
@@ -34,7 +34,7 @@ export default function ImagePickField({
|
||||
const input_ref = useRef<HTMLInputElement>(null);
|
||||
|
||||
return (
|
||||
<Row className="w-full gap-4! flex-nowrap items-center">
|
||||
<Row className="w-full gap-4! items-center">
|
||||
{preview}
|
||||
<Stack className="gap-2! min-w-0">
|
||||
<Row className="gap-2!">
|
||||
@@ -60,14 +60,17 @@ export default function ImagePickField({
|
||||
disabled={disabled || loading}
|
||||
onClick={() => {
|
||||
onRemove();
|
||||
if (input_ref.current) input_ref.current.value = "";
|
||||
if (input_ref.current)
|
||||
input_ref.current.value = "";
|
||||
}}
|
||||
>
|
||||
Remove
|
||||
</Button>
|
||||
) : null}
|
||||
</Row>
|
||||
<Span className="text-[13px] leading-[18px] text-ink-secondary">{note}</Span>
|
||||
<Span className="text-[13px] leading-[18px] text-ink-secondary">
|
||||
{note}
|
||||
</Span>
|
||||
</Stack>
|
||||
{/*
|
||||
* Raw on purpose: twui `Input` writes `value` on change, which
|
||||
@@ -85,7 +88,8 @@ export default function ImagePickField({
|
||||
if (!e.target.files?.[0]) return;
|
||||
|
||||
imageInputToBase64({ imageInput: e.target }).then((res) => {
|
||||
if (res?.imageBase64Full) onPick({ data_url: res.imageBase64Full });
|
||||
if (res?.imageBase64Full)
|
||||
onPick({ data_url: res.imageBase64Full });
|
||||
});
|
||||
}}
|
||||
/>
|
||||
|
||||
@@ -19,7 +19,9 @@ type Props = {
|
||||
export default function RoutineForm({ cron_job, onCancel, onSaved }: Props) {
|
||||
const [title, setTitle] = useState(cron_job.title || "");
|
||||
const [schedule, setSchedule] = useState(cron_job.schedule || "");
|
||||
const [instructions, setInstructions] = useState(cron_job.instructions || "");
|
||||
const [instructions, setInstructions] = useState(
|
||||
cron_job.instructions || "",
|
||||
);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState<string>();
|
||||
|
||||
@@ -69,13 +71,18 @@ export default function RoutineForm({ cron_job, onCancel, onSaved }: Props) {
|
||||
/>
|
||||
<CodeEditor
|
||||
mode="markdown"
|
||||
className="h-40"
|
||||
className="h-[300px]"
|
||||
title="Brief"
|
||||
content={instructions}
|
||||
info="What the bot does at every run, and how it knows it's done."
|
||||
onChange={(value) => setInstructions(value)}
|
||||
/>
|
||||
<AddFormActions submit_label="Save" loading={loading} error={error} onCancel={onCancel} />
|
||||
<AddFormActions
|
||||
submit_label="Save"
|
||||
loading={loading}
|
||||
error={error}
|
||||
onCancel={onCancel}
|
||||
/>
|
||||
</Form>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
import AppError from "@/src/utils/app-error";
|
||||
import deleteSessionRows from "./delete-session-rows";
|
||||
import grabUserBotSession from "./grab-user-bot-session";
|
||||
import hasOpenSessionJob from "./has-open-session-job";
|
||||
import startBotSession from "./start-bot-session";
|
||||
|
||||
type Params = {
|
||||
session_id: number | string;
|
||||
user_id: number | string;
|
||||
};
|
||||
|
||||
/**
|
||||
* Deletes one of the user's sessions and everything in it. Deleting the
|
||||
* active one hands the conversation a fresh session, since a conversation
|
||||
* always has one to write in. A session with a run in progress is refused:
|
||||
* the run would keep writing into rows that are gone.
|
||||
*/
|
||||
export default async function deleteBotSession({
|
||||
session_id,
|
||||
user_id,
|
||||
}: Params): Promise<void> {
|
||||
const session = await grabUserBotSession({ session_id, user_id });
|
||||
|
||||
if (!session?.id) {
|
||||
throw new AppError(`Session not found.`);
|
||||
}
|
||||
|
||||
/**
|
||||
* A bot's part of a crew request is only ever read there.
|
||||
*/
|
||||
if (session.ask_id) {
|
||||
throw new AppError(`Session not found.`);
|
||||
}
|
||||
|
||||
if (await hasOpenSessionJob({ session_id: session.id })) {
|
||||
throw new AppError(`This session has a run in progress. Stop it first, then delete the session.`);
|
||||
}
|
||||
|
||||
await deleteSessionRows({ session_ids: [session.id] });
|
||||
|
||||
if (session.status != "active") return;
|
||||
|
||||
await startBotSession({
|
||||
user_id: session.user_id!,
|
||||
bot_id: session.bot_id!,
|
||||
workspace_id: session.workspace_id,
|
||||
});
|
||||
}
|
||||
@@ -12,7 +12,9 @@ type Params = {
|
||||
* traces, jobs, what the runs were billed (`token_usages`), job tasks,
|
||||
* reactions, message files, messages, tasks, then the sessions.
|
||||
* Files a message carried are unlinked, and their media row is deleted once
|
||||
* nothing else points at it.
|
||||
* nothing else points at it. A newer session's `previous_session_id` and a
|
||||
* message's `carried_from_session_id` that named one of these are cleared,
|
||||
* since neither is a foreign key.
|
||||
*/
|
||||
export default async function deleteSessionRows({ session_ids }: Params) {
|
||||
const ids = session_ids.map(Number).filter(Boolean);
|
||||
@@ -107,6 +109,20 @@ export default async function deleteSessionRows({ session_ids }: Params) {
|
||||
values: ids,
|
||||
});
|
||||
await deleteBotPlanRows({ session_ids: ids });
|
||||
|
||||
/**
|
||||
* A newer session may carry on from one of these, and a message may have
|
||||
* carried one over: neither link is a foreign key, so it dangles.
|
||||
*/
|
||||
await BunSQLite.sql({
|
||||
sql: `UPDATE bot_sessions SET previous_session_id = NULL WHERE previous_session_id IN (${session_placeholders})`,
|
||||
values: ids,
|
||||
});
|
||||
await BunSQLite.sql({
|
||||
sql: `UPDATE bot_messages SET carried_from_session_id = NULL WHERE carried_from_session_id IN (${session_placeholders})`,
|
||||
values: ids,
|
||||
});
|
||||
|
||||
await BunSQLite.sql({
|
||||
sql: `DELETE FROM bot_sessions WHERE id IN (${session_placeholders})`,
|
||||
values: ids,
|
||||
|
||||
@@ -9,6 +9,7 @@ type Params = {
|
||||
| "new-session"
|
||||
| "continue-session"
|
||||
| "reopen-session"
|
||||
| "delete-session"
|
||||
| "session-messages"
|
||||
| "older-messages";
|
||||
body: Record<string, unknown>;
|
||||
|
||||
@@ -123,7 +123,21 @@ export default function useBotSessions({ bot_id, workspace_id, open, limit, atte
|
||||
};
|
||||
}, [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> }) => {
|
||||
const act = async ({
|
||||
id,
|
||||
path,
|
||||
body,
|
||||
reload = true,
|
||||
}: {
|
||||
id: number | "new";
|
||||
path: "new-session" | "reopen-session" | "delete-session";
|
||||
body: Record<string, unknown>;
|
||||
/**
|
||||
* Whether it lands the conversation on its session; a deleted
|
||||
* session other than the one on screen only reloads the list.
|
||||
*/
|
||||
reload?: boolean;
|
||||
}) => {
|
||||
if (busy_id) return;
|
||||
|
||||
setBusyId(id);
|
||||
@@ -135,7 +149,7 @@ export default function useBotSessions({ bot_id, workspace_id, open, limit, atte
|
||||
* The plain address, not a reload: one showing a session to read
|
||||
* (`?session_id=`) would stay on it.
|
||||
*/
|
||||
if (res?.success) {
|
||||
if (res?.success && reload) {
|
||||
window.location.assign(conversationHref({ bot_id, workspace_id }));
|
||||
return;
|
||||
}
|
||||
@@ -150,6 +164,12 @@ export default function useBotSessions({ bot_id, workspace_id, open, limit, atte
|
||||
}
|
||||
|
||||
setBusyId(undefined);
|
||||
|
||||
if (res?.success) {
|
||||
setRevision((value) => value + 1);
|
||||
return;
|
||||
}
|
||||
|
||||
setError(res?.msg || "That didn't work.");
|
||||
};
|
||||
|
||||
@@ -163,5 +183,7 @@ export default function useBotSessions({ bot_id, workspace_id, open, limit, atte
|
||||
startSession: () => act({ id: "new", path: "new-session", body: { bot_id, workspace_id } }),
|
||||
reopenSession: ({ session_id }: { session_id: number }) =>
|
||||
act({ id: session_id, path: "reopen-session", body: { session_id } }),
|
||||
deleteSession: ({ session_id, current }: { session_id: number; current: boolean }) =>
|
||||
act({ id: session_id, path: "delete-session", body: { session_id }, reload: current }),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -16,6 +16,7 @@ type Props = {
|
||||
stone: BotStoneShape;
|
||||
image_media_id?: number | string | null;
|
||||
picked_src?: string;
|
||||
avatar_size?: number;
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -30,6 +31,7 @@ export default function BotFormPreview({
|
||||
stone,
|
||||
image_media_id,
|
||||
picked_src,
|
||||
avatar_size = 56,
|
||||
}: Props) {
|
||||
const has_picture = Boolean(picked_src || image_media_id);
|
||||
/** A palette colour by name, else a colour the user made up. */
|
||||
@@ -42,7 +44,7 @@ export default function BotFormPreview({
|
||||
<BotAvatar
|
||||
color={color}
|
||||
stone={stone}
|
||||
size={56}
|
||||
size={avatar_size}
|
||||
image_media_id={image_media_id}
|
||||
src={picked_src}
|
||||
/>
|
||||
|
||||
@@ -91,7 +91,14 @@ export default function BotForm({ bot, onCancel, onSaved }: Props) {
|
||||
})
|
||||
: await postAdminApi<{ bot_id: number }>({
|
||||
path: "bots/create-bot",
|
||||
body: { name, role, color, stone, system_prompt, workspace_id },
|
||||
body: {
|
||||
name,
|
||||
role,
|
||||
color,
|
||||
stone,
|
||||
system_prompt,
|
||||
workspace_id,
|
||||
},
|
||||
});
|
||||
const bot_id =
|
||||
bot?.id ||
|
||||
@@ -158,6 +165,7 @@ export default function BotForm({ bot, onCancel, onSaved }: Props) {
|
||||
stone={stone}
|
||||
image_media_id={image.image_media_id}
|
||||
picked_src={image.data_url}
|
||||
avatar_size={100}
|
||||
/>
|
||||
}
|
||||
has_image={image.has_image}
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
import userAuth from "@/src/functions/backend/auth/user-auth";
|
||||
import deleteBotSession from "@/src/functions/backend/db/bot-sessions/delete-bot-session";
|
||||
import { BotSessionIdRequestSchema } from "@/src/schemas/bot-schema";
|
||||
import AppError from "@/src/utils/app-error";
|
||||
import parseWithSchema from "@/src/utils/parse-with-schema";
|
||||
import isReadOnlyUser from "@/src/utils/rbac/is-read-only-user";
|
||||
import safeErrorMessage from "@/src/utils/safe-error-message";
|
||||
import type {
|
||||
APIResponseObject,
|
||||
BunextAPIRouteHandler,
|
||||
} from "@moduletrace/bunext/types";
|
||||
|
||||
/**
|
||||
* Deletes one of the session user's sessions, with its messages. The
|
||||
* active one hands the conversation a fresh session.
|
||||
*/
|
||||
export const handler: BunextAPIRouteHandler<APIResponseObject> = async ({ req, body }) => {
|
||||
try {
|
||||
if (req.method != "POST") {
|
||||
throw new AppError(`Method not allowed`);
|
||||
}
|
||||
|
||||
const { user, user_types } = await userAuth({ req });
|
||||
|
||||
if (!user?.logged_in_status || !user.id) {
|
||||
return { success: false, msg: `Unauthorized`, logoutUser: true };
|
||||
}
|
||||
|
||||
if (isReadOnlyUser({ user_types: user_types || [] })) {
|
||||
throw new AppError(`This user can only read records.`);
|
||||
}
|
||||
|
||||
const { session_id } = parseWithSchema({
|
||||
schema: BotSessionIdRequestSchema,
|
||||
data: body,
|
||||
});
|
||||
|
||||
await deleteBotSession({ session_id, user_id: user.id });
|
||||
|
||||
return { success: true, msg: `Session deleted.` };
|
||||
} catch (error: unknown) {
|
||||
return { success: false, msg: safeErrorMessage({ error }) };
|
||||
}
|
||||
};
|
||||
Reference in New Issue
Block a user