Compare commits

...
19 Commits
Author SHA1 Message Date
tben 7bc9ab93ad Bump version to 0.28.13
CI / check (push) Waiting to run
Release image / image (release) Waiting to run
Release image / computer-image (release) Waiting to run
2026-11-26 09:39:18 +01:00
tben 0eee6781c4 Tell a refused card from a failed send, and stop losing what a run did
The harness audit's tier 1 and tier 2, from the Model Tester's runs.

A card the tool refused is not send_reply failing. runTextLoop stamped
replyClosingFailedNote whenever any closing call failed, so job 699 spent three
turns re-drafting an answer that had already shipped, beside a trace that blamed
the wrong tool. It now splits the failures: a refused card gets a new
replyCardFailedNote naming the card, and only a failed send_reply gets the old
note. suggest_next_steps states its caps in the schema (the 120-character step
limit it enforces), the wrap-up saving turn is traced, and the closing slice no
longer reads the whole run's tool history when a turn called nothing.

Providers tell the truth now: an error body carried by a 200 goes through
toHarnessError, so an oversized request is fatal with the context-window advice
and a dead key benches the provider (52 such rows, one task limping for 18
minutes); a 405 benches like a 404; a crash in an adapter writes a failed-call
row before it goes up; the error reported is a provider-wide or fatal one, not
simply the last. A pinned model that can't serve the harness says so instead of
answering on an automatic pick, an image or video call with references hands
over to a generation model only while that harness's fallback is on, and an
empty answer from a thinking model is named for what it was.

Nothing is promised that a run doesn't carry: ComputerFilesNote and the chat
take-over line stay out of a run without a computer, TaskRunNote names ask_user
only to a run that may ask, load_tools says when a name is already inline, and
an unknown browser tool is told its slug when the run has one. An interim crew
update goes through the run's redaction: it lands in another bot's conversation,
where a raw env value would sit forever.

The queue and plans hold their record: a job locks with the pid as well as its
family, so two processes can no longer renew each other's locks (startup still
releases the family's rows); stopping or cancelling a plan's step pauses it the
way a failure does; a step keeps the run that finished it, so a step whose report
never went out is put back instead of skipped; a job that failed, retried and
then answered no longer reads completed beside its old error; the stopped line
follows a conversation that carried on; and a finished row with no timestamp is
pruned at all. The model picker warns when a text model's capabilities were
guessed from its name, which is how a vision model was pinned as a worker's text
model and every reply ended as a draft.
2026-11-26 09:38:35 +01:00
tben 01d6cffa8d Bump version to 0.28.12
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
2026-11-26 06:04:31 +01:00
tben 8897f0b23f Let a knowledgebase document be read, and open its original
Clicking a document reads it over the list: written text as markdown, a file's extracted text as it is, cut at KnowledgebaseTextMaxChars and flagged when there is more. A file document's Open original loads its uploaded media row in the existing file preview, which crew managers now reach through grabKnowledgebaseDocumentMedia.

The bot composer's knowledgebase rows get the same documents list, read-only.
2026-11-26 06:04:26 +01:00
tben 2dc6972de4 Bump version to 0.28.11
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
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
112 changed files with 3080 additions and 645 deletions
+10 -10
View File
File diff suppressed because one or more lines are too long
+4
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"],
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "cobble",
"version": "0.28.7",
"version": "0.28.13",
"module": "index.ts",
"type": "module",
"private": true,
+3 -2
View File
@@ -9,7 +9,8 @@ import processBotJob from "./process-bot-job";
import reportLostBotJobs from "./report-lost-bot-jobs";
import { setBotsQueueWaker } from "./wake-bots-queue";
const worker = AppData.BotQueueWorker;
/** Per-process lock id: the family plus this process's pid. */
const worker = `${AppData.BotQueueWorker}-${process.pid}`;
const running = { task: 0, reply: 0 };
let polling = false;
let timer: ReturnType<typeof setTimeout> | undefined;
@@ -41,7 +42,7 @@ export default async function botsQueue() {
* it fails, polling still starts, and the lock timeout releases them.
*/
try {
const released = await releaseWorkerBotJobs({ worker });
const released = await releaseWorkerBotJobs({ family: AppData.BotQueueWorker });
if (released) {
bunext.bunextLog.info(`Bots queue: released ${released} cut-off job(s)`);
+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.
+12 -2
View File
@@ -135,6 +135,7 @@ export default async function runBotReply({
user_id,
job,
signal,
stop_signal,
report,
trace,
}: Params): Promise<BotJobOutcome> {
@@ -546,6 +547,7 @@ export default async function runBotReply({
user_id,
session_id: Number(session_id),
ask_id: ask_id_for_updates,
redact: redact_reply,
}),
]
: []),
@@ -617,6 +619,7 @@ export default async function runBotReply({
bot_id: bot.id,
session_id,
workspace_id,
job_id: job.id,
on_step: on_plan_step,
/**
* A plan nobody approved yet needs the user, so
@@ -668,12 +671,18 @@ export default async function runBotReply({
prompt,
carry_over,
long_session_note,
chatReplyNote({ bot_id: bot.id }),
chatReplyNote({ bot_id: bot.id, can_take_over: computers.length > 0 }),
plan_mode ? PlanModeNote : "",
is_retry ? RerunReplyNote : "",
retry_failure ? RetryFailureNote({ reason: retry_failure.reason }) : "",
botFilesNote({ bot_id: bot.id }),
ComputerFilesNote({ computer_id: computers[0]?.id || 0, dirs, can_import: computers.length > 0 }),
/**
* Only with a computer: the note is about the run's folders and
* browser there, and a reply without one has neither tool.
*/
computers.length
? ComputerFilesNote({ computer_id: computers[0]?.id || 0, dirs, can_import: true })
: "",
TasksNote,
TaskReminderNote,
can_hand_over ? HandOverTaskNote : "",
@@ -731,6 +740,7 @@ export default async function runBotReply({
bot_id: bot.id,
workspace_id,
signal,
stop_signal,
onStep: report,
trace,
incoming,
+14 -22
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> {
@@ -339,6 +339,7 @@ export default async function runBotTask({
bot_id: bot.id,
session_id: session_id!,
workspace_id,
job_id: job.id,
on_step: true,
onPlan: ({ ref }) => shown.push(ref),
})
@@ -354,6 +355,7 @@ export default async function runBotTask({
user_id,
session_id: Number(session_id),
ask_id: Number(params.ask_id),
redact: redact_text,
}),
]
: []),
@@ -489,22 +491,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({
@@ -654,15 +640,19 @@ export default async function runBotTask({
const system = [
prompt,
carry_over,
TaskRunNote,
TaskRunNote({ can_ask }),
steps_note,
scheduled ? ScheduledRunNote : "",
scheduled ? ScheduledPlanNote : "",
hooked ? HookRunNote : "",
install_request_id ? InstallRequestNote : "",
Number(params.ask_id) ? AskTaskRunNote : "",
botFilesNote({ bot_id: bot.id }),
ComputerFilesNote({ computer_id: job.computer_id || 0, dirs }),
/**
* Only when the run has a computer: the note describes its folders
* and its browser, and a run with none has no computer tools at all
* (the closing note below is what tells it so).
*/
computer ? ComputerFilesNote({ computer_id: job.computer_id || 0, dirs }) : "",
named_files_note,
TasksNote,
/**
@@ -721,9 +711,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 +779,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
@@ -10,7 +10,12 @@ export default async function pruneBotsQueue() {
Date.now() - AppData.BotQueueRetentionDays * 24 * 60 * 60 * 1000;
const res = await BunSQLite.sql({
sql: `DELETE FROM bots_queue WHERE status IN ('completed', 'failed') AND finished_at IS NOT NULL AND finished_at < ? RETURNING id`,
/**
* `updated_at` stands in for a row finished without a timestamp (an
* older build, or a writer that set the status directly): without it
* such a row sits in the queue for ever.
*/
sql: `DELETE FROM bots_queue WHERE status IN ('completed', 'failed') AND COALESCE(finished_at, updated_at) < ? RETURNING id`,
values: [cutoff],
});
+12 -2
View File
@@ -389,8 +389,12 @@ export const AppData = {
*/
ScheduledRunRetryMs: 5 * 60 * 1000,
/**
* The queue handler's lock name. Stable across restarts, so on startup
* it can release the jobs it was running when the process stopped.
* The queue handler's lock family. The id a handler locks with adds the
* process's pid (`src/bots-queue/index.ts`), so two processes (a dev
* server and the app, or two replicas) can never renew each other's
* locks: a heartbeat then fails, and the handler that lost the job stops.
* Startup still releases the family's jobs, so a restart doesn't leave
* its own cut-off runs waiting out the lock timeout.
*/
BotQueueWorker: "main",
BotQueuePollMs: 3000,
@@ -1043,6 +1047,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
+18 -13
View File
@@ -23,7 +23,6 @@ import {
PlanWaitingNote,
PlanActiveNote,
PlanPausedNote,
ScheduledPlanNote,
RetryFailureNote,
} from "./harness-prompts";
import computerRunDirs from "@/src/utils/computer-work-dirs";
@@ -232,10 +231,13 @@ describe("wrapUpWorktreeNote", () => {
});
describe("TaskRunNote", () => {
const attended = TaskRunNote({ can_ask: true });
const unattended = TaskRunNote({ can_ask: false });
test("says a brief can be wrong about the tree, and that handing on finishes the task", () => {
expect(TaskRunNote).toContain("A brief can be wrong about the repository");
expect(TaskRunNote).toContain("the tree wins");
expect(TaskRunNote).toContain("start_task with separate for the rest");
expect(attended).toContain("A brief can be wrong about the repository");
expect(attended).toContain("the tree wins");
expect(attended).toContain("start_task with separate for the rest");
});
test("gives the plan permission to hand work on", () => {
@@ -243,11 +245,17 @@ describe("TaskRunNote", () => {
});
test("says the user's own words win over the brief, and the way they named is the way it is done", () => {
expect(TaskRunNote).toContain("the run opens with their own words");
expect(TaskRunNote).toContain("the brief after it is your summary of it");
expect(TaskRunNote).toContain("the way they named (a tool, app, service or path) is the way it is done");
expect(TaskRunNote).toContain("never reach the same result some other way without asking first");
expect(TaskRunNote).not.toContain("\u2014");
expect(attended).toContain("the run opens with their own words");
expect(attended).toContain("the brief after it is your summary of it");
expect(attended).toContain("the way they named (a tool, app, service or path) is the way it is done");
expect(attended).toContain("never reach the same result some other way without asking first");
expect(attended).not.toContain("\u2014");
});
test("names ask_user only for a run the user watches", () => {
expect(attended).toContain("ask_user");
expect(attended).toContain("ask_user_to_take_over");
expect(unattended).not.toContain("ask_user");
});
});
@@ -355,8 +363,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");
});
});
+58 -14
View File
@@ -77,7 +77,13 @@ function ownFolderRef({ bot_id }: { bot_id: number | string }) {
* Added to a bot's prompt when it answers the user in chat. `bot_id` is the
* bot itself: the examples it reads are its own refs.
*/
export const chatReplyNote = ({ bot_id }: { bot_id: number | string }) => `# Replying in chat
export const chatReplyNote = ({
bot_id,
can_take_over = true,
}: {
bot_id: number | string;
can_take_over?: boolean;
}) => `# Replying in chat
You are chatting with the user. Answer their latest messages directly and briefly, in markdown.
@@ -87,8 +93,11 @@ You are chatting with the user. Answer their latest messages directly and briefl
- send_reply({status:"working", work:{title, instructions, computer_id?}}) for work that takes more than a moment, or anything on a computer (running commands, editing files, browsing). The app queues the run before your message goes out; a task you start is your own work, so never say you handed it to anyone else. Its result is posted here when it's done.
- send_reply({status:"blocked"}) when the work can't go on; say why in the message.
- When a message mixes both, answer the quick parts and queue the rest with status "working" and work.
- When only the user can do something on a computer (log in, solve a captcha, enter a code), ask them to take over with ask_user_to_take_over and say exactly what to do. They'll tell you when they hand it back; then carry on.
- When the user tells you something worth keeping, save it with update_memory: about them in your memory of this user, never in your core memory, which every user you work for shares. When they correct how you work for everyone, update your instructions with update_instructions; a correction that's only their preference goes in your memory of them.
${
can_take_over
? `- When only the user can do something on a computer (log in, solve a captcha, enter a code), ask them to take over with ask_user_to_take_over and say exactly what to do. They'll tell you when they hand it back; then carry on.\n`
: ""
}- When the user tells you something worth keeping, save it with update_memory: about them in your memory of this user, never in your core memory, which every user you work for shares. When they correct how you work for everyone, update your instructions with update_instructions; a correction that's only their preference goes in your memory of them.
- An app record saying the user reacted to one of your messages is their feedback on it: 👍, ❤️ and 🎉 mean they liked it, 👎 that they didn't; 😂, 😮 and 😢 are how it made them feel, not a verdict. When reactions show a preference that lasts (length, format, tone, what to include or leave out), save it in your memory of this user with update_memory (scope "user", in a workspace too). One reaction to one answer isn't a preference yet, so don't save it, and don't save what your memory already says. Bring a reaction up only when it helps: after a 👎 on your last answer with no word about why, you can ask in one short question what to change.
- To add a worker to the crew, use create_bot once the user has asked for it or agreed, and add_bot_to_workspace to place it. A bot exists only when create_bot made it: never describe one as if it did, and never write it into a workspace's context.
- Never claim you did something you didn't do.
@@ -129,6 +138,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
@@ -396,10 +417,18 @@ export const workspaceAdminsLine = ({ admins }: { admins: { id?: number | "" }[]
/**
* Added to a bot's prompt when it works through a queued task.
*
* `can_ask` decides whether it may name `ask_user`: a routine, a hook call or
* a hidden session has no card the user would see (the tool is taken away
* there), so the note must not order a call that isn't offered.
*/
export const TaskRunNote = `# Working on a task
export const TaskRunNote = ({ can_ask }: { can_ask: boolean }) => `# Working on a task
You are working through a task on your own; the user isn't watching. Use your tools until the task is done, then answer with the report for the user: what you did, what you found, and anything left for them. The report is posted straight to them, so write to them ("you"), never about them by name or as "the user". End it with the next step you'd suggest: offered with ask_user when a real choice or new direction remains for the user, otherwise state the outcome plainly without ask_user. Keep the report short and in markdown.
You are working through a task on your own; the user isn't watching. Use your tools until the task is done, then answer with the report for the user: what you did, what you found, and anything left for them. The report is posted straight to them, so write to them ("you"), never about them by name or as "the user". End it with the next step you'd suggest${
can_ask
? `: offered with ask_user when a real choice or new direction remains for the user, otherwise state the outcome plainly without ask_user`
: `, or state the outcome plainly`
}. Keep the report short and in markdown.
When they asked for this work in their chat, the run opens with their own words: that message is the request itself, and the brief after it is your summary of it. Where the two disagree the words win, and the way they named (a tool, app, service or path) is the way it is done. If that way can't work, the report says what blocked it and what the alternatives are; never reach the same result some other way without asking first.
@@ -411,7 +440,11 @@ Work larger than one run is handed on, not half-done: start_task with separate f
The report ends with send_reply and the text beside it: status "done" when nothing follows it, "working" when you handed work on and it is still running, or "blocked" when it can't finish. A report without it is a draft and is never sent.
If you're blocked on something only the user can give you, stop and ask for it in the report. The same goes for being stuck: when several different tries at the same thing (a search, a page, a fix) leave you no closer, stop there and report what you tried and what you need, rather than spending the run on more of the same. If they need to do it on the computer themselves (log in, a captcha, a code), call ask_user_to_take_over first.`;
If you're blocked on something only the user can give you, stop and ask for it in the report. The same goes for being stuck: when several different tries at the same thing (a search, a page, a fix) leave you no closer, stop there and report what you tried and what you need, rather than spending the run on more of the same.${
can_ask
? ` If they need to do it on the computer themselves (log in, a captcha, a code), call ask_user_to_take_over first.`
: ""
}`;
/**
* Told to a task run with what the user wrote in its conversation since
@@ -561,6 +594,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
@@ -603,6 +645,16 @@ export const replyClosingMixedNote = `send_reply's turn can also call suggest_ne
*/
export const replyClosingFailedNote = `send_reply did not go through (its error is above), so the message was not sent. Status "working" needs work queued in the call or a run you already started; fix that and call send_reply again with the message, or use status "done" or "blocked".`;
/**
* Told when `send_reply` went through and only the card beside it was refused
* (a step over its length cap, an argument the tool rejected): the message is
* kept, so the model must not rewrite it. Naming send_reply as the failed
* call here spent three turns of one run re-writing an answer that had already
* shipped, and logged the failure against the wrong tool.
*/
export const replyCardFailedNote = ({ tools }: { tools: string[] }) =>
`send_reply went through and your message is kept. The card call did not: ${tools.join(" and ")} refused (its error is above). Fix those arguments, or drop the card, and call send_reply again in the same turn with the same message.`;
/**
* Put under an answer the review kept faulting once its unsupported parts
* were taken out (`repairAnswerText`): the user is told part of it is gone
@@ -1134,11 +1186,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.`;
@@ -16,6 +16,12 @@ type Params = {
* What the step produced, in a line or two.
*/
summary: string;
/**
* The run finishing it, kept on the step so a report that never went out
* (a refused answer, a stop) puts the step back instead of leaving the
* card offering the next one over a step nobody delivered.
*/
job_id?: number | string;
};
/**
@@ -27,7 +33,7 @@ type Params = {
* time: a plan waiting on the user can't be worked, and neither can one
* that's paused, ended, or has nothing left.
*/
export default async function completeBotPlanStep({ plan_id, session_id, summary }: Params) {
export default async function completeBotPlanStep({ plan_id, session_id, summary, job_id }: Params) {
const row = await grabBotPlan({ plan_id });
if (Number(row.session_id) != Number(session_id)) {
@@ -58,7 +64,12 @@ export default async function completeBotPlanStep({ plan_id, session_id, summary
throw new AppError(`Every step of plan #${row.id} is already done.`);
}
steps[index] = { text: working.text, state: "done", note };
steps[index] = {
text: working.text,
state: "done",
note,
...(Number(job_id) ? { done_job_id: Number(job_id) } : {}),
};
const next = currentPlanStepIndex({ steps });
const now = Date.now();
@@ -0,0 +1,45 @@
import { describe, expect, test } from "bun:test";
import parseBotPlanSteps from "@/src/utils/parse-bot-plan-steps";
import { reopenWorkedPlanStep } from "./pause-failed-plan-step";
/**
* A run that finished a plan step and then never delivered its report must
* leave that step to work again, not a card showing it done and offering the
* step after it.
*/
describe("reopenWorkedPlanStep", () => {
const steps = parseBotPlanSteps({
text: JSON.stringify([
{ text: "Collect", state: "done", note: "14 pages", done_job_id: 700 },
{ text: "Score", state: "done", note: "8 kept", done_job_id: 701 },
{ text: "Write", state: "pending", note: "" },
]),
});
test("puts back the step that run finished, with its note kept", () => {
const { steps: reopened, reopened: changed } = reopenWorkedPlanStep({ steps, job_id: 701 });
expect(changed).toBe(true);
expect(reopened.map((step) => step.state)).toEqual(["done", "pending", "pending"]);
expect(reopened[1]?.note).toBe("8 kept");
/**
* The step before it, delivered by another run, is untouched.
*/
expect(reopened[0]).toEqual(steps[0]);
});
test("a run that finished no step changes nothing", () => {
const { steps: same, reopened } = reopenWorkedPlanStep({ steps, job_id: 999 });
expect(reopened).toBe(false);
expect(same).toBe(steps);
});
test("a step written before the run was recorded is left done", () => {
const older = parseBotPlanSteps({ text: JSON.stringify([{ text: "Collect", state: "done", note: "14" }]) });
const { steps: same, reopened } = reopenWorkedPlanStep({ steps: older, job_id: 700 });
expect(reopened).toBe(false);
expect(same.map((step) => step.state)).toEqual(["done"]);
});
});
@@ -1,19 +1,45 @@
import BunSQLite from "@moduletrace/bun-sqlite";
import type { BUN_SQLITE_COBBLE_BOTS_QUEUE } from "@/db/types/db";
import parseJobJson from "@/src/bots-queue/parse-job-json";
import parseBotPlanSteps, { type BotPlanStepRecord } from "@/src/utils/parse-bot-plan-steps";
import grabBotPlan from "./grab-bot-plan";
type Params = {
job: BUN_SQLITE_COBBLE_BOTS_QUEUE;
};
/**
* The step one run finished, put back to pending (its note kept: the retry
* reads what the earlier attempt made). `reopened` says whether that run had
* finished a step at all, which is what lets a plan read `done` come back
* when the run that ended it never delivered its report.
*/
export function reopenWorkedPlanStep({
steps,
job_id,
}: {
steps: BotPlanStepRecord[];
job_id: number;
}): { steps: BotPlanStepRecord[]; reopened: boolean } {
const worked = steps.findIndex((step) => step.done_job_id === job_id);
const step = worked < 0 ? undefined : steps[worked];
if (!step) return { steps, reopened: false };
const next = [...steps];
next[worked] = { ...step, state: "pending" };
return { steps: next, reopened: true };
}
/**
* Pauses the plan a failed run was working a step of: nothing would ever
* advance it, so it would show that step in progress forever and every later
* reply in that conversation would be told the plan is under way and may not
* move it. Paused, the card offers the step again (Resume queues it as it
* stands). The step itself is left for that retry. A plan the user paused or
* ended meanwhile, or one of another conversation, is left alone.
* stands). A step this run finished is put back with it, since the report that
* delivered it never went out. A plan the user paused or ended meanwhile, or
* one of another conversation, is left alone.
*/
export default async function pauseFailedPlanStep({ job }: Params) {
const plan_id = Number(parseJobJson({ text: job.params })?.plan_id) || 0;
@@ -22,14 +48,30 @@ export default async function pauseFailedPlanStep({ job }: Params) {
const row = await grabBotPlan({ plan_id }).catch(() => null);
if (!row?.id || row.status != "active") return null;
if (!row?.id) return null;
if (Number(row.session_id) != Number(job.session_id)) return null;
/**
* A step this run marked done is put back before the plan pauses: its
* report never reached the user (a refused answer, a stop, a lost run),
* so the card must not show it delivered or offer the step after it. A
* plan the user ended meanwhile is left alone; `done` is reopened only
* when this very run was the one that finished the last step.
*/
const { steps, reopened } = reopenWorkedPlanStep({
steps: parseBotPlanSteps({ text: row.steps }),
job_id: Number(job.id),
});
if (row.status != "active" && !(row.status == "done" && reopened)) return null;
const now = Date.now();
const res = await BunSQLite.sql<{ id: number }>({
sql: `UPDATE bot_plans SET status = 'paused', updated_at = ?
WHERE id = ? AND status = 'active' RETURNING id`,
values: [Date.now(), Number(row.id)],
sql: `UPDATE bot_plans SET steps = ?, status = 'paused', updated_at = ?
WHERE id = ? AND status IN ('active', 'done') RETURNING id`,
values: [JSON.stringify(steps), now, Number(row.id)],
});
if (!res.payload?.length) return null;
@@ -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,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)],
};
}
@@ -5,6 +5,8 @@ import AppError from "@/src/utils/app-error";
import { abortRunningJob } from "@/src/bots-queue/job-abort-registry";
import recordHookCallResponse from "../bot-hooks/record-hook-call-response";
import settleInstallRequest from "../install-requests/settle-install-request";
import pauseFailedPlanStep from "../bot-plans/pause-failed-plan-step";
import pushBotPlan from "@/src/bots-queue/push-bot-plan";
import botFaceAfterJob from "./bot-face-after-job";
type Params = {
@@ -59,5 +61,13 @@ export default async function cancelBotJob({ user_id, job_id }: Params) {
await settleInstallRequest({ job, text: BotJobCancelledError, failed: true });
/**
* Its plan pauses with it, the way a stopped or failed run's does: no
* card would ever offer the step again otherwise.
*/
const paused_plan = await pauseFailedPlanStep({ job }).catch(() => null);
if (paused_plan) await pushBotPlan(paused_plan).catch(() => null);
return job;
}
@@ -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 });
@@ -158,7 +169,13 @@ export default async function completeBotJob({
}
await BunSQLite.sql({
sql: `UPDATE bots_queue SET result = ?, finished_at = ? WHERE id = ?`,
/**
* A job that failed, was retried and then answered must not stay
* marked with the old failure: the Details modal reads last_error off
* the row (job #699 shipped as "completed" beside "The model returned
* an empty answer.").
*/
sql: `UPDATE bots_queue SET result = ?, finished_at = ?, last_error = NULL WHERE id = ?`,
values: [result, now, job.id],
});
@@ -198,31 +215,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,7 +1,12 @@
import BunSQLite from "@moduletrace/bun-sqlite";
type Params = {
worker: string;
/**
* The handler's family (`AppData.BotQueueWorker`), not its own id: the id
* carries the process's pid, so a restart releases what the previous
* process of this install was running.
*/
family: string;
};
/**
@@ -9,12 +14,12 @@ type Params = {
* instead of waiting out the lock timeout. For startup, after a restart
* cut those jobs off. The cut-off attempt isn't counted.
*/
export default async function releaseWorkerBotJobs({ worker }: Params) {
export default async function releaseWorkerBotJobs({ family }: Params) {
const now = Date.now();
const res = await BunSQLite.sql({
sql: `UPDATE bots_queue SET status = 'pending', attempts = MAX(attempts - 1, 0), available_at = ?, locked_at = NULL, locked_by = NULL, updated_at = ? WHERE status = 'processing' AND locked_by = ? RETURNING id`,
values: [now, now, worker],
sql: `UPDATE bots_queue SET status = 'pending', attempts = MAX(attempts - 1, 0), available_at = ?, locked_at = NULL, locked_by = NULL, updated_at = ? WHERE status = 'processing' AND (locked_by = ? OR locked_by LIKE ?) RETURNING id`,
values: [now, now, family, `${family}-%`],
});
return res.payload?.length || 0;
@@ -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";
@@ -15,7 +16,11 @@ import stopAsks from "../asks/stop-asks";
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 pauseFailedPlanStep from "../bot-plans/pause-failed-plan-step";
import pushBotPlan from "@/src/bots-queue/push-bot-plan";
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 +32,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 +50,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 +74,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[] = [];
@@ -102,6 +128,15 @@ export default async function stopBotJobs({ bot_id, user_id }: Params): Promise<
await recordHookCallResponse({ job: stopped, status: "failed", response: BotJobStoppedError, now });
/**
* A plan whose step this run was working pauses with it, the way a
* failed run's does (`notifyBotJobFailed`): nothing else would ever
* advance it, and the card would show that step running for ever.
*/
const paused_plan = await pauseFailedPlanStep({ job: stopped }).catch(() => null);
if (paused_plan) await pushBotPlan(paused_plan).catch(() => null);
/**
* A coordinator stopped on an install request: the worker that
* asked is told.
@@ -128,11 +163,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 +189,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,39 +211,105 @@ 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;
/**
* The session this run's conversation is in now, not the one it was
* queued in: a reply that carried the conversation into a new session
* between the UPDATE above and here would put the stopped line in a
* thread the user has left, and the live conversation would show
* nothing.
*/
const current = (
await BunSQLite.sql<{ session_id: number | null }>({
sql: `SELECT session_id FROM bots_queue WHERE id = ?`,
values: [Number(job.id)],
}).catch(() => null)
)?.payload?.[0]?.session_id;
const message = await insertBotMessage({
bot_id: Number(bot_id),
session_id,
session_id: Number(current || session_id),
workspace_id: job.workspace_id || null,
text: stoppedJobReport({ job }),
}).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);
}
}
@@ -11,7 +11,10 @@ type Params = {
pinned_ids?: number[];
};
type ModelRow = BUN_SQLITE_COBBLE_HARNESS_MODELS & { provider_name?: string };
type ModelRow = BUN_SQLITE_COBBLE_HARNESS_MODELS & {
provider_name?: string;
provider_kind?: string;
};
export type HarnessModelEntry = {
row: ModelRow;
@@ -31,7 +34,7 @@ export default async function grabHarnessModelEntries({
const rows =
(
await BunSQLite.sql<ModelRow>({
sql: `SELECT m.*, p.name AS provider_name FROM harness_models m
sql: `SELECT m.*, p.name AS provider_name, p.kind AS provider_kind FROM harness_models m
JOIN harness_providers p ON p.id = m.provider_id
WHERE (m.available = 1 AND p.enabled = 1)
${ids.length ? `OR m.id IN (${ids.map(() => "?").join(", ")})` : ""}
@@ -57,6 +60,14 @@ export default async function grabHarnessModelEntries({
input_modalities: model.input_modalities,
supported_parameters: model.supported_parameters,
context_length: model.context_length,
/**
* Only OpenRouter's catalog says what a model takes; every
* other provider is listed by id and guessed from its name
* (`guessModelModalities`, via `list-models.ts`). Said on the
* option so the picker can warn about a text model pinned
* from a list that never said it calls tools.
*/
capabilities_guessed: row.provider_kind != "openrouter",
},
};
});
@@ -0,0 +1,40 @@
import BunSQLite from "@moduletrace/bun-sqlite";
import type {
BUN_SQLITE_COBBLE_KNOWLEDGEBASE_DOCUMENTS,
BUN_SQLITE_COBBLE_MEDIA,
} from "@/db/types/db";
import canManageCrew from "@/src/utils/rbac/can-manage-crew";
import grabUserTypes from "../users/grab-user-types";
type Params = {
media_id: number | string;
user_id: number | string;
};
/**
* A knowledgebase document's own file (its private `media` row) for a crew
* manager, the same people Settings > Knowledgebases shows its documents
* to, so "Open original" loads it.
*/
export default async function grabKnowledgebaseDocumentMedia({
media_id,
user_id,
}: Params): Promise<BUN_SQLITE_COBBLE_MEDIA | null> {
const document = (
await BunSQLite.sql<Pick<BUN_SQLITE_COBBLE_KNOWLEDGEBASE_DOCUMENTS, "id">>({
sql: `SELECT id FROM knowledgebase_documents WHERE media_id = ? LIMIT 1`,
values: [Number(media_id)],
})
).payload?.[0];
if (!document?.id) return null;
if (!canManageCrew({ user_types: await grabUserTypes({ user_id }) })) return null;
const media = await BunSQLite.sql<BUN_SQLITE_COBBLE_MEDIA>({
sql: `SELECT * FROM media WHERE id = ? LIMIT 1`,
values: [Number(media_id)],
});
return media.payload?.[0] || null;
}
@@ -5,7 +5,7 @@ type Params = {
document: {
source?: string | null;
content?: string | null;
media_id?: number | null;
media_id?: number | string | null;
name?: string | null;
mime_type?: string | null;
};
@@ -18,11 +18,12 @@ type Params = {
export default async function grabKnowledgebaseDocumentText({ document }: Params) {
if (document.source == "text") return document.content || "";
if (!document.media_id) return "";
const media_id = Number(document.media_id) || 0;
if (!media_id) return "";
const media = await BunSQLite.sql<{ media_write_path?: string; text_content?: string }>({
sql: `SELECT media_write_path, text_content FROM media WHERE id = ? LIMIT 1`,
values: [document.media_id],
values: [media_id],
}).then((res) => res.payload?.[0]);
return (
@@ -1,6 +1,7 @@
import BunSQLite from "@moduletrace/bun-sqlite";
import type { BUN_SQLITE_COBBLE_KNOWLEDGEBASE_DOCUMENTS } from "@/db/types/db";
import type { KnowledgebaseDocumentsPayload } from "@/src/types";
import grabInstallEmbeddingModel from "./grab-install-embedding-model";
import grabKnowledgebase from "./grab-knowledgebase";
import { KnowledgebaseDocumentIndexingSql } from "./knowledgebase-document-indexing-sql";
import parseKnowledgebaseDocumentRow from "./parse-knowledgebase-document-row";
@@ -10,7 +11,8 @@ type Params = {
};
/**
* A knowledgebase's documents, newest first, without their text.
* A knowledgebase's documents, newest first, without their text, and the
* install's embedding model for their lines.
*/
export default async function listKnowledgebaseDocuments({
knowledgebase_id,
@@ -18,7 +20,7 @@ export default async function listKnowledgebaseDocuments({
const knowledgebase = await grabKnowledgebase({ knowledgebase_id });
const rows = await BunSQLite.sql<BUN_SQLITE_COBBLE_KNOWLEDGEBASE_DOCUMENTS & { indexing?: number }>({
sql: `SELECT id, knowledgebase_id, name, source, mime_type, size, chunk_count, embedding_model,
sql: `SELECT id, knowledgebase_id, name, source, media_id, mime_type, size, chunk_count, embedding_model,
ingested_at, ingest_error, created_at, ${KnowledgebaseDocumentIndexingSql} AS indexing
FROM knowledgebase_documents d WHERE knowledgebase_id = ? ORDER BY id DESC`,
values: [knowledgebase.id],
@@ -27,5 +29,6 @@ export default async function listKnowledgebaseDocuments({
return {
knowledgebase_id: knowledgebase.id,
documents: (rows.payload || []).map((row) => parseKnowledgebaseDocumentRow({ row })),
embedding_model: await grabInstallEmbeddingModel(),
};
}
@@ -0,0 +1,25 @@
import { describe, expect, test } from "bun:test";
import type { BUN_SQLITE_COBBLE_KNOWLEDGEBASE_DOCUMENTS } from "@/db/types/db";
import parseKnowledgebaseDocumentRow from "./parse-knowledgebase-document-row";
const parse = ({ media_id }: { media_id?: unknown }) =>
parseKnowledgebaseDocumentRow({
row: {
id: 1,
knowledgebase_id: 2,
name: "notes.md",
source: "file",
media_id,
} as BUN_SQLITE_COBBLE_KNOWLEDGEBASE_DOCUMENTS,
});
describe("parseKnowledgebaseDocumentRow", () => {
test("carries the file's media row, which Open original loads", () => {
expect(parse({ media_id: 12 }).media_id).toBe(12);
});
test("has no media row for a written document or a missing one", () => {
expect(parse({ media_id: undefined }).media_id).toBeNull();
expect(parse({ media_id: "" }).media_id).toBeNull();
});
});
@@ -18,6 +18,7 @@ export default function parseKnowledgebaseDocumentRow({ row }: Params): Knowledg
knowledgebase_id: Number(row.knowledgebase_id),
name: row.name || "",
source: row.source == "text" ? "text" : "file",
media_id: Number(row.media_id) || null,
mime_type: row.mime_type || "",
size: Number(row.size) || 0,
chunk_count: Number(row.chunk_count) || 0,
@@ -2,6 +2,7 @@ import BunSQLite from "@moduletrace/bun-sqlite";
import type { BUN_SQLITE_COBBLE_MEDIA, BunSQLiteTables } from "@/db/types/db";
import grabSharedPictureMedia from "@/src/functions/backend/db/access/grab-shared-picture-media";
import grabBotFileMedia from "@/src/functions/backend/db/bot-files/grab-bot-file-media";
import grabKnowledgebaseDocumentMedia from "@/src/functions/backend/db/knowledgebases/grab-knowledgebase-document-media";
import grabTaskMediaFile from "@/src/functions/backend/db/tasks/grab-task-media-file";
type Params = {
@@ -20,7 +21,9 @@ type Params = {
* - a bot's or workspace's file, to whoever reaches the folder it lives in
* (`grabBotFileMedia`),
* - a file attached to a task, to whoever reaches the task
* (`grabTaskMediaFile`).
* (`grabTaskMediaFile`),
* - a knowledgebase document's file, to crew managers
* (`grabKnowledgebaseDocumentMedia`).
*
* Null when it is not theirs to see, so a request never turns into a path
* before this has passed.
@@ -51,6 +54,7 @@ export default async function grabUserMedia({
(await grabSharedPictureMedia({ media_id })) ||
(await grabBotFileMedia({ media_id, user_id })) ||
(await grabTaskMediaFile({ media_id, user_id })) ||
(await grabKnowledgebaseDocumentMedia({ media_id, user_id })) ||
undefined
);
}
@@ -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
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;
+26 -5
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;
@@ -57,14 +58,21 @@ export default async function generateImage({
if (has_references && !ordered.length && image.length) {
throw new HarnessError({
message: `None of the image models here takes reference images. A super admin can pick one under Image editing in Settings, under Models.`,
message: `None of the image models here takes reference images. A super admin can pick one under Image editing in Settings, under Models, or turn Image editing's fallback on to send the call to a generation model that takes them.`,
code: "unavailable",
});
}
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,13 +97,19 @@ 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;
}
/**
* Image editing's setting and candidates, or undefined while it's off.
* Image editing's setting and candidates. Turned off still reports its
* fallback, so a call with references can hand over to a generation model
* that takes images (with fallback off it never leaves the harness).
*/
async function grabEdit({
bot_id,
@@ -106,7 +120,14 @@ async function grabEdit({
}) {
const setting = await grabHarnessSetting({ harness: "image_edit", bot_id, workspace_id });
if (!setting.enabled) return undefined;
if (!setting.enabled) {
/**
* Turned off still hands its fallback flag down: a call with
* references may go to a generation model that takes images, but only
* while fallback is on, or it would leave the harness quietly.
*/
return { picked: false, fallback: setting.fallback, candidates: [] };
}
return {
picked: Boolean(setting.model_id),
@@ -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.`;
}
@@ -47,6 +47,7 @@ const chat: HarnessAdapter["chat"] = async ({
provider_name:
provider.name || grabProviderPreset({ kind: provider.kind }).title,
candidate_key: candidate.key,
url: res.url,
});
};
@@ -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;
@@ -1,7 +1,7 @@
import HarnessError from "../../harness-error";
import toHarnessError from "../to-harness-error";
import type { HarnessChatResult, HarnessToolCall } from "../../types";
import readReasoning from "./read-reasoning";
import redactProviderError from "../redact-provider-error";
type WireToolCall = {
id?: string;
@@ -15,6 +15,10 @@ type Params = {
json: any;
provider_name: string;
candidate_key?: string;
/**
* Where the call went, so a refusal names the address it came from.
*/
url?: string;
};
/**
@@ -25,15 +29,22 @@ export default function readChatResponse({
json,
provider_name,
candidate_key,
url,
}: Params): HarnessChatResult {
if (json?.error) {
const status = Number(json.error.code) || undefined;
throw new HarnessError({
message: `${provider_name}: ${redactProviderError({ text: json.error.message || "The model failed." })}`,
status,
retryable: !status || status == 429 || status >= 500,
/**
* Built by the classifier, not by hand: a 200 carrying an error body
* skipped `toHarnessError` whole, so an oversized request read as a
* plain refusal that benched nothing and re-fired on every turn (52
* failed rows, one task limping through its fallbacks for 18 minutes).
* Overflow, a dead key and the provider's own words are decided there.
*/
throw toHarnessError({
status: Number(json.error.code) || 400,
body: JSON.stringify({ error: json.error }),
provider_name,
candidate_key,
url,
});
}
+8 -3
View File
@@ -14,8 +14,13 @@ import type { HarnessCooldowns } from "./create-cooldowns";
*/
const slot = globalCache<HarnessCooldowns>({ name: "cobble.harnessCooldowns" });
const HarnessCooldowns = slot.get() || createCooldowns();
/**
* Not named `HarnessCooldowns`: the type of that name is imported above, and
* an `export default` of a name both declare resolves to the type for some
* compilers, so every importer of this value is then called a type-only import.
*/
const cooldowns = slot.get() || createCooldowns();
slot.set(HarnessCooldowns);
slot.set(cooldowns);
export default HarnessCooldowns;
export default cooldowns;
@@ -101,6 +101,25 @@ export default async function resolveHarnessCandidates({
modelServesHarness({ model: entry, harness }),
);
/**
* A pick that can't run is not "no model set up": with fallback off the
* call would otherwise answer on a free automatic pick while the setting
* names a model, and the usage row would say `auto` (this is how a pinned
* tool-less model ran eleven replies and none of them closed).
*/
if (setting.model_id && !pinned && !setting.fallback) {
const title = Harnesses.find((h) => h.value == harness)?.title;
const slug = rows.find((row) => row.id == setting.model_id)?.slug;
throw new HarnessError({
message:
`${slug || "The picked model"} can't be used for ${title ? title.toLowerCase() : harness} ` +
`(it's unavailable, its provider isn't usable, or it doesn't serve this harness), and fallback is off. ` +
`Pick a model that serves it under Models, or turn fallback on.`,
code: "unavailable",
});
}
/**
* Each fallback model names its own provider, so the setting's
* provider limit doesn't apply to them.
@@ -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");
+35 -3
View File
@@ -165,7 +165,26 @@ export default async function withCandidates<T>({
return { result, candidate };
} catch (error: unknown) {
if (!(error instanceof HarnessError)) throw error;
if (!(error instanceof HarnessError)) {
/**
* A bug in an adapter is not swallowed (it goes up as it is),
* but it stops being invisible: with no row the message's
* Details modal showed nothing at all for the call that ended
* the run.
*/
if (log_failures) {
await recordHarnessFailure({
harness: harness_of?.get(candidate.key) || harness,
candidate,
error: new HarnessError({
message: error instanceof Error ? error.message : String(error),
candidate_key: candidate.key,
}),
});
}
throw error;
}
if (error.code == "aborted") throw error;
/**
* A fatal failure is the run's own: another model fails the same
@@ -229,7 +248,13 @@ export default async function withCandidates<T>({
}
}
const last = errors[errors.length - 1];
/**
* The error worth reading, not simply the last one: a dead key on the
* first candidate and a 400 on the second left the bot told its user the
* request was bad, when the provider's key was the whole story.
*/
const last =
errors.find((error) => error.provider_wide || error.fatal) || errors[errors.length - 1];
if (!last) {
const next = soonestRest({ candidates: ordered, cooldowns, now: now() });
@@ -259,6 +284,7 @@ export default async function withCandidates<T>({
model_name: last.model_name,
method: last.method,
url: last.url,
timed_out: last.timed_out,
});
}
@@ -368,7 +394,13 @@ function coolDown({
return at;
}
if (error.status == 403 || error.status == 404) {
/**
* A 405 says the path isn't there at all (`toHarnessError` calls it a
* missing endpoint), so another turn on the same base URL answers the
* same way: benched like a 404, or a wrong base URL is paid for on every
* turn, forever.
*/
if (error.status == 403 || error.status == 404 || error.status == 405) {
cooldowns.set({ key: candidate.key, at: until });
return until;
}
+13 -2
View File
@@ -37,7 +37,10 @@ export type GenerateTextParams = {
*/
limits?: HarnessCallLimits;
/**
* Overrides the saved generation settings (media reading wants 0).
* Overrides the saved generation settings (media reading wants 0). Sent as
* given: `prepareMessagesForModel` and `readImage` build their own call, and
* anything passed here must already be keys the candidate advertises, since
* this path does not filter them the way `grabChatParams` does.
*/
params?: HarnessWireParams;
signal?: AbortSignal;
@@ -146,8 +149,16 @@ export default async function generateText({
: { text: "", reasoning: null };
if (!stripped.text && !answer.tool_calls.length) {
/**
* Named for what happened: a thinking model whose content came
* back empty or all inline tags reaches here, and "an empty
* answer" sent a bot to explain a model it had just been
* charged for (job 699 attempt 1).
*/
throw new HarnessError({
message: `The model returned an empty answer.`,
message: answer.reasoning || stripped.reasoning
? `The model answered with only its thinking: no message and no tool call.`
: `The model returned an empty answer.`,
retryable: true,
candidate_key: candidate.key,
});
+271 -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, replyCardFailedNote, replyClosingFailedNote, 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([
@@ -2131,6 +2202,115 @@ describe("runTextLoop required send_reply", () => {
expect(seen[1]!.messages.at(-1)).toMatchObject({ role: "user", content: replyClosingRequiredNote });
});
test("a card the tool refused beside a good send_reply names the card, not send_reply", async () => {
/**
* Job 699: `send_reply` returned ok and `suggest_next_steps` refused a
* step over its length cap. The note said "send_reply did not go
* through", so the model spent three turns re-writing a message that
* had already shipped, and the trace logged closing_failed against the
* wrong tool.
*/
const cappedSteps: HarnessTool<{ steps: string[] }> = {
name: "suggest_next_steps",
description: "Offers the next steps as buttons.",
schema: z.object({
steps: z.array(z.string().max(AppData.BotSuggestionStepMaxChars, "Keep each step under 120 characters")),
}),
run: async ({ args }) => {
suggested.push(...args.steps);
return "Suggested. The buttons are under your message.";
},
};
const long_step =
"Summarise every tab open in the browser on the computer, name the ones you think are stale, and tell me which I can close today.";
expect(long_step.length).toBeGreaterThan(AppData.BotSuggestionStepMaxChars);
const { generate, seen } = scripted([
{
text: "Nine tabs are open.",
tool_calls: [
{ id: "s1", name: "send_reply", arguments: `{"status":"done"}` },
{ id: "c1", name: "suggest_next_steps", arguments: JSON.stringify({ steps: [long_step] }) },
],
},
{
text: "Nine tabs are open.",
tool_calls: [
{ id: "s2", name: "send_reply", arguments: `{"status":"done"}` },
{ id: "c2", name: "suggest_next_steps", arguments: `{"steps":["Close the extras"]}` },
],
},
]);
const result = await runTextLoop({
system: "s",
messages: [{ role: "user", content: "What's open?" }],
tools: [sendReply, cappedSteps],
generate,
resolveCandidates,
require_closing_answer: true,
});
expect(seen[1]!.messages.at(-1)).toMatchObject({
role: "user",
content: replyCardFailedNote({ tools: ["suggest_next_steps"] }),
});
expect(result.text).toBe("Nine tabs are open.");
expect(result.tool_uses).toEqual([
{ name: "send_reply", ok: true },
{ name: "suggest_next_steps", ok: false },
{ name: "send_reply", ok: true },
{ name: "suggest_next_steps", ok: true },
]);
});
test("a send_reply that failed is still blamed, even beside a failed card", async () => {
const failingSend: HarnessTool<{ status?: string }> = {
name: "send_reply",
description: "Sends the message.",
schema: z.object({ status: z.string().optional() }),
run: async () => {
throw new Error('Status "working" needs work queued in the call.');
},
};
const refusedSteps: HarnessTool<{ steps: string[] }> = {
name: "suggest_next_steps",
description: "Offers the next steps as buttons.",
schema: z.object({ steps: z.array(z.string()) }),
run: async () => {
throw new Error("Keep each step under 120 characters");
},
};
const { generate, seen } = scripted([
{
text: "I'm on it.",
tool_calls: [
{ id: "s1", name: "send_reply", arguments: `{"status":"working"}` },
{ id: "c1", name: "suggest_next_steps", arguments: `{"steps":["Look again"]}` },
],
},
]);
const result = await runTextLoop({
system: "s",
messages: [{ role: "user", content: "Check the browser." }],
tools: [failingSend, refusedSteps],
generate,
resolveCandidates,
require_closing_answer: true,
});
/**
* Both closing calls failed, so the message never went out and the old
* note is the right one: it names send_reply, which is what has to be
* fixed. Only a card failing on its own takes the new note.
*/
expect(seen[1]!.messages.at(-1)!.content).toBe(replyClosingFailedNote);
expect(result.text).toBe("");
});
test("send_reply with no message beside it is told once", async () => {
const { generate, seen } = scripted([
{ tool_calls: [{ id: "s1", name: "send_reply", arguments: `{"status":"done"}` }] },
@@ -2709,3 +2889,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.");
});
});
File diff suppressed because it is too large Load Diff
@@ -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({
@@ -22,6 +22,7 @@ const document: KnowledgebaseDocument = {
knowledgebase_id: 3,
name: "leave.md",
source: "file",
media_id: null,
mime_type: "md",
size: 2048,
chunk_count: 4,
@@ -8,11 +8,10 @@ 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.
* The run working the step, kept on it so a report the app never sent
* puts the step back (`pauseFailedPlanStep`).
*/
in_run?: boolean;
job_id?: number | string;
};
type Args = {
@@ -26,14 +25,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, job_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 +44,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.`);
}
@@ -55,6 +52,7 @@ export default function completePlanStepTool({ bot_id, session_id, in_run }: Par
plan_id: args.plan_id,
session_id,
summary: args.summary,
job_id,
});
completed = true;
@@ -71,11 +69,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,23 +14,23 @@ 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.
*/
onPlan: (params: { ref: string; waiting?: boolean }) => void;
/**
* The run these tools belong to, kept on a step the run finishes (see
* `completeBotPlanStep`).
*/
job_id?: number | string;
};
/**
* 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 +40,25 @@ 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,
job_id,
}: 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, job_id }));
return tools;
}
}
@@ -51,7 +51,9 @@ export default function suggestNextStepsTool({ user_id, bot_id, session_id, work
.max(AppData.BotSuggestionTitleMaxChars)
.optional()
.describe(`A short heading for the row, e.g. "What I can do next" (defaults to "Next steps")`),
steps: BotSuggestionStepsSchema.describe("The suggested steps, best first, each written as the message the user would send"),
steps: BotSuggestionStepsSchema.describe(
`The suggested steps, best first, at most ${AppData.BotSuggestionMaxSteps}, each under ${AppData.BotSuggestionStepMaxChars} characters and written as the message the user would send`,
),
}),
run: async ({ args }) => {
if (suggested) {
@@ -22,6 +22,12 @@ type Params = {
* Called with each update sent, so the run knows it said something.
*/
onSend?: (params: { message_id: number }) => void;
/**
* What the run typed, run through the run's secret redaction before it is
* stored: an update lands in another bot's conversation, where a raw env
* value or a password field's content would sit in a message forever.
*/
redact?: (text: string) => string;
};
type Args = {
@@ -37,7 +43,7 @@ type Args = {
* back on its own when the work ends. At most
* `AppData.BotReplyInterimMessagesMax` per run.
*/
export default function updateRequesterTool({ user_id, session_id, ask_id, onSend }: Params): HarnessTool<Args> {
export default function updateRequesterTool({ user_id, session_id, ask_id, onSend, redact = (text) => text }: Params): HarnessTool<Args> {
let sent = 0;
return {
@@ -63,7 +69,7 @@ export default function updateRequesterTool({ user_id, session_id, ask_id, onSen
const posted = await tellAskRequester({
ask,
text: askUpdateMessage({ ask, text: stripQuestionRefs({ text: args.text }).text }),
text: askUpdateMessage({ ask, text: stripQuestionRefs({ text: redact(args.text) }).text }),
});
sent++;
@@ -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(),
+11 -1
View File
@@ -51,11 +51,21 @@ export default function loadToolsTool({ deferred, isLoaded, onLoad }: Params): H
if (fresh.length) onLoad(fresh);
/**
* A name already offered inline isn't in the loadable list at all,
* so without this a run that had the tool in hand was sent looking
* for it in a list it wasn't in, and gave up (production:
* `load_tools("browser")`).
*/
const ready = missing.filter((name) => isLoaded(name));
return [
fresh.length ? `Loaded: ${fresh.join(", ")}. Call them from your next step.` : "",
already.length ? `Already loaded: ${already.join(", ")}.` : "",
missing.length
? `Not in the list: ${missing.join(", ")}. Use the exact names or family names under "Tools you can load".`
? `Not in the list: ${missing.join(", ")}.${
ready.length ? ` Already yours, no loading needed: ${ready.join(", ")}.` : ""
} Use the exact names or family names under "Tools you can load", and a computer or browser tool a reply doesn't carry is work for send_reply with status "working".`
: "",
]
.filter(Boolean)
@@ -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 })}`);
});
@@ -1,5 +1,6 @@
import { z } from "zod";
import { AppData } from "@/src/data/app-data";
import describeHarnessFailure from "@/src/harness/describe-harness-failure";
import recordBotFile from "@/src/functions/backend/db/bot-files/record-bot-file";
import loadReferenceImages from "@/src/harness/image/load-reference-images";
import generateVideo from "@/src/harness/video/generate-video";
@@ -129,8 +130,7 @@ export default function generateVideoTool(context: StorageToolContext): HarnessT
bot_id: context.bot_id,
workspace_id: context.workspace_id,
}).catch((error: unknown) => {
const message = error instanceof Error ? error.message : String(error);
throw new Error(`Video generation isn't working: ${message}`);
throw new Error(`Video generation isn't working: ${describeHarnessFailure({ error })}`);
});
if (!made.length) {
@@ -28,4 +28,32 @@ describe("unknownToolMessage", () => {
expect(text).toContain("only exist in a task on a computer");
expect(text).not.toContain("start_task");
});
/**
* The user's own browser's tools carry the browser's slug, so a reply that
* has one is not short of a browser: it named the tool the wrong way.
*/
test("names the slug when the run's browser tools have one", () => {
const text = unknownToolMessage({
name: "browser_navigate",
tools: [{ name: "send_reply" }, { name: "work-laptop__browser_navigate" }],
});
expect(text).toContain(`the browser's slug, e.g. "work-laptop__browser_navigate"`);
expect(text).not.toContain("only exist in a task");
});
/**
* A task run's own `browser_*` tools have no slug, so an excluded one must
* not be told to look for a prefixed name it does not have.
*/
test("keeps the task message for a computer browser tool", () => {
const text = unknownToolMessage({
name: "browser_close",
tools: [{ name: "browser_navigate" }, { name: "computer_bash" }],
});
expect(text).toContain("only exist in a task on a computer");
expect(text).not.toContain("slug");
});
});
+18 -1
View File
@@ -7,9 +7,14 @@ type Params = {
/**
* Computer tools: the app's own shell and file tools and Playwright MCP's
* browser tools, which only a task run on a computer has.
* browser tools, which only a task run on a computer has. A user's own
* browser is named with its slug (`<slug>__browser_navigate`), so the prefix
* test is not enough to know a call wanted the computer's browser.
*/
const ComputerToolPattern = /^(?:computer_|browser_)/;
const WantsBrowserPattern = /(?:^|__)browser_/;
/** A user's own browser's tool, named under the browser's slug. */
const SlugBrowserPattern = /__browser_/;
/**
* What a call to a tool the run doesn't have gets back. A computer or
@@ -21,6 +26,18 @@ const ComputerToolPattern = /^(?:computer_|browser_)/;
export default function unknownToolMessage({ name, tools }: Params) {
const available = `Available: ${tools.map((t) => t.name).join(", ") || "none"}.`;
/**
* A reply with the user's own browser does have browser tools, just under
* the browser's slug: telling it they only exist in a task was a lie that
* ended with "I have no browser" (production, Nov 2026). A task run's own
* `browser_*` tools carry no slug, so they keep the message below.
*/
const own = WantsBrowserPattern.test(name) ? tools.find((t) => SlugBrowserPattern.test(t.name)) : undefined;
if (own) {
return `Error: There is no tool called "${name}". Your browser tools carry the browser's slug, e.g. "${own.name}". ${available}`;
}
if (!ComputerToolPattern.test(name)) {
return `Error: There is no tool called "${name}". ${available}`;
}
+4 -2
View File
@@ -106,7 +106,9 @@ export default async function generateVideo({
}
/**
* Video editing's setting and candidates, or undefined while it's off.
* Video editing's setting and candidates. Turned off still reports its
* fallback, the way image editing does, so the order is the same decision
* in both lanes.
*/
async function grabEdit({
bot_id,
@@ -117,7 +119,7 @@ async function grabEdit({
}) {
const setting = await grabHarnessSetting({ harness: "video_edit", bot_id, workspace_id });
if (!setting.enabled) return undefined;
if (!setting.enabled) return { picked: false, fallback: setting.fallback, candidates: [] };
return {
picked: Boolean(setting.model_id),
@@ -51,10 +51,7 @@ describe("orderVideoCandidates", () => {
).toEqual(["video_edit:flux-video-edit"]);
});
test("video editing off or unpicked goes to the generation models that take videos", () => {
expect(
slugs(orderVideoCandidates({ images: false, videos: true, video: [veo, seedance] })),
).toEqual(["video:seedance"]);
test("video editing unpicked goes to the generation models that take videos, with fallback on", () => {
expect(
slugs(
orderVideoCandidates({
@@ -67,14 +64,30 @@ describe("orderVideoCandidates", () => {
).toEqual(["video:seedance"]);
});
test("an edit pick that can't take the images passed falls to generation", () => {
test("video editing off with no fallback has nothing to try, as image editing does", () => {
expect(
slugs(orderVideoCandidates({ images: false, videos: true, video: [veo, seedance] })),
).toEqual([]);
expect(
slugs(
orderVideoCandidates({
images: false,
videos: true,
video: [veo, seedance],
edit: { picked: false, fallback: false, candidates: [] },
}),
),
).toEqual([]);
});
test("an edit pick that can't take the images passed falls to generation, with fallback on", () => {
expect(
slugs(
orderVideoCandidates({
images: true,
videos: true,
video: [veo, seedance],
edit: { picked: true, fallback: false, candidates: [flux_edit] },
edit: { picked: true, fallback: true, candidates: [flux_edit] },
}),
),
).toEqual(["video:seedance"]);
+4 -2
View File
@@ -22,7 +22,7 @@ type Params = {
*/
video: HarnessCandidate[];
/**
* Video editing's setting and candidates; undefined when it's off.
* Video editing's setting and candidates; no pick while it's off.
*/
edit?: {
/**
@@ -59,7 +59,9 @@ export default function orderVideoCandidates({ images, videos, video, edit }: Pa
? edit.candidates.filter(takes).map((candidate) => ({ candidate, harness: "video_edit" as const }))
: [];
const ordered = !edits.length ? generation : [...edits, ...(edit?.fallback ? generation : [])];
// The hand-over to generation, whether the edit pick failed or there is
// none, happens only with fallback on: the same rule as image editing.
const ordered = [...edits, ...(edit?.fallback ? generation : [])];
const seen = new Set<string>();
return ordered.filter(({ candidate }) => {
+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) => (
@@ -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" },
];
@@ -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]);
}
}
@@ -11,7 +11,6 @@ import Loading from "@moduletrace/twui/elements/Loading";
import { X } from "lucide-react";
import SidePanel from "@/src/components/general/side-panel";
import BotAvatar from "@/src/components/general/bot-avatar";
import CodeEditor from "@/src/components/general/code-editor";
import TabButton from "@/src/components/general/tab-button";
import type { BotFace } from "@/src/dict/bot-dict";
import botStoneProps from "@/src/utils/bot-stone-props";
@@ -27,6 +26,7 @@ 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";
@@ -78,15 +78,13 @@ export default function BotPanel({
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 &&
memory != undefined &&
user_memory != undefined &&
(!can_edit ||
!workspace_id ||
Boolean(workspace_instructions.instructions));
(!workspace_id || Boolean(workspace_instructions.instructions));
const loaded_error = error || workspace_instructions.error;
useTopModalEscape({ onClose: on_close, enabled: open });
@@ -221,27 +219,41 @@ export default function BotPanel({
) : (
<>
<Span className="text-[13px] leading-[18px] text-ink-secondary">
{`What ${name} is for, and the instructions it follows.`}
{`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}
{system_prompt != undefined &&
user_memory != undefined ? (
{memory_ready ? (
<>
<CodeEditor
<BotReadOnlyBlock
title="Instructions"
content={
system_prompt || "Nothing yet."
}
mode="markdown"
content={system_prompt || ""}
className="h-52"
readOnly
onChange={() => {}}
/>
<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}
@@ -250,9 +262,9 @@ export default function BotPanel({
onCancel={on_close}
/>
</>
) : error ? (
) : loaded_error ? (
<Span className="py-6 text-[13px] leading-[18px] text-ink-secondary">
{error}
{loaded_error}
</Span>
) : (
<Stack className="w-full py-10 items-center">
@@ -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={() => {}}
/>
);
}
@@ -4,6 +4,7 @@ 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;
@@ -70,13 +71,10 @@ export default function BotUserMemory({
<Span className="text-[13px] leading-[18px] text-ink-secondary">
{description}
</Span>
<CodeEditor
<BotReadOnlyBlock
title="About you"
content={memory || "Nothing yet."}
mode="markdown"
content={memory}
className="h-32"
readOnly
onChange={() => {}}
/>
</>
);
@@ -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>
);
}
@@ -0,0 +1,37 @@
import Button from "@moduletrace/twui/layout/Button";
import Span from "@moduletrace/twui/layout/Span";
import { twMerge } from "tailwind-merge";
import type { ComposerCommand } from "../(data)/composer-commands";
type Props = {
command: ComposerCommand;
active: boolean;
onPick: (command: ComposerCommand) => void;
};
/**
* One slash command in the composer's command list, with what it does.
*/
export default function ComposerCommandOption({ command, active, onPick }: Props) {
return (
<Button
type="button"
variant="ghost"
color="text"
role="option"
aria-selected={active}
title={`/${command.name}`}
onMouseDown={(e) => {
e.preventDefault();
onPick(command);
}}
className={twMerge(
"w-full justify-start! gap-2.5! px-2! py-1.5! rounded-default-sm text-left text-ink",
active && "bg-sunken",
)}
>
<Span className="shrink-0 text-sm font-bold leading-5">{`/${command.name}`}</Span>
<Span className="min-w-0 truncate text-xs leading-4 text-ink-secondary">{command.description}</Span>
</Button>
);
}
@@ -31,6 +31,11 @@ type Props = {
add_hint: string;
add_noun: string;
onAdd: (params: { kind: BotExtensionKind; id: number }) => Promise<boolean>;
/**
* Reads a knowledgebase's documents. Only crew managers: the documents
* API is theirs.
*/
onOpenItem?: (item: BotExtension) => void;
onRemove: (params: {
kind: BotExtensionKind;
id: number;
@@ -55,6 +60,7 @@ export default function ComposerExtensionsList({
add_hint,
add_noun,
onAdd,
onOpenItem,
onRemove,
}: Props) {
return (
@@ -69,6 +75,11 @@ export default function ComposerExtensionsList({
key={`${item.kind}:${item.id}`}
item={item}
busy={busy == `${item.kind}:${item.id}`}
onOpen={
can_manage && item.kind == "knowledgebase" && onOpenItem
? () => onOpenItem(item)
: undefined
}
onRemove={
can_manage && item.source == "bot"
? () =>
@@ -2,14 +2,19 @@ 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 { X } from "lucide-react";
import { FileText, X } from "lucide-react";
import extensionIcon from "@/src/components/general/extension-icon";
import RowIconButton from "@/src/components/general/row-icon-button";
import type { BotExtension } from "@/src/types";
import extensionStateNote from "@/src/utils/extension-state-note";
type Props = {
item: BotExtension;
busy?: boolean;
/**
* Reads a knowledgebase's documents; not given for anything else.
*/
onOpen?: () => void;
/**
* Takes it from the bot; not given for a workspace's own or when the
* user can't.
@@ -22,7 +27,7 @@ type Props = {
* the composer's modals. One that isn't working says so
* (`extensionStateNote`), one that's off is struck out.
*/
export default function ComposerToolRow({ item, busy, onRemove }: Props) {
export default function ComposerToolRow({ item, busy, onOpen, onRemove }: Props) {
const Icon = extensionIcon({ kind: item.kind });
const notes = [
item.detail,
@@ -50,6 +55,13 @@ export default function ComposerToolRow({ item, busy, onRemove }: Props) {
</Span>
) : null}
</Stack>
{onOpen ? (
<RowIconButton
icon={FileText}
title={`Open ${item.name}`}
onClick={onOpen}
/>
) : null}
{onRemove ? (
<Button
title={`Remove ${item.name}`}
@@ -13,6 +13,7 @@ import type {
BotExtensionsPayload,
ConnectorAppIcon,
} from "@/src/types";
import KnowledgebaseDocumentsModal from "@/src/pages/admin/settings/knowledgebases/(partials)/knowledgebase-documents-modal";
import ComposerConnectorsSection from "./composer-connectors-section";
import ComposerExtensionsList from "./composer-extensions-list";
import { twMerge } from "tailwind-merge";
@@ -108,6 +109,11 @@ export default function ComposerToolsModal({
onConnectorApps,
}: Props) {
const [open, setOpen] = useState(false);
/**
* The knowledgebase whose documents are read from its row; a read-only
* look at what the bot searches.
*/
const [viewing, setViewing] = useState<BotExtension>();
const count = attached.length;
const total = count + (connectors ? Number(connector_count || 0) : 0);
const has_problem = attached.some(
@@ -120,77 +126,87 @@ export default function ComposerToolsModal({
: copy.empty_label;
return (
<Modal
target={
<Button
title={copy.title}
type="button"
variant="ghost"
color="gray"
size="small"
beforeIcon={
<Row className="items-center gap-1! flex-nowrap">
{app_icons.map((app, index) => (
<Img
key={app.id}
src={app.logo}
alt={app.name}
title={app.name}
size={16}
circle
className={twMerge(
"shrink-0 border border-hairline bg-white object-contain relative",
index > 0 ? "-ml-1.5" : "",
)}
style={{ zIndex: index + 1 }}
/>
))}
<TriggerIcon size={12} aria-hidden />
</Row>
}
className={twMerge(
"shrink-0 gap-1! px-2! py-0.5! text-[12px] leading-4 text-ink-secondary",
)}
>
{label}
</Button>
}
targetWrapperProps={{ className: "shrink-0" }}
open={open}
setOpen={setOpen}
className="max-w-lg bg-paper p-6"
>
<Stack className="w-full gap-1! items-stretch">
<H2 className="text-lg! leading-6! tracking-normal! font-bold text-ink">
{copy.title}
</H2>
<Span className="text-[13px] leading-[18px] text-ink-secondary">
{total ? copy.some : copy.none}
</Span>
</Stack>
<>
<Modal
target={
<Button
title={copy.title}
type="button"
variant="ghost"
color="gray"
size="small"
beforeIcon={
<Row className="items-center gap-1! flex-nowrap">
{app_icons.map((app, index) => (
<Img
key={app.id}
src={app.logo}
alt={app.name}
title={app.name}
size={16}
circle
className={twMerge(
"shrink-0 border border-hairline bg-white object-contain relative",
index > 0 ? "-ml-1.5" : "",
)}
style={{ zIndex: index + 1 }}
/>
))}
<TriggerIcon size={12} aria-hidden />
</Row>
}
className={twMerge(
"shrink-0 gap-1! px-2! py-0.5! text-[12px] leading-4 text-ink-secondary",
)}
>
{label}
</Button>
}
targetWrapperProps={{ className: "shrink-0" }}
open={open}
setOpen={setOpen}
className="max-w-lg bg-paper p-6"
>
<Stack className="w-full gap-1! items-stretch">
<H2 className="text-lg! leading-6! tracking-normal! font-bold text-ink">
{copy.title}
</H2>
<Span className="text-[13px] leading-[18px] text-ink-secondary">
{total ? copy.some : copy.none}
</Span>
</Stack>
<ComposerExtensionsList
id={copy.id}
label={copy.title}
items={attached}
addable={addable}
can_manage={can_manage}
busy={busy}
add_hint={copy.add_hint}
add_noun={copy.add_noun}
onAdd={onAdd}
onRemove={onRemove}
/>
<ComposerExtensionsList
id={copy.id}
label={copy.title}
items={attached}
addable={addable}
can_manage={can_manage}
busy={busy}
add_hint={copy.add_hint}
add_noun={copy.add_noun}
onAdd={onAdd}
onOpenItem={setViewing}
onRemove={onRemove}
/>
{connectors ? (
<ComposerConnectorsSection
bot_id={connectors.bot_id}
workspace_id={connectors.workspace_id}
open={open}
onCount={onConnectorCount}
onApps={onConnectorApps}
{connectors ? (
<ComposerConnectorsSection
bot_id={connectors.bot_id}
workspace_id={connectors.workspace_id}
open={open}
onCount={onConnectorCount}
onApps={onConnectorApps}
/>
) : null}
</Modal>
{viewing ? (
<KnowledgebaseDocumentsModal
knowledgebase={{ id: viewing.id, name: viewing.name }}
can_edit={false}
onClose={() => setViewing(undefined)}
/>
) : null}
</Modal>
</>
);
}
@@ -15,8 +15,10 @@ import type {
BotVoicePayload,
BotWithLastMessage,
} from "@/src/types";
import type { ComposerCommand } from "../(data)/composer-commands";
import { CrewBotsContext } from "../(data)/crew-bots-context";
import { CrewWorkspacesContext } from "../(data)/crew-workspaces-context";
import postSessionApi from "@/src/functions/frontend/post-session-api";
import sendBotMessage from "../(functions)/send-bot-message";
import transcribeVoice from "../(functions)/transcribe-voice";
import useComposerAttachments from "../(hooks)/use-composer-attachments";
@@ -27,12 +29,15 @@ import useVoiceRecorder from "../(hooks)/use-voice-recorder";
import useOnlineStatus from "@/src/hooks/use-online-status";
import { AppData } from "@/src/data/app-data";
import messageTooLongMessage from "@/src/utils/message-too-long-message";
import conversationHref from "@/src/utils/conversation-href";
import composerHistoryTexts from "../(utils)/composer-history-texts";
import composerDraftKey from "../(utils)/composer-draft-key";
import composerCommandMatches from "../(utils)/composer-command-matches";
import loadedBuildId from "../(utils)/loaded-build";
import ComposerAttachButton from "./composer-attach-button";
import ComposerAttachments from "./composer-attachments";
import ComposerClearButton from "./composer-clear-button";
import ComposerCommandList from "./composer-command-list";
import ComposerEditor from "./composer-editor";
import ComposerMentionList from "./composer-mention-list";
import ComposerNotice from "./composer-notice";
@@ -157,6 +162,13 @@ export default function Composer({
const bots = useContext(CrewBotsContext);
const workspaces = useContext(CrewWorkspacesContext);
const send_ref = useRef<() => void>(() => {});
/**
* The slash commands the text is asking for, the one highlighted, and
* a command still on its way (`/continue` writes a summary).
*/
const commands = composerCommandMatches({ text });
const [command_index, set_command_index] = useState(0);
const [command_busy, set_command_busy] = useState(false);
/**
* Temporary ids for messages the server doesn't have yet, and the text
@@ -192,10 +204,37 @@ export default function Composer({
},
onSubmit: () => send_ref.current(),
onFiles: files.add,
onHistory: (params) => walk_history.current(params),
onHistory: (params) => {
/**
* An open command list keeps the arrows: they walk it when
* there's more than one, rather than the user's earlier
* messages.
*/
if (commands.length) {
if (commands.length > 1) {
moveCommand({ direction: params.direction });
}
return true;
}
return walk_history.current(params);
},
});
const editor = input.editor;
function moveCommand({ direction }: { direction: "up" | "down" }) {
const count = commands.length;
const step = direction == "down" ? 1 : -1;
set_command_index((index) => (index + step + count) % count);
}
/**
* Typing or deleting moves the highlight back to the first command.
*/
useEffect(() => set_command_index(0), [text]);
walk_history.current = ({ direction, empty }) => {
const next = history.step({
direction,
@@ -327,6 +366,84 @@ export default function Composer({
editor?.commands.focus();
}
/**
* A picked command goes into the input rather than running from the
* click, so what it does is read before Enter runs it.
*/
function pickCommand(command: ComposerCommand) {
const command_text = `/${command.name}`;
setText(command_text);
history.reset();
input.setMarkdown({ markdown: command_text });
editor?.commands.focus("end");
}
/**
* `/new`, `/continue` and `/clear` act on the conversation's session
* rather than being sent, and the page lands on the session they
* leave. `/clear` destroys messages, so it asks first. A failure puts
* the command back in the input with the reason under it (a session
* with a run in progress can't be deleted).
*/
async function runCommand({ command }: { command: ComposerCommand }) {
if (sending.current) return;
if (command.name == "clear") {
if (!session_id) {
setError("The session is still loading. Try again in a moment.");
return;
}
if (
!window.confirm(
"Delete this session and all its messages, then start a new one? This can't be undone.",
)
) {
return;
}
}
sending.current = true;
set_command_busy(true);
setError(undefined);
const lost_text = text.trim();
setText("");
history.reset();
input.clear();
const res = await postSessionApi({
path:
command.name == "new"
? "new-session"
: command.name == "continue"
? "continue-session"
: "delete-session",
body:
command.name == "clear"
? { session_id }
: { bot_id: bot.id, workspace_id },
}).catch(() => null);
if (res?.success) {
window.location.assign(
conversationHref({ bot_id: Number(bot.id), workspace_id }),
);
return;
}
sending.current = false;
set_command_busy(false);
setError(res?.msg || "That didn't work.");
if (!latest_text.current.trim()) {
setText(lost_text);
input.setMarkdown({ markdown: lost_text });
}
}
/**
* The bubble and the bot's "getting your message" row show at once, and
* the input empties, so a slow connection never holds any of it. The
@@ -335,6 +452,13 @@ export default function Composer({
async function send() {
if (!can_send || !bot.id || sending.current) return;
const command = commands[command_index] ?? commands[0];
if (command) {
await runCommand({ command });
return;
}
/**
* Held until this send comes back: a second click while the first is
* still on its way (a double tap, Enter twice, a phone that fires
@@ -480,6 +604,13 @@ export default function Composer({
onCancel={onCancelReply}
/>
) : null}
{commands.length ? (
<ComposerCommandList
commands={commands}
index={command_index}
onPick={pickCommand}
/>
) : null}
{input.menu ? <ComposerMentionList menu={input.menu} /> : null}
<Row
className={`w-full max-w-container mx-auto min-h-[88px] ${reply_to ? "pt-3 pb-7" : "py-7"} gap-3! md:gap-4! flex-nowrap items-end px-3 md:px-6 cursor-text`}
@@ -521,7 +652,7 @@ export default function Composer({
) : null}
<ComposerSendButton
disabled={!can_send}
loading={files.uploading}
loading={files.uploading || command_busy}
onClick={send}
/>
</Row>
@@ -46,6 +46,11 @@ type Props = {
* thinking row that will never move.
*/
awaiting_reply?: boolean;
/**
* The session shown was carried into a newer one: its thread is a record
* to read, so a last word of the user's isn't a reply that never came.
*/
moved_on?: boolean;
/**
* This session has an active task.
*/
@@ -102,7 +107,10 @@ type Props = {
loading: boolean;
error?: string;
loadOlder: () => void;
loadPrevious?: () => void;
/**
* The session this one carries on from, as the page that reads it.
*/
previous_session_href?: string | null;
};
};
@@ -112,9 +120,9 @@ type Props = {
* While the bot works on a reply or a task, a status row sits under the
* last one, and each request the bot has open with the crew shows where
* its bots stand until it's done. Text selected in a message can be quoted in the composer.
* Older messages load as it scrolls to the top, and at the start of a
* session that carries on from another, the earlier one can be opened
* above it (shown only, never put in the bot's prompt); the reversed column keeps
* Older messages load as it scrolls to the top, and the session before
* this one is linked above the thread as its own page (shown only, never
* put in the bot's prompt); the reversed column keeps
* the view where it was as they land above it. The thread follows new
* messages while it sits at its bottom, stays put while it's scrolled up
* and then offers a button to get back down. Pulled up past its bottom on
@@ -127,6 +135,7 @@ export default function MessageThread({
reply_progress,
receiving,
awaiting_reply,
moved_on,
session_id,
debug_open,
on_toggle_debug,
@@ -182,7 +191,9 @@ export default function MessageThread({
*/
const last_shown = shown[shown.length - 1];
const unanswered =
!awaiting_reply && !receiving && last_shown?.author == "user" ? last_shown : null;
!awaiting_reply && !receiving && !moved_on && last_shown?.author == "user"
? last_shown
: null;
const scroll = useThreadScroll({ messages: shown });
const pull_state = usePullToRefresh({
column_ref: scroll.column_ref,
@@ -215,13 +226,10 @@ export default function MessageThread({
error={older.error}
onLoad={older.loadOlder}
/>
) : older?.has_previous && older.loadPrevious ? (
) : older?.previous_session_href ? (
<OlderMessagesLoader
loading={older.loading}
error={older.error}
onLoad={older.loadPrevious}
href={older.previous_session_href}
label="Show the previous session"
manual
/>
) : null}
<SessionGalleryContext.Provider value={session_gallery}>
@@ -4,30 +4,31 @@ import Button from "@moduletrace/twui/layout/Button";
import Stack from "@moduletrace/twui/layout/Stack";
type Props = {
loading: boolean;
loading?: boolean;
error?: string;
onLoad: () => void;
onLoad?: () => void;
/**
* Opens a page instead of loading more here (the session before this
* one, read as it was).
*/
href?: string;
/**
* Defaults to "Show earlier messages".
*/
label?: string;
/**
* Loads only on a click, never as it scrolls into view.
*/
manual?: boolean;
};
/**
* The top of a thread with older messages: loads them as it scrolls into
* view (unless `manual`), with a button for when it can't (or a load
* failed).
* view, with a button for when it can't (or a load failed). With `href` it
* is only ever a link.
*/
export default function OlderMessagesLoader({
loading,
loading = false,
error,
onLoad,
href,
label = "Show earlier messages",
manual,
}: Props) {
const ref = useRef<HTMLDivElement>(null);
const load = useRef(onLoad);
@@ -37,11 +38,11 @@ export default function OlderMessagesLoader({
useEffect(() => {
const el = ref.current;
if (!el || error || manual || typeof IntersectionObserver == "undefined") return;
if (!el || href || error || typeof IntersectionObserver == "undefined") return;
const observer = new IntersectionObserver(
(entries) => {
if (entries.some((entry) => entry.isIntersecting)) load.current();
if (entries.some((entry) => entry.isIntersecting)) load.current?.();
},
{ rootMargin: "400px 0px 0px 0px" },
);
@@ -49,7 +50,7 @@ export default function OlderMessagesLoader({
observer.observe(el);
return () => observer.disconnect();
}, [error, loading, manual]);
}, [error, loading, href]);
return (
<Stack
@@ -64,6 +65,7 @@ export default function OlderMessagesLoader({
type="button"
variant="ghost"
color="text"
href={href}
onClick={onLoad}
className="text-[13px]! leading-[18px]! text-ink-secondary"
>
@@ -41,6 +41,7 @@ import useOlderMessages from "../(hooks)/use-older-messages";
import ConversationHeader from "../(partials)/conversation-header";
import useDebugOpen from "../(hooks)/use-debug-open";
import MessageThread from "../(partials)/message-thread";
import conversationHref from "@/src/utils/conversation-href";
import Composer, { type ComposerHandle } from "../(partials)/composer";
/**
* A computer's live screen (noVNC, its websocket and transport) is only
@@ -110,6 +111,14 @@ export default function Conversation() {
* session, which the composer gives way to a link to.
*/
const [moved_to_session_id, setMovedToSessionId] = useState<number | null>(null);
/**
* The page was opened on one session (`?session_id=`) rather than the
* live conversation: that's the way back into an old thread, so it
* stays there even when that session was carried on into a newer one.
*/
const pinned_session = useRef(
typeof window != "undefined" && new URLSearchParams(window.location.search).has("session_id"),
).current;
/**
* How many replies the session still has to come, as the last catch-up
* read found them, or null while that isn't known yet. A reply that ends
@@ -324,6 +333,14 @@ export default function Conversation() {
running: Boolean(progress.task_id) || Boolean(open_reply_jobs),
last_message_id: last_saved_id,
on_open_jobs: ({ open_jobs }) => setOpenReplyJobs(open_jobs),
/**
* A carry whose push the page missed: the live conversation goes to
* the session that answers, rather than waiting on this one for
* ever. A pinned read stays where it is, as the push path does.
*/
on_moved_to: () => {
if (!pinned_session) history.retry();
},
});
/**
@@ -403,15 +420,14 @@ export default function Conversation() {
) {
/**
* This session's conversation was carried into a new one,
* whose summary opens it. While the user's message is on
* its way, it was that message (the rollover at the
* session length): the thread follows into the new
* session. Otherwise (the bot, Continue in new session in
* another tab) the composer gives way to a link there.
* whose summary opens it. The live page follows it without
* a word (the bot's answer lands there, and a rollover's
* message on its way goes there too); a page opened on this
* session keeps its thread and offers the way on instead.
*/
if (Number(message.carried_from_session_id) == session_id) {
if (pending_messages.length) {
following_send.current = true;
if (pending_messages.length || !pinned_session) {
following_send.current = Boolean(pending_messages.length);
history.retry();
return;
}
@@ -568,6 +584,14 @@ export default function Conversation() {
* The thread, kept intact so the stop control can wrap it without
* reindenting every provider.
*/
const previous_session_href = older.previous_session_id
? conversationHref({
bot_id: Number(bot?.id) || 0,
workspace_id,
session_id: older.previous_session_id,
})
: null;
const thread = (
<CrewBotsContext.Provider value={bots}>
<CrewWorkspacesContext.Provider value={workspaces}>
@@ -610,6 +634,7 @@ export default function Conversation() {
reply_progress={reply_progress}
receiving={pending_messages.length > 0}
awaiting_reply={awaiting_reply}
moved_on={Boolean(moved_to_session_id)}
has_task={Boolean(progress.task_id)}
rerun_message_id={rerun_after_id}
session_id={session_id}
@@ -622,7 +647,7 @@ export default function Conversation() {
<NoModelNotice bot_name={live_bot.name || "This bot"} />
) : null
}
older={older}
older={{ ...older, previous_session_href }}
onReload={reload_conversation}
onQuote={({ text }) =>
composer.current?.insertQuote({ text })
@@ -0,0 +1,29 @@
import { describe, expect, test } from "bun:test";
import composerCommandMatches from "./composer-command-matches";
const names = ({ text }: { text: string }) =>
composerCommandMatches({ text }).map((command) => command.name);
describe("composerCommandMatches", () => {
test("a lone slash offers every command", () => {
expect(names({ text: "/" })).toEqual(["new", "continue", "clear"]);
});
test("narrows by the letters typed", () => {
expect(names({ text: "/c" })).toEqual(["continue", "clear"]);
expect(names({ text: "/ne" })).toEqual(["new"]);
expect(names({ text: "/new" })).toEqual(["new"]);
});
test("ignores the case and the space around it", () => {
expect(names({ text: " /NEW " })).toEqual(["new"]);
});
test("an ordinary message that starts with a slash matches none", () => {
expect(names({ text: "/etc/hosts is missing" })).toEqual([]);
expect(names({ text: "/news" })).toEqual([]);
expect(names({ text: "/new please" })).toEqual([]);
expect(names({ text: "message" })).toEqual([]);
expect(names({ text: "" })).toEqual([]);
});
});
@@ -0,0 +1,17 @@
import { ComposerCommands, type ComposerCommand } from "../(data)/composer-commands";
/**
* The slash commands the composer's text is asking for: all of them while
* it is just `/`, then those the letters typed so far begin. Anything else
* (`/etc/hosts`, a command followed by more words) is an ordinary message
* and matches none.
*/
export default function composerCommandMatches({ text }: { text: string }): ComposerCommand[] {
const match = /^\/([a-z]*)$/i.exec(text.trim());
if (!match) return [];
const typed = (match[1] ?? "").toLowerCase();
return ComposerCommands.filter((command) => command.name.startsWith(typed));
}
@@ -21,6 +21,7 @@ const PollMs = 4000;
*/
export default function useKnowledgebaseDocuments({ knowledgebase_id }: Params) {
const [documents, setDocuments] = useState<KnowledgebaseDocument[]>();
const [embedding_model, setEmbeddingModel] = useState<string | null>(null);
const [busy, setBusy] = useState(false);
const [status, setStatus] = useState<Status>();
@@ -30,8 +31,10 @@ export default function useKnowledgebaseDocuments({ knowledgebase_id }: Params)
body: { knowledgebase_id },
});
if (res.success && res.singleRes) setDocuments(res.singleRes.documents);
else setStatus({ error: true, msg: res.msg || "Couldn't load the documents." });
if (res.success && res.singleRes) {
setDocuments(res.singleRes.documents);
setEmbeddingModel(res.singleRes.embedding_model);
} else setStatus({ error: true, msg: res.msg || "Couldn't load the documents." });
};
useEffect(() => {
@@ -62,6 +65,7 @@ export default function useKnowledgebaseDocuments({ knowledgebase_id }: Params)
}
setDocuments(res.singleRes.documents);
setEmbeddingModel(res.singleRes.embedding_model);
setStatus({ success: true, msg: res.msg || "Saved." });
return true;
};
@@ -116,5 +120,5 @@ export default function useKnowledgebaseDocuments({ knowledgebase_id }: Params)
});
};
return { documents, busy, status, upload, saveText, remove, retry };
return { documents, embedding_model, busy, status, upload, saveText, remove, retry };
}
@@ -12,6 +12,11 @@ type Props = {
document: KnowledgebaseDocument;
embedding_model: string | null;
busy?: boolean;
/**
* Reads the document over the list: its text, and the original behind
* "Open original".
*/
onOpen?: () => void;
/**
* Opens a text document to edit; not given for a file or when the user
* can't edit.
@@ -28,11 +33,12 @@ type Props = {
* One document in a knowledgebase: what it is and how much of it bots can
* search, or why it couldn't be read.
*/
export default function KnowledgebaseDocumentRow({ document, embedding_model, busy, onEdit, onRetry, onDelete }: Props) {
export default function KnowledgebaseDocumentRow({ document, embedding_model, busy, onOpen, onEdit, onRetry, onDelete }: Props) {
return (
<SettingsListRow
avatar={<IconTile Icon={document.source == "text" ? NotebookPen : FileText} />}
title={document.name}
onOpen={onOpen}
title_icon={
<IndexStateMark
state={knowledgebaseIndexState({
@@ -0,0 +1,127 @@
import { useEffect, useState } from "react";
import Loading from "@moduletrace/twui/elements/Loading";
import Modal from "@moduletrace/twui/elements/Modal";
import Button from "@moduletrace/twui/layout/Button";
import H2 from "@moduletrace/twui/layout/H2";
import Row from "@moduletrace/twui/layout/Row";
import Span from "@moduletrace/twui/layout/Span";
import Stack from "@moduletrace/twui/layout/Stack";
import { FileText } from "lucide-react";
import FilePreviewCode from "@/src/components/general/file-preview-code";
import FilePreviewMarkdown from "@/src/components/general/file-preview-markdown";
import FilePreviewModal from "@/src/components/general/file-preview-modal";
import TopModalEscape from "@/src/components/general/top-modal-escape";
import { AppData } from "@/src/data/app-data";
import postAdminApi from "@/src/layouts/bots/(functions)/post-admin-api";
import type { KnowledgebaseDocument } from "@/src/types";
import SettingsStatus from "../../(partials)/settings-status";
type Props = {
document: KnowledgebaseDocument;
onClose: () => void;
};
/**
* One document over its list, read-only: the text bots search, written in
* or read from its file (markdown rendered, extracted text as it is), with
* the original a click away.
*/
export default function KnowledgebaseDocumentView({ document, onClose }: Props) {
const [text, set_text] = useState<{ content: string; truncated: boolean }>();
const [error, set_error] = useState<string>();
const [original, set_original] = useState(false);
useEffect(() => {
let live = true;
postAdminApi<{ content: string; truncated: boolean }>({
path: "knowledgebases/document-text",
body: { document_id: document.id },
}).then((res) => {
if (!live) return;
if (res.success && res.singleRes) set_text({ content: res.singleRes.content, truncated: res.singleRes.truncated });
else set_error(res.msg || "Couldn't open the document.");
});
return () => {
live = false;
};
}, [document.id]);
return (
<>
<Modal
open
setOpen={(next) => {
if (!next) onClose();
}}
className="max-w-[860px]! w-[95vw] h-[85vh] p-0 bg-paper flex flex-col overflow-hidden"
>
<TopModalEscape onClose={onClose} />
<Stack className="w-full min-w-0 gap-1! items-stretch pl-5 pr-14 py-3 border-0 border-b border-solid border-hairline">
<Row className="w-full gap-3! flex-wrap sm:flex-nowrap items-center">
<Stack className="grow min-w-0 gap-0! items-stretch">
<H2
title={document.name}
className="text-base! leading-6! tracking-normal! font-bold text-ink truncate min-w-0"
>
{document.name}
</H2>
{text?.truncated ? (
<Span className="text-xs leading-4 text-ink-secondary">
Showing its first {AppData.KnowledgebaseTextMaxChars.toLocaleString()} characters. Open
the original to read the rest.
</Span>
) : null}
</Stack>
{document.media_id ? (
<Button
title={`Open the original of ${document.name}`}
type="button"
variant="ghost"
color="gray"
size="small"
onClick={() => set_original(true)}
beforeIcon={<FileText size={16} aria-hidden />}
className="shrink-0 gap-1!"
>
Open original
</Button>
) : null}
</Row>
</Stack>
{error ? (
<Stack className="w-full p-5 items-start">
<SettingsStatus status={{ error: true, msg: error }} />
</Stack>
) : !text ? (
<Stack className="w-full grow items-center justify-center">
<Loading />
</Stack>
) : !text.content.trim() ? (
<Stack className="w-full p-5 items-start">
<Span className="text-[13px] leading-[18px] text-ink-secondary">
{document.source == "text"
? "This document has no text yet."
: "No text could be read from its file. Open the original to read it."}
</Span>
</Stack>
) : document.source == "text" ? (
<FilePreviewMarkdown text={text.content} />
) : (
<FilePreviewCode text={text.content} />
)}
</Modal>
{original && document.media_id ? (
<FilePreviewModal
name={document.name}
url={`/media/${document.media_id}`}
media_type="document"
size={document.size}
onClose={() => set_original(false)}
/>
) : null}
</>
);
}
@@ -5,25 +5,24 @@ import Row from "@moduletrace/twui/layout/Row";
import { NotebookPen, Upload } from "lucide-react";
import { BotTextFileExtensions } from "@/src/dict/bot-file-dict";
import AddModalShell from "@/src/layouts/bots/(partials)/add-modal-shell";
import type { PublicKnowledgebase } from "@/src/types";
import type { KnowledgebaseDocument, PublicKnowledgebase } from "@/src/types";
import SettingsList from "../../(partials)/settings-list";
import SettingsStatus from "../../(partials)/settings-status";
import useKnowledgebaseDocuments from "../(hooks)/use-knowledgebase-documents";
import KnowledgebaseDocumentRow from "./knowledgebase-document-row";
import KnowledgebaseDocumentView from "./knowledgebase-document-view";
import KnowledgebaseTextForm from "./knowledgebase-text-form";
type Props = {
knowledgebase: PublicKnowledgebase;
/**
* Its id and name are all the list needs: the composer opens it too.
*/
knowledgebase: Pick<PublicKnowledgebase, "id" | "name">;
/**
* A super admin: adds, writes and deletes documents. Admins only read
* the list.
*/
can_edit: boolean;
/**
* The install's embedding model, to tell a document that needs
* re-indexing.
*/
embedding_model: string | null;
onClose: () => void;
};
@@ -31,16 +30,20 @@ type Props = {
* A knowledgebase's documents: each with how much of it is searchable,
* files to upload, and text to write straight in. A document is read
* (chunked and embedded) in the background; the list follows until it's
* done.
* done. Clicking one reads it over the list.
*/
export default function KnowledgebaseDocumentsModal({ knowledgebase, can_edit, embedding_model, onClose }: Props) {
const { documents, busy, status, upload, saveText, remove, retry } = useKnowledgebaseDocuments({
export default function KnowledgebaseDocumentsModal({ knowledgebase, can_edit, onClose }: Props) {
const { documents, embedding_model, busy, status, upload, saveText, remove, retry } = useKnowledgebaseDocuments({
knowledgebase_id: knowledgebase.id,
});
/**
* `new` writes a text document, a number edits that one.
*/
const [writing, setWriting] = useState<"new" | number>();
/**
* The document read over the list.
*/
const [viewing, set_viewing] = useState<KnowledgebaseDocument>();
const file_input = useRef<HTMLInputElement>(null);
if (writing) {
@@ -63,76 +66,84 @@ export default function KnowledgebaseDocumentsModal({ knowledgebase, can_edit, e
}
return (
<AddModalShell
open
setOpen={(next) => !next && onClose()}
title={`Documents in ${knowledgebase.name}`}
description={`Upload ${BotTextFileExtensions.join(", ")} files, or write text straight in. Each is split into passages bots search.`}
>
{documents ? (
<SettingsList is_empty={!documents.length} empty="No documents yet.">
{documents.map((document) => (
<KnowledgebaseDocumentRow
key={document.id}
document={document}
embedding_model={embedding_model}
busy={busy}
onEdit={can_edit && document.source == "text" ? () => setWriting(document.id) : undefined}
onRetry={
can_edit && document.ingest_error && !document.indexing
? () => retry({ document })
: undefined
}
onDelete={can_edit ? () => remove({ document }) : undefined}
<>
<AddModalShell
open
setOpen={(next) => !next && onClose()}
title={`Documents in ${knowledgebase.name}`}
description={
can_edit
? `Upload ${BotTextFileExtensions.join(", ")} files, or write text straight in. Each is split into passages bots search. Click a document to read it.`
: "Each is split into passages bots search. Click a document to read it."
}
>
{documents ? (
<SettingsList is_empty={!documents.length} empty="No documents yet.">
{documents.map((document) => (
<KnowledgebaseDocumentRow
key={document.id}
document={document}
embedding_model={embedding_model}
busy={busy}
onOpen={() => set_viewing(document)}
onEdit={can_edit && document.source == "text" ? () => setWriting(document.id) : undefined}
onRetry={
can_edit && document.ingest_error && !document.indexing
? () => retry({ document })
: undefined
}
onDelete={can_edit ? () => remove({ document }) : undefined}
/>
))}
</SettingsList>
) : (
<Loading />
)}
{can_edit ? (
<Row className="gap-1!">
<input
ref={file_input}
type="file"
multiple
accept={BotTextFileExtensions.map((ext) => `.${ext}`).join(",")}
className="hidden"
onChange={(event) => {
const files = Array.from(event.target.files || []);
upload({ files }).catch(() => {});
event.target.value = "";
}}
/>
))}
</SettingsList>
) : (
<Loading />
)}
{can_edit ? (
<Row className="gap-1!">
<input
ref={file_input}
type="file"
multiple
accept={BotTextFileExtensions.map((ext) => `.${ext}`).join(",")}
className="hidden"
onChange={(event) => {
const files = Array.from(event.target.files || []);
upload({ files }).catch(() => {});
event.target.value = "";
}}
/>
<Button
title="Upload files"
type="button"
variant="ghost"
color="gray"
size="small"
loading={busy}
onClick={() => file_input.current?.click()}
beforeIcon={<Upload size={14} aria-hidden />}
className="gap-1!"
>
Upload files
</Button>
<Button
title="Write a document"
type="button"
variant="ghost"
color="gray"
size="small"
disabled={busy}
onClick={() => setWriting("new")}
beforeIcon={<NotebookPen size={14} aria-hidden />}
className="gap-1!"
>
Write a document
</Button>
</Row>
) : null}
<SettingsStatus status={status} />
</AddModalShell>
<Button
title="Upload files"
type="button"
variant="ghost"
color="gray"
size="small"
loading={busy}
onClick={() => file_input.current?.click()}
beforeIcon={<Upload size={14} aria-hidden />}
className="gap-1!"
>
Upload files
</Button>
<Button
title="Write a document"
type="button"
variant="ghost"
color="gray"
size="small"
disabled={busy}
onClick={() => setWriting("new")}
beforeIcon={<NotebookPen size={14} aria-hidden />}
className="gap-1!"
>
Write a document
</Button>
</Row>
) : null}
<SettingsStatus status={status} />
</AddModalShell>
{viewing ? <KnowledgebaseDocumentView document={viewing} onClose={() => set_viewing(undefined)} /> : null}
</>
);
}
@@ -22,7 +22,7 @@ type Props = {
knowledgebase: PublicKnowledgebase;
targets: ExtensionTargets;
/**
* The install's embedding model, for the documents' lines.
* The install's embedding model, for its index mark.
*/
embedding_model: string | null;
onChanged: (overview: KnowledgebasesOverviewPayload, msg: string) => void;
@@ -167,7 +167,6 @@ export default function KnowledgebaseRow({ selected, onSelected, knowledgebase,
<KnowledgebaseDocumentsModal
knowledgebase={knowledgebase}
can_edit={targets.can_edit}
embedding_model={embedding_model}
onClose={closeDocuments}
/>
) : null}
@@ -0,0 +1,30 @@
import { describe, expect, test } from "bun:test";
import { renderToString } from "react-dom/server";
import HarnessGuessedModelNote from "./harness-guessed-model-note";
import type { HarnessModelOption } from "@/src/types";
const model = (capabilities_guessed?: boolean): HarnessModelOption => ({
id: 908359,
provider_id: 12,
provider_name: "Liquid AI",
slug: "lfm3-vl-2b",
name: "lfm3-vl-2b",
free: false,
capabilities_guessed,
});
describe("HarnessGuessedModelNote", () => {
test("says the capabilities are guessed for a model listed by id only", () => {
const html = renderToString(<HarnessGuessedModelNote model={model(true)} />);
expect(html).toContain("lists model ids only");
expect(html).toContain("lfm3-vl-2b");
expect(html).toContain("never calls tools");
});
test("says nothing for a model whose catalog declared its capabilities", () => {
expect(renderToString(<HarnessGuessedModelNote model={model(false)} />)).toBe("");
expect(renderToString(<HarnessGuessedModelNote model={model()} />)).toBe("");
expect(renderToString(<HarnessGuessedModelNote />)).toBe("");
});
});
@@ -0,0 +1,25 @@
import Span from "@moduletrace/twui/layout/Span";
import type { HarnessModelOption } from "@/src/types";
type Props = {
model?: HarnessModelOption;
};
/**
* A word when the picked text model's capabilities were guessed: only
* OpenRouter's catalog says what a model takes, so every other provider is
* listed by id and read from its name (`guessModelModalities`), which always
* answers that it calls tools. Said out loud because a vision model was
* pinned this way as a worker's text model and answered every reply as prose
* that never closed with `send_reply`: the run failed, and nothing on the
* page said the model was never a tool-caller.
*/
export default function HarnessGuessedModelNote({ model }: Props) {
if (!model?.capabilities_guessed) return null;
return (
<Span className="text-[13px] leading-[18px] text-ink-secondary">
{`${model.provider_name} lists model ids only, so ${model.name}'s capabilities are guessed from its name: nothing here can tell that it takes images, or that it never calls tools. A model that can't drive a run fails quietly (answers that end as drafts, reports that never close), so watch its first runs and unpin it if the bot stops calling tools. OpenRouter is the one provider whose catalog says what each model takes.`}
</Span>
);
}
@@ -0,0 +1,44 @@
import { describe, expect, test } from "bun:test";
import { renderToString } from "react-dom/server";
import HarnessReferenceModelNote from "./harness-reference-model-note";
const model = (name: string, input_modalities: string[]) => ({
id: 1,
provider_id: 1,
provider_name: "OpenRouter",
slug: name.toLowerCase().replace(/ /g, "-"),
name,
free: true,
input_modalities,
});
describe("HarnessReferenceModelNote", () => {
test("names where a reference call goes when the pick can't take one", () => {
const html = renderToString(
<HarnessReferenceModelNote
model={model("Recraft V4.1", ["text"])}
reference_model={model("qwen-image-3.0-pro", ["text", "image"])}
/>,
);
expect(html).toContain("Recraft V4.1 can");
expect(html).toContain("reference images");
expect(html).toContain("qwen-image-3.0-pro");
});
test("says a model must be picked when Image editing has none", () => {
expect(renderToString(<HarnessReferenceModelNote model={model("Recraft", ["text"])} />)).toContain(
"needs a model picked under Image editing",
);
});
test("says nothing for a model that takes references", () => {
expect(
renderToString(<HarnessReferenceModelNote model={model("Gemini Image", ["text", "image"])} />),
).toBe("");
});
test("says nothing when there's no model to judge", () => {
expect(renderToString(<HarnessReferenceModelNote />)).toBe("");
});
});
@@ -0,0 +1,32 @@
import Span from "@moduletrace/twui/layout/Span";
import type { HarnessModelOption } from "@/src/types";
type Props = {
/**
* The model the Image setting uses now.
*/
model?: HarnessModelOption;
/**
* Image editing's current model: where a call with a reference goes while
* the image pick can't take one.
*/
reference_model?: HarnessModelOption;
};
/**
* A word on a model that can't take a reference image: every call that passes
* one goes to Image editing instead, so the pick isn't the model that answers.
* Recraft was picked a minute before a run spent 29 minutes on the old qwen
* edit pick, and nothing on this page said so.
*/
export default function HarnessReferenceModelNote({ model, reference_model }: Props) {
if (!model || model.input_modalities?.includes("image")) return null;
return (
<Span className="text-[13px] leading-[18px] text-ink-secondary">
{reference_model
? `${model.name} can't take reference images, so a request with one (recreating or reworking an image) uses Image editing's model, ${reference_model.name}.`
: `${model.name} can't take reference images, so a request with one needs a model picked under Image editing.`}
</Span>
);
}
@@ -1,14 +1,16 @@
import { harnessFallbackTitle } from "@/src/dict/harness-dict";
import type { HarnessFormValue, HarnessOverview } from "@/src/types";
import type { HarnessFormValue, HarnessModelOption, HarnessOverview } from "@/src/types";
import SettingsGroup from "../../(partials)/settings-group";
import harnessDefaultName from "../(utils)/harness-default-name";
import nextHarnessModelValue from "../(utils)/next-harness-model-value";
import nextHarnessProviderValue from "../(utils)/next-harness-provider-value";
import HarnessCurrentModel from "./harness-current-model";
import HarnessGuessedModelNote from "./harness-guessed-model-note";
import HarnessModelSelect from "./harness-model-select";
import HarnessOptionsCheckboxes from "./harness-options-checkboxes";
import HarnessParamsButton from "./harness-params-button";
import HarnessProviderSelect from "./harness-provider-select";
import HarnessReferenceModelNote from "./harness-reference-model-note";
import HarnessTextFallbacks from "./harness-text-fallbacks";
import HarnessVoiceControls from "./harness-voice-controls";
import HarnessWindowNote from "./harness-window-note";
@@ -17,13 +19,18 @@ type Props = {
harness: HarnessOverview;
value: HarnessFormValue;
onChange: (value: HarnessFormValue) => void;
/**
* Image editing's current model, for the Image group's note about
* reference images.
*/
reference_model?: HarnessModelOption;
};
/**
* One harness: its provider, its model, text fallback models,
* automatic fallback options, and voice controls for speech.
*/
export default function HarnessSettingGroup({ harness, value, onChange }: Props) {
export default function HarnessSettingGroup({ harness, value, onChange, reference_model }: Props) {
const id = `harness-${harness.harness}`;
const provider = harness.providers.find((p) => p.id == value.provider_id);
const models = value.provider_id
@@ -31,6 +38,8 @@ export default function HarnessSettingGroup({ harness, value, onChange }: Props)
: harness.models;
const picked = models.find((model) => model.id == value.model_id);
const on_bot_page = harness.default !== undefined;
/** The model this row's settings would show the user the truth about. */
const shown = value.inherit ? harness.default?.current : picked || harness.current;
const falls_back_title = harnessFallbackTitle({ harness: harness.harness });
const default_name = harnessDefaultName({
harness_default: harness.default,
@@ -67,18 +76,27 @@ export default function HarnessSettingGroup({ harness, value, onChange }: Props)
onChange={(model_id) => onChange(nextHarnessModelValue({ value, model_id }))}
/>
)}
{harness.harness == "image" ? (
<HarnessReferenceModelNote
model={shown}
reference_model={reference_model}
/>
) : null}
<HarnessTextFallbacks id={id} harness={harness} value={value} onChange={onChange} />
<HarnessCurrentModel
harness={value.inherit && harness.default ? { ...harness, ...harness.default } : harness}
/>
{harness.harness == "text" ? (
<HarnessWindowNote model={value.inherit ? harness.default?.current : picked || harness.current} />
<>
<HarnessWindowNote model={shown} />
<HarnessGuessedModelNote model={shown} />
</>
) : null}
<HarnessOptionsCheckboxes
harness={harness}
value={value}
provider={provider}
model={value.inherit ? harness.default?.current : picked || harness.current}
model={shown}
falls_back_title={falls_back_title}
onChange={onChange}
/>

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