Let a user stop a bot, and say the app is still alpha
The thinking row and the header menu both carry Stop while a bot has work open for the user anywhere: every pending or processing job of that bot in their conversations is failed as stopped, its task closed, a Stopped step recorded and one closing message posted per session, so the thread stops waiting and the bot goes idle. The handler running the job is aborted from this process through a registry, so a job stuck waiting on a model stops at once instead of on its next heartbeat, and a late face change after the abort is dropped. The release stage is now said in the app too: Settings > General reports "Cobble v0.1.5 (alpha)" next to development, and the README and RELEASING.md say what alpha means for installs.
This commit is contained in:
@@ -0,0 +1,58 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { abortRunningJob, registerJobAbort, unregisterJobAbort } from "./job-abort-registry";
|
||||
|
||||
describe("job-abort-registry", () => {
|
||||
test("aborts the job this process is running", () => {
|
||||
let aborted = false;
|
||||
|
||||
registerJobAbort({ job_id: 101, abort: () => (aborted = true) });
|
||||
|
||||
expect(abortRunningJob({ job_id: 101 })).toBe(true);
|
||||
expect(aborted).toBe(true);
|
||||
|
||||
unregisterJobAbort({ job_id: 101 });
|
||||
});
|
||||
|
||||
test("a job running in another process is not here, so it isn't reported as aborted", () => {
|
||||
expect(abortRunningJob({ job_id: 202 })).toBe(false);
|
||||
});
|
||||
|
||||
test("a finished job is cleaned up, so its id can't abort a later one", () => {
|
||||
let aborted = false;
|
||||
|
||||
registerJobAbort({ job_id: 303, abort: () => (aborted = true) });
|
||||
unregisterJobAbort({ job_id: 303 });
|
||||
|
||||
expect(abortRunningJob({ job_id: 303 })).toBe(false);
|
||||
expect(aborted).toBe(false);
|
||||
});
|
||||
|
||||
test("a numeric string id reaches the same entry, since a route may send one", () => {
|
||||
let aborted = false;
|
||||
|
||||
registerJobAbort({ job_id: 404, abort: () => (aborted = true) });
|
||||
|
||||
expect(abortRunningJob({ job_id: "404" })).toBe(true);
|
||||
expect(aborted).toBe(true);
|
||||
|
||||
unregisterJobAbort({ job_id: 404 });
|
||||
});
|
||||
|
||||
test("unregistering a job nobody registered is harmless", () => {
|
||||
expect(() => unregisterJobAbort({ job_id: 505 })).not.toThrow();
|
||||
});
|
||||
|
||||
test("only one job is aborted at a time", () => {
|
||||
const aborted: number[] = [];
|
||||
|
||||
registerJobAbort({ job_id: 606, abort: () => aborted.push(606) });
|
||||
registerJobAbort({ job_id: 707, abort: () => aborted.push(707) });
|
||||
|
||||
abortRunningJob({ job_id: 606 });
|
||||
|
||||
expect(aborted).toEqual([606]);
|
||||
|
||||
unregisterJobAbort({ job_id: 606 });
|
||||
unregisterJobAbort({ job_id: 707 });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,40 @@
|
||||
/**
|
||||
* The abort controllers of the jobs this process is running right now,
|
||||
* keyed by job id. Stopping a bot from the chat aborts the request its job
|
||||
* is waiting on (a model that never answers, a tool that hangs) instead of
|
||||
* leaving it to find out on its next heartbeat, which can take minutes.
|
||||
*
|
||||
* Only the process running a job can abort it, so this is a bonus: the job
|
||||
* is already failed in `bots_queue`, and a handler in another process
|
||||
* learns that on its next `updateBotJob`. Kept free of imports so the API
|
||||
* routes can use it without pulling the queue handler into a page bundle.
|
||||
*/
|
||||
const running = new Map<number, () => void>();
|
||||
|
||||
/**
|
||||
* Called by a handler once it holds a job, with the way to abort it.
|
||||
*/
|
||||
export function registerJobAbort({ job_id, abort }: { job_id: number | string; abort: () => void }) {
|
||||
running.set(Number(job_id), abort);
|
||||
}
|
||||
|
||||
/**
|
||||
* Called by a handler in its `finally`, whatever the outcome.
|
||||
*/
|
||||
export function unregisterJobAbort({ job_id }: { job_id: number | string }) {
|
||||
running.delete(Number(job_id));
|
||||
}
|
||||
|
||||
/**
|
||||
* Aborts a job running here. False means another process (or nobody) has
|
||||
* it, so the row's new status is how it finds out.
|
||||
*/
|
||||
export function abortRunningJob({ job_id }: { job_id: number | string }) {
|
||||
const abort = running.get(Number(job_id));
|
||||
|
||||
if (!abort) return false;
|
||||
|
||||
abort();
|
||||
|
||||
return true;
|
||||
}
|
||||
@@ -27,6 +27,7 @@ import runBotJob from "./run-bot-job";
|
||||
import parseJobJson from "./parse-job-json";
|
||||
import nameBotSession from "./name-bot-session";
|
||||
import pushBotSession from "./push-bot-session";
|
||||
import { registerJobAbort, unregisterJobAbort } from "./job-abort-registry";
|
||||
import type { BotJobUpdateData } from "@/src/types";
|
||||
import type { BotJobContext, BotJobRunner } from "./types";
|
||||
|
||||
@@ -80,11 +81,6 @@ export default async function processBotJob({
|
||||
*/
|
||||
const user_id = await grabJobUserId({ job }).catch(() => null);
|
||||
|
||||
const setFace = async (face: Omit<Parameters<typeof setBotFace>[0], "bot_id" | "user_id">) => {
|
||||
if (!user_id) return;
|
||||
|
||||
await pushBotNotice({ bot_id, bot: await setBotFace({ bot_id, user_id, ...face }) });
|
||||
};
|
||||
const controller = new AbortController();
|
||||
/**
|
||||
* The deadline is the one abort that is a failure, not a cancellation:
|
||||
@@ -94,6 +90,25 @@ export default async function processBotJob({
|
||||
const timeout_message = `"${job.title || "The job"}" took too long and was stopped.`;
|
||||
let timed_out = false;
|
||||
|
||||
/**
|
||||
* A stopped job never touches the face again: `stopBotJobs` already set
|
||||
* it to idle, and a late `working` or `asleep` would push over that and
|
||||
* 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 || controller.signal.aborted) return;
|
||||
|
||||
await pushBotNotice({ bot_id, bot: await setBotFace({ bot_id, user_id, ...face }) });
|
||||
};
|
||||
|
||||
/**
|
||||
* Stopping the bot from the chat aborts the request this job is
|
||||
* waiting on, here and now, rather than at the next heartbeat. The job
|
||||
* is already failed in the queue, so an abort is a cancellation and its
|
||||
* result is dropped (`controller.signal.aborted` below).
|
||||
*/
|
||||
registerJobAbort({ job_id, abort: () => controller.abort() });
|
||||
|
||||
const update: BotJobContext["update"] = async (params) => {
|
||||
if (controller.signal.aborted) return false;
|
||||
|
||||
@@ -305,5 +320,6 @@ export default async function processBotJob({
|
||||
}
|
||||
} finally {
|
||||
clearInterval(heartbeat);
|
||||
unregisterJobAbort({ job_id });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -18,6 +18,12 @@ type Params = {
|
||||
* (`relayJobToRequester`): a message in that bot's conversation.
|
||||
*/
|
||||
relay?: { bot_id: number; message: BUN_SQLITE_COBBLE_BOT_MESSAGES } | null;
|
||||
/**
|
||||
* Skip the push notification, keeping only the live send. For a message
|
||||
* the user just caused themselves (stopping the bot): they are looking
|
||||
* at the app, and one notification per conversation would be noise.
|
||||
*/
|
||||
quiet_push?: boolean;
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -27,9 +33,9 @@ type Params = {
|
||||
* goes to the conversation it was posted in. 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 }: Params) {
|
||||
export default async function pushBotNotice({ bot_id, message, bot, relay, quiet_push }: Params) {
|
||||
try {
|
||||
await push({ bot_id, message, bot, relay });
|
||||
await push({ bot_id, message, bot, relay, quiet_push });
|
||||
} catch (error) {
|
||||
await logError({
|
||||
title: "Bot notice wasn't pushed",
|
||||
@@ -39,7 +45,7 @@ export default async function pushBotNotice({ bot_id, message, bot, relay }: Par
|
||||
}
|
||||
}
|
||||
|
||||
async function push({ bot_id, message, bot, relay }: Params) {
|
||||
async function push({ bot_id, message, bot, relay, quiet_push }: Params) {
|
||||
if (message) {
|
||||
await pushToSessionUser({
|
||||
session_id: message.session_id,
|
||||
@@ -49,7 +55,7 @@ async function push({ bot_id, message, bot, relay }: Params) {
|
||||
/**
|
||||
* Not waited on: a push service's latency must not slow the job.
|
||||
*/
|
||||
void notifyBotMessage({ message });
|
||||
if (!quiet_push) void notifyBotMessage({ message });
|
||||
}
|
||||
|
||||
if (relay) {
|
||||
@@ -58,7 +64,7 @@ async function push({ bot_id, message, bot, relay }: Params) {
|
||||
data: { event: "server:bot-message", data: relay.message },
|
||||
});
|
||||
|
||||
void notifyBotMessage({ message: relay.message });
|
||||
if (!quiet_push) void notifyBotMessage({ message: relay.message });
|
||||
}
|
||||
|
||||
if (bot) {
|
||||
|
||||
@@ -6,9 +6,5 @@ export default async function heartbeat() {
|
||||
sql: `SELECT 1 AS alive`,
|
||||
});
|
||||
|
||||
bunext.bunextLog.info(
|
||||
`Cron: database heartbeat ${db_alive.success ? "ok" : "failed"}`,
|
||||
);
|
||||
|
||||
return db_alive;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,8 +3,10 @@ import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
import type { BUN_SQLITE_COBBLE_CONTAINERS } from "@/db/types/db";
|
||||
import refreshComputerContainer from "@/src/functions/backend/db/computers/refresh-computer-container";
|
||||
|
||||
type Row = Pick<BUN_SQLITE_COBBLE_CONTAINERS, "id" | "docker_id" | "status" | "ip_address"> &
|
||||
{ computer_id: number };
|
||||
type Row = Pick<
|
||||
BUN_SQLITE_COBBLE_CONTAINERS,
|
||||
"id" | "docker_id" | "status" | "ip_address"
|
||||
> & { computer_id: number };
|
||||
|
||||
/**
|
||||
* Reads every computer container's state from docker and records it
|
||||
@@ -24,10 +26,11 @@ export default async function syncComputers() {
|
||||
let changed = 0;
|
||||
|
||||
for (const { computer_id, ...container } of rows) {
|
||||
const refreshed = await refreshComputerContainer({ computer_id, container });
|
||||
const refreshed = await refreshComputerContainer({
|
||||
computer_id,
|
||||
container,
|
||||
});
|
||||
|
||||
if (refreshed?.changed) changed++;
|
||||
}
|
||||
|
||||
bunext.bunextLog.info(`Cron: ${rows.length} computer(s) checked, ${changed} changed`);
|
||||
}
|
||||
|
||||
@@ -4,6 +4,30 @@
|
||||
*/
|
||||
export const BotJobCancelledError = "Cancelled";
|
||||
|
||||
/**
|
||||
* `last_error` of a job the user stopped from the chat. A stopped job is
|
||||
* never retried and never told about: the user pulled the plug.
|
||||
*/
|
||||
export const BotJobStoppedError = "Stopped by the user";
|
||||
|
||||
/**
|
||||
* The last step recorded on a stopped job. It's a step, not a message, so a
|
||||
* bot that was stopped mid-thought doesn't answer on its own.
|
||||
*/
|
||||
export const BotJobStoppedStep = "Stopped";
|
||||
|
||||
/**
|
||||
* What the thinking row's stop button says, so the row and its tooltip
|
||||
* never drift.
|
||||
*/
|
||||
export const BotStopButtonLabel = "Stop";
|
||||
|
||||
/**
|
||||
* What the bot says in the conversation once the user has stopped it. It's
|
||||
* the bot's turn again, so the thread stops waiting on a reply.
|
||||
*/
|
||||
export const BotStoppedMessage = "Stopped. I'll carry on when you ask me to.";
|
||||
|
||||
/**
|
||||
* `last_error` bun-sqlite sets when it releases a job whose handler went
|
||||
* silent past the lock timeout on its last attempt.
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
import { Database } from "bun:sqlite";
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import openBotJobsSql from "./open-bot-jobs-sql";
|
||||
import type { SqlCondition } from "@/src/utils/crew-access/types";
|
||||
|
||||
/**
|
||||
* What "stop the bot" pulls the plug on: a bot's open jobs for one user,
|
||||
* across every one of their conversations with it. The test runs the
|
||||
* condition against real SQLite, since a wrong join would either leave a
|
||||
* job running (a stuck bot stays stuck) or stop another user's work.
|
||||
*/
|
||||
const db = new Database(":memory:");
|
||||
|
||||
db.run(`CREATE TABLE bot_sessions (id INTEGER PRIMARY KEY, user_id INTEGER, bot_id INTEGER)`);
|
||||
db.run(
|
||||
`CREATE TABLE bots_queue (id INTEGER PRIMARY KEY, bot_id INTEGER, session_id INTEGER, status TEXT, kind TEXT, title TEXT)`,
|
||||
);
|
||||
db.run(`INSERT INTO bot_sessions VALUES (100, 7, 2), (101, 7, 2), (102, 8, 2), (103, 9, 3)`);
|
||||
db.run(`INSERT INTO bots_queue VALUES
|
||||
(1, 2, 100, 'pending', 'reply', 'Thinking'),
|
||||
(2, 2, 101, 'processing', 'task', 'The audit'),
|
||||
(3, 2, 102, 'processing', 'task', 'Another user''s job'),
|
||||
(4, 2, 100, 'completed', 'reply', 'Thinking'),
|
||||
(5, 2, 100, 'failed', 'task', 'An old failure'),
|
||||
(6, 3, 103, 'pending', 'reply', 'Thinking'),
|
||||
(7, 3, 103, 'processing', 'task', 'A finished bot''s job')`);
|
||||
|
||||
function ids(condition: SqlCondition) {
|
||||
return db
|
||||
.query(`SELECT q.id FROM bots_queue q WHERE ${condition.sql} ORDER BY q.id`)
|
||||
.all(...condition.values)
|
||||
.map((row) => (row as { id: number }).id);
|
||||
}
|
||||
|
||||
describe("openBotJobsSql", () => {
|
||||
test("takes every open job of the bot across the user's conversations, tasks and replies alike", () => {
|
||||
expect(ids(openBotJobsSql({ bot_id: 2, user_id: 7 }))).toEqual([1, 2]);
|
||||
});
|
||||
|
||||
test("never takes another user's job, even on the same bot", () => {
|
||||
expect(ids(openBotJobsSql({ bot_id: 2, user_id: 7 }))).not.toContain(3);
|
||||
});
|
||||
|
||||
test("leaves finished jobs alone, so the work they did still counts", () => {
|
||||
expect(ids(openBotJobsSql({ bot_id: 2, user_id: 7 }))).not.toContain(4);
|
||||
expect(ids(openBotJobsSql({ bot_id: 2, user_id: 7 }))).not.toContain(5);
|
||||
});
|
||||
|
||||
test("another bot's jobs are never in it", () => {
|
||||
expect(ids(openBotJobsSql({ bot_id: 2, user_id: 7 }))).not.toContain(6);
|
||||
expect(ids(openBotJobsSql({ bot_id: 3, user_id: 9 }))).toEqual([6, 7]);
|
||||
});
|
||||
|
||||
test("a user with nothing open stops nothing", () => {
|
||||
expect(ids(openBotJobsSql({ bot_id: 2, user_id: 8 }))).toEqual([3]);
|
||||
expect(ids(openBotJobsSql({ bot_id: 2, user_id: 99 }))).toEqual([]);
|
||||
});
|
||||
|
||||
test("reads a join alias when one is given", () => {
|
||||
const condition = openBotJobsSql({ bot_id: 2, user_id: 7, alias: "j" });
|
||||
|
||||
expect(
|
||||
db
|
||||
.query(`SELECT j.id FROM bots_queue j WHERE ${condition.sql} ORDER BY j.id`)
|
||||
.all(...condition.values)
|
||||
.map((row) => (row as { id: number }).id),
|
||||
).toEqual([1, 2]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,29 @@
|
||||
import type { SqlCondition } from "@/src/utils/crew-access/types";
|
||||
|
||||
type Params = {
|
||||
bot_id: number | string;
|
||||
/**
|
||||
* Only jobs in this user's conversations, never another user's.
|
||||
*/
|
||||
user_id: number | string;
|
||||
/**
|
||||
* The `bots_queue` alias the condition reads.
|
||||
*/
|
||||
alias?: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* The SQL for a bot's jobs for one user that can still run or are running:
|
||||
* pending (including one held back with `available_at` until a model comes
|
||||
* back) and processing (including one waiting for its computer). A job's
|
||||
* session is what makes it the user's, so another user's job is never in
|
||||
* it. This is what "stop the bot" pulls the plug on: with none of these
|
||||
* left, nothing of the bot's starts again until the user asks.
|
||||
*/
|
||||
export default function openBotJobsSql({ bot_id, user_id, alias = "q" }: Params): SqlCondition {
|
||||
return {
|
||||
sql: `(${alias}.bot_id = ? AND ${alias}.status IN ('pending', 'processing')
|
||||
AND ${alias}.session_id IN (SELECT id FROM bot_sessions WHERE user_id = ?))`,
|
||||
values: [Number(bot_id), Number(user_id)],
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
import { Database } from "bun:sqlite";
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import stopBotJobs from "./stop-bot-jobs";
|
||||
|
||||
/**
|
||||
* Stopping the bot from the chat stops every open job of it in the user's
|
||||
* conversations and nothing else: another user's work, another bot's work
|
||||
* and finished jobs all survive, and the bot's own handler must find out
|
||||
* (its lock is gone) so it drops what it was producing.
|
||||
*
|
||||
* The helper talks to bun-sqlite's process-wide client, so this suite has to
|
||||
* drive a real one. It's skipped where the client isn't set up rather than
|
||||
* failing the other suites; `open-bot-jobs-sql.test.ts` covers the
|
||||
* selection itself against real SQLite unconditionally.
|
||||
*/
|
||||
const sqlite_ready = (() => {
|
||||
try {
|
||||
new Database(":memory:").run(`SELECT 1`);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
})();
|
||||
|
||||
describe.skipIf(!sqlite_ready)("stopBotJobs", () => {
|
||||
test("a user with nothing open is a no-op", async () => {
|
||||
const stopped = await stopBotJobs({ bot_id: 999_999, user_id: 999_999 });
|
||||
|
||||
expect(stopped).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,130 @@
|
||||
import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
import type { BUN_SQLITE_COBBLE_BOT_MESSAGES, BUN_SQLITE_COBBLE_BOTS_QUEUE } from "@/db/types/db";
|
||||
import { BotJobStoppedError, BotJobStoppedStep } from "@/src/dict/bot-queue-dict";
|
||||
import insertBotMessage from "../bots/insert-bot-message";
|
||||
import setBotFace, { type BotFaceChange } from "../bots/set-bot-face";
|
||||
import { abortRunningJob } from "@/src/bots-queue/job-abort-registry";
|
||||
import insertBotJobUpdate from "./insert-bot-job-update";
|
||||
import openBotJobsSql from "./open-bot-jobs-sql";
|
||||
import stoppedJobReport, { pickReportedJobs } from "./stopped-job-report";
|
||||
|
||||
type Params = {
|
||||
bot_id: number | string;
|
||||
/**
|
||||
* Whose conversations stop. Never another user's jobs.
|
||||
*/
|
||||
user_id: number | string;
|
||||
};
|
||||
|
||||
export type StoppedBotJobs = {
|
||||
/**
|
||||
* The jobs that were open and are now failed as stopped.
|
||||
*/
|
||||
jobs: BUN_SQLITE_COBBLE_BOTS_QUEUE[];
|
||||
/**
|
||||
* One closing message per session the bot worked in, for the live
|
||||
* push. It's what ends the thread's "still thinking" state: the last
|
||||
* word is the bot's again.
|
||||
*/
|
||||
messages: BUN_SQLITE_COBBLE_BOT_MESSAGES[];
|
||||
/**
|
||||
* The user's face change (idle), for the live push.
|
||||
*/
|
||||
bot: BotFaceChange;
|
||||
};
|
||||
|
||||
/**
|
||||
* Pulls the plug on a bot for one user: every job of it that could still
|
||||
* run or is running in their conversations (replies it still owes, tasks
|
||||
* it's on, across all of them) is failed as stopped, its task closed. A
|
||||
* running handler finds out on its next `updateBotJob` (which returns
|
||||
* false) and drops whatever it was producing. Each job gets a closing
|
||||
* step, so a thread's working row says why it went quiet even after a
|
||||
* reload, one message per session ends it out loud, and the bot goes
|
||||
* idle. It's not a bus: nothing restarts by itself, so a stopped bot
|
||||
* works again only when the user asks. A schedule the user set up still
|
||||
* comes round, since that is work they asked for.
|
||||
*/
|
||||
export default async function stopBotJobs({ bot_id, user_id }: Params): Promise<StoppedBotJobs | null> {
|
||||
const condition = openBotJobsSql({ bot_id, user_id });
|
||||
|
||||
const open = (
|
||||
await BunSQLite.sql<BUN_SQLITE_COBBLE_BOTS_QUEUE>({
|
||||
sql: `SELECT * FROM bots_queue q WHERE ${condition.sql} ORDER BY q.id ASC`,
|
||||
values: condition.values,
|
||||
})
|
||||
).payload || [];
|
||||
|
||||
if (!open.length) return null;
|
||||
|
||||
const now = Date.now();
|
||||
const jobs: BUN_SQLITE_COBBLE_BOTS_QUEUE[] = [];
|
||||
|
||||
for (const job of open) {
|
||||
/**
|
||||
* One by one, and only while it's still open: a job that finished
|
||||
* on its own between the read and here keeps its result.
|
||||
*/
|
||||
const res = await BunSQLite.sql<BUN_SQLITE_COBBLE_BOTS_QUEUE>({
|
||||
sql: `UPDATE bots_queue SET status = 'failed', last_error = ?, locked_at = NULL, locked_by = NULL, finished_at = ?, updated_at = ?
|
||||
WHERE id = ? AND status IN ('pending', 'processing')
|
||||
RETURNING *`,
|
||||
values: [BotJobStoppedError, now, now, Number(job.id)],
|
||||
});
|
||||
|
||||
const stopped = res.payload?.[0];
|
||||
|
||||
if (!stopped?.id) continue;
|
||||
|
||||
jobs.push(stopped);
|
||||
|
||||
/**
|
||||
* If this process is the one running it, stop what it's waiting on
|
||||
* now. Anywhere else, the handler finds out on its next heartbeat.
|
||||
*/
|
||||
abortRunningJob({ job_id: Number(stopped.id) });
|
||||
|
||||
if (stopped.task_id) {
|
||||
await BunSQLite.sql({
|
||||
sql: `UPDATE bot_tasks SET status = 'done', updated_at = ? WHERE id = ?`,
|
||||
values: [now, Number(stopped.task_id)],
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Recorded as the job's last step, so the working row says why it
|
||||
* went quiet.
|
||||
*/
|
||||
try {
|
||||
await insertBotJobUpdate({
|
||||
job_id: Number(stopped.id),
|
||||
bot_id: Number(stopped.bot_id) || Number(bot_id),
|
||||
kind: "note",
|
||||
text: BotJobStoppedStep,
|
||||
});
|
||||
} catch {
|
||||
/**
|
||||
* The step is a courtesy: the job is stopped either way.
|
||||
*/
|
||||
}
|
||||
}
|
||||
|
||||
const messages: BUN_SQLITE_COBBLE_BOT_MESSAGES[] = [];
|
||||
|
||||
for (const [session_id, job] of pickReportedJobs({ jobs })) {
|
||||
const message = await insertBotMessage({
|
||||
bot_id: Number(bot_id),
|
||||
session_id,
|
||||
workspace_id: job.workspace_id || null,
|
||||
text: stoppedJobReport({ job }),
|
||||
}).catch(() => null);
|
||||
|
||||
if (message?.id) messages.push(message);
|
||||
}
|
||||
|
||||
return {
|
||||
jobs,
|
||||
messages,
|
||||
bot: await setBotFace({ bot_id, user_id, face: "idle" }),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { BotStoppedMessage } from "@/src/dict/bot-queue-dict";
|
||||
import stoppedJobReport, { pickReportedJobs } from "./stopped-job-report";
|
||||
|
||||
describe("stoppedJobReport", () => {
|
||||
test("a stopped task names the work that was cut off", () => {
|
||||
expect(stoppedJobReport({ job: { session_id: 1, kind: "task", title: "The audit" } })).toBe(
|
||||
`${BotStoppedMessage} I was on **The audit**.`,
|
||||
);
|
||||
});
|
||||
|
||||
test("a stopped reply just says so, since it has no title worth quoting", () => {
|
||||
expect(stoppedJobReport({ job: { session_id: 1, kind: "reply", title: "Thinking" } })).toBe(
|
||||
BotStoppedMessage,
|
||||
);
|
||||
});
|
||||
|
||||
test("a task without a title doesn't leave a dangling bold sentence", () => {
|
||||
expect(stoppedJobReport({ job: { session_id: 1, kind: "task", title: " " } })).toBe(
|
||||
BotStoppedMessage,
|
||||
);
|
||||
});
|
||||
|
||||
test("the message is a sentence the user can read, and it says the bot waits for them", () => {
|
||||
expect(BotStoppedMessage).toContain("Stopped");
|
||||
expect(BotStoppedMessage).toContain("when you ask");
|
||||
});
|
||||
});
|
||||
|
||||
describe("pickReportedJobs", () => {
|
||||
test("one job speaks per session, so a reply and the task it started don't both report", () => {
|
||||
const picked = pickReportedJobs({
|
||||
jobs: [
|
||||
{ session_id: 7, kind: "reply", id: 1 },
|
||||
{ session_id: 7, kind: "task", id: 2 },
|
||||
],
|
||||
});
|
||||
|
||||
expect([...picked.keys()]).toEqual([7]);
|
||||
});
|
||||
|
||||
test("the task wins, since it's the one that can name the work", () => {
|
||||
const picked = pickReportedJobs({
|
||||
jobs: [
|
||||
{ session_id: 7, kind: "reply", id: 1 },
|
||||
{ session_id: 7, kind: "task", id: 2 },
|
||||
],
|
||||
});
|
||||
|
||||
expect(picked.get(7)?.id).toBe(2);
|
||||
});
|
||||
|
||||
test("a task first isn't replaced by a later reply", () => {
|
||||
const picked = pickReportedJobs({
|
||||
jobs: [
|
||||
{ session_id: 7, kind: "task", id: 2 },
|
||||
{ session_id: 7, kind: "reply", id: 1 },
|
||||
],
|
||||
});
|
||||
|
||||
expect(picked.get(7)?.id).toBe(2);
|
||||
});
|
||||
|
||||
test("every session gets its own report", () => {
|
||||
const picked = pickReportedJobs({
|
||||
jobs: [
|
||||
{ session_id: 7, kind: "reply", id: 1 },
|
||||
{ session_id: 8, kind: "task", id: 2 },
|
||||
{ session_id: 9, kind: "task", id: 3 },
|
||||
],
|
||||
});
|
||||
|
||||
expect([...picked.keys()].sort()).toEqual([7, 8, 9]);
|
||||
});
|
||||
|
||||
test("nothing open picks nothing", () => {
|
||||
expect(pickReportedJobs({ jobs: [] }).size).toBe(0);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,45 @@
|
||||
import { BotStoppedMessage } from "@/src/dict/bot-queue-dict";
|
||||
|
||||
type Job = {
|
||||
session_id?: number | string | null;
|
||||
kind?: string | null;
|
||||
title?: string | null;
|
||||
};
|
||||
|
||||
/**
|
||||
* What the bot says in a conversation the user stopped it in. A task names
|
||||
* the work that was cut off, so a long job that quietly went nowhere reads
|
||||
* as stopped rather than as finished; a reply has no title worth quoting.
|
||||
*/
|
||||
export default function stoppedJobReport({ job }: { job: Job }): string {
|
||||
const title = (job.title || "").trim();
|
||||
|
||||
return job.kind == "task" && title
|
||||
? `${BotStoppedMessage} I was on **${title}**.`
|
||||
: BotStoppedMessage;
|
||||
}
|
||||
|
||||
/**
|
||||
* The job that speaks for each session: one per session, since a reply and
|
||||
* the task it started are the same conversation and two notes there read as
|
||||
* a stutter. A task wins, because it's the one that can name the work.
|
||||
*/
|
||||
export function pickReportedJobs<T extends Job>({ jobs }: { jobs: T[] }): Map<number, T> {
|
||||
const picked = new Map<number, T>();
|
||||
|
||||
for (const job of jobs) {
|
||||
/**
|
||||
* A job with no session is stopped all the same; it just has
|
||||
* nowhere to report it.
|
||||
*/
|
||||
if (job.session_id === null || job.session_id === undefined) continue;
|
||||
|
||||
const known = picked.get(Number(job.session_id));
|
||||
|
||||
if (!known || (known.kind != "task" && job.kind == "task")) {
|
||||
picked.set(Number(job.session_id), job);
|
||||
}
|
||||
}
|
||||
|
||||
return picked;
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import React from "react";
|
||||
import type { StopBot } from "../(hooks)/use-stop-bot";
|
||||
|
||||
export type StopBotState = StopBot & {
|
||||
/**
|
||||
* The bot has something open for the signed-in user right now (a reply
|
||||
* it owes, a task it's on, a wait for a model or a computer), so
|
||||
* stopping it has something to pull the plug on.
|
||||
*/
|
||||
can_stop: boolean;
|
||||
};
|
||||
|
||||
/**
|
||||
* The conversation's stop control, shared by the thinking row under the
|
||||
* thread and the header's menu, so both pull the same plug.
|
||||
*/
|
||||
export const StopBotContext = React.createContext<StopBotState>({
|
||||
stop: async () => {},
|
||||
stopping: false,
|
||||
can_stop: false,
|
||||
});
|
||||
@@ -0,0 +1,19 @@
|
||||
import fetchApi from "@moduletrace/twui/utils/fetch/fetchApi";
|
||||
import type { APIResponseObject } from "@moduletrace/bunext/types";
|
||||
import type { BotConversationRequest } from "@/src/schemas/bot-schema";
|
||||
import type { BotStoppedPayload } from "@/src/types";
|
||||
|
||||
/**
|
||||
* Pulls the plug on the bot for the signed-in user: every job of it that's
|
||||
* queued or running stops, wherever they chat with it. The messages that
|
||||
* end the wait arrive over the WebSocket, so nothing here reloads.
|
||||
*/
|
||||
export default async function stopBot({ bot_id, workspace_id }: BotConversationRequest) {
|
||||
return await fetchApi<
|
||||
BotConversationRequest,
|
||||
APIResponseObject<BotStoppedPayload>
|
||||
>(`/api/admin/bots/stop`, {
|
||||
method: "POST",
|
||||
body: { bot_id, workspace_id },
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
import { useRef, useState } from "react";
|
||||
import stopBot from "../(functions)/stop-bot";
|
||||
|
||||
export type StopBot = {
|
||||
/**
|
||||
* Stops every job of the bot for the signed-in user.
|
||||
*/
|
||||
stop: () => Promise<void>;
|
||||
/**
|
||||
* A stop is on its way to the server.
|
||||
*/
|
||||
stopping: boolean;
|
||||
/**
|
||||
* Why the last stop didn't work, for the button's title.
|
||||
*/
|
||||
error?: string;
|
||||
};
|
||||
|
||||
type Params = {
|
||||
bot_id: number;
|
||||
workspace_id?: number | null;
|
||||
};
|
||||
|
||||
/**
|
||||
* The conversation's stop button: pulls the plug on the bot for the
|
||||
* signed-in user, wherever they chat with it. It's quiet on the way out:
|
||||
* the bot's closing message and idle face arrive as pushes, so nothing
|
||||
* here reloads and a failed stop only surfaces as the button's title.
|
||||
*/
|
||||
export default function useStopBot({ bot_id, workspace_id }: Params): StopBot {
|
||||
const [stopping, setStopping] = useState(false);
|
||||
const [error, setError] = useState<string>();
|
||||
|
||||
/**
|
||||
* A ref, not the state: two clicks in one tick both read the old
|
||||
* `stopping` and would send two stops.
|
||||
*/
|
||||
const in_flight = useRef(false);
|
||||
|
||||
const stop = async () => {
|
||||
if (in_flight.current) return;
|
||||
|
||||
in_flight.current = true;
|
||||
setStopping(true);
|
||||
setError(undefined);
|
||||
|
||||
try {
|
||||
const res = await stopBot({
|
||||
bot_id,
|
||||
workspace_id: workspace_id || null,
|
||||
}).catch(() => null);
|
||||
|
||||
/**
|
||||
* A message without a failure is the count ("Stopped 2 jobs."),
|
||||
* so only an unsuccessful answer is an error.
|
||||
*/
|
||||
if (!res?.success) setError(res?.msg || "Couldn't stop the bot.");
|
||||
} finally {
|
||||
in_flight.current = false;
|
||||
setStopping(false);
|
||||
}
|
||||
};
|
||||
|
||||
return { stop, stopping, error };
|
||||
}
|
||||
@@ -2,15 +2,11 @@ import Row from "@moduletrace/twui/layout/Row";
|
||||
import Span from "@moduletrace/twui/layout/Span";
|
||||
import Stack from "@moduletrace/twui/layout/Stack";
|
||||
import BotAvatar from "@/src/components/general/bot-avatar";
|
||||
import type { BotFace } from "@/src/dict/bot-dict";
|
||||
import botStoneProps from "@/src/utils/bot-stone-props";
|
||||
import {
|
||||
BotComputerBusyStatusLine,
|
||||
BotGettingMessageStatusLine,
|
||||
BotReplyJobTitle,
|
||||
BotWaitingStatusLine,
|
||||
} from "@/src/dict/bot-queue-dict";
|
||||
import { BotGettingMessageStatusLine } from "@/src/dict/bot-queue-dict";
|
||||
import type { BotWithLastMessage } from "@/src/types";
|
||||
import botBusyState from "../(utils)/bot-busy-state";
|
||||
import StopBotButton from "./stop-bot-button";
|
||||
|
||||
type Props = {
|
||||
bot: BotWithLastMessage;
|
||||
@@ -45,7 +41,7 @@ type Props = {
|
||||
* reply shows from the thread alone: every user message queues one, so while
|
||||
* the user has the last word a reply is due here, even while the bot works
|
||||
* elsewhere. Only the waits (for a model, for its computer) come from the
|
||||
* face.
|
||||
* face. While it shows, a stop button pulls the plug on the bot's work.
|
||||
*/
|
||||
export default function BotThinkingRow({
|
||||
bot,
|
||||
@@ -56,17 +52,14 @@ export default function BotThinkingRow({
|
||||
has_task,
|
||||
}: Props) {
|
||||
const name = bot.name || "The bot";
|
||||
const asleep = bot.face == "asleep";
|
||||
const waiting_model = asleep && bot.status_line == BotWaitingStatusLine && Boolean(awaiting_reply || has_task);
|
||||
const waiting_computer =
|
||||
asleep && bot.status_line == BotComputerBusyStatusLine && Boolean(has_task) && !awaiting_reply;
|
||||
const waiting = waiting_model || waiting_computer;
|
||||
const getting = Boolean(receiving) && Boolean(awaiting_reply);
|
||||
const thinking = Boolean(awaiting_reply) && !waiting && !getting;
|
||||
const working =
|
||||
!awaiting_reply && bot.face == "working" && bot.status_line != BotReplyJobTitle && Boolean(has_task);
|
||||
const { waiting, getting, thinking, working, busy, stoppable } = botBusyState({
|
||||
bot,
|
||||
awaiting_reply,
|
||||
receiving,
|
||||
has_task,
|
||||
});
|
||||
|
||||
if (!getting && !thinking && !working && !waiting) return null;
|
||||
if (!busy) return null;
|
||||
|
||||
const label = getting
|
||||
? `${name} is ${BotGettingMessageStatusLine.toLowerCase()}…`
|
||||
@@ -95,6 +88,7 @@ export default function BotThinkingRow({
|
||||
</Span>
|
||||
) : null}
|
||||
</Stack>
|
||||
<StopBotButton bot_name={bot.name} disabled={!stoppable} />
|
||||
</Row>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -16,6 +16,7 @@ import BotRoutinesModal from "./bot-routines-modal";
|
||||
import BotModelsModal from "./bot-models-modal";
|
||||
import HeaderMenuItem from "./header-menu-item";
|
||||
import NewSessionButton from "./new-session-button";
|
||||
import StopBotButton from "./stop-bot-button";
|
||||
|
||||
type Props = {
|
||||
bot: BotWithLastMessage;
|
||||
@@ -48,8 +49,9 @@ type Props = {
|
||||
|
||||
/**
|
||||
* The conversation header's menu: the sessions, a new session, the bot's
|
||||
* computer, its models and its settings. A row that opens a modal closes
|
||||
* the menu first, so the modal never sits behind an open menu.
|
||||
* computer, its models, its settings and, while it works, stopping it. A
|
||||
* row that opens a modal closes the menu first, so the modal never sits
|
||||
* behind an open menu.
|
||||
*/
|
||||
export default function ConversationHeaderMenu({
|
||||
bot,
|
||||
@@ -136,6 +138,8 @@ export default function ConversationHeaderMenu({
|
||||
onSaved={on_model_saved}
|
||||
/>
|
||||
</Stack>
|
||||
<Divider className="my-1 mx-3 w-auto border-hairline dark:border-hairline" />
|
||||
<StopBotButton menu bot_name={bot.name} />
|
||||
{can_open_settings ? (
|
||||
<>
|
||||
<Divider className="my-1 mx-3 w-auto border-hairline dark:border-hairline" />
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
import { useContext } from "react";
|
||||
import Button from "@moduletrace/twui/layout/Button";
|
||||
import { CircleStop } from "lucide-react";
|
||||
import { BotStopButtonLabel } from "@/src/dict/bot-queue-dict";
|
||||
import { StopBotContext } from "../(data)/stop-bot-context";
|
||||
import HeaderMenuItem from "./header-menu-item";
|
||||
|
||||
type Props = {
|
||||
/**
|
||||
* Whose work stops, named in the tooltip so it's clear this pulls the
|
||||
* bot's plug everywhere the user chats with it.
|
||||
*/
|
||||
bot_name?: string | null;
|
||||
/**
|
||||
* Shown as a row in the conversation header's menu instead of a button
|
||||
* in the thinking row.
|
||||
*/
|
||||
menu?: boolean;
|
||||
/**
|
||||
* The caller already knows there's nothing to pull (a row that says the
|
||||
* bot is only collecting the message), so the button sits out.
|
||||
*/
|
||||
disabled?: boolean;
|
||||
};
|
||||
|
||||
/**
|
||||
* Pulls the plug on the bot for the signed-in user: its queued and running
|
||||
* work stops wherever they chat with it, so a bot stuck waiting for a model
|
||||
* (or anything else) comes back. The thinking row carries it while
|
||||
* something is running; the header's menu carries it too, disabled when
|
||||
* there's nothing to stop.
|
||||
*/
|
||||
export default function StopBotButton({ bot_name, menu, disabled }: Props) {
|
||||
const { stop, stopping, error, can_stop } = useContext(StopBotContext);
|
||||
const name = bot_name || "the bot";
|
||||
const off = Boolean(disabled) || !can_stop || stopping;
|
||||
const title = error
|
||||
? error
|
||||
: off && !stopping
|
||||
? `Nothing of ${name}'s is running for you.`
|
||||
: `Stop ${name}. Its queued and running work stops, everywhere you chat with it.`;
|
||||
|
||||
if (menu) {
|
||||
return (
|
||||
<HeaderMenuItem
|
||||
icon={CircleStop}
|
||||
title={BotStopButtonLabel}
|
||||
description={title}
|
||||
hint={stopping ? "Stopping" : undefined}
|
||||
loading={stopping}
|
||||
disabled={off}
|
||||
onClick={() => {
|
||||
void stop();
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Button
|
||||
title={title}
|
||||
aria-label={title}
|
||||
type="button"
|
||||
variant="ghost"
|
||||
color="text"
|
||||
size="smaller"
|
||||
disabled={off}
|
||||
loading={stopping}
|
||||
loadingIconSize="small"
|
||||
beforeIcon={<CircleStop size={14} aria-hidden />}
|
||||
onClick={() => {
|
||||
void stop();
|
||||
}}
|
||||
className="shrink-0 text-ink-secondary dark:text-ink-secondary hover:text-ink hover:dark:text-ink hover:bg-sunken hover:dark:bg-sunken rounded-default transition-colors duration-[var(--m-fast)] focus-visible:ring-2 focus-visible:ring-ink"
|
||||
>
|
||||
{BotStopButtonLabel}
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
@@ -15,9 +15,15 @@ import { CrewBotsContext } from "../(data)/crew-bots-context";
|
||||
import { CrewWorkspacesContext } from "../(data)/crew-workspaces-context";
|
||||
import { BotMessageActionsContext } from "../(data)/message-actions-context";
|
||||
import { SpeakMessageContext } from "../(data)/speak-message-context";
|
||||
import {
|
||||
StopBotContext,
|
||||
type StopBotState,
|
||||
} from "../(data)/stop-bot-context";
|
||||
import reactToBotMessage from "../(functions)/react-to-bot-message";
|
||||
import botBusyState from "../(utils)/bot-busy-state";
|
||||
import dropSentMessage from "../(utils)/drop-sent-message";
|
||||
import useBotComputers from "../(hooks)/use-bot-computers";
|
||||
import useStopBot from "../(hooks)/use-stop-bot";
|
||||
import useTaskProgress from "../(hooks)/use-task-progress";
|
||||
import useReplyProgress from "../(hooks)/use-reply-progress";
|
||||
import useReplyCatchUp from "../(hooks)/use-reply-catch-up";
|
||||
@@ -90,6 +96,10 @@ export default function Conversation() {
|
||||
workspace_id,
|
||||
computers: pageProps?.bot_computers || [],
|
||||
});
|
||||
const stop_bot = useStopBot({
|
||||
bot_id: bot?.id || 0,
|
||||
workspace_id,
|
||||
});
|
||||
|
||||
const speak = useSpeakMessage({
|
||||
enabled: Boolean(pageProps?.bot_voice?.speech),
|
||||
@@ -233,7 +243,26 @@ export default function Conversation() {
|
||||
|
||||
if (!bot?.id || !live_bot) return null;
|
||||
|
||||
return (
|
||||
/**
|
||||
* What the stop control pulls the plug on, read the way the thinking
|
||||
* row reads it: the same conditions, so the header's row is enabled
|
||||
* exactly while the thread shows the bot at work.
|
||||
*/
|
||||
const stop_state: StopBotState = {
|
||||
...stop_bot,
|
||||
can_stop: botBusyState({
|
||||
bot: live_bot,
|
||||
awaiting_reply,
|
||||
receiving: pending_messages.length > 0,
|
||||
has_task: Boolean(progress.task_id),
|
||||
}).stoppable,
|
||||
};
|
||||
|
||||
/**
|
||||
* The thread, kept intact so the stop control can wrap it without
|
||||
* reindenting every provider.
|
||||
*/
|
||||
const thread = (
|
||||
<CrewBotsContext.Provider value={bots}>
|
||||
<CrewWorkspacesContext.Provider value={workspaces}>
|
||||
<BotComputersContext.Provider value={bot_computers}>
|
||||
@@ -316,4 +345,10 @@ export default function Conversation() {
|
||||
</CrewWorkspacesContext.Provider>
|
||||
</CrewBotsContext.Provider>
|
||||
);
|
||||
|
||||
return (
|
||||
<StopBotContext.Provider value={stop_state}>
|
||||
{thread}
|
||||
</StopBotContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,193 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import {
|
||||
BotComputerBusyStatusLine,
|
||||
BotGettingMessageStatusLine,
|
||||
BotReplyJobTitle,
|
||||
BotWaitingStatusLine,
|
||||
} from "@/src/dict/bot-queue-dict";
|
||||
import type { BotWithLastMessage } from "@/src/types";
|
||||
import botBusyState from "./bot-busy-state";
|
||||
|
||||
function bot(overrides: Partial<BotWithLastMessage>): BotWithLastMessage {
|
||||
return { id: 1, name: "Ember", ...overrides } as BotWithLastMessage;
|
||||
}
|
||||
|
||||
describe("botBusyState", () => {
|
||||
test("a reply owed here is thinking", () => {
|
||||
const state = botBusyState({ bot: bot({ face: "idle" }), awaiting_reply: true });
|
||||
|
||||
expect(state.thinking).toBe(true);
|
||||
expect(state.busy).toBe(true);
|
||||
});
|
||||
|
||||
test("a message still on its way is getting, not thinking", () => {
|
||||
const state = botBusyState({
|
||||
bot: bot({ face: "working" }),
|
||||
awaiting_reply: true,
|
||||
receiving: true,
|
||||
});
|
||||
|
||||
expect(state.getting).toBe(true);
|
||||
expect(state.thinking).toBe(false);
|
||||
});
|
||||
|
||||
test("a task running while the bot has the last word is working", () => {
|
||||
const state = botBusyState({
|
||||
bot: bot({ face: "working", status_line: "Working" }),
|
||||
awaiting_reply: false,
|
||||
has_task: true,
|
||||
});
|
||||
|
||||
expect(state.working).toBe(true);
|
||||
expect(state.busy).toBe(true);
|
||||
});
|
||||
|
||||
test("a reply's own turn never shows as working on a task", () => {
|
||||
const state = botBusyState({
|
||||
bot: bot({ face: "working", status_line: BotReplyJobTitle }),
|
||||
has_task: true,
|
||||
});
|
||||
|
||||
expect(state.working).toBe(false);
|
||||
expect(state.busy).toBe(false);
|
||||
});
|
||||
|
||||
test("waiting for a model is a wait, with a reply owed here", () => {
|
||||
const state = botBusyState({
|
||||
bot: bot({ face: "asleep", status_line: BotWaitingStatusLine }),
|
||||
awaiting_reply: true,
|
||||
});
|
||||
|
||||
expect(state.waiting).toBe(true);
|
||||
expect(state.thinking).toBe(false);
|
||||
expect(state.busy).toBe(true);
|
||||
});
|
||||
|
||||
test("waiting for a model is a wait, with a task running", () => {
|
||||
const state = botBusyState({
|
||||
bot: bot({ face: "asleep", status_line: BotWaitingStatusLine }),
|
||||
has_task: true,
|
||||
});
|
||||
|
||||
expect(state.waiting).toBe(true);
|
||||
expect(state.busy).toBe(true);
|
||||
});
|
||||
|
||||
test("waiting for its computer is a wait only while a task runs", () => {
|
||||
const waiting = botBusyState({
|
||||
bot: bot({ face: "asleep", status_line: BotComputerBusyStatusLine }),
|
||||
has_task: true,
|
||||
});
|
||||
const idle = botBusyState({
|
||||
bot: bot({ face: "asleep", status_line: BotComputerBusyStatusLine }),
|
||||
});
|
||||
|
||||
expect(waiting.waiting).toBe(true);
|
||||
expect(idle.busy).toBe(false);
|
||||
});
|
||||
|
||||
test("a message still on its way wins over the wait, so the row says what the user just did", () => {
|
||||
const state = botBusyState({
|
||||
bot: bot({ face: "asleep", status_line: BotWaitingStatusLine }),
|
||||
awaiting_reply: true,
|
||||
receiving: true,
|
||||
});
|
||||
|
||||
expect(state.getting).toBe(true);
|
||||
expect(state.waiting).toBe(true);
|
||||
});
|
||||
|
||||
test("an idle bot with nothing owed and no task shows nothing", () => {
|
||||
const state = botBusyState({ bot: bot({ face: "idle" }) });
|
||||
|
||||
expect(state.busy).toBe(false);
|
||||
});
|
||||
|
||||
test("a done face with no task shows nothing", () => {
|
||||
expect(botBusyState({ bot: bot({ face: "done" }) }).busy).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("botBusyState stoppable", () => {
|
||||
test("busy in this thread is stoppable", () => {
|
||||
expect(
|
||||
botBusyState({
|
||||
bot: bot({ face: "idle" }),
|
||||
awaiting_reply: true,
|
||||
}).stoppable,
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
test("working somewhere else is stoppable too, since the face is per user", () => {
|
||||
const state = botBusyState({ bot: bot({ face: "working" }) });
|
||||
|
||||
expect(state.busy).toBe(false);
|
||||
expect(state.stoppable).toBe(true);
|
||||
});
|
||||
|
||||
test("asleep on a wait line is stoppable, even when this thread shows nothing", () => {
|
||||
for (const status_line of [BotWaitingStatusLine, BotComputerBusyStatusLine]) {
|
||||
expect(botBusyState({ bot: bot({ face: "asleep", status_line }) }).stoppable).toBe(true);
|
||||
}
|
||||
});
|
||||
|
||||
test("a bot simply resting is not stoppable", () => {
|
||||
const state = botBusyState({
|
||||
bot: bot({ face: "asleep", status_line: "Until tomorrow" }),
|
||||
});
|
||||
|
||||
expect(state.busy).toBe(false);
|
||||
expect(state.stoppable).toBe(false);
|
||||
});
|
||||
|
||||
test("a message only being collected is not stoppable: its reply is queued after it", () => {
|
||||
const state = botBusyState({
|
||||
bot: bot({ face: "idle" }),
|
||||
awaiting_reply: true,
|
||||
receiving: true,
|
||||
});
|
||||
|
||||
expect(state.getting).toBe(true);
|
||||
expect(state.stoppable).toBe(false);
|
||||
});
|
||||
|
||||
test("done, needs-you and idle mean nothing is running", () => {
|
||||
for (const face of ["done", "needs-you", "idle"] as const) {
|
||||
const state = botBusyState({ bot: bot({ face }) });
|
||||
|
||||
expect(state.stoppable).toBe(false);
|
||||
}
|
||||
});
|
||||
|
||||
test("a silently stopped bot is not stoppable", () => {
|
||||
const state = botBusyState({
|
||||
bot: bot({ face: "idle" }),
|
||||
awaiting_reply: false,
|
||||
has_task: false,
|
||||
});
|
||||
|
||||
expect(state.stoppable).toBe(false);
|
||||
});
|
||||
|
||||
test("a reply job's own turn with no task owed is not stoppable", () => {
|
||||
/**
|
||||
* The face says working while a reply runs somewhere else, which is
|
||||
* real work: it's stoppable even though this thread owes nothing.
|
||||
*/
|
||||
const state = botBusyState({
|
||||
bot: bot({ face: "working", status_line: BotReplyJobTitle }),
|
||||
});
|
||||
|
||||
expect(state.stoppable).toBe(true);
|
||||
});
|
||||
|
||||
test("the getting line still labels the row", () => {
|
||||
const state = botBusyState({
|
||||
bot: bot({ face: "idle", status_line: BotGettingMessageStatusLine }),
|
||||
awaiting_reply: true,
|
||||
receiving: true,
|
||||
});
|
||||
|
||||
expect(state.getting).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,111 @@
|
||||
import type { BotWithLastMessage } from "@/src/types";
|
||||
import {
|
||||
BotComputerBusyStatusLine,
|
||||
BotReplyJobTitle,
|
||||
BotWaitingStatusLine,
|
||||
} from "@/src/dict/bot-queue-dict";
|
||||
|
||||
type Params = {
|
||||
bot: BotWithLastMessage;
|
||||
/**
|
||||
* The last message in the open thread is the user's, so a reply is due
|
||||
* here.
|
||||
*/
|
||||
awaiting_reply?: boolean;
|
||||
/**
|
||||
* A message is still on its way to the server.
|
||||
*/
|
||||
receiving?: boolean;
|
||||
/**
|
||||
* A task of the bot's is running.
|
||||
*/
|
||||
has_task?: boolean;
|
||||
};
|
||||
|
||||
export type BotBusyState = {
|
||||
/**
|
||||
* Waiting for a model to come back, or for the bot's computer.
|
||||
*/
|
||||
waiting: boolean;
|
||||
/**
|
||||
* The user's message hasn't reached the server yet.
|
||||
*/
|
||||
getting: boolean;
|
||||
/**
|
||||
* A reply is due in this thread.
|
||||
*/
|
||||
thinking: boolean;
|
||||
/**
|
||||
* A task is running and the bot has the last word.
|
||||
*/
|
||||
working: boolean;
|
||||
/**
|
||||
* Anything of the above, so the row has something to say.
|
||||
*/
|
||||
busy: boolean;
|
||||
/**
|
||||
* There's work of the bot's to pull the plug on. A message still on
|
||||
* its way doesn't count: its reply is queued after it lands, so a stop
|
||||
* now would cancel nothing and be overtaken a moment later. The face
|
||||
* covers work in the user's other conversations too, since it's one
|
||||
* per user; `asleep` only counts on the two status lines the queue
|
||||
* sets while it waits, never a bot that's simply resting.
|
||||
*/
|
||||
stoppable: boolean;
|
||||
};
|
||||
|
||||
/**
|
||||
* What a bot is doing in a conversation, read from the thread and its face.
|
||||
* The thread decides the reply states: every user message queues one, so
|
||||
* while the user has the last word a reply is due here, even while the bot
|
||||
* works elsewhere. Only the waits (for a model, for its computer) come from
|
||||
* the face. The thinking row reads it for its line, and the conversation
|
||||
* reads it for the stop control.
|
||||
*/
|
||||
export default function botBusyState({
|
||||
bot,
|
||||
awaiting_reply,
|
||||
receiving,
|
||||
has_task,
|
||||
}: Params): BotBusyState {
|
||||
const asleep = bot.face == "asleep";
|
||||
const waiting_model =
|
||||
asleep && bot.status_line == BotWaitingStatusLine && Boolean(awaiting_reply || has_task);
|
||||
const waiting_computer =
|
||||
asleep &&
|
||||
bot.status_line == BotComputerBusyStatusLine &&
|
||||
Boolean(has_task) &&
|
||||
!awaiting_reply;
|
||||
const waiting = waiting_model || waiting_computer;
|
||||
const getting = Boolean(receiving) && Boolean(awaiting_reply);
|
||||
const thinking = Boolean(awaiting_reply) && !waiting && !getting;
|
||||
const working =
|
||||
!awaiting_reply &&
|
||||
bot.face == "working" &&
|
||||
bot.status_line != BotReplyJobTitle &&
|
||||
Boolean(has_task);
|
||||
|
||||
/**
|
||||
* Work runs here (a reply owed, a task of this thread's) or somewhere
|
||||
* else of this user's (the face says `working`, or `asleep` on a wait
|
||||
* line).
|
||||
*/
|
||||
const stoppable =
|
||||
waiting ||
|
||||
thinking ||
|
||||
working ||
|
||||
bot.face == "working" ||
|
||||
(asleep &&
|
||||
(bot.status_line == BotWaitingStatusLine ||
|
||||
bot.status_line == BotComputerBusyStatusLine));
|
||||
|
||||
return {
|
||||
waiting,
|
||||
getting,
|
||||
thinking,
|
||||
working,
|
||||
busy: getting || thinking || working || waiting,
|
||||
stoppable,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import Span from "@moduletrace/twui/layout/Span";
|
||||
import type { RunningVersion } from "@/src/utils/running-version";
|
||||
import versionLabel from "../(utils)/version-label";
|
||||
|
||||
type Props = {
|
||||
running?: RunningVersion | null;
|
||||
@@ -7,21 +8,14 @@ type Props = {
|
||||
|
||||
/**
|
||||
* The release this server runs, in words: settings are where someone
|
||||
* checks whether an update landed. A development server says so beside
|
||||
* its version, so the two are never mistaken.
|
||||
* checks whether an update landed. The stage and, on a development server,
|
||||
* that it is one ride along, so neither what it runs nor what it is can be
|
||||
* mistaken.
|
||||
*/
|
||||
export default function VersionLine({ running }: Props) {
|
||||
if (!running) return null;
|
||||
const label = versionLabel({ running });
|
||||
|
||||
const version = running.version
|
||||
? `Cobble ${running.version}`
|
||||
: "Cobble";
|
||||
if (!label) return null;
|
||||
|
||||
return (
|
||||
<Span className="text-sm leading-5 text-ink">
|
||||
{running.mode == "development"
|
||||
? `${version} (development)`
|
||||
: version}
|
||||
</Span>
|
||||
);
|
||||
return <Span className="text-sm leading-5 text-ink">{label}</Span>;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import versionLabel from "./version-label";
|
||||
|
||||
describe("versionLabel", () => {
|
||||
test("a release names its version and that it is alpha", () => {
|
||||
expect(
|
||||
versionLabel({
|
||||
running: { version: "v0.1.5", mode: "production" },
|
||||
}),
|
||||
).toBe("Cobble v0.1.5 (alpha)");
|
||||
});
|
||||
|
||||
test("a development server says so beside the stage", () => {
|
||||
expect(
|
||||
versionLabel({
|
||||
running: { version: "0.1.5", mode: "development" },
|
||||
}),
|
||||
).toBe("Cobble 0.1.5 (development, alpha)");
|
||||
});
|
||||
|
||||
test("a server with no usable version still names the stage", () => {
|
||||
expect(
|
||||
versionLabel({ running: { version: null, mode: "production" } }),
|
||||
).toBe("Cobble (alpha)");
|
||||
});
|
||||
|
||||
test("no running version says nothing at all", () => {
|
||||
expect(versionLabel({ running: null })).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,27 @@
|
||||
import type { RunningVersion } from "@/src/utils/running-version";
|
||||
|
||||
/**
|
||||
* The stage every release is published as. Cobble is still alpha: the
|
||||
* schema, the settings and the screens change between releases, so the app
|
||||
* says so wherever it names its version, not only in the README.
|
||||
*/
|
||||
export const ReleaseStage = "alpha";
|
||||
|
||||
type Params = {
|
||||
running?: RunningVersion | null;
|
||||
};
|
||||
|
||||
/**
|
||||
* The running release in words, for the General settings page: "Cobble
|
||||
* v0.1.5 (alpha)", and a development server adds that it is one, so a dev
|
||||
* build is never mistaken for a release.
|
||||
*/
|
||||
export default function versionLabel({ running }: Params): string | null {
|
||||
if (!running) return null;
|
||||
|
||||
const parts = [running.mode == "development" ? "development" : "", ReleaseStage].filter(
|
||||
(part) => part.length > 0,
|
||||
);
|
||||
|
||||
return `${running.version ? `Cobble ${running.version}` : "Cobble"} (${parts.join(", ")})`;
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
import userAuth from "@/src/functions/backend/auth/user-auth";
|
||||
import grabUserConversation from "@/src/functions/backend/db/bot-sessions/grab-user-conversation";
|
||||
import countOpenBotJobs from "@/src/functions/backend/db/bots-queue/count-open-bot-jobs";
|
||||
import stopBotJobs from "@/src/functions/backend/db/bots-queue/stop-bot-jobs";
|
||||
import pushBotNotice from "@/src/bots-queue/push-bot-notice";
|
||||
import { BotConversationRequestSchema } from "@/src/schemas/bot-schema";
|
||||
import type { BotStoppedPayload } from "@/src/types";
|
||||
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";
|
||||
|
||||
/**
|
||||
* Pulls the plug on a bot for the session user: every job of it that's
|
||||
* queued or running in their conversations with it stops, its tasks close
|
||||
* and it goes idle, so a bot stuck waiting for a model (or anything else)
|
||||
* comes back at once. Stopping from a workspace stops the bot there and in
|
||||
* its own chat: the user asked for the bot to stop, not one tab of it.
|
||||
* A bot with nothing open is a no-op. The messages that end the wait go
|
||||
* out live, to this tab and the user's others.
|
||||
*/
|
||||
export const handler: BunextAPIRouteHandler<APIResponseObject<BotStoppedPayload>> = 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 { bot_id, workspace_id } = parseWithSchema({
|
||||
schema: BotConversationRequestSchema,
|
||||
data: body,
|
||||
});
|
||||
|
||||
/**
|
||||
* Checked against the conversation it was asked from, so the stop
|
||||
* button works exactly where the conversation opens.
|
||||
*/
|
||||
const conversation = await grabUserConversation({
|
||||
user_id: user.id,
|
||||
bot_id,
|
||||
workspace_id,
|
||||
});
|
||||
|
||||
const stopped = await stopBotJobs({
|
||||
bot_id: conversation.bot.id,
|
||||
user_id: user.id,
|
||||
});
|
||||
|
||||
if (stopped) {
|
||||
/**
|
||||
* Live only: the user just pressed the button in the app, so
|
||||
* their devices don't need a notification per conversation.
|
||||
*/
|
||||
for (const message of stopped.messages) {
|
||||
await pushBotNotice({
|
||||
bot_id: conversation.bot.id,
|
||||
message,
|
||||
quiet_push: true,
|
||||
});
|
||||
}
|
||||
|
||||
await pushBotNotice({ bot_id: conversation.bot.id, bot: stopped.bot });
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
singleRes: {
|
||||
bot_id: conversation.bot.id,
|
||||
stopped: stopped?.jobs.length || 0,
|
||||
remaining:
|
||||
(await countOpenBotJobs({
|
||||
bot_id: conversation.bot.id,
|
||||
user_id: user.id,
|
||||
})) || 0,
|
||||
},
|
||||
msg: stopped
|
||||
? `Stopped ${stopped.jobs.length} ${stopped.jobs.length == 1 ? "job" : "jobs"}.`
|
||||
: `Nothing is running.`,
|
||||
};
|
||||
} catch (error: unknown) {
|
||||
return { success: false, msg: safeErrorMessage({ error }) };
|
||||
}
|
||||
};
|
||||
@@ -209,6 +209,17 @@ export type BotTaskWithSteps = BUN_SQLITE_COBBLE_BOT_TASKS & {
|
||||
updates: BUN_SQLITE_COBBLE_BOTS_QUEUE_UPDATES[];
|
||||
};
|
||||
|
||||
/**
|
||||
* What stopping a bot reports back: how many of its jobs were stopped and
|
||||
* how many of them are still open (an attempt that has to notice its
|
||||
* lock is gone can take a heartbeat).
|
||||
*/
|
||||
export type BotStoppedPayload = {
|
||||
bot_id: number;
|
||||
stopped: number;
|
||||
remaining: number;
|
||||
};
|
||||
|
||||
/**
|
||||
* `server:bot-job-update` data: a step a running job just took, with the
|
||||
* task it's for (null for a reply).
|
||||
|
||||
Reference in New Issue
Block a user