Compare commits

...
9 Commits
Author SHA1 Message Date
tben 15a74cacde v0.28.5
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
2026-11-25 04:52:19 +01:00
tben 67395500b5 Show a person's and a bot's picture at the size it is set up at
A picture preview was drawn whatever the size asked for, so setting up a
photo meant judging a thumbnail. BotAvatar passes its size through to the
image, UserAvatar gains xl and xxl, and the profile photo and the bot form's
preview use them.
2026-11-25 04:52:19 +01:00
tben 95c8ee7c39 v0.28.4
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
2026-11-25 04:37:37 +01:00
tben edd451342e Give the routine form's brief room to read 2026-11-25 04:37:37 +01:00
tben b635eeb543 Keep the hook form's buttons from being clipped away by the modal 2026-11-25 04:36:05 +01:00
tben 4cadde55e2 Size the bot form's preview picture from the form
The preview takes an avatar size, so the new-bot form shows it at 100px
rather than the 56px it uses in a list.
2026-11-25 04:32:23 +01:00
tben e000b09898 Let a user delete a chat session
The sessions modal now deletes a session and everything in it, refused
while a run is open in it. Deleting the active one gives the conversation
a fresh session instead of leaving it pointing at a removed one, and the
list rows truncate their summary to the row's width.
2026-11-25 04:32:19 +01:00
tben 4852c39ad3 Scope a workspace run to its workspace
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
A bot working in a workspace could reach every task in every other
workspace it belongs to, and every routine and hook it has anywhere.
botTaskScopesSql now takes the run's workspace and reaches only its
tasks: a coordinator or that workspace's admin all of them, a worker its
own and the workspace-wide ones there. grabTasks, grabRunTask and every
task tool pass it through, and create_task refuses to place a task in
another workspace from inside one.

Routines and hooks follow the same rule through the existing place
filters: list, update, delete, pause, search and read are narrowed to the
run's workspace, the coordinator's list showing every bot's there. A run
in the bot's own chat keeps its old reach, and update/delete schedule
keep no place filter when the run has none, since null there means "own
chat only".

v0.28.3
2026-11-25 03:52:51 +01:00
tben bf533330b1 Hold the drawer's computer preview until asked, and tell SSH computers apart
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
The Tools section streamed a bot's computer screen the moment the drawer
opened. It now shows the same block with a line and a Preview button, and
streams only once that is clicked.

Also show the bot's memory of the viewer in the drawer's settings tab, space
the panel fields so their labels stop overlapping, and draw an SSH computer
with a server icon instead of the container's monitor.
2026-11-24 16:50:51 +01:00
67 changed files with 827 additions and 227 deletions
+1 -1
View File
@@ -89,7 +89,7 @@ Enables SQLite foreign keys (`enableForeignKeys`), `bunextInit()`, `ensureDocker
### Bots, sessions, chat
- **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 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.
- **Sessions:** one thread per user per bot in its own chat plus one per workspace; split into `bot_sessions` (rollover at the app setting `bot_session_max_messages`, default `AppData.BotSessionMaxMessages`, via `grabBotSessionMaxMessages`; titled and summarised by `name-bot-session.ts` from the session's opening after a reply or a task (a session with no user message, work handed to the bot, is named from the bot's own messages; `grabSessionOpening`; `grabBotMessages` reads the latest; each opening message is cut to `AppData.BotSessionNameMessageChars`, so a pasted brief of tens of thousands of characters costs one naming call, not a second copy of itself), summary carried into the next session only when they're linked by `previous_session_id`, which only a carry-over sets; older implicit links are cleared at boot by `clearImplicitSessionLinks`). New session (`startBotSession`) and a conversation with no active session always start fresh. The rollover carries over like the bot does (`rollOverBotSession` -> `continueBotSession`, falling back to the stored summary; kept for the next message while a job is open in the full session or there's nothing to carry), inside send-message, so the user's message lands under the summary. Sending a message and answering a question card both hold the conversation's lock (`conversationLock`, `src/functions/backend/db/bot-sessions/conversation-lock.ts`, a `createKeyLock` per user, bot and workspace), since two sends 78 ms apart both read the same full session and one then wrote into the session the other had just closed; when its own rollover writes nothing, `rollOverBotSession` returns the conversation's current active session rather than the stale one. The composer holds its send until it answers (`sending`), so a double tap sends once. An open plan follows its conversation across a rollover (`carry-over-bot-session` moves `bot_plans.session_id`). A routine and a hook each keep a thread of their own, marked by `bot_sessions.routine_id` and `hook_id`, with the routine's or hook's title, rolled over at the same session max into a new linked session (`rollOverLinkedSession`, `previous_session_id`, the summary opening the new one), and read and chatted in with `?session_id=` like any session. `ensureRoutineSession`/`ensureHookSession` open it `closed` and then make it the conversation's active session (`activateBotSession`, a routine and a non-silent hook alike), so a run takes the chat over instead of landing in a sidebar; a silent hook is the opt-out (`bot_hooks.silent`). A deleted routine or hook detaches its thread (`routine_id`/`hook_id` set to null) and keeps the messages; a silent hook's thread is the one exception to being followed (`followedSessionSql`: no rail row, no unread, no push, no face change) **until the user writes in it**: a human message takes the thread from the hook (`adoptHookSession`, from `insertUserMessage`, so a chat message and a question's answer alike), so the thread is theirs from then on and the hook opens a new one next time, while a hook that isn't silent makes its thread the conversation's active session for its run. Helpers in `src/functions/backend/db/bot-sessions/`. Job results land in the job's own session, even after it closes, except a reply that called `continue_in_new_session` (`carryOverBotSession`; the menu's and sessions modal's Continue in new session does the same through `continueBotSession`, the model writing title and summary, refused while a job is open in the session): its summary is kept on the closed session and opens the new one as a bot message (`carried_from_session_id`), the job's `session_id` moves so the answer follows, the new session is titled by the bot then (it has no first exchange to be named from), and the old one can never be reopened (`reopenBotSession` refuses; a thread showing it swaps its composer for a link to the new one). Session lists (rail, sessions modal) reopen a session on click, as before; a carried-over one can't be, so it opens to read (`?session_id=`, `conversationHref`). The sessions modal deletes a session too (`delete-session` -> `deleteBotSession` -> `deleteSessionRows`), refused while a run is open in it; deleting the active one starts the conversation a fresh session. The page tells them which session it shows (`announceShownSession` -> `useShownSession`): they reload, mark it Current (greyed out; without `?session_id=` the active one is), list it even when it's older than the rail's latest, and the active row then leads back. From half the session length the reply prompt suggests moving on (`longSessionNote`). Earlier sessions never enter the prompt (only the last one's summary): the thread can open them above a session (`useOlderMessages.loadPrevious`, a divider per session, quote and reply as usual), and replies get `search_past_sessions`/`read_past_session` (scoped to that user, bot and place, never the current session) when the conversation has any.
- **Coordinator:** exactly one, the super admin's alone, created idempotently by `ensureCoordinatorBot`. Default prompt `src/data/coordinator-system-prompt.ts`, backfilled only when empty.
- **Routes:** `/admin/bots` reopens the last visited bot's own chat (cookie `cobble_last_visited_bot_id`, `<bot>` or `<bot>:<workspace>`; the landing uses only the bot) if still reachable, else coordinator (super admin) / latest bot / first workspace / empty. Workspace and conversation pages record the visit per user (`recordWorkspaceVisit`/`workspace_user_visits`, `recordBotVisit`/`bot_user_visits`) and the rail lists both latest visited first (`last_visited_at`, `orderByLastVisit`; recorded before the crew is read, so the conversation opened is already on top in that render, and its bot leads whatever the visits say (`pinned_id`); a workspace nobody visited yet ranks by its creation, so a new one leads); it never decides the landing. Settings and the rail pages get the cookie's conversation, workspace included, as root prop `last_conversation` (`grabLastConversation`, access-checked, only on those paths: `isPagesRailPath`), shown above their rail list as the way back (`RailLastConversation`). `/admin/bots/[bot_id]` conversation (header, thread and composer at 760px, the bot panel (`BotPanel`) sliding in from the right when its stone (beside the name or beside its messages in the thread) or its name is tapped, or a phone swipes that way, over the conversation rather than taking width; `?session_id=` opens another of the user's sessions there: a closed one is reopened, except a carried-over one, which shows with `SessionMovedBar` instead of the composer, pointing where the conversation went on); `/admin/bots/[bot_id]/models`; `/admin/workspaces/[id]` dashboard; `/admin/workspaces/[id]/bots/[bot_id]` same conversation scoped to the workspace.
- **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.
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "cobble",
"version": "0.28.1",
"version": "0.28.5",
"module": "index.ts",
"type": "module",
"private": true,
+6 -1
View File
@@ -31,7 +31,11 @@ type Props = ComponentProps<typeof BotStone> & {
* never a circle, so it isn't mistaken for a person), else its stone. Its
* colour still marks it everywhere else, e.g. the unread dot.
*/
export default function BotAvatar({ image_media_id, src: picked, ...stone }: Props) {
export default function BotAvatar({
image_media_id,
src: picked,
...stone
}: Props) {
const saved = profileImageUrls({ media_id: image_media_id });
const thumbnail_src = picked || saved.thumbnail_src;
const src = picked || saved.src;
@@ -49,6 +53,7 @@ export default function BotAvatar({ image_media_id, src: picked, ...stone }: Pro
BotAvatarSizeClasses[size] || BotAvatarSizeClasses[32],
stone.className,
)}
size={size}
/>
);
}
+65 -48
View File
@@ -2,16 +2,23 @@ import Button from "@moduletrace/twui/layout/Button";
import Row from "@moduletrace/twui/layout/Row";
import Span from "@moduletrace/twui/layout/Span";
import Stack from "@moduletrace/twui/layout/Stack";
import { Trash2 } from "lucide-react";
import { twMerge } from "tailwind-merge";
import type { BotSessionListItem } from "@/src/types";
import messagePreview from "@/src/utils/message-preview";
import relativeTime from "@/src/utils/relative-time";
import RowIconButton from "./row-icon-button";
type Props = {
session: BotSessionListItem;
loading?: boolean;
disabled?: boolean;
onOpen: () => void;
/**
* Deletes the session and its messages; left out where sessions can't be
* deleted (the rail).
*/
onDelete?: () => void;
/**
* The session the page shows (`?session_id=`, else the active one):
* marked Current and greyed out.
@@ -25,7 +32,7 @@ type Props = {
* recent. The one on screen is Current (greyed out); any other opens on
* click (reopening a closed one, going back to the active one).
*/
export default function BotSessionRow({ session, loading, disabled, onOpen, current }: Props) {
export default function BotSessionRow({ session, loading, disabled, onOpen, onDelete, current }: Props) {
const preview = session.summary || session.last_message_text || "";
const at = session.last_activity_at || session.created_at;
const tag = session.routine_title
@@ -35,56 +42,66 @@ export default function BotSessionRow({ session, loading, disabled, onOpen, curr
: null;
return (
<Button
title={
current
? "This is the session on screen"
: session.status == "active"
? "Go back to the active session"
: `Reopen "${session.title || "Untitled"}"`
}
type="button"
variant="ghost"
color="text"
loading={loading}
disabled={current || disabled}
onClick={onOpen}
buttonContentProps={{ className: "w-full min-w-0 flex-nowrap" }}
className={twMerge(
"w-full justify-start! items-start! gap-0! px-3! py-2.5! rounded-default text-left text-ink dark:text-ink hover:bg-ink/5 hover:dark:bg-ink/5 focus-visible:ring-2 focus-visible:ring-ink",
current && "bg-sunken hover:bg-sunken hover:dark:bg-sunken opacity-100!",
)}
>
<Stack className="w-full min-w-0 gap-0.5! items-stretch">
<Row className="w-full gap-2! flex-nowrap items-center">
<Span
className={twMerge(
"grow min-w-0 truncate text-sm font-bold leading-5",
current ? "text-ink-secondary" : "text-ink",
)}
>
{session.title || "Untitled session"}
</Span>
{tag ? (
<Row className="w-full flex-nowrap items-center gap-1">
<Button
title={
current
? "This is the session on screen"
: session.status == "active"
? "Go back to the active session"
: `Reopen "${session.title || "Untitled"}"`
}
type="button"
variant="ghost"
color="text"
loading={loading}
disabled={current || disabled}
onClick={onOpen}
buttonContentProps={{ className: "w-full min-w-0 flex-nowrap" }}
className={twMerge(
"grow min-w-0 justify-start! items-start! gap-0! px-3! py-2.5! rounded-default text-left text-ink dark:text-ink hover:bg-ink/5 hover:dark:bg-ink/5 focus-visible:ring-2 focus-visible:ring-ink",
current && "bg-sunken hover:bg-sunken hover:dark:bg-sunken opacity-100!",
)}
>
<Stack className="w-full min-w-0 gap-0.5! items-stretch">
<Row className="w-full gap-2! flex-nowrap items-center">
<Span
title={tag.title}
className="shrink-0 rounded-default bg-ink/5 px-1.5 text-[11px] leading-4 text-ink-secondary"
className={twMerge(
"grow min-w-0 truncate text-sm font-bold leading-5",
current ? "text-ink-secondary" : "text-ink",
)}
>
{tag.label}
{session.title || "Untitled session"}
</Span>
) : null}
{session.unread && !current ? (
<Span className="shrink-0 text-[11px] font-bold leading-4 text-ink">New</Span>
) : null}
<Span className="shrink-0 text-[11px] leading-4 text-ink-secondary">
{current ? "Current" : at ? relativeTime({ at: Number(at) }) : ""}
{tag ? (
<Span
title={tag.title}
className="shrink-0 rounded-default bg-ink/5 px-1.5 text-[11px] leading-4 text-ink-secondary"
>
{tag.label}
</Span>
) : null}
{session.unread && !current ? (
<Span className="shrink-0 text-[11px] font-bold leading-4 text-ink">New</Span>
) : null}
<Span className="shrink-0 text-[11px] leading-4 text-ink-secondary">
{current ? "Current" : at ? relativeTime({ at: Number(at) }) : ""}
</Span>
</Row>
<Span className="w-full truncate text-xs leading-4 text-ink-secondary">
{`${session.message_count} message${session.message_count == 1 ? "" : "s"}`}
{preview ? ` · ${messagePreview({ text: preview })}` : ""}
</Span>
</Row>
<Span className="w-full truncate text-xs leading-4 text-ink-secondary">
{`${session.message_count} message${session.message_count == 1 ? "" : "s"}`}
{preview ? ` · ${messagePreview({ text: preview })}` : ""}
</Span>
</Stack>
</Button>
</Stack>
</Button>
{onDelete ? (
<RowIconButton
icon={Trash2}
title={`Delete "${session.title || "Untitled"}"`}
disabled={Boolean(loading) || disabled}
onClick={onDelete}
/>
) : null}
</Row>
);
}
+37 -17
View File
@@ -43,7 +43,7 @@ type Props = {
* The sessions icon (or another target) that opens a conversation's
* sessions. A conversation is split into sessions so a bot's context never
* grows without bound; this lists them, searches them, starts a fresh one,
* or reopens an old one to carry on.
* reopens an old one to carry on, or deletes one.
*/
export default function BotSessionsModal({
bot,
@@ -139,22 +139,42 @@ export default function BotSessionsModal({
</Span>
) : null}
<Stack className="w-full mt-2 max-h-[60vh] overflow-y-auto gap-0! items-stretch">
{sessions.sessions.map((session) => (
<BotSessionRow
key={session.id}
session={session}
loading={sessions.busy_id == session.id}
disabled={Boolean(sessions.busy_id)}
current={on_screen?.id ? on_screen.id == session.id : session.status == "active"}
onOpen={() =>
session.status == "active"
? window.location.assign(conversationHref({ bot_id: Number(bot.id), workspace_id }))
: sessions.reopenSession({
session_id: Number(session.id),
})
}
/>
))}
{sessions.sessions.map((session) => {
const is_current = on_screen?.id
? on_screen.id == session.id
: session.status == "active";
return (
<BotSessionRow
key={session.id}
session={session}
loading={sessions.busy_id == session.id}
disabled={Boolean(sessions.busy_id)}
current={is_current}
onOpen={() =>
session.status == "active"
? window.location.assign(conversationHref({ bot_id: Number(bot.id), workspace_id }))
: sessions.reopenSession({
session_id: Number(session.id),
})
}
onDelete={() => {
if (
!window.confirm(
`Delete "${session.title || "this session"}"? Its messages go with it, and this can't be undone.`,
)
) {
return;
}
sessions.deleteSession({
session_id: Number(session.id),
current: is_current,
});
}}
/>
);
})}
{sessions.loading ? (
<LoadingBlock className="w-full h-[300px]" />
) : !sessions.sessions.length ? (
+16 -1
View File
@@ -22,6 +22,11 @@ type Props = {
* Its height, e.g. `h-24`.
*/
className?: string;
/**
* Shows the text without letting it be edited; `onChange` is then never
* called.
*/
readOnly?: boolean;
onChange: (value: string) => void;
};
@@ -30,7 +35,16 @@ type Props = {
* under it. Loads the editor's scripts when it first shows
* (`loadAceScripts`).
*/
export default function CodeEditor({ title, content, mode, placeholder, info, className, onChange }: Props) {
export default function CodeEditor({
title,
content,
mode,
placeholder,
info,
className,
readOnly,
onChange,
}: Props) {
/**
* The editor keeps the handler it was created with; this keeps it
* calling the latest one.
@@ -50,6 +64,7 @@ export default function CodeEditor({ title, content, mode, placeholder, info, cl
content={content}
mode={mode}
placeholder={placeholder}
readOnly={readOnly}
fontSize="13px"
delay={0}
wrapperProps={{ className: twMerge("h-40", className) }}
+12 -5
View File
@@ -1,9 +1,16 @@
import { Monitor } from "lucide-react";
import computerIcon from "@/src/utils/computer-icon";
import IconTile from "./icon-tile";
/**
* A computer's avatar in lists: the monitor icon on a small tile.
* A computer's avatar in lists: its icon (`computerIcon`) on a small tile.
*/
export default function ComputerIconTile() {
return <IconTile Icon={Monitor} />;
}
export default function ComputerIconTile({
connection,
}: {
/**
* `ssh` wears a server instead of a monitor.
*/
connection?: string | null;
}) {
return <IconTile Icon={computerIcon({ connection })} />;
}
+2 -1
View File
@@ -193,8 +193,9 @@ export default function HookForm({
};
return (
// shrink-0: a capped flex column (the modal) would squash the form and clip the buttons away.
<Form
className="w-full gap-4! items-stretch pt-4 overflow-hidden px-1"
className="w-full shrink-0 gap-4! items-stretch pt-4 overflow-hidden px-1"
onSubmit={submit}
>
<Input
+8 -4
View File
@@ -34,7 +34,7 @@ export default function ImagePickField({
const input_ref = useRef<HTMLInputElement>(null);
return (
<Row className="w-full gap-4! flex-nowrap items-center">
<Row className="w-full gap-4! items-center">
{preview}
<Stack className="gap-2! min-w-0">
<Row className="gap-2!">
@@ -60,14 +60,17 @@ export default function ImagePickField({
disabled={disabled || loading}
onClick={() => {
onRemove();
if (input_ref.current) input_ref.current.value = "";
if (input_ref.current)
input_ref.current.value = "";
}}
>
Remove
</Button>
) : null}
</Row>
<Span className="text-[13px] leading-[18px] text-ink-secondary">{note}</Span>
<Span className="text-[13px] leading-[18px] text-ink-secondary">
{note}
</Span>
</Stack>
{/*
* Raw on purpose: twui `Input` writes `value` on change, which
@@ -85,7 +88,8 @@ export default function ImagePickField({
if (!e.target.files?.[0]) return;
imageInputToBase64({ imageInput: e.target }).then((res) => {
if (res?.imageBase64Full) onPick({ data_url: res.imageBase64Full });
if (res?.imageBase64Full)
onPick({ data_url: res.imageBase64Full });
});
}}
/>
+10 -3
View File
@@ -19,7 +19,9 @@ type Props = {
export default function RoutineForm({ cron_job, onCancel, onSaved }: Props) {
const [title, setTitle] = useState(cron_job.title || "");
const [schedule, setSchedule] = useState(cron_job.schedule || "");
const [instructions, setInstructions] = useState(cron_job.instructions || "");
const [instructions, setInstructions] = useState(
cron_job.instructions || "",
);
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string>();
@@ -69,13 +71,18 @@ export default function RoutineForm({ cron_job, onCancel, onSaved }: Props) {
/>
<CodeEditor
mode="markdown"
className="h-40"
className="h-[300px]"
title="Brief"
content={instructions}
info="What the bot does at every run, and how it knows it's done."
onChange={(value) => setInstructions(value)}
/>
<AddFormActions submit_label="Save" loading={loading} error={error} onCancel={onCancel} />
<AddFormActions
submit_label="Save"
loading={loading}
error={error}
onCancel={onCancel}
/>
</Form>
);
}
+5 -1
View File
@@ -12,6 +12,8 @@ const UserAvatarSizeClasses = {
sm: "size-6 text-[11px]",
md: "size-8 text-xs",
lg: "size-16 text-lg",
xl: "size-24 text-xl",
xxl: "size-32 text-2xl",
} as const;
type Props = {
@@ -47,7 +49,9 @@ export default function UserAvatar({
size = "md",
className,
}: Props) {
const photo = person?.profile_media_id ? grabMediaURL({ user: person }) : {};
const photo = person?.profile_media_id
? grabMediaURL({ user: person })
: {};
const src = passed_src || photo.media_thumbnail_url || photo.media_url;
const img_err_src = passed_src ? passed_err_src : photo.media_url;
const initials = passed_initials || userInitials(person || {});
@@ -9,18 +9,30 @@ type Params = {
* Only a call to this bot's hooks.
*/
bot_id?: number | string | null;
/**
* Only a call to a hook that runs in this workspace.
*/
workspace_id?: number | string | null;
};
/**
* One call to one of the user's hooks, whole: what it sent and what its
* run answered. Throws when it isn't theirs (or that bot's).
* run answered. Throws when it isn't theirs (or that bot's, or that
* workspace's).
*/
export default async function grabBotHookEvent({ user_id, event_id, bot_id }: Params) {
export default async function grabBotHookEvent({ user_id, event_id, bot_id, workspace_id }: Params) {
const res = await BunSQLite.sql<BotHookCall>({
sql: `SELECT e.*, h.title AS hook_title, h.bot_id, h.workspace_id
FROM bot_hook_events e JOIN bot_hooks h ON h.id = e.hook_id
WHERE e.id = ? AND h.user_id = ? AND (? IS NULL OR h.bot_id = ?)`,
values: [Number(event_id), user_id, bot_id ? Number(bot_id) : null, bot_id ? Number(bot_id) : null],
WHERE e.id = ? AND h.user_id = ? AND (? IS NULL OR h.bot_id = ?) AND (? IS NULL OR h.workspace_id = ?)`,
values: [
Number(event_id),
user_id,
bot_id ? Number(bot_id) : null,
bot_id ? Number(bot_id) : null,
workspace_id ? Number(workspace_id) : null,
workspace_id ? Number(workspace_id) : null,
],
});
const call = res.payload?.[0];
@@ -11,7 +11,9 @@ type Params = {
bot_id?: number | string;
/**
* With `bot_id`: only the hooks of that conversation (null is the
* bot's own chat), as `grabCronJobs` does for routines.
* bot's own chat), as `grabCronJobs` does for routines. Without
* `bot_id`: every bot's hooks in that workspace (a coordinator working
* there).
*/
workspace_id?: number | string | null;
/**
@@ -46,6 +48,9 @@ export default async function grabBotHooks({
where.push(scope.sql);
values.push(...scope.values);
}
} else if (workspace_id) {
where.push(`h.workspace_id = ?`);
values.push(workspace_id);
}
if (hook_id) {
@@ -4,13 +4,17 @@ import grabBotHooks from "./grab-bot-hooks";
type Params = {
user_id: number | string;
hook_id: number | string;
/**
* Only if it runs in that workspace (a run working there).
*/
workspace_id?: number | string | null;
};
/**
* One of the user's hooks. Throws when it isn't theirs.
*/
export default async function grabUserBotHook({ user_id, hook_id }: Params) {
const [hook] = await grabBotHooks({ user_id, hook_id });
export default async function grabUserBotHook({ user_id, hook_id, workspace_id }: Params) {
const [hook] = await grabBotHooks({ user_id, hook_id, workspace_id });
if (!hook?.id) {
throw new AppError(`Hook #${hook_id} not found.`);
@@ -8,6 +8,10 @@ export type SearchHookCallsParams = {
user_id: number | string;
hook_id?: number | string | null;
bot_id?: number | string | null;
/**
* Only calls to hooks that run in this workspace (a run working there).
*/
workspace_id?: number | string | null;
/**
* Words to find in what a call sent or what its run answered.
*/
@@ -33,6 +37,7 @@ export default function searchHookCallsSql({
user_id,
hook_id,
bot_id,
workspace_id,
query,
status,
before_id,
@@ -52,6 +57,11 @@ export default function searchHookCallsSql({
values.push(Number(bot_id));
}
if (workspace_id) {
where.push(`h.workspace_id = ?`);
values.push(Number(workspace_id));
}
if (status) {
where.push(`e.status = ?`);
values.push(status);
@@ -0,0 +1,48 @@
import AppError from "@/src/utils/app-error";
import deleteSessionRows from "./delete-session-rows";
import grabUserBotSession from "./grab-user-bot-session";
import hasOpenSessionJob from "./has-open-session-job";
import startBotSession from "./start-bot-session";
type Params = {
session_id: number | string;
user_id: number | string;
};
/**
* Deletes one of the user's sessions and everything in it. Deleting the
* active one hands the conversation a fresh session, since a conversation
* always has one to write in. A session with a run in progress is refused:
* the run would keep writing into rows that are gone.
*/
export default async function deleteBotSession({
session_id,
user_id,
}: Params): Promise<void> {
const session = await grabUserBotSession({ session_id, user_id });
if (!session?.id) {
throw new AppError(`Session not found.`);
}
/**
* A bot's part of a crew request is only ever read there.
*/
if (session.ask_id) {
throw new AppError(`Session not found.`);
}
if (await hasOpenSessionJob({ session_id: session.id })) {
throw new AppError(`This session has a run in progress. Stop it first, then delete the session.`);
}
await deleteSessionRows({ session_ids: [session.id] });
if (session.status != "active") return;
await startBotSession({
user_id: session.user_id!,
bot_id: session.bot_id!,
workspace_id: session.workspace_id,
});
}
@@ -12,7 +12,9 @@ type Params = {
* traces, jobs, what the runs were billed (`token_usages`), job tasks,
* reactions, message files, messages, tasks, then the sessions.
* Files a message carried are unlinked, and their media row is deleted once
* nothing else points at it.
* nothing else points at it. A newer session's `previous_session_id` and a
* message's `carried_from_session_id` that named one of these are cleared,
* since neither is a foreign key.
*/
export default async function deleteSessionRows({ session_ids }: Params) {
const ids = session_ids.map(Number).filter(Boolean);
@@ -107,6 +109,20 @@ export default async function deleteSessionRows({ session_ids }: Params) {
values: ids,
});
await deleteBotPlanRows({ session_ids: ids });
/**
* A newer session may carry on from one of these, and a message may have
* carried one over: neither link is a foreign key, so it dangles.
*/
await BunSQLite.sql({
sql: `UPDATE bot_sessions SET previous_session_id = NULL WHERE previous_session_id IN (${session_placeholders})`,
values: ids,
});
await BunSQLite.sql({
sql: `UPDATE bot_messages SET carried_from_session_id = NULL WHERE carried_from_session_id IN (${session_placeholders})`,
values: ids,
});
await BunSQLite.sql({
sql: `DELETE FROM bot_sessions WHERE id IN (${session_placeholders})`,
values: ids,
@@ -8,6 +8,10 @@ type Params = {
* Only if it's this bot's (a bot managing its own schedules).
*/
bot_id?: number | string;
/**
* Only if it runs in that workspace (a run working there).
*/
workspace_id?: number | string | null;
};
/**
@@ -15,8 +19,8 @@ type Params = {
* The sessions its runs held stay, as the user's own threads (they're
* ordinary sessions once no routine owns them).
*/
export default async function deleteCronJob({ user_id, cron_job_id, bot_id }: Params) {
const cron_job = await grabUserCronJob({ user_id, cron_job_id, bot_id });
export default async function deleteCronJob({ user_id, cron_job_id, bot_id, workspace_id }: Params) {
const cron_job = await grabUserCronJob({ user_id, cron_job_id, bot_id, workspace_id });
const detached = await BunSQLite.sql({
sql: `UPDATE bot_sessions SET routine_id = NULL, updated_at = ? WHERE routine_id = ?`,
@@ -12,7 +12,8 @@ type Params = {
/**
* With `bot_id`: only the routines of that conversation, here
* (`routineScopeSql`). `null` is the bot's own chat, so it has to be
* given rather than left out to mean "everywhere".
* given rather than left out to mean "everywhere". Without `bot_id`:
* every bot's routines in that workspace (a coordinator working there).
*/
workspace_id?: number | string | null;
/**
@@ -48,6 +49,9 @@ export default async function grabCronJobs({
where.push(scope.sql);
values.push(...scope.values);
}
} else if (workspace_id) {
where.push(`c.workspace_id = ?`);
values.push(workspace_id);
}
if (cron_job_id) {
@@ -8,13 +8,17 @@ type Params = {
* Only if it's this bot's (a bot managing its own schedules).
*/
bot_id?: number | string;
/**
* Only if it runs in that workspace (a run working there).
*/
workspace_id?: number | string | null;
};
/**
* One of the user's schedules. Throws when it isn't theirs (or the bot's).
*/
export default async function grabUserCronJob({ user_id, cron_job_id, bot_id }: Params) {
const [cron_job] = await grabCronJobs({ user_id, bot_id, cron_job_id });
export default async function grabUserCronJob({ user_id, cron_job_id, bot_id, workspace_id }: Params) {
const [cron_job] = await grabCronJobs({ user_id, bot_id, workspace_id, cron_job_id });
if (!cron_job?.id) {
throw new AppError(`Schedule #${cron_job_id} not found.`);
@@ -10,6 +10,10 @@ type Params = {
* Only if it's this bot's (a bot managing its own schedules).
*/
bot_id?: number | string;
/**
* Only if it runs in that workspace (a run working there).
*/
workspace_id?: number | string | null;
/**
* Only the fields given are changed. `max_runs: null` runs it until
* it's stopped.
@@ -28,8 +32,8 @@ type Params = {
* on, counts the next run from now; turning a finished one back on (all
* its `max_runs` done) starts its count over. Returns the schedule.
*/
export default async function updateCronJob({ user_id, cron_job_id, bot_id, data }: Params) {
const cron_job = await grabUserCronJob({ user_id, cron_job_id, bot_id });
export default async function updateCronJob({ user_id, cron_job_id, bot_id, workspace_id, data }: Params) {
const cron_job = await grabUserCronJob({ user_id, cron_job_id, bot_id, workspace_id });
const schedule = data.schedule?.trim() || cron_job.schedule || "";
const schedule_changed = Boolean(data.schedule?.trim()) && schedule != cron_job.schedule;
@@ -79,5 +83,5 @@ export default async function updateCronJob({ user_id, cron_job_id, bot_id, data
throw new Error(`Couldn't update the schedule: ${res.error}`);
}
return await grabUserCronJob({ user_id, cron_job_id: cron_job.id! });
return await grabUserCronJob({ user_id, cron_job_id: cron_job.id!, bot_id, workspace_id });
}
@@ -15,6 +15,10 @@ type Params = {
* The workspaces the bot is admin of (`grabBotRunPowers`).
*/
admin_workspace_ids?: number[];
/**
* The workspace the run is in: only its tasks are in reach.
*/
workspace_id?: number | string | null;
};
/**
@@ -30,8 +34,9 @@ export default async function grabRunTask({
bot_id,
is_coordinator,
admin_workspace_ids,
workspace_id,
}: Params): Promise<BUN_SQLITE_COBBLE_TASKS> {
const read = runTaskSql({ task_id, bot_id, is_coordinator, admin_workspace_ids });
const read = runTaskSql({ task_id, bot_id, is_coordinator, admin_workspace_ids, workspace_id });
const res = await BunSQLite.sql<BUN_SQLITE_COBBLE_TASKS>(read);
+7 -1
View File
@@ -23,6 +23,11 @@ type Params = {
* The workspaces the bot is admin of (`grabBotRunPowers`).
*/
admin_workspace_ids?: number[];
/**
* The workspace the run is in: with `bot_id`, only that workspace's
* tasks are in reach (`botTaskScopesSql`).
*/
workspace_id?: number | string | null;
/**
* Only the tasks this bot has (anywhere, unless narrowed).
*/
@@ -64,6 +69,7 @@ export default async function grabTasks({
bot_id,
is_coordinator,
admin_workspace_ids,
workspace_id,
only_bot_id,
with_workspace_wide,
only_workspace_id,
@@ -81,7 +87,7 @@ export default async function grabTasks({
where.push(access.sql);
values.push(...access.values);
} else if (bot_id != null) {
const access = botTaskScopesSql({ bot_id, is_coordinator: Boolean(is_coordinator), admin_workspace_ids });
const access = botTaskScopesSql({ bot_id, is_coordinator: Boolean(is_coordinator), admin_workspace_ids, workspace_id });
where.push(access.sql);
values.push(...access.values);
}
@@ -21,8 +21,18 @@ db.run(`INSERT INTO tasks VALUES
(7, 'Another bot''s, in a workspace it works in', 11, 5, 'todo')`);
db.run(`INSERT INTO workspace_bots VALUES (5, 10)`);
function task(bot_id: number, task_id: number, options: { is_coordinator?: boolean; admin_workspace_ids?: number[] } = {}) {
const { sql, values } = runTaskSql({ task_id, bot_id, is_coordinator: options.is_coordinator ?? false, admin_workspace_ids: options.admin_workspace_ids });
function task(
bot_id: number,
task_id: number,
options: { is_coordinator?: boolean; admin_workspace_ids?: number[]; workspace_id?: number } = {},
) {
const { sql, values } = runTaskSql({
task_id,
bot_id,
is_coordinator: options.is_coordinator ?? false,
admin_workspace_ids: options.admin_workspace_ids,
workspace_id: options.workspace_id,
});
return db.query(sql).get(...values) as { id: number } | null;
}
@@ -50,6 +60,20 @@ describe("runTaskSql", () => {
expect(task(10, 6)).toBeNull();
});
test("working in a workspace, it reaches that workspace alone", () => {
expect(task(10, 3, { workspace_id: 5 })?.id).toBe(3);
expect(task(10, 4, { workspace_id: 5 })?.id).toBe(4);
expect(task(10, 1, { workspace_id: 5 })).toBeNull();
expect(task(10, 5, { workspace_id: 5 })).toBeNull();
expect(task(10, 6, { workspace_id: 5 })).toBeNull();
expect(task(10, 3, { workspace_id: 6 })).toBeNull();
});
test("the coordinator in a workspace reaches that workspace alone", () => {
expect(task(1, 5, { is_coordinator: true, workspace_id: 6 })?.id).toBe(5);
expect(task(1, 2, { is_coordinator: true, workspace_id: 6 })).toBeNull();
});
test("the coordinator reaches every task, whoever has it", () => {
expect(task(1, 2, { is_coordinator: true })?.id).toBe(2);
expect(task(1, 5, { is_coordinator: true })?.id).toBe(5);
@@ -60,6 +84,12 @@ describe("runTaskSql", () => {
expect(task(10, 5, { admin_workspace_ids: [6] })?.id).toBe(5);
expect(task(10, 6, { admin_workspace_ids: [6] })).toBeNull();
});
test("and in a run elsewhere, only what that run's workspace holds", () => {
expect(task(10, 5, { admin_workspace_ids: [6], workspace_id: 6 })?.id).toBe(5);
expect(task(10, 6, { admin_workspace_ids: [6], workspace_id: 6 })).toBeNull();
expect(task(10, 5, { admin_workspace_ids: [6], workspace_id: 5 })).toBeNull();
});
});
describe("taskRowSql", () => {
@@ -6,14 +6,19 @@ type Params = {
bot_id: number | string;
is_coordinator: boolean;
admin_workspace_ids?: number[];
/**
* The workspace the run is in: only its tasks are in reach
* (`botTaskScopesSql`).
*/
workspace_id?: number | string | null;
};
/**
* The read `grabRunTask` makes: the task, but only while the run reaches
* it. Split out so the reach rules can be run against real SQLite.
*/
export function runTaskSql({ task_id, bot_id, is_coordinator, admin_workspace_ids }: Params): SqlCondition {
const access = botTaskScopesSql({ bot_id, is_coordinator, admin_workspace_ids });
export function runTaskSql({ task_id, bot_id, is_coordinator, admin_workspace_ids, workspace_id }: Params): SqlCondition {
const access = botTaskScopesSql({ bot_id, is_coordinator, admin_workspace_ids, workspace_id });
return {
sql: `SELECT t.* FROM tasks t WHERE t.id = ? AND ${access.sql} LIMIT 1`,
@@ -9,6 +9,7 @@ type Params = {
| "new-session"
| "continue-session"
| "reopen-session"
| "delete-session"
| "session-messages"
| "older-messages";
body: Record<string, unknown>;
+1 -1
View File
@@ -165,7 +165,7 @@ export default function delegateTaskTool({
* worked in that workspace, so the crew comes from there.
*/
const task = args.task_id
? await grabRunTask({ task_id: args.task_id, bot_id: requester_id, is_coordinator, admin_workspace_ids })
? await grabRunTask({ task_id: args.task_id, bot_id: requester_id, is_coordinator, admin_workspace_ids, workspace_id })
: null;
const asked_workspace_id = workspace_id || args.workspace_id;
@@ -9,6 +9,10 @@ type Params = {
* The coordinator deletes any of the user's routines, not only its own.
*/
is_coordinator?: boolean;
/**
* The workspace the run is in: only a routine that runs there.
*/
workspace_id?: number | string | null;
};
type Args = {
@@ -19,7 +23,7 @@ type Args = {
* Lets a bot delete one of its own schedules, or as the coordinator any of
* the user's.
*/
export default function deleteScheduleTool({ user_id, bot_id, is_coordinator }: Params): HarnessTool<Args> {
export default function deleteScheduleTool({ user_id, bot_id, is_coordinator, workspace_id }: Params): HarnessTool<Args> {
return {
name: "delete_schedule",
description: is_coordinator
@@ -33,6 +37,7 @@ export default function deleteScheduleTool({ user_id, bot_id, is_coordinator }:
user_id,
cron_job_id: args.schedule_id,
...(is_coordinator ? {} : { bot_id }),
...(workspace_id ? { workspace_id } : {}),
});
return `Schedule #${cron_job.id} "${cron_job.title}" deleted.`;
@@ -247,6 +247,7 @@ export default async function grabBotChatTools({
powers,
workers,
grabTargets: () => askableBots({ user_id, requester_bot_id: bot_id, workspace_id }),
workspace_id,
onTask,
}),
);
+3 -3
View File
@@ -112,10 +112,10 @@ export default async function grabBotTools({
? []
: [
createScheduleTool({ user_id, bot_id, workspace_id, computers }),
updateScheduleTool({ user_id, bot_id, is_coordinator }),
deleteScheduleTool({ user_id, bot_id, is_coordinator }),
updateScheduleTool({ user_id, bot_id, is_coordinator, workspace_id }),
deleteScheduleTool({ user_id, bot_id, is_coordinator, workspace_id }),
]),
listSchedulesTool({ user_id, bot_id, is_coordinator }),
listSchedulesTool({ user_id, bot_id, is_coordinator, workspace_id }),
...grabBotHookTools({ user_id, bot_id, session_id, workspace_id, computers, hooked, is_coordinator, onPropose }),
...(session_id ? [reactToMessageTool({ bot_id, user_id, session_id })] : []),
/**
+7 -1
View File
@@ -32,6 +32,11 @@ type Params = {
* there: the ones it could ask (`askableBots`).
*/
grabTargets: () => Promise<BUN_SQLITE_COBBLE_BOTS[]>;
/**
* The workspace the run is in: a task it hands over is one of that
* workspace's, never another workspace's.
*/
workspace_id?: number | string | null;
/**
* Called with the task it hands over, so the message the run posts links
* to it (`bot_messages.task_ids`).
@@ -62,7 +67,7 @@ type Args = {
* for the move the bot asks first. The other bot works that same task, and
* the result is reported back in this session.
*/
export default function handOverTaskTool({ user_id, bot, session_id, powers, workers, grabTargets, onTask }: Params): HarnessTool<Args> {
export default function handOverTaskTool({ user_id, bot, session_id, powers, workers, grabTargets, workspace_id, onTask }: Params): HarnessTool<Args> {
const bot_id = bot.id || 0;
const crew = workers.map((worker) => `${worker.id}: ${worker.name}`).join("; ");
@@ -90,6 +95,7 @@ export default function handOverTaskTool({ user_id, bot, session_id, powers, wor
bot_id,
is_coordinator: powers.is_coordinator,
admin_workspace_ids: powers.admin_workspace_ids,
workspace_id,
});
/**
@@ -10,6 +10,10 @@ type Params = {
* The coordinator deletes any of the user's hooks, not only its own.
*/
is_coordinator?: boolean;
/**
* The workspace the run is in: only a hook that runs there.
*/
workspace_id?: number | string | null;
};
type Args = {
@@ -20,7 +24,7 @@ type Args = {
* Lets a bot delete one of its hooks for good, or as the coordinator any of
* the user's.
*/
export default function deleteHookTool({ user_id, bot_id, is_coordinator }: Params): HarnessTool<Args> {
export default function deleteHookTool({ user_id, bot_id, is_coordinator, workspace_id }: Params): HarnessTool<Args> {
return {
name: "delete_hook",
description: `Delete ${
@@ -30,7 +34,7 @@ export default function deleteHookTool({ user_id, bot_id, is_coordinator }: Para
hook_id: z.number().int().positive(),
}),
run: async ({ args }) => {
const hook = await grabOwnHook({ user_id, bot_id, hook_id: args.hook_id, is_coordinator });
const hook = await grabOwnHook({ user_id, bot_id, hook_id: args.hook_id, is_coordinator, workspace_id });
await deleteBotHook({ user_id, hook_id: hook.id! });
@@ -50,11 +50,11 @@ export default function grabBotHookTools({
if (hooked) return [];
return [
listHooksTool({ user_id, bot_id, is_coordinator }),
searchHookCallsTool({ user_id, bot_id, is_coordinator }),
readHookCallTool({ user_id, bot_id, is_coordinator }),
pauseHookTool({ user_id, bot_id, is_coordinator }),
deleteHookTool({ user_id, bot_id, is_coordinator }),
listHooksTool({ user_id, bot_id, is_coordinator, workspace_id }),
searchHookCallsTool({ user_id, bot_id, is_coordinator, workspace_id }),
readHookCallTool({ user_id, bot_id, is_coordinator, workspace_id }),
pauseHookTool({ user_id, bot_id, is_coordinator, workspace_id }),
deleteHookTool({ user_id, bot_id, is_coordinator, workspace_id }),
...(session_id && onPropose
? [proposeHookTool({ user_id, bot_id, session_id, workspace_id, computers, onPropose })]
: []),
+8 -3
View File
@@ -9,15 +9,20 @@ type Params = {
* The coordinator reaches every hook the user has, not only its own.
*/
is_coordinator?: boolean;
/**
* The workspace the run is in: only a hook that runs there.
*/
workspace_id?: number | string | null;
};
/**
* One of the user's hooks that this bot runs, or an `AppError`: a bot
* never touches another bot's hooks, except the coordinator, which the
* user made responsible for the whole crew.
* user made responsible for the whole crew. In a workspace only that
* workspace's hooks are within reach.
*/
export default async function grabOwnHook({ user_id, bot_id, hook_id, is_coordinator }: Params) {
const hook = await grabUserBotHook({ user_id, hook_id });
export default async function grabOwnHook({ user_id, bot_id, hook_id, is_coordinator, workspace_id }: Params) {
const hook = await grabUserBotHook({ user_id, hook_id, workspace_id });
if (!is_coordinator && String(hook.bot_id) != String(bot_id)) {
throw new AppError(`Hook #${hook_id} isn't one of yours.`);
+17 -7
View File
@@ -12,6 +12,10 @@ type Params = {
* crew's hooks, not only its own.
*/
is_coordinator?: boolean;
/**
* The workspace the run is in: only the hooks that run there.
*/
workspace_id?: number | string | null;
};
type Args = {
@@ -21,14 +25,14 @@ type Args = {
/**
* Lets a bot see the user's hooks it runs, everywhere it works, never
* their URLs. The coordinator sees the crew's, each naming the bot that
* runs it.
* runs it. In a workspace only that workspace's hooks are in reach.
*/
export default function listHooksTool({ user_id, bot_id, is_coordinator }: Params): HarnessTool<Args> {
export default function listHooksTool({ user_id, bot_id, is_coordinator, workspace_id }: Params): HarnessTool<Args> {
return {
name: "list_hooks",
description: is_coordinator
? `List the hooks that give the user's bots work: id, name, which bot runs it, what calls it (an outside service at its secret URL, or browser notifications on a computer), where it runs, whether it's paused, its runs, last call and last error. Pass bot_id to see only one bot's. To see what calls sent and what the runs answered, use search_hook_calls. You never see a hook's URL: only the user does. This is a list, not a census of the install: give what it holds and never conclude from it that a hook does not exist.`
: `List the user's hooks that give you work: id, name, what calls it (an outside service at its secret URL, or browser notifications on a computer), where it runs, whether it's paused, its runs, last call and last error. Only the ones that run as you: another bot's hooks are not in this list, so never say the user has no hook from it, since they may have one on another bot. To see what calls sent and what your runs answered, use search_hook_calls. You never see a hook's URL: only the user does.`,
? `List ${workspace_id ? "the hooks that run in this workspace, on any of its bots" : "the hooks that give the user's bots work"}: id, name, which bot runs it, what calls it (an outside service at its secret URL, or browser notifications on a computer), where it runs, whether it's paused, its runs, last call and last error. Pass bot_id to see only one bot's. To see what calls sent and what the runs answered, use search_hook_calls. You never see a hook's URL: only the user does. This is a list, not a census of the install: give what it holds and never conclude from it that a hook does not exist.`
: `List the hooks ${workspace_id ? "that run in this workspace and give you work" : "that give you work"}: id, name, what calls it (an outside service at its secret URL, or browser notifications on a computer), where it runs, whether it's paused, its runs, last call and last error.${workspace_id ? " Nothing outside this workspace is in reach." : " Only the ones that run as you: another bot's hooks are not in this list, so never say the user has no hook from it, since they may have one on another bot."} To see what calls sent and what your runs answered, use search_hook_calls. You never see a hook's URL: only the user does.`,
schema: is_coordinator
? z.object({
bot_id: z.number().int().positive().optional().describe("Only this bot's hooks"),
@@ -37,15 +41,21 @@ export default function listHooksTool({ user_id, bot_id, is_coordinator }: Param
run: async ({ args }) => {
const hooks = await grabBotHooks({
user_id,
...(is_coordinator ? (args.bot_id ? { bot_id: args.bot_id } : {}) : { bot_id }),
...(is_coordinator
? { ...(args.bot_id ? { bot_id: args.bot_id } : {}), ...(workspace_id ? { workspace_id } : {}) }
: { bot_id, ...(workspace_id ? { workspace_id } : {}) }),
});
if (!hooks.length) {
if (is_coordinator) {
return args.bot_id ? `Bot ${botRef({ id: args.bot_id })} has no hooks.` : `The user's crew has no hooks.`;
if (args.bot_id) return `Bot ${botRef({ id: args.bot_id })} has no hooks${workspace_id ? " in this workspace" : ""}.`;
return workspace_id ? `There are no hooks in this workspace.` : `The user's crew has no hooks.`;
}
return `You have no hooks of your own. Other bots' hooks aren't in this list.`;
return workspace_id
? `There are no hooks in this workspace. Hooks elsewhere aren't in this list.`
: `You have no hooks of your own. Other bots' hooks aren't in this list.`;
}
return hooks
@@ -11,6 +11,10 @@ type Params = {
* The coordinator pauses any of the user's hooks, not only its own.
*/
is_coordinator?: boolean;
/**
* The workspace the run is in: only a hook that runs there.
*/
workspace_id?: number | string | null;
};
type Args = {
@@ -22,7 +26,7 @@ type Args = {
* again. Only taking away needs no confirming; switching it back on is a
* proposal (`propose_hook`).
*/
export default function pauseHookTool({ user_id, bot_id, is_coordinator }: Params): HarnessTool<Args> {
export default function pauseHookTool({ user_id, bot_id, is_coordinator, workspace_id }: Params): HarnessTool<Args> {
return {
name: "pause_hook",
description: `Pause ${
@@ -32,7 +36,7 @@ export default function pauseHookTool({ user_id, bot_id, is_coordinator }: Param
hook_id: z.number().int().positive(),
}),
run: async ({ args }) => {
const hook = await grabOwnHook({ user_id, bot_id, hook_id: args.hook_id, is_coordinator });
const hook = await grabOwnHook({ user_id, bot_id, hook_id: args.hook_id, is_coordinator, workspace_id });
if (!hook.enabled) return `Hook #${hook.id} "${hook.title}" is already paused.`;
@@ -11,6 +11,10 @@ type Params = {
* The coordinator reads a call to any of the user's hooks.
*/
is_coordinator?: boolean;
/**
* The workspace the run is in: only a call to a hook that runs there.
*/
workspace_id?: number | string | null;
};
type Args = {
@@ -22,7 +26,7 @@ type Args = {
* outside data, and what its run answered. The coordinator reads any of
* the user's.
*/
export default function readHookCallTool({ user_id, bot_id, is_coordinator }: Params): HarnessTool<Args> {
export default function readHookCallTool({ user_id, bot_id, is_coordinator, workspace_id }: Params): HarnessTool<Args> {
return {
name: "read_hook_call",
description: `Read one call to ${
@@ -35,6 +39,7 @@ export default function readHookCallTool({ user_id, bot_id, is_coordinator }: Pa
const call = await grabBotHookEvent({
user_id,
...(is_coordinator ? {} : { bot_id }),
workspace_id,
event_id: args.call_id,
});
@@ -12,6 +12,10 @@ type Params = {
* The coordinator searches the calls to any of the user's hooks.
*/
is_coordinator?: boolean;
/**
* The workspace the run is in: only calls to hooks that run there.
*/
workspace_id?: number | string | null;
};
type Args = {
@@ -27,7 +31,7 @@ type Args = {
* each sent and what its run answered, newest first. Never another bot's,
* except the coordinator, which sees the crew's.
*/
export default function searchHookCallsTool({ user_id, bot_id, is_coordinator }: Params): HarnessTool<Args> {
export default function searchHookCallsTool({ user_id, bot_id, is_coordinator, workspace_id }: Params): HarnessTool<Args> {
return {
name: "search_hook_calls",
description: `Search the calls to ${
@@ -47,6 +51,7 @@ export default function searchHookCallsTool({ user_id, bot_id, is_coordinator }:
const calls = await grabBotHookEvents({
user_id,
...(is_coordinator ? {} : { bot_id }),
workspace_id,
hook_id: args.hook_id,
query: args.query,
status: args.status,
+19 -7
View File
@@ -12,6 +12,11 @@ type Params = {
* crew's routines, not only its own.
*/
is_coordinator?: boolean;
/**
* The workspace the run is in: then only the routines that run there,
* never another workspace's nor the bots' own chat.
*/
workspace_id?: number | string | null;
};
type Args = {
@@ -20,14 +25,15 @@ type Args = {
/**
* Lets a bot see its own schedules, everywhere it works. The coordinator
* sees the crew's, each naming the bot that runs it.
* sees the crew's, each naming the bot that runs it. In a workspace only
* that workspace's routines are in reach.
*/
export default function listSchedulesTool({ user_id, bot_id, is_coordinator }: Params): HarnessTool<Args> {
export default function listSchedulesTool({ user_id, bot_id, is_coordinator, workspace_id }: Params): HarnessTool<Args> {
return {
name: "list_schedules",
description: is_coordinator
? `List the schedules (routines) of every bot the user has: id, cron expression (UTC), which bot runs it, where, whether it's paused, its next run and its last error. Pass bot_id to see only one bot's. This is a list, not a census of the install: give what it holds and never conclude from it that a routine does not exist.`
: `List your own schedules (routines): id, cron expression (UTC), where each runs, whether it's paused, its next run and its last error. Only yours: another bot's routines are not in this list, so never say the user has no routine from it, since they may have one on another bot.`,
? `${workspace_id ? "List the schedules (routines) that run in this workspace, on any of its bots" : "List the schedules (routines) of every bot the user has"}: id, cron expression (UTC), which bot runs it, where, whether it's paused, its next run and its last error. Pass bot_id to see only one bot's. This is a list, not a census of the install: give what it holds and never conclude from it that a routine does not exist.`
: `List ${workspace_id ? "the schedules (routines) that run in this workspace" : "your own schedules (routines)"}: id, cron expression (UTC), where each runs, whether it's paused, its next run and its last error.${workspace_id ? " Nothing outside this workspace is in reach." : " Only yours: another bot's routines are not in this list, so never say the user has no routine from it, since they may have one on another bot."}`,
schema: is_coordinator
? z.object({
bot_id: z.number().int().positive().optional().describe("Only this bot's schedules"),
@@ -36,15 +42,21 @@ export default function listSchedulesTool({ user_id, bot_id, is_coordinator }: P
run: async ({ args }) => {
const cron_jobs = await grabCronJobs({
user_id,
...(is_coordinator ? (args.bot_id ? { bot_id: args.bot_id } : {}) : { bot_id }),
...(is_coordinator
? { ...(args.bot_id ? { bot_id: args.bot_id } : {}), ...(workspace_id ? { workspace_id } : {}) }
: { bot_id, ...(workspace_id ? { workspace_id } : {}) }),
});
if (!cron_jobs.length) {
if (is_coordinator) {
return args.bot_id ? `Bot ${botRef({ id: args.bot_id })} has no schedules.` : `The user's crew has no schedules.`;
if (args.bot_id) return `Bot ${botRef({ id: args.bot_id })} has no schedules${workspace_id ? " in this workspace" : ""}.`;
return workspace_id ? `There are no schedules in this workspace.` : `The user's crew has no schedules.`;
}
return `You have no schedules of your own. Other bots' routines aren't in this list.`;
return workspace_id
? `There are no schedules in this workspace. Routines elsewhere aren't in this list.`
: `You have no schedules of your own. Other bots' routines aren't in this list.`;
}
return cron_jobs
@@ -81,6 +81,10 @@ function resolvePlace({
}
if (is_coordinator) {
if (workspace_id && target_workspace && target_workspace != Number(workspace_id)) {
return `You're working in workspace #${workspace_id}, so a task made here goes there. Create it from your own chat to put it in another workspace.`;
}
const place_workspace = target_workspace || (workspace_id ? Number(workspace_id) : null);
if (args.workspace_wide) {
@@ -12,6 +12,10 @@ type Params = {
* The workspaces the bot is admin of (`grabBotRunPowers`).
*/
admin_workspace_ids?: number[];
/**
* The workspace the run is in: only its tasks are in reach.
*/
workspace_id?: number | string | null;
/**
* Told the task it deleted, so the message's app record names it: a bot
* read a plain "delete_task" and later described the task as still
@@ -32,7 +36,14 @@ type Args = {
* (`assertUserReachesTask`). Only chat replies get it: a routine, a hook
* call has no user asking, and a payload could ask for it.
*/
export default function deleteTaskTool({ user_id, bot_id, is_coordinator, admin_workspace_ids = [], onTask }: Params): HarnessTool<Args> {
export default function deleteTaskTool({
user_id,
bot_id,
is_coordinator,
admin_workspace_ids = [],
workspace_id,
onTask,
}: Params): HarnessTool<Args> {
return {
name: "delete_task",
description: `Delete a task from the to-do list for good, with its notes and file links (the files themselves stay). Only when the user asked for that task, or tasks like it, to be deleted; work that was dropped but should stay on record is cancelled with update_task instead. Say "deleted" only after this call says so; cancelling isn't deleting.`,
@@ -40,7 +51,7 @@ export default function deleteTaskTool({ user_id, bot_id, is_coordinator, admin_
task_id: z.number().int(),
}),
run: async ({ args }) => {
const task = await grabRunTask({ task_id: args.task_id, bot_id, is_coordinator, admin_workspace_ids });
const task = await grabRunTask({ task_id: args.task_id, bot_id, is_coordinator, admin_workspace_ids, workspace_id });
await assertUserReachesTask({ user_id, task_id: task.id! });
await deleteTask({ user_id, task_id: task.id!, deleted_by_bot_id: bot_id });
@@ -90,7 +90,7 @@ export default async function grabBotTaskTools({
members,
onTask,
}),
updateTaskTool({ user_id, bot_id, is_coordinator, admin_workspace_ids, scopes, onTask }),
...(can_delete ? [deleteTaskTool({ user_id, bot_id, is_coordinator, admin_workspace_ids, onTask })] : []),
updateTaskTool({ user_id, bot_id, is_coordinator, admin_workspace_ids, workspace_id, scopes, onTask }),
...(can_delete ? [deleteTaskTool({ user_id, bot_id, is_coordinator, admin_workspace_ids, workspace_id, onTask })] : []),
];
}
@@ -47,7 +47,7 @@ type Args = {
export default function listTasksTool({ bot_id, user_id, is_coordinator, admin_workspace_ids, workspace_id, onTask }: Params): HarnessTool<Args> {
return {
name: "list_tasks",
description: `List tasks: yours (your own list and the ones you have in workspaces), the ones in ${workspace_id ? "this workspace" : "a workspace"}, or ${is_coordinator ? "every task in the install" : "every task you can reach (yours, the workspace-wide ones in your workspaces, and as a workspace's admin every task there)"}. Each line is its id, status, title, whose it is, its files and its latest note with who wrote it. Open ones come first (blocked, then doing, then to do). Use it to plan work, and to check what's still pending when the user says hello or asks what's next. A workspace-wide task is worked on by every bot in its workspace: before you work on one, read it with task_id to see its brief and its whole log (which bot did what, and when), so you pick up where the others left off instead of redoing their part.`,
description: `List tasks: yours (your own list and the ones you have in workspaces), the ones in ${workspace_id ? "this workspace" : "a workspace"}, or ${is_coordinator ? "every task in the install" : "every task you can reach (yours, the workspace-wide ones in your workspaces, and as a workspace's admin every task there)"}.${workspace_id ? " You are working in a workspace, so only its tasks are in reach: never another workspace's, nor your own list outside it." : ""} Each line is its id, status, title, whose it is, its files and its latest note with who wrote it. Open ones come first (blocked, then doing, then to do). Use it to plan work, and to check what's still pending when the user says hello or asks what's next. A workspace-wide task is worked on by every bot in its workspace: before you work on one, read it with task_id to see its brief and its whole log (which bot did what, and when), so you pick up where the others left off instead of redoing their part.`,
schema: z.object({
task_id: z
.number()
@@ -66,14 +66,14 @@ export default function listTasksTool({ bot_id, user_id, is_coordinator, admin_w
}),
run: async ({ args }) => {
if (args.task_id) {
const task = await grabRunTask({ task_id: args.task_id, bot_id, is_coordinator, admin_workspace_ids });
const task = await grabRunTask({ task_id: args.task_id, bot_id, is_coordinator, admin_workspace_ids, workspace_id });
onTask?.({ task_id: Number(task.id) });
const [notes, files, parts] = await Promise.all([
grabTaskNotes({ task_id: task.id! }),
grabTaskMedia({ task_id: task.id! }),
grabTasks({ bot_id, is_coordinator, admin_workspace_ids, only_parent_task_id: task.id! }),
grabTasks({ bot_id, is_coordinator, admin_workspace_ids, workspace_id, only_parent_task_id: task.id! }),
]);
const parent = task.parent_task_id ? await grabTaskRow({ task_id: task.parent_task_id }) : null;
@@ -88,8 +88,7 @@ export default function listTasksTool({ bot_id, user_id, is_coordinator, admin_w
}
const scope = args.scope || "all";
const only_workspace_id =
scope == "workspace" && workspace_id ? Number(workspace_id) : undefined;
const only_workspace_id = workspace_id ? Number(workspace_id) : undefined;
const tasks = await grabTasks({
bot_id,
@@ -24,6 +24,10 @@ type Params = {
* The workspaces the bot is admin of (`grabBotRunPowers`).
*/
admin_workspace_ids?: number[];
/**
* The workspace the run is in: only its tasks are in reach.
*/
workspace_id?: number | string | null;
/**
* The run's folders, for linking a deliverable by its `[file:ID]` ref.
*/
@@ -61,7 +65,15 @@ type Args = {
* which bot did what and when. The coordinator and a workspace's admin bot
* can also turn a bot's task there into a workspace-wide one.
*/
export default function updateTaskTool({ user_id, bot_id, is_coordinator, admin_workspace_ids = [], scopes = [], onTask }: Params): HarnessTool<Args> {
export default function updateTaskTool({
user_id,
bot_id,
is_coordinator,
admin_workspace_ids = [],
workspace_id,
scopes = [],
onTask,
}: Params): HarnessTool<Args> {
/**
* Only the coordinator and workspace admins get the switch at all.
*/
@@ -131,7 +143,7 @@ export default function updateTaskTool({ user_id, bot_id, is_coordinator, admin_
),
}),
run: async ({ args }) => {
const task = await grabRunTask({ task_id: args.task_id, bot_id, is_coordinator, admin_workspace_ids });
const task = await grabRunTask({ task_id: args.task_id, bot_id, is_coordinator, admin_workspace_ids, workspace_id });
const said: string[] = [];
onTask?.({ task_id: Number(task.id) });
@@ -197,6 +209,7 @@ export default function updateTaskTool({ user_id, bot_id, is_coordinator, admin_
bot_id,
is_coordinator,
admin_workspace_ids,
workspace_id,
only_workspace_id: task.workspace_id,
own_list: !task.workspace_id,
open_only: true,
@@ -10,6 +10,10 @@ type Params = {
* The coordinator changes any of the user's routines, not only its own.
*/
is_coordinator?: boolean;
/**
* The workspace the run is in: only a routine that runs there.
*/
workspace_id?: number | string | null;
};
type Args = {
@@ -25,7 +29,7 @@ type Args = {
* Lets a bot change, pause or resume one of its own schedules, or as the
* coordinator any of the user's.
*/
export default function updateScheduleTool({ user_id, bot_id, is_coordinator }: Params): HarnessTool<Args> {
export default function updateScheduleTool({ user_id, bot_id, is_coordinator, workspace_id }: Params): HarnessTool<Args> {
return {
name: "update_schedule",
description: is_coordinator
@@ -45,6 +49,7 @@ export default function updateScheduleTool({ user_id, bot_id, is_coordinator }:
user_id,
cron_job_id: schedule_id,
...(is_coordinator ? {} : { bot_id }),
...(workspace_id ? { workspace_id } : {}),
data,
});
+24 -2
View File
@@ -123,7 +123,21 @@ export default function useBotSessions({ bot_id, workspace_id, open, limit, atte
};
}, [open, query, bot_id, workspace_id, limit, attended_only, revision, refresh_key]);
const act = async ({ id, path, body }: { id: number | "new"; path: "new-session" | "reopen-session"; body: Record<string, unknown> }) => {
const act = async ({
id,
path,
body,
reload = true,
}: {
id: number | "new";
path: "new-session" | "reopen-session" | "delete-session";
body: Record<string, unknown>;
/**
* Whether it lands the conversation on its session; a deleted
* session other than the one on screen only reloads the list.
*/
reload?: boolean;
}) => {
if (busy_id) return;
setBusyId(id);
@@ -135,7 +149,7 @@ export default function useBotSessions({ bot_id, workspace_id, open, limit, atte
* The plain address, not a reload: one showing a session to read
* (`?session_id=`) would stay on it.
*/
if (res?.success) {
if (res?.success && reload) {
window.location.assign(conversationHref({ bot_id, workspace_id }));
return;
}
@@ -150,6 +164,12 @@ export default function useBotSessions({ bot_id, workspace_id, open, limit, atte
}
setBusyId(undefined);
if (res?.success) {
setRevision((value) => value + 1);
return;
}
setError(res?.msg || "That didn't work.");
};
@@ -163,5 +183,7 @@ export default function useBotSessions({ bot_id, workspace_id, open, limit, atte
startSession: () => act({ id: "new", path: "new-session", body: { bot_id, workspace_id } }),
reopenSession: ({ session_id }: { session_id: number }) =>
act({ id: session_id, path: "reopen-session", body: { session_id } }),
deleteSession: ({ session_id, current }: { session_id: number; current: boolean }) =>
act({ id: session_id, path: "delete-session", body: { session_id }, reload: current }),
};
}
@@ -16,6 +16,7 @@ type Props = {
stone: BotStoneShape;
image_media_id?: number | string | null;
picked_src?: string;
avatar_size?: number;
};
/**
@@ -30,6 +31,7 @@ export default function BotFormPreview({
stone,
image_media_id,
picked_src,
avatar_size = 56,
}: Props) {
const has_picture = Boolean(picked_src || image_media_id);
/** A palette colour by name, else a colour the user made up. */
@@ -42,7 +44,7 @@ export default function BotFormPreview({
<BotAvatar
color={color}
stone={stone}
size={56}
size={avatar_size}
image_media_id={image_media_id}
src={picked_src}
/>
+9 -1
View File
@@ -91,7 +91,14 @@ export default function BotForm({ bot, onCancel, onSaved }: Props) {
})
: await postAdminApi<{ bot_id: number }>({
path: "bots/create-bot",
body: { name, role, color, stone, system_prompt, workspace_id },
body: {
name,
role,
color,
stone,
system_prompt,
workspace_id,
},
});
const bot_id =
bot?.id ||
@@ -158,6 +165,7 @@ export default function BotForm({ bot, onCancel, onSaved }: Props) {
stone={stone}
image_media_id={image.image_media_id}
picked_src={image.data_url}
avatar_size={120}
/>
}
has_image={image.has_image}
@@ -133,7 +133,7 @@ export default function RailSettingsAside({ pathname }: Props) {
computerStatusLabel({ computer }),
computerResourcesLabel({ computer }),
].join(" · ");
avatar = <ComputerIconTile />;
avatar = <ComputerIconTile connection={computer.connection} />;
}
return (
@@ -3,11 +3,12 @@ import type { APIResponseObject } from "@moduletrace/bunext/types";
import type { BotIdRequest } from "@/src/schemas/bot-schema";
/**
* A bot's core instructions and memory, for its panel.
* A bot's core instructions and memory for its panel, and what it remembers
* about the user reading it.
*/
export default async function fetchBotInstructions({ bot_id }: BotIdRequest) {
return await fetchApi<BotIdRequest, APIResponseObject<{ system_prompt: string; memory: string }>>(
`/api/admin/bots/bot-instructions`,
{ method: "POST", body: { bot_id } },
);
return await fetchApi<
BotIdRequest,
APIResponseObject<{ system_prompt: string; memory: string; user_memory: string }>
>(`/api/admin/bots/bot-instructions`, { method: "POST", body: { bot_id } });
}
@@ -17,12 +17,14 @@ type Params = {
export default function useBotInstructions({ bot_id, enabled }: Params) {
const [system_prompt, setSystemPrompt] = useState<string>();
const [memory, setMemory] = useState<string>();
const [user_memory, setUserMemory] = useState<string>();
const [error, setError] = useState<string>();
useEffect(() => {
/** Cleared on close, so the next open never shows an old copy. */
setSystemPrompt(undefined);
setMemory(undefined);
setUserMemory(undefined);
setError(undefined);
if (!enabled || !bot_id) return;
@@ -36,6 +38,7 @@ export default function useBotInstructions({ bot_id, enabled }: Params) {
if (res.success && res.singleRes) {
setSystemPrompt(res.singleRes.system_prompt);
setMemory(res.singleRes.memory);
setUserMemory(res.singleRes.user_memory);
} else {
setError(res.msg || "Couldn't load the instructions.");
}
@@ -49,5 +52,5 @@ export default function useBotInstructions({ bot_id, enabled }: Params) {
};
}, [enabled, bot_id]);
return { system_prompt, memory, error };
return { system_prompt, memory, user_memory, error };
}
@@ -13,16 +13,15 @@ function render() {
}
describe("BotComputerPreview", () => {
test("it shows the computer's live browser, view only", () => {
/**
* The block is always there, at its usual size; only the live stream
* waits for Preview, since it is a stream nobody asked for.
*/
test("it keeps the block and holds its screen until asked", () => {
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"');
expect(html).toContain("h-[250px]");
expect(html).toContain("Preview");
expect(html).not.toContain("/computers/7/");
});
});
@@ -1,6 +1,8 @@
import { useState } from "react";
import Button from "@moduletrace/twui/layout/Button";
import Span from "@moduletrace/twui/layout/Span";
import Stack from "@moduletrace/twui/layout/Stack";
import { Maximize2 } from "lucide-react";
import { Eye, Maximize2 } from "lucide-react";
import ComputerViewFrame from "@/src/components/general/computer-view-frame";
type Props = {
@@ -14,30 +16,61 @@ type Props = {
/**
* 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.
* sees what it is doing without leaving the conversation. The block is always
* there, but the screen is a live stream: it is only shown once Preview is
* clicked. 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) {
export default function BotComputerPreview({
computer_id,
name,
onOpen,
}: Props) {
const [previewing, setPreviewing] = useState(false);
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 className="relative w-full h-[250px] mt-2 overflow-hidden rounded-default border border-solid border-hairline bg-sunken">
{previewing ? (
<>
<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 className="absolute inset-0 gap-2! items-center justify-center px-6">
<Span className="text-[13px] leading-[18px] text-ink-secondary text-center">
{`See ${name}'s screen without opening the viewer.`}
</Span>
<Button
type="button"
title={`Preview ${name}'s screen`}
onClick={() => setPreviewing(true)}
beforeIcon={<Eye size={14} aria-hidden />}
>
Preview
</Button>
</Stack>
</Button>
)}
</Stack>
);
}
}
@@ -3,7 +3,7 @@ import Modal from "@moduletrace/twui/elements/Modal";
import H2 from "@moduletrace/twui/layout/H2";
import Span from "@moduletrace/twui/layout/Span";
import Stack from "@moduletrace/twui/layout/Stack";
import { Monitor } from "lucide-react";
import computerIcon from "@/src/utils/computer-icon";
import type { BotWithLastMessage } from "@/src/types";
import { BotComputersContext } from "../(data)/bot-computers-context";
import BotComputerOption from "./bot-computer-option";
@@ -66,6 +66,7 @@ export default function BotComputersModal({
const name = bot.name || "This bot";
const can_switch = computers.length > 1;
const Icon = computerIcon({ connection: current.connection });
const title = can_switch
? `Switch ${name}'s computer`
@@ -76,7 +77,7 @@ export default function BotComputersModal({
target={
meta_text ? (
<HeaderMetaItem
icon={Monitor}
icon={Icon}
label="Computer"
text={meta_text}
title={title}
@@ -84,7 +85,7 @@ export default function BotComputersModal({
/>
) : menu ? (
<HeaderMenuItem
icon={Monitor}
icon={Icon}
title="Computer"
hint={
menu_hint ||
@@ -96,7 +97,7 @@ export default function BotComputersModal({
/>
) : (
<HeaderIconButton
icon={Monitor}
icon={Icon}
title={title}
loading={Boolean(switching_id)}
/>
@@ -26,6 +26,7 @@ import useWorkspaceBotInstructions from "../(hooks)/use-workspace-bot-instructio
import BotMemoryForm from "./bot-memory-form";
import BotPanelTrigger from "./bot-panel-trigger";
import BotToolsTab from "./bot-tools-tab";
import BotUserMemory from "./bot-user-memory";
type Props = {
bot: BotWithLastMessage;
@@ -53,13 +54,19 @@ type PanelTab = "settings" | "tools";
* 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) {
export default function BotPanel({
bot,
workspace,
open,
on_open,
on_close,
}: Props) {
const { pageProps } = useContext(AppContext);
const name = bot.name || "This bot";
const can_edit = canManageCrew({ user_types: pageProps?.user_types });
const [tab, setTab] = useState<PanelTab>("settings");
const workspace_id = Number(workspace?.id) || 0;
const { system_prompt, memory, error } = useBotInstructions({
const { system_prompt, memory, user_memory, error } = useBotInstructions({
bot_id: Number(bot.id) || 0,
enabled: open && can_edit,
});
@@ -71,6 +78,7 @@ export default function BotPanel({ bot, workspace, open, on_open, on_close }: Pr
const memory_ready =
system_prompt != undefined &&
memory != undefined &&
user_memory != undefined &&
(!workspace_id || Boolean(workspace_instructions.instructions));
const loaded_error = error || workspace_instructions.error;
@@ -107,7 +115,11 @@ export default function BotPanel({ bot, workspace, open, on_open, on_close }: Pr
<Stack className="shrink-0">
<BotAvatar
image_media_id={bot.image_media_id}
{...botStoneProps({ color: bot.color, stone: bot.stone, hue: bot.hue })}
{...botStoneProps({
color: bot.color,
stone: bot.stone,
hue: bot.hue,
})}
face={(bot.face || "idle") as BotFace}
size={35}
/>
@@ -132,10 +144,18 @@ export default function BotPanel({ bot, workspace, open, on_open, on_close }: Pr
aria-label={`Edit ${name}`}
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="Tools" active={tab == "tools"} onPick={() => setTab("tools")} />
<TabButton
title="Settings"
active={tab == "settings"}
onPick={() => setTab("settings")}
/>
<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">
<Stack className="grow min-h-0 overflow-y-auto gap-4! items-stretch px-4 pt-4 pb-6 [&>*]:shrink-0">
{open && tab == "settings" ? (
<>
<Span className="text-[13px] leading-[18px] text-ink-secondary">
@@ -154,15 +174,28 @@ export default function BotPanel({ bot, workspace, open, on_open, on_close }: Pr
{`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}
/>
<>
<BotMemoryForm
bot_id={Number(bot.id) || 0}
bot_name={name}
memory={memory || ""}
workspace_id={
workspace_id || undefined
}
workspace_name={workspace?.name}
workspace_memory={
workspace_instructions
.instructions?.memory ||
""
}
onCancel={on_close}
/>
<Divider className="my-2 border-hairline dark:border-hairline" />
<BotUserMemory
bot_name={name}
memory={user_memory || ""}
/>
</>
) : loaded_error ? (
<Span className="py-6 text-[13px] leading-[18px] text-ink-secondary">
{loaded_error}
@@ -197,4 +230,4 @@ export default function BotPanel({ bot, workspace, open, on_open, on_close }: Pr
</SidePanel>
</>
);
}
}
@@ -0,0 +1,34 @@
import Span from "@moduletrace/twui/layout/Span";
import CodeEditor from "@/src/components/general/code-editor";
type Props = {
bot_name: string;
/**
* What the bot has saved about the user reading the panel; empty until
* it saved anything.
*/
memory: string;
};
/**
* What the bot remembers about this user alone (`bot_user_memories`), shown
* in its panel's settings tab. It shapes how the bot works with them, never
* what it does, and only the bot writes it.
*/
export default function BotUserMemory({ bot_name, memory }: Props) {
return (
<>
<Span className="text-[13px] leading-[18px] text-ink-secondary">
{`What ${bot_name} remembers about you, which only shapes how it works with you.`}
</Span>
<CodeEditor
title="About you"
content={memory || "Nothing yet."}
mode="markdown"
className="h-32"
readOnly
onChange={() => {}}
/>
</>
);
}
@@ -1,6 +1,6 @@
import { useContext } from "react";
import Button from "@moduletrace/twui/layout/Button";
import { Monitor } from "lucide-react";
import computerIcon from "@/src/utils/computer-icon";
import { BotComputersContext } from "../(data)/bot-computers-context";
import Span from "@moduletrace/twui/layout/Span";
@@ -16,6 +16,7 @@ export default function ComposerComputerButton() {
if (!computer?.id) return null;
const title = `Open ${computer.name || `computer ${computer.id}`}`;
const Icon = computerIcon({ connection: computer.connection });
return (
<Button
@@ -33,7 +34,7 @@ export default function ComposerComputerButton() {
<Span className="text-[12px] leading-4 text-ink-secondary">
Computer
</Span>
<Monitor size={14} aria-hidden />
<Icon size={14} aria-hidden />
</Button>
);
}
@@ -1,8 +1,9 @@
import { useContext } from "react";
import Button from "@moduletrace/twui/layout/Button";
import Span from "@moduletrace/twui/layout/Span";
import { Check, Monitor } from "lucide-react";
import { Check } from "lucide-react";
import { twMerge } from "tailwind-merge";
import computerIcon from "@/src/utils/computer-icon";
import { BotComputersContext } from "../(data)/bot-computers-context";
type Props = {
@@ -26,6 +27,7 @@ export default function ComputerRefChip({ computer_id }: Props) {
}
const current = computers[0]?.id == computer.id;
const Icon = computerIcon({ connection: computer.connection });
return (
<Button
@@ -45,7 +47,7 @@ export default function ComputerRefChip({ computer_id }: Props) {
: "bg-transparent hover:bg-sunken",
)}
>
<Monitor size={14} aria-hidden className="shrink-0" />
<Icon size={14} aria-hidden className="shrink-0" />
<Span className="min-w-0 truncate">{name}</Span>
{current ? <Check size={14} aria-hidden className="shrink-0" /> : null}
</Button>
@@ -40,7 +40,7 @@ export default function ComputerListRow({
return (
<SettingsListRow
avatar={<ComputerIconTile />}
avatar={<ComputerIconTile connection={computer.connection} />}
href={
linked ? `/admin/settings/computers/${computer.id}` : undefined
}
@@ -31,7 +31,7 @@ export default function ComputerOverviewGroup({ computer }: Props) {
}
>
<Row className="w-full gap-4! flex-nowrap items-center">
<ComputerIconTile />
<ComputerIconTile connection={computer.connection} />
<Stack className="grow min-w-0 gap-0!">
<Row className="gap-2! flex-nowrap items-center">
<Span className="text-sm font-bold leading-5 text-ink truncate">
@@ -32,7 +32,12 @@ export default function ProfilePhotoField({
return (
<Row className="w-full gap-4! flex-nowrap items-center">
<UserAvatar src={preview_src} initials={initials} alt="Your photo" size="lg" />
<UserAvatar
src={preview_src}
initials={initials}
alt="Your photo"
size="xxl"
/>
<Stack className="gap-2! min-w-0">
<Row className="gap-2!">
<Button
+14 -5
View File
@@ -1,4 +1,5 @@
import userAuth from "@/src/functions/backend/auth/user-auth";
import grabBotUserMemory from "@/src/functions/backend/db/bots/grab-bot-user-memory";
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";
@@ -11,12 +12,13 @@ import type {
} from "@moduletrace/bunext/types";
/**
* A bot's core instructions and memory, for its panel in the conversation,
* which loads them when it opens (page props leave them out). For super
* admins and admins; only the super admin reaches the coordinator.
* A bot's core instructions and memory for its panel in the conversation,
* which loads them when it opens (page props leave them out), plus what it
* remembers about the user reading it. For super admins and admins; only the
* super admin reaches the coordinator.
*/
export const handler: BunextAPIRouteHandler<
APIResponseObject<{ system_prompt: string; memory: string }>
APIResponseObject<{ system_prompt: string; memory: string; user_memory: string }>
> = async ({ req, body }) => {
try {
if (req.method != "POST") {
@@ -40,7 +42,14 @@ export const handler: BunextAPIRouteHandler<
throw new AppError(`Bot not found.`);
}
return { success: true, singleRes: { system_prompt: bot.system_prompt || "", memory: bot.memory || "" } };
return {
success: true,
singleRes: {
system_prompt: bot.system_prompt || "",
memory: bot.memory || "",
user_memory: (await grabBotUserMemory({ bot_id: bot.id, user_id: user.id })) || "",
},
};
} catch (error: unknown) {
return { success: false, msg: safeErrorMessage({ error }) };
}
@@ -0,0 +1,44 @@
import userAuth from "@/src/functions/backend/auth/user-auth";
import deleteBotSession from "@/src/functions/backend/db/bot-sessions/delete-bot-session";
import { BotSessionIdRequestSchema } from "@/src/schemas/bot-schema";
import AppError from "@/src/utils/app-error";
import parseWithSchema from "@/src/utils/parse-with-schema";
import isReadOnlyUser from "@/src/utils/rbac/is-read-only-user";
import safeErrorMessage from "@/src/utils/safe-error-message";
import type {
APIResponseObject,
BunextAPIRouteHandler,
} from "@moduletrace/bunext/types";
/**
* Deletes one of the session user's sessions, with its messages. The
* active one hands the conversation a fresh session.
*/
export const handler: BunextAPIRouteHandler<APIResponseObject> = async ({ req, body }) => {
try {
if (req.method != "POST") {
throw new AppError(`Method not allowed`);
}
const { user, user_types } = await userAuth({ req });
if (!user?.logged_in_status || !user.id) {
return { success: false, msg: `Unauthorized`, logoutUser: true };
}
if (isReadOnlyUser({ user_types: user_types || [] })) {
throw new AppError(`This user can only read records.`);
}
const { session_id } = parseWithSchema({
schema: BotSessionIdRequestSchema,
data: body,
});
await deleteBotSession({ session_id, user_id: user.id });
return { success: true, msg: `Session deleted.` };
} catch (error: unknown) {
return { success: false, msg: safeErrorMessage({ error }) };
}
};
+11
View File
@@ -0,0 +1,11 @@
import { describe, expect, test } from "bun:test";
import { Monitor, Server } from "lucide-react";
import computerIcon from "./computer-icon";
describe("computerIcon", () => {
test("a container wears a monitor, an SSH machine a server", () => {
expect(computerIcon({ connection: "docker" })).toBe(Monitor);
expect(computerIcon({ connection: null })).toBe(Monitor);
expect(computerIcon({ connection: "ssh" })).toBe(Server);
});
});
+14
View File
@@ -0,0 +1,14 @@
import { Monitor, Server } from "lucide-react";
/**
* A computer's icon: a monitor for the sandboxed container this app makes
* (a screen and a shell of its own), a server for a remote machine reached
* over SSH, which has no screen here.
*/
export default function computerIcon({
connection,
}: {
connection?: string | null;
}) {
return connection == "ssh" ? Server : Monitor;
}
+23 -1
View File
@@ -12,6 +12,12 @@ type Params = {
* whoever has it.
*/
admin_workspace_ids?: number[];
/**
* The workspace the run is in (`bot_sessions.workspace_id`): then only
* that workspace's tasks are in reach, never another workspace's nor
* the bot's own list outside one.
*/
workspace_id?: number | string | null;
/**
* The table alias the condition reads.
*/
@@ -23,14 +29,30 @@ type Params = {
* worker reaches its own list and the tasks it has in the workspaces it
* still works in, never another bot's, plus every workspace-wide task (no
* bot) in those workspaces. A workspace admin also reaches every task in
* that workspace; the coordinator every task in the install.
* that workspace; the coordinator every task in the install. A run in a
* workspace is scoped to it: its session reaches nothing outside it, which
* is the whole point of working there.
*/
export default function botTaskScopesSql({
bot_id,
is_coordinator,
admin_workspace_ids = [],
workspace_id,
alias = "t",
}: Params): SqlCondition {
if (workspace_id) {
const id = Number(workspace_id);
if (is_coordinator || admin_workspace_ids.map(Number).includes(id)) {
return { sql: `${alias}.workspace_id = ?`, values: [id] };
}
return {
sql: `(${alias}.workspace_id = ? AND ${alias}.workspace_id IN (SELECT workspace_id FROM workspace_bots WHERE bot_id = ?) AND (${alias}.bot_id = ? OR ${alias}.bot_id IS NULL))`,
values: [id, Number(bot_id), Number(bot_id)],
};
}
if (is_coordinator) return { sql: `1`, values: [] };
const admin_ids = admin_workspace_ids.map(Number).filter(Boolean);
+29
View File
@@ -86,6 +86,35 @@ describe("botTaskScopesSql for a workspace admin", () => {
});
});
describe("botTaskScopesSql in a workspace", () => {
test("a worker's run there reaches that workspace's tasks and nothing else, not even its own list", () => {
expect(ids({ condition: botTaskScopesSql({ bot_id: 3, is_coordinator: false, workspace_id: 10 }) })).toEqual([110]);
expect(ids({ condition: botTaskScopesSql({ bot_id: 3, is_coordinator: false, workspace_id: 11 }) })).toEqual([112]);
});
test("the coordinator's run there reaches every task of that workspace alone", () => {
expect(ids({ condition: botTaskScopesSql({ bot_id: 1, is_coordinator: true, workspace_id: 11 }) })).toEqual([
111, 112, 113,
]);
expect(ids({ condition: botTaskScopesSql({ bot_id: 1, is_coordinator: true, workspace_id: 10 }) })).toEqual([110]);
});
test("a workspace admin's run there reaches its whole workspace and no other", () => {
db.run(`INSERT INTO workspace_bots VALUES (11, 4)`);
expect(
ids({ condition: botTaskScopesSql({ bot_id: 4, is_coordinator: false, admin_workspace_ids: [11], workspace_id: 11 }) }),
).toEqual([111, 112, 113]);
expect(
ids({ condition: botTaskScopesSql({ bot_id: 4, is_coordinator: false, admin_workspace_ids: [11], workspace_id: 10 }) }),
).toEqual([]);
db.run(`DELETE FROM workspace_bots WHERE bot_id = 4`);
});
test("workspace_id given as a string still scopes", () => {
expect(ids({ condition: botTaskScopesSql({ bot_id: 3, is_coordinator: false, workspace_id: "10" }) })).toEqual([110]);
});
});
describe("workspace-wide tasks", () => {
test("every bot working there reaches one, no bot elsewhere does, and users see it with the workspace", () => {
db.run(`INSERT INTO tasks VALUES (114, NULL, 11, NULL)`);