Compare commits

...
8 Commits
Author SHA1 Message Date
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
tben b69714a750 Reconnect a lost browser session, and stop a run stuck on one tool
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
A routine's browser died mid-run, every browser call then failed with
"Session not found" for 55 minutes, and the retry that reached it burned
18M prompt tokens probing ports its own account is closed off from.

- Reconnect once when a tool error says the MCP session is gone.
- Say in the tool result that the browser belongs to the computer and only
  the user can restart it, for every browser error (the settle-timeout hint
  moved out of with-browser-outputs, where an isError result never reached
  it).
- End a run at a wrap up after 20 calls of one tool that all answered the
  same, and tell it so (stuckToolNote).
- Close every prompt with RoadblockNote: stop after two or three attempts
  at the same error and report, rather than working around it.
2026-11-24 16:18:53 +01:00
81 changed files with 1283 additions and 279 deletions
+2 -2
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.
@@ -121,7 +121,7 @@ Enables SQLite foreign keys (`enableForeignKeys`), `bunextInit()`, `ensureDocker
`composeBotPrompt` (`src/utils/compose-bot-prompt.ts`, via `grab-bot-prompt`): core `system_prompt`, install-wide append (`bot_system_prompt_append`), then in a workspace its context, the bot's instructions there and the run's user's role there (`workspace_user_roles`), then core `memory`, per-user memory (`bot_user_memories`), workspace memory (`workspace_bots.memory`). Core memory is never about one user. `update_memory` defaults to `user` (`workspace` in a workspace); core only for what holds for everyone. Whole-text replace, capped at `AppData.PromptMaxLength`. Each whole-text replace (`update_workspace`'s context, `set_bot_workspace_instructions`, `update_memory`) refuses once a save that would drop a section (`markdownHeadings`) or cut the text below `AppData.SharedTextShrinkShare` of its length (`sharedTextProblem`, `src/utils/shared-text-guard.ts`), until the caller passes `replace: true`; the context is read before it is rewritten with `find_workspace` `include_context` (coordinator wherever it works, and a workspace admin), and each of them reads its save back before reporting it. Each memory section says it shapes how the bot does the work, never what it does beyond the request.
Every run also gets `RequestScopeNote` (`src/data/harness-prompts.ts`): the user's request sets the scope, and crew changes (create, place, remove, assign a computer, change a role) and handing work out (delegating, handing over a task or routine) happen only once the user asked for them, through one `ask_user` card in a reply or task, or as a proposal in a run nobody watches (routine, hook call, crew request). The way they named is part of the request too: a tool, app, service, provider or path they asked for is the one to use, a blocked one is reported and asked about, never swapped for another way that reaches the same result, and a probe is not a deliverable. Memory, habits and the bot's own initiative never widen a request.
Every run also gets `RequestScopeNote` (`src/data/harness-prompts.ts`): the user's request sets the scope, and crew changes (create, place, remove, assign a computer, change a role) and handing work out (delegating, handing over a task or routine) happen only once the user asked for them, through one `ask_user` card in a reply or task, or as a proposal in a run nobody watches (routine, hook call, crew request). The way they named is part of the request too: a tool, app, service, provider or path they asked for is the one to use, a blocked one is reported and asked about, never swapped for another way that reaches the same result, and a probe is not a deliverable. Memory, habits and the bot's own initiative never widen a request. Every prompt ends with `RoadblockNote`: a run that is blocked (a tool failing again and again, a computer or page down, access it does not have) stops after two or three attempts and reports what failed and what the user must do, never works around it another way or describes the work as done. The app enforces the tool-loop half itself: `AppData.HarnessStuckToolRepeats` consecutive calls of one tool with the same answer end the run at a wrap up (`stuckToolNote`, `run-text-loop.ts`).
### Queue (`bots_queue`)
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "cobble",
"version": "0.28.0",
"version": "0.28.4",
"module": "index.ts",
"type": "module",
"private": true,
+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>
);
}
+12
View File
@@ -672,6 +672,18 @@ export const AppData = {
* row, each repeat resending the whole transcript.
*/
HarnessSameFailureRetries: 1,
/**
* How many calls of one tool in a row end a run: at this count the run
* stops working and gets its wrap up, where it reports what it has and
* what is blocking it (`stuckToolNote`). A reply with no step or token
* limit otherwise loops until someone stops it: one spent 194 calls of
* `search_computers` and 18M prompt tokens probing a browser that its
* account can never reach (Nov 2026). Counted by tool name and its
* answer, since the loop's calls each had different arguments, and a run
* that clicks through a long list one item at a time gets a different
* answer each time and is not stuck.
*/
HarnessStuckToolRepeats: 20,
/**
* How many times the review may send an answer back to be written again
* before the run stops without an answer. A note fixes most answers; the
+35
View File
@@ -51,6 +51,19 @@ export const SupersededSnapshotNote = `[An older page snapshot or find, replaced
*/
export const browserSettleTimeoutNote = `This timed out because the element never stopped moving: the page animates, so the same call will time out in the same place however often it is made. Drive it from the page itself instead: browser_evaluate with getByRole('button', { name: 'Publish' }).click(), or with element.click() on the element.`;
/**
* Appended to a browser tool whose connection to the computer's Playwright
* MCP is gone (`browserRecoveryHint`). The agent supervises that server and
* starts it again on its own, so the bridge being down is the computer's
* problem, not the run's: a worker account cannot reach the agent, CDP or
* the MCP port at all (`guardServicePorts`), and only the user can restart
* the computer. One routine spent 18M prompt tokens probing 9222/8931,
* starting its own Chrome and killing processes before it was told to stop.
*/
export const browserBridgeNote = `The browser belongs to the computer and is started and supervised there, so this run cannot start, restart or repair it. Your account is a worker account: the browser's ports are closed to it on purpose, so starting Chrome, killing processes, starting the MCP server or probing ports cannot work and is not the fix.
Only the user can restart the computer (its Restart button on the computer's page) or sign in to a site again on its screen. Stop here and report: what you were doing, what the browser last showed, and what the user has to do. Do not spend more calls on it.`;
/**
* The folder-ref example a note shows, always over the running bot's own
* folder: a literal owner id in the prompt teaches the bot to name another
@@ -308,6 +321,19 @@ The user's request sets the scope. Do what they asked, in the scope they gave, a
}
- If the user declines, or doesn't pick it, drop it: don't do it anyway, don't do a smaller version of it, and don't offer it again in this conversation.`;
/**
* The last thing in every bot prompt (`composeBotPrompt`), not a note added
* once a tool has already failed: what a blocked run does is the app's rule,
* in replies, tasks, routines and hook calls alike. One routine spent 18M
* prompt tokens probing a browser its account can never reach, and stopped
* only when the user told it to (Nov 2026).
*/
export const RoadblockNote = `# When you are blocked
When something stops the work - a tool that keeps failing, a page or computer that is down, access you do not have, a step that will not work however you try it - stop and report. Say what you were doing, what failed, what you tried, and what the user has to do next.
Two or three attempts at the same error is the limit: another one buys the same answer and resends this whole conversation. Don't keep trying variations, don't switch to a way the user didn't ask for to get past it, and never describe the work as done while it is blocked. A clear block the user can act on is the right answer.`;
/**
* Added to chat replies and to tasks the user started: before acting on
* something unclear, a bot asks (`ask_user`) rather than guesses.
@@ -499,6 +525,15 @@ export const failedToolCallNote = ({
Nothing has run since that could change that answer, so calling it once more only buys the same error (and resends this whole conversation). Fix the call itself: change the arguments, do the step it is missing first, or report it as blocked.`;
/**
* What the wrap up says when it comes because one tool was called over and
* over (`AppData.HarnessStuckToolRepeats`): the run is not out of steps or
* tokens, it is out of ideas, and another call of the same tool buys the
* same answer for the price of the whole conversation.
*/
export const stuckToolNote = ({ name, repeats }: { name: string; repeats: number }) =>
`This run has called ${name} ${repeats} times in a row and got no further each time. Nothing about the situation has changed since the first call, so another one only buys the same answer (and resends this whole conversation). Stop working on it and say what is blocking it.`;
/**
* Told once to a run that wrote a message for the user and then called a
* tool: only the run's last message goes out, so that one never arrived.
@@ -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>;
+15 -3
View File
@@ -4,7 +4,16 @@ import listMcpTools from "./list-mcp-tools";
import mcpHarnessTool from "./mcp-harness-tool";
type Params = {
client: Client;
/**
* The connected client, or how to connect on the first call and again
* after a lost session.
*/
client: Client | (() => Promise<Client>);
/**
* Drops a lost connection so the next call connects again
* (`mcpHarnessTool`).
*/
reconnect?: () => Promise<void>;
/**
* Tool names to leave out.
*/
@@ -25,11 +34,14 @@ type Params = {
*/
export default async function grabMcpTools({
client,
reconnect,
exclude = [],
image_focus,
redact,
}: Params): Promise<HarnessTool[]> {
return (await listMcpTools({ client }))
const connected = typeof client == "function" ? await client() : client;
return (await listMcpTools({ client: connected }))
.filter((tool) => !exclude.includes(tool.name))
.map((tool) => mcpHarnessTool({ tool, client, image_focus, redact }));
.map((tool) => mcpHarnessTool({ tool, client, reconnect, image_focus, redact }));
}
@@ -0,0 +1,20 @@
import { describe, expect, test } from "bun:test";
import isLostMcpSession from "./is-lost-mcp-session";
describe("isLostMcpSession", () => {
test("matches the errors a restarted server gives", () => {
expect(
isLostMcpSession({
text: "Error: Streamable HTTP error: Error POSTing to endpoint: Session not found",
}),
).toBe(true);
expect(isLostMcpSession({ text: "Error: fetch failed" })).toBe(true);
expect(isLostMcpSession({ text: "Error: Connection refused (ECONNREFUSED)" })).toBe(true);
expect(isLostMcpSession({ text: "MCP error -32000: Connection closed" })).toBe(true);
});
test("leaves a tool's own error alone", () => {
expect(isLostMcpSession({ text: "Error: Element not found: ref=e12" })).toBe(false);
expect(isLostMcpSession({ text: "Error: Wrong arguments for browser_click." })).toBe(false);
});
});
+18
View File
@@ -0,0 +1,18 @@
/**
* Whether an MCP error means the session this run opened is gone. The
* computer's agent restarts Playwright MCP on its own whenever it exits
* (`computer/agent/start-services.ts`), and a restart invalidates every
* session id the server handed out: the next call fails with `Session not
* found` for the rest of the run, which is how a routine's browser died
* mid-pass (Nov 2026). Calling again after a reconnect is safe: a session id
* the server no longer knows cannot run the call a second time.
*
* Broad on purpose: a false match costs one reconnect that fails the same
* way, a miss costs the run.
*/
const LostSession =
/session not found|not connected|connection (?:closed|refused)|fetch failed|socket hang up|transport closed|ECONNRESET|ECONNREFUSED/i;
export default function isLostMcpSession({ text }: { text: string }) {
return LostSession.test(text);
}
+79
View File
@@ -0,0 +1,79 @@
import { describe, expect, test } from "bun:test";
import type { Client } from "@modelcontextprotocol/sdk/client/index.js";
import mcpHarnessTool from "./mcp-harness-tool";
const tool = { name: "browser_snapshot", description: "Looks at the page.", input_schema: {} };
const lost = "Streamable HTTP error: Error POSTing to endpoint: Session not found";
function fakeClient({ fail }: { fail: () => string | null }) {
const client = {
calls: 0,
async callTool() {
client.calls++;
const error = fail();
if (error) throw new Error(error);
return { content: [{ type: "text", text: "The page." }] };
},
};
return client;
}
describe("mcpHarnessTool", () => {
test("reconnects once and makes the call again when the session is gone", async () => {
const broken = fakeClient({ fail: () => lost });
const fresh = fakeClient({ fail: () => null });
let current = broken as unknown as Client;
let reconnects = 0;
const call = mcpHarnessTool({
tool,
client: async () => current,
reconnect: async () => {
reconnects++;
current = fresh as unknown as Client;
},
});
expect(await call.run({ args: {}, signal: new AbortController().signal })).toBe("The page.");
expect(reconnects).toBe(1);
expect(broken.calls).toBe(1);
expect(fresh.calls).toBe(1);
});
test("a tool's own error is passed on without reconnecting", async () => {
const broken = fakeClient({ fail: () => "Element not found: ref=e12" });
let reconnects = 0;
const call = mcpHarnessTool({
tool,
client: broken as unknown as Client,
reconnect: async () => {
reconnects++;
},
});
await expect(call.run({ args: {}, signal: new AbortController().signal })).rejects.toThrow("Element not found");
expect(reconnects).toBe(0);
expect(broken.calls).toBe(1);
});
test("a bridge that is really down fails after one retry", async () => {
const broken = fakeClient({ fail: () => lost });
let reconnects = 0;
const call = mcpHarnessTool({
tool,
client: broken as unknown as Client,
reconnect: async () => {
reconnects++;
},
});
await expect(call.run({ args: {}, signal: new AbortController().signal })).rejects.toThrow("Session not found");
expect(reconnects).toBe(1);
expect(broken.calls).toBe(2);
});
});
+61 -23
View File
@@ -1,6 +1,7 @@
import type { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { AppData } from "@/src/data/app-data";
import type { HarnessTool } from "../types";
import isLostMcpSession from "./is-lost-mcp-session";
import mcpResultToText from "./mcp-result-to-text";
type Params = {
@@ -13,9 +14,17 @@ type Params = {
*/
tool: { name: string; description?: string; input_schema: Record<string, unknown> };
/**
* The connected client, or how to get it on the first call.
* The connected client, or how to get it on the first call (and again
* after `reconnect`).
*/
client: Client | (() => Promise<Client>);
/**
* Closes the lost connection and drops it, so the next call connects
* again: a server that restarts mid-run leaves every call failing with
* `Session not found` for the rest of the run, and a long run outlives
* one restart (`isLostMcpSession`).
*/
reconnect?: () => Promise<void>;
/**
* What a reading of an image this tool returns should look for, for a
* model that can't see it.
@@ -30,44 +39,73 @@ type Params = {
* results come back via `mcpResultToText`, the text redacted and images
* (screenshots) handed back for the run to show the model, or have read
* (and the reading redacted) for one that can't see.
*
* A call that fails because the session is gone is reconnected and made
* once more: a session the server does not know has nothing left to run.
*/
export default function mcpHarnessTool({
name,
tool,
client,
reconnect,
image_focus,
redact = (text) => text,
}: Params): HarnessTool {
const call = async ({ args, signal }: { args: Record<string, unknown>; signal: AbortSignal }) => {
const connected = typeof client == "function" ? await client() : client;
const { text, images } = mcpResultToText({
result: await connected.callTool({ name: tool.name, arguments: args }, undefined, {
signal,
timeout: AppData.McpToolTimeoutMs,
resetTimeoutOnProgress: true,
}),
});
if (!images.length) return redact(text);
return {
text: redact(text),
images: images.map(({ data, mime_type }) => ({
url: `data:${mime_type};base64,${data}`,
focus: image_focus,
redact,
})),
};
};
return {
name: name || tool.name,
description: tool.description || tool.name,
parameters: tool.input_schema,
run: async ({ args, signal }) => {
try {
const connected = typeof client == "function" ? await client() : client;
const { text, images } = mcpResultToText({
result: await connected.callTool({ name: tool.name, arguments: args }, undefined, {
signal,
timeout: AppData.McpToolTimeoutMs,
resetTimeoutOnProgress: true,
}),
});
if (!images.length) return redact(text);
return {
text: redact(text),
images: images.map(({ data, mime_type }) => ({
url: `data:${mime_type};base64,${data}`,
focus: image_focus,
redact,
})),
};
return await call({ args, signal });
} catch (error: unknown) {
if (error instanceof Error) error.message = redact(error.message);
throw error;
if (!reconnect || !isLostMcpSession({ text: messageOf(error) })) throw redacted({ error, redact });
await reconnect().catch(() => null);
try {
return await call({ args, signal });
} catch (retry_error: unknown) {
throw redacted({ error: retry_error, redact });
}
}
},
};
}
function messageOf(error: unknown) {
return error instanceof Error ? error.message : String(error);
}
/**
* A tool error is handed to the model, so a secret the server echoed can't
* ride along in it.
*/
function redacted({ error, redact }: { error: unknown; redact: (text: string) => string }) {
if (error instanceof Error) error.message = redact(error.message);
return error;
}
+94 -6
View File
@@ -2,7 +2,7 @@ import { afterAll, describe, expect, mock, test } from "bun:test";
import { z } from "zod";
import { AppData } from "@/src/data/app-data";
import { UnlimitedLimit } from "@/src/utils/run-limit";
import { alreadyRanToolNote, answerNotSentNote, closingFailedNote, closingMixedNote, closingNoTextNote, contextTrimmedNote, DroppedToolImageNote, repeatedAnswerNote, replyClosingMixedNote, replyClosingRequiredNote, replyDraftNote, replyNoTextNote, SupersededSnapshotNote, ToolImagesNote } from "@/src/data/harness-prompts";
import { alreadyRanToolNote, answerNotSentNote, closingFailedNote, closingMixedNote, closingNoTextNote, contextTrimmedNote, DroppedToolImageNote, repeatedAnswerNote, replyClosingMixedNote, replyClosingRequiredNote, replyDraftNote, replyNoTextNote, stuckToolNote, SupersededSnapshotNote, ToolImagesNote } from "@/src/data/harness-prompts";
import HarnessError from "../harness-error";
import type { HarnessCandidate, HarnessTool } from "../types";
import type { HarnessTrace } from "../trace/types";
@@ -55,6 +55,13 @@ const remember: HarnessTool<{ note: string }> = {
},
};
const glance: HarnessTool<{ at: string }> = {
name: "glance",
description: "Looks at something.",
schema: z.object({ at: z.string() }),
run: async () => "Looked.",
};
const asked: string[] = [];
const askUser: HarnessTool<{ question: string }> = {
@@ -283,16 +290,23 @@ describe("runTextLoop", () => {
test("a run with no step limit keeps going, and records the window it works to", async () => {
memory.length = 0;
const loop_call = {
tool_calls: [{ id: "c", name: "remember", arguments: `{"note":"x"}` }],
};
/**
* Two tools in turn: the same one 30 times in a row is a stuck run
* now (`HarnessStuckToolRepeats`), which is not what this tests.
*/
const loop_calls = [
{ tool_calls: [{ id: "c", name: "remember", arguments: `{"note":"x"}` }] },
{ tool_calls: [{ id: "c", name: "glance", arguments: `{"at":"x"}` }] },
];
const turns = 30;
const { generate, seen } = scripted(Array.from({ length: turns }, () => loop_call));
const { generate, seen } = scripted(
Array.from({ length: turns }, (_turn, index) => loop_calls[index % loop_calls.length]!),
);
const result = await runTextLoop({
system: "s",
messages: [{ role: "user", content: "go" }],
tools: [remember],
tools: [remember, glance],
max_steps: UnlimitedLimit,
generate,
resolveCandidates,
@@ -483,6 +497,80 @@ describe("runTextLoop", () => {
expect(prompt).not.toContain("start_task");
});
test("stops a run stuck on one tool and makes it report", async () => {
const repeats = AppData.HarnessStuckToolRepeats;
const { generate, seen } = scripted(
Array.from({ length: repeats }, (_, index) => ({
text: null,
tool_calls: [{ id: `c${index}`, name: "remember", arguments: `{"note":"${index}"}` }],
})),
);
await runTextLoop({
system: "s",
messages: [{ role: "user", content: "go" }],
tools: [remember],
generate,
resolveCandidates,
});
const prompts = seen.map((params) => String(params.messages.at(-1)!.content));
expect(prompts.some((prompt) => prompt.includes(stuckToolNote({ name: "remember", repeats })))).toBe(true);
expect(seen).toHaveLength(repeats + 1);
});
test("a tool called over and over that answers differently each time is not stuck", async () => {
let counted = 0;
const counter: HarnessTool<Record<string, never>> = {
name: "count",
description: "Counts.",
schema: z.object({}),
run: async () => `Line ${++counted}.`,
};
const calls = AppData.HarnessStuckToolRepeats + 2;
const { generate, seen } = scripted(
Array.from({ length: calls }, (_, index) => ({
text: null,
tool_calls: [{ id: `c${index}`, name: "count", arguments: `` }],
})),
);
await runTextLoop({
system: "s",
messages: [{ role: "user", content: "go" }],
tools: [counter],
generate,
resolveCandidates,
});
const prompts = seen.map((params) => String(params.messages.at(-1)!.content));
expect(prompts.some((prompt) => prompt.includes("This run has called"))).toBe(false);
});
test("a run one call short of the limit is not stopped", async () => {
const calls = AppData.HarnessStuckToolRepeats - 1;
const { generate, seen } = scripted(
Array.from({ length: calls }, (_, index) => ({
text: null,
tool_calls: [{ id: `c${index}`, name: "remember", arguments: `{"note":"${index}"}` }],
})),
);
await runTextLoop({
system: "s",
messages: [{ role: "user", content: "go" }],
tools: [remember],
generate,
resolveCandidates,
});
const prompts = seen.map((params) => String(params.messages.at(-1)!.content));
expect(prompts.some((prompt) => prompt.includes("This run has called"))).toBe(false);
});
test("warns once, a few steps before the wrap up, in a long enough run", async () => {
const max_steps = AppData.HarnessStepsLowMinSteps;
const loop_call = {
+54 -5
View File
@@ -17,6 +17,7 @@ import {
replyDraftNote,
replyNoTextNote,
staticPromptOverBudgetNote,
stuckToolNote,
tokensLowNote,
} from "@/src/data/harness-prompts";
import { isUnlimitedLimit, type RunLimit, UnlimitedLimit } from "@/src/utils/run-limit";
@@ -269,17 +270,28 @@ export const WrapUpSavingTurns = 2;
export const wrapUpPrompt = ({
uses,
reason = "steps",
tool,
saving = [],
hand_off = [],
answer = [],
}: {
uses: HarnessToolUse[];
reason?: "steps" | "tokens";
reason?: "steps" | "tokens" | "stuck";
/**
* The tool the run was stuck on, with the wrap up it caused (`stuck`).
*/
tool?: { name: string; repeats: number };
saving?: string[];
hand_off?: string[];
answer?: string[];
}) =>
`${reason == "tokens" ? "This run has used all the tokens it may spend." : "You've used every step this run allows."} ${wrapUpToolsPrompt({
`${
reason == "stuck" && tool
? stuckToolNote(tool)
: reason == "tokens"
? "This run has used all the tokens it may spend."
: "You've used every step this run allows."
} ${wrapUpToolsPrompt({
saving,
hand_off,
answer,
@@ -568,6 +580,17 @@ export default async function runTextLoop({
const step_ceiling = isUnlimitedLimit(max_steps) ? Infinity : max_steps;
const warn_at = isUnlimitedLimit(max_steps) ? 0 : stepsLowWarningLeft({ max_steps });
/**
* The last tool the run called, how many times in a row it called it,
* and the answer it got: the same call giving the same answer is a run
* getting nowhere, and at `AppData.HarnessStuckToolRepeats` it stops and
* reports (`same_tool.stuck`) instead of paying for that answer again
* with the whole conversation.
*/
const same_tool: {
last: { name: string; answer: string; count: number } | null;
stuck: { name: string; repeats: number } | null;
} = { last: null, stuck: null };
let prefer_key = planned_key;
/**
* How many answers the review has sent back, and the last one it faulted,
@@ -767,7 +790,12 @@ export default async function runTextLoop({
max_prompt_tokens > 0 &&
usage.prompt_tokens >= max_prompt_tokens,
);
const wrap_up = out_of_steps || out_of_tokens;
const wrap_up: boolean = out_of_steps || out_of_tokens || same_tool.stuck !== null;
/**
* Why the run is wrapping up: its steps, its tokens, or one tool
* called over and over.
*/
const wrap_reason = same_tool.stuck ? "stuck" : out_of_steps ? "steps" : "tokens";
/**
* The saving turn: only the tools a wrap up has left. Without one
* of them, or once it had its round, the wrap up is the old one,
@@ -797,7 +825,8 @@ export default async function runTextLoop({
transcript,
content: wrapUpPrompt({
uses: tool_uses,
reason: out_of_steps ? "steps" : "tokens",
reason: wrap_reason,
tool: same_tool.stuck ?? undefined,
saving: wrap_up_saving ? save_tools.map((tool) => tool.name) : [],
hand_off: wrap_up_saving ? hand_off_tools.map((tool) => tool.name) : [],
answer: answer_tools.map((tool) => tool.name),
@@ -808,7 +837,13 @@ export default async function runTextLoop({
kind: "event",
index,
name: "wrap_up",
text: `${out_of_steps ? "Out of steps" : "Out of tokens"}. ${wrap_tools.length ? `It has one turn left with ${wrap_tools.map((tool) => tool.name).join(", ")}.` : "It has no tool left and must answer now."}`,
text: `${
same_tool.stuck
? `Stuck on ${same_tool.stuck.name} (${same_tool.stuck.repeats} calls in a row)`
: out_of_steps
? "Out of steps"
: "Out of tokens"
}. ${wrap_tools.length ? `It has one turn left with ${wrap_tools.map((tool) => tool.name).join(", ")}.` : "It has no tool left and must answer now."}`,
});
}
@@ -1229,6 +1264,20 @@ export default async function runTextLoop({
tool_uses.push({ name: call.name, ok });
/**
* The same tool over and over, answering the same thing, gets
* the run nowhere: it stops and reports at the wrap up
* (`AppData.HarnessStuckToolRepeats`).
*/
const previous = same_tool.last;
const repeats =
previous && previous.name == call.name && previous.answer == content ? previous.count + 1 : 1;
same_tool.last = { name: call.name, answer: content, count: repeats };
if (!same_tool.stuck && repeats >= AppData.HarnessStuckToolRepeats) {
same_tool.stuck = { name: call.name, repeats };
}
await traced({
kind: "tool",
index,
+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,
});
@@ -1,5 +1,5 @@
import { describe, expect, test } from "bun:test";
import { browserSettleTimeoutNote } from "@/src/data/harness-prompts";
import { browserBridgeNote, browserSettleTimeoutNote } from "@/src/data/harness-prompts";
import browserRecoveryHint from "./browser-recovery-hint";
const settle_timeout = `Error: ### Error
@@ -19,6 +19,12 @@ describe("browserRecoveryHint", () => {
expect(browserRecoveryHint({ name: "laptop__browser_click", text: settle_timeout })).toBe(browserSettleTimeoutNote);
});
test("says the bridge is the computer's after the session dies", () => {
const lost = "Error: Streamable HTTP error: Error POSTing to endpoint: Session not found";
expect(browserRecoveryHint({ name: "browser_snapshot", text: lost })).toBe(browserBridgeNote);
});
test("says nothing about a failure that already names its own fix", () => {
const bad_target = `Error: ### Error
Error: "button "More account and team options"" is not a valid target. Use a ref from the page snapshot (e.g. "e5"), a CSS selector, or a locator.`;
@@ -1,5 +1,6 @@
import { browserSettleTimeoutNote } from "@/src/data/harness-prompts";
import { browserBridgeNote, browserSettleTimeoutNote } from "@/src/data/harness-prompts";
import isBrowserTool from "@/src/utils/browser-tool-name";
import isLostMcpSession from "../../mcp/is-lost-mcp-session";
/**
* Playwright's wording for an action that gave up on an element which never
@@ -10,15 +11,24 @@ import isBrowserTool from "@/src/utils/browser-tool-name";
const SettleTimeout = /waiting for element to be visible, enabled and stable/i;
/**
* What to add after a browser action that timed out waiting for its element
* to settle, or nothing when the call did not fail that way. The run has
* just spent 5 seconds on it, and retrying the same call is what one Canva
* run did five times in a row.
* What to add to a browser tool's error, or nothing when the call failed
* for a reason the error already explains (a bad target, a missing
* element). Two failures say more than the error itself:
*
* - the element never settled, so retrying it is what one Canva run did
* five times in a row;
* - the connection to the computer's browser bridge is gone, which is the
* computer's to fix, not the run's (`browserBridgeNote`).
*
* Applied where tool errors become the model's text (`run-tool-call`): a
* result the server flags as an error is thrown, so a wrapper around a
* successful result never sees it.
*/
export default function browserRecoveryHint({ name, text }: { name: string; text: string }) {
if (!isBrowserTool({ name })) return "";
if (!text.startsWith("Error:")) return "";
if (!SettleTimeout.test(text)) return "";
if (SettleTimeout.test(text)) return browserSettleTimeoutNote;
if (isLostMcpSession({ text })) return browserBridgeNote;
return browserSettleTimeoutNote;
}
return "";
}
@@ -1,3 +1,4 @@
import type { Client } from "@modelcontextprotocol/sdk/client/index.js";
import type { ComputerApi } from "@/src/functions/backend/computers/computer-fetch";
import { AppData } from "@/src/data/app-data";
import { ComputerMcpExcludedTools } from "@/src/dict/computer-dict";
@@ -213,9 +214,28 @@ export default async function openComputerTools({
*/
const redact_page = (text: string) => redact(maskPasswordFieldValues({ text }));
const client = browser
? await connectMcpServer({ url: target.url, headers: { authorization: `Bearer ${target.token}` }, signal })
: null;
/**
* Connected on the first browser call, and again after the computer's
* agent restarts Playwright MCP under the run: a session it handed out
* stops existing, and every call fails with `Session not found` until
* the run connects again (`mcpHarnessTool`).
*/
const link: { client: Client | null } = { client: null };
const connect = async () => {
const client =
link.client ??
(link.client = await connectMcpServer({
url: target.url,
headers: { authorization: `Bearer ${target.token}` },
signal,
}));
return client;
};
const reconnect = async () => {
await link.client?.close().catch(() => null);
link.client = null;
};
const context: ComputerToolContext = {
computer: target,
computer_id: Number(computer_id),
@@ -228,9 +248,10 @@ export default async function openComputerTools({
};
try {
const browser_tools = client
const browser_tools = browser
? await grabMcpTools({
client,
client: connect,
reconnect,
exclude: ComputerMcpExcludedTools,
redact: redact_page,
image_focus: "This is a screenshot of a web page. Describe the page layout, text, buttons and form fields, and any errors or popups.",
@@ -272,11 +293,11 @@ export default async function openComputerTools({
envs: envs.map((env) => ({ key: env.key, description: env.description })),
redact,
close: async () => {
await client?.close().catch(() => {});
await link.client?.close().catch(() => {});
},
};
} catch (error) {
await client?.close().catch(() => {});
await link.client?.close().catch(() => {});
throw error;
}
}
@@ -5,7 +5,6 @@ import type { ComputerApi } from "@/src/functions/backend/computers/computer-fet
import browserOutputText from "@/src/utils/browser-output-text";
import type { ComputerRunDirs } from "@/src/utils/computer-work-dirs";
import type { HarnessTool } from "../../types";
import browserRecoveryHint from "./browser-recovery-hint";
import { computerWorkspaceFullWarning } from "./computer-workspace-room";
type Params = {
@@ -52,10 +51,8 @@ export default function withBrowserOutputs({ tool, computer, dirs }: Params): Ha
? await computerWorkspaceFullWarning({ computer, dirs, signal }).catch(() => null)
: null;
const parts = [lines.length ? `${text}\n### Downloads\n${lines.join("\n")}` : text];
const hint = browserRecoveryHint({ name: tool.name, text });
if (full) parts.push(full);
if (hint) parts.push(hint);
const next = parts.join("\n\n");
+17 -1
View File
@@ -22,6 +22,15 @@ const failing: HarnessTool = {
},
};
const browser_fails: HarnessTool = {
name: "pc__browser_snapshot",
description: "Fails to reach the browser.",
schema: z.object({}),
run: async () => {
throw new Error("Streamable HTTP error: Error POSTing to endpoint: Session not found");
},
};
const signal = new AbortController().signal;
const shot: HarnessTool = {
name: "shot",
@@ -39,7 +48,7 @@ const shot: HarnessTool = {
const run = (name: string, args: string) =>
runToolCall({
call: { id: "1", name, arguments: args },
tools: [echo, failing, shot],
tools: [echo, failing, shot, browser_fails],
signal,
});
const call = async (name: string, args: string) => (await run(name, args)).text;
@@ -49,6 +58,13 @@ describe("runToolCall", () => {
expect(await call("echo", `{"text":"hi"}`)).toBe("hi");
});
test("adds what a failed browser call's error doesn't say", async () => {
const text = await call("pc__browser_snapshot", "");
expect(text.startsWith("Error: Streamable HTTP error")).toBe(true);
expect(text).toContain("Only the user can restart the computer");
});
test("reports problems to the model instead of throwing", async () => {
expect(await call("nope", "{}")).toContain(`no tool called "nope"`);
expect(await call("echo", "{bad")).toContain("weren't valid JSON");
+21 -2
View File
@@ -4,6 +4,7 @@ import isBrowserTool from "@/src/utils/browser-tool-name";
import TaskTimeoutError from "@/src/utils/task-timeout-error";
import withTimeout from "@/src/utils/with-timeout";
import HarnessError from "../harness-error";
import browserRecoveryHint from "./computer/browser-recovery-hint";
import unknownToolArgs from "./unknown-tool-args";
import unknownToolMessage from "./unknown-tool-message";
import toolTimeoutMs from "./tool-timeout-ms";
@@ -130,13 +131,31 @@ async function runTool({ call, tools, signal }: Params): Promise<ToolOutput> {
}
if (error instanceof TaskTimeoutError) {
return { text: `Error: ${error.message}`, images: [], ok: false };
return { text: withBrowserHint({ name: call.name, text: `Error: ${error.message}` }), images: [], ok: false };
}
return { text: `Error: ${error instanceof Error ? error.message : String(error)}`, images: [], ok: false };
return {
text: withBrowserHint({
name: call.name,
text: `Error: ${error instanceof Error ? error.message : String(error)}`,
}),
images: [],
ok: false,
};
}
}
/**
* A failed browser call with what its error doesn't say (`browserRecoveryHint`):
* an element that never settled, or a bridge that is down and belongs to the
* computer. Every other tool, and every other failure, is left as it is.
*/
function withBrowserHint({ name, text }: { name: string; text: string }) {
const hint = browserRecoveryHint({ name, text });
return hint ? `${text}\n\n${hint}` : text;
}
/**
* A result past its tool's cap is cut there, keeping its start and its
* end: a command's answer and the totals or error it ends with are the
+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={100}
/>
}
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;
@@ -59,7 +60,7 @@ export default function BotPanel({ bot, workspace, open, on_open, on_close }: Pr
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 +72,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;
@@ -135,7 +137,7 @@ export default function BotPanel({ bot, workspace, open, on_open, on_close }: Pr
<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 +156,19 @@ 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}
@@ -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">
+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 }) };
}
};
+17
View File
@@ -1,4 +1,5 @@
import { describe, expect, test } from "bun:test";
import { RoadblockNote } from "@/src/data/harness-prompts";
import composeBotPrompt from "./compose-bot-prompt";
describe("composeBotPrompt", () => {
@@ -8,6 +9,7 @@ describe("composeBotPrompt", () => {
"# You are Scout",
"You are a worker bot on this crew. Your role: Finds things.",
"Your bot id is 7. That id is you: when a tool takes a bot id for the bot it is about (your own tasks, your own picture), this is it, and when you name yourself in a message write the ref `[bot:7]`, never another bot's.",
RoadblockNote,
].join("\n\n"),
);
});
@@ -18,6 +20,7 @@ describe("composeBotPrompt", () => {
"# You are A bot",
"You are the coordinator on this crew.",
"Your bot id is 1. That id is you: when a tool takes a bot id for the bot it is about (your own tasks, your own picture), this is it, and when you name yourself in a message write the ref `[bot:1]`, never another bot's.",
RoadblockNote,
].join("\n\n"),
);
});
@@ -35,6 +38,7 @@ describe("composeBotPrompt", () => {
"You are a worker bot on this crew.",
"Your bot id is 4. That id is you: when a tool takes a bot id for the bot it is about (your own tasks, your own picture), this is it, and when you name yourself in a message write the ref `[bot:4]`, never another bot's.",
"Core.",
RoadblockNote,
].join("\n\n"),
);
});
@@ -67,6 +71,7 @@ describe("composeBotPrompt", () => {
"# Memory\n\nYour own notes: they shape how you do what you're asked, never what you're asked to do.\n\n- Cite sources.",
"# Memory about the user\n\nWhat you've learned about the user. It shapes how you do the work, never what you do beyond it.\n\n- The user prefers short replies.",
`# Memory in Launch\n\nYour own notes for this workspace: what you have learned here. They shape how you do the work here, never what you do beyond it. They are not the workspace's description or context, which the user sets above; never call them the workspace's record. The user reads them in the workspace's settings, under this bot's row.\n\n- Marketing signs off on copy.`,
RoadblockNote,
].join("\n\n"),
);
});
@@ -89,6 +94,7 @@ describe("composeBotPrompt", () => {
"# Install-wide instructions\n\nNever invent sources.",
`# Workspace: Launch\n\nYou're working in the workspace "Launch". Follow its context and your instructions for it below, over your general habits where they differ.\n\nThe workspace's context, which the user sets:\n\nThe spring launch.`,
"# Memory\n\nYour own notes: they shape how you do what you're asked, never what you're asked to do.\n\n- Cite sources.",
RoadblockNote,
].join("\n\n"),
);
});
@@ -133,6 +139,17 @@ describe("composeBotPrompt", () => {
expect(composeBotPrompt({ workspace: { name: "Launch" }, user_role: " " })).not.toContain("role in Launch");
});
test("ends with the app's rule for a blocked run, for every bot", () => {
const prompt = composeBotPrompt({
bot: { id: 4, name: "Scout" },
system_prompt: "Core.",
memory: "- Cite sources.",
});
expect(prompt.endsWith(RoadblockNote)).toBe(true);
expect(composeBotPrompt({ system_prompt: "Core." })).not.toContain("# When you are blocked");
});
test("names an untitled workspace even when it has no context", () => {
expect(composeBotPrompt({ workspace: { name: null } })).toBe(
`# Workspace: Untitled\n\nYou're working in the workspace "Untitled". Follow its context and your instructions for it below, over your general habits where they differ.`,
+8
View File
@@ -1,3 +1,5 @@
import { RoadblockNote } from "@/src/data/harness-prompts";
type WorkspacePrompt = {
name?: string | null;
description?: string | null;
@@ -140,6 +142,12 @@ export default function composeBotPrompt({
);
}
/**
* The app's rule for a blocked run, said last so no workspace text or
* memory stands after it.
*/
if (identity) parts.push(RoadblockNote);
return parts.join("\n\n");
}
+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)`);