Compare commits

..
1 Commits
Author SHA1 Message Date
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
7 changed files with 70 additions and 37 deletions
+1 -1
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: 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.
- **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, instructions and memory (the workspace's too, `bot-instructions`/`workspace-bot`) 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.
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "cobble",
"version": "0.28.7",
"version": "0.28.8",
"module": "index.ts",
"type": "module",
"private": true,
@@ -11,7 +11,6 @@ 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";
@@ -27,6 +26,7 @@ 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";
@@ -78,15 +78,13 @@ export default function BotPanel({
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 &&
memory != undefined &&
user_memory != undefined &&
(!can_edit ||
!workspace_id ||
Boolean(workspace_instructions.instructions));
(!workspace_id || Boolean(workspace_instructions.instructions));
const loaded_error = error || workspace_instructions.error;
useTopModalEscape({ onClose: on_close, enabled: open });
@@ -221,27 +219,41 @@ export default function BotPanel({
) : (
<>
<Span className="text-[13px] leading-[18px] text-ink-secondary">
{`What ${name} is for, and the instructions it follows.`}
{`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}
{system_prompt != undefined &&
user_memory != undefined ? (
{memory_ready ? (
<>
<CodeEditor
<BotReadOnlyBlock
title="Instructions"
content={
system_prompt || "Nothing yet."
}
mode="markdown"
content={system_prompt || ""}
className="h-52"
readOnly
onChange={() => {}}
/>
<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}
@@ -250,9 +262,9 @@ export default function BotPanel({
onCancel={on_close}
/>
</>
) : error ? (
) : loaded_error ? (
<Span className="py-6 text-[13px] leading-[18px] text-ink-secondary">
{error}
{loaded_error}
</Span>
) : (
<Stack className="w-full py-10 items-center">
@@ -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={() => {}}
/>
);
}
@@ -4,6 +4,7 @@ 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;
@@ -70,13 +71,10 @@ export default function BotUserMemory({
<Span className="text-[13px] leading-[18px] text-ink-secondary">
{description}
</Span>
<CodeEditor
<BotReadOnlyBlock
title="About you"
content={memory || "Nothing yet."}
mode="markdown"
content={memory}
className="h-32"
readOnly
onChange={() => {}}
/>
</>
);
+4 -7
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,
@@ -14,8 +13,8 @@ import type {
/**
* 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
* 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<
@@ -26,14 +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 };
}
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 });
@@ -45,7 +42,7 @@ export const handler: BunextAPIRouteHandler<
success: true,
singleRes: {
system_prompt: bot.system_prompt || "",
memory: may_read_core ? bot.memory || "" : "",
memory: bot.memory || "",
user_memory: (await grabBotUserMemory({ bot_id: bot.id, user_id: user.id })) || "",
},
};
@@ -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 || "",
},
};