Compare commits

..
9 Commits
Author SHA1 Message Date
tben ee4af467b3 Bump version to 0.28.9
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
2026-11-25 10:02:24 +01:00
tben b2c8a788da Ask for a routine's or hook's brief as the plan its run follows
Routines and hook calls never plan at run time, so the tools that make or
change one ask for the instructions as the steps in order, each naming what
it produces.
2026-11-25 09:59:04 +01:00
tben d38a15862a Never plan in routines or hooks, follow a carried session, and open the previous one as its own page
Routines and hook calls already have their plan (the brief, the runbook), so
they get neither the plan tools nor the planning turn, and the approve/in_run
paths those runs needed are gone.

A live conversation now follows its session into a newer one, from the push or
from the catch-up read that reports it, instead of waiting on the old thread
and showing "No answer came."; a page opened on an old session keeps its bar
and hides that row.

The thread's "Show the previous session" opens that session as its own page
instead of paging it inline.
2026-11-25 09:49:33 +01:00
tben e8b59997ac Keep ref pills their own colour in the user bubble
The bubble-wide link rule outranked a pill's text-ink, so chips with links
turned blue. Exclude links inside a ref chip's quote wrapper.
2026-11-25 09:39:38 +01:00
tben 7919bb39b8 Autofocus the all-bots search and restore the user bubble link colour 2026-11-25 09:35:06 +01:00
tben fcfc6874a8 Add session slash commands to the composer
/new starts a fresh session, /continue carries the conversation into a new one with a summary, and /clear deletes this session and starts a fresh one after a confirm. Up and Down walk the list, Enter runs the highlighted command, and a click fills it in first; a failed command comes back in the input with the server's reason.
2026-11-25 09:35:06 +01:00
tben e538ca029f Let members read the bot's instructions and memory in its panel
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
2026-11-25 08:24:16 +01:00
tben f66c97448f Let members open the bot panel and keep their own memory about them
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
Members read a bot's role and instructions, rewrite what it remembers about
them, and see its tools read-only; the stone and the name open the panel for
everyone. Also comments out the user bubble link colour.
2026-11-25 07:41:17 +01:00
tben 98948c559c Reload into the new build when a stale page sends a message
A page left open across a deploy kept sending from code the server no
longer serves. The root now puts the running build in a cobble-build meta
tag, the composer sends the build it was loaded from, and the send route
refuses an older one with stale_build before storing or queueing anything.
The composer keeps the typed text and uploaded attachments in the draft
and reloads, so the new build picks them up and the user sends again.
2026-11-25 07:30:35 +01:00
50 changed files with 1000 additions and 347 deletions
+7 -7
View File
File diff suppressed because one or more lines are too long
+4
View File
@@ -673,6 +673,10 @@ const schema: BUN_SQLITE_DatabaseSchemaType = {
indexName: "idx_bot_messages_session_id_created_at",
indexTableFields: ["session_id", "created_at"],
},
{
indexName: "idx_bot_messages_carried_from_session_id",
indexTableFields: ["carried_from_session_id"],
},
{
indexName: "idx_bot_messages_reply_to_message_id",
indexTableFields: ["reply_to_message_id"],
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "cobble",
"version": "0.28.6",
"version": "0.28.9",
"module": "index.ts",
"type": "module",
"private": true,
+3 -20
View File
@@ -15,7 +15,6 @@ import {
ConnectorsNote,
ComputerFilesNote,
ScheduledRunNote,
ScheduledPlanNote,
HookRunNote,
InstallRequestNote,
TasksNote,
@@ -489,22 +488,6 @@ export default async function runBotTask({
job_id: job.id || null,
onGraphic: ({ ref }) => shown.push(ref),
}),
/**
* A routine's plan is approved at once and worked through in
* the run, since nobody is there to approve it on a card
* (`ScheduledPlanNote`). A hook call gets none: its thread is a
* log of calls, not a conversation to read a plan in.
*/
...(scheduled && session_id
? grabBotPlanTools({
user_id,
bot_id: bot.id,
session_id,
workspace_id,
approve: true,
onPlan: ({ ref }) => shown.push(ref),
})
: []),
];
extensions = await openBotExtensions({
@@ -657,7 +640,6 @@ export default async function runBotTask({
TaskRunNote,
steps_note,
scheduled ? ScheduledRunNote : "",
scheduled ? ScheduledPlanNote : "",
hooked ? HookRunNote : "",
install_request_id ? InstallRequestNote : "",
Number(params.ask_id) ? AskTaskRunNote : "",
@@ -721,9 +703,10 @@ export default async function runBotTask({
* a step (`planBotTask`). It shares this run's prompt, so it costs
* little more than the plan, and it saves the steps a long run
* spends finding out what it is doing. A run whose plan can't be
* written starts the way it always did.
* written starts the way it always did. A routine or a hook call
* already has its plan (the brief, the runbook), so it works that.
*/
const planned = shouldPlanBotTask({ max_steps })
const planned = !scheduled && !hooked && shouldPlanBotTask({ max_steps })
? await planBotTask({ system, messages: opening, signal, bot_id: bot.id, workspace_id }).catch(
(error) => {
if (signal.aborted) throw error;
+1 -5
View File
@@ -23,7 +23,6 @@ import {
PlanWaitingNote,
PlanActiveNote,
PlanPausedNote,
ScheduledPlanNote,
RetryFailureNote,
} from "./harness-prompts";
import computerRunDirs from "@/src/utils/computer-work-dirs";
@@ -355,8 +354,5 @@ describe("plan notes", () => {
expect(PlanPausedNote({ plan: { ...plan, status: "paused" } })).toContain("paused by the user");
});
test("a routine's plan is approved at once and worked through in the run", () => {
expect(ScheduledPlanNote).toContain("approved at once");
expect(ScheduledPlanNote).toContain("work its steps in this run");
});
});
-8
View File
@@ -1134,11 +1134,3 @@ The user sent this message with Plan mode on. This reply plans, reads and asks;
- Every answer here carries a Turn Plan mode off button under it, so the way on is one click: say in one sentence what you will do once it is off, and stop there. Never hand the work back to them to paste or do by hand; turning the mode off (that button, or Tab) is the only thing in the way.
- End with send_reply: done sends the plan or the answer, blocked says what stopped you. Work can't be queued here.
- Say what you would do and what it depends on, not that you are doing it.`;
/**
* Added to a routine's run: nobody is there to approve a plan, so the bot
* writes one and works all of it in the run, reporting at the end.
*/
export const ScheduledPlanNote = `# A plan in a scheduled run
Nobody is watching this run, so a plan can't wait for approval. If this run's work is several pieces that build on each other, write it with create_plan anyway (it is approved at once here) and work its steps in this run: complete_plan_step after each one, with what it produced, so the conversation shows how far it got. Nothing interleaves with your run, so don't stop after one step. Your report at the end covers the whole plan: what each step produced and what is left.`;
+6
View File
@@ -25,6 +25,12 @@ export const PwaLoadingPath = "/loading.html";
export const PwaBuildInfoPath = "/build-info.json";
export const PwaPrecacheCachePrefix = "cobble-assets-";
export const PwaPrecacheMarkerPath = "/__cobble-precached";
/**
* The meta tag the root puts the running build in, so the page's own code
* knows which build it was loaded from (`loaded-build.ts`) and a send from
* an older one can be refused.
*/
export const PwaBuildMetaName = "cobble-build";
export type PwaIcon = {
src: string;
@@ -46,7 +46,7 @@ export default function createScheduleTool({ user_id, bot_id, workspace_id, comp
computers.length
? `Runs use the computer you're on when they start unless you pick one: ${listed}.`
: `You have no computer here, so runs can't use one.`
} Write the instructions as a full brief for a future you with no memory of this chat. Runs carry the brief out without asking the user, so state the action itself ("send the summary to ..."), not a draft for them to approve, unless they asked to approve it.`,
} Write the instructions as a full brief for a future you with no memory of this chat, and as the plan the run follows: the steps in order, each naming what it produces. Runs carry the brief out without asking the user, so state the action itself ("send the summary to ..."), not a draft for them to approve, unless they asked to approve it.`,
schema: z.object({
title: z.string().min(1).max(80).describe(`A short label, e.g. "Morning inbox digest"`),
instructions: z.string().min(1).max(8000),
@@ -66,7 +66,7 @@ export default function proposeHookTool({
name: "propose_hook",
description: `Propose a hook for the user to confirm: a secret URL an outside service (a webhook from GitHub, Stripe, a form, a script) calls to give you a task, or a watcher that hands you each browser notification on one of your computers (source browser_notifications, with watch_computer_id and an optional watch_filter, text the notification's site, title or body must contain). Every call queues your instructions (the brief) as a task for you, ${
workspace_id ? "in this workspace" : "in your own chat"
}, with what the caller sent attached as data, in the hook's own thread: results never come back to this chat, the user reads them by opening the hook. Runs carry the brief out without asking the user, so write it as a full brief for a future you with no memory of this chat, saying exactly what to do with each call. ${
}, with what the caller sent attached as data, in the hook's own thread: results never come back to this chat, the user reads them by opening the hook. Runs carry the brief out without asking the user, so write it as a full brief for a future you with no memory of this chat, saying exactly what to do with each call, and lay it out as the plan the run follows: the steps in order, each naming what it produces. ${
computers.length ? `Your computers here: ${listed}.` : `You have no computer here, so it can't watch one.`
} To change one of your hooks (ids from list_hooks), give hook_id and only what changes: title, instructions, watch_filter, enabled true to switch a paused one back on, or its runner; what calls it and where it runs can't change. A hook whose caller is a process on your computer (a bridge started there) can keep it running: give runner_command, the command the app runs for it, runner_dir (a folder inside the bot's folder, such as whatsapp) and, if not the bot's own, runner_computer_id. The app starts it again by itself within five minutes of it dying, and when the computer restarts, so it must stay in the foreground and not go into the background with &. It runs as the bot's account, and the card shows the command word for word: only a crew manager can confirm a runner, so if the user isn't one, tell them an admin has to. Nothing is saved until the user presses Confirm on the card. A new hook's URL is shown to the user on the card, once: you never see it, never ask for it, and never set a signing secret (the user adds one from the Hooks menu). Check list_hooks first: if a hook already does the job, propose a change to it instead. When the user tells you to handle a hook's calls differently (often in reply to a run's report), tell them the hook's brief has to change for that and propose the new brief. Runs follow the brief over your memory, so don't save it to your memory or promise to do it from now on instead: neither changes what the next call does.`,
schema: z.object({
@@ -7,12 +7,6 @@ import type { HarnessTool } from "../../../types";
type Params = {
bot_id: number | string;
session_id: number | string;
/**
* The step is finished inside a run that works the whole plan itself (a
* routine), so this isn't the reply that ends it: the run carries on
* into the next step, and one run can finish more than one.
*/
in_run?: boolean;
};
type Args = {
@@ -26,14 +20,12 @@ type Args = {
* ends on, so a step is only ever finished by a run that did the work, one
* at a time.
*/
export default function completePlanStepTool({ bot_id, session_id, in_run }: Params): HarnessTool<Args> {
export default function completePlanStepTool({ bot_id, session_id }: Params): HarnessTool<Args> {
let completed = false;
return {
name: "complete_plan_step",
description: in_run
? `Finish one step of the plan, once you have actually done it, before you start the next. Give one or two lines on what it produced (the number, the path, the link). You work this plan yourself here, so call it after each step and keep going.`
: `Finish the plan's current step, once you have actually done it. Give one or two lines on what it produced (the number, the path, the link). Call it before you write your report: the report is this reply's last message. One step per reply. Never call it for a step you didn't do, and never for one after the current step.`,
description: `Finish the plan's current step, once you have actually done it. Give one or two lines on what it produced (the number, the path, the link). Call it before you write your report: the report is this reply's last message. One step per reply. Never call it for a step you didn't do, and never for one after the current step.`,
schema: z.object({
plan_id: z.number().int().positive().describe(`The plan's id, as your prompt gives it`),
summary: z
@@ -47,7 +39,7 @@ export default function completePlanStepTool({ bot_id, session_id, in_run }: Par
.describe(`What the step produced, in a line or two`),
}),
run: async ({ args }) => {
if (completed && !in_run) {
if (completed) {
throw new Error(`You already finished a step of this plan in this reply. One step per reply.`);
}
@@ -71,11 +63,7 @@ export default function completePlanStepTool({ bot_id, session_id, in_run }: Par
const next = done.steps[done.next_step ?? 0];
if (in_run) {
return `Step ${done.index + 1} is done: the card shows it. Carry on with step ${(done.next_step ?? 0) + 1}: ${next?.text || ""}. Save your report for the end, when every step is done.`;
}
return `Step ${done.index + 1} is done: the card shows it. The next step (step ${(done.next_step ?? 0) + 1}: ${next?.text || ""}) starts when the user answers the card on your report, so don't start it now. Write your report: two or three sentences on what this step produced, and put the card up beside it.`;
},
};
}
}
@@ -1,6 +1,5 @@
import { z } from "zod";
import createBotPlan from "@/src/functions/backend/db/bot-plans/create-bot-plan";
import setBotPlanStatus from "@/src/functions/backend/db/bot-plans/set-bot-plan-status";
import pushBotPlan from "@/src/bots-queue/push-bot-plan";
import { BotPlanGoalSchema, BotPlanStepTextsSchema, BotPlanTitleSchema } from "@/src/schemas/bot-plan-schema";
import botPlanRef from "@/src/utils/bot-plan-ref";
@@ -12,13 +11,7 @@ type Params = {
session_id: number | string;
workspace_id?: number | string | null;
/**
* A scheduled run, which nobody watches: the plan is approved at once,
* since there is no card for someone to approve it on.
*/
approve?: boolean;
/**
* Called with the plan's ref, so the message carries its card. `waiting`
* says nobody approved it yet: the user is needed for it to go on.
* Called with the plan's ref, so the message carries its card.
*/
onPlan: (params: { ref: string; waiting?: boolean }) => void;
};
@@ -30,17 +23,15 @@ type Args = {
};
/**
* The bot broke work into a plan. In a chat it waits on its card for the
* user to approve (or change) it, and the app then wakes the bot one step at
* a time. In a scheduled run nobody is there to approve anything, so the
* plan starts itself and the run works through it.
* The bot broke work into a plan. It waits on its card for the user to
* approve (or change) it, and the app then wakes the bot one step at a time.
* A routine and a hook call have no card to wait on, so they get no plan
* tools at all.
*/
export default function createPlanTool({ user_id, bot_id, session_id, workspace_id, approve, onPlan }: Params): HarnessTool<Args> {
export default function createPlanTool({ user_id, bot_id, session_id, workspace_id, onPlan }: Params): HarnessTool<Args> {
return {
name: "create_plan",
description: approve
? `Write the plan for work that is several steps, before starting it: the goal that says what finished looks like, and 3 to 6 steps in the order you'd do them, one line each, each naming what it produces. Nobody is watching this run, so it's approved at once and you work it here: call complete_plan_step after each step.`
: `Write the plan for work that is several steps, before starting it: the goal that says what finished looks like, and 3 to 6 steps in the order you'd do them, one line each, each naming what it produces. It goes to the user as a card in this conversation, and nothing of it runs until they approve it (they can change the steps first). Write the plan instead of answering with a long list of everything you're about to do. Only when a plan is already open in this conversation, work it instead.`,
description: `Write the plan for work that is several steps, before starting it: the goal that says what finished looks like, and 3 to 6 steps in the order you'd do them, one line each, each naming what it produces. It goes to the user as a card in this conversation, and nothing of it runs until they approve it (they can change the steps first). Write the plan instead of answering with a long list of everything you're about to do. Only when a plan is already open in this conversation, work it instead.`,
schema: z.object({
title: BotPlanTitleSchema.describe(`A short name for the work, e.g. "Audit the pricing pages"`),
goal: BotPlanGoalSchema.describe(`What the plan is for and what "done" means, in one sentence`),
@@ -57,20 +48,12 @@ export default function createPlanTool({ user_id, bot_id, session_id, workspace_
steps: args.steps,
});
if (approve) {
await setBotPlanStatus({ plan_id, user_id, status: "active" });
}
onPlan({ ref: botPlanRef({ plan_id }), waiting: !approve });
onPlan({ ref: botPlanRef({ plan_id }), waiting: true });
await pushBotPlan({ plan_id, session_id, bot_id });
const count = args.steps.length;
if (approve) {
return `Plan #${plan_id} is written (${count} step${count == 1 ? "" : "s"}), and it's approved already because this run isn't watched. Work its steps in this run, calling complete_plan_step after each with what it produced.`;
}
return `Plan #${plan_id} is on its card in the conversation (${count} step${count == 1 ? "" : "s"}) and nothing of it runs until the user approves it. Say in one sentence that you wrote it and that they can change it before it starts; don't repeat the steps and don't work any of them now. When they approve it, you'll be woken for the first step.`;
},
};
}
}
@@ -3,11 +3,10 @@ import grabBotPlanTools from "./grab-bot-plan-tools";
/**
* A run working a plan's step may only work it: writing another plan, or
* cancelling the one it was woken for, is the user's call on the card. A
* scheduled run has no card to approve anything on, so its plan starts
* itself and nothing is left for the bot to cancel. A reply that isn't a
* step can't finish one either, or the plan would sit active with no card
* to start the next step from.
* cancelling the one it was woken for, is the user's call on the card. Only
* a chat reply writes a plan. A reply that isn't a step can't finish one
* either, or the plan would sit active with no card to start the next step
* from.
*/
const names = (tools: { name: string }[]) => tools.map((tool) => tool.name);
@@ -30,10 +29,6 @@ describe("grabBotPlanTools", () => {
expect(names(build({ on_step: true }))).toEqual(["update_plan", "complete_plan_step"]);
});
test("a scheduled run writes a plan that's already approved, and can't cancel it", () => {
expect(names(build({ approve: true }))).toEqual(["create_plan", "update_plan", "complete_plan_step"]);
});
test("a plan the app writes shows its card on the message", () => {
const refs: string[] = [];
@@ -41,4 +36,4 @@ describe("grabBotPlanTools", () => {
expect(refs).toEqual([]);
});
});
});
@@ -14,11 +14,6 @@ type Params = {
* to write one or end one.
*/
on_step?: boolean;
/**
* A scheduled run, which nobody watches: a plan it writes is approved
* at once and worked through in the run (`ScheduledPlanNote`).
*/
approve?: boolean;
/**
* Called with each plan's ref, so the message carries its card.
*/
@@ -28,9 +23,9 @@ type Params = {
/**
* The tools a bot plans with: `create_plan` when work is several steps,
* `update_plan` when what it found makes the rest wrong, and
* `complete_plan_step` to finish the step it worked. A chat reply's plan
* waits on its card for the user; a scheduled run's is approved at once,
* since nobody is there to approve it.
* `complete_plan_step` to finish the step it worked. A plan waits on its
* card for the user; only a chat reply writes one, since routines and hook
* calls already have their plan.
*
* A run that is itself working a plan gets neither `create_plan` (the
* conversation already has one open) nor `cancel_plan` (whether the plan
@@ -40,20 +35,17 @@ type Params = {
* finish it with no card under its report, and the plan would sit active
* with nothing to start the next one.
*/
export default function grabBotPlanTools({ user_id, bot_id, session_id, workspace_id, on_step, approve, onPlan }: Params) {
export default function grabBotPlanTools({ user_id, bot_id, session_id, workspace_id, on_step, onPlan }: Params) {
const tools: HarnessTool[] = [];
if (!on_step) {
tools.push(createPlanTool({ user_id, bot_id, session_id, workspace_id, approve, onPlan }));
if (!approve) {
tools.push(cancelPlanTool({ user_id, bot_id, session_id }));
}
tools.push(createPlanTool({ user_id, bot_id, session_id, workspace_id, onPlan }));
tools.push(cancelPlanTool({ user_id, bot_id, session_id }));
}
tools.push(updatePlanTool({ user_id, bot_id, session_id, onPlan }));
if (on_step || approve) tools.push(completePlanStepTool({ bot_id, session_id, in_run: approve }));
if (on_step) tools.push(completePlanStepTool({ bot_id, session_id }));
return tools;
}
}
@@ -38,7 +38,7 @@ export default function updateScheduleTool({ user_id, bot_id, is_coordinator, wo
schema: z.object({
schedule_id: z.number().int(),
title: z.string().min(1).max(80).optional(),
instructions: z.string().min(1).max(8000).optional(),
instructions: z.string().min(1).max(8000).optional().describe("The brief every run follows, as its plan: the steps in order"),
schedule: z.string().min(1).max(100).optional(),
enabled: z.boolean().optional(),
max_runs: z.number().int().positive().nullable().optional(),
+17 -3
View File
@@ -18,15 +18,28 @@ type Props = {
* Every bot (of the crew, or of a workspace), latest activity first, with
* a search by name or job. A bot opens its conversation.
*/
export default function AllBotsModal({ open, setOpen, title, bots, hrefFor }: Props) {
export default function AllBotsModal({
open,
setOpen,
title,
bots,
hrefFor,
}: Props) {
const [query, setQuery] = useState("");
const search = query.trim().toLowerCase();
const found = search
? bots.filter((bot) => `${bot.name} ${bot.role || ""}`.toLowerCase().includes(search))
? bots.filter((bot) =>
`${bot.name} ${bot.role || ""}`.toLowerCase().includes(search),
)
: bots;
return (
<AddModalShell open={open} setOpen={setOpen} title={title} description={`${bots.length} in all.`}>
<AddModalShell
open={open}
setOpen={setOpen}
title={title}
description={`${bots.length} in all.`}
>
<Input
id="all-bots-search"
title="Search bots"
@@ -35,6 +48,7 @@ export default function AllBotsModal({ open, setOpen, title, bots, hrefFor }: Pr
defaultValue={query}
onChange={(e) => setQuery(e.target.value)}
wrapperWrapperProps={{ className: "mt-4" }}
autoFocus
/>
<Stack className="w-full mt-2 max-h-[60vh] overflow-y-auto gap-0! items-stretch">
{found.map((bot) => (
+2
View File
@@ -9,6 +9,7 @@ import { SettingsDefaultPath } from "../dict/settings-pages-dict";
import grabInstallName from "../functions/backend/db/app-settings/grab-install-name";
import grabInstallIcon from "../functions/backend/db/app-settings/grab-install-icon";
import grabLastConversation from "../functions/backend/db/bot-sessions/grab-last-conversation";
import grabPrecacheManifest from "../functions/server/pwa/grab-precache-manifest";
import isPagesRailPath from "../utils/is-pages-rail-path";
/**
@@ -87,6 +88,7 @@ const server: BunextPageServerFn<PagePropsType> = async ({ req, url }) => {
},
user,
user_types,
build_id: grabPrecacheManifest()?.build_id || null,
install_name: await grabInstallName().catch(() => ""),
install_icon: await grabInstallIcon().catch(() => null),
last_conversation:
+4
View File
@@ -20,6 +20,7 @@ import AuthLayout from "../layouts/auth";
import BotsLayout from "../layouts/bots";
import ThemeInitScript from "../components/general/theme-init-script";
import PwaInitScript from "../components/general/pwa-init-script";
import { PwaBuildMetaName } from "../data/pwa-data";
import ServiceWorkerRegistrar from "../components/general/service-worker-registrar";
export const AppContext = React.createContext<AppContextObject>(
@@ -111,6 +112,9 @@ export function Head({ serverRes, ctx }: BunextPageHeadFCProps) {
<>
<ThemeInitScript />
<PwaInitScript />
{root_props?.build_id ? (
<meta name={PwaBuildMetaName} content={root_props.build_id} />
) : null}
<meta name="application-name" content={app_name} />
<meta name="mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-capable" content="yes" />
@@ -0,0 +1,15 @@
/**
* The composer's slash commands: what `/new`, `/continue` and `/clear` do
* to the conversation's session, and how the list above the input
* describes them.
*/
export type ComposerCommand = {
name: "new" | "continue" | "clear";
description: string;
};
export const ComposerCommands: ComposerCommand[] = [
{ name: "new", description: "Start a fresh session" },
{ name: "continue", description: "Carry this conversation into a new session, with a summary" },
{ name: "clear", description: "Delete this session and start a new one" },
];
@@ -12,6 +12,7 @@ export default async function sendBotMessage({
session_id,
client_id,
plan_mode,
build_id,
}: SendBotMessageRequest) {
return await fetchApi<
SendBotMessageRequest,
@@ -27,6 +28,7 @@ export default async function sendBotMessage({
session_id,
client_id,
plan_mode,
build_id,
},
});
}
@@ -20,12 +20,11 @@ type Params = {
/**
* Loads the session's older messages a page at a time, when the thread
* is scrolled to its top. Once the session's first message is in, the
* session it carries on from can be opened above it (`loadPrevious`, on
* the user's ask) and paged the same way, and so on back. Those messages
* are only shown: the bot's prompt still reads the session it answers in.
* A session the thread moves onto starts with its first message, so it
* has none older; `reset` starts over from a loaded history instead.
* is scrolled to its top. The session it carries on from is opened as its
* own page (its id is handed back for the link), never in place: the bot's
* prompt reads the session it answers in, not this one. A session the
* thread moves onto starts with its first message, so it has none older;
* `reset` starts over from a loaded history instead.
*/
export default function useOlderMessages({
session_id,
@@ -34,10 +33,6 @@ export default function useOlderMessages({
onLoaded,
}: Params) {
const [has_more, setHasMore] = useState(initial_has_more);
/**
* The session the thread's top belongs to, and the one before it.
*/
const [paging_session_id, setPagingSessionId] = useState<number | null>(session_id || null);
const [previous_session_id, setPreviousSessionId] = useState<number | null>(null);
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string>();
@@ -48,7 +43,6 @@ export default function useOlderMessages({
base_session.current = session_id;
setHasMore(false);
setPagingSessionId(session_id || null);
setPreviousSessionId(null);
setError(undefined);
}, [session_id]);
@@ -69,20 +63,21 @@ export default function useOlderMessages({
}) => {
base_session.current = session_id;
setHasMore(has_more);
setPagingSessionId(session_id);
setPreviousSessionId(previous_session_id || null);
setError(undefined);
},
[],
);
const load = async ({ session_id, before_id }: { session_id: number; before_id?: number | null }) => {
const loadOlder = async () => {
if (loading || !has_more || !session_id || !first_message_id) return;
setLoading(true);
setError(undefined);
const res = await postSessionApi<OlderBotMessagesData>({
path: "older-messages",
body: { session_id, before_id },
body: { session_id, before_id: first_message_id },
}).catch(() => null);
setLoading(false);
@@ -94,29 +89,15 @@ export default function useOlderMessages({
onLoaded({ messages: res.singleRes.messages });
setHasMore(res.singleRes.has_more);
setPagingSessionId(res.singleRes.session.id);
setPreviousSessionId(res.singleRes.session.previous_session_id);
};
const loadOlder = async () => {
if (loading || !has_more || !paging_session_id || !first_message_id) return;
await load({ session_id: paging_session_id, before_id: first_message_id });
};
const loadPrevious = async () => {
if (loading || has_more || !previous_session_id) return;
await load({ session_id: previous_session_id });
};
return {
has_more,
has_previous: !has_more && Boolean(previous_session_id),
previous_session_id,
loading,
error,
loadOlder,
loadPrevious,
reset,
};
}
@@ -29,6 +29,11 @@ type Params = {
* zero means the one it was waiting on ended without a message.
*/
on_open_jobs?: (params: { open_jobs: number }) => void;
/**
* The session was carried into a newer one: what the thread waited on
* is answering there, so an open conversation follows it.
*/
on_moved_to?: () => void;
};
/**
@@ -47,7 +52,8 @@ type Params = {
* face or task clear itself without a reload. The replies the session still
* has to come are handed back too: a run that ended without a word leaves
* the thread's last message the user's, so the face alone can't tell it from
* one still on its way.
* one still on its way. A session carried into a newer one is handed back
* with them, so the page that missed that push follows the answer there.
*/
export default function useReplyCatchUp({
session_id,
@@ -55,6 +61,7 @@ export default function useReplyCatchUp({
running,
last_message_id,
on_open_jobs,
on_moved_to,
}: Params) {
const last_message = useRef(Number(last_message_id) || 0);
/**
@@ -62,6 +69,7 @@ export default function useReplyCatchUp({
* the check (and the poll's timer with it).
*/
const report_open_jobs = useRef(on_open_jobs);
const report_moved_to = useRef(on_moved_to);
/**
* The open session: a read that lands after the thread moved to
* another one is dropped instead of replaying into the wrong thread.
@@ -71,6 +79,7 @@ export default function useReplyCatchUp({
last_message.current = Number(last_message_id) || 0;
open_session.current = session_id;
report_open_jobs.current = on_open_jobs;
report_moved_to.current = on_moved_to;
const check = useCallback(async () => {
if (!session_id) return;
@@ -116,6 +125,12 @@ export default function useReplyCatchUp({
if (typeof res.open_jobs == "number") {
report_open_jobs.current?.({ open_jobs: res.open_jobs });
}
/**
* The session was carried while the page wasn't looking (a phone
* that slept through the push): the new one holds the answer.
*/
if (Number(res.moved_to_session_id)) report_moved_to.current?.();
}, [session_id]);
useRefocus({ onRefocus: () => void check() });
@@ -148,4 +163,4 @@ export default function useReplyCatchUp({
window.removeEventListener("pageshow", check);
};
}, [check]);
}
}
@@ -3,6 +3,7 @@ import Row from "@moduletrace/twui/layout/Row";
import Span from "@moduletrace/twui/layout/Span";
import Stack from "@moduletrace/twui/layout/Stack";
import { AppWindow, Check } from "lucide-react";
import { twMerge } from "tailwind-merge";
import type { BUN_SQLITE_COBBLE_COMPUTERS } from "@/db/types/db";
type Props = {
@@ -11,6 +12,11 @@ type Props = {
* The computer the bot is on.
*/
current: boolean;
/**
* Whether picking another one moves the bot; without it the list is read
* alone.
*/
can_pick?: boolean;
onPick: () => void;
/**
* Opens the computer in the viewer.
@@ -22,27 +28,38 @@ type Props = {
* One computer in the header's computers modal, checked when it's the
* one the bot is on, with a button that opens it.
*/
export default function BotComputerOption({ computer, current, onPick, onOpen }: Props) {
export default function BotComputerOption({
computer,
current,
can_pick = true,
onPick,
onOpen,
}: Props) {
const name = computer.name || `Computer ${computer.id}`;
return (
<Row className="w-full gap-1! flex-nowrap items-center pr-2 hover:bg-sunken transition-colors duration-[var(--m-fast)]">
<Row
role="radio"
aria-checked={current}
tabIndex={0}
onClick={current ? undefined : onPick}
role={can_pick ? "radio" : undefined}
aria-checked={can_pick ? current : undefined}
tabIndex={can_pick ? 0 : undefined}
onClick={can_pick && !current ? onPick : undefined}
onKeyDown={(e) => {
if (!current && (e.key == "Enter" || e.key == " ")) {
if (can_pick && !current && (e.key == "Enter" || e.key == " ")) {
e.preventDefault();
onPick();
}
}}
className={`grow min-w-0 min-h-9 gap-2.5! flex-nowrap items-center px-4 py-1.5 text-ink focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ink ${
current ? "cursor-default" : "cursor-pointer"
}`}
className={twMerge(
"grow min-w-0 min-h-9 gap-2.5! flex-nowrap items-center px-4 py-1.5 text-ink cursor-default focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ink",
can_pick && !current && "cursor-pointer"
)}
>
<Check size={16} aria-hidden className={`shrink-0 ${current ? "" : "invisible"}`} />
<Check
size={16}
aria-hidden
className={twMerge("shrink-0", !current && "invisible")}
/>
<Stack className="min-w-0 gap-0!">
<Span className="text-sm leading-5 text-ink truncate w-full">
{name}
@@ -25,8 +25,9 @@ type RenderProps = {
};
/**
* The name is the header's heading either way; only a crew manager's is a
* button that opens the bot's panel.
* The name is the header's heading either way, and a button that opens the
* bot's panel for everyone who reaches it, labelled by what they may do
* there.
*/
function render({ user_type, name = "Assistant" }: RenderProps) {
const pageProps: PagePropsType = {
@@ -42,13 +43,14 @@ function render({ user_type, name = "Assistant" }: RenderProps) {
}
describe("BotPanelName", () => {
test("a member reads the name as a plain heading", () => {
test("a member's name opens the panel too, to read", () => {
const html = render({ user_type: "member" });
expect(html).toContain("<h1");
expect(html).toContain(">Assistant<");
expect(html).not.toContain("<button");
expect(html).not.toContain('aria-haspopup="dialog"');
expect(html).toContain("<button");
expect(html).toContain('aria-haspopup="dialog"');
expect(html).toContain('aria-label="About Assistant"');
});
test("a crew manager's name is a button that opens the panel", () => {
@@ -14,27 +14,20 @@ type Props = {
};
/**
* The conversation's name: the page's heading, and for super admins and
* admins a second way into the bot's panel, beside its avatar. Everyone else
* reads the name alone.
* The conversation's name: the page's heading, and a second way into the
* bot's panel beside its avatar, for everyone who can reach it.
*/
export default function BotPanelName({ bot, on_open }: Props) {
const { pageProps } = useContext(AppContext);
const name = bot.name || "This bot";
const can_edit = canManageCrew({ user_types: pageProps?.user_types });
if (!can_edit) {
return (
<H1 className="min-w-0 text-lg! leading-6! tracking-normal! font-bold text-ink truncate line-clamp-1">
{bot.name}
</H1>
);
}
const label = canManageCrew({ user_types: pageProps?.user_types })
? `Edit ${name}`
: `About ${name}`;
return (
<H1 className="min-w-0 text-lg! leading-6! tracking-normal! font-bold text-ink">
<Button
title={`Edit ${name}`}
title={label}
type="button"
variant="ghost"
color="text"
@@ -25,8 +25,9 @@ type RenderProps = {
};
/**
* The stone is the same either way; only a crew manager's opens the bot's
* panel, whether it sits in the header or beside a message.
* The stone is the same either way; it opens the bot's panel for everyone
* who reaches the bot, labelled by what they may do there, whether it sits in
* the header or beside a message.
*/
function render({ user_type, name = "Assistant" }: RenderProps) {
const pageProps: PagePropsType = {
@@ -42,12 +43,13 @@ function render({ user_type, name = "Assistant" }: RenderProps) {
}
describe("BotPanelTrigger", () => {
test("a member sees the stone alone", () => {
test("a member's stone opens the panel too, to read", () => {
const html = render({ user_type: "member" });
expect(html).toContain("<svg");
expect(html).not.toContain("<button");
expect(html).not.toContain('aria-haspopup="dialog"');
expect(html).toContain("<button");
expect(html).toContain('aria-haspopup="dialog"');
expect(html).toContain('aria-label="About Assistant"');
});
test("a crew manager's stone is a button that opens the panel", () => {
@@ -2,7 +2,6 @@
import { useContext } from "react";
import Button from "@moduletrace/twui/layout/Button";
import Stack from "@moduletrace/twui/layout/Stack";
import { twMerge } from "tailwind-merge";
import BotAvatar from "@/src/components/general/bot-avatar";
import type { BotFace } from "@/src/dict/bot-dict";
@@ -27,9 +26,10 @@ type Props = {
};
/**
* The bot's stone: opens the bot's panel to edit it, for super admins and
* admins. Everyone else sees the stone alone. It sits in the header beside
* the conversation's name and beside the bot's messages in the thread.
* The bot's stone: opens the bot's panel, which super admins and admins edit
* and everyone else reads (their own memory there is theirs to rewrite). It
* sits in the header beside the conversation's name and beside the bot's
* messages in the thread.
*/
export default function BotPanelTrigger({
bot,
@@ -39,28 +39,17 @@ export default function BotPanelTrigger({
}: Props) {
const { pageProps } = useContext(AppContext);
const name = bot.name || "This bot";
const can_edit = canManageCrew({ user_types: pageProps?.user_types });
const avatar = (
<BotAvatar
image_media_id={bot.image_media_id}
{...botStoneProps({ color: bot.color, stone: bot.stone, hue: bot.hue })}
face={(bot.face || "idle") as BotFace}
size={size}
/>
);
if (!can_edit) {
return <Stack className={twMerge("shrink-0", className)}>{avatar}</Stack>;
}
const label = canManageCrew({ user_types: pageProps?.user_types })
? `Edit ${name}`
: `About ${name}`;
return (
<Button
title={`Edit ${name}`}
title={label}
type="button"
variant="ghost"
color="text"
aria-label={`Edit ${name}`}
aria-label={label}
aria-haspopup="dialog"
onClick={on_open}
className={twMerge(
@@ -68,7 +57,16 @@ export default function BotPanelTrigger({
className,
)}
>
{avatar}
<BotAvatar
image_media_id={bot.image_media_id}
{...botStoneProps({
color: bot.color,
stone: bot.stone,
hue: bot.hue,
})}
face={(bot.face || "idle") as BotFace}
size={size}
/>
</Button>
);
}
@@ -22,9 +22,14 @@ const pageProps: PagePropsType = {
user_types: [{ user_type: "super_admin" }] as PagePropsType["user_types"],
};
function render() {
const memberPageProps: PagePropsType = {
...pageProps,
user_types: [{ user_type: "member" }] as PagePropsType["user_types"],
};
function render(props: PagePropsType = pageProps) {
return renderToString(
<AppContext.Provider value={{ pageProps } as AppContextObject}>
<AppContext.Provider value={{ pageProps: props } as AppContextObject}>
<BotPanel
bot={bot}
open={false}
@@ -48,4 +53,17 @@ describe("BotPanel", () => {
expect(html).toContain(">Tools<");
expect(html).not.toContain(">Memory<");
});
/**
* A member reads the bot and rewrites what it remembers about them, so
* the stone still opens the panel, under a title that doesn't promise
* edits they can't make.
*/
test("a member reads it, without the edit it alone can't make", () => {
const html = render(memberPageProps);
expect(html.match(/role="tab"/g)?.length).toBe(2);
expect(html).toContain(`aria-label="About Assistant"`);
expect(html).not.toContain("Edit Assistant");
});
});
@@ -20,11 +20,13 @@ import type { BUN_SQLITE_COBBLE_WORKSPACES } from "@/db/types/db";
import BotForm from "@/src/layouts/bots/(partials)/bot-form";
import { AppContext } from "@/src/pages/__root";
import canManageCrew from "@/src/utils/rbac/can-manage-crew";
import isReadOnlyUser from "@/src/utils/rbac/is-read-only-user";
import useTopModalEscape from "@/src/hooks/use-top-modal-escape";
import useBotInstructions from "../(hooks)/use-bot-instructions";
import useWorkspaceBotInstructions from "../(hooks)/use-workspace-bot-instructions";
import BotMemoryForm from "./bot-memory-form";
import BotPanelTrigger from "./bot-panel-trigger";
import BotReadOnlyBlock from "./bot-read-only-block";
import BotToolsTab from "./bot-tools-tab";
import BotUserMemory from "./bot-user-memory";
@@ -47,12 +49,13 @@ type PanelTab = "settings" | "tools";
/**
* The bot's profile (picture, name, job, colour, instructions), what it keeps
* in mind and what it works with (computer, tools, knowledgebases) to edit,
* sliding in from the right over the conversation, for super admins and
* admins. The avatar and the name beside it open it, and so does a swipe from
* the right on a phone (`BotPanelOpenEvent`, sent by the layout, so a page
* without a conversation has nobody listening). The tab's data loads when it
* opens, and Escape, the backdrop or the X closes it.
* in mind and what it works with (computer, tools, knowledgebases), sliding in
* from the right over the conversation. Super admins and admins edit it; every
* other user reads its job and instructions and rewrites what it remembers
* about them. The avatar and the name beside it open it, and so does a swipe
* from the right on a phone (`BotPanelOpenEvent`, sent by the layout, so a
* page without a conversation has nobody listening). The tab's data loads when
* it opens, and Escape, the backdrop or the X closes it.
*/
export default function BotPanel({
bot,
@@ -64,16 +67,18 @@ export default function BotPanel({
const { pageProps } = useContext(AppContext);
const name = bot.name || "This bot";
const can_edit = canManageCrew({ user_types: pageProps?.user_types });
const may_write = !isReadOnlyUser({ user_types: pageProps?.user_types });
const title = can_edit ? `Edit ${name}` : `About ${name}`;
const [tab, setTab] = useState<PanelTab>("settings");
const workspace_id = Number(workspace?.id) || 0;
const { system_prompt, memory, user_memory, error } = useBotInstructions({
bot_id: Number(bot.id) || 0,
enabled: open && can_edit,
enabled: open,
});
const workspace_instructions = useWorkspaceBotInstructions({
workspace_id,
bot_id: Number(bot.id) || 0,
enabled: open && can_edit && Boolean(workspace_id) && tab == "settings",
enabled: open && Boolean(workspace_id) && tab == "settings",
});
const memory_ready =
system_prompt != undefined &&
@@ -85,22 +90,11 @@ export default function BotPanel({
useTopModalEscape({ onClose: on_close, enabled: open });
useEffect(() => {
if (!can_edit) return;
const openPanel = () => on_open();
window.addEventListener(BotPanelOpenEvent, openPanel);
return () => window.removeEventListener(BotPanelOpenEvent, openPanel);
}, [can_edit, on_open]);
/**
* A swipe from the right is a request for the panel, but a bot that
* cannot be edited keeps the avatar plain: a slide-over holding nothing
* would be worse than nothing happening.
*/
if (!can_edit) {
return <BotPanelTrigger bot={bot} on_open={() => {}} />;
}
}, [on_open]);
return (
<>
@@ -109,7 +103,7 @@ export default function BotPanel({
side="right"
open={open}
onClose={on_close}
label={`Edit ${name}`}
label={title}
>
<Row className="shrink-0 gap-3! flex-nowrap items-center px-4 py-3 border-0 border-b border-solid border-hairline">
<Stack className="shrink-0">
@@ -125,7 +119,7 @@ export default function BotPanel({
/>
</Stack>
<H2 className="min-w-0 grow text-lg! leading-6! tracking-normal! font-bold text-ink truncate">
{`Edit ${name}`}
{title}
</H2>
<Button
title="Close"
@@ -141,7 +135,7 @@ export default function BotPanel({
</Row>
<Row
role="tablist"
aria-label={`Edit ${name}`}
aria-label={title}
className="shrink-0 gap-1! flex-nowrap items-center px-3 py-2 border-0 border-b border-solid border-hairline"
>
<TabButton
@@ -157,65 +151,128 @@ export default function BotPanel({
</Row>
<Stack className="grow min-h-0 overflow-y-auto gap-4! items-stretch px-4 pt-4 pb-6 [&>*]:shrink-0">
{open && tab == "settings" ? (
<>
<Span className="text-[13px] leading-[18px] text-ink-secondary">
{bot.kind == "coordinator"
? "The coordinator keeps its name. Give it a picture, or change its core instructions."
: `${name}'s core instructions apply everywhere. What it does in one workspace is under Instructions here in the menu of its conversation there.`}
</Span>
{system_prompt != undefined ? (
<>
<BotForm
bot={{ ...bot, system_prompt }}
onCancel={on_close}
/>
<Divider className="my-2 border-hairline dark:border-hairline" />
<Span className="text-[13px] leading-[18px] text-ink-secondary">
{`What ${name} keeps in mind, and can add to itself as it works.`}
</Span>
{memory_ready ? (
<>
<BotMemoryForm
bot_id={Number(bot.id) || 0}
bot_name={name}
memory={memory || ""}
workspace_id={
workspace_id || undefined
}
workspace_name={workspace?.name}
workspace_memory={
workspace_instructions
.instructions?.memory ||
""
}
onCancel={on_close}
/>
<Divider className="my-2 border-hairline dark:border-hairline" />
<BotUserMemory
bot_name={name}
memory={user_memory || ""}
/>
</>
) : loaded_error ? (
<Span className="py-6 text-[13px] leading-[18px] text-ink-secondary">
{loaded_error}
</Span>
) : (
<Stack className="w-full py-10 items-center">
<Loading />
</Stack>
)}
</>
) : error ? (
<Span className="py-6 text-[13px] leading-[18px] text-ink-secondary">
{error}
can_edit ? (
<>
<Span className="text-[13px] leading-[18px] text-ink-secondary">
{bot.kind == "coordinator"
? "The coordinator keeps its name. Give it a picture, or change its core instructions."
: `${name}'s core instructions apply everywhere. What it does in one workspace is under Instructions here in the menu of its conversation there.`}
</Span>
) : (
<Stack className="w-full py-10 items-center">
<Loading />
</Stack>
)}
</>
{system_prompt != undefined ? (
<>
<BotForm
bot={{ ...bot, system_prompt }}
onCancel={on_close}
/>
<Divider className="my-2 border-hairline dark:border-hairline" />
<Span className="text-[13px] leading-[18px] text-ink-secondary">
{`What ${name} keeps in mind, and can add to itself as it works.`}
</Span>
{memory_ready ? (
<>
<BotMemoryForm
bot_id={Number(bot.id) || 0}
bot_name={name}
memory={memory || ""}
workspace_id={
workspace_id || undefined
}
workspace_name={
workspace?.name
}
workspace_memory={
workspace_instructions
.instructions
?.memory || ""
}
onCancel={on_close}
/>
<Divider className="my-2 border-hairline dark:border-hairline" />
<BotUserMemory
bot_id={Number(bot.id) || 0}
bot_name={name}
memory={user_memory || ""}
can_edit={may_write}
onCancel={on_close}
/>
</>
) : loaded_error ? (
<Span className="py-6 text-[13px] leading-[18px] text-ink-secondary">
{loaded_error}
</Span>
) : (
<Stack className="w-full py-10 items-center">
<Loading />
</Stack>
)}
</>
) : error ? (
<Span className="py-6 text-[13px] leading-[18px] text-ink-secondary">
{error}
</Span>
) : (
<Stack className="w-full py-10 items-center">
<Loading />
</Stack>
)}
</>
) : (
<>
<Span className="text-[13px] leading-[18px] text-ink-secondary">
{`What ${name} is for, the instructions it follows and what it remembers.`}
</Span>
{bot.role ? (
<Span className="text-[13px] leading-[18px] text-ink">
{bot.role}
</Span>
) : null}
{memory_ready ? (
<>
<BotReadOnlyBlock
title="Instructions"
content={system_prompt || ""}
className="h-52"
/>
<Divider className="my-2 border-hairline dark:border-hairline" />
<BotReadOnlyBlock
title="Memory"
content={memory || ""}
className="h-52"
/>
{workspace_id ? (
<>
<Divider className="my-2 border-hairline dark:border-hairline" />
<BotReadOnlyBlock
title={`Memory in ${workspace?.name || "this workspace"}`}
content={
workspace_instructions
.instructions
?.memory || ""
}
className="h-40"
/>
</>
) : null}
<Divider className="my-2 border-hairline dark:border-hairline" />
<BotUserMemory
bot_id={Number(bot.id) || 0}
bot_name={name}
memory={user_memory || ""}
can_edit={may_write}
onCancel={on_close}
/>
</>
) : loaded_error ? (
<Span className="py-6 text-[13px] leading-[18px] text-ink-secondary">
{loaded_error}
</Span>
) : (
<Stack className="w-full py-10 items-center">
<Loading />
</Stack>
)}
</>
)
) : null}
{open && tab == "tools" ? (
<BotToolsTab
@@ -223,6 +280,9 @@ export default function BotPanel({
workspace_id={workspace_id || null}
initial={pageProps?.bot_extensions}
has_browsers={Boolean(pageProps?.has_browsers)}
can_switch_computer={
may_write && (!workspace_id || can_edit)
}
open={open && tab == "tools"}
/>
) : null}
@@ -0,0 +1,25 @@
import CodeEditor from "@/src/components/general/code-editor";
type BotReadOnlyBlockProps = {
title: string;
content: string;
className?: string;
};
/** A block of a bot's own text its panel shows a user read-only. */
export default function BotReadOnlyBlock({
title,
content,
className,
}: BotReadOnlyBlockProps) {
return (
<CodeEditor
title={title}
content={content || "Nothing yet."}
mode="markdown"
className={className}
readOnly
onChange={() => {}}
/>
);
}
@@ -24,6 +24,12 @@ type Props = {
* nothing to pick.
*/
has_browsers?: boolean;
/**
* Whether the viewer may move the bot to another of its computers. Any
* user who reaches it can, except a workspace's default computer, which
* is the crew's.
*/
can_switch_computer?: boolean;
/**
* Whether the tab is on show, so its connectors are read then and its
* computer switches show.
@@ -32,16 +38,18 @@ type Props = {
};
/**
* The bot panel's third tab: where it works and what it can use there - its
* The bot panel's tools tab: where it works and what it can use there - its
* computer, the MCP servers, tools and skills it was given (the apps its
* connectors reach for you among them), its knowledgebases, and which of
* your browsers it acts as you in.
* your browsers it acts as you in. Read-only for a user who cannot manage the
* crew: the lists show, adding and removing them does not.
*/
export default function BotToolsTab({
bot,
workspace_id,
initial,
has_browsers,
can_switch_computer = false,
open,
}: Props) {
const bot_name = bot.name || "this bot";
@@ -82,8 +90,12 @@ export default function BotToolsTab({
>
{computers.length ? (
<Stack
role="radiogroup"
aria-label={`${bot_name}'s computers`}
role={can_switch_computer ? "radiogroup" : undefined}
aria-label={
can_switch_computer
? `${bot_name}'s computers`
: undefined
}
className="w-full mt-2 py-1 gap-0! items-stretch rounded-default border border-solid border-hairline bg-surface"
>
{computers.map((computer, index) => (
@@ -91,6 +103,7 @@ export default function BotToolsTab({
key={computer.id}
computer={computer}
current={index == 0}
can_pick={can_switch_computer}
onPick={async () => {
await switchComputer({
computer_id: computer.id || 0,
@@ -1,34 +1,109 @@
import { useState } from "react";
import Form from "@moduletrace/twui/form/Form";
import Span from "@moduletrace/twui/layout/Span";
import CodeEditor from "@/src/components/general/code-editor";
import postAdminApi from "@/src/layouts/bots/(functions)/post-admin-api";
import AddFormActions from "@/src/layouts/bots/(partials)/add-form-actions";
import BotReadOnlyBlock from "./bot-read-only-block";
type Props = {
bot_id: number;
bot_name: string;
/**
* What the bot has saved about the user reading the panel; empty until
* it saved anything.
*/
memory: string;
/**
* A read-only user reads it alone; their own memory needs no admin.
*/
can_edit?: boolean;
onCancel?: () => void;
};
/**
* What the bot remembers about this user alone (`bot_user_memories`), shown
* in its panel's settings tab. It shapes how the bot works with them, never
* what it does, and only the bot writes it.
* in its panel: the bot writes it as it works, and the user rewrites it here.
* It shapes how the bot works with them, never what it does.
*/
export default function BotUserMemory({ bot_name, memory }: Props) {
export default function BotUserMemory({
bot_id,
bot_name,
memory,
can_edit,
onCancel,
}: Props) {
const [text, setText] = useState(memory);
const [loading, setLoading] = useState(false);
const [saved, setSaved] = useState(false);
const [error, setError] = useState<string>();
const submit = async () => {
if (loading) return;
setLoading(true);
setError(undefined);
setSaved(false);
try {
const res = await postAdminApi({
path: "bots/update-user-memory",
body: { bot_id, memory: text },
});
if (res.success) {
setSaved(true);
} else {
setError(res.msg || "Couldn't save its memory.");
}
} catch {
setError("Couldn't save its memory.");
} finally {
setLoading(false);
}
};
const description = `What ${bot_name} remembers about you, which only shapes how it works with you.`;
if (!can_edit) {
return (
<>
<Span className="text-[13px] leading-[18px] text-ink-secondary">
{description}
</Span>
<BotReadOnlyBlock
title="About you"
content={memory}
className="h-32"
/>
</>
);
}
return (
<>
<Form onSubmit={submit} className="w-full gap-4! items-stretch">
<Span className="text-[13px] leading-[18px] text-ink-secondary">
{`What ${bot_name} remembers about you, which only shapes how it works with you.`}
{description}
</Span>
<CodeEditor
title="About you"
content={memory || "Nothing yet."}
content={memory}
mode="markdown"
placeholder="What it should keep in mind about you..."
info="Markdown, replaced whole. Only this bot, and only when it works with you."
className="h-32"
readOnly
onChange={() => {}}
onChange={(value) => {
setText(value);
setSaved(false);
}}
/>
</>
<AddFormActions
submit_label="Save"
loading={loading}
error={error}
notice={saved ? "Saved." : undefined}
onCancel={onCancel}
/>
</Form>
);
}
}
@@ -0,0 +1,35 @@
import Stack from "@moduletrace/twui/layout/Stack";
import type { ComposerCommand } from "../(data)/composer-commands";
import ComposerCommandOption from "./composer-command-option";
type Props = {
commands: ComposerCommand[];
index: number;
onPick: (command: ComposerCommand) => void;
};
/**
* The slash commands matching what's typed, just above the composer's
* input. Up and Down move, Enter runs the highlighted one; a click fills
* the input with it.
*/
export default function ComposerCommandList({ commands, index, onPick }: Props) {
return (
<Stack
role="listbox"
aria-label="Commands"
className="w-full max-w-container mx-auto gap-0.5! items-stretch px-3 md:px-6 pt-3"
>
<Stack className="gap-0.5! items-stretch p-1 rounded-default border border-solid border-hairline bg-surface shadow-popover">
{commands.map((command, command_index) => (
<ComposerCommandOption
key={command.name}
command={command}
active={command_index == index}
onPick={onPick}
/>
))}
</Stack>
</Stack>
);
}
@@ -0,0 +1,37 @@
import Button from "@moduletrace/twui/layout/Button";
import Span from "@moduletrace/twui/layout/Span";
import { twMerge } from "tailwind-merge";
import type { ComposerCommand } from "../(data)/composer-commands";
type Props = {
command: ComposerCommand;
active: boolean;
onPick: (command: ComposerCommand) => void;
};
/**
* One slash command in the composer's command list, with what it does.
*/
export default function ComposerCommandOption({ command, active, onPick }: Props) {
return (
<Button
type="button"
variant="ghost"
color="text"
role="option"
aria-selected={active}
title={`/${command.name}`}
onMouseDown={(e) => {
e.preventDefault();
onPick(command);
}}
className={twMerge(
"w-full justify-start! gap-2.5! px-2! py-1.5! rounded-default-sm text-left text-ink",
active && "bg-sunken",
)}
>
<Span className="shrink-0 text-sm font-bold leading-5">{`/${command.name}`}</Span>
<Span className="min-w-0 truncate text-xs leading-4 text-ink-secondary">{command.description}</Span>
</Button>
);
}
@@ -15,8 +15,10 @@ import type {
BotVoicePayload,
BotWithLastMessage,
} from "@/src/types";
import type { ComposerCommand } from "../(data)/composer-commands";
import { CrewBotsContext } from "../(data)/crew-bots-context";
import { CrewWorkspacesContext } from "../(data)/crew-workspaces-context";
import postSessionApi from "@/src/functions/frontend/post-session-api";
import sendBotMessage from "../(functions)/send-bot-message";
import transcribeVoice from "../(functions)/transcribe-voice";
import useComposerAttachments from "../(hooks)/use-composer-attachments";
@@ -27,10 +29,15 @@ import useVoiceRecorder from "../(hooks)/use-voice-recorder";
import useOnlineStatus from "@/src/hooks/use-online-status";
import { AppData } from "@/src/data/app-data";
import messageTooLongMessage from "@/src/utils/message-too-long-message";
import conversationHref from "@/src/utils/conversation-href";
import composerHistoryTexts from "../(utils)/composer-history-texts";
import composerDraftKey from "../(utils)/composer-draft-key";
import composerCommandMatches from "../(utils)/composer-command-matches";
import loadedBuildId from "../(utils)/loaded-build";
import ComposerAttachButton from "./composer-attach-button";
import ComposerAttachments from "./composer-attachments";
import ComposerClearButton from "./composer-clear-button";
import ComposerCommandList from "./composer-command-list";
import ComposerEditor from "./composer-editor";
import ComposerMentionList from "./composer-mention-list";
import ComposerNotice from "./composer-notice";
@@ -155,6 +162,13 @@ export default function Composer({
const bots = useContext(CrewBotsContext);
const workspaces = useContext(CrewWorkspacesContext);
const send_ref = useRef<() => void>(() => {});
/**
* The slash commands the text is asking for, the one highlighted, and
* a command still on its way (`/continue` writes a summary).
*/
const commands = composerCommandMatches({ text });
const [command_index, set_command_index] = useState(0);
const [command_busy, set_command_busy] = useState(false);
/**
* Temporary ids for messages the server doesn't have yet, and the text
@@ -190,10 +204,37 @@ export default function Composer({
},
onSubmit: () => send_ref.current(),
onFiles: files.add,
onHistory: (params) => walk_history.current(params),
onHistory: (params) => {
/**
* An open command list keeps the arrows: they walk it when
* there's more than one, rather than the user's earlier
* messages.
*/
if (commands.length) {
if (commands.length > 1) {
moveCommand({ direction: params.direction });
}
return true;
}
return walk_history.current(params);
},
});
const editor = input.editor;
function moveCommand({ direction }: { direction: "up" | "down" }) {
const count = commands.length;
const step = direction == "down" ? 1 : -1;
set_command_index((index) => (index + step + count) % count);
}
/**
* Typing or deleting moves the highlight back to the first command.
*/
useEffect(() => set_command_index(0), [text]);
walk_history.current = ({ direction, empty }) => {
const next = history.step({
direction,
@@ -289,6 +330,31 @@ export default function Composer({
files.restore({ attachments });
};
/**
* The page is a build older than the server's: what was being sent goes
* into the draft synchronously (the hooks' own writes are debounced and
* may never run before the reload) and the page reloads into the
* running build, which picks the draft up.
*/
const keepForReload = ({
lost_text,
attachments,
}: {
lost_text: string;
attachments: BotMessageAttachment[];
}) => {
const keep_text = latest_text.current.trim() ? latest_text.current : lost_text;
const text_key = composerDraftKey({ bot_id: bot.id, workspace_id, part: "text" });
const files_key = composerDraftKey({ bot_id: bot.id, workspace_id, part: "files" });
try {
localStorage.setItem(text_key, keep_text);
if (attachments.length) localStorage.setItem(files_key, JSON.stringify(attachments));
else localStorage.removeItem(files_key);
} catch {}
};
/**
* Empties the input's text, without sending it: what was typed is
* dropped, the quote and the picked files stay.
@@ -300,6 +366,84 @@ export default function Composer({
editor?.commands.focus();
}
/**
* A picked command goes into the input rather than running from the
* click, so what it does is read before Enter runs it.
*/
function pickCommand(command: ComposerCommand) {
const command_text = `/${command.name}`;
setText(command_text);
history.reset();
input.setMarkdown({ markdown: command_text });
editor?.commands.focus("end");
}
/**
* `/new`, `/continue` and `/clear` act on the conversation's session
* rather than being sent, and the page lands on the session they
* leave. `/clear` destroys messages, so it asks first. A failure puts
* the command back in the input with the reason under it (a session
* with a run in progress can't be deleted).
*/
async function runCommand({ command }: { command: ComposerCommand }) {
if (sending.current) return;
if (command.name == "clear") {
if (!session_id) {
setError("The session is still loading. Try again in a moment.");
return;
}
if (
!window.confirm(
"Delete this session and all its messages, then start a new one? This can't be undone.",
)
) {
return;
}
}
sending.current = true;
set_command_busy(true);
setError(undefined);
const lost_text = text.trim();
setText("");
history.reset();
input.clear();
const res = await postSessionApi({
path:
command.name == "new"
? "new-session"
: command.name == "continue"
? "continue-session"
: "delete-session",
body:
command.name == "clear"
? { session_id }
: { bot_id: bot.id, workspace_id },
}).catch(() => null);
if (res?.success) {
window.location.assign(
conversationHref({ bot_id: Number(bot.id), workspace_id }),
);
return;
}
sending.current = false;
set_command_busy(false);
setError(res?.msg || "That didn't work.");
if (!latest_text.current.trim()) {
setText(lost_text);
input.setMarkdown({ markdown: lost_text });
}
}
/**
* The bubble and the bot's "getting your message" row show at once, and
* the input empties, so a slow connection never holds any of it. The
@@ -308,6 +452,13 @@ export default function Composer({
async function send() {
if (!can_send || !bot.id || sending.current) return;
const command = commands[command_index] ?? commands[0];
if (command) {
await runCommand({ command });
return;
}
/**
* Held until this send comes back: a second click while the first is
* still on its way (a double tap, Enter twice, a phone that fires
@@ -392,8 +543,20 @@ export default function Composer({
session_id: session_id || null,
client_id: request_id,
plan_mode,
build_id: loadedBuildId(),
});
/**
* A deploy replaced the build while this page was open: reload
* into it rather than writing from code the server no longer
* serves.
*/
if (res.error == "stale_build") {
keepForReload({ lost_text: text_sent, attachments });
window.location.reload();
return;
}
if (!res.success || !res.singleRes) {
setError(res.msg || "Message not sent");
restore({ lost_text: text_sent, attachments });
@@ -441,6 +604,13 @@ export default function Composer({
onCancel={onCancelReply}
/>
) : null}
{commands.length ? (
<ComposerCommandList
commands={commands}
index={command_index}
onPick={pickCommand}
/>
) : null}
{input.menu ? <ComposerMentionList menu={input.menu} /> : null}
<Row
className={`w-full max-w-container mx-auto min-h-[88px] ${reply_to ? "pt-3 pb-7" : "py-7"} gap-3! md:gap-4! flex-nowrap items-end px-3 md:px-6 cursor-text`}
@@ -482,7 +652,7 @@ export default function Composer({
) : null}
<ComposerSendButton
disabled={!can_send}
loading={files.uploading}
loading={files.uploading || command_busy}
onClick={send}
/>
</Row>
@@ -46,6 +46,11 @@ type Props = {
* thinking row that will never move.
*/
awaiting_reply?: boolean;
/**
* The session shown was carried into a newer one: its thread is a record
* to read, so a last word of the user's isn't a reply that never came.
*/
moved_on?: boolean;
/**
* This session has an active task.
*/
@@ -102,7 +107,10 @@ type Props = {
loading: boolean;
error?: string;
loadOlder: () => void;
loadPrevious?: () => void;
/**
* The session this one carries on from, as the page that reads it.
*/
previous_session_href?: string | null;
};
};
@@ -112,9 +120,9 @@ type Props = {
* While the bot works on a reply or a task, a status row sits under the
* last one, and each request the bot has open with the crew shows where
* its bots stand until it's done. Text selected in a message can be quoted in the composer.
* Older messages load as it scrolls to the top, and at the start of a
* session that carries on from another, the earlier one can be opened
* above it (shown only, never put in the bot's prompt); the reversed column keeps
* Older messages load as it scrolls to the top, and the session before
* this one is linked above the thread as its own page (shown only, never
* put in the bot's prompt); the reversed column keeps
* the view where it was as they land above it. The thread follows new
* messages while it sits at its bottom, stays put while it's scrolled up
* and then offers a button to get back down. Pulled up past its bottom on
@@ -127,6 +135,7 @@ export default function MessageThread({
reply_progress,
receiving,
awaiting_reply,
moved_on,
session_id,
debug_open,
on_toggle_debug,
@@ -182,7 +191,9 @@ export default function MessageThread({
*/
const last_shown = shown[shown.length - 1];
const unanswered =
!awaiting_reply && !receiving && last_shown?.author == "user" ? last_shown : null;
!awaiting_reply && !receiving && !moved_on && last_shown?.author == "user"
? last_shown
: null;
const scroll = useThreadScroll({ messages: shown });
const pull_state = usePullToRefresh({
column_ref: scroll.column_ref,
@@ -215,13 +226,10 @@ export default function MessageThread({
error={older.error}
onLoad={older.loadOlder}
/>
) : older?.has_previous && older.loadPrevious ? (
) : older?.previous_session_href ? (
<OlderMessagesLoader
loading={older.loading}
error={older.error}
onLoad={older.loadPrevious}
href={older.previous_session_href}
label="Show the previous session"
manual
/>
) : null}
<SessionGalleryContext.Provider value={session_gallery}>
@@ -4,30 +4,31 @@ import Button from "@moduletrace/twui/layout/Button";
import Stack from "@moduletrace/twui/layout/Stack";
type Props = {
loading: boolean;
loading?: boolean;
error?: string;
onLoad: () => void;
onLoad?: () => void;
/**
* Opens a page instead of loading more here (the session before this
* one, read as it was).
*/
href?: string;
/**
* Defaults to "Show earlier messages".
*/
label?: string;
/**
* Loads only on a click, never as it scrolls into view.
*/
manual?: boolean;
};
/**
* The top of a thread with older messages: loads them as it scrolls into
* view (unless `manual`), with a button for when it can't (or a load
* failed).
* view, with a button for when it can't (or a load failed). With `href` it
* is only ever a link.
*/
export default function OlderMessagesLoader({
loading,
loading = false,
error,
onLoad,
href,
label = "Show earlier messages",
manual,
}: Props) {
const ref = useRef<HTMLDivElement>(null);
const load = useRef(onLoad);
@@ -37,11 +38,11 @@ export default function OlderMessagesLoader({
useEffect(() => {
const el = ref.current;
if (!el || error || manual || typeof IntersectionObserver == "undefined") return;
if (!el || href || error || typeof IntersectionObserver == "undefined") return;
const observer = new IntersectionObserver(
(entries) => {
if (entries.some((entry) => entry.isIntersecting)) load.current();
if (entries.some((entry) => entry.isIntersecting)) load.current?.();
},
{ rootMargin: "400px 0px 0px 0px" },
);
@@ -49,7 +50,7 @@ export default function OlderMessagesLoader({
observer.observe(el);
return () => observer.disconnect();
}, [error, loading, manual]);
}, [error, loading, href]);
return (
<Stack
@@ -64,6 +65,7 @@ export default function OlderMessagesLoader({
type="button"
variant="ghost"
color="text"
href={href}
onClick={onLoad}
className="text-[13px]! leading-[18px]! text-ink-secondary"
>
@@ -41,6 +41,7 @@ import useOlderMessages from "../(hooks)/use-older-messages";
import ConversationHeader from "../(partials)/conversation-header";
import useDebugOpen from "../(hooks)/use-debug-open";
import MessageThread from "../(partials)/message-thread";
import conversationHref from "@/src/utils/conversation-href";
import Composer, { type ComposerHandle } from "../(partials)/composer";
/**
* A computer's live screen (noVNC, its websocket and transport) is only
@@ -110,6 +111,14 @@ export default function Conversation() {
* session, which the composer gives way to a link to.
*/
const [moved_to_session_id, setMovedToSessionId] = useState<number | null>(null);
/**
* The page was opened on one session (`?session_id=`) rather than the
* live conversation: that's the way back into an old thread, so it
* stays there even when that session was carried on into a newer one.
*/
const pinned_session = useRef(
typeof window != "undefined" && new URLSearchParams(window.location.search).has("session_id"),
).current;
/**
* How many replies the session still has to come, as the last catch-up
* read found them, or null while that isn't known yet. A reply that ends
@@ -324,6 +333,14 @@ export default function Conversation() {
running: Boolean(progress.task_id) || Boolean(open_reply_jobs),
last_message_id: last_saved_id,
on_open_jobs: ({ open_jobs }) => setOpenReplyJobs(open_jobs),
/**
* A carry whose push the page missed: the live conversation goes to
* the session that answers, rather than waiting on this one for
* ever. A pinned read stays where it is, as the push path does.
*/
on_moved_to: () => {
if (!pinned_session) history.retry();
},
});
/**
@@ -403,15 +420,14 @@ export default function Conversation() {
) {
/**
* This session's conversation was carried into a new one,
* whose summary opens it. While the user's message is on
* its way, it was that message (the rollover at the
* session length): the thread follows into the new
* session. Otherwise (the bot, Continue in new session in
* another tab) the composer gives way to a link there.
* whose summary opens it. The live page follows it without
* a word (the bot's answer lands there, and a rollover's
* message on its way goes there too); a page opened on this
* session keeps its thread and offers the way on instead.
*/
if (Number(message.carried_from_session_id) == session_id) {
if (pending_messages.length) {
following_send.current = true;
if (pending_messages.length || !pinned_session) {
following_send.current = Boolean(pending_messages.length);
history.retry();
return;
}
@@ -568,6 +584,14 @@ export default function Conversation() {
* The thread, kept intact so the stop control can wrap it without
* reindenting every provider.
*/
const previous_session_href = older.previous_session_id
? conversationHref({
bot_id: Number(bot?.id) || 0,
workspace_id,
session_id: older.previous_session_id,
})
: null;
const thread = (
<CrewBotsContext.Provider value={bots}>
<CrewWorkspacesContext.Provider value={workspaces}>
@@ -610,6 +634,7 @@ export default function Conversation() {
reply_progress={reply_progress}
receiving={pending_messages.length > 0}
awaiting_reply={awaiting_reply}
moved_on={Boolean(moved_to_session_id)}
has_task={Boolean(progress.task_id)}
rerun_message_id={rerun_after_id}
session_id={session_id}
@@ -622,7 +647,7 @@ export default function Conversation() {
<NoModelNotice bot_name={live_bot.name || "This bot"} />
) : null
}
older={older}
older={{ ...older, previous_session_href }}
onReload={reload_conversation}
onQuote={({ text }) =>
composer.current?.insertQuote({ text })
@@ -0,0 +1,29 @@
import { describe, expect, test } from "bun:test";
import composerCommandMatches from "./composer-command-matches";
const names = ({ text }: { text: string }) =>
composerCommandMatches({ text }).map((command) => command.name);
describe("composerCommandMatches", () => {
test("a lone slash offers every command", () => {
expect(names({ text: "/" })).toEqual(["new", "continue", "clear"]);
});
test("narrows by the letters typed", () => {
expect(names({ text: "/c" })).toEqual(["continue", "clear"]);
expect(names({ text: "/ne" })).toEqual(["new"]);
expect(names({ text: "/new" })).toEqual(["new"]);
});
test("ignores the case and the space around it", () => {
expect(names({ text: " /NEW " })).toEqual(["new"]);
});
test("an ordinary message that starts with a slash matches none", () => {
expect(names({ text: "/etc/hosts is missing" })).toEqual([]);
expect(names({ text: "/news" })).toEqual([]);
expect(names({ text: "/new please" })).toEqual([]);
expect(names({ text: "message" })).toEqual([]);
expect(names({ text: "" })).toEqual([]);
});
});
@@ -0,0 +1,17 @@
import { ComposerCommands, type ComposerCommand } from "../(data)/composer-commands";
/**
* The slash commands the composer's text is asking for: all of them while
* it is just `/`, then those the letters typed so far begin. Anything else
* (`/etc/hosts`, a command followed by more words) is an ordinary message
* and matches none.
*/
export default function composerCommandMatches({ text }: { text: string }): ComposerCommand[] {
const match = /^\/([a-z]*)$/i.exec(text.trim());
if (!match) return [];
const typed = (match[1] ?? "").toLowerCase();
return ComposerCommands.filter((command) => command.name.startsWith(typed));
}
@@ -0,0 +1,19 @@
import { PwaBuildMetaName } from "@/src/data/pwa-data";
/**
* The build this document's code came from, read once as the bundle loads
* (the root renders it as a meta tag). Frozen for the life of the page: it
* always names the code actually running, never a newer build a later
* client-side navigation may learn about. Null in development, where
* nothing is precached and every load is the current code.
*/
const loaded_build =
typeof document == "undefined"
? null
: document
.querySelector(`meta[name="${PwaBuildMetaName}"]`)
?.getAttribute("content") || null;
export default function loadedBuildId(): string | null {
return loaded_build;
}
+6 -10
View File
@@ -4,7 +4,6 @@ import grabUserBot from "@/src/functions/backend/db/bots/grab-user-bot";
import { BotIdRequestSchema } from "@/src/schemas/bot-schema";
import AppError from "@/src/utils/app-error";
import parseWithSchema from "@/src/utils/parse-with-schema";
import canManageCrew from "@/src/utils/rbac/can-manage-crew";
import safeErrorMessage from "@/src/utils/safe-error-message";
import type {
APIResponseObject,
@@ -12,10 +11,11 @@ import type {
} from "@moduletrace/bunext/types";
/**
* A bot's core instructions and memory for its panel in the conversation,
* which loads them when it opens (page props leave them out), plus what it
* remembers about the user reading it. For super admins and admins; only the
* super admin reaches the coordinator.
* A bot's core instructions for its panel in the conversation, which loads
* them when it opens (page props leave them out), plus what it remembers about
* the user reading it. Any user who reaches the bot reads its instructions,
* its memory and their own (a member's panel shows the bot's as read-only);
* only the super admin reaches the coordinator.
*/
export const handler: BunextAPIRouteHandler<
APIResponseObject<{ system_prompt: string; memory: string; user_memory: string }>
@@ -25,16 +25,12 @@ export const handler: BunextAPIRouteHandler<
throw new AppError(`Method not allowed`);
}
const { user, user_types } = await userAuth({ req });
const { user } = await userAuth({ req });
if (!user?.logged_in_status || !user.id) {
return { success: false, msg: `Unauthorized`, logoutUser: true };
}
if (!canManageCrew({ user_types })) {
throw new AppError(`Only an admin can edit a bot.`);
}
const { bot_id } = parseWithSchema({ schema: BotIdRequestSchema, data: body });
const bot = await grabUserBot({ bot_id, user_id: user.id });
+21
View File
@@ -15,6 +15,8 @@ import enqueueBotReply from "@/src/functions/backend/db/bots-queue/enqueue-bot-r
import pushBotNotice from "@/src/bots-queue/push-bot-notice";
import wakeBotsQueue from "@/src/bots-queue/wake-bots-queue";
import { SendBotMessageRequestSchema } from "@/src/schemas/bot-schema";
import grabPrecacheManifest from "@/src/functions/server/pwa/grab-precache-manifest";
import isStaleClientBuild from "@/src/utils/is-stale-client-build";
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";
@@ -67,11 +69,30 @@ export const handler: BunextAPIRouteHandler<APIResponseObject> = async ({
session_id,
client_id,
plan_mode,
build_id,
} = parseWithSchema({
schema: SendBotMessageRequestSchema,
data: body,
});
/**
* The page's code is older than the build the server runs: nothing
* is stored or queued, and the composer reloads into the new build
* with what was typed kept.
*/
if (
isStaleClientBuild({
client_build: build_id,
server_build: grabPrecacheManifest()?.build_id,
})
) {
return {
success: false,
error: "stale_build",
msg: "A newer version is available. Reloading to it.",
};
}
const max_chars = await grabBotMessageMaxChars();
if (text.length > max_chars) {
@@ -5,6 +5,7 @@ import grabBotFace from "@/src/functions/backend/db/bots/grab-bot-face";
import grabActiveBotTask from "@/src/functions/backend/db/bots/grab-active-bot-task";
import grabSessionReplyStep from "@/src/functions/backend/db/bots-queue/grab-session-reply-step";
import grabSessionOpenReplies from "@/src/functions/backend/db/bots-queue/grab-session-open-replies";
import grabCarriedToSessionId from "@/src/functions/backend/db/bot-sessions/grab-carried-to-session-id";
import { AppData } from "@/src/data/app-data";
import { BotSessionIdRequestSchema } from "@/src/schemas/bot-schema";
import type { SessionMessagesResponse } from "@/src/types";
@@ -62,6 +63,7 @@ export const handler: BunextAPIRouteHandler<SessionMessagesResponse> = async ({
},
step: await grabSessionReplyStep({ session_id: session.id }),
open_jobs: await grabSessionOpenReplies({ session_id: session.id }),
moved_to_session_id: await grabCarriedToSessionId({ session_id: session.id, user_id: user.id }),
};
} catch (error: unknown) {
return { success: false, msg: safeErrorMessage({ error }) };
@@ -0,0 +1,52 @@
import userAuth from "@/src/functions/backend/auth/user-auth";
import updateBotUserMemory from "@/src/functions/backend/db/bots/update-bot-user-memory";
import logEvent, { grabRequestIP } from "@/src/functions/backend/logger";
import { UpdateBotMemoryRequestSchema } 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";
/**
* Replaces what a bot remembers about the user reading its panel ("About
* you"). The memory is their own, so any user who reaches the bot may rewrite
* it; its core memory and its memory of everyone else stay with admins.
*/
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 { bot_id, memory } = parseWithSchema({
schema: UpdateBotMemoryRequestSchema,
data: body,
});
await updateBotUserMemory({ user_id: user.id, bot_id, memory });
await logEvent({
title: "Bot memory about a user changed",
category: "system",
user_id: user.id,
plain_text: `User #${user.id} edited bot #${bot_id}'s memory about them.`,
metadata: { bot_id },
ip_address: grabRequestIP(req),
});
return { success: true, msg: `Saved.` };
} catch (error: unknown) {
return { success: false, msg: safeErrorMessage({ error }) };
}
};
@@ -14,8 +14,9 @@ import type {
/**
* A bot's instructions and memory for one workspace, for the editor in its
* conversation there, which loads them when it opens (page props leave
* them out). For super admins and admins; only the super admin reaches
* the coordinator.
* them out). Any user in the workspace reads its memory there (a member's
* panel shows it read-only); its instructions there stay with super admins
* and admins, and only the super admin reaches the coordinator.
*/
export const handler: BunextAPIRouteHandler<
APIResponseObject<WorkspaceBotInstructions>
@@ -31,9 +32,7 @@ export const handler: BunextAPIRouteHandler<
return { success: false, msg: `Unauthorized`, logoutUser: true };
}
if (!canManageCrew({ user_types })) {
throw new AppError(`Only an admin can do that.`);
}
const may_read_instructions = canManageCrew({ user_types });
const { workspace_id, bot_id } = parseWithSchema({ schema: WorkspaceBotRequestSchema, data: body });
const bot = (await grabWorkspaceBots({ user_id: user.id, workspace_id })).find(
@@ -47,7 +46,9 @@ export const handler: BunextAPIRouteHandler<
return {
success: true,
singleRes: {
system_prompt: bot.workspace_system_prompt || "",
system_prompt: may_read_instructions
? bot.workspace_system_prompt || ""
: "",
memory: bot.workspace_memory || "",
},
};
+6
View File
@@ -76,6 +76,12 @@ export const SendBotMessageRequestSchema = z.object({
* being posted a second time.
*/
client_id: z.string().trim().max(64).optional(),
/**
* The build the page was loaded from (`cobble-build`). A send from a
* page older than the running build is refused, so it reloads into the
* new one instead of writing from code the server no longer serves.
*/
build_id: z.string().trim().max(64).nullish(),
/**
* Plan mode: the reply plans and inspects, and changes nothing. For a
* user who clicked Plan in the composer or pressed Tab, the run's write
+2 -1
View File
@@ -564,7 +564,8 @@ footer .twui-anchor.active {
@apply text-xs!;
}
.conversation-user-bubble a {
/* Style the bubble's own links, not the pills: a ref chip keeps its colours. */
.conversation-user-bubble a:not([data-quote-inline] a) {
@apply text-blue-400 dark:text-blue-600;
}
+11
View File
@@ -763,6 +763,11 @@ export type SessionMessagesResponse = APIResponseObject<BotMessageWithAttachment
* which is what a run that ended without a message looks like.
*/
open_jobs?: number | null;
/**
* The session this one was carried into, when it was: the open
* conversation follows it, since the bot's answer lands there.
*/
moved_to_session_id?: number | null;
};
/**
@@ -3074,6 +3079,12 @@ export type PagePropsType = {
* (the General settings page).
*/
message_length?: MessageLengthOverview | null;
/**
* The build the page was rendered from (the `cobble-build` meta tag),
* null in development. A send from an older build is refused so the
* page reloads into the running one.
*/
build_id?: string | null;
/**
* The name the install goes by as an installed app (Settings >
* General, and the root's head tags). Empty when never named.
+22
View File
@@ -0,0 +1,22 @@
import { describe, expect, test } from "bun:test";
import isStaleClientBuild from "./is-stale-client-build";
describe("isStaleClientBuild", () => {
test("a page from another build is stale", () => {
expect(isStaleClientBuild({ client_build: "build-a", server_build: "build-b" })).toBe(
true,
);
});
test("the running build is current", () => {
expect(
isStaleClientBuild({ client_build: "build-a", server_build: "build-a" }),
).toBe(false);
});
test("a development server or an old client is never refused", () => {
expect(isStaleClientBuild({ client_build: null, server_build: "build-b" })).toBe(false);
expect(isStaleClientBuild({ client_build: "build-a", server_build: null })).toBe(false);
expect(isStaleClientBuild({})).toBe(false);
});
});
+24
View File
@@ -0,0 +1,24 @@
type Params = {
/**
* The build the page that sent the request was running (`build_id`,
* from its `cobble-build` meta tag).
*/
client_build?: string | null;
/**
* The build the server runs now. Null in development, where nothing is
* precached and every load is the current code.
*/
server_build?: string | null;
};
/**
* Whether a request comes from a page older than the running build. Build
* ids are opaque, so any difference means the page runs code the server no
* longer serves, and it has to reload into the new build. A request that
* carries no build id (development, an old client) is never refused.
*/
export default function isStaleClientBuild({ client_build, server_build }: Params): boolean {
if (!client_build || !server_build) return false;
return client_build != server_build;
}