Compare commits

...
2 Commits
Author SHA1 Message Date
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
25 changed files with 535 additions and 165 deletions
+3 -3
View File
@@ -91,7 +91,7 @@ Enables SQLite foreign keys (`enableForeignKeys`), `bunextInit()`, `ensureDocker
- **Tables:** `bots` (`kind`, `color` `#rrggbb`, `stone`, `role`, `system_prompt`; `hue` is a legacy fallback), `bot_user_faces`, `bot_sessions`, `bot_messages`, `bot_tasks`, `bot_task_steps` (unused yet), `bot_plans` (a plan a bot wrote for work in pieces, its steps and their state), `bot_job_traces` (a run's debug view, 7 days by default). Enums in `src/dict/bot-dict.ts` and `src/dict/bot-plan-dict.ts`.
- **Sessions:** one thread per user per bot in its own chat plus one per workspace; split into `bot_sessions` (rollover at the app setting `bot_session_max_messages`, default `AppData.BotSessionMaxMessages`, via `grabBotSessionMaxMessages`; titled and summarised by `name-bot-session.ts` from the session's opening after a reply or a task (a session with no user message, work handed to the bot, is named from the bot's own messages; `grabSessionOpening`; `grabBotMessages` reads the latest; each opening message is cut to `AppData.BotSessionNameMessageChars`, so a pasted brief of tens of thousands of characters costs one naming call, not a second copy of itself), summary carried into the next session only when they're linked by `previous_session_id`, which only a carry-over sets; older implicit links are cleared at boot by `clearImplicitSessionLinks`). New session (`startBotSession`) and a conversation with no active session always start fresh. The rollover carries over like the bot does (`rollOverBotSession` -> `continueBotSession`, falling back to the stored summary; kept for the next message while a job is open in the full session or there's nothing to carry), inside send-message, so the user's message lands under the summary. Sending a message and answering a question card both hold the conversation's lock (`conversationLock`, `src/functions/backend/db/bot-sessions/conversation-lock.ts`, a `createKeyLock` per user, bot and workspace), since two sends 78 ms apart both read the same full session and one then wrote into the session the other had just closed; when its own rollover writes nothing, `rollOverBotSession` returns the conversation's current active session rather than the stale one. The composer holds its send until it answers (`sending`), so a double tap sends once. An open plan follows its conversation across a rollover (`carry-over-bot-session` moves `bot_plans.session_id`). A routine and a hook each keep a thread of their own, marked by `bot_sessions.routine_id` and `hook_id`, with the routine's or hook's title, rolled over at the same session max into a new linked session (`rollOverLinkedSession`, `previous_session_id`, the summary opening the new one), and read and chatted in with `?session_id=` like any session. `ensureRoutineSession`/`ensureHookSession` open it `closed` and then make it the conversation's active session (`activateBotSession`, a routine and a non-silent hook alike), so a run takes the chat over instead of landing in a sidebar; a silent hook is the opt-out (`bot_hooks.silent`). A deleted routine or hook detaches its thread (`routine_id`/`hook_id` set to null) and keeps the messages; a silent hook's thread is the one exception to being followed (`followedSessionSql`: no rail row, no unread, no push, no face change) **until the user writes in it**: a human message takes the thread from the hook (`adoptHookSession`, from `insertUserMessage`, so a chat message and a question's answer alike), so the thread is theirs from then on and the hook opens a new one next time, while a hook that isn't silent makes its thread the conversation's active session for its run. Helpers in `src/functions/backend/db/bot-sessions/`. Job results land in the job's own session, even after it closes, except a reply that called `continue_in_new_session` (`carryOverBotSession`; the menu's and sessions modal's Continue in new session does the same through `continueBotSession`, the model writing title and summary, refused while a job is open in the session): its summary is kept on the closed session and opens the new one as a bot message (`carried_from_session_id`), the job's `session_id` moves so the answer follows, the new session is titled by the bot then (it has no first exchange to be named from), and the old one can never be reopened (`reopenBotSession` refuses; a thread showing it swaps its composer for a link to the new one). Session lists (rail, sessions modal) reopen a session on click, as before; a carried-over one can't be, so it opens to read (`?session_id=`, `conversationHref`). The sessions modal deletes a session too (`delete-session` -> `deleteBotSession` -> `deleteSessionRows`), refused while a run is open in it; deleting the active one starts the conversation a fresh session. The page tells them which session it shows (`announceShownSession` -> `useShownSession`): they reload, mark it Current (greyed out; without `?session_id=` the active one is), list it even when it's older than the rail's latest, and the active row then leads back. From half the session length the reply prompt suggests moving on (`longSessionNote`). Earlier sessions never enter the prompt (only the last one's summary): the thread can open them above a session (`useOlderMessages.loadPrevious`, a divider per session, quote and reply as usual), and replies get `search_past_sessions`/`read_past_session` (scoped to that user, bot and place, never the current session) when the conversation has any.
- **Coordinator:** exactly one, the super admin's alone, created idempotently by `ensureCoordinatorBot`. Default prompt `src/data/coordinator-system-prompt.ts`, backfilled only when empty.
- **Routes:** `/admin/bots` reopens the last visited bot's own chat (cookie `cobble_last_visited_bot_id`, `<bot>` or `<bot>:<workspace>`; the landing uses only the bot) if still reachable, else coordinator (super admin) / latest bot / first workspace / empty. Workspace and conversation pages record the visit per user (`recordWorkspaceVisit`/`workspace_user_visits`, `recordBotVisit`/`bot_user_visits`) and the rail lists both latest visited first (`last_visited_at`, `orderByLastVisit`; recorded before the crew is read, so the conversation opened is already on top in that render, and its bot leads whatever the visits say (`pinned_id`); a workspace nobody visited yet ranks by its creation, so a new one leads); it never decides the landing. Settings and the rail pages get the cookie's conversation, workspace included, as root prop `last_conversation` (`grabLastConversation`, access-checked, only on those paths: `isPagesRailPath`), shown above their rail list as the way back (`RailLastConversation`). `/admin/bots/[bot_id]` conversation (header, thread and composer at 760px, the bot panel (`BotPanel`) sliding in from the right when its stone (beside the name or beside its messages in the thread) or its name is tapped, or a phone swipes that way, over the conversation rather than taking width; `?session_id=` opens another of the user's sessions there: a closed one is reopened, except a carried-over one, which shows with `SessionMovedBar` instead of the composer, pointing where the conversation went on); `/admin/bots/[bot_id]/models`; `/admin/workspaces/[id]` dashboard; `/admin/workspaces/[id]/bots/[bot_id]` same conversation scoped to the workspace.
- **Routes:** `/admin/bots` reopens the last visited bot's own chat (cookie `cobble_last_visited_bot_id`, `<bot>` or `<bot>:<workspace>`; the landing uses only the bot) if still reachable, else coordinator (super admin) / latest bot / first workspace / empty. Workspace and conversation pages record the visit per user (`recordWorkspaceVisit`/`workspace_user_visits`, `recordBotVisit`/`bot_user_visits`) and the rail lists both latest visited first (`last_visited_at`, `orderByLastVisit`; recorded before the crew is read, so the conversation opened is already on top in that render, and its bot leads whatever the visits say (`pinned_id`); a workspace nobody visited yet ranks by its creation, so a new one leads); it never decides the landing. Settings and the rail pages get the cookie's conversation, workspace included, as root prop `last_conversation` (`grabLastConversation`, access-checked, only on those paths: `isPagesRailPath`), shown above their rail list as the way back (`RailLastConversation`). `/admin/bots/[bot_id]` conversation (header, thread and composer at 760px, the bot panel (`BotPanel`) sliding in from the right when its stone (beside the name or beside its messages in the thread) or its name is tapped, or a phone swipes that way, over the conversation rather than taking width: a crew manager edits it, anyone else reaching the bot reads its role and instructions and rewrites what it remembers about them (`update-user-memory`, no crew guard); `?session_id=` opens another of the user's sessions there: a closed one is reopened, except a carried-over one, which shows with `SessionMovedBar` instead of the composer, pointing where the conversation went on); `/admin/bots/[bot_id]/models`; `/admin/workspaces/[id]` dashboard; `/admin/workspaces/[id]/bots/[bot_id]` same conversation scoped to the workspace.
- **No model:** while the bot has no text model there (`bot_text_model` null, kept live by the models modal), the thread shows `NoModelNotice` (centred when empty): super admins get Connect a provider / Guided setup, others are told the super admin sets it up.
- **Conversation loading:** pages render everything server-side (`grabConversationProps`) **except the history**, which the client loads (`api/admin/bots/conversation-history`, merged with what's already shown, refetched on bfcache restore) and pages older messages on scroll. Rail lists go through `railBots`/`railWorkspaces` (no prompts/memory, previews cut). Every return to the page (window focus, a hidden tab visible, back online: `use-refocus`, `AppData.RefocusGapMs`) reads the crew again (`use-live-crew-refresh` -> `api/admin/bots/live-crew` -> `cobble:live-crew-refreshed`, taken by `useLiveBots`/`useLiveWorkspaces`) and the session's latest messages plus its bot's face, task and the step its reply is on (`session-messages`, `use-reply-catch-up`; the history's own `step` seeds that row on load, `use-reply-progress`, and a row only ever moves forward in `bots_queue_updates` ids), and the page polls the same while a reply is due (read with the live face, never the page's): pushes missed while the phone slept left threads thinking and faces stale until a reload. The thread follows new messages while it sits at its bottom and offers "Jump to latest" (`ScrollToBottomButton`) when scrolled up; End does what that button does and Home goes back to the top of the messages loaded so far, both keeping away from a field being typed in, an open menu and an open modal (`typingInField`, `scrollThreadToTop`). On a phone, pulling the thread up past its bottom lifts the newest message off the edge, opening just enough room for a lone refresh icon (a ghost button, no label; no deeper, however far the drag goes), and letting go only reloads once that full room has been held for half a second, which lights the icon (`AppData.PullToRefreshHoldMs`: an exhausted thread reaches the limit by accident too easily) and then turns it into its spinner for at least a second (`AppData.PullToRefreshMinLoadingMs`) while the conversation and the rail are read again (`use-pull-to-refresh` writes that room straight onto the content as the finger moves, never through a render, and owns the gesture until release; the gesture is a plain state machine in `(utils)/pull-to-refresh-gesture.ts`, its steps tested without a browser, which takes the pull's anchor the moment the thread reaches its end, so one swipe that runs out of conversation hands over instead of stopping dead, and reads the end with `AppData.PullToRefreshEndSlackPx` of slack through `atThreadEnd`, since a phone's fractional device pixel ratio leaves the content a hair short and demanding an exact zero made the whole gesture do nothing; `PullToRefreshIndicator`; dragged back down before the release, the icon hides at the travel that showed it).
- **Sending:** `api/admin/bots/send-message.ts` -> `enqueueBotReply` -> `wakeBotsQueue`. **Never import `src/bots-queue/index.ts` from a page or API route** (pulls the bunext runtime into page bundles). Optimistic bubble in `pending_messages` until the saved message replaces it. A message is capped at the app setting `bot_message_max_chars` (Settings > General, default `AppData.BotMessageMaxChars`, counted on the trimmed markdown, up to `BotMessageMaxCharsMax`), checked by the composer before it sends (the reason shows under the input) and again by the route (`messageTooLongMessage` says how far over it is and to attach the text as a file). Once stored, a message is never cut: it goes into every turn whole. A message sent in **Plan mode** (`bot_messages.plan_mode`, turned on by Tab anywhere on the conversation page or the composer's Plan button, remembered per conversation in `localStorage`) is answered by a planning run: `run-bot-reply` gates every tool outside `PlanModeToolNames` (`gatePlanModeTools`: the write tools stay listed with their own name, description and schema, and calling one throws the Plan mode reason, never "there is no tool called ...", since only `run` is replaced; `load_tools` is gated too, so a deferred MCP or browser tool can't be pulled in), `send_reply` refuses `work` and `working`, and the computer and browser notes are left out; Retry and Run again copy the flag from the message they answer. **Answering or skipping an `ask_user` card is not a way out:** the card carries `bot_questions.plan_mode` from the run that asked, and `postBotQuestionAnswers` runs the answer as a Plan mode reply too (only Tab, or approving a plan, turns the mode off). A reply that ran in it carries `bot_messages.plan_mode` (`jobPlanMode` over the job's params) and shows `PlanModeOffButton` under it while the mode is still on: one click turns it off and puts "Plan mode is off, go ahead." in the composer (`turnOffPlanMode`, never sends), which is the click the bot's answer asks for. A Plan mode reply whose result belongs in a file or another place outside the chat may not paste it or say a write tool is missing: it says the mode stops the save and either writes a plan they approve or tells them to turn Plan mode off, and `planModeFileEscape` sends a reply back when it hands the save to the user instead.
@@ -119,7 +119,7 @@ Enables SQLite foreign keys (`enableForeignKeys`), `bunextInit()`, `ensureDocker
### Prompt and memory
`composeBotPrompt` (`src/utils/compose-bot-prompt.ts`, via `grab-bot-prompt`): core `system_prompt`, install-wide append (`bot_system_prompt_append`), the name of the user the run is for (`grabUserName`; first and last, else username, and no section when they have neither, so no bot asks who it's talking to), then in a workspace its context, the bot's instructions there and the run's user's role there (`workspace_user_roles`), then core `memory`, per-user memory (`bot_user_memories`), workspace memory (`workspace_bots.memory`). Core memory is never about one user. `update_memory` defaults to `user` (`workspace` in a workspace); core only for what holds for everyone. Whole-text replace, capped at `AppData.PromptMaxLength`. Each whole-text replace (`update_workspace`'s context, `set_bot_workspace_instructions`, `update_memory`) refuses once a save that would drop a section (`markdownHeadings`) or cut the text below `AppData.SharedTextShrinkShare` of its length (`sharedTextProblem`, `src/utils/shared-text-guard.ts`), until the caller passes `replace: true`; the context is read before it is rewritten with `find_workspace` `include_context` (coordinator wherever it works, and a workspace admin), and each of them reads its save back before reporting it. Each memory section says it shapes how the bot does the work, never what it does beyond the request.
`composeBotPrompt` (`src/utils/compose-bot-prompt.ts`, via `grab-bot-prompt`): core `system_prompt`, install-wide append (`bot_system_prompt_append`), the name of the user the run is for (`grabUserName`; first and last, else username, and no section when they have neither, so no bot asks who it's talking to), then in a workspace its context, the bot's instructions there and the run's user's role there (`workspace_user_roles`), then core `memory`, per-user memory (`bot_user_memories`, which the bot writes and its user rewrites in the bot panel), workspace memory (`workspace_bots.memory`). Core memory is never about one user. `update_memory` defaults to `user` (`workspace` in a workspace); core only for what holds for everyone. Whole-text replace, capped at `AppData.PromptMaxLength`. Each whole-text replace (`update_workspace`'s context, `set_bot_workspace_instructions`, `update_memory`) refuses once a save that would drop a section (`markdownHeadings`) or cut the text below `AppData.SharedTextShrinkShare` of its length (`sharedTextProblem`, `src/utils/shared-text-guard.ts`), until the caller passes `replace: true`; the context is read before it is rewritten with `find_workspace` `include_context` (coordinator wherever it works, and a workspace admin), and each of them reads its save back before reporting it. Each memory section says it shapes how the bot does the work, never what it does beyond the request.
Every run also gets `RequestScopeNote` (`src/data/harness-prompts.ts`): the user's request sets the scope, and crew changes (create, place, remove, assign a computer, change a role) and handing work out (delegating, handing over a task or routine) happen only once the user asked for them, through one `ask_user` card in a reply or task, or as a proposal in a run nobody watches (routine, hook call, crew request). The way they named is part of the request too: a tool, app, service, provider or path they asked for is the one to use, a blocked one is reported and asked about, never swapped for another way that reaches the same result, and a probe is not a deliverable. Memory, habits and the bot's own initiative never widen a request. Every prompt ends with `RoadblockNote`: a run that is blocked (a tool failing again and again, a computer or page down, access it does not have) stops after two or three attempts and reports what failed and what the user must do, never works around it another way or describes the work as done. The app enforces the tool-loop half itself: `AppData.HarnessStuckToolRepeats` consecutive calls of one tool with the same answer end the run at a wrap up (`stuckToolNote`, `run-text-loop.ts`).
@@ -193,7 +193,7 @@ Set in Settings > Environment (super admin), not `.env`. `envs` (private; encryp
- **Install icon:** app setting `install_icon` (JSON, `parseInstallIcon`): a stone, or an upload (decoded, cropped to `source.png`, never stored as sent, no SVG) with the stone at `PwaCornerMarkInset`/`PwaCornerMarkScale`, inside a round launcher's crop. `saveInstallIcon` draws the set (`renderInstallIcons`, shared with `gen:favicon` via `renderAppIcon`) into `DATA_DIR/install-icon/<version>/`, served publicly and `immutable` by `handleInstallIconFile`; the manifest, head links and push payloads point at it. Ember stone = stock icons, no set.
- Notification `badge` is `icons/badge-96.png` (white silhouette; Android masks by alpha, so never the opaque app icon). Brave on Android has no WebAPK, so its notifications always carry Brave's name and icon.
- `public/sw.js` is served `no-store`; navigations network-only (authenticated HTML never cached); `/api/`, `/ws`, `/media/`, `/computers/`, `/build-info.json` never intercepted. A new worker takes over by itself (`skipWaiting` on install; nothing in it is per-version) and never reloads a page; there is no update prompt. In development the worker and caches are actively removed (`clear-development-service-worker.ts`, stub `/sw.js`).
- **Precache (production):** a navigation without the current build cookie gets `loading.html`, which downloads all of `.bunext/public` into `cobble-assets-<build_id>`, verifies, sets the cookie and reloads (falls back to network on stall). React knows nothing of this.
- **Precache (production):** a navigation without the current build cookie gets `loading.html`, which downloads all of `.bunext/public` into `cobble-assets-<build_id>`, verifies, sets the cookie and reloads (falls back to network on stall). React knows nothing of this. The root also puts the build in a `cobble-build` meta tag, and a chat send from a page running an older build is refused (`stale_build` in `send-message.ts`) so the composer keeps what was typed in its draft and reloads into the running build.
- Phone shell: rail is a slide-over below `md` (the shared `src/components/general/side-panel.tsx`, always mounted so it slides both ways; the rail passes `inertWhenClosed={false}` since it is the page's own rail from `md` up); rail internals use the `@rail:` container variant, not viewport `lg:`. Two swipes anywhere on a phone page move between panes: to the right opens the rail's drawer, to the left the conversation's bot panel (`cobble:open-bot-panel`, `src/utils/bot-panel-open-event.ts`, answered only by a conversation's header, so a page without one slides nothing). They are flicks, read by `src/hooks/use-horizontal-swipe.ts` (a field, a `data-no-swipe` panel, a box that scrolls sideways, a text selection, a finger down longer than `AppData.MobileSwipeMaxMs`, an open twui modal, a screen from `md` up and the open drawer all own the touch), with the thresholds and the one-decision state machine in `src/utils/swipe-gesture.ts` (`AppData.MobileSwipeMinPx`, `MobileSwipeAxisRatio`), tested without a browser. An open panel answers the one swipe back off its edge (`src/hooks/use-swipe-to-close.ts`, `sidePanelCloseSwipe`): a left drag closes the rail's drawer, a right drag the bot panel; `SidePanel` gives both the same phone width (`w-[420px] max-w-[92vw]`). `LiveSocket` is remounted on online/pageshow/visibility since twui stops retrying after three attempts. Nothing is queued offline.
- **Web Push:** `push_subscriptions`, `user_presence`; VAPID keys generated into `envs` by `ensureVapidKeys`. `pushBotNotice` is the one trigger, skipped while the user is present (`AppData.PushPresenceWindowMs`, per user not per device). Best effort, no retry. Needs HTTPS.
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "cobble",
"version": "0.28.6",
"version": "0.28.7",
"module": "index.ts",
"type": "module",
"private": true,
+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;
+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" />
@@ -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,
},
});
}
@@ -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");
});
});
@@ -11,6 +11,7 @@ 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 CodeEditor from "@/src/components/general/code-editor";
import TabButton from "@/src/components/general/tab-button";
import type { BotFace } from "@/src/dict/bot-dict";
import botStoneProps from "@/src/utils/bot-stone-props";
@@ -20,6 +21,7 @@ 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";
@@ -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,11 +67,13 @@ 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,
@@ -79,28 +84,19 @@ export default function BotPanel({
system_prompt != undefined &&
memory != undefined &&
user_memory != undefined &&
(!workspace_id || Boolean(workspace_instructions.instructions));
(!can_edit ||
!workspace_id ||
Boolean(workspace_instructions.instructions));
const loaded_error = error || workspace_instructions.error;
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 +105,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 +121,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 +137,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 +153,114 @@ 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, and the instructions it follows.`}
</Span>
{bot.role ? (
<Span className="text-[13px] leading-[18px] text-ink">
{bot.role}
</Span>
) : null}
{system_prompt != undefined &&
user_memory != undefined ? (
<>
<CodeEditor
title="Instructions"
content={
system_prompt || "Nothing yet."
}
mode="markdown"
className="h-52"
readOnly
onChange={() => {}}
/>
<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}
/>
</>
) : error ? (
<Span className="py-6 text-[13px] leading-[18px] text-ink-secondary">
{error}
</Span>
) : (
<Stack className="w-full py-10 items-center">
<Loading />
</Stack>
)}
</>
)
) : null}
{open && tab == "tools" ? (
<BotToolsTab
@@ -223,6 +268,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}
@@ -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,111 @@
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";
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>
<CodeEditor
title="About you"
content={memory || "Nothing yet."}
mode="markdown"
className="h-32"
readOnly
onChange={() => {}}
/>
</>
);
}
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>
);
}
}
@@ -28,6 +28,8 @@ 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 composerHistoryTexts from "../(utils)/composer-history-texts";
import composerDraftKey from "../(utils)/composer-draft-key";
import loadedBuildId from "../(utils)/loaded-build";
import ComposerAttachButton from "./composer-attach-button";
import ComposerAttachments from "./composer-attachments";
import ComposerClearButton from "./composer-clear-button";
@@ -289,6 +291,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.
@@ -392,8 +419,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 });
@@ -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;
}
+7 -8
View File
@@ -12,10 +12,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 and
* their own memory; its core memory stays with super admins and admins, and
* only the super admin reaches the coordinator.
*/
export const handler: BunextAPIRouteHandler<
APIResponseObject<{ system_prompt: string; memory: string; user_memory: string }>
@@ -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 edit a bot.`);
}
const may_read_core = canManageCrew({ user_types });
const { bot_id } = parseWithSchema({ schema: BotIdRequestSchema, data: body });
const bot = await grabUserBot({ bot_id, user_id: user.id });
@@ -46,7 +45,7 @@ export const handler: BunextAPIRouteHandler<
success: true,
singleRes: {
system_prompt: bot.system_prompt || "",
memory: bot.memory || "",
memory: may_read_core ? bot.memory || "" : "",
user_memory: (await grabBotUserMemory({ bot_id: 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) {
@@ -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 }) };
}
};
+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 -2
View File
@@ -564,9 +564,9 @@ footer .twui-anchor.active {
@apply text-xs!;
}
.conversation-user-bubble a {
/* .conversation-user-bubble a {
@apply text-blue-400 dark:text-blue-600;
}
} */
.lucide[width="24"][height="24"] {
@apply w-[16px] h-[16px];
+6
View File
@@ -3074,6 +3074,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;
}