Compare commits

...
2 Commits
Author SHA1 Message Date
tben 1660857a3c Bump version to 0.28.15
CI / check (push) Waiting to run
Release image / image (release) Waiting to run
Release image / computer-image (release) Waiting to run
2026-11-26 15:34:39 +01:00
tben ccbd3efddf Let the composer's slash commands reach everything the header menu offers 2026-11-26 15:34:39 +01:00
21 changed files with 515 additions and 79 deletions
+1 -1
View File
@@ -95,7 +95,7 @@ Enables SQLite foreign keys (`enableForeignKeys`), `bunextInit()`, `ensureDocker
- **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.
- **Composer:** Tiptap editor reading/writing markdown, drafts in `localStorage`, `@` bots / `#` workspaces written as `[bot:ID]`/`[workspace:ID]`. Enter sends (Mod+Enter in lists/code). **Up/Down walk the user's own earlier messages** (`use-composer-history`, from `composerHistoryTexts` over the thread's user messages, never a crew message): Up recalls the newest from an empty input and older ones from there, Down comes forward again and back to what was being typed, a keystroke takes the input back, an open mention menu or a selection keeps the arrows. A `/` lists the session commands above the input (`composer-commands`): `/new` starts a fresh session, `/continue` carries this one into a new one with a summary, and `/clear` deletes this session and starts a fresh one after a confirm; Enter runs the highlighted one (a message exactly matching a command can't be sent) and a failed command comes back in the input with the server's reason. A clear button (X, disabled while the input is empty) empties the text without sending, keeping the quote and the picked files. Ordered lists are read back from digit markers only (`composer-ordered-list`): Tiptap also takes `a.`/`i.`, so a recalled "Ok. Do that." came back as item 401 with "Ok." eaten. `@tiptap/react` needs `use-sync-external-store`; the app ships an ESM stand-in in `packages/use-sync-external-store-esm` (file dependency + override; the Dockerfile copies `packages/` before `bun install`).
- **Composer:** Tiptap editor reading/writing markdown, drafts in `localStorage`, `@` bots / `#` workspaces written as `[bot:ID]`/`[workspace:ID]`. Enter sends (Mod+Enter in lists/code). **Up/Down walk the user's own earlier messages** (`use-composer-history`, from `composerHistoryTexts` over the thread's user messages, never a crew message): Up recalls the newest from an empty input and older ones from there, Down comes forward again and back to what was being typed, a keystroke takes the input back, an open mention menu or a selection keeps the arrows. A `/` lists the commands above the input (`composer-commands`, an ordered registry of `{name, description, action}`): the session trio `/new` (fresh session), `/continue` (carries this one into a new one with a summary) and `/clear` (deletes this session and starts a fresh one after a confirm) post and reload; `/sessions` `/files` `/tasks` `/routines` `/hooks` `/computers` `/models` `/instructions` open the header menu's modals (a `cobble:composer-command` event, `src/utils/composer-command-event.ts`; each menu-mounted modal listens through `useOpenOnCommand` with a `command` prop, so the header's duplicate Models/Computers rows never answer); `/panel` slides the bot panel in, `/copy` puts the session's markdown on the clipboard (`(functions)/copy-conversation.ts`, shared with the menu item), `/stop` pulls the plug through `StopBotContext` (refused with a line when nothing runs), `/settings` goes to the bot's settings page. Which ones a user sees is `visibleComposerCommands`, mirroring the menu's gates (read-only loses `/hooks`; `/instructions` needs a workspace and a crew manager; `/settings` follows the menu: pass-through for the coordinator, crew managers for a worker). Enter runs the highlighted command (a message exactly matching a command can't be sent), a failed command comes back in the input with the server's reason, and anything not exactly a command (`/etc/hosts ...`) sends as a message. A clear button (X, disabled while the input is empty) empties the text without sending, keeping the quote and the picked files. Ordered lists are read back from digit markers only (`composer-ordered-list`): Tiptap also takes `a.`/`i.`, so a recalled "Ok. Do that." came back as item 401 with "Ok." eaten. `@tiptap/react` needs `use-sync-external-store`; the app ships an ESM stand-in in `packages/use-sync-external-store-esm` (file dependency + override; the Dockerfile copies `packages/` before `bun install`).
- **Rendering:** markdown via `react-markdown` + `remark-gfm`, raw HTML never rendered, component map in `[bot_id]/(data)/message-markdown-components.tsx`. Inline refs, all linked by `link-computer-refs.ts` and rendered by chips in `(partials)/`: `[bot:ID]`, `[workspace:ID]`, `[computer:ID]`, `[file:ID]` (a saved file), `[folder:<volume>:<owner>:<path>]` (opens `FolderPreviewModal`, the files browser's listing over the chat, files opening their own preview; a modified click or its Open in Files goes to `/admin/files`), `[take-over:ID:mode]` (the card that opens the computer on its own line), `[secret:ID]` (masked env, Reveal/Copy), `[suggestion:ID]` (its suggested next steps, buttons that fill the composer), `[plan:ID]` (a plan, as its card: steps, the one being worked, and the buttons to approve or change them), `[graphic:ID]` (a bot graphic, framed inline), `[task:ID]` (a tracker task, opening `TaskDetailModal`), `[setting:<section>:<field>]` (`SettingRefChip`: the exact Settings > General page and field to change, from `src/dict/general-settings-dict.ts`; every group of that page also has its own page under `/admin/settings/general/<section>`, and its fields are anchors). A plan, questions, a proposal, a hook proposal, a secret request and a take-over show in full under the message, as the card the user acts on, never behind a chip: they are blocks, so `MarkdownParagraph` (`(partials)/markdown-paragraph.tsx`) lifts those refs out of the paragraph they were written in (`isCardRefHref` in `(utils)/card-ref-href.ts`), which React would otherwise refuse inside a `p`. Parsers in `src/utils/*-ref.ts`. A chip reads its own row through `(utils)/ref-view-loader.ts`, which keeps only what it read: a read that failed or hung is retried (`AppData.BotRefViewRetryDelaysMs`, each after `BotRefViewTimeoutMs`), so a chip pushed with a run shows its steps or card without a reload, and a chip whose card the user just decided (`primeRefView`) tells every other chip naming the same ref, since a thread can carry the same card twice and the others otherwise went on saying "Waiting for you" until a reload (`subscribeRefView`; `useBotPlan` instead re-reads on `server:bot-plan`). Anywhere else that renders bot-written markdown with `MessageMarkdownComponents` (a workspace's context on its dashboard, a task's description and notes through `TaskMarkdown`) runs it through `linkComputerRefs` and provides `CrewBotsContext`/`CrewWorkspacesContext` too. A ref quoted alone in a code span still links; one inside longer code stays literal (`linkComputerRefs` splits out code first). A file chip opens a file from another bot's folder for a user who reaches that folder (`userReachesFileScope`, the same rule as its bytes), so answers another bot passed on keep working.
- **Message images:** a bot message shows the images it's about under its text (`MessageImages` in `(partials)/`, on `BotMessageLine` and `CrewMessageLine`): its image attachments plus every image `[file:ID]` it names (`liveFileRefIds`, which keeps the renderer's code rules), deduped when a named file is also attached (`file_id`). Each is a `MessageAttachment` thumbnail opening the shared `FilePreviewModal`; in a thread its gallery is the whole conversation (`sessionImageGallery` + `SessionGalleryContext` from `MessageThread`): every image in the session, bot and user, in message order, deduped by URL, falling back to the message's own images outside a thread. Non-image files and unreachable refs show nothing. Named files resolve through `useBotFile`/`useReferencedFiles` (page props first, then the cached `api/admin/bots/files` read shared with `FileRefChip`). A thumbnail URL serves the original when no smaller copy was made (`mediaServeWritePath`), since bot files keep no thumbnail.
- **Task chips:** which tracker tasks a bot message is about is the app's record, not the bot's word: a run's task tools report each task they touch (`onTask`: `list_tasks` with `task_id`, `create_task`, `update_task`, `delete_task`, `delegate_task`'s hand-over), plus a handed-over job's `tracker_task_id`, into `bot_messages.task_ids` (also on its failure notice and its report relayed to the requester). The thread shows them under the message (`MessageTaskChips`) with title and status, read per viewer and only for tasks they reach (`grabMessagesTasks`; pushes carry them through `withMessageTasks`).
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "cobble",
"version": "0.28.14",
"version": "0.28.15",
"module": "index.ts",
"type": "module",
"private": true,
@@ -1,4 +1,5 @@
import ContinueSessionButton from "./continue-session-button";
import useOpenOnCommand from "@/src/hooks/use-open-on-command";
import useShownSession from "@/src/hooks/use-shown-session";
import conversationHref from "@/src/utils/conversation-href";
import {
@@ -37,6 +38,8 @@ type Props = {
* Runs as it opens, e.g. closing the menu it was opened from.
*/
on_open?: () => void;
/** The composer command that opens this modal (`/sessions`). */
command?: string;
};
/**
@@ -52,8 +55,11 @@ export default function BotSessionsModal({
target,
target_wrapper_props,
on_open,
command,
}: Props) {
const [open, setOpen] = useState(false);
useOpenOnCommand({ command, on_fire: () => setOpen(true) });
const on_screen = useShownSession({ bot_id: Number(bot.id), workspace_id });
const sessions = useBotSessions({
bot_id: Number(bot.id),
+35
View File
@@ -0,0 +1,35 @@
import { useEffect, useRef } from "react";
import { ComposerCommandEvent } from "@/src/utils/composer-command-event";
/**
* Answers a composer command by name: while `command` is set, `on_fire` runs
* when the composer dispatches that command. Components mounted behind a
* closed dropdown still hear it (twui keeps the content mounted), so the
* composer can open any of them. Pass `command` only to the instance the
* commands should drive.
*/
export default function useOpenOnCommand({
command,
on_fire,
}: {
command?: string;
on_fire: () => void;
}) {
const fire = useRef(on_fire);
fire.current = on_fire;
useEffect(() => {
if (!command) return;
function listen(event: Event) {
if ((event as CustomEvent).detail != command) return;
fire.current();
}
window.addEventListener(ComposerCommandEvent, listen);
return () => window.removeEventListener(ComposerCommandEvent, listen);
}, [command]);
}
@@ -1,15 +1,44 @@
/**
* The composer's slash commands: what `/new`, `/continue` and `/clear` do
* to the conversation's session, and how the list above the input
* describes them.
* The composer's slash commands. The session trio (`/new`, `/continue`,
* `/clear`) acts on the conversation's session and reloads the page; the
* modal ones open what the conversation header's menu opens (the list loads
* then, so nothing costs anything until picked); `/copy` and `/stop` do the
* menu's own two actions from the input; `/panel` slides the bot panel in
* and `/settings` goes to the bot's settings page. Which ones a user sees is
* `visibleComposerCommands`, mirroring the menu's own gates.
*/
export type ComposerCommandAction =
| "session"
| "modal"
| "copy"
| "stop"
| "panel"
| "link";
export type ComposerCommand = {
name: "new" | "continue" | "clear";
name: string;
description: string;
action: ComposerCommandAction;
/** For a session command: the API the composer posts to. */
path?: "new-session" | "continue-session" | "delete-session";
/** For a link command: where it goes. */
href?: (params: { bot_id: number }) => string;
};
export const ComposerCommands: ComposerCommand[] = [
{ name: "new", description: "Start a fresh session" },
{ name: "continue", description: "Carry this conversation into a new session, with a summary" },
{ name: "clear", description: "Delete this session and start a new one" },
];
{ name: "new", description: "Start a fresh session", action: "session", path: "new-session" },
{ name: "continue", description: "Carry this conversation into a new session, with a summary", action: "session", path: "continue-session" },
{ name: "clear", description: "Delete this session and start a new one", action: "session", path: "delete-session" },
{ name: "sessions", description: "List this bot's chat sessions", action: "modal" },
{ name: "files", description: "Browse the bot's files", action: "modal" },
{ name: "tasks", description: "See the tasks this bot works on", action: "modal" },
{ name: "routines", description: "See the routines this bot runs", action: "modal" },
{ name: "hooks", description: "See the hooks that wake this bot", action: "modal" },
{ name: "computers", description: "See the computers this bot works on", action: "modal" },
{ name: "models", description: "See and change the models this bot runs on", action: "modal" },
{ name: "instructions", description: "Edit what this bot does in this workspace", action: "modal" },
{ name: "panel", description: "Open the bot's panel", action: "panel" },
{ name: "copy", description: "Copy this session as markdown", action: "copy" },
{ name: "stop", description: "Stop the bot's queued and running work", action: "stop" },
{ name: "settings", description: "Open this bot's settings", action: "link", href: ({ bot_id }) => `/admin/settings/bots/${bot_id}` },
];
@@ -0,0 +1,34 @@
import conversationMarkdown from "@/src/utils/conversation-markdown";
import copyPendingText from "@/src/utils/copy-pending-text";
import fetchConversationExport from "./fetch-conversation-export";
/**
* Puts the conversation's active session on the clipboard as one markdown
* document. The clipboard write starts at once with a pending
* `ClipboardItem`, so it keeps the user's gesture (the menu's click, or the
* Enter keypress that ran `/copy`) even though the export is still
* fetching. Returns nothing on success, or the reason to show.
*/
export default async function copyConversation({
bot_id,
workspace_id,
}: {
bot_id: number;
workspace_id?: number | null;
}): Promise<string | null> {
const markdown = fetchConversationExport({ bot_id, workspace_id }).then((res) => {
if (!res?.success || !res.singleRes) {
throw new Error(res?.msg || "Couldn't load the chat.");
}
return conversationMarkdown({ conversation: res.singleRes, now: Date.now() });
});
try {
const worked = await copyPendingText({ text: markdown });
return worked ? null : "Couldn't copy the chat to the clipboard.";
} catch (error: unknown) {
return error instanceof Error ? error.message : "Couldn't copy the chat.";
}
}
@@ -1,4 +1,5 @@
import { useContext, useEffect, useState } from "react";
import useOpenOnCommand from "@/src/hooks/use-open-on-command";
import Modal from "@moduletrace/twui/elements/Modal";
import H2 from "@moduletrace/twui/layout/H2";
import Span from "@moduletrace/twui/layout/Span";
@@ -36,6 +37,8 @@ type Props = {
* (its text) instead of an icon: clicking it opens the modal.
*/
meta_text?: string;
/** The composer command that opens this modal (`/computers`). */
command?: string;
};
/**
@@ -51,11 +54,14 @@ export default function BotComputersModal({
menu_hint,
on_open,
meta_text,
command,
}: Props) {
const { computers, switching_id, error, switchComputer, openComputer } =
useContext(BotComputersContext);
const [open, setOpen] = useState(false);
useOpenOnCommand({ command, on_fire: () => setOpen(true) });
const current = computers[0];
useEffect(() => {
@@ -1,4 +1,5 @@
import { useContext, useEffect, useMemo, useState } from "react";
import useOpenOnCommand from "@/src/hooks/use-open-on-command";
import Modal from "@moduletrace/twui/elements/Modal";
import H2 from "@moduletrace/twui/layout/H2";
import Span from "@moduletrace/twui/layout/Span";
@@ -27,6 +28,8 @@ type Props = {
*/
menu?: boolean;
on_open?: () => void;
/** The composer command that opens this modal (`/files`). */
command?: string;
};
/**
@@ -36,9 +39,11 @@ type Props = {
* as the user types) goes through the same endpoint, so the page props
* stay small.
*/
export default function BotFilesModal({ bot, workspace, menu, on_open }: Props) {
export default function BotFilesModal({ bot, workspace, menu, on_open, command }: Props) {
const { pageProps } = useContext(AppContext);
const [open, setOpen] = useState(false);
useOpenOnCommand({ command, on_fire: () => setOpen(true) });
const [search, setSearch] = useState("");
const query = useDebouncedValue({ value: search.trim() });
const [busy_id, setBusyId] = useState<number>();
@@ -1,4 +1,5 @@
import { useContext, useEffect, useState } from "react";
import useOpenOnCommand from "@/src/hooks/use-open-on-command";
import Modal from "@moduletrace/twui/elements/Modal";
import H2 from "@moduletrace/twui/layout/H2";
import Row from "@moduletrace/twui/layout/Row";
@@ -37,6 +38,8 @@ type Props = {
bot: BotWithLastMessage;
workspace?: BUN_SQLITE_COBBLE_WORKSPACES | null;
on_open?: () => void;
/** The composer command that opens this modal (`/hooks`). */
command?: string;
};
/**
@@ -47,9 +50,11 @@ type Props = {
* their own; bots propose new hooks and changes from the chat
* (`propose_hook`), which the user confirms there.
*/
export default function BotHooksModal({ bot, workspace, on_open }: Props) {
export default function BotHooksModal({ bot, workspace, on_open, command }: Props) {
const { pageProps } = useContext(AppContext);
const [open, set_open] = useState(false);
useOpenOnCommand({ command, on_fire: () => set_open(true) });
const [view, set_view] = useState<View>();
const [opened, set_opened] = useState<BotHookWithNames>();
const [busy, set_busy] = useState(false);
@@ -1,4 +1,5 @@
import { useContext, useEffect, useState } from "react";
import useOpenOnCommand from "@/src/hooks/use-open-on-command";
import Modal from "@moduletrace/twui/elements/Modal";
import H2 from "@moduletrace/twui/layout/H2";
import Span from "@moduletrace/twui/layout/Span";
@@ -41,6 +42,8 @@ type Props = {
*/
meta_text?: string;
onSaved: (harnesses: HarnessOverview[]) => void;
/** The composer command that opens this modal (`/models`). */
command?: string;
};
/**
@@ -63,9 +66,12 @@ export default function BotModelsModal({
on_open,
meta_text,
onSaved,
command,
}: Props) {
const { pageProps } = useContext(AppContext);
const [open, setOpen] = useState(false);
useOpenOnCommand({ command, on_fire: () => setOpen(true) });
/**
* The pointer or focus reached the icon: start loading before the click.
*/
@@ -1,4 +1,5 @@
import { useEffect, useState } from "react";
import useOpenOnCommand from "@/src/hooks/use-open-on-command";
import Modal from "@moduletrace/twui/elements/Modal";
import H2 from "@moduletrace/twui/layout/H2";
import Row from "@moduletrace/twui/layout/Row";
@@ -28,6 +29,8 @@ type Props = {
*/
menu?: boolean;
on_open?: () => void;
/** The composer command that opens this modal (`/routines`). */
command?: string;
};
/**
@@ -37,8 +40,10 @@ type Props = {
* page's props stay small. The user pauses, resumes, edits, hands over
* and deletes their own; the bot makes them when asked in chat.
*/
export default function BotRoutinesModal({ bot, workspace, menu, on_open }: Props) {
export default function BotRoutinesModal({ bot, workspace, menu, on_open, command }: Props) {
const [open, set_open] = useState(false);
useOpenOnCommand({ command, on_fire: () => set_open(true) });
const [editing, set_editing] = useState<CronJobWithNames>();
const [handing, set_handing] = useState<CronJobWithNames>();
const [busy, set_busy] = useState(false);
@@ -16,6 +16,7 @@ import TaskListItem from "@/src/components/general/task-list-item";
import { AppContext } from "@/src/pages/__root";
import canManageCrew from "@/src/utils/rbac/can-manage-crew";
import useOpenOnCommand from "@/src/hooks/use-open-on-command";
import useBotTasks from "../(hooks)/use-bot-tasks";
import HeaderMenuItem from "./header-menu-item";
@@ -27,6 +28,11 @@ type Props = {
*/
menu?: boolean;
on_open?: () => void;
/**
* The composer command that opens this modal (`/tasks`): only the
* instance named by the header menu listens.
*/
command?: string;
};
/**
@@ -36,9 +42,11 @@ type Props = {
* and deletes; a card opens the task in a modal of its own with everything
* about it.
*/
export default function BotTasksModal({ bot, workspace, menu, on_open }: Props) {
export default function BotTasksModal({ bot, workspace, menu, on_open, command }: Props) {
const { pageProps } = useContext(AppContext);
const [open, setOpen] = useState(false);
useOpenOnCommand({ command, on_fire: () => setOpen(true) });
const [adding, set_adding] = useState(false);
const [open_task, set_open_task] = useState<TaskWithNames | null>(null);
const [busy, set_busy] = useState(false);
@@ -1,4 +1,5 @@
import { useEffect, useState } from "react";
import useOpenOnCommand from "@/src/hooks/use-open-on-command";
import Modal from "@moduletrace/twui/elements/Modal";
import Loading from "@moduletrace/twui/elements/Loading";
import H2 from "@moduletrace/twui/layout/H2";
@@ -15,6 +16,8 @@ type Props = {
bot: BotWithLastMessage;
workspace: BUN_SQLITE_COBBLE_WORKSPACES;
on_open?: () => void;
/** The composer command that opens this modal (`/instructions`). */
command?: string;
};
/**
@@ -23,8 +26,10 @@ type Props = {
* here (crew managers). Both load when it opens, so it shows the bot's
* own latest edits.
*/
export default function BotWorkspaceInstructionsModal({ bot, workspace, on_open }: Props) {
export default function BotWorkspaceInstructionsModal({ bot, workspace, on_open, command }: Props) {
const [open, setOpen] = useState(false);
useOpenOnCommand({ command, on_fire: () => setOpen(true) });
const name = bot.name || "This bot";
const place = workspace.name || "this workspace";
const { instructions, error } = useWorkspaceBotInstructions({
@@ -19,6 +19,12 @@ import type { ComposerCommand } from "../(data)/composer-commands";
import { CrewBotsContext } from "../(data)/crew-bots-context";
import { CrewWorkspacesContext } from "../(data)/crew-workspaces-context";
import postSessionApi from "@/src/functions/frontend/post-session-api";
import { AppContext } from "@/src/pages/__root";
import dispatchComposerCommand from "@/src/utils/composer-command-event";
import requestBotPanel from "@/src/utils/bot-panel-open-event";
import copyConversation from "../(functions)/copy-conversation";
import visibleComposerCommands from "../(utils)/visible-composer-commands";
import { StopBotContext } from "../(data)/stop-bot-context";
import sendBotMessage from "../(functions)/send-bot-message";
import transcribeVoice from "../(functions)/transcribe-voice";
import useComposerAttachments from "../(hooks)/use-composer-attachments";
@@ -161,12 +167,22 @@ export default function Composer({
const online = useOnlineStatus();
const bots = useContext(CrewBotsContext);
const workspaces = useContext(CrewWorkspacesContext);
const { pageProps } = useContext(AppContext);
const { stop, can_stop } = useContext(StopBotContext);
const send_ref = useRef<() => void>(() => {});
/**
* The slash commands the text is asking for, the one highlighted, and
* a command still on its way (`/continue` writes a summary).
* The slash commands the text is asking for, from the ones this user
* gets here, the one highlighted, and a command still on its way
* (`/continue` writes a summary).
*/
const commands = composerCommandMatches({ text });
const commands = composerCommandMatches({
text,
commands: visibleComposerCommands({
user_types: pageProps?.user_types,
bot_kind: bot.kind,
workspace_id,
}),
});
const [command_index, set_command_index] = useState(0);
const [command_busy, set_command_busy] = useState(false);
@@ -380,15 +396,77 @@ export default function Composer({
}
/**
* `/new`, `/continue` and `/clear` act on the conversation's session
* rather than being sent, and the page lands on the session they
* leave. `/clear` destroys messages, so it asks first. A failure puts
* the command back in the input with the reason under it (a session
* with a run in progress can't be deleted).
* A command acts on the page rather than being sent: the session trio
* posts and lands on the session it leaves (`/clear` destroys messages,
* so it asks first); the modal commands open what the header menu's
* rows open; `/copy` puts the session on the clipboard and `/stop`
* pulls the bot's plug; `/panel` slides the bot panel in; `/settings`
* goes to the settings page. A failure puts the command back in the
* input with the reason under it (a session with a run in progress
* can't be deleted, a bot with nothing running has nothing to stop).
*/
async function runCommand({ command }: { command: ComposerCommand }) {
if (sending.current) return;
setError(undefined);
const lost_text = text.trim();
const restore = () => {
if (!latest_text.current.trim()) {
setText(lost_text);
input.setMarkdown({ markdown: lost_text });
}
};
// Nothing to pull the plug on: say so and leave the command in the
// input (this is before the clear, so there is nothing to restore).
if (command.action == "stop" && !can_stop) {
setError(
`Nothing of ${bot.name || "the bot"}'s is running for you.`,
);
return;
}
if (command.action != "session") {
setText("");
history.reset();
input.clear();
switch (command.action) {
case "modal":
dispatchComposerCommand({ name: command.name });
return;
case "panel":
requestBotPanel();
return;
case "link":
if (command.href) {
window.location.assign(
command.href({ bot_id: Number(bot.id) }),
);
}
return;
case "copy": {
const failure = await copyConversation({
bot_id: Number(bot.id),
workspace_id,
});
if (failure) {
setError(failure);
restore();
}
return;
}
case "stop":
void stop();
return;
}
}
if (command.name == "clear") {
if (!session_id) {
setError("The session is still loading. Try again in a moment.");
@@ -406,21 +484,13 @@ export default function Composer({
sending.current = true;
set_command_busy(true);
setError(undefined);
const lost_text = text.trim();
setText("");
history.reset();
input.clear();
const res = await postSessionApi({
path:
command.name == "new"
? "new-session"
: command.name == "continue"
? "continue-session"
: "delete-session",
path: command.path || "new-session",
body:
command.name == "clear"
? { session_id }
@@ -437,11 +507,7 @@ export default function Composer({
sending.current = false;
set_command_busy(false);
setError(res?.msg || "That didn't work.");
if (!latest_text.current.trim()) {
setText(lost_text);
input.setMarkdown({ markdown: lost_text });
}
restore();
}
/**
@@ -120,6 +120,7 @@ export default function ConversationHeaderMenu({
<Stack className="w-full gap-0! items-stretch">
<BotSessionsModal
bot={bot}
command="sessions"
workspace_id={workspace?.id || null}
has_other_unread={has_other_unread}
target={
@@ -165,24 +166,28 @@ export default function ConversationHeaderMenu({
menu
bot={bot}
workspace={workspace}
command="files"
on_open={on_open}
/>
<BotTasksModal
menu
bot={bot}
workspace={workspace}
command="tasks"
on_open={on_open}
/>
<BotRoutinesModal
menu
bot={bot}
workspace={workspace}
command="routines"
on_open={on_open}
/>
{can_make_hooks ? (
<BotHooksModal
bot={bot}
workspace={workspace}
command="hooks"
on_open={on_open}
/>
) : null}
@@ -195,6 +200,7 @@ export default function ConversationHeaderMenu({
: null
}
menu_hint={computer_name}
command="computers"
on_open={on_open}
/>
<BotModelsModal
@@ -203,6 +209,7 @@ export default function ConversationHeaderMenu({
bot={bot}
workspace={workspace}
menu_hint={model_name}
command="models"
on_open={on_open}
onSaved={on_model_saved}
/>
@@ -210,6 +217,7 @@ export default function ConversationHeaderMenu({
<BotWorkspaceInstructionsModal
bot={bot}
workspace={workspace}
command="instructions"
on_open={on_open}
/>
) : null}
@@ -1,9 +1,7 @@
import { useEffect, useRef, useState } from "react";
import { Check, ClipboardCopy } from "lucide-react";
import { AppData } from "@/src/data/app-data";
import conversationMarkdown from "@/src/utils/conversation-markdown";
import copyPendingText from "@/src/utils/copy-pending-text";
import fetchConversationExport from "../(functions)/fetch-conversation-export";
import copyConversation from "../(functions)/copy-conversation";
import HeaderMenuItem from "./header-menu-item";
type Props = {
@@ -17,8 +15,8 @@ type Props = {
/**
* The header menu's "Copy chat": puts the session on screen on the
* clipboard as one markdown document (`conversationMarkdown`). The row shows a check for a moment, then the
* menu closes.
* clipboard as one markdown document (`copyConversation`). The row shows a
* check for a moment, then the menu closes.
*/
export default function CopyChatMenuItem({ bot_id, workspace_id, on_open }: Props) {
const [loading, setLoading] = useState(false);
@@ -34,33 +32,20 @@ export default function CopyChatMenuItem({ bot_id, workspace_id, on_open }: Prop
const copy = async () => {
setLoading(true);
const markdown = fetchConversationExport({ bot_id, workspace_id }).then((res) => {
if (!res?.success || !res.singleRes) {
throw new Error(res?.msg || "Couldn't load the chat.");
}
const failure = await copyConversation({ bot_id, workspace_id });
return conversationMarkdown({ conversation: res.singleRes, now: Date.now() });
});
setLoading(false);
try {
const worked = await copyPendingText({ text: markdown });
setLoading(false);
if (!worked) {
window.alert("Couldn't copy the chat to the clipboard.");
return;
}
setCopied(true);
timeout.current = setTimeout(() => {
setCopied(false);
on_open?.();
}, AppData.CopyConfirmationMs);
} catch (error: unknown) {
setLoading(false);
window.alert(error instanceof Error ? error.message : "Couldn't copy the chat.");
if (failure) {
window.alert(failure);
return;
}
setCopied(true);
timeout.current = setTimeout(() => {
setCopied(false);
on_open?.();
}, AppData.CopyConfirmationMs);
};
return (
@@ -1,20 +1,49 @@
import { describe, expect, test } from "bun:test";
import composerCommandMatches from "./composer-command-matches";
import { ComposerCommands, type ComposerCommand } from "../(data)/composer-commands";
const names = ({ text }: { text: string }) =>
composerCommandMatches({ text }).map((command) => command.name);
const names = ({
text,
commands,
}: {
text: string;
commands?: ComposerCommand[];
}) => composerCommandMatches({ text, commands }).map((command) => command.name);
describe("composerCommandMatches", () => {
test("a lone slash offers every command", () => {
expect(names({ text: "/" })).toEqual(["new", "continue", "clear"]);
test("a lone slash offers every command, in the registry's order", () => {
expect(names({ text: "/" })).toEqual(
ComposerCommands.map((command) => command.name),
);
});
test("narrows by the letters typed", () => {
expect(names({ text: "/c" })).toEqual(["continue", "clear"]);
expect(names({ text: "/c" })).toEqual([
"continue",
"clear",
"computers",
"copy",
]);
expect(names({ text: "/s" })).toEqual(["sessions", "stop", "settings"]);
expect(names({ text: "/ne" })).toEqual(["new"]);
expect(names({ text: "/new" })).toEqual(["new"]);
});
test("only the commands the caller says this user gets", () => {
const session_trio = ComposerCommands.slice(0, 3);
expect(names({ text: "/", commands: session_trio })).toEqual([
"new",
"continue",
"clear",
]);
expect(names({ text: "/c", commands: session_trio })).toEqual([
"continue",
"clear",
]);
expect(names({ text: "/hooks", commands: session_trio })).toEqual([]);
});
test("ignores the case and the space around it", () => {
expect(names({ text: " /NEW " })).toEqual(["new"]);
});
@@ -26,4 +55,4 @@ describe("composerCommandMatches", () => {
expect(names({ text: "message" })).toEqual([]);
expect(names({ text: "" })).toEqual([]);
});
});
});
@@ -1,17 +1,23 @@
import { ComposerCommands, type ComposerCommand } from "../(data)/composer-commands";
/**
* The slash commands the composer's text is asking for: all of them while
* it is just `/`, then those the letters typed so far begin. Anything else
* (`/etc/hosts`, a command followed by more words) is an ordinary message
* and matches none.
* The slash commands the composer's text is asking for, from the list the
* caller says this user gets: all of them while it is just `/`, then those
* the letters typed so far begin. Anything else (`/etc/hosts`, a command
* followed by more words) is an ordinary message and matches none.
*/
export default function composerCommandMatches({ text }: { text: string }): ComposerCommand[] {
export default function composerCommandMatches({
text,
commands = ComposerCommands,
}: {
text: string;
commands?: ComposerCommand[];
}): ComposerCommand[] {
const match = /^\/([a-z]*)$/i.exec(text.trim());
if (!match) return [];
const typed = (match[1] ?? "").toLowerCase();
return ComposerCommands.filter((command) => command.name.startsWith(typed));
}
return commands.filter((command) => command.name.startsWith(typed));
}
@@ -0,0 +1,144 @@
import { describe, expect, test } from "bun:test";
import visibleComposerCommands from "./visible-composer-commands";
import type { BUN_SQLITE_COBBLE_USER_TYPES } from "@/db/types/db";
const as = (...user_types: string[]) =>
user_types.map((user_type) => ({ user_type })) as BUN_SQLITE_COBBLE_USER_TYPES[];
const names = (params: Parameters<typeof visibleComposerCommands>[0]) =>
visibleComposerCommands(params).map((command) => command.name);
const held = ({
params,
name,
}: {
params: Parameters<typeof visibleComposerCommands>[0];
name: string;
}) => names(params).includes(name);
describe("visibleComposerCommands", () => {
test("the session trio and the plain views are for everyone", () => {
const member = {
user_types: as("member"),
bot_kind: "worker" as const,
};
for (const name of [
"new",
"continue",
"clear",
"sessions",
"files",
"tasks",
"routines",
"computers",
"models",
"panel",
"copy",
"stop",
]) {
expect(held({ params: member, name })).toBe(true);
}
});
test("a read-only user does not get the hooks that wake a bot", () => {
expect(
held({
params: {
user_types: as("read_only"),
bot_kind: "worker",
},
name: "hooks",
}),
).toBe(false);
expect(
held({
params: { user_types: as("member"), bot_kind: "worker" },
name: "hooks",
}),
).toBe(true);
});
test("instructions need a workspace and a crew manager", () => {
expect(
held({
params: {
user_types: as("member"),
bot_kind: "worker",
workspace_id: 4,
},
name: "instructions",
}),
).toBe(false);
expect(
held({
params: {
user_types: as("admin"),
bot_kind: "worker",
workspace_id: null,
},
name: "instructions",
}),
).toBe(false);
expect(
held({
params: {
user_types: as("admin"),
bot_kind: "worker",
workspace_id: 4,
},
name: "instructions",
}),
).toBe(true);
});
test("a member gets no settings on either kind of bot", () => {
expect(
held({
params: { user_types: as("member"), bot_kind: "worker" },
name: "settings",
}),
).toBe(false);
expect(
held({
params: { user_types: as("member"), bot_kind: "coordinator" },
name: "settings",
}),
).toBe(false);
});
test("the coordinator's settings follow the menu: pass-through only", () => {
expect(
held({
params: { user_types: as("admin"), bot_kind: "coordinator" },
name: "settings",
}),
).toBe(false);
expect(
held({
params: {
user_types: as("super_admin"),
bot_kind: "coordinator",
},
name: "settings",
}),
).toBe(true);
});
test("a worker's settings are for crew managers", () => {
expect(
held({
params: { user_types: as("admin"), bot_kind: "worker" },
name: "settings",
}),
).toBe(true);
});
test("no user types at all is treated as a member", () => {
const listed = names({ user_types: null, bot_kind: "worker" });
expect(listed).not.toContain("settings");
expect(listed).not.toContain("instructions");
expect(listed).toContain("hooks");
});
});
@@ -0,0 +1,39 @@
import type { BUN_SQLITE_COBBLE_USER_TYPES } from "@/db/types/db";
import { ComposerCommands, type ComposerCommand } from "../(data)/composer-commands";
import canManageCrew from "@/src/utils/rbac/can-manage-crew";
import isPassThroughUser from "@/src/utils/rbac/is-pass-through-user";
import isReadOnlyUser from "@/src/utils/rbac/is-read-only-user";
type Params = {
user_types?: BUN_SQLITE_COBBLE_USER_TYPES[] | null;
bot_kind?: string | null;
workspace_id?: number | null;
};
/**
* The commands this user gets in this conversation, with exactly the gates
* the header menu puts on its rows: hooks start work, so a read-only user
* doesn't get them; instructions are per workspace and crew managers only;
* settings follow the menu (the coordinator's page only for pass-through
* actors, a worker's for crew managers).
*/
export default function visibleComposerCommands({
user_types,
bot_kind,
workspace_id,
}: Params): ComposerCommand[] {
const can_make_hooks = !isReadOnlyUser({ user_types });
const can_edit_here = Boolean(workspace_id && canManageCrew({ user_types }));
const can_open_settings =
bot_kind == "coordinator"
? isPassThroughUser({ user_types })
: canManageCrew({ user_types });
return ComposerCommands.filter((command) => {
if (command.name == "hooks") return can_make_hooks;
if (command.name == "instructions") return can_edit_here;
if (command.name == "settings") return can_open_settings;
return true;
});
}
+15
View File
@@ -0,0 +1,15 @@
export const ComposerCommandEvent = "cobble:composer-command";
/**
* Asks the page to do what a composer command names (open one of the header
* menu's modals): the composer sends it, and the mounted component listening
* for its own name answers. Like the bot panel's open event, a page without
* a listener simply ignores it.
*/
export default function dispatchComposerCommand({ name }: { name: string }) {
if (typeof window == "undefined") return;
window.dispatchEvent(
new CustomEvent(ComposerCommandEvent, { detail: name }),
);
}