Compare commits

...
27 Commits
Author SHA1 Message Date
tben 2dc6972de4 Bump version to 0.28.11
CI / check (push) Waiting to run
Release image / image (release) Waiting to run
Release image / computer-image (release) Waiting to run
2026-11-25 14:07:34 +01:00
tben 82fa223691 Refuse a carry while the user's latest message is unanswered 2026-11-25 14:07:34 +01:00
tben 1aa5fc4a05 Bump version to 0.28.10
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
2026-11-25 11:39:05 +01:00
tben afdfad1ecf Read a worker's computer folder through its agent
Since worker bots got their own accounts, a worker's computer folder is
owned by cb-<bot> (2770) and a dev server running as a plain user can't
open it: the files browser treated the folder as missing, so a folder
chip said it may have been moved or deleted. Production runs as root and
never saw it.

When this process is denied a folder on the computers volume, list it
through the computer's agent instead (find as root, NUL-separated, no
symlinks), and stream its files from /api/files/download. The path
rules, size cap and computerPathAllowed check stay the same, and every
other volume reads the host exactly as before.
2026-11-25 11:38:00 +01:00
tben 5087f115e7 Trace a dropped last turn and let it answer once more
Job 687 finished a report and called a tool the last turn no longer
offers: the loop dropped the turn untraced and failed with a notice
blaming the review, which had never run.

The dropped turn and its calls are now traced, a closing_failed event
says what happened, and the model gets one more turn with send_reply
alone before the run gives up. The notice says the tool was gone
instead of that the answer failed the review.
2026-11-25 11:32:08 +01:00
tben 7816affdc8 Name the image model that ran and stop after one timeout 2026-11-25 11:14:10 +01:00
tben 6b048c5b4f Stop a run where it is and have it say what it did
Stop used to kill the job and post a fixed line. Now the run this process
is on is asked to stop at its step and write what it did so far, with only
send_reply offered (StoppedRunNote), and that message is the session's last
word with the run's calls and traces on it. The job completes as stopped:
idle face, no work of its own left running, no crew request or hand-over
answered.

stopBotJobs waits AppData.BotStopSummaryMs (20s, so Bun.serve's idleTimeout
is 30 in production) for that summary, then fails what is still open and
posts the plain stopped line with its run info attached, so a stop never
leaves the thread thinking. A run in another process, or one whose summary
is refused, gets the plain line the way it did before.
2026-11-25 11:04:58 +01:00
tben da304e000b Open the add-provider form in a modal 2026-11-25 10:36:51 +01:00
tben ee4af467b3 Bump version to 0.28.9
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
2026-11-25 10:02:24 +01:00
tben b2c8a788da Ask for a routine's or hook's brief as the plan its run follows
Routines and hook calls never plan at run time, so the tools that make or
change one ask for the instructions as the steps in order, each naming what
it produces.
2026-11-25 09:59:04 +01:00
tben d38a15862a Never plan in routines or hooks, follow a carried session, and open the previous one as its own page
Routines and hook calls already have their plan (the brief, the runbook), so
they get neither the plan tools nor the planning turn, and the approve/in_run
paths those runs needed are gone.

A live conversation now follows its session into a newer one, from the push or
from the catch-up read that reports it, instead of waiting on the old thread
and showing "No answer came."; a page opened on an old session keeps its bar
and hides that row.

The thread's "Show the previous session" opens that session as its own page
instead of paging it inline.
2026-11-25 09:49:33 +01:00
tben e8b59997ac Keep ref pills their own colour in the user bubble
The bubble-wide link rule outranked a pill's text-ink, so chips with links
turned blue. Exclude links inside a ref chip's quote wrapper.
2026-11-25 09:39:38 +01:00
tben 7919bb39b8 Autofocus the all-bots search and restore the user bubble link colour 2026-11-25 09:35:06 +01:00
tben fcfc6874a8 Add session slash commands to the composer
/new starts a fresh session, /continue carries the conversation into a new one with a summary, and /clear deletes this session and starts a fresh one after a confirm. Up and Down walk the list, Enter runs the highlighted command, and a click fills it in first; a failed command comes back in the input with the server's reason.
2026-11-25 09:35:06 +01:00
tben e538ca029f Let members read the bot's instructions and memory in its panel
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
2026-11-25 08:24:16 +01:00
tben f66c97448f Let members open the bot panel and keep their own memory about them
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
Members read a bot's role and instructions, rewrite what it remembers about
them, and see its tools read-only; the stone and the name open the panel for
everyone. Also comments out the user bubble link colour.
2026-11-25 07:41:17 +01:00
tben 98948c559c Reload into the new build when a stale page sends a message
A page left open across a deploy kept sending from code the server no
longer serves. The root now puts the running build in a cobble-build meta
tag, the composer sends the build it was loaded from, and the send route
refuses an older one with stale_build before storing or queueing anything.
The composer keeps the typed text and uploaded attachments in the draft
and reloads, so the new build picks them up and the user sends again.
2026-11-25 07:30:35 +01:00
tben bab6683295 v0.28.6
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
2026-11-25 07:00:02 +01:00
tben 1757311262 Tell a bot who it's working for, and show user ids in the People list
A bot asked a member to confirm their identity because no run's prompt
ever carried the user's name; it had guessed one from the workspace name.
Every run now gets a who-you're-working-for section from grabUserName
(first and last, else username), and each row on Settings > Users ends
with the user's id.
2026-11-25 06:59:22 +01:00
tben d4469e6848 Give every provider its generation settings, not just OpenRouter
Only OpenRouter's /models says what each model takes, so every other provider's models carried no supported_parameters and the settings page hid temperature, effort and the rest. A provider now declares them (its saved pick, else its preset's list, else its host's: Alibaba's Token Plan hosts included) and the sync writes them into every model that reports none of its own. Reasoning effort goes flat as reasoning_effort outside OpenRouter, where the nested form was ignored, and thinking on/off goes as a boolean.
2026-11-25 06:55:07 +01:00
tben 15a74cacde v0.28.5
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
2026-11-25 04:52:19 +01:00
tben 67395500b5 Show a person's and a bot's picture at the size it is set up at
A picture preview was drawn whatever the size asked for, so setting up a
photo meant judging a thumbnail. BotAvatar passes its size through to the
image, UserAvatar gains xl and xxl, and the profile photo and the bot form's
preview use them.
2026-11-25 04:52:19 +01:00
tben 95c8ee7c39 v0.28.4
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
2026-11-25 04:37:37 +01:00
tben edd451342e Give the routine form's brief room to read 2026-11-25 04:37:37 +01:00
tben b635eeb543 Keep the hook form's buttons from being clipped away by the modal 2026-11-25 04:36:05 +01:00
tben 4cadde55e2 Size the bot form's preview picture from the form
The preview takes an avatar size, so the new-bot form shows it at 100px
rather than the 56px it uses in a list.
2026-11-25 04:32:23 +01:00
tben e000b09898 Let a user delete a chat session
The sessions modal now deletes a session and everything in it, refused
while a run is open in it. Deleting the active one gives the conversation
a fresh session instead of leaving it pointing at a removed one, and the
list rows truncate their summary to the row's width.
2026-11-25 04:32:19 +01:00
134 changed files with 3405 additions and 646 deletions
+12 -12
View File
File diff suppressed because one or more lines are too long
+9
View File
@@ -673,6 +673,10 @@ const schema: BUN_SQLITE_DatabaseSchemaType = {
indexName: "idx_bot_messages_session_id_created_at",
indexTableFields: ["session_id", "created_at"],
},
{
indexName: "idx_bot_messages_carried_from_session_id",
indexTableFields: ["carried_from_session_id"],
},
{
indexName: "idx_bot_messages_reply_to_message_id",
indexTableFields: ["reply_to_message_id"],
@@ -3237,6 +3241,11 @@ const schema: BUN_SQLITE_DatabaseSchemaType = {
fieldDescription: `Context window, in tokens, for the models this provider lists without one of their own (a custom provider lists ids only). The sync writes it into harness_models.context_length; null leaves them unknown`,
dataType: "INTEGER",
},
{
fieldName: "parameters",
fieldDescription: `JSON array of the generation settings this provider's models are offered, for the models whose own list carries none (a custom provider lists ids only). Null follows the preset's or host's own list; an empty array means it takes none`,
dataType: "TEXT",
},
{
fieldName: "last_synced_at",
fieldDescription: `Unix timestamp of the last model list sync`,
+4
View File
@@ -2009,6 +2009,10 @@ export type BUN_SQLITE_COBBLE_HARNESS_PROVIDERS = {
* Context window, in tokens, for the models this provider lists without one of their own (a custom provider lists ids only). The sync writes it into harness_models.context_length; null leaves them unknown
*/
context_length?: number | "";
/**
* JSON array of the generation settings this provider's models are offered, for the models whose own list carries none (a custom provider lists ids only). Null follows the preset's or host's own list; an empty array means it takes none
*/
parameters?: string;
/**
* Unix timestamp of the last model list sync
*/
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "cobble",
"version": "0.28.3",
"version": "0.28.11",
"module": "index.ts",
"type": "module",
"private": true,
+40 -7
View File
@@ -4,18 +4,36 @@
* is waiting on (a model that never answers, a tool that hangs) instead of
* leaving it to find out on its next heartbeat, which can take minutes.
*
* Only the process running a job can abort it, so this is a bonus: the job
* is already failed in `bots_queue`, and a handler in another process
* Only the process running a job can abort it, so this is a bonus: a job
* that stops has already been asked to, and a handler in another process
* learns that on its next `updateBotJob`. Kept free of imports so the API
* routes can use it without pulling the queue handler into a page bundle.
*/
const running = new Map<number, () => void>();
type Entry = {
abort: () => void;
/**
* Stops the run where it is and leaves it one turn to say what it did
* (`StoppedRunNote`), instead of dropping its work.
*/
stop_summary?: () => void;
};
const running = new Map<number, Entry>();
/**
* Called by a handler once it holds a job, with the way to abort it.
* Called by a handler once it holds a job, with the way to abort it and to
* let it summarize what it did first.
*/
export function registerJobAbort({ job_id, abort }: { job_id: number | string; abort: () => void }) {
running.set(Number(job_id), abort);
export function registerJobAbort({
job_id,
abort,
stop_summary,
}: {
job_id: number | string;
abort: () => void;
stop_summary?: () => void;
}) {
running.set(Number(job_id), { abort, stop_summary });
}
/**
@@ -30,7 +48,7 @@ export function unregisterJobAbort({ job_id }: { job_id: number | string }) {
* it, so the row's new status is how it finds out.
*/
export function abortRunningJob({ job_id }: { job_id: number | string }) {
const abort = running.get(Number(job_id));
const abort = running.get(Number(job_id))?.abort;
if (!abort) return false;
@@ -38,3 +56,18 @@ export function abortRunningJob({ job_id }: { job_id: number | string }) {
return true;
}
/**
* Asks a job running here to stop at its next step and write what it did so
* far. False means it runs in another process, or not at all: the plain
* stopped message is what the user gets then.
*/
export function requestJobStopSummary({ job_id }: { job_id: number | string }) {
const stop_summary = running.get(Number(job_id))?.stop_summary;
if (!stop_summary) return false;
stop_summary();
return true;
}
+25 -1
View File
@@ -86,12 +86,27 @@ export default async function processBotJob({
const hook_id = Number(params.hook_id) || null;
const controller = new AbortController();
/**
* The user's Stop, which is not a cancellation: the run stops at its
* step and writes what it did so far, and that message is posted instead
* of the app's plain stopped line (`stop-bot-jobs` waits
* `AppData.BotStopSummaryMs` for it).
*/
const stop_controller = new AbortController();
let stop_requested = false;
/**
* Registered before the first read below: those queries can wait on a
* busy database, and a Stop that arrived while they ran found nothing
* to abort, so a stopped job went on running until its own next write.
*/
registerJobAbort({ job_id, abort: () => controller.abort() });
registerJobAbort({
job_id,
abort: () => controller.abort(),
stop_summary: () => {
stop_requested = true;
stop_controller.abort();
},
});
/**
* Its face changes only for the user it works for.
@@ -280,6 +295,7 @@ export default async function processBotJob({
params,
checkpoint: parseJobJson({ text: job.checkpoint }),
signal: run_signal,
stop_signal: stop_controller.signal,
update,
report,
trace,
@@ -319,6 +335,7 @@ export default async function processBotJob({
task_ids: outcome.task_ids,
plan_id: outcome.plan_message_id,
exhausted: outcome.exhausted,
stopped: stop_requested,
});
await pushBotNotice({ bot_id, ...completion });
@@ -363,6 +380,13 @@ export default async function processBotJob({
} catch (error: unknown) {
if (controller.signal.aborted) return;
/**
* A stopped run that couldn't write its summary leaves the job open:
* `stop-bot-jobs` fails it and posts the plain stopped line when its
* wait runs out, so a stop is never turned into a retryable failure.
*/
if (stop_requested) return;
/**
* Every model is cooling down (rate limits): nothing was tried, so
* wait for the first to come back without using an attempt.
+2
View File
@@ -135,6 +135,7 @@ export default async function runBotReply({
user_id,
job,
signal,
stop_signal,
report,
trace,
}: Params): Promise<BotJobOutcome> {
@@ -731,6 +732,7 @@ export default async function runBotReply({
bot_id: bot.id,
workspace_id,
signal,
stop_signal,
onStep: report,
trace,
incoming,
+5 -20
View File
@@ -15,7 +15,6 @@ import {
ConnectorsNote,
ComputerFilesNote,
ScheduledRunNote,
ScheduledPlanNote,
HookRunNote,
InstallRequestNote,
TasksNote,
@@ -138,6 +137,7 @@ export default async function runBotTask({
job,
params,
signal,
stop_signal,
report,
trace,
}: Params): Promise<BotJobOutcome> {
@@ -489,22 +489,6 @@ export default async function runBotTask({
job_id: job.id || null,
onGraphic: ({ ref }) => shown.push(ref),
}),
/**
* A routine's plan is approved at once and worked through in
* the run, since nobody is there to approve it on a card
* (`ScheduledPlanNote`). A hook call gets none: its thread is a
* log of calls, not a conversation to read a plan in.
*/
...(scheduled && session_id
? grabBotPlanTools({
user_id,
bot_id: bot.id,
session_id,
workspace_id,
approve: true,
onPlan: ({ ref }) => shown.push(ref),
})
: []),
];
extensions = await openBotExtensions({
@@ -657,7 +641,6 @@ export default async function runBotTask({
TaskRunNote,
steps_note,
scheduled ? ScheduledRunNote : "",
scheduled ? ScheduledPlanNote : "",
hooked ? HookRunNote : "",
install_request_id ? InstallRequestNote : "",
Number(params.ask_id) ? AskTaskRunNote : "",
@@ -721,9 +704,10 @@ export default async function runBotTask({
* a step (`planBotTask`). It shares this run's prompt, so it costs
* little more than the plan, and it saves the steps a long run
* spends finding out what it is doing. A run whose plan can't be
* written starts the way it always did.
* written starts the way it always did. A routine or a hook call
* already has its plan (the brief, the runbook), so it works that.
*/
const planned = shouldPlanBotTask({ max_steps })
const planned = !scheduled && !hooked && shouldPlanBotTask({ max_steps })
? await planBotTask({ system, messages: opening, signal, bot_id: bot.id, workspace_id }).catch(
(error) => {
if (signal.aborted) throw error;
@@ -788,6 +772,7 @@ export default async function runBotTask({
bot_id: bot.id,
workspace_id,
signal,
stop_signal,
onStep: (step) =>
report({ ...step, text: step.text ? redact_text(step.text) : step.text }),
/**
+8
View File
@@ -17,6 +17,14 @@ export type BotJobContext = {
* work and return; the result is discarded.
*/
signal: AbortSignal;
/**
* Aborted when the user stops this run from the chat. Unlike `signal`
* the job is not cancelled: the run stops at the step it is on and
* writes what it did so far (`StoppedRunNote`), which is posted as the
* run's message. `stop-bot-jobs` gives it
* `AppData.BotStopSummaryMs` before the plain stopped line goes out.
*/
stop_signal: AbortSignal;
/**
* Save progress and a checkpoint. The lock is renewed on a timer
* already, so call this for meaningful steps. False once the job is
+7 -1
View File
@@ -1,5 +1,5 @@
import { describe, expect, test } from "bun:test";
import { closingNoTextNote, replyDraftNote, replyNoTextNote } from "@/src/data/harness-prompts";
import { closingNoTextNote, closingToolGoneNote, replyDraftNote, replyNoTextNote } from "@/src/data/harness-prompts";
import unsentAnswerMessage from "./unsent-answer-message";
/**
@@ -23,6 +23,12 @@ describe("unsentAnswerMessage", () => {
);
});
test("a last turn that called a tool it no longer had says so", () => {
expect(unsentAnswerMessage({ note: closingToolGoneNote })).toBe(
`The run's last turn called a tool it no longer had, so its message wasn't sent.`,
);
});
test("a check against the record keeps saying so", () => {
expect(unsentAnswerMessage({ note: "It names task #16, and no such task exists." })).toBe(
`The answer didn't hold up against the app's record, so it wasn't sent.`,
+5 -1
View File
@@ -1,4 +1,4 @@
import { closingNoTextNote, replyDraftNote, replyNoTextNote } from "@/src/data/harness-prompts";
import { closingNoTextNote, closingToolGoneNote, replyDraftNote, replyNoTextNote } from "@/src/data/harness-prompts";
type Params = {
/**
@@ -25,5 +25,9 @@ export default function unsentAnswerMessage({ note }: Params) {
return `The reply ended as a draft instead of a sent message, so it wasn't sent.`;
}
if (note === closingToolGoneNote) {
return `The run's last turn called a tool it no longer had, so its message wasn't sent.`;
}
return `The answer didn't hold up against the app's record, so it wasn't sent.`;
}
+6 -1
View File
@@ -31,7 +31,11 @@ type Props = ComponentProps<typeof BotStone> & {
* never a circle, so it isn't mistaken for a person), else its stone. Its
* colour still marks it everywhere else, e.g. the unread dot.
*/
export default function BotAvatar({ image_media_id, src: picked, ...stone }: Props) {
export default function BotAvatar({
image_media_id,
src: picked,
...stone
}: Props) {
const saved = profileImageUrls({ media_id: image_media_id });
const thumbnail_src = picked || saved.thumbnail_src;
const src = picked || saved.src;
@@ -49,6 +53,7 @@ export default function BotAvatar({ image_media_id, src: picked, ...stone }: Pro
BotAvatarSizeClasses[size] || BotAvatarSizeClasses[32],
stone.className,
)}
size={size}
/>
);
}
+65 -48
View File
@@ -2,16 +2,23 @@ import Button from "@moduletrace/twui/layout/Button";
import Row from "@moduletrace/twui/layout/Row";
import Span from "@moduletrace/twui/layout/Span";
import Stack from "@moduletrace/twui/layout/Stack";
import { Trash2 } from "lucide-react";
import { twMerge } from "tailwind-merge";
import type { BotSessionListItem } from "@/src/types";
import messagePreview from "@/src/utils/message-preview";
import relativeTime from "@/src/utils/relative-time";
import RowIconButton from "./row-icon-button";
type Props = {
session: BotSessionListItem;
loading?: boolean;
disabled?: boolean;
onOpen: () => void;
/**
* Deletes the session and its messages; left out where sessions can't be
* deleted (the rail).
*/
onDelete?: () => void;
/**
* The session the page shows (`?session_id=`, else the active one):
* marked Current and greyed out.
@@ -25,7 +32,7 @@ type Props = {
* recent. The one on screen is Current (greyed out); any other opens on
* click (reopening a closed one, going back to the active one).
*/
export default function BotSessionRow({ session, loading, disabled, onOpen, current }: Props) {
export default function BotSessionRow({ session, loading, disabled, onOpen, onDelete, current }: Props) {
const preview = session.summary || session.last_message_text || "";
const at = session.last_activity_at || session.created_at;
const tag = session.routine_title
@@ -35,56 +42,66 @@ export default function BotSessionRow({ session, loading, disabled, onOpen, curr
: null;
return (
<Button
title={
current
? "This is the session on screen"
: session.status == "active"
? "Go back to the active session"
: `Reopen "${session.title || "Untitled"}"`
}
type="button"
variant="ghost"
color="text"
loading={loading}
disabled={current || disabled}
onClick={onOpen}
buttonContentProps={{ className: "w-full min-w-0 flex-nowrap" }}
className={twMerge(
"w-full justify-start! items-start! gap-0! px-3! py-2.5! rounded-default text-left text-ink dark:text-ink hover:bg-ink/5 hover:dark:bg-ink/5 focus-visible:ring-2 focus-visible:ring-ink",
current && "bg-sunken hover:bg-sunken hover:dark:bg-sunken opacity-100!",
)}
>
<Stack className="w-full min-w-0 gap-0.5! items-stretch">
<Row className="w-full gap-2! flex-nowrap items-center">
<Span
className={twMerge(
"grow min-w-0 truncate text-sm font-bold leading-5",
current ? "text-ink-secondary" : "text-ink",
)}
>
{session.title || "Untitled session"}
</Span>
{tag ? (
<Row className="w-full flex-nowrap items-center gap-1">
<Button
title={
current
? "This is the session on screen"
: session.status == "active"
? "Go back to the active session"
: `Reopen "${session.title || "Untitled"}"`
}
type="button"
variant="ghost"
color="text"
loading={loading}
disabled={current || disabled}
onClick={onOpen}
buttonContentProps={{ className: "w-full min-w-0 flex-nowrap" }}
className={twMerge(
"grow min-w-0 justify-start! items-start! gap-0! px-3! py-2.5! rounded-default text-left text-ink dark:text-ink hover:bg-ink/5 hover:dark:bg-ink/5 focus-visible:ring-2 focus-visible:ring-ink",
current && "bg-sunken hover:bg-sunken hover:dark:bg-sunken opacity-100!",
)}
>
<Stack className="w-full min-w-0 gap-0.5! items-stretch">
<Row className="w-full gap-2! flex-nowrap items-center">
<Span
title={tag.title}
className="shrink-0 rounded-default bg-ink/5 px-1.5 text-[11px] leading-4 text-ink-secondary"
className={twMerge(
"grow min-w-0 truncate text-sm font-bold leading-5",
current ? "text-ink-secondary" : "text-ink",
)}
>
{tag.label}
{session.title || "Untitled session"}
</Span>
) : null}
{session.unread && !current ? (
<Span className="shrink-0 text-[11px] font-bold leading-4 text-ink">New</Span>
) : null}
<Span className="shrink-0 text-[11px] leading-4 text-ink-secondary">
{current ? "Current" : at ? relativeTime({ at: Number(at) }) : ""}
{tag ? (
<Span
title={tag.title}
className="shrink-0 rounded-default bg-ink/5 px-1.5 text-[11px] leading-4 text-ink-secondary"
>
{tag.label}
</Span>
) : null}
{session.unread && !current ? (
<Span className="shrink-0 text-[11px] font-bold leading-4 text-ink">New</Span>
) : null}
<Span className="shrink-0 text-[11px] leading-4 text-ink-secondary">
{current ? "Current" : at ? relativeTime({ at: Number(at) }) : ""}
</Span>
</Row>
<Span className="w-full truncate text-xs leading-4 text-ink-secondary">
{`${session.message_count} message${session.message_count == 1 ? "" : "s"}`}
{preview ? ` · ${messagePreview({ text: preview })}` : ""}
</Span>
</Row>
<Span className="w-full truncate text-xs leading-4 text-ink-secondary">
{`${session.message_count} message${session.message_count == 1 ? "" : "s"}`}
{preview ? ` · ${messagePreview({ text: preview })}` : ""}
</Span>
</Stack>
</Button>
</Stack>
</Button>
{onDelete ? (
<RowIconButton
icon={Trash2}
title={`Delete "${session.title || "Untitled"}"`}
disabled={Boolean(loading) || disabled}
onClick={onDelete}
/>
) : null}
</Row>
);
}
+37 -17
View File
@@ -43,7 +43,7 @@ type Props = {
* The sessions icon (or another target) that opens a conversation's
* sessions. A conversation is split into sessions so a bot's context never
* grows without bound; this lists them, searches them, starts a fresh one,
* or reopens an old one to carry on.
* reopens an old one to carry on, or deletes one.
*/
export default function BotSessionsModal({
bot,
@@ -139,22 +139,42 @@ export default function BotSessionsModal({
</Span>
) : null}
<Stack className="w-full mt-2 max-h-[60vh] overflow-y-auto gap-0! items-stretch">
{sessions.sessions.map((session) => (
<BotSessionRow
key={session.id}
session={session}
loading={sessions.busy_id == session.id}
disabled={Boolean(sessions.busy_id)}
current={on_screen?.id ? on_screen.id == session.id : session.status == "active"}
onOpen={() =>
session.status == "active"
? window.location.assign(conversationHref({ bot_id: Number(bot.id), workspace_id }))
: sessions.reopenSession({
session_id: Number(session.id),
})
}
/>
))}
{sessions.sessions.map((session) => {
const is_current = on_screen?.id
? on_screen.id == session.id
: session.status == "active";
return (
<BotSessionRow
key={session.id}
session={session}
loading={sessions.busy_id == session.id}
disabled={Boolean(sessions.busy_id)}
current={is_current}
onOpen={() =>
session.status == "active"
? window.location.assign(conversationHref({ bot_id: Number(bot.id), workspace_id }))
: sessions.reopenSession({
session_id: Number(session.id),
})
}
onDelete={() => {
if (
!window.confirm(
`Delete "${session.title || "this session"}"? Its messages go with it, and this can't be undone.`,
)
) {
return;
}
sessions.deleteSession({
session_id: Number(session.id),
current: is_current,
});
}}
/>
);
})}
{sessions.loading ? (
<LoadingBlock className="w-full h-[300px]" />
) : !sessions.sessions.length ? (
+2 -1
View File
@@ -193,8 +193,9 @@ export default function HookForm({
};
return (
// shrink-0: a capped flex column (the modal) would squash the form and clip the buttons away.
<Form
className="w-full gap-4! items-stretch pt-4 overflow-hidden px-1"
className="w-full shrink-0 gap-4! items-stretch pt-4 overflow-hidden px-1"
onSubmit={submit}
>
<Input
+8 -4
View File
@@ -34,7 +34,7 @@ export default function ImagePickField({
const input_ref = useRef<HTMLInputElement>(null);
return (
<Row className="w-full gap-4! flex-nowrap items-center">
<Row className="w-full gap-4! items-center">
{preview}
<Stack className="gap-2! min-w-0">
<Row className="gap-2!">
@@ -60,14 +60,17 @@ export default function ImagePickField({
disabled={disabled || loading}
onClick={() => {
onRemove();
if (input_ref.current) input_ref.current.value = "";
if (input_ref.current)
input_ref.current.value = "";
}}
>
Remove
</Button>
) : null}
</Row>
<Span className="text-[13px] leading-[18px] text-ink-secondary">{note}</Span>
<Span className="text-[13px] leading-[18px] text-ink-secondary">
{note}
</Span>
</Stack>
{/*
* Raw on purpose: twui `Input` writes `value` on change, which
@@ -85,7 +88,8 @@ export default function ImagePickField({
if (!e.target.files?.[0]) return;
imageInputToBase64({ imageInput: e.target }).then((res) => {
if (res?.imageBase64Full) onPick({ data_url: res.imageBase64Full });
if (res?.imageBase64Full)
onPick({ data_url: res.imageBase64Full });
});
}}
/>
+10 -3
View File
@@ -19,7 +19,9 @@ type Props = {
export default function RoutineForm({ cron_job, onCancel, onSaved }: Props) {
const [title, setTitle] = useState(cron_job.title || "");
const [schedule, setSchedule] = useState(cron_job.schedule || "");
const [instructions, setInstructions] = useState(cron_job.instructions || "");
const [instructions, setInstructions] = useState(
cron_job.instructions || "",
);
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string>();
@@ -69,13 +71,18 @@ export default function RoutineForm({ cron_job, onCancel, onSaved }: Props) {
/>
<CodeEditor
mode="markdown"
className="h-40"
className="h-[300px]"
title="Brief"
content={instructions}
info="What the bot does at every run, and how it knows it's done."
onChange={(value) => setInstructions(value)}
/>
<AddFormActions submit_label="Save" loading={loading} error={error} onCancel={onCancel} />
<AddFormActions
submit_label="Save"
loading={loading}
error={error}
onCancel={onCancel}
/>
</Form>
);
}
+5 -1
View File
@@ -12,6 +12,8 @@ const UserAvatarSizeClasses = {
sm: "size-6 text-[11px]",
md: "size-8 text-xs",
lg: "size-16 text-lg",
xl: "size-24 text-xl",
xxl: "size-32 text-2xl",
} as const;
type Props = {
@@ -47,7 +49,9 @@ export default function UserAvatar({
size = "md",
className,
}: Props) {
const photo = person?.profile_media_id ? grabMediaURL({ user: person }) : {};
const photo = person?.profile_media_id
? grabMediaURL({ user: person })
: {};
const src = passed_src || photo.media_thumbnail_url || photo.media_url;
const img_err_src = passed_src ? passed_err_src : photo.media_url;
const initials = passed_initials || userInitials(person || {});
+6
View File
@@ -1043,6 +1043,12 @@ export const AppData = {
* to have pushed the last ones (`LiveRelayPollMs`).
*/
BotJobStepsKeepMs: 60 * 1000,
/**
* How long a stop waits for the run to write what it did before it
* stopped (`StoppedRunNote`). Past it the plain stopped message goes out
* instead, so Stop never leaves the thread thinking.
*/
BotStopSummaryMs: 20 * 1000,
/**
* The debug view's detailed trace of a job (`bot_job_traces`, read and
* written only by `process-bot-job`): how many rows one job keeps, how
+1 -5
View File
@@ -23,7 +23,6 @@ import {
PlanWaitingNote,
PlanActiveNote,
PlanPausedNote,
ScheduledPlanNote,
RetryFailureNote,
} from "./harness-prompts";
import computerRunDirs from "@/src/utils/computer-work-dirs";
@@ -355,8 +354,5 @@ describe("plan notes", () => {
expect(PlanPausedNote({ plan: { ...plan, status: "paused" } })).toContain("paused by the user");
});
test("a routine's plan is approved at once and worked through in the run", () => {
expect(ScheduledPlanNote).toContain("approved at once");
expect(ScheduledPlanNote).toContain("work its steps in this run");
});
});
+21 -8
View File
@@ -129,6 +129,18 @@ The user asked for this reply again. Work from their latest messages and write i
- If the answer did go out, write it again for what they asked, as if it were the first time. The earlier one stays in the thread, so don't repeat it word for word if you have something better to say, and don't assume they missed it.
- Start the work now, in this reply or with send_reply status "working" and work: never answer that you'll look into it.`;
/**
* The turn a run gets when the user stops it from the chat: stop where it
* is, and say what happened so far, so the thread's last word comes from
* the run instead of the app's plain stopped line. `stop-bot-jobs` gives it
* `AppData.BotStopSummaryMs` before that line goes out anyway.
*/
export const StoppedRunNote = `# Stopped
The user stopped this run. Stop at the step you are on: don't call any tool that does work, and don't start, queue or promise anything new.
Write one short message for them that starts with "Stopped." and says what this run did so far and what is still undone, only from what it actually did (the tool calls it made and what came back). Then call send_reply with status "done".`;
/**
* Added beside `RerunReplyNote` when the attempt before this one failed:
* `reason` is the job's `last_error` (`grabRetryFailure`), so the run knows
@@ -561,6 +573,15 @@ export const closingFailedNote = `The card that call was meant to put up was not
*/
export const closingMixedNote = `The card you put up is there: that call worked. This turn also did other work, so it isn't the reply yet. Don't put another card up - a run asks once - and don't call ask_user or suggest_next_steps again. Write the message that goes with the card you already created, and stop there.`;
/**
* Told when the run's last turn called a tool it no longer has: only
* `send_reply` is offered by then, so the call and the message beside it are
* dropped and nothing was sent. A finished report is the whole point of a
* run that got this far, so it is written again once before the run gives up
* (job 687 lost one to a stray call).
*/
export const closingToolGoneNote = `This run's last turn offers send_reply alone, and the tool you called is not one it can run any more: that call and the message beside it were dropped, so nothing was sent. Write the whole message again in that turn as send_reply's text or its message argument, with status "done" when nothing is running after it, "working" when something is, or "blocked" when it can't go on. Finish every table, list and code fence in it.`;
/**
* Told once when a closing call worked but the turn said nothing beside it:
* a card alone leaves the user with buttons and no answer, and a run that
@@ -1134,11 +1155,3 @@ The user sent this message with Plan mode on. This reply plans, reads and asks;
- Every answer here carries a Turn Plan mode off button under it, so the way on is one click: say in one sentence what you will do once it is off, and stop there. Never hand the work back to them to paste or do by hand; turning the mode off (that button, or Tab) is the only thing in the way.
- End with send_reply: done sends the plan or the answer, blocked says what stopped you. Work can't be queued here.
- Say what you would do and what it depends on, not that you are doing it.`;
/**
* Added to a routine's run: nobody is there to approve a plan, so the bot
* writes one and works all of it in the run, reporting at the end.
*/
export const ScheduledPlanNote = `# A plan in a scheduled run
Nobody is watching this run, so a plan can't wait for approval. If this run's work is several pieces that build on each other, write it with create_plan anyway (it is approved at once here) and work its steps in this run: complete_plan_step after each one, with what it produced, so the conversation shows how far it got. Nothing interleaves with your run, so don't stop after one step. Your report at the end covers the whole plan: what each step produced and what is left.`;
+6
View File
@@ -25,6 +25,12 @@ export const PwaLoadingPath = "/loading.html";
export const PwaBuildInfoPath = "/build-info.json";
export const PwaPrecacheCachePrefix = "cobble-assets-";
export const PwaPrecacheMarkerPath = "/__cobble-precached";
/**
* The meta tag the root puts the running build in, so the page's own code
* knows which build it was loaded from (`loaded-build.ts`) and a send from
* an older one can be refused.
*/
export const PwaBuildMetaName = "cobble-build";
export type PwaIcon = {
src: string;
+11
View File
@@ -5,6 +5,7 @@ import {
harnessParametersFromOptions,
harnessParameterValue,
modelAdvertisesParameter,
providerSupportedParameters,
withHarnessParameters,
} from "./harness-parameter-dict";
@@ -68,4 +69,14 @@ describe("harness parameters", () => {
harnessParameterValue({ harness: "text", params: { temperature: 0 }, key: "temperature" }),
).toEqual({ value: 0, saved: true });
});
test("a provider's declared settings go under the names its models advertise", () => {
expect(
providerSupportedParameters({
keys: ["temperature", "reasoning_effort"],
}),
).toEqual(["temperature", "reasoning"]);
expect(providerSupportedParameters({})).toBeUndefined();
expect(providerSupportedParameters({ keys: [] })).toEqual([]);
});
});
+55
View File
@@ -8,6 +8,7 @@
* - `advertised`: the name a provider's model list uses for it, when it
* differs (OpenRouter's `supported_parameters`)
* - `wire`: how the field is written, for providers that nest it
* - `wire_boolean`: saved as "true"/"false", sent as a JSON boolean
*/
export const HarnessParameters = [
{
@@ -104,12 +105,42 @@ export const HarnessParameters = [
{ value: "high", title: "High" },
],
},
{
key: "enable_thinking",
title: "Thinking",
description: `Whether it thinks before it answers, which is slower and costs more. "Default" leaves each model's own setting alone. Providers that turn thinking on by another field ignore it.`,
value_type: "select",
wire_boolean: true,
options: [
{ value: "true", title: "On" },
{ value: "false", title: "Off" },
],
},
{
key: "thinking_budget",
title: "Thinking budget",
description: `How many tokens it may think with, up to 32768. Only some models take it, and usually only while thinking is on.`,
value_type: "number",
min: 0,
max: 32768,
step: 1,
},
] as const;
export type HarnessParameter = (typeof HarnessParameters)[number];
export type HarnessParameterKey = HarnessParameter["key"];
export type HarnessParameterValue = number | string;
/**
* The generation settings as they go on the wire: OpenRouter's reasoning
* effort nests as `reasoning: { effort }`, a boolean setting as a JSON
* boolean, the rest as they are.
*/
export type HarnessWireParams = Record<
string,
number | string | boolean | { effort: string }
>;
/**
* The harnesses whose models are chat models, so the only ones the
* generation settings apply to.
@@ -189,6 +220,30 @@ export function modelAdvertisesParameter({
);
}
/**
* The names a provider's declared settings go under: what its models'
* `supported_parameters` should carry, so the same advertised names
* OpenRouter's catalog uses. Undefined when the provider declares nothing,
* which leaves its models with none.
*/
export function providerSupportedParameters({
keys,
}: {
keys?: readonly HarnessParameterKey[] | null;
}) {
if (!keys) return undefined;
return keys.flatMap((key) => {
const parameter = HarnessParameters.find((p) => p.key == key);
if (!parameter) return [];
return [
"advertised" in parameter ? parameter.advertised : parameter.key,
];
});
}
/**
* The generation settings a saved `options` object holds.
*/
+13
View File
@@ -8,6 +8,9 @@
* tools support and prices; `openai-compatible` gives only ids, so
* capabilities are guessed from the names
* - `local`: runs on the user's own hardware, so its models count as free
* - `parameters`: the generation settings its models get when its own model
* list carries none (`HarnessParameters` keys). Empty for a provider whose
* catalog decides (OpenRouter) or whose host is checked instead (custom)
* - `image_path`: image generation endpoint
* - `image_edit_path`: where images made from reference images go. OpenRouter
* takes them on `image_path` (`input_references`); the others take a
@@ -22,6 +25,7 @@ export const HarnessProviderKinds = [
{
title: "OpenRouter",
value: "openrouter",
parameters: [],
base_url: "https://openrouter.ai/api/v1",
needs_key: true,
key_env: "OPENROUTER_API_KEY",
@@ -34,6 +38,7 @@ export const HarnessProviderKinds = [
{
title: "OpenAI",
value: "openai",
parameters: ["temperature", "top_p", "frequency_penalty", "presence_penalty", "seed", "reasoning_effort"],
base_url: "https://api.openai.com/v1",
needs_key: true,
key_env: "OPENAI_API_KEY",
@@ -46,6 +51,7 @@ export const HarnessProviderKinds = [
{
title: "Anthropic",
value: "anthropic",
parameters: ["temperature", "top_p", "top_k"],
base_url: "https://api.anthropic.com/v1",
needs_key: true,
key_env: "ANTHROPIC_API_KEY",
@@ -58,6 +64,7 @@ export const HarnessProviderKinds = [
{
title: "Google Gemini",
value: "google",
parameters: ["temperature", "top_p", "top_k", "seed", "frequency_penalty", "presence_penalty"],
base_url: "https://generativelanguage.googleapis.com/v1beta/openai",
needs_key: true,
key_env: "GEMINI_API_KEY",
@@ -70,6 +77,7 @@ export const HarnessProviderKinds = [
{
title: "DeepSeek",
value: "deepseek",
parameters: ["temperature", "top_p", "frequency_penalty", "presence_penalty"],
base_url: "https://api.deepseek.com",
needs_key: true,
key_env: "DEEPSEEK_API_KEY",
@@ -82,6 +90,7 @@ export const HarnessProviderKinds = [
{
title: "Groq",
value: "groq",
parameters: ["temperature", "top_p", "top_k", "seed", "frequency_penalty", "presence_penalty", "reasoning_effort"],
base_url: "https://api.groq.com/openai/v1",
needs_key: true,
key_env: "GROQ_API_KEY",
@@ -94,6 +103,7 @@ export const HarnessProviderKinds = [
{
title: "Mistral",
value: "mistral",
parameters: ["temperature", "top_p", "top_k", "seed", "frequency_penalty", "presence_penalty"],
base_url: "https://api.mistral.ai/v1",
needs_key: true,
key_env: "MISTRAL_API_KEY",
@@ -106,6 +116,7 @@ export const HarnessProviderKinds = [
{
title: "xAI",
value: "xai",
parameters: ["temperature", "top_p", "presence_penalty", "frequency_penalty", "seed", "reasoning_effort"],
base_url: "https://api.x.ai/v1",
needs_key: true,
key_env: "XAI_API_KEY",
@@ -118,6 +129,7 @@ export const HarnessProviderKinds = [
{
title: "Ollama",
value: "ollama",
parameters: ["temperature", "top_p", "top_k", "min_p", "repetition_penalty", "seed"],
base_url: "http://localhost:11434/v1",
needs_key: false,
key_env: "",
@@ -130,6 +142,7 @@ export const HarnessProviderKinds = [
{
title: "Other (OpenAI-compatible)",
value: "custom",
parameters: [],
base_url: "",
needs_key: false,
key_env: "",
@@ -6,7 +6,7 @@ import wakeBotsQueue from "@/src/bots-queue/wake-bots-queue";
import type { BotQuestionView } from "@/src/types";
import botQuestionAnswersText from "@/src/utils/bot-question-answers-text";
import planContinueAnswer from "@/src/utils/plan-continue-answer";
import conversationLock from "../bot-sessions/conversation-lock";
import conversationLock, { conversationLockKey } from "../bot-sessions/conversation-lock";
import ensureBotSession from "../bot-sessions/ensure-bot-session";
import grabUserBotSession from "../bot-sessions/grab-user-bot-session";
import insertUserMessage from "../bots/insert-user-message";
@@ -43,7 +43,7 @@ export default async function postBotQuestionAnswers({ view, user_id }: Params)
const bot_id = Number(row.bot_id);
await conversationLock.run({
key: `${user_id}:${bot_id}:${workspace_id || 0}`,
key: conversationLockKey({ user_id, bot_id, workspace_id }),
task: async () => {
const session = await pickSession({ row, user_id });
@@ -3,9 +3,11 @@ import BunSQLite from "@moduletrace/bun-sqlite";
import { AppData } from "@/src/data/app-data";
import AppError from "@/src/utils/app-error";
import insertBotMessage from "../bots/insert-bot-message";
import conversationLock, { conversationLockKey } from "./conversation-lock";
import createBotSession from "./create-bot-session";
import grabActiveBotSession from "./grab-active-bot-session";
import grabUserBotSession from "./grab-user-bot-session";
import unansweredMessageSql from "./unanswered-message-sql";
type Params = {
/**
@@ -57,8 +59,27 @@ type Params = {
* session (`allow_inactive`, `next_status` closed), keeping the link to
* the routine or hook and the conversation's active session untouched.
* Returns that first message, for the caller to push.
*
* A reply's carry is refused while the user has written something that
* reply hasn't answered: closing the session now leaves their message
* behind in it while the answer goes to the new one.
*/
export default async function carryOverBotSession({
export default async function carryOverBotSession(params: Params): Promise<BUN_SQLITE_COBBLE_BOT_MESSAGES> {
/**
* The reply writes to the conversation like a send does, so it waits
* its turn: a message the user writes while it works lands in one
* session or the other, never in one closed under it. A routine's or a
* silent hook's own thread (`allow_inactive`, no job) moves on its own.
*/
if (!params.job_id) return await carryOverSession(params);
return await conversationLock.run({
key: conversationLockKey(params),
task: () => carryOverSession(params),
});
}
async function carryOverSession({
session_id,
user_id,
bot_id,
@@ -104,6 +125,23 @@ export default async function carryOverBotSession({
throw new AppError(`This session has no messages yet: it's already fresh.`);
}
if (job_id) {
const unanswered = unansweredMessageSql({ session_id: active.id, job_id });
const waiting = (
await BunSQLite.sql<{ unanswered: number }>({
sql: `SELECT ${unanswered.sql} AS unanswered`,
values: unanswered.values,
})
).payload?.[0]?.unanswered;
if (waiting) {
throw new AppError(
`The user wrote something this reply hasn't answered yet. Answer it in this session first, and carry the conversation over in a later reply.`,
);
}
}
const now = Date.now();
await BunSQLite.sql({
@@ -6,8 +6,18 @@ import createKeyLock from "@/src/utils/create-key-lock";
* flight together (a double submit, a retry firing beside the first) both
* read the same full session, one rolls the conversation over, and the
* other writes into the session that was just closed, where the user never
* sees it.
* sees it. A reply carrying the conversation on is one of those writes.
*/
const conversationLock = createKeyLock();
type KeyParams = {
user_id: number | string;
bot_id: number;
workspace_id?: number | null;
};
export function conversationLockKey({ user_id, bot_id, workspace_id }: KeyParams) {
return `${user_id}:${bot_id}:${workspace_id || 0}`;
}
export default conversationLock;
@@ -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,
@@ -0,0 +1,80 @@
import { Database } from "bun:sqlite";
import { describe, expect, test } from "bun:test";
import unansweredMessageSql from "./unanswered-message-sql";
/**
* A carry must notice the user's words it would leave behind: a message
* written after the one the reply answers (or after a plan's step was
* queued) is unanswered, and the session it is in is not safe to close.
* Crew messages and the message the job answers are not the user's new
* words.
*/
const db = new Database(":memory:");
db.run(
`CREATE TABLE bot_messages (id INTEGER PRIMARY KEY, session_id INTEGER, author TEXT,
from_ask_id INTEGER, from_install_request_id INTEGER, created_at INTEGER)`,
);
db.run(`CREATE TABLE bots_queue (id INTEGER PRIMARY KEY, message_id INTEGER, created_at INTEGER)`);
db.run(`INSERT INTO bots_queue VALUES (10, 100, 1000), (11, NULL, 2000)`);
db.run(`INSERT INTO bot_messages VALUES
(100, 5, 'user', NULL, NULL, 900),
(101, 5, 'user', NULL, NULL, 1100),
(102, 5, 'user', 3, NULL, 1200),
(103, 5, 'user', NULL, 4, 1300),
(104, 5, 'bot', NULL, NULL, 1400),
(200, 6, 'user', NULL, NULL, 2100),
(201, 6, 'bot', NULL, NULL, 2200)`);
function unanswered({ session_id, job_id }: { session_id: number; job_id: number }) {
const condition = unansweredMessageSql({ session_id, job_id });
return Boolean(
(
db.query(`SELECT ${condition.sql} AS unanswered`).get(...condition.values) as
| { unanswered: number }
| null
)?.unanswered,
);
}
describe("unansweredMessageSql", () => {
test("a message written after the one the job answers is unanswered", () => {
expect(unanswered({ session_id: 5, job_id: 10 })).toBe(true);
});
test("the message the job answers is not", () => {
db.run(`DELETE FROM bot_messages WHERE id IN (101, 102, 103)`);
expect(unanswered({ session_id: 5, job_id: 10 })).toBe(false);
db.run(`INSERT INTO bot_messages VALUES
(101, 5, 'user', NULL, NULL, 1100),
(102, 5, 'user', 3, NULL, 1200),
(103, 5, 'user', NULL, 4, 1300)`);
});
test("a crew message is never the user's words", () => {
db.run(`DELETE FROM bot_messages WHERE id = 101`);
expect(unanswered({ session_id: 5, job_id: 10 })).toBe(false);
db.run(`INSERT INTO bot_messages VALUES (101, 5, 'user', NULL, NULL, 1100)`);
});
test("a step queued with no message counts what the user wrote after it", () => {
expect(unanswered({ session_id: 6, job_id: 11 })).toBe(true);
db.run(`DELETE FROM bot_messages WHERE id = 200`);
expect(unanswered({ session_id: 6, job_id: 11 })).toBe(false);
db.run(`INSERT INTO bot_messages VALUES (200, 6, 'user', NULL, NULL, 2100)`);
});
test("a job queued after the session's messages counts none of them", () => {
expect(unanswered({ session_id: 5, job_id: 11 })).toBe(false);
});
});
@@ -0,0 +1,30 @@
import type { SqlCondition } from "@/src/utils/crew-access/types";
type Params = {
/**
* The session the reply is answering in.
*/
session_id: number | string;
/**
* The reply's own job: the message it answers is `bots_queue.message_id`.
*/
job_id: number | string;
};
/**
* The SQL for a user message the reply's job hasn't answered: one written
* after the message the job answers, or, for a job queued with no message
* (a plan's step), after the job was queued. Crew messages are left out:
* they wake a bot, they aren't the user's own words. A run carrying the
* conversation on while its answer is one of these leaves it behind in the
* session it closes, unanswered.
*/
export default function unansweredMessageSql({ session_id, job_id }: Params): SqlCondition {
return {
sql: `EXISTS (SELECT 1 FROM bot_messages m JOIN bots_queue q ON q.id = ?
WHERE m.session_id = ? AND m.author = 'user'
AND m.from_ask_id IS NULL AND m.from_install_request_id IS NULL
AND (m.id > q.message_id OR (q.message_id IS NULL AND m.created_at > q.created_at)))`,
values: [Number(job_id), Number(session_id)],
};
}
@@ -1,6 +1,6 @@
import BunSQLite from "@moduletrace/bun-sqlite";
import AppError from "@/src/utils/app-error";
import { BotNeedsYouStatusLine } from "@/src/dict/bot-queue-dict";
import { BotNeedsYouStatusLine, BotJobStoppedError } from "@/src/dict/bot-queue-dict";
import insertBotMessage from "../bots/insert-bot-message";
import deleteBotMessage from "../bots/delete-bot-message";
import setBotFace from "../bots/set-bot-face";
@@ -63,6 +63,14 @@ type Params = {
* a run that spent its whole budget and did no work says so itself.
*/
exhausted?: boolean;
/**
* The user stopped this run, and its message says what it did so far
* (`StoppedRunNote`). Nothing is answered by it: no crew request is
* finished, no hand-over is relayed, no handed-over task is touched
* (`stop-bot-jobs` ends the rest), and the bot goes idle rather than
* done.
*/
stopped?: boolean;
};
/**
@@ -75,7 +83,9 @@ type Params = {
* it over (`relay`), and a handed-over task left open says so, or is blocked when the run used
* its whole step budget without finishing (`noteTrackerTask`). A hook
* run's result is kept on the calls it answered (`recordHookCallResponse`). A job working a crew
* request ends it (`onAskJobEnded`) and leaves the bot's face alone. Throws if this handler no longer holds the job.
* request ends it (`onAskJobEnded`) and leaves the bot's face alone. A run the
* user stopped (`stopped`) only says what it did so far and goes idle: it
* answers nothing. Throws if this handler no longer holds the job.
*/
export default async function completeBotJob({
job_id,
@@ -88,6 +98,7 @@ export default async function completeBotJob({
task_ids = [],
plan_id,
exhausted,
stopped,
}: Params) {
const job = await grabLockedBotJob({ job_id, worker });
@@ -198,31 +209,49 @@ export default async function completeBotJob({
bot =
!user_id || unattended
? null
: needs_you
? await setBotFace({
bot_id: job.bot_id,
user_id,
face: "needs-you",
status_line: BotNeedsYouStatusLine,
})
: await botFaceAfterJob({ bot_id: job.bot_id, user_id, kind: job.kind });
: stopped
? await setBotFace({ bot_id: job.bot_id, user_id, face: "idle" })
: needs_you
? await setBotFace({
bot_id: job.bot_id,
user_id,
face: "needs-you",
status_line: BotNeedsYouStatusLine,
})
: await botFaceAfterJob({ bot_id: job.bot_id, user_id, kind: job.kind });
await noteTrackerTask({ job, exhausted });
if (stopped) {
/**
* A stopped run answers nothing: the hook call it was in and an
* install request it was settling end as stopped, and the crew
* request it was answering is ended by `stop-bot-jobs`.
*/
await recordHookCallResponse({
job,
status: "failed",
response: BotJobStoppedError,
message_id: inserted?.id,
});
await recordHookCallResponse({
job,
status: "done",
response: result,
message_id: inserted?.id,
});
await settleInstallRequest({ job, text: BotJobStoppedError, failed: true });
} else {
await noteTrackerTask({ job, exhausted });
relay = silent
? null
: await relayJobToRequester({ job, text: result, task_ids: message_task_ids });
await recordHookCallResponse({
job,
status: "done",
response: result,
message_id: inserted?.id,
});
await onAskJobEnded({ job, text: silent ? "" : result, tool_uses: tool_log });
relay = silent
? null
: await relayJobToRequester({ job, text: result, task_ids: message_task_ids });
await settleInstallRequest({ job, text: result });
await onAskJobEnded({ job, text: silent ? "" : result, tool_uses: tool_log });
await settleInstallRequest({ job, text: result });
}
} catch (error) {
await logError({
title: `Bot job #${job.id} completed, its clearing up didn't`,
@@ -1,9 +1,10 @@
import BunSQLite from "@moduletrace/bun-sqlite";
import type { BUN_SQLITE_COBBLE_BOT_MESSAGES, BUN_SQLITE_COBBLE_BOTS_QUEUE } from "@/db/types/db";
import { AppData } from "@/src/data/app-data";
import { BotJobStoppedError, BotJobStoppedStep } from "@/src/dict/bot-queue-dict";
import insertBotMessage from "../bots/insert-bot-message";
import setBotFace, { type BotFaceChange } from "../bots/set-bot-face";
import { abortRunningJob } from "@/src/bots-queue/job-abort-registry";
import { abortRunningJob, requestJobStopSummary } from "@/src/bots-queue/job-abort-registry";
import insertBotJobUpdate from "./insert-bot-job-update";
import recordHookCallResponse from "../bot-hooks/record-hook-call-response";
import openBotJobsSql from "./open-bot-jobs-sql";
@@ -16,6 +17,8 @@ import grabOpenAskBySession from "../asks/grab-open-ask-by-session";
import isUnattendedHookSession from "../bot-hooks/is-unattended-hook-session";
import settleInstallRequest from "../install-requests/settle-install-request";
import attachJobTracesToMessage from "./attach-job-traces-to-message";
import attachJobCallsToMessage from "../usage/attach-job-calls-to-message";
import withMessageUsage from "../usage/with-message-usage";
type Params = {
bot_id: number | string;
@@ -27,7 +30,7 @@ type Params = {
export type StoppedBotJobs = {
/**
* The jobs that were open and are now failed as stopped.
* The jobs that were open when the stop came.
*/
jobs: BUN_SQLITE_COBBLE_BOTS_QUEUE[];
/**
@@ -45,13 +48,16 @@ export type StoppedBotJobs = {
/**
* Pulls the plug on a bot for one user: every job of it that could still
* run or is running in their conversations (replies it still owes, tasks
* it's on, across all of them) is failed as stopped, its task closed. A
* running handler finds out on its next `updateBotJob` (which returns
* false) and drops whatever it was producing. Each job gets a closing
* step, so a thread's working row says why it went quiet even after a
* reload, one message per session ends it out loud, and the bot goes
* idle. It's not a bus: nothing restarts by itself, so a stopped bot
* works again only when the user asks. A schedule the user set up still
* it's on, across all of them) is failed as stopped, its task closed.
*
* A run this process is running is asked to stop where it is and write what
* it did so far (`StoppedRunNote`), and that message is the session's last
* word. `AppData.BotStopSummaryMs` is all it gets: past that the job is
* failed and the plain stopped line goes out instead, so a stop never
* leaves the thread thinking. Each job gets a closing step too, so a
* thread's working row says why it went quiet even after a reload, and the
* bot goes idle. It's not a bus: nothing restarts by itself, so a stopped
* bot works again only when the user asks. A schedule the user set up still
* comes round, since that is work they asked for.
*/
export default async function stopBotJobs({ bot_id, user_id }: Params): Promise<StoppedBotJobs | null> {
@@ -66,6 +72,24 @@ export default async function stopBotJobs({ bot_id, user_id }: Params): Promise<
if (!open.length) return null;
/**
* The runs this process can still write for are asked to stop and say
* what they did, one per session (`pickReportedJobs`): that is what the
* session reads, so a second summary there would stutter.
*/
const picked = pickReportedJobs({ jobs: open });
const summarizing: { job_id: number; session_id: number }[] = [];
const stop_started_at = Date.now();
for (const [session_id, job] of picked) {
if (job.status != "processing") continue;
if (!requestJobStopSummary({ job_id: Number(job.id) })) continue;
summarizing.push({ job_id: Number(job.id), session_id });
}
await waitForStopSummaries({ job_ids: summarizing.map((entry) => entry.job_id) });
const now = Date.now();
const jobs: BUN_SQLITE_COBBLE_BOTS_QUEUE[] = [];
@@ -128,11 +152,13 @@ export default async function stopBotJobs({ bot_id, user_id }: Params): Promise<
/**
* A job it was doing for a crew request stops the request: the bot that
* asked is told, and the other side's run is cancelled.
* asked is told, and the other side's run is cancelled. Read from every
* job that was open, since a run that wrote its own summary is still a
* stop for the request it was answering.
*/
const ask_ids = new Set<number>();
for (const job of jobs) {
for (const job of open) {
const from_session = await grabSessionAskId({ session_id: Number(job.session_id) }).catch(
() => null,
);
@@ -152,11 +178,11 @@ export default async function stopBotJobs({ bot_id, user_id }: Params): Promise<
* own: the open request is found by the session it answers in.
*/
if (!asked && !from_session && job.session_id) {
const open = await grabOpenAskBySession({ session_id: Number(job.session_id) }).catch(
const open_ask = await grabOpenAskBySession({ session_id: Number(job.session_id) }).catch(
() => null,
);
if (open?.id) ask_ids.add(Number(open.id));
if (open_ask?.id) ask_ids.add(Number(open_ask.id));
}
}
@@ -174,18 +200,42 @@ export default async function stopBotJobs({ bot_id, user_id }: Params): Promise<
await stopAsks({
user_id,
requester_bot_id: bot_id,
session_ids: jobs.map((job) => Number(job.session_id)),
session_ids: open.map((job) => Number(job.session_id)),
}).catch(() => []);
/**
* A session whose run wrote its own summary already has its last word.
*/
const stopped_ids = new Set(jobs.map((job) => Number(job.id)));
const summarized_sessions = new Set(
summarizing.filter((entry) => !stopped_ids.has(entry.job_id)).map((entry) => entry.session_id),
);
const messages: BUN_SQLITE_COBBLE_BOT_MESSAGES[] = [];
for (const [session_id, job] of pickReportedJobs({ jobs })) {
if (summarized_sessions.has(session_id)) continue;
/**
* A silent hook's call says it was stopped in its thread
* (`recordHookCallResponse`), nowhere the user reads.
*/
if (await isUnattendedHookSession({ session_id })) continue;
/**
* A run that wrote its summary just as the wait ran out has its row
* failed under it: its message is still there, so the plain line
* would only repeat it.
*/
const answered = (
await BunSQLite.sql<{ id: number }>({
sql: `SELECT id FROM bot_messages WHERE session_id = ? AND author = 'bot' AND created_at >= ? LIMIT 1`,
values: [session_id, stop_started_at],
}).catch(() => null)
)?.payload?.length;
if (answered) continue;
const message = await insertBotMessage({
bot_id: Number(bot_id),
session_id,
@@ -194,19 +244,47 @@ export default async function stopBotJobs({ bot_id, user_id }: Params): Promise<
}).catch(() => null);
if (message?.id) {
messages.push(message);
/**
* The run's debug logs go with the answer that took its place,
* the way a finished run's go with its own.
* The run's info goes with the message that took its place: its
* own calls and failures behind the usage chip, and its debug
* logs, the way a finished run's go with its own.
*/
await attachJobCallsToMessage({ job_id: Number(job.id), message_id: Number(message.id) });
await attachJobTracesToMessage({ job_id: Number(job.id), message_id: Number(message.id) });
messages.push((await withMessageUsage({ messages: [message] }).catch(() => [message]))[0] ?? message);
}
}
return {
jobs,
jobs: open,
messages,
bot: await setBotFace({ bot_id, user_id, face: "idle" }),
};
}
/**
* Waits for the runs asked to summarize to close their rows, never past
* `AppData.BotStopSummaryMs`: past it the plain stopped line goes out
* instead. Polled rather than awaited: another process's handler can only
* be read through the queue.
*/
async function waitForStopSummaries({ job_ids }: { job_ids: number[] }) {
if (!job_ids.length) return;
const deadline = Date.now() + AppData.BotStopSummaryMs;
const placeholders = job_ids.map(() => "?").join(", ");
while (Date.now() < deadline) {
const still_open = (
await BunSQLite.sql<{ id: number }>({
sql: `SELECT id FROM bots_queue WHERE id IN (${placeholders}) AND status IN ('pending', 'processing')`,
values: job_ids,
}).catch(() => null)
)?.payload;
if (!still_open?.length) return;
await Bun.sleep(250);
}
}
@@ -3,13 +3,15 @@ import AppError from "@/src/utils/app-error";
import grabSystemPromptAppend from "../app-settings/grab-system-prompt-append";
import grabWorkspaceBot from "../workspaces/grab-workspace-bot";
import grabWorkspaceUserRole from "../workspaces/grab-workspace-user-role";
import grabUserName from "../users/grab-user-name";
import grabBotUserMemory from "./grab-bot-user-memory";
import grabUserBot from "./grab-user-bot";
type Params = {
bot_id: number | string;
/**
* The user the bot works with: only their memory joins the prompt.
* The user the bot works with: their name and their memory join the
* prompt.
*/
user_id: number | string;
/**
@@ -23,8 +25,9 @@ type Params = {
/**
* The full prompt for one of the user's bots (`composeBotPrompt`): who it
* is (its name and id), its core instructions, the install-wide appendix,
* its memory, what it remembers about this user, and in a workspace that
* workspace's context, what the bot has for it and who this user is there.
* who the user it's working for is, its memory, what it remembers about this
* user, and in a workspace that workspace's context, what the bot has for it
* and who this user is there.
*/
export default async function grabBotPrompt({ bot_id, user_id, workspace_id }: Params) {
const bot = await grabUserBot({ bot_id, user_id });
@@ -45,6 +48,7 @@ export default async function grabBotPrompt({ bot_id, user_id, workspace_id }: P
bot: { id: bot.id, name: bot.name, kind: bot.kind, role: bot.role },
system_prompt: bot.system_prompt,
appendix: await grabSystemPromptAppend(),
user_name: await grabUserName({ user_id }),
memory: bot.memory,
user_memory: await grabBotUserMemory({ bot_id: bot.id, user_id }),
workspace: found?.workspace,
@@ -0,0 +1,26 @@
import { describe, expect, test } from "bun:test";
import modelSupportedParameters from "./model-supported-parameters";
describe("model supported parameters", () => {
test("the provider's own list wins", () => {
expect(
modelSupportedParameters({
model: { supported_parameters: ["temperature"] },
provider_parameters: ["temperature", "seed"],
}),
).toEqual(["temperature"]);
});
test("a model that lists none gets the provider's", () => {
expect(
modelSupportedParameters({
model: {},
provider_parameters: ["temperature", "seed"],
}),
).toEqual(["temperature", "seed"]);
});
test("nothing declared stays nothing", () => {
expect(modelSupportedParameters({ model: {} })).toBeNull();
});
});
@@ -0,0 +1,23 @@
import type { HarnessCatalogModel } from "@/src/harness/types";
type Params = {
model: Pick<HarnessCatalogModel, "supported_parameters">;
/**
* The names the provider's own row declares, for the models it lists
* without any (a custom provider lists ids only).
*/
provider_parameters?: string[] | null;
};
/**
* The parameters a `harness_models` row keeps: what the provider's own list
* said, else the settings the provider declares (its preset, its host or a
* super admin's pick). A model's own list wins, so OpenRouter's catalog is
* never overridden.
*/
export default function modelSupportedParameters({
model,
provider_parameters,
}: Params) {
return model.supported_parameters ?? provider_parameters ?? null;
}
@@ -0,0 +1,32 @@
import {
HarnessParameterKeys,
type HarnessParameterKey,
} from "@/src/dict/harness-parameter-dict";
type Params = {
text?: string | null;
};
/**
* The generation settings a provider row saved, or undefined when it saved
* none (which follows its preset or host instead). Unknown keys are dropped,
* so an older release's name can't reach a model's `supported_parameters`
* and be offered as a field that never gets sent.
*/
export default function parseProviderParameters({
text,
}: Params): HarnessParameterKey[] | undefined {
if (!text) return undefined;
try {
const value = JSON.parse(text);
if (!Array.isArray(value)) return undefined;
return value.filter((key): key is HarnessParameterKey =>
HarnessParameterKeys.includes(key as HarnessParameterKey),
);
} catch {
return undefined;
}
}
@@ -4,6 +4,7 @@ import type {
BunSQLiteTables,
} from "@/db/types/db";
import type { HarnessProviderKind } from "@/src/dict/harness-provider-dict";
import type { HarnessParameterKey } from "@/src/dict/harness-parameter-dict";
import grabProviderPreset from "@/src/harness/providers/grab-provider-preset";
import AppError from "@/src/utils/app-error";
import { encrypt } from "@/src/utils/crypt";
@@ -27,6 +28,11 @@ type Params = {
* leaves them unknown.
*/
context_length?: number;
/**
* The generation settings its models are offered. Left out follows its
* preset or host; an empty array means it takes none.
*/
parameters?: HarnessParameterKey[];
enabled: boolean;
};
@@ -42,6 +48,7 @@ export default async function saveHarnessProvider({
api_key,
clear_key,
context_length,
parameters,
enabled,
}: Params) {
const preset = grabProviderPreset({ kind });
@@ -75,6 +82,7 @@ export default async function saveHarnessProvider({
* cleared with null (the plugin binds it as NULL).
*/
context_length: (context_length && context_length > 0 ? context_length : null) as number,
parameters: (parameters ? JSON.stringify(parameters) : null) as string,
...key_update,
};
@@ -1,6 +1,9 @@
import BunSQLite from "@moduletrace/bun-sqlite";
import type { BUN_SQLITE_COBBLE_HARNESS_PROVIDERS } from "@/db/types/db";
import grabHarnessAdapter from "@/src/harness/providers/grab-harness-adapter";
import providerParameterKeys from "@/src/harness/providers/provider-parameter-keys";
import { providerSupportedParameters } from "@/src/dict/harness-parameter-dict";
import parseProviderParameters from "./parse-provider-parameters";
import resolveProviderConfig from "./resolve-provider-config";
import upsertHarnessModels from "./upsert-harness-models";
@@ -29,6 +32,15 @@ export default async function syncHarnessProviderModels({ provider }: Params) {
provider_id: provider.id,
models,
provider_context_length: provider.context_length || null,
provider_parameters: providerSupportedParameters({
keys: providerParameterKeys({
kind: config.kind,
base_url: provider.base_url,
declared: parseProviderParameters({
text: provider.parameters,
}),
}),
}),
});
await BunSQLite.sql({
@@ -1,5 +1,7 @@
import type { BUN_SQLITE_COBBLE_HARNESS_PROVIDERS } from "@/db/types/db";
import grabProviderPreset from "@/src/harness/providers/grab-provider-preset";
import providerParameterKeys from "@/src/harness/providers/provider-parameter-keys";
import parseProviderParameters from "./parse-provider-parameters";
import type { PublicHarnessProvider } from "@/src/types";
type Params = {
@@ -14,19 +16,29 @@ export default function toPublicHarnessProvider({
provider,
}: Params): PublicHarnessProvider {
const preset = grabProviderPreset({ kind: provider.kind });
const base_url = provider.base_url || preset.base_url;
return {
id: provider.id || 0,
kind: preset.value,
name: provider.name || preset.title,
base_url: provider.base_url || preset.base_url,
base_url,
enabled: provider.enabled != 0,
has_key: Boolean(provider.api_key),
has_env_key: Boolean(preset.key_env && process.env[preset.key_env]),
needs_key: preset.needs_key,
key_env: preset.key_env || undefined,
context_length: provider.context_length || undefined,
/**
* What its form shows ticked, and what its models get on the next
* sync: its saved pick, else its preset's or host's list.
*/
parameters: providerParameterKeys({
kind: preset.value,
base_url,
declared: parseProviderParameters({ text: provider.parameters }),
}),
last_synced_at: provider.last_synced_at || undefined,
sync_error: provider.sync_error || undefined,
};
}
}
@@ -1,6 +1,7 @@
import BunSQLite from "@moduletrace/bun-sqlite";
import type { HarnessCatalogModel } from "@/src/harness/types";
import modelContextLength from "./model-context-length";
import modelSupportedParameters from "./model-supported-parameters";
type Params = {
provider_id: number;
@@ -10,6 +11,11 @@ type Params = {
* of their own (a custom provider lists ids only).
*/
provider_context_length?: number | null;
/**
* The generation settings its provider declares, as the names a model's
* `supported_parameters` carries, for the models it lists without any.
*/
provider_parameters?: string[] | null;
now?: number;
};
@@ -49,6 +55,7 @@ export default async function upsertHarnessModels({
provider_id,
models,
provider_context_length,
provider_parameters,
now = Date.now(),
}: Params) {
const unique = [...new Map(models.map((m) => [m.slug, m])).values()];
@@ -63,27 +70,36 @@ export default async function upsertHarnessModels({
${Columns.filter((c) => c != "created_at" && c != "provider_id" && c != "slug")
.map((c) => `${c} = excluded.${c}`)
.join(", ")}`,
values: chunk.flatMap((model) => [
now,
now,
provider_id,
model.slug,
model.name || model.slug,
model.free ? 1 : 0,
1,
JSON.stringify(model.input_modalities),
JSON.stringify(model.output_modalities),
model.supports_tools ? 1 : 0,
modelContextLength({ model, provider_context_length }),
model.max_output_tokens ?? null,
model.voices ? JSON.stringify(model.voices) : null,
model.supported_parameters ? JSON.stringify(model.supported_parameters) : null,
model.intelligence_score ?? null,
model.agentic_score ?? null,
model.released_at ?? null,
model.expires_at ?? null,
now,
]),
values: chunk.flatMap((model) => {
const supported_parameters = modelSupportedParameters({
model,
provider_parameters,
});
return [
now,
now,
provider_id,
model.slug,
model.name || model.slug,
model.free ? 1 : 0,
1,
JSON.stringify(model.input_modalities),
JSON.stringify(model.output_modalities),
model.supports_tools ? 1 : 0,
modelContextLength({ model, provider_context_length }),
model.max_output_tokens ?? null,
model.voices ? JSON.stringify(model.voices) : null,
supported_parameters
? JSON.stringify(supported_parameters)
: null,
model.intelligence_score ?? null,
model.agentic_score ?? null,
model.released_at ?? null,
model.expires_at ?? null,
now,
];
}),
});
if (!res.success) {
@@ -0,0 +1,31 @@
import BunSQLite from "@moduletrace/bun-sqlite";
type Params = {
user_id: number | string;
};
type UserNameRow = {
first_name: string | null;
last_name: string | null;
username: string | null;
};
/**
* The user's name as the app shows it (first and last, else username), or
* empty when they have neither. Every run's prompt gets it, so its bot knows
* who it's working for instead of asking them to confirm it.
*/
export default async function grabUserName({ user_id }: Params): Promise<string> {
const row = (
await BunSQLite.sql<UserNameRow>({
sql: `SELECT first_name, last_name, username FROM users WHERE id = ? LIMIT 1`,
values: [user_id],
})
).payload?.[0];
return (
[row?.first_name, row?.last_name].filter(Boolean).join(" ").trim() ||
row?.username?.trim() ||
""
);
}
@@ -0,0 +1,62 @@
import { AppData } from "@/src/data/app-data";
import downloadComputerFile from "@/src/functions/backend/computers/download-computer-file";
import { mimeTypeForFile } from "@/src/functions/backend/db/bot-files/media-type-for-file";
import grabComputerTarget from "@/src/functions/backend/db/computers/grab-computer-target";
import { canSeePath } from "./list-storage-entries";
import resolveStoragePath from "./resolve-storage-path";
import type { ResolvedStorageSpec } from "./resolve-storage-spec";
type Params = {
resolved: ResolvedStorageSpec;
/**
* The file to open, relative to the volume's root.
*/
path?: string | null;
};
export type ComputerStorageFile = {
bytes: Buffer;
name: string;
size: number;
mime_type: string;
};
/**
* One file of a computer's workspace, streamed from its agent when the app
* itself can't read the folder (a dev server running as a plain user can't
* read a worker's folder). The same path rules and the same access check as
* the file on this machine (`grabStorageFile`), and the same size limit.
* Null when it isn't a file there, or the computer can't be reached.
*/
export default async function grabComputerStorageFile({
resolved,
path: requested,
}: Params): Promise<ComputerStorageFile | null> {
if (resolved.spec.volume != "computers") return null;
const resolved_path = resolveStoragePath({ root: resolved.root, path: requested });
if (!resolved_path.name) return null;
if (!canSeePath({ resolved, path: resolved_path.relative })) return null;
const target = await grabComputerTarget({ computer_id: resolved.spec.owner_id });
if (!target?.ready || target.connection != "docker") return null;
const file = `${AppData.ComputerWorkspaceDir}/${resolved_path.relative}`;
const download = await downloadComputerFile({
computer: target,
path: file,
max_bytes: AppData.StorageBrowserReadMaxBytes,
});
if (!download.ok) return null;
return {
bytes: download.bytes,
name: resolved_path.name,
size: download.size,
mime_type: mimeTypeForFile({ name: resolved_path.name }),
};
}
@@ -0,0 +1,36 @@
import { describe, expect, test } from "bun:test";
import { parseComputerDirectory } from "./list-computer-directory";
function field({ type, name, size = 0, modified = 0 }: { type: string; name: string; size?: number; modified?: number }) {
return `${type}\0${name}\0${size}\0${modified}\0`;
}
describe("parseComputerDirectory", () => {
test("reads a folder and a file, with its size and time", () => {
const output = field({ type: "d", name: "users", modified: 1763000000 }) +
field({ type: "f", name: "browser-tabs.md", size: 512, modified: 1763000000.75 });
expect(parseComputerDirectory({ output })).toEqual([
{ name: "users", kind: "folder", size: 0, modified_at: 1763000000000 },
{ name: "browser-tabs.md", kind: "file", size: 512, modified_at: 1763000000750 },
]);
});
test("leaves out anything but a folder or a file", () => {
const output = field({ type: "l", name: "escape" }) +
field({ type: "s", name: "socket" }) +
field({ type: "f", name: "kept.md", size: 1 });
expect(parseComputerDirectory({ output }).map((entry) => entry.name)).toEqual(["kept.md"]);
});
test("drops a last entry the answer was cut off in", () => {
const output = field({ type: "f", name: "kept.md", size: 1 }) + "f\0cut-off\0";
expect(parseComputerDirectory({ output }).map((entry) => entry.name)).toEqual(["kept.md"]);
});
test("reads nothing from an empty answer", () => {
expect(parseComputerDirectory({ output: "" })).toEqual([]);
});
});
@@ -0,0 +1,72 @@
import { AppData } from "@/src/data/app-data";
import runComputerCommand from "@/src/functions/backend/computers/run-computer-command";
import grabComputerTarget from "@/src/functions/backend/db/computers/grab-computer-target";
import shellQuote from "@/src/utils/shell-quote";
export type ComputerDirectoryEntry = {
name: string;
kind: "file" | "folder";
size: number;
modified_at: number;
};
type Params = {
computer_id: number | string;
/**
* The folder inside the computer's workspace, relative to its root, e.g.
* `bots/14/users/1`. Empty for the root.
*/
relative: string;
};
/**
* One folder of a computer's workspace, read through its agent when the app
* itself can't open the folder: a dev server running as a plain user can't
* read a worker's folder (`cb-<bot>` owns it), while the agent runs as root
* on the computer. Hidden entries are listed like any other, and symlinks
* are left out, as the browser never follows them. Null when the computer
* can't be reached or the folder isn't there.
*/
export default async function listComputerDirectory({ computer_id, relative }: Params) {
const target = await grabComputerTarget({ computer_id });
if (!target?.ready || target.connection != "docker") return null;
const folder = relative ? `${AppData.ComputerWorkspaceDir}/${relative}` : AppData.ComputerWorkspaceDir;
const command = `sudo -n find ${shellQuote({ text: folder })} -mindepth 1 -maxdepth 1 -printf '%y\\000%f\\000%s\\000%T@\\000' 2>/dev/null`;
const result = await runComputerCommand({ computer: target, command, timeout_ms: 30_000 }).catch(() => null);
if (!result || result.exit_code != 0) return null;
return parseComputerDirectory({ output: result.output });
}
/**
* The agent's `find -printf` answer, four NUL-separated fields an entry:
* its type (`d` or `f`), name, size and modification time in seconds.
* Anything else a folder holds (a symlink, a socket) is left out, and a
* cut-off last entry (a truncated answer) is dropped whole.
*/
export function parseComputerDirectory({ output }: { output: string }) {
const fields = output.split("\0");
if (fields.at(-1) === "") fields.pop();
const entries: ComputerDirectoryEntry[] = [];
for (let index = 0; index + 3 < fields.length; index += 4) {
const [type, name, size, modified] = fields.slice(index, index + 4);
if (!name) continue;
if (type != "d" && type != "f") continue;
entries.push({
name,
kind: type == "d" ? "folder" : "file",
size: type == "f" ? Number(size) || 0 : 0,
modified_at: Math.round((Number(modified) || 0) * 1000),
});
}
return entries;
}
@@ -1,4 +1,4 @@
import { existsSync, lstatSync, readdirSync } from "node:fs";
import { lstatSync, readdirSync, type Dirent } from "node:fs";
import path from "node:path";
import BunSQLite from "@moduletrace/bun-sqlite";
import type { BUN_SQLITE_COBBLE_BOT_FILES } from "@/db/types/db";
@@ -6,6 +6,7 @@ import { AppData } from "@/src/data/app-data";
import grabMediaURL from "../media/grab-media-url";
import computerFolderLabel from "@/src/utils/computer-folder-label";
import computerPathAllowed from "@/src/utils/computer-path-allowed";
import listComputerDirectory, { type ComputerDirectoryEntry } from "./list-computer-directory";
import { isInsideRoot } from "./resolve-storage-path";
import type { ResolvedStorageSpec } from "./resolve-storage-spec";
import type { StorageEntry } from "@/src/types";
@@ -58,13 +59,24 @@ export default async function listStorageEntries({
* starts, a bot's before its first file) shows as empty rather than as
* an error. `missing` keeps that apart from a path that isn't there at
* all, which a stale folder link lands on (the page says so, instead of
* claiming the folder is empty).
* claiming the folder is empty). A worker's computer folder that this
* process can't open (a dev server running as a plain user) is read
* through the computer's agent instead.
*/
if (!existsSync(absolute) || !canSeePath({ resolved, path: relative })) {
const host = hostFolderEntries({ absolute });
const rows =
host == "missing"
? null
: host == "unreadable"
? resolved.spec.volume == "computers"
? await listComputerDirectory({ computer_id: resolved.spec.owner_id, relative })
: null
: host;
if (!rows || !canSeePath({ resolved, path: relative })) {
return { entries: [], total: 0, offset, missing: true };
}
const rows = readdirSync(absolute, { withFileTypes: true });
const indexed = await botFileRows({ resolved, paths: rows.map((row) => joinPath({ relative, name: row.name })) });
const needle = search?.trim().toLowerCase() || "";
const entries: StorageEntry[] = [];
@@ -82,27 +94,13 @@ export default async function listStorageEntries({
if (!isInsideRoot({ root: resolved.root, absolute: entry_absolute })) continue;
let stats;
try {
stats = lstatSync(entry_absolute);
} catch {
continue;
}
/**
* A symlink is not followed: it may lead anywhere, and the
* volume's own folders are what this lists.
*/
if (stats.isSymbolicLink()) continue;
if (stats.isDirectory()) {
if (row.kind == "folder") {
entries.push({
name: row.name,
path: entry_path,
kind: "folder",
size: 0,
modified_at: Math.round(stats.mtimeMs),
modified_at: row.modified_at,
url: storageSpecHref({ spec: resolved.spec, path: entry_path }),
label: resolved.computer
? computerFolderLabel({ path: entry_path, names: resolved.computer.names }) || undefined
@@ -111,8 +109,6 @@ export default async function listStorageEntries({
continue;
}
if (!stats.isFile()) continue;
const file = indexed.get(entry_path);
const { media_url } = file?.media_id
? grabMediaURL({ media: { id: file.media_id } as any })
@@ -122,8 +118,8 @@ export default async function listStorageEntries({
name: row.name,
path: entry_path,
kind: "file",
size: stats.size,
modified_at: Math.round(stats.mtimeMs),
size: row.size,
modified_at: row.modified_at,
media_type: file?.media_type || undefined,
file_id: file?.id ? Number(file.id) : undefined,
url: media_url || fileUrl({ spec: resolved.spec, path: entry_path }),
@@ -199,6 +195,56 @@ export function canSeePath({ resolved, path }: { resolved: ResolvedStorageSpec;
return !resolved.computer || computerPathAllowed({ ...resolved.computer, path });
}
/**
* One folder's own entries on this machine, or why there are none: a
* missing folder, or one this process may not open (a worker's computer
* folder belongs to the worker's own account).
*/
function hostFolderEntries({
absolute,
}: {
absolute: string;
}): ComputerDirectoryEntry[] | "unreadable" | "missing" {
let rows: Dirent[];
try {
rows = readdirSync(absolute, { withFileTypes: true });
} catch (error) {
const code = (error as NodeJS.ErrnoException).code;
return code == "EACCES" || code == "EPERM" ? "unreadable" : "missing";
}
const entries: ComputerDirectoryEntry[] = [];
for (const row of rows) {
let stats;
try {
stats = lstatSync(path.join(absolute, row.name));
} catch {
continue;
}
/**
* A symlink is not followed: it may lead anywhere, and the volume's
* own folders are what this lists.
*/
if (stats.isSymbolicLink()) continue;
if (stats.isDirectory()) {
entries.push({ name: row.name, kind: "folder", size: 0, modified_at: Math.round(stats.mtimeMs) });
continue;
}
if (!stats.isFile()) continue;
entries.push({ name: row.name, kind: "file", size: stats.size, modified_at: Math.round(stats.mtimeMs) });
}
return entries;
}
function joinPath({ relative, name }: { relative: string; name: string }) {
return relative ? `${relative}/${name}` : name;
}
@@ -9,6 +9,7 @@ type Params = {
| "new-session"
| "continue-session"
| "reopen-session"
| "delete-session"
| "session-messages"
| "older-messages";
body: Record<string, unknown>;
+9
View File
@@ -11,6 +11,12 @@ type Params = {
status?: number;
retryable?: boolean;
retry_at?: number;
/**
* The provider never answered within `AppData.HarnessRequestTimeoutMs`.
* A tool whose retry only waits the same span again (`generate_image`)
* reads it to stop instead of spending another three minutes.
*/
timed_out?: boolean;
provider_wide?: boolean;
candidate_key?: string;
resting?: boolean;
@@ -49,6 +55,7 @@ export default class HarnessError extends Error {
* Unix ms before which the failed candidate shouldn't be tried again.
*/
retry_at?: number;
timed_out: boolean;
/**
* The provider's key or account is the problem, so every model on it
* fails the same way.
@@ -75,6 +82,7 @@ export default class HarnessError extends Error {
status,
retryable = false,
retry_at,
timed_out = false,
provider_wide = false,
candidate_key,
resting = false,
@@ -89,6 +97,7 @@ export default class HarnessError extends Error {
this.status = status;
this.retryable = retryable;
this.retry_at = retry_at;
this.timed_out = timed_out;
this.provider_wide = provider_wide;
this.candidate_key = candidate_key;
this.resting = resting;
+14 -2
View File
@@ -7,6 +7,7 @@ import type { HarnessImageOutput, HarnessUsage } from "../types";
import buildUsageCall from "../usage/build-usage-call";
import recordHarnessUsage from "../usage/record-harness-usage";
import orderImageCandidates from "./order-image-candidates";
import referenceModelNote from "./reference-model-note";
type Params = {
prompt: string;
@@ -63,8 +64,15 @@ export default async function generateImage({
}
const harness_of = new Map(ordered.map(({ candidate, harness }) => [candidate.key, harness]));
/**
* A pick that can't take an image is skipped with references, so the
* failure names the model that actually ran and why the pick wasn't it.
*/
const note = has_references
? referenceModelNote({ image, tried: ordered[0]?.candidate.model })
: undefined;
const { result } = await withCandidates<{ images: HarnessImageOutput[]; usage?: HarnessUsage }>({
const made = await withCandidates<{ images: HarnessImageOutput[]; usage?: HarnessUsage }>({
harness: edit?.picked ? "image_edit" : "image",
harness_of,
candidates: ordered.map(({ candidate }) => candidate),
@@ -89,9 +97,13 @@ export default async function generateImage({
references,
signal: signal || new AbortController().signal,
}),
}).catch((error: unknown) => {
if (note && error instanceof Error) error.message = `${error.message} ${note}`;
throw error;
});
return result.images;
return made.result.images;
}
/**
@@ -0,0 +1,79 @@
import { describe, expect, test } from "bun:test";
import type { HarnessCandidate } from "../types";
import referenceModelNote from "./reference-model-note";
const candidate = ({
slug,
name,
modalities,
source,
}: {
slug: string;
name?: string;
modalities: string[];
source: HarnessCandidate["source"];
}): HarnessCandidate => ({
key: `2:${slug}`,
provider: { id: 2, kind: "custom", base_url: "https://example.test" },
model: {
slug,
name,
input_modalities: modalities,
output_modalities: ["image"],
supports_tools: false,
},
source,
});
describe("referenceModelNote", () => {
test("names the model that ran when the pick can't take a reference", () => {
const note = referenceModelNote({
image: [
candidate({ slug: "recraft-v4.1", name: "Recraft V4.1", modalities: ["text"], source: "pinned" }),
],
tried: {
slug: "qwen-image-3.0-pro",
name: "qwen-image-3.0-pro",
input_modalities: ["text", "image"],
output_modalities: ["image"],
supports_tools: false,
},
});
expect(note).toBe(
"Recraft V4.1 can't take reference images, so this went to qwen-image-3.0-pro instead.",
);
});
test("says nothing when the pick itself takes references", () => {
expect(
referenceModelNote({
image: [
candidate({
slug: "gemini-image",
modalities: ["text", "image"],
source: "pinned",
}),
],
}),
).toBeUndefined();
});
test("says nothing when image generation has no pick", () => {
expect(referenceModelNote({ image: [] })).toBeUndefined();
});
test("still says where it went when the model that ran has no name", () => {
expect(
referenceModelNote({
image: [candidate({ slug: "recraft", modalities: ["text"], source: "pinned" })],
tried: {
slug: "qwen-image",
input_modalities: ["text", "image"],
output_modalities: ["image"],
supports_tools: false,
},
}),
).toBe("recraft can't take reference images, so this went to qwen-image instead.");
});
});
+30
View File
@@ -0,0 +1,30 @@
import type { HarnessCandidate, HarnessModelInfo } from "../types";
type Params = {
/**
* Image generation's candidates, as resolved.
*/
image: HarnessCandidate[];
/**
* The model the call actually reached.
*/
tried?: HarnessModelInfo;
};
/**
* Why a call with a reference image never reached the model the Image
* setting picked: a model that can't take an image is skipped with
* references (`orderImageCandidates`), so the call went to Image editing's
* model instead. Said on the failure, because the bot reports only the model
* that ran and the user is left thinking its pick was used (Recraft was set
* a minute before a run spent 29 minutes on the old qwen edit pick).
*/
export default function referenceModelNote({ image, tried }: Params): string | undefined {
const pinned = image.find((candidate) => candidate.source == "pinned");
if (!pinned || pinned.model.input_modalities.includes("image")) return undefined;
return `${pinned.model.name || pinned.model.slug} can't take reference images, so this went to ${
tried ? tried.name || tried.slug : "another model"
} instead.`;
}
+2 -1
View File
@@ -1,4 +1,5 @@
import { ReadImagePrompt } from "@/src/data/harness-prompts";
import type { HarnessWireParams } from "@/src/dict/harness-parameter-dict";
import HarnessError from "../harness-error";
import grabHarnessAdapter from "../providers/grab-harness-adapter";
import resolveHarnessCandidates from "../resolve/resolve-harness-candidates";
@@ -56,7 +57,7 @@ export default async function readImage({ url, focus, signal, bot_id, workspace_
const { result } = await withCandidates<{
text: string;
usage?: HarnessUsage;
sent_params: Record<string, number | string | { effort: string }>;
sent_params: HarnessWireParams;
}>({
harness: "vision",
candidates,
@@ -2,6 +2,7 @@ import type { HarnessAdapter } from "../../types";
import grabProviderPreset from "../grab-provider-preset";
import providerRequest from "./provider-request";
import readChatResponse from "./read-chat-response";
import toWireChatParams from "./to-wire-chat-params";
import toWireMessages from "./to-wire-messages";
/**
@@ -24,7 +25,7 @@ const chat: HarnessAdapter["chat"] = async ({
// Generation settings first, so the core fields below always win:
// a saved parameter must never override the model, the messages,
// the tools or the token ceiling (R12).
...(params || {}),
...toWireChatParams({ params, kind: provider.kind }),
model: model.slug,
messages: toWireMessages({ messages }),
...(tools?.length
@@ -88,7 +88,14 @@ export default async function providerRequest({
: `Couldn't reach ${provider_name} at ${method} ${url}: ${error instanceof Error ? error.message : String(error)}`
: `${provider_name} stopped sending the response.`;
return new HarnessError({ message, retryable: true, candidate_key, method, url });
return new HarnessError({
message,
retryable: true,
candidate_key,
method,
url,
timed_out: phase == "headers" && controller.signal.aborted,
});
};
let res: Response;
@@ -0,0 +1,35 @@
import { describe, expect, test } from "bun:test";
import toWireChatParams from "./to-wire-chat-params";
describe("toWireChatParams", () => {
test("OpenRouter nests the reasoning effort", () => {
expect(
toWireChatParams({
kind: "openrouter",
params: { temperature: 0.3, reasoning: { effort: "high" } },
}),
).toEqual({ temperature: 0.3, reasoning: { effort: "high" } });
});
test("everyone else takes it flat", () => {
expect(
toWireChatParams({
kind: "custom",
params: { temperature: 0.3, reasoning: { effort: "high" } },
}),
).toEqual({ temperature: 0.3, reasoning_effort: "high" });
});
test("the other settings pass through as they are", () => {
expect(
toWireChatParams({
kind: "openai",
params: { top_p: 0.5, enable_thinking: false },
}),
).toEqual({ top_p: 0.5, enable_thinking: false });
});
test("nothing saved sends nothing", () => {
expect(toWireChatParams({ kind: "openai" })).toEqual({});
});
});
@@ -0,0 +1,28 @@
import type { HarnessProviderKind } from "@/src/dict/harness-provider-dict";
import type { HarnessWireParams } from "@/src/dict/harness-parameter-dict";
type Params = {
params?: HarnessWireParams;
kind: HarnessProviderKind;
};
/**
* The generation settings as a provider's `/chat/completions` takes them.
* OpenRouter nests the reasoning effort as `reasoning: { effort }`; everyone
* else (OpenAI, Groq, Alibaba, a custom host) takes it flat as
* `reasoning_effort`, where the nested form is ignored.
*/
export default function toWireChatParams({ params, kind }: Params) {
const wire: HarnessWireParams = { ...(params || {}) };
if (kind == "openrouter") return wire;
const reasoning = wire.reasoning;
if (reasoning && typeof reasoning == "object") {
delete wire.reasoning;
wire.reasoning_effort = reasoning.effort;
}
return wire;
}
@@ -0,0 +1,53 @@
import { describe, expect, test } from "bun:test";
import providerParameterKeys from "./provider-parameter-keys";
describe("provider parameter keys", () => {
test("a provider's own saved pick wins over its preset", () => {
expect(
providerParameterKeys({
kind: "openai",
declared: ["seed"],
}),
).toEqual(["seed"]);
});
test("an empty saved pick means it takes none", () => {
expect(
providerParameterKeys({ kind: "openai", declared: [] }),
).toEqual([]);
});
test("a preset's list fills a provider that saved none", () => {
expect(
providerParameterKeys({ kind: "groq", base_url: "https://api.groq.com/openai/v1" }),
).toContain("temperature");
});
test("a custom provider on Alibaba gets Alibaba's list", () => {
const keys = providerParameterKeys({
kind: "custom",
base_url: "https://token-plan.us-east-1.maas.aliyuncs.com/compatible-mode/v1",
});
expect(keys).toContain("enable_thinking");
expect(keys).toContain("thinking_budget");
});
test("a custom provider elsewhere gets nothing rather than a guess", () => {
expect(
providerParameterKeys({
kind: "custom",
base_url: "http://localhost:8000/v1",
}),
).toBeUndefined();
});
test("OpenRouter keeps its catalog's own list", () => {
expect(
providerParameterKeys({
kind: "openrouter",
base_url: "https://openrouter.ai/api/v1",
}),
).toBeUndefined();
});
});
@@ -0,0 +1,59 @@
import type { HarnessParameterKey } from "@/src/dict/harness-parameter-dict";
import {
HarnessProviderKinds,
type HarnessProviderKind,
} from "@/src/dict/harness-provider-dict";
import { isDashScopeHost } from "./openai-compatible/dashscope-hosts";
/**
* What Alibaba's compatible mode documents taking, the Token Plan hosts
* included. `thinking_budget` is refused by a few of their models, so it is
* offered but not sent until asked for.
*/
const DashScopeParameters: readonly HarnessParameterKey[] = [
"temperature",
"top_p",
"presence_penalty",
"seed",
"enable_thinking",
"thinking_budget",
];
type Params = {
kind: HarnessProviderKind;
base_url?: string | null;
/**
* What the provider's own row saved, when a super admin set it. An empty
* array is a real answer (it takes none); null or undefined follows the
* preset, then the host.
*/
declared?: readonly HarnessParameterKey[] | null;
};
/**
* The generation settings a provider's models are offered: what its row
* saved, else its preset's list, else the list for its host (a custom
* provider pointed at Alibaba). Undefined when nobody knows, which leaves its
* models with no settings rather than sending a field it might refuse.
*/
export default function providerParameterKeys({
kind,
base_url,
declared,
}: Params): HarnessParameterKey[] | undefined {
if (declared) return [...declared];
const preset = HarnessProviderKinds.find((p) => p.value == kind);
if (preset?.parameters.length) return [...preset.parameters];
/**
* OpenRouter's catalog says what each model takes, so its models keep
* their own list.
*/
if (kind != "openrouter" && isDashScopeHost({ base_url })) {
return [...DashScopeParameters];
}
return undefined;
}
@@ -170,6 +170,30 @@ describe("withCandidates", () => {
expect(error.retryable).toBe(false);
});
/**
* `generate_image` stops a run's later calls after a provider timeout, so
* the flag has to survive the error the caller finally sees.
*/
test("keeps the timeout flag from the failure it reports", async () => {
const a = candidate("a");
const error = (await withCandidates({
harness: "image",
candidates: [a],
cooldowns: createCooldowns(),
run: async () => {
throw new HarnessError({
message: "took too long to answer",
retryable: true,
candidate_key: a.key,
timed_out: true,
});
},
}).catch((e) => e)) as HarnessError;
expect(error.timed_out).toBe(true);
});
test("waits instead of calling when everything is cooling down", async () => {
const cooldowns = createCooldowns();
const a = candidate("a");
+1
View File
@@ -259,6 +259,7 @@ export default async function withCandidates<T>({
model_name: last.model_name,
method: last.method,
url: last.url,
timed_out: last.timed_out,
});
}
+3 -2
View File
@@ -2,6 +2,7 @@ import HarnessError from "../harness-error";
import grabHarnessAdapter from "../providers/grab-harness-adapter";
import resolveHarnessCandidates from "../resolve/resolve-harness-candidates";
import withCandidates from "../resolve/with-candidates";
import type { HarnessWireParams } from "@/src/dict/harness-parameter-dict";
import type {
HarnessCandidate,
HarnessChatResult,
@@ -38,7 +39,7 @@ export type GenerateTextParams = {
/**
* Overrides the saved generation settings (media reading wants 0).
*/
params?: Record<string, number | string | { effort: string }>;
params?: HarnessWireParams;
signal?: AbortSignal;
/**
* Media readings shared across calls of one run.
@@ -67,7 +68,7 @@ type ChatAnswer = Omit<HarnessChatResult, "text"> & {
/**
* The generation settings sent to this candidate, for its usage row.
*/
sent_params?: Record<string, number | string | { effort: string }>;
sent_params?: HarnessWireParams;
};
/**
@@ -83,6 +83,15 @@ describe("grabChatParams", () => {
expect(paramsFor(model(["reasoning_effort"]))).toEqual({});
});
test("thinking on/off goes on the wire as a boolean", async () => {
options = { enable_thinking: "false" };
const { paramsFor } = await grabChatParams({ harness: "text" });
expect(paramsFor(model(["enable_thinking"]))).toEqual({
enable_thinking: false,
});
});
test("the vision default is a literal 0", async () => {
const { paramsFor } = await grabChatParams({ harness: "vision" });
+11 -2
View File
@@ -2,6 +2,7 @@ import {
HarnessParameters,
harnessParameterValue,
modelAdvertisesParameter,
type HarnessWireParams,
} from "@/src/dict/harness-parameter-dict";
import grabHarnessSetting from "@/src/functions/backend/db/harness/grab-harness-setting";
import type { HarnessModelInfo } from "../types";
@@ -26,7 +27,7 @@ export default async function grabChatParams({
bot_id,
workspace_id,
}: Params): Promise<{
paramsFor: (model: HarnessModelInfo) => Record<string, number | string | { effort: string }>;
paramsFor: (model: HarnessModelInfo) => HarnessWireParams;
source: "default" | "bot" | "workspace";
}> {
const setting = await grabHarnessSetting({
@@ -55,9 +56,17 @@ export default async function grabChatParams({
return [];
const key = "wire" in parameter ? parameter.wire : parameter.key;
const boolean = "wire_boolean" in parameter;
return [
[key, key == "reasoning" ? { effort: String(value) } : value],
[
key,
key == "reasoning"
? { effort: String(value) }
: boolean
? value === "true"
: value,
],
];
}),
);
+162 -1
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, stuckToolNote, SupersededSnapshotNote, ToolImagesNote } from "@/src/data/harness-prompts";
import { alreadyRanToolNote, answerNotSentNote, closingFailedNote, closingMixedNote, closingNoTextNote, closingToolGoneNote, contextTrimmedNote, DroppedToolImageNote, repeatedAnswerNote, replyClosingMixedNote, replyClosingRequiredNote, replyDraftNote, replyNoTextNote, StoppedRunNote, 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";
@@ -2046,6 +2046,77 @@ describe("runTextLoop required send_reply", () => {
expect(result.review_note).toBe(replyDraftNote);
});
test("a stray call on the last turn is traced, and gets one more turn to answer", async () => {
/**
* Job 687 reached for a tool the run no longer had on its last turn:
* the call and a finished report were dropped, the turn was never
* traced, and the notice read as if the review had refused the text.
*/
const { generate, seen } = scripted([
{ tool_calls: [{ id: "c1", name: "remember", arguments: `{"note":"x"}` }] },
{ text: "First draft." },
{ text: "Second draft." },
{ tool_calls: [{ id: "c2", name: "remember", arguments: `{"note":"again"}` }] },
{
text: "The report.",
tool_calls: [{ id: "s1", name: "send_reply", arguments: `{"status":"done"}` }],
},
]);
const traces: HarnessTrace[] = [];
const result = await runTextLoop({
system: "s",
messages: [{ role: "user", content: "Go." }],
tools: [remember, sendReply],
max_steps: 1,
generate,
resolveCandidates,
require_closing_answer: true,
trace: (entry) => {
traces.push(entry);
},
});
expect(seen).toHaveLength(5);
expect(seen[4]!.tools!.map((tool) => tool.name)).toEqual(["send_reply"]);
expect(seen[4]!.messages.at(-1)!.content).toContain(closingToolGoneNote);
expect(traces.find((entry) => entry.kind === "turn" && entry.index === 3)).toMatchObject({
text: null,
tool_calls: [{ name: "remember", arguments: `{"note":"again"}` }],
});
expect(traces.find((entry) => entry.kind === "event" && entry.name === "closing_failed")).toMatchObject({
index: 3,
});
expect(result.text).toBe("The report.");
expect(result.tool_uses).toEqual([
{ name: "remember", ok: true },
{ name: "send_reply", ok: true },
]);
});
test("a second stray call on the last turn ends the run unsent", async () => {
const { generate } = scripted([
{ tool_calls: [{ id: "c1", name: "remember", arguments: `{"note":"x"}` }] },
{ text: "First draft." },
{ text: "Second draft." },
{ tool_calls: [{ id: "c2", name: "remember", arguments: `{"note":"again"}` }] },
{ tool_calls: [{ id: "c3", name: "remember", arguments: `{"note":"and again"}` }] },
]);
const result = await runTextLoop({
system: "s",
messages: [{ role: "user", content: "Go." }],
tools: [remember, sendReply],
max_steps: 1,
generate,
resolveCandidates,
require_closing_answer: true,
});
expect(result.text).toBe("");
expect(result.review_note).toBe(closingToolGoneNote);
});
test("passes send_reply's status to the review", async () => {
const statuses: (string | undefined)[] = [];
const { generate } = scripted([
@@ -2709,3 +2780,93 @@ describe("runTextLoop trimming and wrap up notes", () => {
expect(runText(seen[1]!.messages)).not.toContain("What is on disk now");
});
});
describe("runTextLoop stop", () => {
const sendReply: HarnessTool<{ status?: "done" | "working" | "blocked"; message?: string }> = {
name: "send_reply",
description: "Sends the message.",
schema: z.object({
status: z.enum(["done", "working", "blocked"]).optional(),
message: z.string().optional(),
}),
run: async () => "Sent.",
};
test("a stopped run drops the call in flight and writes what it did", async () => {
const stop = new AbortController();
const seen: GenerateTextParams[] = [];
const generate = async (params: GenerateTextParams) => {
seen.push(params);
if (seen.length == 1) {
stop.abort();
throw new HarnessError({ message: "Cancelled.", code: "aborted" });
}
return {
text: "Stopped. I read the file; the report is unwritten.",
tool_calls: [{ id: "s1", name: "send_reply", arguments: `{"status":"done"}` }],
candidate,
} as GenerateTextResult;
};
const result = await runTextLoop({
system: "s",
messages: [{ role: "user", content: "Write the report." }],
tools: [remember, sendReply],
stop_signal: stop.signal,
generate,
resolveCandidates,
require_closing_answer: true,
});
expect(result.text).toContain("Stopped.");
expect(result.status).toBe("done");
expect(
seen[1]!.messages.some(
(message) => typeof message.content == "string" && message.content.includes(StoppedRunNote),
),
).toBe(true);
expect(seen[1]!.tools?.map((tool) => tool.name)).toEqual(["send_reply"]);
});
test("a call the stop cuts off still answers every call of its turn", async () => {
const stop = new AbortController();
const cut: HarnessTool = {
name: "glance",
description: "Looks at something.",
schema: z.object({ at: z.string() }),
run: async () => {
stop.abort();
throw new HarnessError({ message: "Cancelled.", code: "aborted" });
},
};
const { generate, seen } = scripted([
{
tool_calls: [
{ id: "c1", name: "glance", arguments: `{"at":"one"}` },
{ id: "c2", name: "glance", arguments: `{"at":"two"}` },
],
},
{ text: "Stopped. I looked at one page.", tool_calls: [{ id: "s1", name: "send_reply", arguments: "{}" }] },
]);
const result = await runTextLoop({
system: "s",
messages: [{ role: "user", content: "Check both." }],
tools: [cut, sendReply],
stop_signal: stop.signal,
generate,
resolveCandidates,
require_closing_answer: true,
});
const tools = seen[1]!.messages.filter((message) => message.role == "tool");
expect(tools).toEqual([
{ role: "tool", tool_call_id: "c1", content: "The user stopped this call." },
{ role: "tool", tool_call_id: "c2", content: "The user stopped this call." },
]);
expect(result.text).toContain("Stopped.");
});
});
+207 -72
View File
@@ -5,6 +5,7 @@ import {
closingFailedNote,
closingMixedNote,
closingNoTextNote,
closingToolGoneNote,
commitEarlyNote,
contextTrimmedNote,
failedToolCallNote,
@@ -17,6 +18,7 @@ import {
replyDraftNote,
replyNoTextNote,
staticPromptOverBudgetNote,
StoppedRunNote,
stuckToolNote,
tokensLowNote,
} from "@/src/data/harness-prompts";
@@ -98,6 +100,13 @@ type Params = {
*/
context_budget?: RunLimit;
signal?: AbortSignal;
/**
* Aborted when the user stops the run from the chat: the call in flight
* is dropped, and the run's next turn stops where it is and writes what
* it did so far (`StoppedRunNote`). Never the same as `signal`: that one
* ends the run with no answer at all.
*/
stop_signal?: AbortSignal;
/**
* The model a plan turn already used (`planBotTask`). Tried first among
* the automatic picks, so the run works the plan on the model that
@@ -432,6 +441,7 @@ export default async function runTextLoop({
max_prompt_tokens,
context_budget,
signal = new AbortController().signal,
stop_signal,
prefer_key: planned_key,
onStep,
trace,
@@ -616,6 +626,11 @@ export default async function runTextLoop({
* the sentence that goes with it (`closingNoTextNote`).
*/
let told_closing_text = false;
/**
* The last turn called a tool the run no longer has, and has been told
* once to write its message again beside `send_reply`.
*/
let told_stray_call = false;
/**
* A message that stopped inside a table, a fence or a bare marker has
* been sent back once (`unfinishedAnswerText`). Past that the run
@@ -699,6 +714,18 @@ export default async function runTextLoop({
* on): the next turn offers none, so the run always ends.
*/
let used_wrap_turn = false;
/**
* The user stopped the run: whatever was in flight is dropped, and the
* turn that follows says what the run did so far (`StoppedRunNote`).
*/
let stopped = false;
/**
* What an in-flight call is aborted by. The stop reaches only the turn
* it interrupted: the summary after it has to reach the model, or the
* run could never say what it did (the job's own `signal` still ends it,
* and `stop-bot-jobs` gives up after `AppData.BotStopSummaryMs`).
*/
const callSignal = () => (stopped || !stop_signal ? signal : AbortSignal.any([signal, stop_signal]));
/**
* One trace entry, kept only when the run has somewhere to put it. A
@@ -714,6 +741,35 @@ export default async function runTextLoop({
}
};
/**
* A turn as the debug view reads it: what the model reasoned and said,
* the calls it made and the answer it spent. Written wherever a turn
* ends, the one dropped for calling a tool it no longer has included.
*/
const traceTurn = async ({
index,
answer,
calls,
started_at,
}: {
index: number;
answer: Awaited<ReturnType<typeof generate>>;
calls: { name: string; arguments: string }[];
started_at: number;
}) =>
traced({
kind: "turn",
index,
model: answer.candidate.model.name || answer.candidate.model.slug,
provider: answer.candidate.provider.name || null,
text: answer.text,
reasoning: answer.reasoning ?? null,
tool_calls: calls.map((call) => ({ name: call.name, arguments: call.arguments })),
usage: answer.usage ?? null,
finish_reason: answer.finish_reason ?? null,
duration_ms: Date.now() - started_at,
});
/**
* The answer checked against the app's own record before it goes out:
* files, tasks and settings it names, and work it says is under way. A
@@ -790,7 +846,13 @@ export default async function runTextLoop({
max_prompt_tokens > 0 &&
usage.prompt_tokens >= max_prompt_tokens,
);
const wrap_up: boolean = out_of_steps || out_of_tokens || same_tool.stuck !== null;
/**
* A stop is the run's own wrap up: no more work, one turn to say
* what it did. Read once and kept, so the turn after a dropped call
* is still the summary.
*/
stopped ||= Boolean(stop_signal?.aborted);
const wrap_up: boolean = out_of_steps || out_of_tokens || same_tool.stuck !== null || stopped;
/**
* Why the run is wrapping up: its steps, its tokens, or one tool
* called over and over.
@@ -802,12 +864,33 @@ export default async function runTextLoop({
* with no tools at all, so the run always ends.
*/
const wrap_up_saving =
wrap_up && !used_wrap_turn && saving_turns < WrapUpSavingTurns && wrap_tools.length > 0;
wrap_up && !stopped && !used_wrap_turn && saving_turns < WrapUpSavingTurns && wrap_tools.length > 0;
/**
* The turn past which nothing is written again. A stopped run keeps
* its one rewrite: a summary the review faults has to be written
* once more, or the stop says nothing.
*/
const final_wrap = wrap_up && !wrap_up_saving && !stopped;
if (wrap_up && !wrap_up_announced) {
wrap_up_announced = true;
if (incoming_notes?.wrap_up) await takeIncoming({ note: incoming_notes.wrap_up, index, counted: false });
if (stopped) {
/**
* A stopped run gets no wrap-up prompt and no worktree
* read: it stops where it is and writes what happened.
*/
pushUserTurn({ transcript, content: StoppedRunNote });
await traced({
kind: "event",
index,
name: "stopped",
text: "The user stopped this run. It writes what happened so far.",
});
}
if (!stopped) {
if (incoming_notes?.wrap_up) await takeIncoming({ note: incoming_notes.wrap_up, index, counted: false });
/**
* The machine's own account of the work, when the caller has
@@ -845,6 +928,7 @@ export default async function runTextLoop({
: "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."}`,
});
}
}
if (wrap_up_saving) saving_turns++;
@@ -935,17 +1019,30 @@ export default async function runTextLoop({
const turn_started_at = Date.now();
const answer = await generate({
messages: [{ role: "system", content: run_system }, ...transcript],
tools: definitions.length ? definitions : undefined,
candidates,
prefer_key,
signal,
media_cache,
bot_id,
workspace_id,
limits: call_limits,
});
let answer: Awaited<ReturnType<typeof generate>>;
try {
answer = await generate({
messages: [{ role: "system", content: run_system }, ...transcript],
tools: definitions.length ? definitions : undefined,
candidates,
prefer_key,
signal: callSignal(),
media_cache,
bot_id,
workspace_id,
limits: call_limits,
});
} catch (error) {
/**
* The user stopped the run while the model was answering: that
* call is dropped and the next turn writes what happened.
*/
if (!stop_signal?.aborted || signal.aborted) throw error;
stopped = true;
continue;
}
prefer_key = answer.candidate.key;
usage.prompt_tokens += answer.usage?.prompt_tokens || 0;
@@ -999,24 +1096,41 @@ export default async function runTextLoop({
}
/**
* On the last turn only the answer tool is offered: a turn that
* reaches for anything else beside it would have that call silently
* dropped, and the message could say it happened. Refuse the whole
* turn and say what is left.
* On the last turn only the answer tool is offered: a call for
* anything else beside it would never run, and the message could say
* it did. The call and that turn's message are dropped, and the turn
* is told once what is left.
*/
if (
wrap_up &&
!wrap_up_saving &&
answer_tools.length > 0 &&
answer.tool_calls.some((call) => !answer_tools.some((tool) => tool.name == call.name))
) {
const stray_calls =
wrap_up && !wrap_up_saving && !stopped && answer_tools.length > 0
? answer.tool_calls.filter((call) => !answer_tools.some((tool) => tool.name == call.name))
: [];
if (stray_calls.length) {
/**
* This is the last turn, so there is no next one to try again
* on: the message would be a draft the app cannot vouch for.
* The dropped turn is traced before it goes: it is the one that
* ended the run, and a debug view that left it out showed a run
* failing with nothing after its last tool (job 687).
*/
await traceTurn({ index, answer, calls: answer.tool_calls, started_at: turn_started_at });
if (!told_stray_call && !out_of_tokens) {
told_stray_call = true;
pushUserTurn({ transcript, content: closingToolGoneNote });
await traced({
kind: "event",
index,
name: "closing_failed",
text: `Only ${answer_tools.map((tool) => tool.name).join(" and ")} can end this run, and this turn called ${stray_calls.map((call) => call.name).join(", ")} instead, so it has one more turn to write the message.`,
});
continue;
}
await traced({ kind: "event", index, name: "closing_failed", text: closingToolGoneNote });
return {
text: "",
review_note: `Only ${answer_tools.map((tool) => tool.name).join(" and ")} can end this run, and this turn called something else beside it, so no message was sent.`,
review_note: closingToolGoneNote,
messages: transcript,
steps: index + 1,
candidate: answer.candidate,
@@ -1038,18 +1152,7 @@ export default async function runTextLoop({
candidate: answer.candidate,
});
await traced({
kind: "turn",
index,
model: answer.candidate.model.name || answer.candidate.model.slug,
provider: answer.candidate.provider.name || null,
text: answer.text,
reasoning: answer.reasoning ?? null,
tool_calls: tool_calls.map((call) => ({ name: call.name, arguments: call.arguments })),
usage: answer.usage ?? null,
finish_reason: answer.finish_reason ?? null,
duration_ms: Date.now() - turn_started_at,
});
await traceTurn({ index, answer, calls: tool_calls, started_at: turn_started_at });
/**
* An answer the user wrote past is drafted again. Not on the wrap
@@ -1085,7 +1188,7 @@ export default async function runTextLoop({
* the end: returning it as an answer is exactly the hole this
* protocol closes.
*/
if (!(wrap_up && !wrap_up_saving) && reply_drafts < AppData.HarnessReplyDraftsMax) {
if (!final_wrap && reply_drafts < AppData.HarnessReplyDraftsMax) {
reply_drafts += 1;
draft_text = answer.text || "";
card_text = "";
@@ -1108,7 +1211,7 @@ export default async function runTextLoop({
if (!tool_calls.length && (!wrap_up || review_pending)) {
review_pending = false;
const check = await checkAnswer({ text: answer.text || "", index, final: wrap_up });
const check = await checkAnswer({ text: answer.text || "", index, final: final_wrap });
if (check.verdict === "refused") {
/**
@@ -1126,7 +1229,7 @@ export default async function runTextLoop({
* (M3). So the repaired text is checked again, and goes
* out only once the app's record supports all of it.
*/
const recheck = await checkAnswer({ text: repaired.text, index, final: wrap_up });
const recheck = await checkAnswer({ text: repaired.text, index, final: final_wrap });
if (recheck.verdict === "passed") {
await traced({
@@ -1182,7 +1285,7 @@ export default async function runTextLoop({
const said = (answer.text || "").trim();
return {
text: said || `I ran out of steps before I could finish.`,
text: said || (stopped ? "" : `I ran out of steps before I could finish.`),
messages: transcript,
steps: index + 1,
candidate: answer.candidate,
@@ -1200,7 +1303,7 @@ export default async function runTextLoop({
const said = (answer.text || "").trim();
return {
text: said || (wrap_up ? `I ran out of steps before I could finish.` : ""),
text: said || (wrap_up && !stopped ? `I ran out of steps before I could finish.` : ""),
messages: transcript,
steps: index + 1,
candidate: answer.candidate,
@@ -1213,6 +1316,12 @@ export default async function runTextLoop({
const shown: { tool_name: string; images: HarnessToolImage[] }[] = [];
/**
* A call the stop cut off takes the rest of the turn with it: the
* summary is the next turn, not this one.
*/
let broke_for_stop = false;
for (const call of tool_calls) {
const repeat_key = repeatToolCallKey({ call });
const remembered = repeat_key ? repeated_reads.get(repeat_key) : undefined;
@@ -1229,27 +1338,51 @@ export default async function runTextLoop({
const give_up =
failed_before !== undefined && failed_before.attempts > AppData.HarnessSameFailureRetries;
const result: ToolCallResult =
already_read !== undefined
? {
text: alreadyRanToolNote({ name: call.name, step: already_read }),
images: [],
duration_ms: 0,
ok: true,
}
: give_up
? {
text: failedToolCallNote({
name: call.name,
step: failed_before.step,
attempts: failed_before.attempts,
error: failed_before.error,
}),
images: [],
duration_ms: 0,
ok: false,
}
: await runToolCall({ call, tools: run_tools, signal });
let result: ToolCallResult;
try {
result =
already_read !== undefined
? {
text: alreadyRanToolNote({ name: call.name, step: already_read }),
images: [],
duration_ms: 0,
ok: true,
}
: give_up
? {
text: failedToolCallNote({
name: call.name,
step: failed_before.step,
attempts: failed_before.attempts,
error: failed_before.error,
}),
images: [],
duration_ms: 0,
ok: false,
}
: await runToolCall({ call, tools: run_tools, signal: callSignal() });
} catch (error) {
/**
* The user stopped the run while this call ran: it stops
* here, and every call of the turn still gets an answer so
* the conversation stays valid. The next turn says what
* happened.
*/
if (!stop_signal?.aborted || signal.aborted) throw error;
for (const cut of tool_calls.slice(tool_calls.indexOf(call))) {
transcript.push({
role: "tool",
tool_call_id: cut.id,
content: "The user stopped this call.",
});
}
stopped = true;
broke_for_stop = true;
break;
}
const { text: content, images } = result;
const ok = result.ok;
@@ -1324,6 +1457,8 @@ export default async function runTextLoop({
if (images.length) shown.push({ tool_name: call.name, images });
}
if (broke_for_stop) continue;
/**
* An answer that called a card is the whole reply: the question
* waits for the user, and what comes next was just offered. Going on
@@ -1404,7 +1539,7 @@ export default async function runTextLoop({
* card it can't put up. A required closing message is refused
* instead: without `send_reply` there is no honest message.
*/
if (closing_retries >= AppData.MaxClosingRetries || (wrap_up && !wrap_up_saving)) {
if (closing_retries >= AppData.MaxClosingRetries || final_wrap) {
if (require_closing_answer) {
return {
text: "",
@@ -1421,7 +1556,7 @@ export default async function runTextLoop({
};
}
const check = await checkAnswer({ text: answer.text || "", index, final: wrap_up && !wrap_up_saving });
const check = await checkAnswer({ text: answer.text || "", index, final: final_wrap });
return {
text: check.verdict === "refused" ? "" : answer.text || "",
@@ -1460,7 +1595,7 @@ export default async function runTextLoop({
if (closing_worked && called_card && !message_text.trim()) {
const no_text_note = called_send_reply ? replyNoTextNote : closingNoTextNote;
if (!told_closing_text && !(wrap_up && !wrap_up_saving)) {
if (!told_closing_text && !final_wrap) {
told_closing_text = true;
pushUserTurn({ transcript, content: no_text_note });
await traced({ kind: "event", index, name: "closing_no_text", text: no_text_note });
@@ -1500,7 +1635,7 @@ export default async function runTextLoop({
const unfinished = unfinishedAnswerText({ text: message_text });
if (unfinished) {
if (!told_unfinished && !(wrap_up && !wrap_up_saving)) {
if (!told_unfinished && !final_wrap) {
told_unfinished = true;
draft_text = "";
card_text = "";
@@ -1520,7 +1655,7 @@ export default async function runTextLoop({
};
}
const final_turn = wrap_up && !wrap_up_saving;
const final_turn = final_wrap;
const check = await checkAnswer({ text: message_text, index, status: reply_status, final: final_turn });
if (check.verdict === "refused") {
@@ -1546,7 +1681,7 @@ export default async function runTextLoop({
candidate: answer.candidate,
usage,
tool_uses,
status: reply_status,
status: stopped ? "done" : reply_status,
};
}
}
@@ -1581,7 +1716,7 @@ export default async function runTextLoop({
candidate: answer.candidate,
usage,
tool_uses,
status: reply_status,
status: stopped ? "done" : reply_status,
};
}
@@ -59,7 +59,7 @@ export default function continueInNewSessionTool({
return {
name: "continue_in_new_session",
description: `Move this conversation into a fresh session, carrying over a summary you write. Every reply re-reads the session's recent messages, so a long one costs more each time. Always use it when the user asks to carry on in a new, fresh or different session ("let's continue this in another session", "start a new chat for this"): don't just agree, move. Also use it when the session has grown long and the current topic is at a natural break (say so in your answer). The summary opens the new session, shown to the user and given to you from then on in place of these messages, so put in everything needed to carry on: what the user wants, decisions made, what's done, what's in progress or open, and every name, number, path, link and ref ([bot:ID], [file:ID], ...) exactly. Call it last: your answer then goes in the new session under the summary, so keep it to a line.`,
description: `Move this conversation into a fresh session, carrying over a summary you write. Every reply re-reads the session's recent messages, so a long one costs more each time. Always use it when the user asks to carry on in a new, fresh or different session ("let's continue this in another session", "start a new chat for this"): don't just agree, move. Also use it when the session has grown long and the current topic is at a natural break (say so in your answer). The summary opens the new session, shown to the user and given to you from then on in place of these messages, so put in everything needed to carry on: what the user wants, decisions made, what's done, what's in progress or open, and every name, number, path, link and ref ([bot:ID], [file:ID], ...) exactly. Call it last: your answer then goes in the new session under the summary, so keep it to a line. If the user wrote something while you worked, answer that here first: the conversation only moves once everything they said is answered.`,
schema: z.object({
summary: z
.string()
@@ -46,7 +46,7 @@ export default function createScheduleTool({ user_id, bot_id, workspace_id, comp
computers.length
? `Runs use the computer you're on when they start unless you pick one: ${listed}.`
: `You have no computer here, so runs can't use one.`
} Write the instructions as a full brief for a future you with no memory of this chat. Runs carry the brief out without asking the user, so state the action itself ("send the summary to ..."), not a draft for them to approve, unless they asked to approve it.`,
} Write the instructions as a full brief for a future you with no memory of this chat, and as the plan the run follows: the steps in order, each naming what it produces. Runs carry the brief out without asking the user, so state the action itself ("send the summary to ..."), not a draft for them to approve, unless they asked to approve it.`,
schema: z.object({
title: z.string().min(1).max(80).describe(`A short label, e.g. "Morning inbox digest"`),
instructions: z.string().min(1).max(8000),
@@ -66,7 +66,7 @@ export default function proposeHookTool({
name: "propose_hook",
description: `Propose a hook for the user to confirm: a secret URL an outside service (a webhook from GitHub, Stripe, a form, a script) calls to give you a task, or a watcher that hands you each browser notification on one of your computers (source browser_notifications, with watch_computer_id and an optional watch_filter, text the notification's site, title or body must contain). Every call queues your instructions (the brief) as a task for you, ${
workspace_id ? "in this workspace" : "in your own chat"
}, with what the caller sent attached as data, in the hook's own thread: results never come back to this chat, the user reads them by opening the hook. Runs carry the brief out without asking the user, so write it as a full brief for a future you with no memory of this chat, saying exactly what to do with each call. ${
}, with what the caller sent attached as data, in the hook's own thread: results never come back to this chat, the user reads them by opening the hook. Runs carry the brief out without asking the user, so write it as a full brief for a future you with no memory of this chat, saying exactly what to do with each call, and lay it out as the plan the run follows: the steps in order, each naming what it produces. ${
computers.length ? `Your computers here: ${listed}.` : `You have no computer here, so it can't watch one.`
} To change one of your hooks (ids from list_hooks), give hook_id and only what changes: title, instructions, watch_filter, enabled true to switch a paused one back on, or its runner; what calls it and where it runs can't change. A hook whose caller is a process on your computer (a bridge started there) can keep it running: give runner_command, the command the app runs for it, runner_dir (a folder inside the bot's folder, such as whatsapp) and, if not the bot's own, runner_computer_id. The app starts it again by itself within five minutes of it dying, and when the computer restarts, so it must stay in the foreground and not go into the background with &. It runs as the bot's account, and the card shows the command word for word: only a crew manager can confirm a runner, so if the user isn't one, tell them an admin has to. Nothing is saved until the user presses Confirm on the card. A new hook's URL is shown to the user on the card, once: you never see it, never ask for it, and never set a signing secret (the user adds one from the Hooks menu). Check list_hooks first: if a hook already does the job, propose a change to it instead. When the user tells you to handle a hook's calls differently (often in reply to a run's report), tell them the hook's brief has to change for that and propose the new brief. Runs follow the brief over your memory, so don't save it to your memory or promise to do it from now on instead: neither changes what the next call does.`,
schema: z.object({
@@ -7,12 +7,6 @@ import type { HarnessTool } from "../../../types";
type Params = {
bot_id: number | string;
session_id: number | string;
/**
* The step is finished inside a run that works the whole plan itself (a
* routine), so this isn't the reply that ends it: the run carries on
* into the next step, and one run can finish more than one.
*/
in_run?: boolean;
};
type Args = {
@@ -26,14 +20,12 @@ type Args = {
* ends on, so a step is only ever finished by a run that did the work, one
* at a time.
*/
export default function completePlanStepTool({ bot_id, session_id, in_run }: Params): HarnessTool<Args> {
export default function completePlanStepTool({ bot_id, session_id }: Params): HarnessTool<Args> {
let completed = false;
return {
name: "complete_plan_step",
description: in_run
? `Finish one step of the plan, once you have actually done it, before you start the next. Give one or two lines on what it produced (the number, the path, the link). You work this plan yourself here, so call it after each step and keep going.`
: `Finish the plan's current step, once you have actually done it. Give one or two lines on what it produced (the number, the path, the link). Call it before you write your report: the report is this reply's last message. One step per reply. Never call it for a step you didn't do, and never for one after the current step.`,
description: `Finish the plan's current step, once you have actually done it. Give one or two lines on what it produced (the number, the path, the link). Call it before you write your report: the report is this reply's last message. One step per reply. Never call it for a step you didn't do, and never for one after the current step.`,
schema: z.object({
plan_id: z.number().int().positive().describe(`The plan's id, as your prompt gives it`),
summary: z
@@ -47,7 +39,7 @@ export default function completePlanStepTool({ bot_id, session_id, in_run }: Par
.describe(`What the step produced, in a line or two`),
}),
run: async ({ args }) => {
if (completed && !in_run) {
if (completed) {
throw new Error(`You already finished a step of this plan in this reply. One step per reply.`);
}
@@ -71,11 +63,7 @@ export default function completePlanStepTool({ bot_id, session_id, in_run }: Par
const next = done.steps[done.next_step ?? 0];
if (in_run) {
return `Step ${done.index + 1} is done: the card shows it. Carry on with step ${(done.next_step ?? 0) + 1}: ${next?.text || ""}. Save your report for the end, when every step is done.`;
}
return `Step ${done.index + 1} is done: the card shows it. The next step (step ${(done.next_step ?? 0) + 1}: ${next?.text || ""}) starts when the user answers the card on your report, so don't start it now. Write your report: two or three sentences on what this step produced, and put the card up beside it.`;
},
};
}
}
@@ -1,6 +1,5 @@
import { z } from "zod";
import createBotPlan from "@/src/functions/backend/db/bot-plans/create-bot-plan";
import setBotPlanStatus from "@/src/functions/backend/db/bot-plans/set-bot-plan-status";
import pushBotPlan from "@/src/bots-queue/push-bot-plan";
import { BotPlanGoalSchema, BotPlanStepTextsSchema, BotPlanTitleSchema } from "@/src/schemas/bot-plan-schema";
import botPlanRef from "@/src/utils/bot-plan-ref";
@@ -12,13 +11,7 @@ type Params = {
session_id: number | string;
workspace_id?: number | string | null;
/**
* A scheduled run, which nobody watches: the plan is approved at once,
* since there is no card for someone to approve it on.
*/
approve?: boolean;
/**
* Called with the plan's ref, so the message carries its card. `waiting`
* says nobody approved it yet: the user is needed for it to go on.
* Called with the plan's ref, so the message carries its card.
*/
onPlan: (params: { ref: string; waiting?: boolean }) => void;
};
@@ -30,17 +23,15 @@ type Args = {
};
/**
* The bot broke work into a plan. In a chat it waits on its card for the
* user to approve (or change) it, and the app then wakes the bot one step at
* a time. In a scheduled run nobody is there to approve anything, so the
* plan starts itself and the run works through it.
* The bot broke work into a plan. It waits on its card for the user to
* approve (or change) it, and the app then wakes the bot one step at a time.
* A routine and a hook call have no card to wait on, so they get no plan
* tools at all.
*/
export default function createPlanTool({ user_id, bot_id, session_id, workspace_id, approve, onPlan }: Params): HarnessTool<Args> {
export default function createPlanTool({ user_id, bot_id, session_id, workspace_id, onPlan }: Params): HarnessTool<Args> {
return {
name: "create_plan",
description: approve
? `Write the plan for work that is several steps, before starting it: the goal that says what finished looks like, and 3 to 6 steps in the order you'd do them, one line each, each naming what it produces. Nobody is watching this run, so it's approved at once and you work it here: call complete_plan_step after each step.`
: `Write the plan for work that is several steps, before starting it: the goal that says what finished looks like, and 3 to 6 steps in the order you'd do them, one line each, each naming what it produces. It goes to the user as a card in this conversation, and nothing of it runs until they approve it (they can change the steps first). Write the plan instead of answering with a long list of everything you're about to do. Only when a plan is already open in this conversation, work it instead.`,
description: `Write the plan for work that is several steps, before starting it: the goal that says what finished looks like, and 3 to 6 steps in the order you'd do them, one line each, each naming what it produces. It goes to the user as a card in this conversation, and nothing of it runs until they approve it (they can change the steps first). Write the plan instead of answering with a long list of everything you're about to do. Only when a plan is already open in this conversation, work it instead.`,
schema: z.object({
title: BotPlanTitleSchema.describe(`A short name for the work, e.g. "Audit the pricing pages"`),
goal: BotPlanGoalSchema.describe(`What the plan is for and what "done" means, in one sentence`),
@@ -57,20 +48,12 @@ export default function createPlanTool({ user_id, bot_id, session_id, workspace_
steps: args.steps,
});
if (approve) {
await setBotPlanStatus({ plan_id, user_id, status: "active" });
}
onPlan({ ref: botPlanRef({ plan_id }), waiting: !approve });
onPlan({ ref: botPlanRef({ plan_id }), waiting: true });
await pushBotPlan({ plan_id, session_id, bot_id });
const count = args.steps.length;
if (approve) {
return `Plan #${plan_id} is written (${count} step${count == 1 ? "" : "s"}), and it's approved already because this run isn't watched. Work its steps in this run, calling complete_plan_step after each with what it produced.`;
}
return `Plan #${plan_id} is on its card in the conversation (${count} step${count == 1 ? "" : "s"}) and nothing of it runs until the user approves it. Say in one sentence that you wrote it and that they can change it before it starts; don't repeat the steps and don't work any of them now. When they approve it, you'll be woken for the first step.`;
},
};
}
}
@@ -3,11 +3,10 @@ import grabBotPlanTools from "./grab-bot-plan-tools";
/**
* A run working a plan's step may only work it: writing another plan, or
* cancelling the one it was woken for, is the user's call on the card. A
* scheduled run has no card to approve anything on, so its plan starts
* itself and nothing is left for the bot to cancel. A reply that isn't a
* step can't finish one either, or the plan would sit active with no card
* to start the next step from.
* cancelling the one it was woken for, is the user's call on the card. Only
* a chat reply writes a plan. A reply that isn't a step can't finish one
* either, or the plan would sit active with no card to start the next step
* from.
*/
const names = (tools: { name: string }[]) => tools.map((tool) => tool.name);
@@ -30,10 +29,6 @@ describe("grabBotPlanTools", () => {
expect(names(build({ on_step: true }))).toEqual(["update_plan", "complete_plan_step"]);
});
test("a scheduled run writes a plan that's already approved, and can't cancel it", () => {
expect(names(build({ approve: true }))).toEqual(["create_plan", "update_plan", "complete_plan_step"]);
});
test("a plan the app writes shows its card on the message", () => {
const refs: string[] = [];
@@ -41,4 +36,4 @@ describe("grabBotPlanTools", () => {
expect(refs).toEqual([]);
});
});
});
@@ -14,11 +14,6 @@ type Params = {
* to write one or end one.
*/
on_step?: boolean;
/**
* A scheduled run, which nobody watches: a plan it writes is approved
* at once and worked through in the run (`ScheduledPlanNote`).
*/
approve?: boolean;
/**
* Called with each plan's ref, so the message carries its card.
*/
@@ -28,9 +23,9 @@ type Params = {
/**
* The tools a bot plans with: `create_plan` when work is several steps,
* `update_plan` when what it found makes the rest wrong, and
* `complete_plan_step` to finish the step it worked. A chat reply's plan
* waits on its card for the user; a scheduled run's is approved at once,
* since nobody is there to approve it.
* `complete_plan_step` to finish the step it worked. A plan waits on its
* card for the user; only a chat reply writes one, since routines and hook
* calls already have their plan.
*
* A run that is itself working a plan gets neither `create_plan` (the
* conversation already has one open) nor `cancel_plan` (whether the plan
@@ -40,20 +35,17 @@ type Params = {
* finish it with no card under its report, and the plan would sit active
* with nothing to start the next one.
*/
export default function grabBotPlanTools({ user_id, bot_id, session_id, workspace_id, on_step, approve, onPlan }: Params) {
export default function grabBotPlanTools({ user_id, bot_id, session_id, workspace_id, on_step, onPlan }: Params) {
const tools: HarnessTool[] = [];
if (!on_step) {
tools.push(createPlanTool({ user_id, bot_id, session_id, workspace_id, approve, onPlan }));
if (!approve) {
tools.push(cancelPlanTool({ user_id, bot_id, session_id }));
}
tools.push(createPlanTool({ user_id, bot_id, session_id, workspace_id, onPlan }));
tools.push(cancelPlanTool({ user_id, bot_id, session_id }));
}
tools.push(updatePlanTool({ user_id, bot_id, session_id, onPlan }));
if (on_step || approve) tools.push(completePlanStepTool({ bot_id, session_id, in_run: approve }));
if (on_step) tools.push(completePlanStepTool({ bot_id, session_id }));
return tools;
}
}
@@ -38,7 +38,7 @@ export default function updateScheduleTool({ user_id, bot_id, is_coordinator, wo
schema: z.object({
schedule_id: z.number().int(),
title: z.string().min(1).max(80).optional(),
instructions: z.string().min(1).max(8000).optional(),
instructions: z.string().min(1).max(8000).optional().describe("The brief every run follows, as its plan: the steps in order"),
schedule: z.string().min(1).max(100).optional(),
enabled: z.boolean().optional(),
max_runs: z.number().int().positive().nullable().optional(),
@@ -0,0 +1,61 @@
import { afterAll, describe, expect, mock, test } from "bun:test";
import HarnessError from "@/src/harness/harness-error";
import type { StorageToolContext } from "./storage-tool-context";
/**
* A provider that never answers costs the whole request timeout, and a bot
* that retries it waits the same span again: four attempts once took 29
* minutes. The tool allows one timeout per run, then a plain report.
*/
let calls = 0;
let failure: unknown;
mock.module("@/src/harness/image/generate-image", () => ({
default: async () => {
calls += 1;
throw failure;
},
}));
const { default: generateImageTool } = await import("./generate-image-tool");
afterAll(() => {
mock.restore();
});
const context: StorageToolContext = {
user_id: 1,
bot_id: 3,
scopes: [{ scope: "bot", owner_id: 3 }],
};
const signal = new AbortController().signal;
describe("generate_image after a provider timeout", () => {
test("stops the run's other attempts", async () => {
calls = 0;
failure = new HarnessError({
message: "Example took too long to answer.",
retryable: true,
timed_out: true,
});
const tool = generateImageTool(context);
await expect(tool.run({ args: { prompt: "draw a cat" }, signal })).rejects.toThrow(
"Image generation isn't working",
);
await expect(tool.run({ args: { prompt: "draw a cat again" }, signal })).rejects.toThrow(
"The image model timed out earlier in this run",
);
expect(calls).toBe(1);
});
test("a failure that isn't a timeout can be tried again", async () => {
calls = 0;
failure = new HarnessError({ message: "No image came back.", retryable: true });
const tool = generateImageTool(context);
await expect(tool.run({ args: { prompt: "draw a cat" }, signal })).rejects.toThrow();
await expect(tool.run({ args: { prompt: "draw a cat again" }, signal })).rejects.toThrow();
expect(calls).toBe(2);
});
});
@@ -4,6 +4,7 @@ import { AppData } from "@/src/data/app-data";
import generateImage from "@/src/harness/image/generate-image";
import loadReferenceImages from "@/src/harness/image/load-reference-images";
import describeHarnessFailure from "@/src/harness/describe-harness-failure";
import HarnessError from "@/src/harness/harness-error";
import parseFileRef from "@/src/utils/parse-file-ref";
import type { HarnessTool } from "../../types";
import {
@@ -35,6 +36,12 @@ type Args = {
*/
export default function generateImageTool(context: StorageToolContext): HarnessTool<Args> {
const own = context.scopes[0];
/**
* A provider that never answers costs the whole request timeout and a
* retry waits the same span again (one run spent 29 minutes on four).
* This run gets one timeout, then a plain report.
*/
let timed_out = false;
return {
name: "generate_image",
@@ -68,6 +75,12 @@ export default function generateImageTool(context: StorageToolContext): HarnessT
scope: z.string().optional().describe(`"bot:<id>" or "workspace:<id>"`),
}),
run: async ({ args, signal }) => {
if (timed_out) {
throw new Error(
`The image model timed out earlier in this run, so calling it again would wait the same ${Math.round(AppData.HarnessRequestTimeoutMs / 60_000)} minutes and fail the same way. Stop here and report what failed. Don't build the image another way unless the user asks for that.`,
);
}
const named = args.scope
? findNamedScope({ scopes: context.scopes, name: args.scope })
: own;
@@ -100,6 +113,7 @@ export default function generateImageTool(context: StorageToolContext): HarnessT
bot_id: context.bot_id,
workspace_id: context.workspace_id,
}).catch((error: unknown) => {
timed_out = error instanceof HarnessError && error.timed_out;
throw new Error(`Image generation isn't working: ${describeHarnessFailure({ error })}`);
});
+2 -1
View File
@@ -1,6 +1,7 @@
import type { z } from "zod";
import type { HarnessKind } from "@/src/dict/harness-dict";
import type { HarnessProviderKind } from "@/src/dict/harness-provider-dict";
import type { HarnessWireParams } from "@/src/dict/harness-parameter-dict";
/**
* Part of a user message. Images are an https or `data:` URL; audio is
@@ -234,7 +235,7 @@ export type HarnessChatParams = {
* Sampling and reasoning fields, keyed by their wire name. The caller
* only includes what the model advertises.
*/
params?: Record<string, number | string | { effort: string }>;
params?: HarnessWireParams;
signal: AbortSignal;
};
@@ -13,6 +13,12 @@ describe("flattenSentParams", () => {
expect(flattenSentParams({ params: { temperature: 0, seed: "" } })).toEqual({ temperature: 0 });
});
test("reads a boolean setting back as on or off", () => {
expect(
flattenSentParams({ params: { enable_thinking: false, temperature: 0.3 } }),
).toEqual({ enable_thinking: "off", temperature: 0.3 });
});
test("is undefined when nothing was sent", () => {
expect(flattenSentParams({ params: {} })).toBeUndefined();
expect(flattenSentParams({ params: null })).toBeUndefined();
+5 -1
View File
@@ -1,8 +1,10 @@
import type { HarnessWireParams } from "@/src/dict/harness-parameter-dict";
type Params = {
/**
* Keyed by the field sent on the wire (`grabChatParams`).
*/
params?: Record<string, number | string | { effort: string }> | null;
params?: HarnessWireParams | null;
};
/**
@@ -17,6 +19,8 @@ export default function flattenSentParams({ params }: Params) {
for (const [key, value] of Object.entries(params || {})) {
if (value && typeof value == "object") {
if (value.effort) flat[key == "reasoning" ? "reasoning_effort" : key] = String(value.effort);
} else if (typeof value == "boolean") {
flat[key] = value ? "on" : "off";
} else if (typeof value == "number" || (typeof value == "string" && value)) {
flat[key] = value;
}
+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 }),
};
}
+17 -3
View File
@@ -18,15 +18,28 @@ type Props = {
* Every bot (of the crew, or of a workspace), latest activity first, with
* a search by name or job. A bot opens its conversation.
*/
export default function AllBotsModal({ open, setOpen, title, bots, hrefFor }: Props) {
export default function AllBotsModal({
open,
setOpen,
title,
bots,
hrefFor,
}: Props) {
const [query, setQuery] = useState("");
const search = query.trim().toLowerCase();
const found = search
? bots.filter((bot) => `${bot.name} ${bot.role || ""}`.toLowerCase().includes(search))
? bots.filter((bot) =>
`${bot.name} ${bot.role || ""}`.toLowerCase().includes(search),
)
: bots;
return (
<AddModalShell open={open} setOpen={setOpen} title={title} description={`${bots.length} in all.`}>
<AddModalShell
open={open}
setOpen={setOpen}
title={title}
description={`${bots.length} in all.`}
>
<Input
id="all-bots-search"
title="Search bots"
@@ -35,6 +48,7 @@ export default function AllBotsModal({ open, setOpen, title, bots, hrefFor }: Pr
defaultValue={query}
onChange={(e) => setQuery(e.target.value)}
wrapperWrapperProps={{ className: "mt-4" }}
autoFocus
/>
<Stack className="w-full mt-2 max-h-[60vh] overflow-y-auto gap-0! items-stretch">
{found.map((bot) => (
@@ -16,6 +16,7 @@ type Props = {
stone: BotStoneShape;
image_media_id?: number | string | null;
picked_src?: string;
avatar_size?: number;
};
/**
@@ -30,6 +31,7 @@ export default function BotFormPreview({
stone,
image_media_id,
picked_src,
avatar_size = 56,
}: Props) {
const has_picture = Boolean(picked_src || image_media_id);
/** A palette colour by name, else a colour the user made up. */
@@ -42,7 +44,7 @@ export default function BotFormPreview({
<BotAvatar
color={color}
stone={stone}
size={56}
size={avatar_size}
image_media_id={image_media_id}
src={picked_src}
/>
+9 -1
View File
@@ -91,7 +91,14 @@ export default function BotForm({ bot, onCancel, onSaved }: Props) {
})
: await postAdminApi<{ bot_id: number }>({
path: "bots/create-bot",
body: { name, role, color, stone, system_prompt, workspace_id },
body: {
name,
role,
color,
stone,
system_prompt,
workspace_id,
},
});
const bot_id =
bot?.id ||
@@ -158,6 +165,7 @@ export default function BotForm({ bot, onCancel, onSaved }: Props) {
stone={stone}
image_media_id={image.image_media_id}
picked_src={image.data_url}
avatar_size={120}
/>
}
has_image={image.has_image}
+2
View File
@@ -9,6 +9,7 @@ import { SettingsDefaultPath } from "../dict/settings-pages-dict";
import grabInstallName from "../functions/backend/db/app-settings/grab-install-name";
import grabInstallIcon from "../functions/backend/db/app-settings/grab-install-icon";
import grabLastConversation from "../functions/backend/db/bot-sessions/grab-last-conversation";
import grabPrecacheManifest from "../functions/server/pwa/grab-precache-manifest";
import isPagesRailPath from "../utils/is-pages-rail-path";
/**
@@ -87,6 +88,7 @@ const server: BunextPageServerFn<PagePropsType> = async ({ req, url }) => {
},
user,
user_types,
build_id: grabPrecacheManifest()?.build_id || null,
install_name: await grabInstallName().catch(() => ""),
install_icon: await grabInstallIcon().catch(() => null),
last_conversation:
+4
View File
@@ -20,6 +20,7 @@ import AuthLayout from "../layouts/auth";
import BotsLayout from "../layouts/bots";
import ThemeInitScript from "../components/general/theme-init-script";
import PwaInitScript from "../components/general/pwa-init-script";
import { PwaBuildMetaName } from "../data/pwa-data";
import ServiceWorkerRegistrar from "../components/general/service-worker-registrar";
export const AppContext = React.createContext<AppContextObject>(
@@ -111,6 +112,9 @@ export function Head({ serverRes, ctx }: BunextPageHeadFCProps) {
<>
<ThemeInitScript />
<PwaInitScript />
{root_props?.build_id ? (
<meta name={PwaBuildMetaName} content={root_props.build_id} />
) : null}
<meta name="application-name" content={app_name} />
<meta name="mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-capable" content="yes" />
@@ -0,0 +1,15 @@
/**
* The composer's slash commands: what `/new`, `/continue` and `/clear` do
* to the conversation's session, and how the list above the input
* describes them.
*/
export type ComposerCommand = {
name: "new" | "continue" | "clear";
description: string;
};
export const ComposerCommands: ComposerCommand[] = [
{ name: "new", description: "Start a fresh session" },
{ name: "continue", description: "Carry this conversation into a new session, with a summary" },
{ name: "clear", description: "Delete this session and start a new one" },
];
@@ -12,6 +12,7 @@ export default async function sendBotMessage({
session_id,
client_id,
plan_mode,
build_id,
}: SendBotMessageRequest) {
return await fetchApi<
SendBotMessageRequest,
@@ -27,6 +28,7 @@ export default async function sendBotMessage({
session_id,
client_id,
plan_mode,
build_id,
},
});
}
@@ -20,12 +20,11 @@ type Params = {
/**
* Loads the session's older messages a page at a time, when the thread
* is scrolled to its top. Once the session's first message is in, the
* session it carries on from can be opened above it (`loadPrevious`, on
* the user's ask) and paged the same way, and so on back. Those messages
* are only shown: the bot's prompt still reads the session it answers in.
* A session the thread moves onto starts with its first message, so it
* has none older; `reset` starts over from a loaded history instead.
* is scrolled to its top. The session it carries on from is opened as its
* own page (its id is handed back for the link), never in place: the bot's
* prompt reads the session it answers in, not this one. A session the
* thread moves onto starts with its first message, so it has none older;
* `reset` starts over from a loaded history instead.
*/
export default function useOlderMessages({
session_id,
@@ -34,10 +33,6 @@ export default function useOlderMessages({
onLoaded,
}: Params) {
const [has_more, setHasMore] = useState(initial_has_more);
/**
* The session the thread's top belongs to, and the one before it.
*/
const [paging_session_id, setPagingSessionId] = useState<number | null>(session_id || null);
const [previous_session_id, setPreviousSessionId] = useState<number | null>(null);
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string>();
@@ -48,7 +43,6 @@ export default function useOlderMessages({
base_session.current = session_id;
setHasMore(false);
setPagingSessionId(session_id || null);
setPreviousSessionId(null);
setError(undefined);
}, [session_id]);
@@ -69,20 +63,21 @@ export default function useOlderMessages({
}) => {
base_session.current = session_id;
setHasMore(has_more);
setPagingSessionId(session_id);
setPreviousSessionId(previous_session_id || null);
setError(undefined);
},
[],
);
const load = async ({ session_id, before_id }: { session_id: number; before_id?: number | null }) => {
const loadOlder = async () => {
if (loading || !has_more || !session_id || !first_message_id) return;
setLoading(true);
setError(undefined);
const res = await postSessionApi<OlderBotMessagesData>({
path: "older-messages",
body: { session_id, before_id },
body: { session_id, before_id: first_message_id },
}).catch(() => null);
setLoading(false);
@@ -94,29 +89,15 @@ export default function useOlderMessages({
onLoaded({ messages: res.singleRes.messages });
setHasMore(res.singleRes.has_more);
setPagingSessionId(res.singleRes.session.id);
setPreviousSessionId(res.singleRes.session.previous_session_id);
};
const loadOlder = async () => {
if (loading || !has_more || !paging_session_id || !first_message_id) return;
await load({ session_id: paging_session_id, before_id: first_message_id });
};
const loadPrevious = async () => {
if (loading || has_more || !previous_session_id) return;
await load({ session_id: previous_session_id });
};
return {
has_more,
has_previous: !has_more && Boolean(previous_session_id),
previous_session_id,
loading,
error,
loadOlder,
loadPrevious,
reset,
};
}
@@ -29,6 +29,11 @@ type Params = {
* zero means the one it was waiting on ended without a message.
*/
on_open_jobs?: (params: { open_jobs: number }) => void;
/**
* The session was carried into a newer one: what the thread waited on
* is answering there, so an open conversation follows it.
*/
on_moved_to?: () => void;
};
/**
@@ -47,7 +52,8 @@ type Params = {
* face or task clear itself without a reload. The replies the session still
* has to come are handed back too: a run that ended without a word leaves
* the thread's last message the user's, so the face alone can't tell it from
* one still on its way.
* one still on its way. A session carried into a newer one is handed back
* with them, so the page that missed that push follows the answer there.
*/
export default function useReplyCatchUp({
session_id,
@@ -55,6 +61,7 @@ export default function useReplyCatchUp({
running,
last_message_id,
on_open_jobs,
on_moved_to,
}: Params) {
const last_message = useRef(Number(last_message_id) || 0);
/**
@@ -62,6 +69,7 @@ export default function useReplyCatchUp({
* the check (and the poll's timer with it).
*/
const report_open_jobs = useRef(on_open_jobs);
const report_moved_to = useRef(on_moved_to);
/**
* The open session: a read that lands after the thread moved to
* another one is dropped instead of replaying into the wrong thread.
@@ -71,6 +79,7 @@ export default function useReplyCatchUp({
last_message.current = Number(last_message_id) || 0;
open_session.current = session_id;
report_open_jobs.current = on_open_jobs;
report_moved_to.current = on_moved_to;
const check = useCallback(async () => {
if (!session_id) return;
@@ -116,6 +125,12 @@ export default function useReplyCatchUp({
if (typeof res.open_jobs == "number") {
report_open_jobs.current?.({ open_jobs: res.open_jobs });
}
/**
* The session was carried while the page wasn't looking (a phone
* that slept through the push): the new one holds the answer.
*/
if (Number(res.moved_to_session_id)) report_moved_to.current?.();
}, [session_id]);
useRefocus({ onRefocus: () => void check() });
@@ -148,4 +163,4 @@ export default function useReplyCatchUp({
window.removeEventListener("pageshow", check);
};
}, [check]);
}
}
@@ -3,6 +3,7 @@ import Row from "@moduletrace/twui/layout/Row";
import Span from "@moduletrace/twui/layout/Span";
import Stack from "@moduletrace/twui/layout/Stack";
import { AppWindow, Check } from "lucide-react";
import { twMerge } from "tailwind-merge";
import type { BUN_SQLITE_COBBLE_COMPUTERS } from "@/db/types/db";
type Props = {
@@ -11,6 +12,11 @@ type Props = {
* The computer the bot is on.
*/
current: boolean;
/**
* Whether picking another one moves the bot; without it the list is read
* alone.
*/
can_pick?: boolean;
onPick: () => void;
/**
* Opens the computer in the viewer.
@@ -22,27 +28,38 @@ type Props = {
* One computer in the header's computers modal, checked when it's the
* one the bot is on, with a button that opens it.
*/
export default function BotComputerOption({ computer, current, onPick, onOpen }: Props) {
export default function BotComputerOption({
computer,
current,
can_pick = true,
onPick,
onOpen,
}: Props) {
const name = computer.name || `Computer ${computer.id}`;
return (
<Row className="w-full gap-1! flex-nowrap items-center pr-2 hover:bg-sunken transition-colors duration-[var(--m-fast)]">
<Row
role="radio"
aria-checked={current}
tabIndex={0}
onClick={current ? undefined : onPick}
role={can_pick ? "radio" : undefined}
aria-checked={can_pick ? current : undefined}
tabIndex={can_pick ? 0 : undefined}
onClick={can_pick && !current ? onPick : undefined}
onKeyDown={(e) => {
if (!current && (e.key == "Enter" || e.key == " ")) {
if (can_pick && !current && (e.key == "Enter" || e.key == " ")) {
e.preventDefault();
onPick();
}
}}
className={`grow min-w-0 min-h-9 gap-2.5! flex-nowrap items-center px-4 py-1.5 text-ink focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ink ${
current ? "cursor-default" : "cursor-pointer"
}`}
className={twMerge(
"grow min-w-0 min-h-9 gap-2.5! flex-nowrap items-center px-4 py-1.5 text-ink cursor-default focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ink",
can_pick && !current && "cursor-pointer"
)}
>
<Check size={16} aria-hidden className={`shrink-0 ${current ? "" : "invisible"}`} />
<Check
size={16}
aria-hidden
className={twMerge("shrink-0", !current && "invisible")}
/>
<Stack className="min-w-0 gap-0!">
<Span className="text-sm leading-5 text-ink truncate w-full">
{name}
@@ -25,8 +25,9 @@ type RenderProps = {
};
/**
* The name is the header's heading either way; only a crew manager's is a
* button that opens the bot's panel.
* The name is the header's heading either way, and a button that opens the
* bot's panel for everyone who reaches it, labelled by what they may do
* there.
*/
function render({ user_type, name = "Assistant" }: RenderProps) {
const pageProps: PagePropsType = {
@@ -42,13 +43,14 @@ function render({ user_type, name = "Assistant" }: RenderProps) {
}
describe("BotPanelName", () => {
test("a member reads the name as a plain heading", () => {
test("a member's name opens the panel too, to read", () => {
const html = render({ user_type: "member" });
expect(html).toContain("<h1");
expect(html).toContain(">Assistant<");
expect(html).not.toContain("<button");
expect(html).not.toContain('aria-haspopup="dialog"');
expect(html).toContain("<button");
expect(html).toContain('aria-haspopup="dialog"');
expect(html).toContain('aria-label="About Assistant"');
});
test("a crew manager's name is a button that opens the panel", () => {
@@ -14,27 +14,20 @@ type Props = {
};
/**
* The conversation's name: the page's heading, and for super admins and
* admins a second way into the bot's panel, beside its avatar. Everyone else
* reads the name alone.
* The conversation's name: the page's heading, and a second way into the
* bot's panel beside its avatar, for everyone who can reach it.
*/
export default function BotPanelName({ bot, on_open }: Props) {
const { pageProps } = useContext(AppContext);
const name = bot.name || "This bot";
const can_edit = canManageCrew({ user_types: pageProps?.user_types });
if (!can_edit) {
return (
<H1 className="min-w-0 text-lg! leading-6! tracking-normal! font-bold text-ink truncate line-clamp-1">
{bot.name}
</H1>
);
}
const label = canManageCrew({ user_types: pageProps?.user_types })
? `Edit ${name}`
: `About ${name}`;
return (
<H1 className="min-w-0 text-lg! leading-6! tracking-normal! font-bold text-ink">
<Button
title={`Edit ${name}`}
title={label}
type="button"
variant="ghost"
color="text"
@@ -25,8 +25,9 @@ type RenderProps = {
};
/**
* The stone is the same either way; only a crew manager's opens the bot's
* panel, whether it sits in the header or beside a message.
* The stone is the same either way; it opens the bot's panel for everyone
* who reaches the bot, labelled by what they may do there, whether it sits in
* the header or beside a message.
*/
function render({ user_type, name = "Assistant" }: RenderProps) {
const pageProps: PagePropsType = {
@@ -42,12 +43,13 @@ function render({ user_type, name = "Assistant" }: RenderProps) {
}
describe("BotPanelTrigger", () => {
test("a member sees the stone alone", () => {
test("a member's stone opens the panel too, to read", () => {
const html = render({ user_type: "member" });
expect(html).toContain("<svg");
expect(html).not.toContain("<button");
expect(html).not.toContain('aria-haspopup="dialog"');
expect(html).toContain("<button");
expect(html).toContain('aria-haspopup="dialog"');
expect(html).toContain('aria-label="About Assistant"');
});
test("a crew manager's stone is a button that opens the panel", () => {
@@ -2,7 +2,6 @@
import { useContext } from "react";
import Button from "@moduletrace/twui/layout/Button";
import Stack from "@moduletrace/twui/layout/Stack";
import { twMerge } from "tailwind-merge";
import BotAvatar from "@/src/components/general/bot-avatar";
import type { BotFace } from "@/src/dict/bot-dict";
@@ -27,9 +26,10 @@ type Props = {
};
/**
* The bot's stone: opens the bot's panel to edit it, for super admins and
* admins. Everyone else sees the stone alone. It sits in the header beside
* the conversation's name and beside the bot's messages in the thread.
* The bot's stone: opens the bot's panel, which super admins and admins edit
* and everyone else reads (their own memory there is theirs to rewrite). It
* sits in the header beside the conversation's name and beside the bot's
* messages in the thread.
*/
export default function BotPanelTrigger({
bot,
@@ -39,28 +39,17 @@ export default function BotPanelTrigger({
}: Props) {
const { pageProps } = useContext(AppContext);
const name = bot.name || "This bot";
const can_edit = canManageCrew({ user_types: pageProps?.user_types });
const avatar = (
<BotAvatar
image_media_id={bot.image_media_id}
{...botStoneProps({ color: bot.color, stone: bot.stone, hue: bot.hue })}
face={(bot.face || "idle") as BotFace}
size={size}
/>
);
if (!can_edit) {
return <Stack className={twMerge("shrink-0", className)}>{avatar}</Stack>;
}
const label = canManageCrew({ user_types: pageProps?.user_types })
? `Edit ${name}`
: `About ${name}`;
return (
<Button
title={`Edit ${name}`}
title={label}
type="button"
variant="ghost"
color="text"
aria-label={`Edit ${name}`}
aria-label={label}
aria-haspopup="dialog"
onClick={on_open}
className={twMerge(
@@ -68,7 +57,16 @@ export default function BotPanelTrigger({
className,
)}
>
{avatar}
<BotAvatar
image_media_id={bot.image_media_id}
{...botStoneProps({
color: bot.color,
stone: bot.stone,
hue: bot.hue,
})}
face={(bot.face || "idle") as BotFace}
size={size}
/>
</Button>
);
}
@@ -22,9 +22,14 @@ const pageProps: PagePropsType = {
user_types: [{ user_type: "super_admin" }] as PagePropsType["user_types"],
};
function render() {
const memberPageProps: PagePropsType = {
...pageProps,
user_types: [{ user_type: "member" }] as PagePropsType["user_types"],
};
function render(props: PagePropsType = pageProps) {
return renderToString(
<AppContext.Provider value={{ pageProps } as AppContextObject}>
<AppContext.Provider value={{ pageProps: props } as AppContextObject}>
<BotPanel
bot={bot}
open={false}
@@ -48,4 +53,17 @@ describe("BotPanel", () => {
expect(html).toContain(">Tools<");
expect(html).not.toContain(">Memory<");
});
/**
* A member reads the bot and rewrites what it remembers about them, so
* the stone still opens the panel, under a title that doesn't promise
* edits they can't make.
*/
test("a member reads it, without the edit it alone can't make", () => {
const html = render(memberPageProps);
expect(html.match(/role="tab"/g)?.length).toBe(2);
expect(html).toContain(`aria-label="About Assistant"`);
expect(html).not.toContain("Edit Assistant");
});
});
@@ -20,11 +20,13 @@ import type { BUN_SQLITE_COBBLE_WORKSPACES } from "@/db/types/db";
import BotForm from "@/src/layouts/bots/(partials)/bot-form";
import { AppContext } from "@/src/pages/__root";
import canManageCrew from "@/src/utils/rbac/can-manage-crew";
import isReadOnlyUser from "@/src/utils/rbac/is-read-only-user";
import useTopModalEscape from "@/src/hooks/use-top-modal-escape";
import useBotInstructions from "../(hooks)/use-bot-instructions";
import useWorkspaceBotInstructions from "../(hooks)/use-workspace-bot-instructions";
import BotMemoryForm from "./bot-memory-form";
import BotPanelTrigger from "./bot-panel-trigger";
import BotReadOnlyBlock from "./bot-read-only-block";
import BotToolsTab from "./bot-tools-tab";
import BotUserMemory from "./bot-user-memory";
@@ -47,27 +49,36 @@ type PanelTab = "settings" | "tools";
/**
* The bot's profile (picture, name, job, colour, instructions), what it keeps
* in mind and what it works with (computer, tools, knowledgebases) to edit,
* sliding in from the right over the conversation, for super admins and
* admins. The avatar and the name beside it open it, and so does a swipe from
* the right on a phone (`BotPanelOpenEvent`, sent by the layout, so a page
* without a conversation has nobody listening). The tab's data loads when it
* opens, and Escape, the backdrop or the X closes it.
* in mind and what it works with (computer, tools, knowledgebases), sliding in
* from the right over the conversation. Super admins and admins edit it; every
* other user reads its job and instructions and rewrites what it remembers
* about them. The avatar and the name beside it open it, and so does a swipe
* from the right on a phone (`BotPanelOpenEvent`, sent by the layout, so a
* page without a conversation has nobody listening). The tab's data loads when
* it opens, and Escape, the backdrop or the X closes it.
*/
export default function BotPanel({ bot, workspace, open, on_open, on_close }: Props) {
export default function BotPanel({
bot,
workspace,
open,
on_open,
on_close,
}: Props) {
const { pageProps } = useContext(AppContext);
const name = bot.name || "This bot";
const can_edit = canManageCrew({ user_types: pageProps?.user_types });
const may_write = !isReadOnlyUser({ user_types: pageProps?.user_types });
const title = can_edit ? `Edit ${name}` : `About ${name}`;
const [tab, setTab] = useState<PanelTab>("settings");
const workspace_id = Number(workspace?.id) || 0;
const { system_prompt, memory, user_memory, error } = useBotInstructions({
bot_id: Number(bot.id) || 0,
enabled: open && can_edit,
enabled: open,
});
const workspace_instructions = useWorkspaceBotInstructions({
workspace_id,
bot_id: Number(bot.id) || 0,
enabled: open && can_edit && Boolean(workspace_id) && tab == "settings",
enabled: open && Boolean(workspace_id) && tab == "settings",
});
const memory_ready =
system_prompt != undefined &&
@@ -79,22 +90,11 @@ export default function BotPanel({ bot, workspace, open, on_open, on_close }: Pr
useTopModalEscape({ onClose: on_close, enabled: open });
useEffect(() => {
if (!can_edit) return;
const openPanel = () => on_open();
window.addEventListener(BotPanelOpenEvent, openPanel);
return () => window.removeEventListener(BotPanelOpenEvent, openPanel);
}, [can_edit, on_open]);
/**
* A swipe from the right is a request for the panel, but a bot that
* cannot be edited keeps the avatar plain: a slide-over holding nothing
* would be worse than nothing happening.
*/
if (!can_edit) {
return <BotPanelTrigger bot={bot} on_open={() => {}} />;
}
}, [on_open]);
return (
<>
@@ -103,19 +103,23 @@ export default function BotPanel({ bot, workspace, open, on_open, on_close }: Pr
side="right"
open={open}
onClose={on_close}
label={`Edit ${name}`}
label={title}
>
<Row className="shrink-0 gap-3! flex-nowrap items-center px-4 py-3 border-0 border-b border-solid border-hairline">
<Stack className="shrink-0">
<BotAvatar
image_media_id={bot.image_media_id}
{...botStoneProps({ color: bot.color, stone: bot.stone, hue: bot.hue })}
{...botStoneProps({
color: bot.color,
stone: bot.stone,
hue: bot.hue,
})}
face={(bot.face || "idle") as BotFace}
size={35}
/>
</Stack>
<H2 className="min-w-0 grow text-lg! leading-6! tracking-normal! font-bold text-ink truncate">
{`Edit ${name}`}
{title}
</H2>
<Button
title="Close"
@@ -131,64 +135,144 @@ export default function BotPanel({ bot, workspace, open, on_open, on_close }: Pr
</Row>
<Row
role="tablist"
aria-label={`Edit ${name}`}
aria-label={title}
className="shrink-0 gap-1! flex-nowrap items-center px-3 py-2 border-0 border-b border-solid border-hairline"
>
<TabButton title="Settings" active={tab == "settings"} onPick={() => setTab("settings")} />
<TabButton title="Tools" active={tab == "tools"} onPick={() => setTab("tools")} />
<TabButton
title="Settings"
active={tab == "settings"}
onPick={() => setTab("settings")}
/>
<TabButton
title="Tools"
active={tab == "tools"}
onPick={() => setTab("tools")}
/>
</Row>
<Stack className="grow min-h-0 overflow-y-auto gap-4! items-stretch px-4 pt-4 pb-6 [&>*]:shrink-0">
{open && tab == "settings" ? (
<>
<Span className="text-[13px] leading-[18px] text-ink-secondary">
{bot.kind == "coordinator"
? "The coordinator keeps its name. Give it a picture, or change its core instructions."
: `${name}'s core instructions apply everywhere. What it does in one workspace is under Instructions here in the menu of its conversation there.`}
</Span>
{system_prompt != undefined ? (
<>
<BotForm
bot={{ ...bot, system_prompt }}
onCancel={on_close}
/>
<Divider className="my-2 border-hairline dark:border-hairline" />
<Span className="text-[13px] leading-[18px] text-ink-secondary">
{`What ${name} keeps in mind, and can add to itself as it works.`}
</Span>
{memory_ready ? (
<>
<BotMemoryForm
bot_id={Number(bot.id) || 0}
bot_name={name}
memory={memory || ""}
workspace_id={workspace_id || undefined}
workspace_name={workspace?.name}
workspace_memory={workspace_instructions.instructions?.memory || ""}
onCancel={on_close}
/>
<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}
</Span>
) : (
<Stack className="w-full py-10 items-center">
<Loading />
</Stack>
)}
</>
) : error ? (
<Span className="py-6 text-[13px] leading-[18px] text-ink-secondary">
{error}
can_edit ? (
<>
<Span className="text-[13px] leading-[18px] text-ink-secondary">
{bot.kind == "coordinator"
? "The coordinator keeps its name. Give it a picture, or change its core instructions."
: `${name}'s core instructions apply everywhere. What it does in one workspace is under Instructions here in the menu of its conversation there.`}
</Span>
) : (
<Stack className="w-full py-10 items-center">
<Loading />
</Stack>
)}
</>
{system_prompt != undefined ? (
<>
<BotForm
bot={{ ...bot, system_prompt }}
onCancel={on_close}
/>
<Divider className="my-2 border-hairline dark:border-hairline" />
<Span className="text-[13px] leading-[18px] text-ink-secondary">
{`What ${name} keeps in mind, and can add to itself as it works.`}
</Span>
{memory_ready ? (
<>
<BotMemoryForm
bot_id={Number(bot.id) || 0}
bot_name={name}
memory={memory || ""}
workspace_id={
workspace_id || undefined
}
workspace_name={
workspace?.name
}
workspace_memory={
workspace_instructions
.instructions
?.memory || ""
}
onCancel={on_close}
/>
<Divider className="my-2 border-hairline dark:border-hairline" />
<BotUserMemory
bot_id={Number(bot.id) || 0}
bot_name={name}
memory={user_memory || ""}
can_edit={may_write}
onCancel={on_close}
/>
</>
) : loaded_error ? (
<Span className="py-6 text-[13px] leading-[18px] text-ink-secondary">
{loaded_error}
</Span>
) : (
<Stack className="w-full py-10 items-center">
<Loading />
</Stack>
)}
</>
) : error ? (
<Span className="py-6 text-[13px] leading-[18px] text-ink-secondary">
{error}
</Span>
) : (
<Stack className="w-full py-10 items-center">
<Loading />
</Stack>
)}
</>
) : (
<>
<Span className="text-[13px] leading-[18px] text-ink-secondary">
{`What ${name} is for, the instructions it follows and what it remembers.`}
</Span>
{bot.role ? (
<Span className="text-[13px] leading-[18px] text-ink">
{bot.role}
</Span>
) : null}
{memory_ready ? (
<>
<BotReadOnlyBlock
title="Instructions"
content={system_prompt || ""}
className="h-52"
/>
<Divider className="my-2 border-hairline dark:border-hairline" />
<BotReadOnlyBlock
title="Memory"
content={memory || ""}
className="h-52"
/>
{workspace_id ? (
<>
<Divider className="my-2 border-hairline dark:border-hairline" />
<BotReadOnlyBlock
title={`Memory in ${workspace?.name || "this workspace"}`}
content={
workspace_instructions
.instructions
?.memory || ""
}
className="h-40"
/>
</>
) : null}
<Divider className="my-2 border-hairline dark:border-hairline" />
<BotUserMemory
bot_id={Number(bot.id) || 0}
bot_name={name}
memory={user_memory || ""}
can_edit={may_write}
onCancel={on_close}
/>
</>
) : loaded_error ? (
<Span className="py-6 text-[13px] leading-[18px] text-ink-secondary">
{loaded_error}
</Span>
) : (
<Stack className="w-full py-10 items-center">
<Loading />
</Stack>
)}
</>
)
) : null}
{open && tab == "tools" ? (
<BotToolsTab
@@ -196,6 +280,9 @@ export default function BotPanel({ bot, workspace, open, on_open, on_close }: Pr
workspace_id={workspace_id || null}
initial={pageProps?.bot_extensions}
has_browsers={Boolean(pageProps?.has_browsers)}
can_switch_computer={
may_write && (!workspace_id || can_edit)
}
open={open && tab == "tools"}
/>
) : null}
@@ -203,4 +290,4 @@ export default function BotPanel({ bot, workspace, open, on_open, on_close }: Pr
</SidePanel>
</>
);
}
}
@@ -0,0 +1,25 @@
import CodeEditor from "@/src/components/general/code-editor";
type BotReadOnlyBlockProps = {
title: string;
content: string;
className?: string;
};
/** A block of a bot's own text its panel shows a user read-only. */
export default function BotReadOnlyBlock({
title,
content,
className,
}: BotReadOnlyBlockProps) {
return (
<CodeEditor
title={title}
content={content || "Nothing yet."}
mode="markdown"
className={className}
readOnly
onChange={() => {}}
/>
);
}
@@ -24,6 +24,12 @@ type Props = {
* nothing to pick.
*/
has_browsers?: boolean;
/**
* Whether the viewer may move the bot to another of its computers. Any
* user who reaches it can, except a workspace's default computer, which
* is the crew's.
*/
can_switch_computer?: boolean;
/**
* Whether the tab is on show, so its connectors are read then and its
* computer switches show.
@@ -32,16 +38,18 @@ type Props = {
};
/**
* The bot panel's third tab: where it works and what it can use there - its
* The bot panel's tools tab: where it works and what it can use there - its
* computer, the MCP servers, tools and skills it was given (the apps its
* connectors reach for you among them), its knowledgebases, and which of
* your browsers it acts as you in.
* your browsers it acts as you in. Read-only for a user who cannot manage the
* crew: the lists show, adding and removing them does not.
*/
export default function BotToolsTab({
bot,
workspace_id,
initial,
has_browsers,
can_switch_computer = false,
open,
}: Props) {
const bot_name = bot.name || "this bot";
@@ -82,8 +90,12 @@ export default function BotToolsTab({
>
{computers.length ? (
<Stack
role="radiogroup"
aria-label={`${bot_name}'s computers`}
role={can_switch_computer ? "radiogroup" : undefined}
aria-label={
can_switch_computer
? `${bot_name}'s computers`
: undefined
}
className="w-full mt-2 py-1 gap-0! items-stretch rounded-default border border-solid border-hairline bg-surface"
>
{computers.map((computer, index) => (
@@ -91,6 +103,7 @@ export default function BotToolsTab({
key={computer.id}
computer={computer}
current={index == 0}
can_pick={can_switch_computer}
onPick={async () => {
await switchComputer({
computer_id: computer.id || 0,
@@ -1,34 +1,109 @@
import { useState } from "react";
import Form from "@moduletrace/twui/form/Form";
import Span from "@moduletrace/twui/layout/Span";
import CodeEditor from "@/src/components/general/code-editor";
import postAdminApi from "@/src/layouts/bots/(functions)/post-admin-api";
import AddFormActions from "@/src/layouts/bots/(partials)/add-form-actions";
import BotReadOnlyBlock from "./bot-read-only-block";
type Props = {
bot_id: number;
bot_name: string;
/**
* What the bot has saved about the user reading the panel; empty until
* it saved anything.
*/
memory: string;
/**
* A read-only user reads it alone; their own memory needs no admin.
*/
can_edit?: boolean;
onCancel?: () => void;
};
/**
* 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.
* in its panel: the bot writes it as it works, and the user rewrites it here.
* It shapes how the bot works with them, never what it does.
*/
export default function BotUserMemory({ bot_name, memory }: Props) {
export default function BotUserMemory({
bot_id,
bot_name,
memory,
can_edit,
onCancel,
}: Props) {
const [text, setText] = useState(memory);
const [loading, setLoading] = useState(false);
const [saved, setSaved] = useState(false);
const [error, setError] = useState<string>();
const submit = async () => {
if (loading) return;
setLoading(true);
setError(undefined);
setSaved(false);
try {
const res = await postAdminApi({
path: "bots/update-user-memory",
body: { bot_id, memory: text },
});
if (res.success) {
setSaved(true);
} else {
setError(res.msg || "Couldn't save its memory.");
}
} catch {
setError("Couldn't save its memory.");
} finally {
setLoading(false);
}
};
const description = `What ${bot_name} remembers about you, which only shapes how it works with you.`;
if (!can_edit) {
return (
<>
<Span className="text-[13px] leading-[18px] text-ink-secondary">
{description}
</Span>
<BotReadOnlyBlock
title="About you"
content={memory}
className="h-32"
/>
</>
);
}
return (
<>
<Form onSubmit={submit} className="w-full gap-4! items-stretch">
<Span className="text-[13px] leading-[18px] text-ink-secondary">
{`What ${bot_name} remembers about you, which only shapes how it works with you.`}
{description}
</Span>
<CodeEditor
title="About you"
content={memory || "Nothing yet."}
content={memory}
mode="markdown"
placeholder="What it should keep in mind about you..."
info="Markdown, replaced whole. Only this bot, and only when it works with you."
className="h-32"
readOnly
onChange={() => {}}
onChange={(value) => {
setText(value);
setSaved(false);
}}
/>
</>
<AddFormActions
submit_label="Save"
loading={loading}
error={error}
notice={saved ? "Saved." : undefined}
onCancel={onCancel}
/>
</Form>
);
}
}
@@ -0,0 +1,35 @@
import Stack from "@moduletrace/twui/layout/Stack";
import type { ComposerCommand } from "../(data)/composer-commands";
import ComposerCommandOption from "./composer-command-option";
type Props = {
commands: ComposerCommand[];
index: number;
onPick: (command: ComposerCommand) => void;
};
/**
* The slash commands matching what's typed, just above the composer's
* input. Up and Down move, Enter runs the highlighted one; a click fills
* the input with it.
*/
export default function ComposerCommandList({ commands, index, onPick }: Props) {
return (
<Stack
role="listbox"
aria-label="Commands"
className="w-full max-w-container mx-auto gap-0.5! items-stretch px-3 md:px-6 pt-3"
>
<Stack className="gap-0.5! items-stretch p-1 rounded-default border border-solid border-hairline bg-surface shadow-popover">
{commands.map((command, command_index) => (
<ComposerCommandOption
key={command.name}
command={command}
active={command_index == index}
onPick={onPick}
/>
))}
</Stack>
</Stack>
);
}

Some files were not shown because too many files have changed in this diff Show More