From 60022d822019b920cd351b5f19d46aa253d55aa3 Mon Sep 17 00:00:00 2001 From: Benjamin Toby Date: Sun, 22 Nov 2026 16:49:44 +0100 Subject: [PATCH] Split the bot panel into Settings, Memory and Tools The drawer held only the bot's profile. Its memory and everything it works with now have tabs of their own, the last one sharing the composer's own list of tools and knowledgebases. - Memory: core memory, plus the workspace's memory for the bot when the conversation is in one. New `update-bot-memory` route; the workspace request's fields are optional so a memory-only save cannot blank the instructions there. - Tools: computer, tools/skills/MCPs with connectors and browsers, and knowledgebases. --- .../(functions)/fetch-bot-instructions.ts | 6 +- .../[bot_id]/(hooks)/use-bot-instructions.ts | 15 +- .../[bot_id]/(partials)/bot-memory-form.tsx | 124 +++++++++++++ .../[bot_id]/(partials)/bot-panel-section.tsx | 26 +++ .../bots/[bot_id]/(partials)/bot-panel.tsx | 127 +++++++++++--- .../[bot_id]/(partials)/bot-tools-tab.tsx | 163 ++++++++++++++++++ .../(partials)/composer-extensions-list.tsx | 103 +++++++++++ .../(partials)/composer-tools-modal.tsx | 54 ++---- .../(partials)/conversation-header.tsx | 1 + src/pages/api/admin/bots/bot-instructions.ts | 10 +- src/pages/api/admin/bots/update-bot-memory.ts | 60 +++++++ src/schemas/bot-schema.test.ts | 20 ++- src/schemas/bot-schema.ts | 13 ++ src/schemas/workspace-schema.test.ts | 11 ++ src/schemas/workspace-schema.ts | 8 +- 15 files changed, 656 insertions(+), 85 deletions(-) create mode 100644 src/pages/admin/bots/[bot_id]/(partials)/bot-memory-form.tsx create mode 100644 src/pages/admin/bots/[bot_id]/(partials)/bot-panel-section.tsx create mode 100644 src/pages/admin/bots/[bot_id]/(partials)/bot-tools-tab.tsx create mode 100644 src/pages/admin/bots/[bot_id]/(partials)/composer-extensions-list.tsx create mode 100644 src/pages/api/admin/bots/update-bot-memory.ts create mode 100644 src/schemas/workspace-schema.test.ts diff --git a/src/pages/admin/bots/[bot_id]/(functions)/fetch-bot-instructions.ts b/src/pages/admin/bots/[bot_id]/(functions)/fetch-bot-instructions.ts index 729d660c..1261da1b 100644 --- a/src/pages/admin/bots/[bot_id]/(functions)/fetch-bot-instructions.ts +++ b/src/pages/admin/bots/[bot_id]/(functions)/fetch-bot-instructions.ts @@ -3,11 +3,11 @@ import type { APIResponseObject } from "@moduletrace/bunext/types"; import type { BotIdRequest } from "@/src/schemas/bot-schema"; /** - * A bot's core instructions, for its edit form. + * A bot's core instructions and memory, for its panel. */ export default async function fetchBotInstructions({ bot_id }: BotIdRequest) { - return await fetchApi>( + return await fetchApi>( `/api/admin/bots/bot-instructions`, { method: "POST", body: { bot_id } }, ); -} +} \ No newline at end of file diff --git a/src/pages/admin/bots/[bot_id]/(hooks)/use-bot-instructions.ts b/src/pages/admin/bots/[bot_id]/(hooks)/use-bot-instructions.ts index c03cd585..68c6b799 100644 --- a/src/pages/admin/bots/[bot_id]/(hooks)/use-bot-instructions.ts +++ b/src/pages/admin/bots/[bot_id]/(hooks)/use-bot-instructions.ts @@ -4,23 +4,25 @@ import fetchBotInstructions from "../(functions)/fetch-bot-instructions"; type Params = { bot_id: number; /** - * Loads each time this turns true (the edit form opens), so the form - * starts from what was last saved. + * Loads each time this turns true (the panel opens), so its forms start + * from what was last saved. */ enabled: boolean; }; /** - * The bot's core instructions for its edit form, loaded when it opens: - * page props leave them out of every bot row. + * The bot's core instructions and memory for its panel, loaded when it + * opens: page props leave them out of every bot row. */ export default function useBotInstructions({ bot_id, enabled }: Params) { const [system_prompt, setSystemPrompt] = useState(); + const [memory, setMemory] = useState(); const [error, setError] = useState(); useEffect(() => { /** Cleared on close, so the next open never shows an old copy. */ setSystemPrompt(undefined); + setMemory(undefined); setError(undefined); if (!enabled || !bot_id) return; @@ -33,6 +35,7 @@ export default function useBotInstructions({ bot_id, enabled }: Params) { if (res.success && res.singleRes) { setSystemPrompt(res.singleRes.system_prompt); + setMemory(res.singleRes.memory); } else { setError(res.msg || "Couldn't load the instructions."); } @@ -46,5 +49,5 @@ export default function useBotInstructions({ bot_id, enabled }: Params) { }; }, [enabled, bot_id]); - return { system_prompt, error }; -} + return { system_prompt, memory, error }; +} \ No newline at end of file diff --git a/src/pages/admin/bots/[bot_id]/(partials)/bot-memory-form.tsx b/src/pages/admin/bots/[bot_id]/(partials)/bot-memory-form.tsx new file mode 100644 index 00000000..f3bab669 --- /dev/null +++ b/src/pages/admin/bots/[bot_id]/(partials)/bot-memory-form.tsx @@ -0,0 +1,124 @@ +import { useState } from "react"; +import Form from "@moduletrace/twui/form/Form"; +import Stack from "@moduletrace/twui/layout/Stack"; +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"; + +type Props = { + bot_id: number; + bot_name: string; + /** + * Its core memory, from the panel's read. + */ + memory: string; + /** + * Where the conversation is, so its memory there is edited beside it. + */ + workspace_id?: number | null; + workspace_name?: string | null; + workspace_memory?: string; + onCancel?: () => void; +}; + +/** + * The bot panel's memory tab: what it keeps in mind everywhere, and (in a + * workspace) what it keeps in mind there. Both are markdown, replaced whole; + * the bot's memory of each person stays its own. + */ +export default function BotMemoryForm({ + bot_id, + bot_name, + memory, + workspace_id, + workspace_name, + workspace_memory = "", + onCancel, +}: Props) { + const [core, setCore] = useState(memory); + const [here, setHere] = useState(workspace_memory); + const [loading, setLoading] = useState(false); + const [saved, setSaved] = useState(false); + const [error, setError] = useState(); + + const submit = async () => { + if (loading) return; + if (!window.confirm(`Save ${bot_name}'s memory?`)) return; + + setLoading(true); + setError(undefined); + setSaved(false); + + try { + const coreRes = await postAdminApi({ + path: "bots/update-bot-memory", + body: { bot_id, memory: core }, + }); + + if (!coreRes.success) { + setError(coreRes.msg || "Couldn't save its memory."); + return; + } + + if (workspace_id) { + const hereRes = await postAdminApi({ + path: "workspaces/update-bot", + body: { workspace_id, bot_id, memory: here }, + }); + + if (!hereRes.success) { + setError( + `Saved its memory everywhere, but not in ${workspace_name || "this workspace"}: ${hereRes.msg || "the save failed"}`, + ); + return; + } + } + + setSaved(true); + } catch { + setError("Couldn't save its memory."); + } finally { + setLoading(false); + } + }; + + return ( +
+ { + setCore(value); + setSaved(false); + }} + /> + + {workspace_id ? ( + { + setHere(value); + setSaved(false); + }} + /> + ) : null} + + + + ); +} \ No newline at end of file diff --git a/src/pages/admin/bots/[bot_id]/(partials)/bot-panel-section.tsx b/src/pages/admin/bots/[bot_id]/(partials)/bot-panel-section.tsx new file mode 100644 index 00000000..9d034684 --- /dev/null +++ b/src/pages/admin/bots/[bot_id]/(partials)/bot-panel-section.tsx @@ -0,0 +1,26 @@ +import Span from "@moduletrace/twui/layout/Span"; +import Stack from "@moduletrace/twui/layout/Stack"; +import type { ReactNode } from "react"; + +type Props = { + title: string; + /** + * One line under the title, saying what the section is. + */ + description: string; + children?: ReactNode; +}; + +/** + * One labelled part of the bot panel's tools tab: what it is, then its + * list. + */ +export default function BotPanelSection({ title, description, children }: Props) { + return ( + + {title} + {description} + {children} + + ); +} \ No newline at end of file diff --git a/src/pages/admin/bots/[bot_id]/(partials)/bot-panel.tsx b/src/pages/admin/bots/[bot_id]/(partials)/bot-panel.tsx index 52c1ce45..3d44d653 100644 --- a/src/pages/admin/bots/[bot_id]/(partials)/bot-panel.tsx +++ b/src/pages/admin/bots/[bot_id]/(partials)/bot-panel.tsx @@ -1,6 +1,6 @@ "use client"; -import { useContext, useEffect } from "react"; +import { useContext, useEffect, useState } from "react"; import Button from "@moduletrace/twui/layout/Button"; import H2 from "@moduletrace/twui/layout/H2"; import Row from "@moduletrace/twui/layout/Row"; @@ -10,19 +10,29 @@ import Loading from "@moduletrace/twui/elements/Loading"; import { X } from "lucide-react"; import SidePanel from "@/src/components/general/side-panel"; import BotAvatar from "@/src/components/general/bot-avatar"; +import TabButton from "@/src/components/general/tab-button"; import type { BotFace } from "@/src/dict/bot-dict"; import botStoneProps from "@/src/utils/bot-stone-props"; import { BotPanelOpenEvent } from "@/src/utils/bot-panel-open-event"; import type { BotWithLastMessage } from "@/src/types"; +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 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 BotToolsTab from "./bot-tools-tab"; type Props = { bot: BotWithLastMessage; + /** + * The workspace the conversation is in, so its memory and instructions + * there are edited too. + */ + workspace?: BUN_SQLITE_COBBLE_WORKSPACES | null; /** * The header owns it, since the avatar and the name both open the panel. */ @@ -31,22 +41,37 @@ type Props = { on_close: () => void; }; +type PanelTab = "settings" | "memory" | "tools"; + /** - * The bot's profile (picture, name, job, colour, instructions) 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 instructions load when - * it opens, and Escape, the backdrop or the X closes it. + * The bot's profile (picture, name, job, colour, instructions), its memory + * 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. */ -export default function BotPanel({ bot, open, on_open, on_close }: Props) { +export default function BotPanel({ bot, workspace, open, on_open, on_close }: Props) { const { pageProps } = useContext(AppContext); const name = bot.name || "This bot"; const can_edit = canManageCrew({ user_types: pageProps?.user_types }); - const { system_prompt, error } = useBotInstructions({ + const [tab, setTab] = useState("settings"); + const workspace_id = Number(workspace?.id) || 0; + const { system_prompt, memory, error } = useBotInstructions({ bot_id: Number(bot.id) || 0, enabled: open && can_edit, }); + const workspace_instructions = useWorkspaceBotInstructions({ + workspace_id, + bot_id: Number(bot.id) || 0, + enabled: open && can_edit && Boolean(workspace_id) && tab == "memory", + }); + const memory_ready = + system_prompt != undefined && + memory != undefined && + (!workspace_id || Boolean(workspace_instructions.instructions)); + const loaded_error = error || workspace_instructions.error; useTopModalEscape({ onClose: on_close, enabled: open }); @@ -101,26 +126,74 @@ export default function BotPanel({ bot, open, on_open, on_close }: Props) { + + setTab("settings")} /> + setTab("memory")} /> + setTab("tools")} /> + - - {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.`} - - {!open ? null : system_prompt != undefined ? ( - + + {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.`} + + {system_prompt != undefined ? ( + + ) : loaded_error ? ( + + {loaded_error} + + ) : ( + + + + )} + + ) : null} + {open && tab == "memory" ? ( + memory_ready ? ( + <> + + {`What ${name} keeps in mind, and can add to itself as it works.`} + + + + ) : loaded_error ? ( + + {loaded_error} + + ) : ( + + + + ) + ) : null} + {open && tab == "tools" ? ( + - ) : error ? ( - - {error} - - ) : ( - - - - )} + ) : null} diff --git a/src/pages/admin/bots/[bot_id]/(partials)/bot-tools-tab.tsx b/src/pages/admin/bots/[bot_id]/(partials)/bot-tools-tab.tsx new file mode 100644 index 00000000..a4f98dfb --- /dev/null +++ b/src/pages/admin/bots/[bot_id]/(partials)/bot-tools-tab.tsx @@ -0,0 +1,163 @@ +import { useContext } from "react"; +import Span from "@moduletrace/twui/layout/Span"; +import Stack from "@moduletrace/twui/layout/Stack"; +import useExtensions from "@/src/hooks/use-extensions"; +import type { + BotExtensionsPayload, + BotWithLastMessage, +} from "@/src/types"; +import { BotComputersContext } from "../(data)/bot-computers-context"; +import { + composerKnowledgebasesCopy, + composerToolsCopy, +} from "../(data)/composer-extensions-copy"; +import BotComputerOption from "./bot-computer-option"; +import BotPanelSection from "./bot-panel-section"; +import ComposerBrowserButton from "./composer-browser-button"; +import ComposerConnectorsSection from "./composer-connectors-section"; +import ComposerExtensionsList from "./composer-extensions-list"; + +type Props = { + bot: BotWithLastMessage; + workspace_id?: number | null; + initial?: BotExtensionsPayload | null; + /** + * Whether the user has a browser of their own; without one there is + * nothing to pick. + */ + has_browsers?: boolean; + /** + * Whether the tab is on show, so its connectors are read then and its + * computer switches show. + */ + open: boolean; +}; + +/** + * The bot panel's third 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. + */ +export default function BotToolsTab({ bot, workspace_id, initial, has_browsers, open }: Props) { + const bot_name = bot.name || "this bot"; + const extensions = useExtensions({ + owner: { bot_id: bot.id || 0, workspace_id }, + owner_name: bot_name, + initial, + }); + const { computers, switching_id, error: computer_error, switchComputer, openComputer } = + useContext(BotComputersContext); + + const is_knowledge = (item: { kind: string }) => item.kind == "knowledgebase"; + const tools = { + attached: extensions.attached.filter((item) => !is_knowledge(item)), + addable: extensions.addable.filter((item) => !is_knowledge(item)), + }; + const knowledge = { + attached: extensions.attached.filter(is_knowledge), + addable: extensions.addable.filter(is_knowledge), + }; + const tools_copy = composerToolsCopy({ bot_name }); + const knowledge_copy = composerKnowledgebasesCopy({ bot_name }); + + return ( + + + {computers.length ? ( + + {computers.map((computer, index) => ( + { + await switchComputer({ computer_id: computer.id || 0 }); + }} + onOpen={() => { + openComputer({ computer_id: computer.id || 0 }); + }} + /> + ))} + + ) : ( + + {`No computer is set up for ${bot_name} yet.`} + + )} + {switching_id ? ( + + Switching its computer. The tasks it has open finish where they are. + + ) : null} + {computer_error ? ( + + {computer_error} + + ) : null} + + + + + + {has_browsers ? ( + + + {`Which of your browsers ${bot_name} acts as you in.`} + + + + ) : null} + + + + + + + {extensions.status?.error ? ( + + {extensions.status.msg} + + ) : null} + + ); +} \ No newline at end of file diff --git a/src/pages/admin/bots/[bot_id]/(partials)/composer-extensions-list.tsx b/src/pages/admin/bots/[bot_id]/(partials)/composer-extensions-list.tsx new file mode 100644 index 00000000..9429f3d9 --- /dev/null +++ b/src/pages/admin/bots/[bot_id]/(partials)/composer-extensions-list.tsx @@ -0,0 +1,103 @@ +import Span from "@moduletrace/twui/layout/Span"; +import Stack from "@moduletrace/twui/layout/Stack"; +import ExtensionAddSelect from "@/src/components/general/extension-add-select"; +import type { + BotExtension, + BotExtensionKind, + BotExtensionsPayload, +} from "@/src/types"; +import ComposerToolRow from "./composer-tool-row"; + +type Props = { + /** + * The add picker's element id, unique on the page. + */ + id: string; + /** + * What the list is, for screen readers. + */ + label: string; + items: BotExtension[]; + addable: BotExtensionsPayload["addable"]; + can_manage: boolean; + /** + * The extension being changed, as `kind:id`. + */ + busy?: string; + /** + * Said instead of the list when it holds nothing. + */ + empty?: string; + add_hint: string; + add_noun: string; + onAdd: (params: { kind: BotExtensionKind; id: number }) => Promise; + onRemove: (params: { + kind: BotExtensionKind; + id: number; + name: string; + }) => Promise; +}; + +/** + * What a bot can use here as a list, then the picker for more: shared by + * the composer's modals and the bot panel's tools tab. Super admins and + * admins take away any it was given (even one every bot started with); a + * workspace's own stay. + */ +export default function ComposerExtensionsList({ + id, + label, + items, + addable, + can_manage, + busy, + empty, + add_hint, + add_noun, + onAdd, + onRemove, +}: Props) { + return ( + <> + {items.length ? ( + + {items.map((item) => ( + + onRemove({ + kind: item.kind, + id: item.id, + name: item.name, + }) + : undefined + } + /> + ))} + + ) : empty ? ( + {empty} + ) : null} + + {can_manage && addable.length ? ( + + {add_hint} + + + ) : null} + + ); +} \ No newline at end of file diff --git a/src/pages/admin/bots/[bot_id]/(partials)/composer-tools-modal.tsx b/src/pages/admin/bots/[bot_id]/(partials)/composer-tools-modal.tsx index fb105f73..18271740 100644 --- a/src/pages/admin/bots/[bot_id]/(partials)/composer-tools-modal.tsx +++ b/src/pages/admin/bots/[bot_id]/(partials)/composer-tools-modal.tsx @@ -7,7 +7,6 @@ import Row from "@moduletrace/twui/layout/Row"; import Span from "@moduletrace/twui/layout/Span"; import Stack from "@moduletrace/twui/layout/Stack"; import { CircleAlert, type LucideIcon } from "lucide-react"; -import ExtensionAddSelect from "@/src/components/general/extension-add-select"; import type { BotExtension, BotExtensionKind, @@ -15,7 +14,7 @@ import type { ConnectorAppIcon, } from "@/src/types"; import ComposerConnectorsSection from "./composer-connectors-section"; -import ComposerToolRow from "./composer-tool-row"; +import ComposerExtensionsList from "./composer-extensions-list"; import { twMerge } from "tailwind-merge"; /** @@ -168,45 +167,18 @@ export default function ComposerToolsModal({ - {count ? ( - - {attached.map((item) => ( - - onRemove({ - kind: item.kind, - id: item.id, - name: item.name, - }) - : undefined - } - /> - ))} - - ) : null} - - {can_manage && addable.length ? ( - - - {copy.add_hint} - - - - ) : null} + {connectors ? ( : null} + APIResponseObject<{ system_prompt: string; memory: string }> > = async ({ req, body }) => { try { if (req.method != "POST") { @@ -40,7 +40,7 @@ export const handler: BunextAPIRouteHandler< throw new AppError(`Bot not found.`); } - return { success: true, singleRes: { system_prompt: bot.system_prompt || "" } }; + return { success: true, singleRes: { system_prompt: bot.system_prompt || "", memory: bot.memory || "" } }; } catch (error: unknown) { return { success: false, msg: safeErrorMessage({ error }) }; } diff --git a/src/pages/api/admin/bots/update-bot-memory.ts b/src/pages/api/admin/bots/update-bot-memory.ts new file mode 100644 index 00000000..1d521b5a --- /dev/null +++ b/src/pages/api/admin/bots/update-bot-memory.ts @@ -0,0 +1,60 @@ +import userAuth from "@/src/functions/backend/auth/user-auth"; +import updateBotMemory from "@/src/functions/backend/db/bots/update-bot-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 canManageCrew from "@/src/utils/rbac/can-manage-crew"; +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 a bot's core memory from its panel (the memory tab), for super + * admins and admins. Its memory of each user and its memory in a workspace + * are separate rows. + */ +export const handler: BunextAPIRouteHandler = 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.`); + } + + if (!canManageCrew({ user_types })) { + throw new AppError(`Only an admin can edit a bot.`); + } + + const { bot_id, memory } = parseWithSchema({ + schema: UpdateBotMemoryRequestSchema, + data: body, + }); + + await updateBotMemory({ user_id: user.id, bot_id, memory }); + + await logEvent({ + title: "Bot memory changed", + category: "system", + user_id: user.id, + plain_text: `User #${user.id} edited bot #${bot_id}'s memory.`, + metadata: { bot_id }, + ip_address: grabRequestIP(req), + }); + + return { success: true, msg: `Saved.` }; + } catch (error: unknown) { + return { success: false, msg: safeErrorMessage({ error }) }; + } +}; \ No newline at end of file diff --git a/src/schemas/bot-schema.test.ts b/src/schemas/bot-schema.test.ts index d8f75e46..935912bd 100644 --- a/src/schemas/bot-schema.test.ts +++ b/src/schemas/bot-schema.test.ts @@ -1,5 +1,5 @@ import { describe, expect, test } from "bun:test"; -import { MessageDetailsRequestSchema } from "./bot-schema"; +import { MessageDetailsRequestSchema, UpdateBotMemoryRequestSchema } from "./bot-schema"; describe("MessageDetailsRequestSchema", () => { test("asks for the modal's calls by default", () => { @@ -21,3 +21,21 @@ describe("MessageDetailsRequestSchema", () => { expect(MessageDetailsRequestSchema.safeParse({}).success).toBe(false); }); }); + +describe("UpdateBotMemoryRequestSchema", () => { + test("takes the whole new memory", () => { + expect(UpdateBotMemoryRequestSchema.parse({ bot_id: "3", memory: "It writes short." })).toEqual({ + bot_id: 3, + memory: "It writes short.", + }); + }); + + test("allows clearing it", () => { + expect(UpdateBotMemoryRequestSchema.parse({ bot_id: 3, memory: "" }).memory).toBe(""); + }); + + test("refuses a bot or a memory that isn't there", () => { + expect(UpdateBotMemoryRequestSchema.safeParse({ bot_id: 3 }).success).toBe(false); + expect(UpdateBotMemoryRequestSchema.safeParse({ bot_id: 0, memory: "x" }).success).toBe(false); + }); +}); diff --git a/src/schemas/bot-schema.ts b/src/schemas/bot-schema.ts index df88ecf7..18a3596f 100644 --- a/src/schemas/bot-schema.ts +++ b/src/schemas/bot-schema.ts @@ -234,6 +234,19 @@ export const UpdateBotRequestSchema = CreateBotRequestSchema.omit({ workspace_id export type UpdateBotRequest = z.infer; +/** + * The bot's core memory, edited from its panel: the whole new text. + */ +export const UpdateBotMemoryRequestSchema = z.object({ + bot_id: z.coerce.number().int().positive("Pick a bot"), + memory: z + .string() + .trim() + .max(AppData.PromptMaxLength, `Keep memory under ${AppData.PromptMaxLength} characters`), +}); + +export type UpdateBotMemoryRequest = z.infer; + export const UploadBotAttachmentRequestSchema = z.object({ /** * The file as a base64 data URL. diff --git a/src/schemas/workspace-schema.test.ts b/src/schemas/workspace-schema.test.ts new file mode 100644 index 00000000..ced7c6d6 --- /dev/null +++ b/src/schemas/workspace-schema.test.ts @@ -0,0 +1,11 @@ +import { describe, expect, test } from "bun:test"; +import { UpdateWorkspaceBotRequestSchema } from "./workspace-schema"; + +describe("UpdateWorkspaceBotRequestSchema", () => { + test("leaves the fields it wasn't given alone", () => { + const parsed = UpdateWorkspaceBotRequestSchema.parse({ workspace_id: "2", bot_id: "5", memory: "Short here." }); + + expect(parsed).toEqual({ workspace_id: 2, bot_id: 5, memory: "Short here." }); + expect("system_prompt" in parsed).toBe(false); + }); +}); diff --git a/src/schemas/workspace-schema.ts b/src/schemas/workspace-schema.ts index 79992d6b..400eb1b8 100644 --- a/src/schemas/workspace-schema.ts +++ b/src/schemas/workspace-schema.ts @@ -32,9 +32,13 @@ export const WorkspaceBotRequestSchema = z.object({ export type WorkspaceBotRequest = z.infer; +/** + * Either one alone: the bot panel's memory tab saves the workspace memory + * without rewriting the instructions here, and vice versa. + */ export const UpdateWorkspaceBotRequestSchema = WorkspaceBotRequestSchema.extend({ - system_prompt: Prompt.default(""), - memory: Prompt.default(""), + system_prompt: Prompt.optional(), + memory: Prompt.optional(), }); export type UpdateWorkspaceBotRequest = z.infer;