Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2dc6972de4 | ||
|
|
82fa223691 |
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "cobble",
|
||||
"version": "0.28.10",
|
||||
"version": "0.28.11",
|
||||
"module": "index.ts",
|
||||
"type": "module",
|
||||
"private": true,
|
||||
|
||||
@@ -6,7 +6,7 @@ import wakeBotsQueue from "@/src/bots-queue/wake-bots-queue";
|
||||
import type { BotQuestionView } from "@/src/types";
|
||||
import botQuestionAnswersText from "@/src/utils/bot-question-answers-text";
|
||||
import planContinueAnswer from "@/src/utils/plan-continue-answer";
|
||||
import conversationLock from "../bot-sessions/conversation-lock";
|
||||
import conversationLock, { conversationLockKey } from "../bot-sessions/conversation-lock";
|
||||
import ensureBotSession from "../bot-sessions/ensure-bot-session";
|
||||
import grabUserBotSession from "../bot-sessions/grab-user-bot-session";
|
||||
import insertUserMessage from "../bots/insert-user-message";
|
||||
@@ -43,7 +43,7 @@ export default async function postBotQuestionAnswers({ view, user_id }: Params)
|
||||
const bot_id = Number(row.bot_id);
|
||||
|
||||
await conversationLock.run({
|
||||
key: `${user_id}:${bot_id}:${workspace_id || 0}`,
|
||||
key: conversationLockKey({ user_id, bot_id, workspace_id }),
|
||||
task: async () => {
|
||||
const session = await pickSession({ row, user_id });
|
||||
|
||||
|
||||
@@ -3,9 +3,11 @@ import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
import AppError from "@/src/utils/app-error";
|
||||
import insertBotMessage from "../bots/insert-bot-message";
|
||||
import conversationLock, { conversationLockKey } from "./conversation-lock";
|
||||
import createBotSession from "./create-bot-session";
|
||||
import grabActiveBotSession from "./grab-active-bot-session";
|
||||
import grabUserBotSession from "./grab-user-bot-session";
|
||||
import unansweredMessageSql from "./unanswered-message-sql";
|
||||
|
||||
type Params = {
|
||||
/**
|
||||
@@ -57,8 +59,27 @@ type Params = {
|
||||
* 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.
|
||||
*
|
||||
* A reply's carry is refused while the user has written something that
|
||||
* reply hasn't answered: closing the session now leaves their message
|
||||
* behind in it while the answer goes to the new one.
|
||||
*/
|
||||
export default async function carryOverBotSession({
|
||||
export default async function carryOverBotSession(params: Params): Promise<BUN_SQLITE_COBBLE_BOT_MESSAGES> {
|
||||
/**
|
||||
* The reply writes to the conversation like a send does, so it waits
|
||||
* its turn: a message the user writes while it works lands in one
|
||||
* session or the other, never in one closed under it. A routine's or a
|
||||
* silent hook's own thread (`allow_inactive`, no job) moves on its own.
|
||||
*/
|
||||
if (!params.job_id) return await carryOverSession(params);
|
||||
|
||||
return await conversationLock.run({
|
||||
key: conversationLockKey(params),
|
||||
task: () => carryOverSession(params),
|
||||
});
|
||||
}
|
||||
|
||||
async function carryOverSession({
|
||||
session_id,
|
||||
user_id,
|
||||
bot_id,
|
||||
@@ -104,6 +125,23 @@ export default async function carryOverBotSession({
|
||||
throw new AppError(`This session has no messages yet: it's already fresh.`);
|
||||
}
|
||||
|
||||
if (job_id) {
|
||||
const unanswered = unansweredMessageSql({ session_id: active.id, job_id });
|
||||
|
||||
const waiting = (
|
||||
await BunSQLite.sql<{ unanswered: number }>({
|
||||
sql: `SELECT ${unanswered.sql} AS unanswered`,
|
||||
values: unanswered.values,
|
||||
})
|
||||
).payload?.[0]?.unanswered;
|
||||
|
||||
if (waiting) {
|
||||
throw new AppError(
|
||||
`The user wrote something this reply hasn't answered yet. Answer it in this session first, and carry the conversation over in a later reply.`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const now = Date.now();
|
||||
|
||||
await BunSQLite.sql({
|
||||
|
||||
@@ -6,8 +6,18 @@ import createKeyLock from "@/src/utils/create-key-lock";
|
||||
* flight together (a double submit, a retry firing beside the first) both
|
||||
* read the same full session, one rolls the conversation over, and the
|
||||
* other writes into the session that was just closed, where the user never
|
||||
* sees it.
|
||||
* sees it. A reply carrying the conversation on is one of those writes.
|
||||
*/
|
||||
const conversationLock = createKeyLock();
|
||||
|
||||
type KeyParams = {
|
||||
user_id: number | string;
|
||||
bot_id: number;
|
||||
workspace_id?: number | null;
|
||||
};
|
||||
|
||||
export function conversationLockKey({ user_id, bot_id, workspace_id }: KeyParams) {
|
||||
return `${user_id}:${bot_id}:${workspace_id || 0}`;
|
||||
}
|
||||
|
||||
export default conversationLock;
|
||||
@@ -0,0 +1,80 @@
|
||||
import { Database } from "bun:sqlite";
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import unansweredMessageSql from "./unanswered-message-sql";
|
||||
|
||||
/**
|
||||
* A carry must notice the user's words it would leave behind: a message
|
||||
* written after the one the reply answers (or after a plan's step was
|
||||
* queued) is unanswered, and the session it is in is not safe to close.
|
||||
* Crew messages and the message the job answers are not the user's new
|
||||
* words.
|
||||
*/
|
||||
const db = new Database(":memory:");
|
||||
|
||||
db.run(
|
||||
`CREATE TABLE bot_messages (id INTEGER PRIMARY KEY, session_id INTEGER, author TEXT,
|
||||
from_ask_id INTEGER, from_install_request_id INTEGER, created_at INTEGER)`,
|
||||
);
|
||||
db.run(`CREATE TABLE bots_queue (id INTEGER PRIMARY KEY, message_id INTEGER, created_at INTEGER)`);
|
||||
|
||||
db.run(`INSERT INTO bots_queue VALUES (10, 100, 1000), (11, NULL, 2000)`);
|
||||
|
||||
db.run(`INSERT INTO bot_messages VALUES
|
||||
(100, 5, 'user', NULL, NULL, 900),
|
||||
(101, 5, 'user', NULL, NULL, 1100),
|
||||
(102, 5, 'user', 3, NULL, 1200),
|
||||
(103, 5, 'user', NULL, 4, 1300),
|
||||
(104, 5, 'bot', NULL, NULL, 1400),
|
||||
(200, 6, 'user', NULL, NULL, 2100),
|
||||
(201, 6, 'bot', NULL, NULL, 2200)`);
|
||||
|
||||
function unanswered({ session_id, job_id }: { session_id: number; job_id: number }) {
|
||||
const condition = unansweredMessageSql({ session_id, job_id });
|
||||
|
||||
return Boolean(
|
||||
(
|
||||
db.query(`SELECT ${condition.sql} AS unanswered`).get(...condition.values) as
|
||||
| { unanswered: number }
|
||||
| null
|
||||
)?.unanswered,
|
||||
);
|
||||
}
|
||||
|
||||
describe("unansweredMessageSql", () => {
|
||||
test("a message written after the one the job answers is unanswered", () => {
|
||||
expect(unanswered({ session_id: 5, job_id: 10 })).toBe(true);
|
||||
});
|
||||
|
||||
test("the message the job answers is not", () => {
|
||||
db.run(`DELETE FROM bot_messages WHERE id IN (101, 102, 103)`);
|
||||
|
||||
expect(unanswered({ session_id: 5, job_id: 10 })).toBe(false);
|
||||
|
||||
db.run(`INSERT INTO bot_messages VALUES
|
||||
(101, 5, 'user', NULL, NULL, 1100),
|
||||
(102, 5, 'user', 3, NULL, 1200),
|
||||
(103, 5, 'user', NULL, 4, 1300)`);
|
||||
});
|
||||
|
||||
test("a crew message is never the user's words", () => {
|
||||
db.run(`DELETE FROM bot_messages WHERE id = 101`);
|
||||
|
||||
expect(unanswered({ session_id: 5, job_id: 10 })).toBe(false);
|
||||
|
||||
db.run(`INSERT INTO bot_messages VALUES (101, 5, 'user', NULL, NULL, 1100)`);
|
||||
});
|
||||
|
||||
test("a step queued with no message counts what the user wrote after it", () => {
|
||||
expect(unanswered({ session_id: 6, job_id: 11 })).toBe(true);
|
||||
|
||||
db.run(`DELETE FROM bot_messages WHERE id = 200`);
|
||||
|
||||
expect(unanswered({ session_id: 6, job_id: 11 })).toBe(false);
|
||||
|
||||
db.run(`INSERT INTO bot_messages VALUES (200, 6, 'user', NULL, NULL, 2100)`);
|
||||
});
|
||||
|
||||
test("a job queued after the session's messages counts none of them", () => {
|
||||
expect(unanswered({ session_id: 5, job_id: 11 })).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,30 @@
|
||||
import type { SqlCondition } from "@/src/utils/crew-access/types";
|
||||
|
||||
type Params = {
|
||||
/**
|
||||
* The session the reply is answering in.
|
||||
*/
|
||||
session_id: number | string;
|
||||
/**
|
||||
* The reply's own job: the message it answers is `bots_queue.message_id`.
|
||||
*/
|
||||
job_id: number | string;
|
||||
};
|
||||
|
||||
/**
|
||||
* The SQL for a user message the reply's job hasn't answered: one written
|
||||
* after the message the job answers, or, for a job queued with no message
|
||||
* (a plan's step), after the job was queued. Crew messages are left out:
|
||||
* they wake a bot, they aren't the user's own words. A run carrying the
|
||||
* conversation on while its answer is one of these leaves it behind in the
|
||||
* session it closes, unanswered.
|
||||
*/
|
||||
export default function unansweredMessageSql({ session_id, job_id }: Params): SqlCondition {
|
||||
return {
|
||||
sql: `EXISTS (SELECT 1 FROM bot_messages m JOIN bots_queue q ON q.id = ?
|
||||
WHERE m.session_id = ? AND m.author = 'user'
|
||||
AND m.from_ask_id IS NULL AND m.from_install_request_id IS NULL
|
||||
AND (m.id > q.message_id OR (q.message_id IS NULL AND m.created_at > q.created_at)))`,
|
||||
values: [Number(job_id), Number(session_id)],
|
||||
};
|
||||
}
|
||||
@@ -59,7 +59,7 @@ export default function continueInNewSessionTool({
|
||||
|
||||
return {
|
||||
name: "continue_in_new_session",
|
||||
description: `Move this conversation into a fresh session, carrying over a summary you write. Every reply re-reads the session's recent messages, so a long one costs more each time. Always use it when the user asks to carry on in a new, fresh or different session ("let's continue this in another session", "start a new chat for this"): don't just agree, move. Also use it when the session has grown long and the current topic is at a natural break (say so in your answer). The summary opens the new session, shown to the user and given to you from then on in place of these messages, so put in everything needed to carry on: what the user wants, decisions made, what's done, what's in progress or open, and every name, number, path, link and ref ([bot:ID], [file:ID], ...) exactly. Call it last: your answer then goes in the new session under the summary, so keep it to a line.`,
|
||||
description: `Move this conversation into a fresh session, carrying over a summary you write. Every reply re-reads the session's recent messages, so a long one costs more each time. Always use it when the user asks to carry on in a new, fresh or different session ("let's continue this in another session", "start a new chat for this"): don't just agree, move. Also use it when the session has grown long and the current topic is at a natural break (say so in your answer). The summary opens the new session, shown to the user and given to you from then on in place of these messages, so put in everything needed to carry on: what the user wants, decisions made, what's done, what's in progress or open, and every name, number, path, link and ref ([bot:ID], [file:ID], ...) exactly. Call it last: your answer then goes in the new session under the summary, so keep it to a line. If the user wrote something while you worked, answer that here first: the conversation only moves once everything they said is answered.`,
|
||||
schema: z.object({
|
||||
summary: z
|
||||
.string()
|
||||
|
||||
@@ -3,7 +3,7 @@ import grabUserConversation from "@/src/functions/backend/db/bot-sessions/grab-u
|
||||
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 conversationLock from "@/src/functions/backend/db/bot-sessions/conversation-lock";
|
||||
import conversationLock, { conversationLockKey } from "@/src/functions/backend/db/bot-sessions/conversation-lock";
|
||||
import insertUserMessage from "@/src/functions/backend/db/bots/insert-user-message";
|
||||
import grabUserBotMessage from "@/src/functions/backend/db/bots/grab-user-bot-message";
|
||||
import grabMessageIdByClientId from "@/src/functions/backend/db/bots/grab-message-id-by-client-id";
|
||||
@@ -151,7 +151,7 @@ export const handler: BunextAPIRouteHandler<APIResponseObject> = async ({
|
||||
* or its reply.
|
||||
*/
|
||||
const message = await conversationLock.run({
|
||||
key: `${user.id}:${bot.id}:${conversation.workspace_id || 0}`,
|
||||
key: conversationLockKey({ user_id: user.id, bot_id: bot.id, workspace_id: conversation.workspace_id }),
|
||||
task: async () => {
|
||||
/**
|
||||
* The thread on screen is where the message goes: a routine's
|
||||
|
||||
Reference in New Issue
Block a user