Sessions no longer take their title from the first message: once the first exchange is sent, the text model writes the title and summary, which the rail and sessions list show. The summary records how many messages it covers so a stale one is rewritten before it is carried into the next session. The sessions hook now reloads on live message and session events, so a session started by the first message, a rollover or another tab appears without a reload. New sessions are pushed as server:bot-session, both from the process that changed them and through the live relay.
51 lines
1.5 KiB
TypeScript
51 lines
1.5 KiB
TypeScript
import type { BUN_SQLITE_COBBLE_BOT_SESSIONS } from "@/db/types/db";
|
|
import BunSQLite from "@moduletrace/bun-sqlite";
|
|
import createBotSession from "./create-bot-session";
|
|
import grabActiveBotSession from "./grab-active-bot-session";
|
|
|
|
type Params = {
|
|
/**
|
|
* The user the conversation is with.
|
|
*/
|
|
user_id: number | string;
|
|
bot_id: number | string;
|
|
workspace_id?: number | string | null;
|
|
};
|
|
|
|
/**
|
|
* Closes the conversation's active session and starts the next one, which
|
|
* carries on from it (its summary goes into the next reply's prompt,
|
|
* rewritten first when it covers fewer messages than the session ended
|
|
* with). An active session with no messages yet is kept as it is.
|
|
*/
|
|
export default async function startBotSession({
|
|
user_id,
|
|
bot_id,
|
|
workspace_id,
|
|
}: Params): Promise<BUN_SQLITE_COBBLE_BOT_SESSIONS> {
|
|
const active = await grabActiveBotSession({ user_id, bot_id, workspace_id });
|
|
|
|
if (active?.id) {
|
|
const has_messages = (
|
|
await BunSQLite.sql({
|
|
sql: `SELECT id FROM bot_messages WHERE session_id = ? LIMIT 1`,
|
|
values: [active.id],
|
|
})
|
|
).payload?.[0];
|
|
|
|
if (!has_messages) return active;
|
|
|
|
await BunSQLite.sql({
|
|
sql: `UPDATE bot_sessions SET status = 'closed', unread = 0, updated_at = ? WHERE id = ?`,
|
|
values: [Date.now(), active.id],
|
|
});
|
|
}
|
|
|
|
return await createBotSession({
|
|
user_id,
|
|
bot_id,
|
|
workspace_id,
|
|
previous_session_id: active?.id || null,
|
|
});
|
|
}
|