Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
197c8f4e2e | ||
|
|
70733e2358 | ||
|
|
2221113e91 | ||
|
|
fa81e93792 | ||
|
|
402df96b76 |
@@ -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, never the chat that happens to be active: `bot_sessions.routine_id` and `hook_id` mark it, `ensureRoutineSession`/`ensureHookSession` open it `closed` (so it takes nothing over) with the routine's or hook's title, roll it over at the same session max into a new linked session (`rollOverLinkedSession`, `previous_session_id`, the summary opening the new one), and it is read and chatted in with `?session_id=` like any session. 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 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 avatar 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; `?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
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "cobble",
|
||||
"version": "0.27.11",
|
||||
"version": "0.27.12",
|
||||
"module": "index.ts",
|
||||
"type": "module",
|
||||
"private": true,
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { BUN_SQLITE_COBBLE_COMPUTERS } from "@/db/types/db";
|
||||
import type { ComputerWithStatus } from "@/src/types";
|
||||
import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
|
||||
type Params = {
|
||||
@@ -30,10 +30,11 @@ export default async function grabBotComputers({
|
||||
bot_id,
|
||||
workspace_id,
|
||||
include_workspace_computers = true,
|
||||
}: Params): Promise<BUN_SQLITE_COBBLE_COMPUTERS[]> {
|
||||
}: Params): Promise<ComputerWithStatus[]> {
|
||||
if (workspace_id) {
|
||||
const res = await BunSQLite.sql<BUN_SQLITE_COBBLE_COMPUTERS>({
|
||||
sql: `SELECT c.* FROM computers c
|
||||
const res = await BunSQLite.sql<ComputerWithStatus>({
|
||||
sql: `SELECT c.*, co.status AS status FROM computers c
|
||||
LEFT JOIN containers co ON co.id = c.container_id
|
||||
JOIN workspace_computers wc ON wc.computer_id = c.id AND wc.workspace_id = ?
|
||||
JOIN workspaces w ON w.id = wc.workspace_id AND w.archived = 0
|
||||
WHERE (
|
||||
@@ -55,8 +56,9 @@ export default async function grabBotComputers({
|
||||
)`
|
||||
: "";
|
||||
|
||||
const res = await BunSQLite.sql<BUN_SQLITE_COBBLE_COMPUTERS>({
|
||||
sql: `SELECT c.* FROM computers c
|
||||
const res = await BunSQLite.sql<ComputerWithStatus>({
|
||||
sql: `SELECT c.*, co.status AS status FROM computers c
|
||||
LEFT JOIN containers co ON co.id = c.container_id
|
||||
WHERE (
|
||||
(SELECT kind FROM bots WHERE id = ?) = 'coordinator'
|
||||
OR c.id IN (SELECT computer_id FROM bot_computers WHERE bot_id = ?)
|
||||
|
||||
@@ -36,7 +36,7 @@ export function composerKnowledgebasesCopy({
|
||||
Icon: Library,
|
||||
one: "knowledgebase",
|
||||
many: "knowledgebases",
|
||||
empty_label: "Add knowledge",
|
||||
empty_label: "knowledge",
|
||||
title: `Knowledgebases ${bot_name} searches here`,
|
||||
some: "Before it answers, it searches these for passages that fit, and it can search them again while it works. Remove one to take it away, or add another below.",
|
||||
none: "It has none yet. Give it a knowledgebase below, or make one under Settings, under Knowledgebases.",
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { useState } from "react";
|
||||
import useServerEvent from "@/src/hooks/use-server-event";
|
||||
import type { BotUpdatedData } from "@/src/types";
|
||||
import type { BUN_SQLITE_COBBLE_COMPUTERS } from "@/db/types/db";
|
||||
import type { BotUpdatedData, ComputerWithStatus } from "@/src/types";
|
||||
import type { ComputerViewMode } from "@/src/dict/computer-dict";
|
||||
import setBotComputer from "../(functions)/set-bot-computer";
|
||||
|
||||
@@ -20,7 +19,7 @@ export type BotComputers = {
|
||||
/**
|
||||
* The bot's computers, the one it's on first.
|
||||
*/
|
||||
computers: BUN_SQLITE_COBBLE_COMPUTERS[];
|
||||
computers: ComputerWithStatus[];
|
||||
/**
|
||||
* The computer being switched to, while the switch runs.
|
||||
*/
|
||||
@@ -38,7 +37,7 @@ type Params = {
|
||||
* In a workspace, switching changes the workspace's default computer.
|
||||
*/
|
||||
workspace_id?: number | null;
|
||||
computers: BUN_SQLITE_COBBLE_COMPUTERS[];
|
||||
computers: ComputerWithStatus[];
|
||||
};
|
||||
|
||||
/**
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { renderToString } from "react-dom/server";
|
||||
import BotComputerPreview from "./bot-computer-preview";
|
||||
|
||||
function render() {
|
||||
return renderToString(
|
||||
<BotComputerPreview
|
||||
computer_id={7}
|
||||
name="Dev box"
|
||||
onOpen={() => {}}
|
||||
/>,
|
||||
);
|
||||
}
|
||||
|
||||
describe("BotComputerPreview", () => {
|
||||
test("it shows the computer's live browser, view only", () => {
|
||||
const html = render();
|
||||
|
||||
expect(html).toContain('src="/computers/7/desktop/"');
|
||||
expect(html).toContain("pointer-events-none");
|
||||
});
|
||||
|
||||
test("a click opens it in the viewer", () => {
|
||||
const html = render();
|
||||
|
||||
expect(html).toContain('aria-label="Open Dev box in the viewer"');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,43 @@
|
||||
import Button from "@moduletrace/twui/layout/Button";
|
||||
import Stack from "@moduletrace/twui/layout/Stack";
|
||||
import { Maximize2 } from "lucide-react";
|
||||
import ComputerViewFrame from "@/src/components/general/computer-view-frame";
|
||||
|
||||
type Props = {
|
||||
computer_id: number;
|
||||
name: string;
|
||||
/**
|
||||
* Opens the computer in the viewer, larger.
|
||||
*/
|
||||
onOpen: () => void;
|
||||
};
|
||||
|
||||
/**
|
||||
* The bot's computer live and small, in its panel's Tools tab, so the user
|
||||
* sees what it is doing without leaving the conversation. The frame takes no
|
||||
* pointer events, or the panel could not be scrolled past it; a click opens
|
||||
* the viewer instead.
|
||||
*/
|
||||
export default function BotComputerPreview({ computer_id, name, onOpen }: Props) {
|
||||
return (
|
||||
<Stack className="relative w-full h-44 mt-2 overflow-hidden rounded-default border border-solid border-hairline bg-sunken">
|
||||
<Stack className="absolute inset-0 pointer-events-none">
|
||||
<ComputerViewFrame computer_id={computer_id} name={name} mode="browser" />
|
||||
</Stack>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
color="text"
|
||||
title={`Open ${name} in the viewer`}
|
||||
aria-label={`Open ${name} in the viewer`}
|
||||
onClick={onOpen}
|
||||
className="absolute inset-0 w-full h-full p-0! rounded-none! focus-visible:ring-2 focus-visible:ring-ink"
|
||||
buttonContentProps={{ className: "absolute right-2 bottom-2" }}
|
||||
>
|
||||
<Stack className="p-1.5 rounded-default bg-paper/90 border border-solid border-hairline text-ink-secondary">
|
||||
<Maximize2 size={14} aria-hidden />
|
||||
</Stack>
|
||||
</Button>
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
@@ -1,11 +1,9 @@
|
||||
import Row from "@moduletrace/twui/layout/Row";
|
||||
import Stack from "@moduletrace/twui/layout/Stack";
|
||||
import BotAvatar from "@/src/components/general/bot-avatar";
|
||||
import type { BotFace } from "@/src/dict/bot-dict";
|
||||
import botStoneProps from "@/src/utils/bot-stone-props";
|
||||
import type { BotWithLastMessage } from "@/src/types";
|
||||
import type { MessageGroup } from "../(utils)/group-messages";
|
||||
import BotMessageLine from "./bot-message-line";
|
||||
import BotPanelTrigger from "./bot-panel-trigger";
|
||||
|
||||
type Props = {
|
||||
bot: BotWithLastMessage;
|
||||
@@ -23,13 +21,7 @@ type Props = {
|
||||
export default function BotMessageGroup({ bot, group, last_bot_id }: Props) {
|
||||
return (
|
||||
<Row className="w-full gap-3! flex-nowrap items-start">
|
||||
<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={28}
|
||||
className="-mt-1"
|
||||
/>
|
||||
<BotPanelTrigger bot={bot} size={28} className="-mt-1" />
|
||||
<Stack className="min-w-0 grow gap-1! items-start">
|
||||
{group.messages.map((message, index) => (
|
||||
<BotMessageLine
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { renderToString } from "react-dom/server";
|
||||
import type {
|
||||
AppContextObject,
|
||||
BotWithLastMessage,
|
||||
PagePropsType,
|
||||
} from "@/src/types";
|
||||
import { AppContext } from "@/src/pages/__root";
|
||||
import BotPanelTrigger from "./bot-panel-trigger";
|
||||
|
||||
function bot(overrides: Partial<BotWithLastMessage> = {}): BotWithLastMessage {
|
||||
return {
|
||||
id: 5,
|
||||
name: "Assistant",
|
||||
color: "#33c9cc",
|
||||
stone: "ember",
|
||||
face: "idle",
|
||||
...overrides,
|
||||
} as BotWithLastMessage;
|
||||
}
|
||||
|
||||
type RenderProps = {
|
||||
user_type: string;
|
||||
name?: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
function render({ user_type, name = "Assistant" }: RenderProps) {
|
||||
const pageProps: PagePropsType = {
|
||||
url: { pathname: "/admin/bots/5" } as PagePropsType["url"],
|
||||
user_types: [{ user_type }] as PagePropsType["user_types"],
|
||||
};
|
||||
|
||||
return renderToString(
|
||||
<AppContext.Provider value={{ pageProps } as AppContextObject}>
|
||||
<BotPanelTrigger bot={bot({ name })} size={28} />
|
||||
</AppContext.Provider>,
|
||||
);
|
||||
}
|
||||
|
||||
describe("BotPanelTrigger", () => {
|
||||
test("a member sees the stone alone", () => {
|
||||
const html = render({ user_type: "member" });
|
||||
|
||||
expect(html).toContain("<svg");
|
||||
expect(html).not.toContain("<button");
|
||||
expect(html).not.toContain('aria-haspopup="dialog"');
|
||||
});
|
||||
|
||||
test("a crew manager's stone is a button that opens the panel", () => {
|
||||
const html = render({ user_type: "super_admin" });
|
||||
|
||||
expect(html).toContain("<button");
|
||||
expect(html).toContain('aria-haspopup="dialog"');
|
||||
expect(html).toContain('aria-label="Edit Assistant"');
|
||||
});
|
||||
|
||||
test("an unnamed bot is called this bot in the button's label", () => {
|
||||
const html = render({ user_type: "admin", name: "" });
|
||||
|
||||
expect(html).toContain('aria-label="Edit This bot"');
|
||||
});
|
||||
});
|
||||
@@ -3,23 +3,40 @@
|
||||
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";
|
||||
import botStoneProps from "@/src/utils/bot-stone-props";
|
||||
import requestBotPanel from "@/src/utils/bot-panel-open-event";
|
||||
import type { BotWithLastMessage } from "@/src/types";
|
||||
import { AppContext } from "@/src/pages/__root";
|
||||
import canManageCrew from "@/src/utils/rbac/can-manage-crew";
|
||||
|
||||
type Props = {
|
||||
bot: BotWithLastMessage;
|
||||
on_open: () => void;
|
||||
/**
|
||||
* The header owns the panel, so its avatar opens it directly; a stone
|
||||
* beside a message asks the header for it instead.
|
||||
*/
|
||||
on_open?: () => void;
|
||||
/**
|
||||
* 35 beside the conversation's name, 28 beside a message.
|
||||
*/
|
||||
size?: number;
|
||||
className?: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* The avatar beside the conversation's name: opens the bot's panel to edit
|
||||
* it, for super admins and admins. Everyone else sees the avatar alone.
|
||||
* 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.
|
||||
*/
|
||||
export default function BotPanelTrigger({ bot, on_open }: Props) {
|
||||
export default function BotPanelTrigger({
|
||||
bot,
|
||||
on_open = () => requestBotPanel(),
|
||||
size = 35,
|
||||
className,
|
||||
}: Props) {
|
||||
const { pageProps } = useContext(AppContext);
|
||||
const name = bot.name || "This bot";
|
||||
const can_edit = canManageCrew({ user_types: pageProps?.user_types });
|
||||
@@ -29,12 +46,12 @@ export default function BotPanelTrigger({ bot, on_open }: Props) {
|
||||
image_media_id={bot.image_media_id}
|
||||
{...botStoneProps({ color: bot.color, stone: bot.stone, hue: bot.hue })}
|
||||
face={(bot.face || "idle") as BotFace}
|
||||
size={35}
|
||||
size={size}
|
||||
/>
|
||||
);
|
||||
|
||||
if (!can_edit) {
|
||||
return <Stack className="shrink-0">{avatar}</Stack>;
|
||||
return <Stack className={twMerge("shrink-0", className)}>{avatar}</Stack>;
|
||||
}
|
||||
|
||||
return (
|
||||
@@ -46,7 +63,10 @@ export default function BotPanelTrigger({ bot, on_open }: Props) {
|
||||
aria-label={`Edit ${name}`}
|
||||
aria-haspopup="dialog"
|
||||
onClick={on_open}
|
||||
className="shrink-0 p-0! rounded-default hover:opacity-80 focus-visible:ring-2 focus-visible:ring-ink focus-visible:ring-offset-2 focus-visible:ring-offset-paper"
|
||||
className={twMerge(
|
||||
"shrink-0 p-0! rounded-default hover:opacity-80 focus-visible:ring-2 focus-visible:ring-ink focus-visible:ring-offset-2 focus-visible:ring-offset-paper",
|
||||
className,
|
||||
)}
|
||||
>
|
||||
{avatar}
|
||||
</Button>
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { renderToString } from "react-dom/server";
|
||||
import type {
|
||||
AppContextObject,
|
||||
BotWithLastMessage,
|
||||
PagePropsType,
|
||||
} from "@/src/types";
|
||||
import { AppContext } from "@/src/pages/__root";
|
||||
import BotPanel from "./bot-panel";
|
||||
|
||||
const bot = {
|
||||
id: 5,
|
||||
name: "Assistant",
|
||||
color: "#33c9cc",
|
||||
stone: "ember",
|
||||
face: "idle",
|
||||
kind: "worker",
|
||||
} as BotWithLastMessage;
|
||||
|
||||
const pageProps: PagePropsType = {
|
||||
url: { pathname: "/admin/bots/5" } as PagePropsType["url"],
|
||||
user_types: [{ user_type: "super_admin" }] as PagePropsType["user_types"],
|
||||
};
|
||||
|
||||
function render() {
|
||||
return renderToString(
|
||||
<AppContext.Provider value={{ pageProps } as AppContextObject}>
|
||||
<BotPanel
|
||||
bot={bot}
|
||||
open={false}
|
||||
on_open={() => {}}
|
||||
on_close={() => {}}
|
||||
/>
|
||||
</AppContext.Provider>,
|
||||
);
|
||||
}
|
||||
|
||||
describe("BotPanel", () => {
|
||||
/**
|
||||
* Memory is edited under Settings: on its own it was one short editor in
|
||||
* a tab of its own.
|
||||
*/
|
||||
test("its memory sits in Settings, so it has two tabs", () => {
|
||||
const html = render();
|
||||
|
||||
expect(html.match(/role="tab"/g)?.length).toBe(2);
|
||||
expect(html).toContain(">Settings<");
|
||||
expect(html).toContain(">Tools<");
|
||||
expect(html).not.toContain(">Memory<");
|
||||
});
|
||||
});
|
||||
@@ -3,6 +3,7 @@
|
||||
import { useContext, useEffect, useState } from "react";
|
||||
import Button from "@moduletrace/twui/layout/Button";
|
||||
import H2 from "@moduletrace/twui/layout/H2";
|
||||
import Divider from "@moduletrace/twui/layout/Divider";
|
||||
import Row from "@moduletrace/twui/layout/Row";
|
||||
import Span from "@moduletrace/twui/layout/Span";
|
||||
import Stack from "@moduletrace/twui/layout/Stack";
|
||||
@@ -41,16 +42,16 @@ type Props = {
|
||||
on_close: () => void;
|
||||
};
|
||||
|
||||
type PanelTab = "settings" | "memory" | "tools";
|
||||
type PanelTab = "settings" | "tools";
|
||||
|
||||
/**
|
||||
* 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.
|
||||
* 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.
|
||||
*/
|
||||
export default function BotPanel({ bot, workspace, open, on_open, on_close }: Props) {
|
||||
const { pageProps } = useContext(AppContext);
|
||||
@@ -65,7 +66,7 @@ export default function BotPanel({ bot, workspace, open, on_open, on_close }: Pr
|
||||
const workspace_instructions = useWorkspaceBotInstructions({
|
||||
workspace_id,
|
||||
bot_id: Number(bot.id) || 0,
|
||||
enabled: open && can_edit && Boolean(workspace_id) && tab == "memory",
|
||||
enabled: open && can_edit && Boolean(workspace_id) && tab == "settings",
|
||||
});
|
||||
const memory_ready =
|
||||
system_prompt != undefined &&
|
||||
@@ -132,7 +133,6 @@ export default function BotPanel({ bot, workspace, open, on_open, on_close }: Pr
|
||||
className="shrink-0 gap-1! flex-nowrap items-center px-3 py-2 border-0 border-b border-solid border-hairline"
|
||||
>
|
||||
<TabButton title="Settings" active={tab == "settings"} onPick={() => setTab("settings")} />
|
||||
<TabButton title="Memory" active={tab == "memory"} onPick={() => setTab("memory")} />
|
||||
<TabButton title="Tools" active={tab == "tools"} onPick={() => setTab("tools")} />
|
||||
</Row>
|
||||
<Stack className="grow min-h-0 overflow-y-auto gap-1! items-stretch px-4 pt-4 pb-6">
|
||||
@@ -144,13 +144,38 @@ export default function BotPanel({ bot, workspace, open, on_open, on_close }: Pr
|
||||
: `${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}
|
||||
/>
|
||||
) : loaded_error ? (
|
||||
<>
|
||||
<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}
|
||||
/>
|
||||
) : 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">
|
||||
{loaded_error}
|
||||
{error}
|
||||
</Span>
|
||||
) : (
|
||||
<Stack className="w-full py-10 items-center">
|
||||
@@ -159,32 +184,6 @@ export default function BotPanel({ bot, workspace, open, on_open, on_close }: Pr
|
||||
)}
|
||||
</>
|
||||
) : null}
|
||||
{open && tab == "memory" ? (
|
||||
memory_ready ? (
|
||||
<>
|
||||
<Span className="text-[13px] leading-[18px] text-ink-secondary">
|
||||
{`What ${name} keeps in mind, and can add to itself as it works.`}
|
||||
</Span>
|
||||
<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}
|
||||
/>
|
||||
</>
|
||||
) : loaded_error ? (
|
||||
<Span className="py-6 text-[13px] leading-[18px] text-ink-secondary">
|
||||
{loaded_error}
|
||||
</Span>
|
||||
) : (
|
||||
<Stack className="w-full py-10 items-center">
|
||||
<Loading />
|
||||
</Stack>
|
||||
)
|
||||
) : null}
|
||||
{open && tab == "tools" ? (
|
||||
<BotToolsTab
|
||||
bot={bot}
|
||||
|
||||
@@ -5,12 +5,11 @@ import Stack from "@moduletrace/twui/layout/Stack";
|
||||
import { lazy, Suspense } from "react";
|
||||
import { twMerge } from "tailwind-merge";
|
||||
import { ArrowRight, Bug } from "lucide-react";
|
||||
import BotAvatar from "@/src/components/general/bot-avatar";
|
||||
import botStoneProps from "@/src/utils/bot-stone-props";
|
||||
import { BotGettingMessageStatusLine } from "@/src/dict/bot-queue-dict";
|
||||
import type { BotWithLastMessage, PagePropsType } from "@/src/types";
|
||||
import conversationHref from "@/src/utils/conversation-href";
|
||||
import botBusyState from "../(utils)/bot-busy-state";
|
||||
import BotPanelTrigger from "./bot-panel-trigger";
|
||||
import StopBotButton from "./stop-bot-button";
|
||||
|
||||
/**
|
||||
@@ -118,10 +117,8 @@ export default function BotThinkingRow({
|
||||
return (
|
||||
<Stack className="w-full gap-0! items-stretch">
|
||||
<Row role="status" className="w-full gap-3! flex-nowrap items-center">
|
||||
<BotAvatar
|
||||
image_media_id={bot.image_media_id}
|
||||
{...botStoneProps({ color: bot.color, stone: bot.stone, hue: bot.hue })}
|
||||
face={waiting ? "asleep" : "working"}
|
||||
<BotPanelTrigger
|
||||
bot={{ ...bot, face: waiting ? "asleep" : "working" }}
|
||||
size={28}
|
||||
/>
|
||||
<Stack className="min-w-0 grow gap-0! items-start">
|
||||
|
||||
@@ -2,16 +2,14 @@ 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 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 BotComputerPreview from "./bot-computer-preview";
|
||||
import BotPanelSection from "./bot-panel-section";
|
||||
import ComposerBrowserButton from "./composer-browser-button";
|
||||
import ComposerConnectorsSection from "./composer-connectors-section";
|
||||
@@ -39,17 +37,29 @@ type Props = {
|
||||
* 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) {
|
||||
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 {
|
||||
computers,
|
||||
switching_id,
|
||||
error: computer_error,
|
||||
switchComputer,
|
||||
openComputer,
|
||||
} = useContext(BotComputersContext);
|
||||
|
||||
const is_knowledge = (item: { kind: string }) => item.kind == "knowledgebase";
|
||||
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)),
|
||||
@@ -60,6 +70,9 @@ export default function BotToolsTab({ bot, workspace_id, initial, has_browsers,
|
||||
};
|
||||
const tools_copy = composerToolsCopy({ bot_name });
|
||||
const knowledge_copy = composerKnowledgebasesCopy({ bot_name });
|
||||
const current = computers[0];
|
||||
/** Only a running computer has a screen to show. */
|
||||
const preview_id = current?.status == "running" ? Number(current.id) || 0 : 0;
|
||||
|
||||
return (
|
||||
<Stack className="w-full gap-4! items-stretch">
|
||||
@@ -79,10 +92,14 @@ export default function BotToolsTab({ bot, workspace_id, initial, has_browsers,
|
||||
computer={computer}
|
||||
current={index == 0}
|
||||
onPick={async () => {
|
||||
await switchComputer({ computer_id: computer.id || 0 });
|
||||
await switchComputer({
|
||||
computer_id: computer.id || 0,
|
||||
});
|
||||
}}
|
||||
onOpen={() => {
|
||||
openComputer({ computer_id: computer.id || 0 });
|
||||
openComputer({
|
||||
computer_id: computer.id || 0,
|
||||
});
|
||||
}}
|
||||
/>
|
||||
))}
|
||||
@@ -94,14 +111,25 @@ export default function BotToolsTab({ bot, workspace_id, initial, has_browsers,
|
||||
)}
|
||||
{switching_id ? (
|
||||
<Span className="mt-2 text-[13px] leading-[18px] text-ink-secondary">
|
||||
Switching its computer. The tasks it has open finish where they are.
|
||||
Switching its computer. The tasks it has open finish
|
||||
where they are.
|
||||
</Span>
|
||||
) : null}
|
||||
{computer_error ? (
|
||||
<Span role="alert" className="mt-2 text-[13px] leading-[18px] text-ink-secondary">
|
||||
<Span
|
||||
role="alert"
|
||||
className="mt-2 text-[13px] leading-[18px] text-ink-secondary"
|
||||
>
|
||||
{computer_error}
|
||||
</Span>
|
||||
) : null}
|
||||
{preview_id ? (
|
||||
<BotComputerPreview
|
||||
computer_id={preview_id}
|
||||
name={current?.name || `Computer ${preview_id}`}
|
||||
onOpen={() => openComputer({ computer_id: preview_id })}
|
||||
/>
|
||||
) : null}
|
||||
</BotPanelSection>
|
||||
|
||||
<BotPanelSection title="Tools" description={tools_copy.some}>
|
||||
@@ -137,7 +165,10 @@ export default function BotToolsTab({ bot, workspace_id, initial, has_browsers,
|
||||
) : null}
|
||||
</BotPanelSection>
|
||||
|
||||
<BotPanelSection title="Knowledgebases" description={knowledge_copy.some}>
|
||||
<BotPanelSection
|
||||
title="Knowledgebases"
|
||||
description={knowledge_copy.some}
|
||||
>
|
||||
<ComposerExtensionsList
|
||||
id="panel-add-knowledgebase"
|
||||
label={knowledge_copy.title}
|
||||
@@ -154,10 +185,13 @@ export default function BotToolsTab({ bot, workspace_id, initial, has_browsers,
|
||||
</BotPanelSection>
|
||||
|
||||
{extensions.status?.error ? (
|
||||
<Span role="alert" className="text-[13px] leading-[18px] text-ink-secondary">
|
||||
<Span
|
||||
role="alert"
|
||||
className="text-[13px] leading-[18px] text-ink-secondary"
|
||||
>
|
||||
{extensions.status.msg}
|
||||
</Span>
|
||||
) : null}
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -148,7 +148,9 @@ export default function ComposerToolsModal({
|
||||
<TriggerIcon size={12} aria-hidden />
|
||||
</Row>
|
||||
}
|
||||
className="shrink-0 gap-1! px-2! py-0.5! text-[12px] leading-4 text-ink-secondary"
|
||||
className={twMerge(
|
||||
"shrink-0 gap-1! px-2! py-0.5! text-[12px] leading-4 text-ink-secondary",
|
||||
)}
|
||||
>
|
||||
{label}
|
||||
</Button>
|
||||
|
||||
@@ -8,7 +8,10 @@ import type {
|
||||
ConnectorAppIcon,
|
||||
} from "@/src/types";
|
||||
import { BotComputersContext } from "../(data)/bot-computers-context";
|
||||
import { composerKnowledgebasesCopy, composerToolsCopy } from "../(data)/composer-extensions-copy";
|
||||
import {
|
||||
composerKnowledgebasesCopy,
|
||||
composerToolsCopy,
|
||||
} from "../(data)/composer-extensions-copy";
|
||||
import ComposerBrowserButton from "./composer-browser-button";
|
||||
import ComposerComputerButton from "./composer-computer-button";
|
||||
import ComposerPlanButton from "./composer-plan-button";
|
||||
@@ -57,7 +60,8 @@ export default function ComposerTools({
|
||||
|
||||
const { computers } = useContext(BotComputersContext);
|
||||
|
||||
const is_knowledge = (item: { kind: string }) => item.kind == "knowledgebase";
|
||||
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)),
|
||||
@@ -83,14 +87,22 @@ export default function ComposerTools({
|
||||
}, [initial?.connector_apps]);
|
||||
|
||||
const has_tools = Boolean(
|
||||
tools.attached.length || connector_count || (extensions.can_manage && tools.addable.length),
|
||||
tools.attached.length ||
|
||||
connector_count ||
|
||||
(extensions.can_manage && tools.addable.length),
|
||||
);
|
||||
const has_knowledge = Boolean(
|
||||
knowledge.attached.length ||
|
||||
(extensions.can_manage && knowledge.addable.length),
|
||||
);
|
||||
const has_knowledge = Boolean(knowledge.attached.length || (extensions.can_manage && knowledge.addable.length));
|
||||
|
||||
return (
|
||||
<Row className="w-full max-w-container mx-auto gap-1.5! items-center px-3 md:px-6 pb-3 -mt-3">
|
||||
{on_toggle_plan_mode ? (
|
||||
<ComposerPlanButton plan_mode={Boolean(plan_mode)} onToggle={on_toggle_plan_mode} />
|
||||
<ComposerPlanButton
|
||||
plan_mode={Boolean(plan_mode)}
|
||||
onToggle={on_toggle_plan_mode}
|
||||
/>
|
||||
) : null}
|
||||
|
||||
{has_tools ? (
|
||||
@@ -124,14 +136,12 @@ export default function ComposerTools({
|
||||
/>
|
||||
) : null}
|
||||
|
||||
{(has_tools || has_knowledge) && (has_browsers || computers.length) ? (
|
||||
<Span className="-mr-2 opacity-40">
|
||||
<Dot size={20} />
|
||||
</Span>
|
||||
) : null}
|
||||
|
||||
{has_browsers ? (
|
||||
<ComposerBrowserButton bot_id={bot.id || 0} bot_name={bot_name} workspace_id={workspace_id} />
|
||||
<ComposerBrowserButton
|
||||
bot_id={bot.id || 0}
|
||||
bot_name={bot_name}
|
||||
workspace_id={workspace_id}
|
||||
/>
|
||||
) : null}
|
||||
|
||||
<ComposerComputerButton />
|
||||
|
||||
@@ -4,11 +4,10 @@ import Span from "@moduletrace/twui/layout/Span";
|
||||
import Stack from "@moduletrace/twui/layout/Stack";
|
||||
import { useContext, useState } from "react";
|
||||
import { RotateCw } from "lucide-react";
|
||||
import BotAvatar from "@/src/components/general/bot-avatar";
|
||||
import botStoneProps from "@/src/utils/bot-stone-props";
|
||||
import type { BotMessageWithAttachments, BotWithLastMessage } from "@/src/types";
|
||||
import { BotMessageActionsContext } from "../(data)/message-actions-context";
|
||||
import retryBotReply from "../(functions)/retry-bot-reply";
|
||||
import BotPanelTrigger from "./bot-panel-trigger";
|
||||
|
||||
type Props = {
|
||||
bot: BotWithLastMessage;
|
||||
@@ -47,12 +46,7 @@ export default function UnansweredReplyRow({ bot, message }: Props) {
|
||||
|
||||
return (
|
||||
<Row role="status" className="w-full gap-3! flex-nowrap items-center">
|
||||
<BotAvatar
|
||||
image_media_id={bot.image_media_id}
|
||||
{...botStoneProps({ color: bot.color, stone: bot.stone, hue: bot.hue })}
|
||||
face={bot.face}
|
||||
size={28}
|
||||
/>
|
||||
<BotPanelTrigger bot={bot} size={28} />
|
||||
<Stack className="min-w-0 grow gap-0! items-start">
|
||||
<Span className="text-sm leading-5 text-ink-secondary">
|
||||
{error || "No answer came."}
|
||||
|
||||
Reference in New Issue
Block a user