Compare commits

...
13 Commits
Author SHA1 Message Date
tbenandClaude Opus 5.5 66bdcff208 Bump version to 0.28.20
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-30 10:26:12 +01:00
tbenandClaude Opus 5.5 d2d250e426 Render bot- and user-written markdown everywhere instead of raw text
TaskMarkdown becomes the shared MarkdownText (with a boxed, scrolling
variant). Proposal briefs, runbooks and prompts, card reasons and
research, plan goals and steps, questions, a hook's brief and the bot
panel's instructions and memory now render through it; code-like values
stay word for word.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-30 10:26:06 +01:00
tbenandClaude Opus 5.5 a569483456 Show the absolute folder a hook's runner starts in
runner_dir is relative to the bot's folder, not a run's ~, and a bare
"whatsapp" led a bot to point its runner at a folder that never
existed. The proposal card, list_hooks and propose_hook now give the
full path (hookRunnerStartPath, resolved like syncHookRunners), and the
form's help text explains the difference.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-30 10:26:06 +01:00
tbenandClaude Opus 5.5 ef0237ecf0 Bump version to 0.28.19
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-30 09:25:57 +01:00
tbenandClaude Opus 5.5 02c49a3c9b Show why a hook's runner check failed, to the user and to the bot
The hook row and modal name the failure and when the runner was last
checked, and list_hooks describes the runner, its folder (inside the
bot's folder, not ~) and a failed check, pointing at propose_hook rather
than a process started by hand. Also reword Run silently: every hook has
its own thread, the setting is whether a run takes the conversation over.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-30 09:25:57 +01:00
tbenandClaude Opus 5.5 f7ac9dbb08 Bump version to 0.28.18
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-30 05:06:13 +01:00
tbenandClaude Opus 5.5 a8e2c891a4 List the whole crew in the coordinator's Crew tab on a workspace page
The tab read the page's crew, which in a workspace is only that
workspace's bots, so a bot needing the user elsewhere went unlisted.
In a workspace it now reads the whole crew itself (useWholeCrew) and
keeps it current from face pushes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-30 05:03:10 +01:00
tbenandClaude Opus 5.5 8a75bb2a43 Open a session of its own for each started task hand-over, with the result reported back
A started hand-over (delegate_task with a new brief, or a task handed over with
start: true) used to queue its run in whatever session the target bot was on.
It now goes through startHandOverRun: a new session titled from the work, and,
when a bot handed it over, a bot_asks row of kind hand_over (no gate, the
user's quote is the say-so). The target gets the back bar, update_requester
and answer_requester, and its report goes back to and wakes the bot that
handed it over, as a crew request's answer does. Hand-overs don't count
toward the open-request cap, aren't stopped with the run that handed them
over, and show the task's own working row. The thread no longer calls a
hand-over's opening brief unanswered while its task is queued.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-30 04:56:40 +01:00
tbenandClaude Opus 5.5 f98b9391b0 Archive a consistent database snapshot instead of the live file in data backups
tar exited 1 with "./db/cobble: file changed as we read it" on every
production export. The database now goes in as a VACUUM INTO copy, the
live file and its journal are left out, and tar's exit 1 (a file changed
mid-read, archive still whole) counts as success.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-30 04:24:48 +01:00
tbenandClaude Opus 5.5 9cc7359334 Add a Crew tab to the coordinator's panel linking bots that need you to their chat
Faces now record the workspace of the job that set them
(bot_user_faces.workspace_id), so each worker that needs the user or is
working links to the right chat: its workspace conversation or its own.
Existing faces are placed at boot from each bot's latest job.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-30 04:11:59 +01:00
tbenandClaude Opus 5.5 05d8f9e9da Show the bot's id in its panel header
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-30 02:31:52 +01:00
tbenandClaude Opus 5.5 a9fe487cbd Bump version to 0.28.17
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-30 02:04:26 +01:00
tbenandClaude Opus 5.5 435e080c06 Fix plan last steps, task hand-offs, card retries and failure notices from production
- A plan's last step ends with its report alone: the review no longer asks
  for a "Finish the plan" card that contradicted complete_plan_step.
- Retry on a failed plan step resumes the plan and re-runs that step.
- A task run handing work on is no longer refused against its own job.
- "handed to [bot:N]" status lines no longer read as work under way.
- A refused card gets its own note, keeps the message written beside it,
  and gets one more turn once it goes up; ask_user reads {label} options
  and JSON-string questions.
- Failure notices name the closing failure instead of blaming the review.
- A reply claiming the plan is over while the record disagrees is sent back.
- A provider's content-filter refusal fails the run at once with a clear
  message.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-30 02:04:26 +01:00
112 changed files with 2421 additions and 370 deletions
+13 -10
View File
File diff suppressed because one or more lines are too long
+13 -1
View File
@@ -52,7 +52,7 @@ import {
CustomToolKinds,
CustomToolStatuses,
} from "@/src/dict/custom-tool-dict";
import { AskStatuses } from "@/src/dict/ask-dict";
import { AskKinds, AskStatuses } from "@/src/dict/ask-dict";
import {
TaskAuthors,
TaskMediaKinds,
@@ -402,6 +402,13 @@ const schema: BUN_SQLITE_DatabaseSchemaType = {
fieldDescription: `The asked bot's session before the request opened one of its own, so its conversation can offer the way back. Not a foreign key`,
dataType: "INTEGER",
},
{
fieldName: "kind",
fieldDescription: `What opened it: \`ask\` (ask_bot, through the coordinator's gate) or \`hand_over\` (a task handed over and started on the user's own words, so no gate)`,
dataType: "TEXT",
options: AskKinds.map((k) => k.value),
defaultValue: "ask",
},
],
indexes: [
{
@@ -2675,6 +2682,11 @@ const schema: BUN_SQLITE_DatabaseSchemaType = {
fieldDescription: `Short status sentence, e.g. "Waiting on you"`,
dataType: "TEXT",
},
{
fieldName: "workspace_id",
fieldDescription: `The workspace of the conversation whose job set this face, null for the bot's own chat (or a face no job set). Not a foreign key: it only says which chat the coordinator's Crew list links to`,
dataType: "INTEGER",
},
],
uniqueConstraints: [
{
+8
View File
@@ -336,6 +336,10 @@ export type BUN_SQLITE_COBBLE_BOT_ASKS = {
* The asked bot's session before the request opened one of its own, so its conversation can offer the way back. Not a foreign key
*/
previous_session_id?: number | "";
/**
* What opened it: `ask` (ask_bot, through the coordinator's gate) or `hand_over` (a task handed over and started on the user's own words, so no gate)
*/
kind?: "ask" | "hand_over" | "";
}
export type BUN_SQLITE_COBBLE_BOT_SESSIONS = {
@@ -1683,6 +1687,10 @@ export type BUN_SQLITE_COBBLE_BOT_USER_FACES = {
* Short status sentence, e.g. "Waiting on you"
*/
status_line?: string;
/**
* The workspace of the conversation whose job set this face, null for the bot's own chat (or a face no job set). Not a foreign key: it only says which chat the coordinator's Crew list links to
*/
workspace_id?: number | "";
}
export type BUN_SQLITE_COBBLE_BOT_MESSAGE_MEDIA = {
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "cobble",
"version": "0.28.16",
"version": "0.28.20",
"module": "index.ts",
"type": "module",
"private": true,
@@ -0,0 +1,47 @@
import { describe, expect, test } from "bun:test";
import claimsWorkUnderWay from "@/src/utils/claims-work-under-way";
import planFinishedClaimNote from "./plan-finished-claim-note";
const paused = { id: 2, status: "paused", current_step: 2, total_steps: 3 };
const active_last = { id: 2, status: "active", current_step: 2, total_steps: 3 };
describe("planFinishedClaimNote", () => {
test("a paused plan claimed as finished is sent back (job 810)", () => {
const note = planFinishedClaimNote({
plan: paused,
text: "**All tasks complete.** Plan #2 finished.",
tool_uses: [{ name: "complete_plan_step", ok: false }],
});
expect(note).toContain("Plan #2 is over");
expect(note).toContain("paused, at step 3 of 3");
expect(note).toContain("update_plan");
});
test("the run that ticked the last step may say the plan is finished", () => {
expect(
planFinishedClaimNote({
plan: active_last,
text: "Plan #2 is now complete.",
tool_uses: [{ name: "complete_plan_step", ok: true }],
}),
).toBeNull();
});
test("a step's completion is not the plan's", () => {
expect(
planFinishedClaimNote({ plan: paused, text: "Plan #2 Step 3 (cross-task wrap-up) complete.", tool_uses: [] }),
).toBeNull();
});
test("a message that claims nothing about the plan, or a run with no plan, passes", () => {
expect(planFinishedClaimNote({ plan: paused, text: "Task #8 is done.", tool_uses: [] })).toBeNull();
expect(planFinishedClaimNote({ plan: null, text: "Plan #2 finished.", tool_uses: [] })).toBeNull();
});
test("the fault note promises no work of its own", () => {
const note = planFinishedClaimNote({ plan: paused, text: "The plan is finished.", tool_uses: [] })!;
expect(claimsWorkUnderWay({ text: note })).toBe(false);
});
});
@@ -0,0 +1,50 @@
import type { HarnessToolUse } from "@/src/harness/types";
type Params = {
/**
* The plan this run sits in, as it stood when the run began: the one it
* was queued for, or the one open in its conversation.
*/
plan: { id: number; status: string; current_step: number | null; total_steps: number } | null;
text: string;
tool_uses: HarnessToolUse[];
};
/**
* "Plan #2 finished", "the plan is now complete": the plan itself claimed
* as over, never one of its steps ("Plan #2 Step 3 complete").
*/
const FinishedClaim =
/\b(?:the\s+)?plan(?:\s*#\d+)?(?:\s+(?:is|has\s+been|was|marked))?(?:\s+now)?\s+(?:finished|completed?|done)\b/i;
/**
* Sends back a reply that says the plan is over when the app's record says
* it isn't. Job 810 wrote "All tasks complete. Plan #2 finished." right
* after `complete_plan_step` refused it ("Plan #2 is paused"), and the
* conversation said the plan was done while its card said paused.
*
* A run that finished the plan's last step itself has made the claim true.
* A plan already done is not open, so it never reaches here.
*/
export default function planFinishedClaimNote({ plan, text, tool_uses }: Params) {
if (!plan || plan.status == "done") return null;
if (!FinishedClaim.test(text.replace(/[*_`]/g, ""))) return null;
const ticked = tool_uses.some((use) => use.ok && use.name == "complete_plan_step");
const on_last = plan.current_step != null && plan.current_step + 1 >= plan.total_steps;
if (ticked && on_last && plan.status == "active") return null;
const where =
plan.current_step == null
? `${plan.status}`
: `${plan.status}, at step ${plan.current_step + 1} of ${plan.total_steps}`;
const fix =
plan.status == "paused"
? `To finish it, the user resumes it on its card (or asks you to, and you use update_plan with status "active"), and its step is then worked and ticked with complete_plan_step.`
: `Finish its current step with complete_plan_step first, or write where it really stands.`;
return `Your message says Plan #${plan.id} is over, but the app's record has it ${where}. Write where the plan really stands. ${fix}`;
}
+17 -8
View File
@@ -29,16 +29,25 @@ describe("planStepReviewNote", () => {
expect(note({ uses })).toBeNull();
});
test("the last step's card offers to finish the plan", () => {
test("ticking the last step finishes the plan, so its report needs no card (jobs 809, 811)", () => {
const last = { ...plan, current_step: 2 };
const ticked = [{ name: "complete_plan_step", ok: true }];
expect(
planStepReviewNote({
plan: last,
on_step: true,
tool_uses: [{ name: "complete_plan_step", ok: true }],
}),
).toContain("Finish the plan");
expect(planStepReviewNote({ plan: last, on_step: true, tool_uses: ticked, status: "done" })).toBeNull();
expect(planStepReviewNote({ plan: last, on_step: false, tool_uses: ticked, status: "done" })).toBeNull();
});
test("the last step left unfinished is sent back to finish it, without asking for a card", () => {
const fault = planStepReviewNote({
plan: { ...plan, current_step: 2 },
on_step: true,
tool_uses: [{ name: "write_file", ok: true }],
});
expect(fault).toContain("its last step");
expect(fault).toContain("complete_plan_step");
expect(fault).toContain("no card goes with this report");
expect(fault).not.toContain("Finish the plan");
});
test("a failed finish does not pass", () => {
+16 -2
View File
@@ -61,7 +61,21 @@ export default function planStepReviewNote({ plan, on_step, tool_uses, status }:
const next = step + 1;
const last_step = next > plan.total_steps;
/**
* Ticking the last step finishes the plan (`completeBotPlanStep` sets it
* `done`), so there is nothing left for a card to move on to: the report
* alone ends it, as `complete_plan_step` tells the bot. Asking for a
* "Finish the plan" card there contradicted that answer, and every
* rewrite was refused until the job failed and the finished plan was
* paused again (jobs 809 and 811, Plan #2).
*/
if (last_step && ticked) return null;
if (last_step) {
return `This reply works step ${step} of Plan #${plan.id} ("${plan.title}"), its last step, and ended without finishing it. Do that step, not another: finish it with complete_plan_step and what it produced, then report it in two or three sentences. That finishes the plan, so no card goes with this report. If it needs the user for something first, ask that with ask_user and say the plan is holding at this step. If the plan itself is wrong, change it with update_plan. If the work has to be handed on, start it.`;
}
return on_step
? `This reply works step ${step} of Plan #${plan.id} ("${plan.title}") and ended without the step's card, so the plan has nothing to move on from. Do that step, not another: finish it with complete_plan_step and what it produced, then report it in two or three sentences, and put the card up in the same turn with ask_user. The card asks "Continue with the plan?": first option "${last_step ? "Finish the plan" : `Continue to step ${next}`}", second option "Pause the plan", then any choice the step really needs. If it needs the user for something else, ask that on the card too. If the plan itself is wrong, change it with update_plan. If the work has to be handed on, start it. Don't write a plan of your own in a file, and don't answer with a different piece of the work.`
: `This reply finished step ${step} of Plan #${plan.id} ("${plan.title}") with complete_plan_step but ended without the step's card, so the plan has nothing to move on from. Keep the report and put the card up in the same turn with ask_user: it asks "Continue with the plan?", first option "${last_step ? "Finish the plan" : `Continue to step ${next}`}", second option "Pause the plan". Don't take the tick back and don't work another step here.`;
? `This reply works step ${step} of Plan #${plan.id} ("${plan.title}") and ended without the step's card, so the plan has nothing to move on from. Do that step, not another: finish it with complete_plan_step and what it produced, then report it in two or three sentences, and put the card up in the same turn with ask_user. The card asks "Continue with the plan?": first option "Continue to step ${next}", second option "Pause the plan", then any choice the step really needs. If it needs the user for something else, ask that on the card too. If the plan itself is wrong, change it with update_plan. If the work has to be handed on, start it. Don't write a plan of your own in a file, and don't answer with a different piece of the work.`
: `This reply finished step ${step} of Plan #${plan.id} ("${plan.title}") with complete_plan_step but ended without the step's card, so the plan has nothing to move on from. Keep the report and put the card up in the same turn with ask_user: it asks "Continue with the plan?", first option "Continue to step ${next}", second option "Pause the plan". Don't take the tick back and don't work another step here.`;
}
+5 -2
View File
@@ -146,10 +146,13 @@ export default async function processBotJob({
* it to idle, and a late `working` or `asleep` would push over that and
* leave a bot that shows work with nothing behind it.
*/
const setFace = async (face: Omit<Parameters<typeof setBotFace>[0], "bot_id" | "user_id">) => {
const setFace = async (face: Omit<Parameters<typeof setBotFace>[0], "bot_id" | "user_id" | "workspace_id">) => {
if (!user_id || unattended || controller.signal.aborted) return;
await pushBotNotice({ bot_id, bot: await setBotFace({ bot_id, user_id, ...face }) });
await pushBotNotice({
bot_id,
bot: await setBotFace({ bot_id, user_id, workspace_id: job.workspace_id || null, ...face }),
});
};
/**
+5 -1
View File
@@ -86,6 +86,7 @@ import stripAppRecords from "@/src/utils/strip-app-records";
import hasUnansweredMessage from "./has-unanswered-message";
import reviewRunAnswer from "./review-run-answer";
import planStepReviewNote from "./plan-step-review";
import planFinishedClaimNote from "./plan-finished-claim-note";
import cancelBotJob from "@/src/functions/backend/db/bots-queue/cancel-bot-job";
import grabAnsweredMessageId from "@/src/functions/backend/db/bots-queue/grab-answered-message-id";
import grabRetryFailure from "@/src/functions/backend/db/bots-queue/grab-retry-failure";
@@ -730,7 +731,10 @@ export default async function runBotReply({
reviewRunAnswer({ bot_id: bot.id!, user_id, session_id, scopes, job_id: job.id, plan_mode })({ text, tool_uses, status }).then((note) => {
if (note) return note;
return planStepReviewNote({ plan, on_step: on_plan_step, tool_uses, status });
return (
planStepReviewNote({ plan, on_step: on_plan_step, tool_uses, status }) ??
planFinishedClaimNote({ plan, text, tool_uses })
);
});
const result = await runTextLoop({
+6 -1
View File
@@ -96,6 +96,7 @@ import ScheduledRunFailedError from "./scheduled-run-failed-error";
import BotJobFatalError from "./bot-job-fatal-error";
import reviewRunAnswer from "./review-run-answer";
import planStepReviewNote from "./plan-step-review";
import planFinishedClaimNote from "./plan-finished-claim-note";
import deleteBotQuestion from "@/src/functions/backend/db/bot-questions/delete-bot-question";
import type { BotJobContext, BotJobOutcome } from "./types";
import computerRunDirs from "@/src/utils/computer-work-dirs";
@@ -847,6 +848,7 @@ export default async function runBotTask({
session_id,
computers,
message_id: job.message_id || undefined,
job_id: job.id,
run_kind: browser_run_kind,
plan_id: on_plan_step ? plan?.id : null,
}),
@@ -915,7 +917,10 @@ export default async function runBotTask({
}).then((note) => {
if (note) return note;
return planStepReviewNote({ plan: plan ?? session_plan, on_step: on_plan_step, tool_uses, status });
return (
planStepReviewNote({ plan: plan ?? session_plan, on_step: on_plan_step, tool_uses, status }) ??
planFinishedClaimNote({ plan: plan ?? session_plan, text, tool_uses })
);
}),
/**
* A report goes out only through `send_reply`, so it can't say
+34 -1
View File
@@ -1,5 +1,16 @@
import { describe, expect, test } from "bun:test";
import { closingNoTextNote, closingToolGoneNote, replyDraftNote, replyNoTextNote } from "@/src/data/harness-prompts";
import {
closingNoTextNote,
closingToolGoneNote,
replyCardFailedNote,
replyCardOnlyFailedNote,
replyClosingFailedNote,
replyClosingMixedNote,
replyClosingRequiredNote,
replyDraftNote,
replyNoTextNote,
} from "@/src/data/harness-prompts";
import planStepReviewNote from "./plan-step-review";
import unsentAnswerMessage from "./unsent-answer-message";
/**
@@ -29,6 +40,28 @@ describe("unsentAnswerMessage", () => {
);
});
test("closing failures name the call that failed, never the review (jobs 680, 694, 700)", () => {
expect(unsentAnswerMessage({ note: replyClosingFailedNote })).toContain("call that sends the message");
expect(unsentAnswerMessage({ note: replyClosingRequiredNote })).toContain("never sent the message");
expect(unsentAnswerMessage({ note: replyClosingMixedNote })).toContain("other work");
expect(unsentAnswerMessage({ note: replyCardOnlyFailedNote({ tools: ["ask_user"] }) })).toContain("card");
expect(unsentAnswerMessage({ note: replyCardFailedNote({ tools: ["suggest_next_steps"] }) })).toContain("card");
for (const note of [replyClosingFailedNote, replyClosingRequiredNote, replyCardOnlyFailedNote({ tools: ["ask_user"] })]) {
expect(unsentAnswerMessage({ note })).not.toContain("app's record");
}
});
test("a plan step that ended wrong says so", () => {
const note = planStepReviewNote({
plan: { id: 2, title: "Finish", current_step: 0, total_steps: 3 },
on_step: true,
tool_uses: [],
});
expect(unsentAnswerMessage({ note: note! })).toContain("plan step");
});
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.`,
+51 -4
View File
@@ -1,4 +1,14 @@
import { closingNoTextNote, closingToolGoneNote, replyDraftNote, replyNoTextNote } from "@/src/data/harness-prompts";
import {
closingFailedNote,
closingMixedNote,
closingNoTextNote,
closingToolGoneNote,
replyClosingFailedNote,
replyClosingMixedNote,
replyClosingRequiredNote,
replyDraftNote,
replyNoTextNote,
} from "@/src/data/harness-prompts";
type Params = {
/**
@@ -9,8 +19,21 @@ type Params = {
};
/**
* The failure notice a run that never sent its answer leaves. The note
* the loop returned picks the line, so an empty close is not called a lie.
* The openings of the notes built per call (`replyCardFailedNote`,
* `replyCardOnlyFailedNote`, `planStepReviewNote`, `unfinishedAnswerText`):
* their tails name tools or steps, so they are told apart by how they start.
*/
const CardRefusedOpenings = ["The card was not put up", "send_reply went through and your message is kept"];
const PlanStepOpenings = ["This reply works step", "This reply finished step"];
const UnfinishedOpening = "The message stops ";
/**
* The failure notice a run that never sent its answer leaves. The note the
* loop returned picks the line, so a run that failed for its own mechanics
* is never called a lie: "didn't hold up against the app's record" is only
* for an answer the review actually checked and refused. Before, every
* closing failure fell through to that line (jobs 680, 694, 700), and the
* user read five failures as a bot caught out when none was.
*/
export default function unsentAnswerMessage({ note }: Params) {
if (note === replyNoTextNote) {
@@ -29,5 +52,29 @@ export default function unsentAnswerMessage({ note }: Params) {
return `The run's last turn called a tool it no longer had, so its message wasn't sent.`;
}
if (note === replyClosingFailedNote) {
return `The call that sends the message kept being refused, so the message wasn't sent.`;
}
if (note === replyClosingRequiredNote) {
return `The reply put its card up but never sent the message with it, so it wasn't sent.`;
}
if (note === replyClosingMixedNote || note === closingMixedNote) {
return `The reply kept doing other work in the turn meant to send its message, so it wasn't sent.`;
}
if (note === closingFailedNote || CardRefusedOpenings.some((opening) => note.startsWith(opening))) {
return `The card under the message kept being refused, so the message wasn't sent.`;
}
if (PlanStepOpenings.some((opening) => note.startsWith(opening))) {
return `The reply didn't end its plan step the way the plan needs, so it wasn't sent.`;
}
if (note.startsWith(UnfinishedOpening)) {
return `The message stopped part-way through (an unclosed table, list or code block), so it wasn't sent.`;
}
return `The answer didn't hold up against the app's record, so it wasn't sent.`;
}
}
+9 -18
View File
@@ -1,34 +1,25 @@
import Markdown from "react-markdown";
import remarkGfm from "remark-gfm";
import Span from "@moduletrace/twui/layout/Span";
import Stack from "@moduletrace/twui/layout/Stack";
import { MessageMarkdownComponents } from "@/src/pages/admin/bots/[bot_id]/(data)/message-markdown-components";
import linkComputerRefs from "@/src/utils/link-computer-refs";
/**
* Kept module-level: a new array on every render makes `react-markdown`
* parse the message again.
*/
const RemarkPlugins = [remarkGfm];
import MarkdownText from "./markdown-text";
type Props = {
label: string;
text: string;
/**
* Long text (a hook's brief): kept to a box that scrolls.
*/
boxed?: boolean;
};
/**
* What a hook call's run answered, rendered like a chat message (raw HTML
* never).
* Markdown about a hook under its label (what a call's run answered, the
* hook's brief), rendered like a chat message (raw HTML never).
*/
export default function HookCallAnswer({ label, text }: Props) {
export default function HookCallAnswer({ label, text, boxed }: Props) {
return (
<Stack className="w-full gap-0.5! items-stretch">
<Span className="text-[11px] leading-4 text-ink-secondary">{label}</Span>
<Stack className="w-full gap-2.5! items-start break-words">
<Markdown remarkPlugins={RemarkPlugins} components={MessageMarkdownComponents}>
{linkComputerRefs({ text })}
</Markdown>
</Stack>
<MarkdownText text={text} boxed={boxed} />
</Stack>
);
}
+11 -3
View File
@@ -11,7 +11,7 @@ import type { BotHookWithNames } from "@/src/types";
import conversationHref from "@/src/utils/conversation-href";
import hookRunnerState from "@/src/utils/hook-runner-state";
import relativeTime from "@/src/utils/relative-time";
import HookCallText from "./hook-call-text";
import HookCallAnswer from "./hook-call-answer";
import HookCalls from "./hook-calls";
import TaskFactRow from "./task-fact-row";
@@ -101,7 +101,15 @@ export default function HookDetailModal({ hook, can_manage = false, onClose, onE
<TaskFactRow label="Runner">
{runner.running
? `Up since ${relativeTime({ at: Number(hook.runner_started_at) || Date.now() })}`
: hook.runner_last_error || "Down"}
: "Down"}
</TaskFactRow>
{runner.error ? (
<TaskFactRow label="Check failed">{runner.error}</TaskFactRow>
) : null}
<TaskFactRow label="Last checked">
{hook.runner_checked_at
? relativeTime({ at: Number(hook.runner_checked_at) })
: "Not yet"}
</TaskFactRow>
{hook.runner_command ? (
<TaskFactRow label="Runner command">
@@ -130,7 +138,7 @@ export default function HookDetailModal({ hook, can_manage = false, onClose, onE
</TaskFactRow>
{hook.last_error ? <TaskFactRow label="Last error">{hook.last_error}</TaskFactRow> : null}
</Stack>
{hook.instructions ? <HookCallText label="Brief" text={hook.instructions} full /> : null}
{hook.instructions ? <HookCallAnswer label="Brief" text={hook.instructions} boxed /> : null}
{status ? <SettingsStatus status={status} /> : null}
<Row className="w-full gap-2! justify-end">
{can_manage && runner?.configured ? (
+2 -2
View File
@@ -289,7 +289,7 @@ export default function HookForm({
autoComplete="off"
placeholder="whatsapp"
defaultValue={hook?.runner_dir || ""}
info={`Where it starts, inside the bot's folder: "whatsapp" is the bot's whatsapp folder. Empty starts in the bot's folder itself.`}
info={`Where it starts, relative to the bot's folder (/home/cb-<bot>/workspace), not to a run's ~: "whatsapp" is /home/cb-<bot>/workspace/whatsapp, while a folder a bot made at ~/whatsapp is "users/<user>/whatsapp". Empty starts in the bot's folder itself.`}
onChange={(e) => setRunnerDir(e.target.value)}
/>
<Select
@@ -317,7 +317,7 @@ export default function HookForm({
) : null}
<Checkbox
title="Run silently"
label="Keep its runs in the hook's own thread: they never take over the conversation or notify me. Read them from the hook, or in the bot's sessions."
label="Run without taking over the conversation: its thread stays out of the rail, its runs don't notify me or change the bot's face. Unchecked, each run makes its thread the conversation's active session."
checked={silent}
changeHandler={setSilent}
labelProps={{ className: "w-full" }}
@@ -1,10 +1,10 @@
import { describe, expect, test } from "bun:test";
import { renderToString } from "react-dom/server";
import TaskMarkdown from "./task-markdown";
import MarkdownText from "./markdown-text";
describe("TaskMarkdown", () => {
describe("MarkdownText", () => {
test("renders the markdown, not as written", () => {
const html = renderToString(<TaskMarkdown text={"## Steps\n\n- **Check** the [docs](https://example.com)"} />);
const html = renderToString(<MarkdownText text={"## Steps\n\n- **Check** the [docs](https://example.com)"} />);
expect(html).not.toContain("## Steps");
expect(html).not.toContain("**Check**");
@@ -13,7 +13,7 @@ describe("TaskMarkdown", () => {
});
test("opens links in a new tab, bare ones too", () => {
const html = renderToString(<TaskMarkdown text={"See [the docs](https://example.com) or https://example.org"} />);
const html = renderToString(<MarkdownText text={"See [the docs](https://example.com) or https://example.org"} />);
expect(html).toContain('href="https://example.com"');
expect(html).toContain('href="https://example.org"');
@@ -22,7 +22,7 @@ describe("TaskMarkdown", () => {
});
test("shows refs as chips", () => {
const html = renderToString(<TaskMarkdown text={"Ask [bot:2] about [task:20]."} />);
const html = renderToString(<MarkdownText text={"Ask [bot:2] about [task:20]."} />);
expect(html).not.toContain("[bot:2]");
expect(html).toContain("bot 2");
@@ -30,7 +30,7 @@ describe("TaskMarkdown", () => {
});
test("never renders raw HTML", () => {
const html = renderToString(<TaskMarkdown text={"<script>alert(1)</script> <b>hi</b>"} />);
const html = renderToString(<MarkdownText text={"<script>alert(1)</script> <b>hi</b>"} />);
expect(html).not.toContain("<script>");
expect(html).not.toContain("<b>");
@@ -17,17 +17,25 @@ const RemarkPlugins = [remarkGfm];
type Props = {
text: string;
/**
* Long text (a brief, a runbook, a memory): kept to a sunken box that
* scrolls, so it never pushes the rest of a card out of sight.
*/
boxed?: boolean;
className?: string;
};
/**
* A task's description or a note on it, rendered like a bot's message
* (raw HTML never rendered, links in a new tab, refs as their chips). The
* crew the chips link to is the page's own when no conversation around it
* gives one. The message elements reach this file again through the task
* chip, so they're read when it renders, never at load.
* Bot- or user-written markdown anywhere outside a message (a task's
* description and notes, a hook's or routine's brief, a skill's runbook,
* a card's reason, a bot's instructions and memory), rendered like a bot's
* message: raw HTML never rendered, links in a new tab, refs as their
* chips. Never show such text raw. The crew the chips link to is the
* page's own when no conversation around it gives one. The message
* elements reach this file again through the chips and cards, so they're
* read when it renders, never at load.
*/
export default function TaskMarkdown({ text, className }: Props) {
export default function MarkdownText({ text, boxed, className }: Props) {
const { pageProps } = useContext(AppContext);
const crew_bots = useContext(CrewBotsContext);
const crew_workspaces = useContext(CrewWorkspacesContext);
@@ -37,7 +45,13 @@ export default function TaskMarkdown({ text, className }: Props) {
return (
<CrewBotsContext.Provider value={bots}>
<CrewWorkspacesContext.Provider value={workspaces}>
<Stack className={twMerge("w-full min-w-0 gap-2! items-stretch", className)}>
<Stack
className={twMerge(
"w-full min-w-0 gap-2! items-stretch break-words",
boxed && "max-h-80 overflow-y-auto rounded-default-xs bg-sunken px-3 py-2",
className,
)}
>
<Markdown remarkPlugins={RemarkPlugins} components={MessageMarkdownComponents}>
{linkComputerRefs({ text })}
</Markdown>
+2 -2
View File
@@ -17,7 +17,7 @@ import TaskNoteRow from "@/src/components/general/task-note-row";
import TaskSubtaskRow from "@/src/components/general/task-subtask-row";
import TaskSubtasksModal from "@/src/components/general/task-subtasks-modal";
import SubtaskLinkForm from "@/src/components/general/subtask-link-form";
import TaskMarkdown from "@/src/components/general/task-markdown";
import MarkdownText from "@/src/components/general/markdown-text";
import type { BotFace } from "@/src/dict/bot-dict";
import { AppContext } from "@/src/pages/__root";
import { AppData } from "@/src/data/app-data";
@@ -474,7 +474,7 @@ export default function TaskDetailPanel({
<Span className="text-[13px] leading-[18px] text-ink">{`Waiting on you: ${task.blocked_reason}`}</Span>
) : null}
{task.description ? <TaskMarkdown text={task.description} /> : null}
{task.description ? <MarkdownText text={task.description} /> : null}
{task.workspace_id && !task.bot_id ? (
<Stack className="w-full gap-1! items-stretch">
+2 -2
View File
@@ -3,7 +3,7 @@ import Span from "@moduletrace/twui/layout/Span";
import Stack from "@moduletrace/twui/layout/Stack";
import type { TaskNote } from "@/src/types";
import relativeTime from "@/src/utils/relative-time";
import TaskMarkdown from "./task-markdown";
import MarkdownText from "./markdown-text";
type Props = {
note: TaskNote;
@@ -26,7 +26,7 @@ export default function TaskNoteRow({ note }: Props) {
</Span>
) : null}
</Row>
{note.text ? <TaskMarkdown text={note.text} /> : null}
{note.text ? <MarkdownText text={note.text} /> : null}
</Stack>
);
}
+7 -2
View File
@@ -345,8 +345,13 @@ describe("plan notes", () => {
expect(note).toContain('"Pause the plan"');
});
test("the last step's card offers to finish the plan", () => {
expect(PlanStepNote({ plan: { ...plan, current_step: 2 } })).toContain('"Finish the plan"');
test("the last step ends the plan with its report alone, no card", () => {
const note = PlanStepNote({ plan: { ...plan, current_step: 2 } });
expect(note).toContain("This is the last step");
expect(note).toContain("no card");
expect(note).not.toContain("Finish the plan");
expect(note).not.toContain("Every finished step ends on a card");
});
test("lists the steps with where each one stands and what it produced", () => {
+27 -8
View File
@@ -385,7 +385,7 @@ When a concept, comparison, process, timeline or set of numbers is easier to see
* `bot_id` is the coordinator itself, so the ref example it copies is its
* own rather than a worker's.
*/
export const coordinatorReplyNote = ({ bot_id }: { bot_id: number | string }) => `As the coordinator, hand work that fits a crew member's role to them with delegate_task. Work that is already a task on a list goes over as that task (delegate_task with its task_id), never as a copy; a routine of yours that belongs with a worker goes with hand_over_schedule. A task handed over lands there as to do and nothing runs: pass start: true only when the user asked for the work to begin now, and when they haven't said, ask before it moves (one ask_user card with every task they named). They post the result in their own conversation, and it's reported back here when they finish or fail, so tell the user who is on it and where: a task with no workspace_id runs in that bot's own chat, on its own memory, files and directly assigned computers; one with workspace_id runs in the workspace, on the workspace's context, files and computers as well as the bot's, and lands in that project's conversation. Never swap one for the other without saying so. When a report comes back, pass on what matters to the user, follow up on anything left, and propose what comes next with ask_user: the next piece of work, which bot would take it, or the question that settles the direction, as options for the user to pick. Once the user agrees, you can also grow the crew with create_bot, put a worker in a workspace with add_bot_to_workspace, and create or change a workspace with create_workspace and update_workspace. When you name a crew member, write its ref instead of its name, e.g. ${botRef({ id: bot_id })} for yourself: the user sees it as the bot's name, linked to its conversation.`;
export const coordinatorReplyNote = ({ bot_id }: { bot_id: number | string }) => `As the coordinator, hand work that fits a crew member's role to them with delegate_task. Work that is already a task on a list goes over as that task (delegate_task with its task_id), never as a copy; a routine of yours that belongs with a worker goes with hand_over_schedule. A task handed over lands there as to do and nothing runs: pass start: true only when the user asked for the work to begin now, and when they haven't said, ask before it moves (one ask_user card with every task they named). Each started run opens a session of its own in their conversation, they can send you a word on the way, and their report comes back here when they finish or fail, so tell the user who is on it and where: a task with no workspace_id runs in that bot's own chat, on its own memory, files and directly assigned computers; one with workspace_id runs in the workspace, on the workspace's context, files and computers as well as the bot's, and lands in that project's conversation. Never swap one for the other without saying so. When a report comes back, pass on what matters to the user, follow up on anything left, and propose what comes next with ask_user: the next piece of work, which bot would take it, or the question that settles the direction, as options for the user to pick. Once the user agrees, you can also grow the crew with create_bot, put a worker in a workspace with add_bot_to_workspace, and create or change a workspace with create_workspace and update_workspace. When you name a crew member, write its ref instead of its name, e.g. ${botRef({ id: bot_id })} for yourself: the user sees it as the bot's name, linked to its conversation.`;
/**
* Added to the coordinator's chat prompt instead while it has no workers,
@@ -406,7 +406,7 @@ export const workspaceAdminNote = ({
members: { id?: number | "" }[];
}) => `# Leading ${workspace_name}
You are this workspace's admin: you lead the bots working here (${members.map((m) => botRef({ id: m.id || 0 })).join(", ")}). Hand work that fits a member's role to them with delegate_task rather than doing all of it yourself (a task already on a list goes over with its task_id, and one of your routines here with hand_over_schedule; a hand-over lands as to do and starts nothing, so pass start: true only when the user asked for the work to begin now, and ask first when they haven't said); they post the result in their conversation here, and it's reported back to you when they finish or fail, so tell the user who is on it. When a report comes back, pass on what matters, follow up on anything left and propose what comes next. Set how a member should work here with set_bot_workspace_instructions, keep the workspace's task list honest (create_task with a member's bot_id gives them a task here), and keep the workspace's shared context current with update_workspace when you have it. When you name a member, write its ref, so the user sees its name linked to its conversation.`;
You are this workspace's admin: you lead the bots working here (${members.map((m) => botRef({ id: m.id || 0 })).join(", ")}). Hand work that fits a member's role to them with delegate_task rather than doing all of it yourself (a task already on a list goes over with its task_id, and one of your routines here with hand_over_schedule; a hand-over lands as to do and starts nothing, so pass start: true only when the user asked for the work to begin now, and ask first when they haven't said); each started run opens a session of its own in their conversation here, they can send you a word on the way, and their report comes back to you when they finish or fail, so tell the user who is on it. When a report comes back, pass on what matters, follow up on anything left and propose what comes next. Set how a member should work here with set_bot_workspace_instructions, keep the workspace's task list honest (create_task with a member's bot_id gives them a task here), and keep the workspace's shared context current with update_workspace when you have it. When you name a member, write its ref, so the user sees its name linked to its conversation.`;
/**
* Added to a workspace member's prompt while the workspace has an admin,
@@ -655,6 +655,14 @@ export const replyClosingFailedNote = `send_reply did not go through (its error
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.`;
/**
* Told when a card was refused in a turn that never called `send_reply`:
* the card's error is what to fix. Telling the model `send_reply` failed
* there sent it after a status error that never happened (job 694).
*/
export const replyCardOnlyFailedNote = ({ tools }: { tools: string[] }) =>
`The card was not put up: ${tools.join(" and ")} refused its arguments (the error is above), so nothing reached the user. Fix those arguments exactly as the error says and call it again, with send_reply in the same turn carrying your message (the message you wrote beside the card is kept for it). Or drop the card and answer with send_reply alone.`;
/**
* 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
@@ -1146,7 +1154,15 @@ export const PlanStepNote = ({ plan }: { plan: PlanPrompt }) => {
const index = plan.current_step ?? 0;
const step = plan.steps[index];
const next = index + 2;
const next_label = next > plan.steps.length ? "Finish the plan" : `Continue to step ${next}`;
const last_step = next > plan.steps.length;
/**
* The last step's tick finishes the plan, so its report ends the plan
* on its own: a "Finish the plan" card would move nothing on, and the
* review used to demand one while the tool said none was needed.
*/
const ending = last_step
? `- **This is the last step.** complete_plan_step finishes the plan, so the report goes out with send_reply alone and no card: there is no next step to continue to.`
: `- **Every finished step ends on a card.** Call ask_user in the same turn as the report (beside the send_reply that sends it): one question, "Continue with the plan?", whose first option is "Continue to step ${next}", whose second is "Pause the plan", after those any choice this step really needs. The user answers in one click and the app starts the next step, so nothing waits on them typing "move on": a report without the card is sent back.`;
return `# Your plan, step ${index + 1} of ${plan.steps.length}
@@ -1156,10 +1172,10 @@ ${planStepLines({ plan })}
This run works step ${index + 1} only: ${step?.text || ""}
- One step per run. The next step starts when the user answers this report's card, so don't start it now and don't do two.
- One step per run.${last_step ? "" : " The next step starts when the user answers this report's card, so don't start it now and don't do two."}
- Finish it with complete_plan_step: one or two lines on what it produced (the number, the path, the link). Then write your report to the user.
- Your report is two or three sentences: what this step did and what it produced. No heading, no recap of the plan, and never "next, I'll...". The card above the report shows the plan and the step after this one, so repeating it only makes the reply longer than it needs to be.
- **Every finished step ends on a card.** Call ask_user in the same turn as the report (beside the send_reply that sends it): one question, "Continue with the plan?", whose first option is "${next_label}", whose second is "Pause the plan", after those any choice this step really needs. The user answers in one click and the app starts the next step, so nothing waits on them typing "move on": a report without the card is sent back.
- Your report is two or three sentences: what this step did and what it produced. No heading, no recap of the plan, and never "next, I'll...". The card above the report shows the plan${last_step ? "" : " and the step after this one"}, so repeating it only makes the reply longer than it needs to be.
${ending}
- If the step can't be done from here (it needs the user, a login or a decision they alone can make), don't finish it: ask that question on the card, and say the plan is holding at this step.
- If what you found means the rest of the plan is wrong, change it with update_plan, in the same run, and say what changed.`;
};
@@ -1175,7 +1191,10 @@ export const PlanActiveNote = ({ plan, plan_mode }: { plan: PlanPrompt; plan_mod
const index = plan.current_step;
const step = index == null ? null : plan.steps[index];
const next = (index ?? 0) + 2;
const next_label = next > plan.steps.length ? "Finish the plan" : `Continue to step ${next}`;
const work_step =
next > plan.steps.length
? `finish it with complete_plan_step in this run. It is the last step, so that finishes the plan and the report goes out alone, with no card.`
: `finish it with complete_plan_step in this run, and put the card up in the same turn with ask_user (one question, "Continue with the plan?", first option "Continue to step ${next}", second "Pause the plan"). A report that ticked the step without that card is sent back.`;
return `# The plan in this conversation
@@ -1187,7 +1206,7 @@ ${
plan_mode
? `- This reply runs in Plan mode: the plan is yours to pick up and refine here, not to work. When what they say bears on the steps, rewrite them with update_plan (the whole list, done steps first and unchanged), as many times as the conversation asks, and say in a line what changed. Don't work or tick a step, and don't pause or resume the plan: that waits until the mode is off.`
: `- Its steps are normally worked one per reply, each ending on a card the user answers to start the next one. This reply isn't a step the app queued: answer whatever the user asked first.
- If what they asked IS step ${index == null ? "?" : index + 1} (${step?.text || "the current step"}), work it now: finish it with complete_plan_step in this run, and put the card up in the same turn with ask_user (one question, "Continue with the plan?", first option "${next_label}", second "Pause the plan"). A report that ticked the step without that card is sent back.
- If what they asked IS step ${index == null ? "?" : index + 1} (${step?.text || "the current step"}), work it now: ${work_step}
- If they asked something else, answer that and leave the plan where it is: it carries on from there. Don't work a step as a side errand.
- If the user's answer to the plan's card was typed rather than a click, it is theirs to read here: carry on with the step when it says to, and park the plan with update_plan and status "paused" when it says to wait.
- Only pause or resume when they asked, with update_plan and its status. Never end a plan on your own: cancelling is theirs. The steps are theirs to change on the card too; if the work moved on from one of them, update_plan and say what changed.`
+23 -1
View File
@@ -85,4 +85,26 @@ export const AskAnswerJobTitle = "Crew request";
* requests one place keeps (`AppData.AskKeepDays`, `AskMaxPerPlace`).
*/
export const AskKeepDaysSettingKey = "ask_keep_days";
export const AskMaxPerPlaceSettingKey = "ask_max_per_place";
export const AskMaxPerPlaceSettingKey = "ask_max_per_place";
/**
* What opened a request. `ask` is `ask_bot`, which goes through the
* coordinator's gate. `hand_over` is a task one bot handed another and
* started because the user said so (`delegate_task`, `hand_over_task`): no
* gate, but the same thread of its own, interim updates and result back.
*/
export const AskKinds = [
{
title: "Crew request",
value: "ask",
},
{
title: "Hand-over",
value: "hand_over",
},
] as const;
export type AskKind = (typeof AskKinds)[number]["value"];
export function isHandOverAsk({ kind }: { kind?: string | null }) {
return kind == "hand_over";
}
@@ -0,0 +1,34 @@
import { Database } from "bun:sqlite";
type Params = {
/**
* The live database file.
*/
source: string;
/**
* Where the copy goes. Must not exist yet.
*/
target: string;
};
/**
* Copies a live SQLite database into one consistent file with
* `VACUUM INTO`, which reads the whole database inside one read
* transaction, so writes made while it runs are either all in the copy or
* none of them. A data archive used to tar the live file, which the app
* writes every few seconds, so tar failed with "file changed as we read
* it" and the copy it kept was torn anyway.
*
* Its own read-only connection, so it needs no extension loaded (the
* vec0 tables' rows are plain shadow tables) and never touches the app's.
*/
export default function snapshotDatabaseFile({ source, target }: Params) {
const db = new Database(source, { readonly: true });
try {
db.run("PRAGMA busy_timeout = 5000;");
db.run("VACUUM INTO ?", [target]);
} finally {
db.close();
}
}
@@ -2,6 +2,7 @@ import { afterEach, describe, expect, test } from "bun:test";
import fs from "fs";
import os from "os";
import path from "path";
import { Database } from "bun:sqlite";
import writeDataBackupArchive from "./write-data-backup-archive";
const dirs: string[] = [];
@@ -25,6 +26,24 @@ function write({ root, relative, content = "x" }: { root: string; relative: stri
fs.writeFileSync(target, content);
}
/**
* A real database at `db/cobble`: the archive snapshots it, so a stand-in
* file would not open.
*/
function writeDatabase({ root, rows = 1 }: { root: string; rows?: number }) {
fs.mkdirSync(path.join(root, "db"), { recursive: true });
const db = new Database(path.join(root, "db", "cobble"), { create: true });
db.run("CREATE TABLE notes (id INTEGER PRIMARY KEY, body TEXT)");
db.transaction(() => {
for (let i = 0; i < rows; i++) db.run("INSERT INTO notes (body) VALUES (?)", [`note ${i}`]);
})();
return db;
}
afterEach(() => {
for (const dir of dirs.splice(0)) {
fs.rmSync(dir, { recursive: true, force: true });
@@ -44,7 +63,7 @@ describe("writeDataBackupArchive", () => {
process.env.DATA_DIR = data_dir;
process.env.BACKUP_ARCHIVE_DIR = archive_dir;
write({ root: data_dir, relative: "db/cobble" });
writeDatabase({ root: data_dir }).close();
write({ root: data_dir, relative: "db/.backups/cobble-1" });
write({ root: data_dir, relative: ".bun-sqlite/.tmp/temp.db" });
write({ root: data_dir, relative: "computers/1/bots/3/users/1/work.txt" });
@@ -91,11 +110,53 @@ describe("writeDataBackupArchive", () => {
process.env.DATA_DIR = data_dir;
process.env.BACKUP_ARCHIVE_DIR = archive_dir;
write({ root: data_dir, relative: "db/cobble" });
writeDatabase({ root: data_dir }).close();
write({ root: archive_dir, relative: "cobble-data-1.tar.gz" });
const created = await writeDataBackupArchive();
expect(fs.existsSync(created.path)).toBe(true);
});
});
test("archives a consistent copy of the database while it is being written", async () => {
const data_dir = makeRoot();
const archive_dir = makeRoot();
const extract_dir = makeRoot();
process.env.DATA_DIR = data_dir;
process.env.BACKUP_ARCHIVE_DIR = archive_dir;
const db = writeDatabase({ root: data_dir, rows: 2000 });
// An open write transaction leaves a journal beside the file,
// which tar would otherwise read half-written.
db.run("BEGIN");
db.run("INSERT INTO notes (body) VALUES ('uncommitted')");
const created = await writeDataBackupArchive();
db.run("ROLLBACK");
db.close();
const root = created.name.replace(/\.tar\.gz$/, "");
const members = new TextDecoder()
.decode(Bun.spawnSync(["tar", "-tzf", created.path]).stdout)
.split("\n")
.filter(Boolean);
expect(members).toContain(`${root}/db/cobble`);
expect(members.some((member) => member.includes(".snapshot"))).toBe(false);
expect(members.some((member) => member.endsWith("-journal"))).toBe(false);
Bun.spawnSync(["tar", "-xzf", created.path, "-C", extract_dir]);
const copy = new Database(path.join(extract_dir, root, "db", "cobble"), { readonly: true });
const { n } = copy.query("SELECT count(*) AS n FROM notes").get() as { n: number };
const { integrity_check } = copy.query("PRAGMA integrity_check").get() as { integrity_check: string };
copy.close();
expect(integrity_check).toBe("ok");
expect(n).toBe(2000);
});
});
@@ -6,6 +6,14 @@ import grabDirNames from "@/src/utils/grab-dir-names";
import grabBackupArchiveDir from "@/src/utils/grab-backup-archive-dir";
import grabDataBackups from "./grab-data-backups";
import listArchiveExclusions from "./list-archive-exclusions";
import snapshotDatabaseFile from "./snapshot-database-file";
import BunSQLiteConfig from "@/bun-sqlite.config";
/**
* The live database's sidecars: the rollback journal, or WAL and its
* index. The snapshot replaces all of them.
*/
const DatabaseSidecarSuffixes = ["", "-journal", "-wal", "-shm"];
export type CreatedDataBackup = {
name: string;
@@ -17,9 +25,15 @@ export type CreatedDataBackup = {
* bot and workspace files, MCP installs, Chrome profiles) into
* `BACKUP_ARCHIVE_DIR` and keeps only the newest
* `AppData.DataBackupsKept`. Every entry sits under one root folder named
* after the archive, so extracting it lands one folder. The SQLite file
* inside is only as consistent as the moment tar read it; `db/.backups` is
* for consistent snapshots.
* after the archive, so extracting it lands one folder.
*
* The database is never tarred live: the app writes it every few seconds,
* so tar exited 1 with "./db/cobble: file changed as we read it" and kept
* a torn copy. A `VACUUM INTO` snapshot (`snapshotDatabaseFile`) goes in
* at `db/<db_name>` instead, and the live file and its journal are left
* out. Anything else changing mid-read (a bot saving a file, Chrome
* writing its cookies) is only tar's exit 1, which still means a whole
* archive, so that is a success; 2 and up fail the run.
*
* It leaves out what is rebuilt on demand or kept elsewhere
* (`listArchiveExclusions`): a computer's own folders, Chrome profile
@@ -41,10 +55,27 @@ export default async function writeDataBackupArchive(): Promise<CreatedDataBacku
const part_path = `${archive_path}.part`;
const excl_dir = fs.mkdtempSync(path.join(os.tmpdir(), "cobble-archive-"));
const excl_path = path.join(excl_dir, "exclude.txt");
const db_file = path.join(DATA_DIR, "db", BunSQLiteConfig.db_name);
const has_db = fs.existsSync(db_file);
// Staged under a name of its own: the live file's member path is
// excluded, and tar would drop a staged file of the same name too.
const snapshot_member = `./db/${BunSQLiteConfig.db_name}.snapshot`;
try {
const exclusions = await listArchiveExclusions({ data_dir: DATA_DIR });
if (has_db) {
for (const suffix of DatabaseSidecarSuffixes) {
exclusions.push(`./db/${BunSQLiteConfig.db_name}${suffix}`);
}
fs.mkdirSync(path.join(excl_dir, "db"), { recursive: true });
snapshotDatabaseFile({
source: db_file,
target: path.join(excl_dir, snapshot_member),
});
}
fs.writeFileSync(excl_path, exclusions.map((line) => `${line}\n`).join(""));
const proc = Bun.spawn(
@@ -58,8 +89,14 @@ export default async function writeDataBackupArchive(): Promise<CreatedDataBacku
// Two expressions: the root `.` itself and every `./`
// member, so the whole archive sits under one folder named
// after it and an extract drops a single folder.
// The database snapshot first takes the live file's
// place (`db/<db_name>`).
"--transform",
`s,^\\.$,${archive_root},;s,^\\./,${archive_root}/,`,
`s,^\\./db/${BunSQLiteConfig.db_name}\\.snapshot$,${archive_root}/db/${BunSQLiteConfig.db_name},;s,^\\.$,${archive_root},;s,^\\./,${archive_root}/,`,
// A file written while tar reads it (a bot's save, a
// Chrome profile) is exit 1, not a broken archive.
"--warning=no-file-changed",
"--warning=no-file-removed",
// The exclusions are exact member paths
// (`listArchiveExclusions`), never patterns: a folder a
// bot named `node_modules!` or `Cache*` must not take a
@@ -69,6 +106,7 @@ export default async function writeDataBackupArchive(): Promise<CreatedDataBacku
"-C",
DATA_DIR,
".",
...(has_db ? ["-C", excl_dir, snapshot_member] : []),
],
{
cwd: process.cwd(),
@@ -85,7 +123,9 @@ export default async function writeDataBackupArchive(): Promise<CreatedDataBacku
proc.exited,
]);
if (exit_code !== 0) {
// GNU tar: 1 is "some files differ" (changed while read), and the
// archive is still whole; 2 is a fatal error.
if (exit_code !== 0 && exit_code !== 1) {
throw new Error(
stderr.trim() ||
stdout.trim() ||
@@ -49,4 +49,15 @@ describe("askOutcomeMessage", () => {
test("names an unnamed request without empty quotes", () => {
expect(askOutcomeMessage({ ask: { ...ask, title: "" }, status: "refused" })).toContain("your crew request");
});
test("a hand-over's report says it was work handed over, not a request the coordinator passed on", () => {
const handed = { ...ask, kind: "hand_over" } as BUN_SQLITE_COBBLE_BOT_ASKS;
const text = askOutcomeMessage({ ask: handed, status: "answered", outcome: "Shipped." });
expect(text).toBe('[bot:12] finished "Cite the sheet" [ask:3], which you handed over. Their report:\n\nShipped.');
expect(askOutcomeMessage({ ask: handed, status: "failed", outcome: "No computer." })).toContain(
"couldn't finish",
);
expect(askOutcomeMessage({ ask: handed, status: "stopped" })).not.toContain("coordinator");
});
});
@@ -1,5 +1,5 @@
import type { BUN_SQLITE_COBBLE_BOT_ASKS } from "@/db/types/db";
import type { AskStatus } from "@/src/dict/ask-dict";
import { isHandOverAsk, type AskStatus } from "@/src/dict/ask-dict";
import askRef from "@/src/utils/ask-ref";
import botRef from "@/src/utils/bot-ref";
@@ -20,6 +20,20 @@ export default function askOutcomeMessage({ ask, status, outcome }: Params) {
const pill = ask.id ? ` ${askRef({ id: ask.id })}` : "";
const target = ask.target_bot_id ? botRef({ id: ask.target_bot_id }) : "the crew";
if (isHandOverAsk({ kind: ask.kind })) {
const handed = ask.title ? `"${ask.title}"` : "the work";
if (status == "stopped") {
return `${handed}${pill}, which you handed to ${target}, was stopped: ${outcome || "the user stopped it."}`;
}
if (status == "failed" || status == "refused") {
return `${target} couldn't finish ${handed}${pill}, which you handed over:\n\n${outcome || "No reason was given."}`;
}
return `${target} finished ${handed}${pill}, which you handed over. Their report:\n\n${outcome || ""}`;
}
if (status == "refused") {
return `The coordinator turned down ${title}${pill}:\n\n${ask.gate_note || outcome || "No reason was given."}`;
}
@@ -1,5 +1,6 @@
import type { BUN_SQLITE_COBBLE_BOT_ASKS } from "@/db/types/db";
import botRef from "@/src/utils/bot-ref";
import { isHandOverAsk } from "@/src/dict/ask-dict";
type Params = {
ask: BUN_SQLITE_COBBLE_BOT_ASKS;
@@ -21,6 +22,18 @@ export default function askRequestMessage({ ask, requester_name, place }: Params
const requester = ask.requester_bot_id ? botRef({ id: ask.requester_bot_id }) : `"${requester_name}"`;
const where = place ? `, from the ${place} workspace` : "";
/**
* A task handed over on the user's word: the work is this run's, and
* its result goes back to the bot that handed it over on its own.
*/
if (isHandOverAsk({ kind: ask.kind })) {
return `${requester} handed this over to you (hand-over #${ask.id}${where}):
> ${(ask.request || "").trim().replace(/\n/g, "\n> ")}
Work it in this conversation. Your report goes back to ${requester} when the run ends; update_requester sends it a word meanwhile.`;
}
return `The coordinator passed on a request from ${requester} (ask #${ask.id}${where}):
> ${(ask.request || "").trim().replace(/\n/g, "\n> ")}
@@ -1,6 +1,7 @@
import type { BUN_SQLITE_COBBLE_BOT_ASKS } from "@/db/types/db";
import askRef from "@/src/utils/ask-ref";
import botRef from "@/src/utils/bot-ref";
import { isHandOverAsk } from "@/src/dict/ask-dict";
type Params = {
ask: BUN_SQLITE_COBBLE_BOT_ASKS;
@@ -36,9 +37,10 @@ export default function askUpdateMessage({ ask, text, failed, ended }: Params) {
? `${target} couldn't finish one piece of ${title}${pill}:`
: `${target} sent a response on ${title}${pill}:`;
const what = isHandOverAsk({ kind: ask.kind }) ? "hand-over" : "request";
const tail = ended
? `_The request had already ended; this is the answer, sent afterwards._`
: `_The request is still open - more may follow._`;
? `_The ${what} had already ended; this is the answer, sent afterwards._`
: `_The ${what} is still open - more may follow._`;
return `${head}\n\n${text}\n\n${tail}`;
}
@@ -12,7 +12,8 @@ type Params = {
export default async function countOpenAsks({ user_id, requester_bot_id }: Params) {
const res = await BunSQLite.sql<{ n: number }>({
sql: `SELECT COUNT(*) AS n FROM bot_asks
WHERE user_id = ? AND requester_bot_id = ? AND status IN ('pending', 'working')`,
WHERE user_id = ? AND requester_bot_id = ? AND status IN ('pending', 'working')
AND COALESCE(kind, 'ask') = 'ask'`,
values: [Number(user_id), Number(requester_bot_id)],
});
@@ -34,7 +34,9 @@ export type ConversationAsk = {
* The crew request the bot is answering for this user, if one is open. The
* answer runs in the bot's own conversation, and stays `working` while any
* run it started is still open, so the row under the last message reads this
* to say who it's answering for as long as the work is under way.
* to say who it's answering for as long as the work is under way. A
* hand-over is a task run, so its thread shows the task's own working row
* (with its progress) instead.
*/
export default async function grabConversationAsk({
user_id,
@@ -52,7 +54,8 @@ export default async function grabConversationAsk({
FROM bot_asks a
LEFT JOIN bots b ON b.id = a.requester_bot_id
LEFT JOIN workspaces w ON w.id = a.workspace_id
WHERE a.user_id = ? AND a.target_bot_id = ? AND a.status = 'working' ${place}
WHERE a.user_id = ? AND a.target_bot_id = ? AND a.status = 'working'
AND COALESCE(a.kind, 'ask') = 'ask' ${place}
ORDER BY a.id DESC
LIMIT 1`,
values,
@@ -169,6 +169,24 @@ describe("onAskJobEnded - the answer reply", () => {
});
});
describe("onAskJobEnded - a hand-over's run", () => {
test("its report ends the hand-over answered", async () => {
ask = { ...workingAsk(), kind: "hand_over" } as BUN_SQLITE_COBBLE_BOT_ASKS;
await onAskJobEnded({ job: answerJob(), text: real_answer });
expect(finished).toEqual([{ status: "answered", outcome: real_answer }]);
});
test("a failed run passes on why it failed", async () => {
ask = { ...workingAsk(), kind: "hand_over" } as BUN_SQLITE_COBBLE_BOT_ASKS;
await onAskJobEnded({ job: answerJob(), text: "The computer is down.", failed: true });
expect(finished).toEqual([{ status: "failed", outcome: "The computer is down." }]);
});
});
describe("onAskJobEnded - a run the answer handed the work to", () => {
test("a result while more work is open is relayed as an update and keeps the request open", async () => {
open_work = true;
@@ -4,7 +4,7 @@ import parseJobJson from "@/src/bots-queue/parse-job-json";
import claimsWorkUnderWay from "@/src/utils/claims-work-under-way";
import { WorkStartingTools } from "@/src/utils/reply-claim-problems";
import stripQuestionRefs from "@/src/utils/strip-question-refs";
import { AskStages } from "@/src/dict/ask-dict";
import { AskStages, isHandOverAsk } from "@/src/dict/ask-dict";
import hasOpenWork from "../bots-queue/has-open-work";
import deleteEmptyAskSession from "../bot-sessions/delete-empty-ask-session";
import askUpdateMessage from "./ask-update-message";
@@ -139,7 +139,13 @@ export default async function onAskJobEnded({ job, text, failed, tool_uses = []
await finishAsk({
ask,
status: "failed",
outcome: "The bot it was passed to couldn't answer. Try again, or ask another bot.",
/**
* A hand-over's run is the work itself: why it failed is what
* the bot that handed it over needs to hear.
*/
outcome: isHandOverAsk({ kind: ask.kind })
? (text || "").trim() || "The run failed."
: "The bot it was passed to couldn't answer. Try again, or ask another bot.",
});
return;
@@ -0,0 +1,218 @@
import BunSQLite from "@moduletrace/bun-sqlite";
import type { BUN_SQLITE_COBBLE_BOT_ASKS, BUN_SQLITE_COBBLE_BOTS, BunSQLiteTables } from "@/db/types/db";
import { AppData } from "@/src/data/app-data";
import { AskStages } from "@/src/dict/ask-dict";
import pushBotNotice from "@/src/bots-queue/push-bot-notice";
import AppError from "@/src/utils/app-error";
import askPreviousSessionId from "@/src/utils/ask-previous-session-id";
import { truncateText } from "@/src/utils/truncate-text";
import grabActiveBotSession from "../bot-sessions/grab-active-bot-session";
import startBotSession from "../bot-sessions/start-bot-session";
import enqueueBotJob from "../bots-queue/enqueue-bot-job";
import grabOpenHandOverRun from "../bots-queue/grab-open-hand-over-run";
import insertBotMessage from "../bots/insert-bot-message";
import insertUserMessage from "../bots/insert-user-message";
import grabWorkspaceName from "../workspaces/grab-workspace-name";
import askRequestMessage from "./ask-request-message";
import grabOpenAskBySession from "./grab-open-ask-by-session";
type Params = {
/**
* The user the work runs for.
*/
user_id: number | string;
/**
* The bot taking the work, and where it runs (null: its own chat).
*/
bot: BUN_SQLITE_COBBLE_BOTS;
workspace_id: number | null;
title: string;
brief: string;
/**
* The tracker task this run works, when a task is handed over.
*/
tracker_task_id?: number | null;
computer_id?: number | null;
/**
* The bot handing it over and the session it did from. None when a user
* hands a task over from the UI.
*/
requested_by_bot_id?: number | string | null;
requested_by_session_id?: number | string | null;
/**
* Who hands it over, for the line that opens the session when no
* hand-over record is made.
*/
notice: string;
task_ids?: number[];
};
export type HandOverRun = {
job_id: number;
session_id: number;
/**
* The hand-over's record (`bot_asks`, kind `hand_over`), when a bot
* handed the work over.
*/
ask_id: number | null;
};
/**
* Starts work handed to a bot the way `ask_bot`'s answer starts: in a
* session of its own (`startBotSession`), titled from the work, so it never
* lands in whatever the bot's conversation was on. When a bot handed it
* over, the session is a hand-over's (`bot_asks` with kind `hand_over`, no
* gate: the user asked for it in their own words), so its thread leads back
* to the session before it, the run (and any reply there while it is open)
* can send that bot a word with `update_requester`, its report goes back and
* wakes that bot (`onAskJobEnded`), and a late answer goes with
* `answer_requester`. Handed over from inside a crew request's answer, the
* run carries that request instead, so its result still reaches the bot
* that asked.
*/
export default async function startHandOverRun({
user_id,
bot,
workspace_id,
title,
brief,
tracker_task_id,
computer_id,
requested_by_bot_id,
requested_by_session_id,
notice,
task_ids,
}: Params): Promise<HandOverRun> {
const bot_id = Number(bot.id);
const open = await grabOpenHandOverRun({
user_id,
bot_id,
tracker_task_id,
title,
requested_by_session_id,
});
if (open) {
throw new AppError(
`${bot.name} already has "${open.title || title}" ${open.status == "pending" ? "queued" : "under way"} (run #${open.id}). Don't hand it over again; its result comes back when it ends.`,
);
}
const parent = requested_by_session_id
? await grabOpenAskBySession({ session_id: requested_by_session_id, user_id }).catch(() => null)
: null;
const previous = await grabActiveBotSession({ user_id, bot_id, workspace_id });
const session = await startBotSession({ user_id, bot_id, workspace_id });
const session_id = Number(session.id);
/**
* Titled from the work, so the sessions list says what it is before the
* bot writes anything (`nameBotSession` renames it later).
*/
await BunSQLite.sql({
sql: "UPDATE bot_sessions SET title = ? WHERE id = ? AND title IS NULL",
values: [title.slice(0, 120), session_id],
}).catch(() => null);
const requested = {
requested_by_bot_id: requested_by_bot_id || undefined,
requested_by_session_id: requested_by_session_id || undefined,
};
const tracker = tracker_task_id ? { tracker_task_id: Number(tracker_task_id) } : {};
if (!requested_by_bot_id || parent?.id) {
const job_id = Number(
await enqueueBotJob({
user_id,
bot_id,
session_id,
title,
instructions: brief,
params: { ...tracker, ...(parent?.id ? { ask_id: Number(parent.id) } : {}) },
computer_id: computer_id || undefined,
...requested,
}),
);
await pushBotNotice({
bot_id,
message: await insertBotMessage({ bot_id, session_id, workspace_id, text: notice, task_ids }),
});
return { job_id, session_id, ask_id: null };
}
const ask_row: BUN_SQLITE_COBBLE_BOT_ASKS = {
user_id: Number(user_id),
workspace_id: workspace_id || undefined,
requester_bot_id: Number(requested_by_bot_id),
target_bot_id: bot_id,
origin_session_id: Number(requested_by_session_id) || undefined,
title: truncateText({ text: title.trim(), max: 120 }),
request: truncateText({ text: brief.trim(), max: AppData.AskBriefMaxChars }),
status: "working",
kind: "hand_over",
session_id,
previous_session_id: askPreviousSessionId({ previous_session_id: previous?.id, session_id }) || undefined,
};
const inserted = await BunSQLite.insert<BUN_SQLITE_COBBLE_BOT_ASKS, (typeof BunSQLiteTables)[number]>({
table: "bot_asks",
data: [ask_row],
});
const ask_id = Number(inserted.postInsertReturn?.insertId) || 0;
if (!inserted.success || !ask_id) {
throw new Error(`Couldn't record the hand-over: ${inserted.msg}`);
}
const ask = { ...ask_row, id: ask_id };
const message = await insertUserMessage({
bot_id,
session_id,
workspace_id,
text: askRequestMessage({ ask, requester_name: "", place: await grabWorkspaceName({ workspace_id }) }),
from_ask_id: ask_id,
});
await pushBotNotice({ bot_id, message });
let job_id: number;
try {
job_id = Number(
await enqueueBotJob({
user_id,
bot_id,
session_id,
title,
instructions: brief,
params: { ...tracker, ask_id, stage: AskStages.answer },
computer_id: computer_id || undefined,
...requested,
}),
);
} catch (error) {
/**
* Nothing will work it: the tool call fails and says why, so the
* record ends without waking anyone.
*/
await BunSQLite.sql({
sql: `UPDATE bot_asks SET status = 'failed', outcome = ?, updated_at = ? WHERE id = ?`,
values: ["It couldn't be started.", Date.now(), ask_id],
}).catch(() => null);
throw error;
}
await BunSQLite.sql({
sql: `UPDATE bot_asks SET job_id = ?, updated_at = ? WHERE id = ?`,
values: [job_id, Date.now(), ask_id],
});
return { job_id, session_id, ask_id };
}
+4 -1
View File
@@ -25,6 +25,9 @@ type Params = {
* Stops every request a bot made from a run the user just stopped: the ask
* ends as `stopped` (the asking bot is told, but not woken, since its run is
* the one that was stopped) and whatever run was working it is cancelled.
* A hand-over is left alone: the user asked for that work themselves, and
* stopping the bot that handed it over (often still writing its reply when
* Stop is pressed) is not stopping the work; its report still comes back.
*/
export default async function stopAsks({ user_id, requester_bot_id, job_ids, session_ids }: Params) {
if (!job_ids.length && !session_ids.length) return [];
@@ -41,7 +44,7 @@ export default async function stopAsks({ user_id, requester_bot_id, job_ids, ses
const res = await BunSQLite.sql<BUN_SQLITE_COBBLE_BOT_ASKS>({
sql: `SELECT * FROM bot_asks WHERE user_id = ? AND requester_bot_id = ?
AND (${match}) AND status IN ('pending', 'working')`,
AND (${match}) AND status IN ('pending', 'working') AND COALESCE(kind, 'ask') = 'ask'`,
values: [
Number(user_id),
Number(requester_bot_id),
@@ -36,13 +36,20 @@ export default async function tellAskRequester({ ask, text, wake = true }: Param
const origin = await grabUserBotSession({ session_id: ask.origin_session_id!, user_id: Number(ask.user_id)! });
/**
* The asking bot's own place: the origin's, which a hand-over from the
* coordinator's own chat into a workspace doesn't share with the request
* (`ask.workspace_id` is where the work runs).
*/
const workspace_id = origin ? Number(origin.workspace_id) || null : Number(ask.workspace_id) || null;
const session =
origin?.status == "active"
? origin
: await ensureBotSession({
user_id: Number(ask.user_id)!,
bot_id: requester.id,
workspace_id: Number(ask.workspace_id) || null,
workspace_id,
});
if (!session?.id) {
@@ -52,7 +59,7 @@ export default async function tellAskRequester({ ask, text, wake = true }: Param
const message = await insertUserMessage({
bot_id: requester.id,
session_id: session.id,
workspace_id: Number(ask.workspace_id) || null,
workspace_id: Number(session.workspace_id) || null,
text,
from_ask_id: Number(ask.id),
});
@@ -17,10 +17,10 @@ type Params = {
export default async function answeringAskFace({
bot_id,
user_id,
}: Params): Promise<{ face: BotFace; status_line: string } | null> {
}: Params): Promise<{ face: BotFace; status_line: string; workspace_id: number | null } | null> {
const running = (
await BunSQLite.sql<{ id: number }>({
sql: `SELECT q.id FROM bots_queue q
await BunSQLite.sql<{ id: number; workspace_id: number | null }>({
sql: `SELECT q.id, q.workspace_id FROM bots_queue q
WHERE q.bot_id = ? AND q.status = 'processing'
AND q.session_id IN (SELECT id FROM bot_sessions WHERE user_id = ? AND ask_id IS NOT NULL)
LIMIT 1`,
@@ -28,5 +28,7 @@ export default async function answeringAskFace({
})
).payload?.[0];
return running ? { face: "working", status_line: BotReplyJobTitle } : null;
return running
? { face: "working", status_line: BotReplyJobTitle, workspace_id: Number(running.workspace_id) || null }
: null;
}
@@ -223,6 +223,7 @@ export default async function completeBotJob({
user_id,
face: "needs-you",
status_line: BotNeedsYouStatusLine,
workspace_id: job.workspace_id || null,
})
: await botFaceAfterJob({ bot_id: job.bot_id, user_id, kind: job.kind });
@@ -1,38 +1,16 @@
import BunSQLite from "@moduletrace/bun-sqlite";
import openBotTaskSql from "./open-bot-task-sql";
type Params = {
bot_id: number | string;
session_id: number | string;
/**
* Only a task with this title. Without it, any open task.
*/
title?: string;
/**
* Only a task on this computer.
*/
computer_id?: number | string | null;
};
type Params = Parameters<typeof openBotTaskSql>[0];
/**
* The bot's latest task in this session that's still queued or working
* (with this title, on this computer, when given), if any, so the same
* work isn't started twice.
* work isn't started twice. The run asking (`exclude_job_id`) is never its
* own obstacle.
*/
export default async function grabOpenBotTask({ bot_id, session_id, title, computer_id }: Params) {
const res = await BunSQLite.sql<{ id: number; status: string; title: string | null }>({
sql: `SELECT id, status, title FROM bots_queue
WHERE bot_id = ? AND session_id = ? AND kind = 'task'
AND status IN ('pending', 'processing')
${title != undefined ? `AND lower(trim(title)) = lower(trim(?))` : ""}
${computer_id ? `AND computer_id = ?` : ""}
ORDER BY id DESC LIMIT 1`,
values: [
bot_id,
session_id,
...(title != undefined ? [title] : []),
...(computer_id ? [Number(computer_id)] : []),
],
});
export default async function grabOpenBotTask(params: Params) {
const res = await BunSQLite.sql<{ id: number; status: string; title: string | null }>(openBotTaskSql(params));
return res.payload?.[0] || null;
}
@@ -0,0 +1,60 @@
import BunSQLite from "@moduletrace/bun-sqlite";
type Params = {
user_id: number | string;
bot_id: number | string;
/**
* The tracker task being handed over: one run of it at a time, whichever
* session it opened.
*/
tracker_task_id?: number | string | null;
/**
* A new brief's title and the conversation it was handed over from: the
* same work handed over twice from there.
*/
title?: string;
requested_by_session_id?: number | string | null;
};
/**
* The bot's open run of work already handed to it, if any. Every started
* hand-over opens a session of its own, so the per-session check
* (`grabOpenBotTask`) would never see the first one: this reads every
* session of the user's with that bot.
*/
export default async function grabOpenHandOverRun({
user_id,
bot_id,
tracker_task_id,
title,
requested_by_session_id,
}: Params) {
const task_id = Number(tracker_task_id) || 0;
const from = Number(requested_by_session_id) || 0;
if (!task_id && !(title && from)) return null;
const match = [
task_id ? `json_extract(COALESCE(params, '{}'), '$.tracker_task_id') = ?` : "",
title && from ? `(requested_by_session_id = ? AND lower(trim(title)) = lower(trim(?)))` : "",
]
.filter(Boolean)
.join(" OR ");
const res = await BunSQLite.sql<{ id: number; status: string; title: string | null }>({
sql: `SELECT id, status, title FROM bots_queue
WHERE bot_id = ? AND kind = 'task' AND status IN ('pending', 'processing')
AND session_id IN (SELECT id FROM bot_sessions WHERE user_id = ? AND bot_id = ?)
AND (${match})
ORDER BY id DESC LIMIT 1`,
values: [
Number(bot_id),
Number(user_id),
Number(bot_id),
...(task_id ? [task_id] : []),
...(title && from ? [from, title] : []),
],
});
return res.payload?.[0] || null;
}
@@ -16,16 +16,16 @@ type Params = {
* The face a bot should show one user while other jobs for them are
* still running: thinking while a reply runs (it's short, and its chat
* needs the row), else working on a task (in its workspace, if it runs in
* one). Null when none is running. Work in a crew request's hidden session
* one), with the workspace of that job's conversation. Null when none is running. Work in a crew request's hidden session
* or a silent hook's thread never counts: it shows there, never on the face.
*/
export default async function grabRunningBotJobFace({
bot_id,
user_id,
}: Params): Promise<{ face: BotFace; status_line: string } | null> {
}: Params): Promise<{ face: BotFace; status_line: string; workspace_id: number | null } | null> {
const jobs = (
await BunSQLite.sql<{ kind: string; workspace_name: string | null }>({
sql: `SELECT q.kind, w.name AS workspace_name FROM bots_queue q
await BunSQLite.sql<{ kind: string; workspace_id: number | null; workspace_name: string | null }>({
sql: `SELECT q.kind, q.workspace_id, w.name AS workspace_name FROM bots_queue q
LEFT JOIN workspaces w ON w.id = q.workspace_id
WHERE q.bot_id = ? AND q.status = 'processing'
AND q.session_id IN (SELECT id FROM bot_sessions WHERE user_id = ? AND ${followedSessionSql()})
@@ -34,11 +34,21 @@ export default async function grabRunningBotJobFace({
})
).payload || [];
if (jobs.some((job) => job.kind == "reply")) return { face: "working", status_line: BotReplyJobTitle };
const reply = jobs.find((job) => job.kind == "reply");
if (reply) {
return { face: "working", status_line: BotReplyJobTitle, workspace_id: Number(reply.workspace_id) || null };
}
const task = jobs.find((job) => job.kind == "task");
if (task) return { face: "working", status_line: taskStatusLine({ workspace_name: task.workspace_name }) };
if (task) {
return {
face: "working",
status_line: taskStatusLine({ workspace_name: task.workspace_name }),
workspace_id: Number(task.workspace_id) || null,
};
}
return null;
}
@@ -116,6 +116,7 @@ export default async function notifyBotJobFailed({
user_id,
face: "needs-you",
status_line: BotNeedsYouStatusLine,
workspace_id: job.workspace_id || null,
})
: null;
@@ -0,0 +1,60 @@
import { Database } from "bun:sqlite";
import { beforeEach, describe, expect, test } from "bun:test";
import openBotTaskSql from "./open-bot-task-sql";
const db = new Database(":memory:");
beforeEach(() => {
db.run(`CREATE TABLE IF NOT EXISTS bots_queue (
id INTEGER PRIMARY KEY,
status TEXT,
kind TEXT,
bot_id INTEGER,
session_id INTEGER,
computer_id INTEGER,
title TEXT
)`);
db.run(`DELETE FROM bots_queue`);
});
function insert(row: { id: number; status: string; title?: string; computer_id?: number }) {
db.run(
`INSERT INTO bots_queue (id, status, kind, bot_id, session_id, computer_id, title) VALUES (?, ?, 'task', 3, 95, ?, ?)`,
[row.id, row.status, row.computer_id ?? 1, row.title ?? "Fix baseline"],
);
}
function found(params: Partial<Parameters<typeof openBotTaskSql>[0]>) {
const query = openBotTaskSql({ bot_id: 3, session_id: 95, ...params });
return (db.query(query.sql).all(...query.values) as { id: number }[]).map((row) => row.id);
}
describe("openBotTaskSql", () => {
test("finds the open run on the computer", () => {
insert({ id: 680, status: "processing" });
expect(found({ computer_id: 1 })).toEqual([680]);
});
test("a task run handing work on is not its own obstacle (jobs 680, 700)", () => {
insert({ id: 680, status: "processing" });
expect(found({ computer_id: 1, exclude_job_id: 680 })).toEqual([]);
expect(found({ title: "Fix baseline", exclude_job_id: 680 })).toEqual([]);
});
test("another open run still counts when the asking run is left out", () => {
insert({ id: 679, status: "pending" });
insert({ id: 680, status: "processing" });
expect(found({ computer_id: 1, exclude_job_id: 680 })).toEqual([679]);
});
test("finished runs and other computers never count", () => {
insert({ id: 1, status: "completed" });
insert({ id: 2, status: "processing", computer_id: 2 });
expect(found({ computer_id: 1 })).toEqual([]);
});
});
@@ -0,0 +1,45 @@
type Params = {
bot_id: number | string;
session_id: number | string;
/**
* Only a task with this title. Without it, any open task.
*/
title?: string;
/**
* Only a task on this computer.
*/
computer_id?: number | string | null;
/**
* The run asking: a task run handing its work on is not the open run
* that work would wait behind. Without it, a task report's `send_reply`
* with `work` was refused against its own job (jobs 680 and 700), and a
* finished report was thrown away.
*/
exclude_job_id?: number | string | null;
};
/**
* The bot's latest task in this session that's still queued or working
* (with this title, on this computer, when given), leaving out the run
* that asks.
*/
export default function openBotTaskSql({ bot_id, session_id, title, computer_id, exclude_job_id }: Params) {
const exclude = Number(exclude_job_id) || 0;
return {
sql: `SELECT id, status, title FROM bots_queue
WHERE bot_id = ? AND session_id = ? AND kind = 'task'
AND status IN ('pending', 'processing')
${title != undefined ? `AND lower(trim(title)) = lower(trim(?))` : ""}
${computer_id ? `AND computer_id = ?` : ""}
${exclude ? `AND id != ?` : ""}
ORDER BY id DESC LIMIT 1`,
values: [
bot_id,
session_id,
...(title != undefined ? [title] : []),
...(computer_id ? [Number(computer_id)] : []),
...(exclude ? [exclude] : []),
],
};
}
@@ -7,6 +7,8 @@ import type {
import insertBotMessage from "../bots/insert-bot-message";
import ensureBotSession from "../bot-sessions/ensure-bot-session";
import stripQuestionRefs from "@/src/utils/strip-question-refs";
import parseJobJson from "@/src/bots-queue/parse-job-json";
import { AskStages } from "@/src/dict/ask-dict";
type Params = {
job: BUN_SQLITE_COBBLE_BOTS_QUEUE;
@@ -34,6 +36,12 @@ export default async function relayJobToRequester({ job, text, failed, task_ids
return null;
}
/**
* A hand-over's run is its request's answer: `onAskJobEnded` reports it
* back (and wakes the bot that handed it over), so it isn't told twice.
*/
if (parseJobJson({ text: job.params })?.stage == AskStages.answer) return null;
const worker = (
await BunSQLite.sql<BUN_SQLITE_COBBLE_BOTS>({
sql: `SELECT name FROM bots WHERE id = ? LIMIT 1`,
@@ -8,15 +8,20 @@ type Params = {
/**
* A bot's face and status line as one user sees it: idle when it has
* none for them.
* none for them, and the workspace of the conversation that set it
* (`face_workspace_id`, null for its own chat).
*/
export default async function grabBotFace({ bot_id, user_id }: Params) {
const row = (
await BunSQLite.sql<{ face: BotFace; status_line: string }>({
sql: `SELECT face, status_line FROM bot_user_faces WHERE bot_id = ? AND user_id = ? LIMIT 1`,
await BunSQLite.sql<{ face: BotFace; status_line: string; workspace_id: number | null }>({
sql: `SELECT face, status_line, workspace_id FROM bot_user_faces WHERE bot_id = ? AND user_id = ? LIMIT 1`,
values: [bot_id, user_id],
})
).payload?.[0];
return { face: (row?.face || "idle") as BotFace, status_line: row?.status_line || "" };
return {
face: (row?.face || "idle") as BotFace,
status_line: row?.status_line || "",
face_workspace_id: Number(row?.workspace_id) || null,
};
}
@@ -0,0 +1,25 @@
import BunSQLite from "@moduletrace/bun-sqlite";
/**
* Faces set before `bot_user_faces.workspace_id` existed say nothing of the
* chat they came from, so a bot that needed the user in a workspace linked
* to its own chat from the coordinator's Crew tab. A face that needs the
* user or shows work takes the workspace of that bot's latest job for that
* user. Faces set since then carry their own; one whose latest job was in
* the bot's own chat stays null, so running it again changes nothing.
*/
export default async function migrateFaceWorkspaces() {
const res = await BunSQLite.sql({
sql: `UPDATE bot_user_faces SET workspace_id = (
SELECT q.workspace_id FROM bots_queue q
JOIN bot_sessions s ON s.id = q.session_id
WHERE q.bot_id = bot_user_faces.bot_id AND s.user_id = bot_user_faces.user_id
ORDER BY q.id DESC LIMIT 1
)
WHERE workspace_id IS NULL AND face IN ('needs-you', 'working')`,
});
if (!res.success) {
throw new Error(`Couldn't place the existing bot faces: ${res.error}`);
}
}
+15 -6
View File
@@ -9,6 +9,12 @@ type Params = {
user_id: number | string;
face: BotFace;
status_line?: string;
/**
* The workspace of the conversation the job is in, null for the bot's
* own chat: where the coordinator's Crew list links a bot that needs
* the user or is working.
*/
workspace_id?: number | string | null;
};
export type BotFaceChange = {
@@ -16,27 +22,30 @@ export type BotFaceChange = {
user_id: number;
face: BotFace;
status_line: string;
workspace_id: number | null;
};
/**
* Sets a bot's face (its status) and status line as one user sees it
* (`bot_user_faces`). Other users keep their own. Callers must check the
* bot first.
* bot first. A face set without `workspace_id` reads as the bot's own chat.
*/
export default async function setBotFace({
bot_id,
user_id,
face,
status_line = "",
workspace_id = null,
}: Params): Promise<BotFaceChange> {
const now = Date.now();
const place = Number(workspace_id) || null;
await BunSQLite.sql({
sql: `INSERT INTO bot_user_faces (created_at, updated_at, bot_id, user_id, face, status_line)
VALUES (?, ?, ?, ?, ?, ?)
ON CONFLICT(bot_id, user_id) DO UPDATE SET face = excluded.face, status_line = excluded.status_line, updated_at = excluded.updated_at`,
values: [now, now, bot_id, user_id, face, status_line],
sql: `INSERT INTO bot_user_faces (created_at, updated_at, bot_id, user_id, face, status_line, workspace_id)
VALUES (?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(bot_id, user_id) DO UPDATE SET face = excluded.face, status_line = excluded.status_line, workspace_id = excluded.workspace_id, updated_at = excluded.updated_at`,
values: [now, now, bot_id, user_id, face, status_line, place],
});
return { id: Number(bot_id), user_id: Number(user_id), face, status_line };
return { id: Number(bot_id), user_id: Number(user_id), face, status_line, workspace_id: place };
}
@@ -25,7 +25,7 @@ export default async function grabHookProposalView({ proposal_id, user_id }: Par
) as number[];
const [bot, workspace, computers] = await Promise.all([
BunSQLite.sql<{ name: string }>({ sql: `SELECT name FROM bots WHERE id = ?`, values: [proposal.bot_id] }),
BunSQLite.sql<{ name: string; kind: string | null }>({ sql: `SELECT name, kind FROM bots WHERE id = ?`, values: [proposal.bot_id] }),
proposal.workspace_id
? BunSQLite.sql<{ name: string }>({ sql: `SELECT name FROM workspaces WHERE id = ?`, values: [proposal.workspace_id] })
: null,
@@ -56,6 +56,8 @@ export default async function grabHookProposalView({ proposal_id, user_id }: Par
current,
workspace_name: workspace?.payload?.[0]?.name || null,
computers: new Map((computers?.payload || []).map((c) => [Number(c.id), c.name || ""])),
bot_id: proposal.bot_id,
bot_kind: bot.payload?.[0]?.kind || null,
}),
reason: proposal.reason,
};
@@ -4,9 +4,8 @@ import AppError from "@/src/utils/app-error";
import handOverPlace from "@/src/utils/hand-over-place";
import grabUserConversation from "../bot-sessions/grab-user-conversation";
import ensureBotSession from "../bot-sessions/ensure-bot-session";
import enqueueBotJob from "../bots-queue/enqueue-bot-job";
import grabOpenBotTask from "../bots-queue/grab-open-bot-task";
import grabOpenAskBySession from "../asks/grab-open-ask-by-session";
import startHandOverRun from "../asks/start-hand-over-run";
import grabOpenHandOverRun from "../bots-queue/grab-open-hand-over-run";
import grabBotById from "../bots/grab-bot-by-id";
import insertBotMessage from "../bots/insert-bot-message";
import grabBotComputers from "../computers/grab-bot-computers";
@@ -64,6 +63,10 @@ export type HandedOverTask = {
* The job doing the work; null when it wasn't started.
*/
job_id: number | string | null;
/**
* The session the run opened; null when it wasn't started.
*/
session_id: number | null;
bot_name: string;
workspace_id: number | null;
/**
@@ -79,9 +82,13 @@ export type HandedOverTask = {
* it to be worked, so by default it only moves: the task goes to the new
* bot's list as to do, no job is queued and the notice says so. With
* `start` true (the user asked for the work to begin now) the task goes to
* doing, its log says who handed it over, and a job is queued in the new
* bot's conversation with the task's brief and `params.tracker_task_id`, so
* the bot moves this same task along and the job's end is noted on it.
* doing, its log says who handed it over, and a job is queued with the
* task's brief and `params.tracker_task_id`, so the bot moves this same task
* along and the job's end is noted on it. That run gets a session of its own
* (`startHandOverRun`), as a crew request's answer does: handed over by a
* bot, its report goes back to that bot and the run can send it a word on
* the way. A task that only moves leaves its notice in the conversation the
* new bot is in, since nothing runs yet.
*/
export default async function handOverTask({
user_id,
@@ -122,13 +129,12 @@ export default async function handOverTask({
* The user must reach the bot there: its own chat, or the workspace.
*/
const conversation = await grabUserConversation({ user_id, bot_id: bot.id, workspace_id: run_workspace_id });
const session = await ensureBotSession({ user_id, bot_id: bot.id, workspace_id: run_workspace_id });
const title = (task.title || "Task").slice(0, 80);
const open = start ? await grabOpenBotTask({ bot_id: bot.id, session_id: Number(session.id), title }) : null;
const open = start ? await grabOpenHandOverRun({ user_id, bot_id: bot.id, tracker_task_id: task.id }) : null;
if (open) {
throw new AppError(
`${bot.name} already has "${title}" ${open.status == "pending" ? "queued" : "under way"} (job #${open.id}).`,
`${bot.name} already has "${title}" ${open.status == "pending" ? "queued" : "under way"} (run #${open.id}).`,
);
}
@@ -147,28 +153,22 @@ export default async function handOverTask({
.filter(Boolean)
.join("\n\n");
/**
* When the hand-over comes from a crew request being answered, the run
* carries the ask_id too, so its result goes back to the bot that asked.
*/
const ask =
start && requested_by_session_id
? await grabOpenAskBySession({ session_id: requested_by_session_id, user_id })
: null;
const job_id = start
? await enqueueBotJob({
const run = start
? await startHandOverRun({
user_id,
bot_id: bot.id,
session_id: Number(session.id),
bot,
workspace_id: run_workspace_id,
title,
instructions: brief,
params: { tracker_task_id: Number(task.id), ...(ask?.id ? { ask_id: Number(ask.id) } : {}) },
computer_id: computers[0]?.id || undefined,
requested_by_bot_id: requested_by_bot_id || undefined,
requested_by_session_id: requested_by_session_id || undefined,
brief,
tracker_task_id: Number(task.id),
computer_id: computers[0]?.id || null,
requested_by_bot_id,
requested_by_session_id,
notice: `${handed_by} handed me task #${task.id}: **${title}**`,
task_ids: [Number(task.id)],
})
: null;
const job_id = run?.job_id ?? null;
const status = start ? "doing" : "todo";
await updateTask({
@@ -185,20 +185,25 @@ export default async function handOverTask({
bot_id: requested_by_bot_id || null,
});
await pushBotNotice({
bot_id: bot.id,
message: await insertBotMessage({
if (!start) {
const session = await ensureBotSession({ user_id, bot_id: bot.id, workspace_id: run_workspace_id });
await pushBotNotice({
bot_id: bot.id,
session_id: Number(session.id),
workspace_id: run_workspace_id,
text: `${handed_by} handed me task #${task.id}: **${title}**${start ? "" : ". It's on my list; I'll start when you say."}`,
task_ids: [Number(task.id)],
}),
});
message: await insertBotMessage({
bot_id: bot.id,
session_id: Number(session.id),
workspace_id: run_workspace_id,
text: `${handed_by} handed me task #${task.id}: **${title}**. It's on my list; I'll start when you say.`,
task_ids: [Number(task.id)],
}),
});
}
return {
task: { ...moved, status },
job_id,
session_id: run?.session_id ?? null,
bot_name: conversation.bot.name || bot.name || "The bot",
workspace_id: run_workspace_id,
joined,
@@ -0,0 +1,43 @@
/**
* The shapes providers use when their own content filter refused the
* request (Alibaba's Model Studio: "Input text data may contain
* inappropriate content.", code `data_inspection_failed`; Azure's
* `content_filter`; OpenAI's usage-policy refusals).
*/
const ContentFilterPhrases = [
"inappropriate content",
"data_inspection_failed",
"data inspection failed",
"content_filter",
"content filter",
"content management policy",
"content_policy_violation",
"content policy",
"responsibleaipolicyviolation",
"violates our usage polic",
"flagged by our moderation",
];
type Params = {
status: number;
/**
* The provider's own words, already read out of its error body.
*/
detail?: string;
};
/**
* Whether the provider's content filter refused the call. The flagged text
* is somewhere in the run's transcript (often a page or a tool's output,
* not the user's request), so retrying the same transcript is refused the
* same way: job 698 lost 41 turns to it. A refusal is a 4xx; a filter that
* is down ("content safety screening is temporarily unavailable", a 503) is
* an outage, and stays retryable.
*/
export default function isContentFilterError({ status, detail }: Params) {
if (status < 400 || status >= 500) return false;
const text = (detail || "").toLowerCase();
return ContentFilterPhrases.some((phrase) => text.includes(phrase));
}
@@ -187,4 +187,32 @@ describe("toHarnessError", () => {
expect(error.fatal).toBe(false);
expect(error.message).not.toContain("Settings > Models");
});
test("a provider's content filter refusing the run is fatal and says so (job 698)", () => {
const error = toHarnessError({
status: 400,
body: JSON.stringify({
error: { code: "data_inspection_failed", message: "Input text data may contain inappropriate content." },
}),
provider_name: "Alibaba Cloud Token Plan",
url: "https://token-plan.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1/chat/completions",
});
expect(error.fatal).toBe(true);
expect(error.retryable).toBe(false);
expect(error.message).toContain("Input text data may contain inappropriate content.");
expect(error.message).toContain("content filter refused this run");
expect(error.message).toContain("not necessarily your message");
});
test("a content filter that is down is an outage, never a refusal", () => {
const error = toHarnessError({
status: 503,
body: JSON.stringify({ error: { message: "content safety screening is temporarily unavailable" } }),
provider_name: "Nvidia Cloud",
});
expect(error.fatal).toBe(false);
expect(error.retryable).toBe(true);
});
});
+14 -4
View File
@@ -1,5 +1,6 @@
import HarnessError from "../harness-error";
import isContextOverflowError from "./is-context-overflow-error";
import isContentFilterError from "./is-content-filter-error";
import parseRetryAt from "./parse-retry-at";
import redactProviderError from "./redact-provider-error";
@@ -66,17 +67,26 @@ export default function toHarnessError({
*/
const overflow = isContextOverflowError({ status, detail: provider_detail });
/**
* The provider's content filter refused something in the transcript:
* the same transcript is refused again on every retry, so the run stops
* here and says plainly that it was the provider's filter (job 698).
*/
const filtered = !overflow && isContentFilterError({ status, detail: provider_detail });
const advice = overflow
? "\nSet this model's context window under Settings > Models: a model with none declared is assumed to have 1,000,000."
: "";
: filtered
? `\n${provider_name}'s content filter refused this run: something in the conversation or what its tools read was flagged, not necessarily your message. Run it again with a narrower request, or use a model from another provider under Settings > Models.`
: "";
const retryable = [408, 409, 425, 429].includes(status) || status >= 500;
const retryable = !filtered && ([408, 409, 425, 429].includes(status) || status >= 500);
return new HarnessError({
message: `${redactProviderError({ text: `${provider_name}: ${detail}${address}${hint}` }).slice(0, overflow ? 320 : 400)}${advice}`,
message: `${redactProviderError({ text: `${provider_name}: ${detail}${address}${hint}` }).slice(0, overflow || filtered ? 320 : 400)}${advice}`,
status,
retryable,
fatal: overflow,
fatal: overflow || filtered,
retry_at: retryable && headers ? parseRetryAt({ headers }) : undefined,
provider_wide: status == 401 || status == 402,
candidate_key,
+49
View File
@@ -2311,6 +2311,55 @@ describe("runTextLoop required send_reply", () => {
expect(result.text).toBe("");
});
/**
* Job 694: the first turn wrote the message beside an `ask_user` whose
* options were objects, the second passed the questions as a string,
* and the third put the card up with no text. The model was told
* send_reply had failed (it was never called), the message from turn
* one was lost, and the run failed with the card finally up.
*/
test("a refused card is blamed on the card, keeps its message, and the run gets to close once it goes up", async () => {
let card_calls = 0;
const pickyAsk: HarnessTool<{ options: string[] }> = {
name: "ask_user",
description: "Asks the user.",
schema: z.object({ options: z.array(z.string()) }),
run: async () => {
card_calls++;
return "Asked. The card is on your message.";
},
};
const { generate, seen } = scripted([
{
text: "Two decisions before I generate.",
tool_calls: [{ id: "a1", name: "ask_user", arguments: `{"options":[{"label":"Crop"},{"label":"Keep"}]}` }],
},
{ tool_calls: [{ id: "a2", name: "ask_user", arguments: `{"options":"[\\"Crop\\",\\"Keep\\"]"}` }] },
{ tool_calls: [{ id: "a3", name: "ask_user", arguments: `{"options":["Crop","Keep"]}` }] },
{ tool_calls: [{ id: "s1", name: "send_reply", arguments: `{"status":"done"}` }] },
]);
const result = await runTextLoop({
system: "s",
messages: [{ role: "user", content: "Harden the prompt." }],
tools: [sendReply, pickyAsk],
generate,
resolveCandidates,
require_closing_answer: true,
});
const told = seen[1]!.messages.at(-1)!.content as string;
expect(told).not.toBe(replyClosingFailedNote);
expect(told).toContain("The card was not put up");
expect(told).toContain("ask_user");
expect(card_calls).toBe(1);
expect(seen).toHaveLength(4);
expect(result.review_note).toBeUndefined();
expect(result.text).toBe("Two decisions before I generate.");
});
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"}` }] },
+59 -6
View File
@@ -13,6 +13,7 @@ import {
repairedAnswerNote,
repeatedAnswerNote,
replyCardFailedNote,
replyCardOnlyFailedNote,
replyClosingFailedNote,
replyClosingMixedNote,
replyClosingRequiredNote,
@@ -669,6 +670,20 @@ export default async function runTextLoop({
* nothing left to say.
*/
let card_text = "";
/**
* The message a turn wrote beside a card the tool refused. It isn't the
* reply yet (it points at a card no one can see), but it is the sentence
* the card belongs under: once a later turn puts the card up, it becomes
* `card_text`. Job 694 wrote it on its first turn, fixed the card's
* arguments twice, and then had nothing left to send.
*/
let failed_card_text = "";
/**
* A card call was refused earlier in this run. When the card then goes
* up, the run has made progress, so it gets one more turn for
* `send_reply` instead of failing on the retries the refusals used up.
*/
let card_refused = false;
/**
* A run whose prompt no longer fits the working context, with nothing
* trimmable left, has been told, once (`oversizedRequestNote`).
@@ -1280,6 +1295,7 @@ export default async function runTextLoop({
*/
draft_text = "";
card_text = "";
failed_card_text = "";
told_closing_text = false;
continue;
}
@@ -1512,12 +1528,19 @@ export default async function runTextLoop({
*/
const send_reply_failed = failed_closing.some((use) => use.name === SendReplyToolName);
const failed_cards = failed_closing.filter((use) => use.name !== SendReplyToolName).map((use) => use.name);
const closing_failed_note =
send_reply_failed || !called_send_reply
? called_send_reply || require_closing_answer
? replyClosingFailedNote
: closingFailedNote
: replyCardFailedNote({ tools: failed_cards });
/**
* A card refused in a turn with no `send_reply` is the card's
* failure, not the send's: telling the model "send_reply did not go
* through" there hid the schema error it had to fix (job 694, three
* turns on `ask_user`'s options).
*/
const closing_failed_note = send_reply_failed
? replyClosingFailedNote
: called_send_reply
? replyCardFailedNote({ tools: failed_cards })
: require_closing_answer
? replyCardOnlyFailedNote({ tools: failed_cards })
: closingFailedNote;
const closing_worked = closing && !closing_failed && closing_required;
/**
* The message this turn wrote beside the call. An earlier draft is
@@ -1545,6 +1568,35 @@ export default async function runTextLoop({
* and pairing it with "Which date rule?" put "I checked the date
* rules." under it.
*/
const card_went_up = asked_something && closing && !closing_failed;
/**
* A refused card keeps the message written beside it for the turn
* that puts the card up; a turn that drops the card (no card call)
* never gets it, since it pointed at a card that isn't there.
*/
if (asked_something && closing_failed && written_text) {
failed_card_text = written_text;
}
if (card_went_up && !written_text && !card_text.trim() && failed_card_text.trim()) {
card_text = failed_card_text;
}
if (card_went_up) failed_card_text = "";
/**
* The card is up after refusals spent the retries: one more turn for
* `send_reply`, since the run made the progress the bound is there to
* demand (job 694 put its card up on the third try and then failed).
*/
if (card_went_up && card_refused && !called_send_reply) {
closing_retries = Math.min(closing_retries, AppData.MaxClosingRetries - 1);
card_refused = false;
}
if (asked_something && closing_failed) card_refused = true;
const carry_card = Boolean(card_text.trim()) && !unfinishedAnswerText({ text: card_text });
const carry_draft =
told_closing_text && !asked_something && !unfinishedAnswerText({ text: draft_text });
@@ -1729,6 +1781,7 @@ export default async function runTextLoop({
*/
draft_text = "";
card_text = "";
failed_card_text = "";
told_closing_text = false;
continue;
}
+13 -47
View File
@@ -1,17 +1,12 @@
import { z } from "zod";
import type { BUN_SQLITE_COBBLE_BOTS, BUN_SQLITE_COBBLE_WORKSPACES } from "@/db/types/db";
import pushBotNotice from "@/src/bots-queue/push-bot-notice";
import assertUserAsked from "@/src/functions/backend/db/bots/assert-user-asked";
import enqueueBotJob from "@/src/functions/backend/db/bots-queue/enqueue-bot-job";
import grabOpenBotTask from "@/src/functions/backend/db/bots-queue/grab-open-bot-task";
import grabOpenAskBySession from "@/src/functions/backend/db/asks/grab-open-ask-by-session";
import startHandOverRun from "@/src/functions/backend/db/asks/start-hand-over-run";
import ensureBotInWorkspace from "@/src/functions/backend/db/workspaces/ensure-bot-in-workspace";
import grabRunTask from "@/src/functions/backend/db/tasks/grab-run-task";
import handOverTask from "@/src/functions/backend/db/tasks/hand-over-task";
import insertBotMessage from "@/src/functions/backend/db/bots/insert-bot-message";
import grabCrewWorkers from "@/src/functions/backend/db/bots/grab-crew-workers";
import grabBotComputers from "@/src/functions/backend/db/computers/grab-bot-computers";
import ensureBotSession from "@/src/functions/backend/db/bot-sessions/ensure-bot-session";
import type { HarnessTool } from "../../types";
type Params = {
@@ -118,7 +113,7 @@ export default function delegateTaskTool({
return {
name: "delegate_task",
description: `Hand a task to a crew member. They run it in the background and post the result in their own conversation; it's also reported back here when they finish or fail. Write the instructions as a full brief: what to do, where, and how they'll know it's done. To hand over a task already on a list (list_tasks), pass its task_id instead of writing a new one: it moves to the crew member's list (a workspace's task stays on the workspace's list and runs there) and they work that same task; title and instructions are then optional, the task's brief is used and yours is added to it. Handing a task over never starts it: it lands there as to do, and only start: true (when the user asked for the work to begin now) marks it doing and queues the run. When the user asked for the move but not for it to start, ask first with ask_user (one card, every task they named: hand over and start, hand over to wait, leave it) and hand over only once they've answered. A new brief with no task_id always runs at once. Pass the user's own words asking for this in because; a quote they did not write in this conversation is refused. Crew: ${crew}.${
description: `Hand a task to a crew member. They run it in the background in a session of its own in their conversation (never the one they were in), can send you a word on the way, and their report comes back here when they finish or fail. Write the instructions as a full brief: what to do, where, and how they'll know it's done. To hand over a task already on a list (list_tasks), pass its task_id instead of writing a new one: it moves to the crew member's list (a workspace's task stays on the workspace's list and runs there) and they work that same task; title and instructions are then optional, the task's brief is used and yours is added to it. Handing a task over never starts it: it lands there as to do, and only start: true (when the user asked for the work to begin now) marks it doing and queues the run. When the user asked for the move but not for it to start, ask first with ask_user (one card, every task they named: hand over and start, hand over to wait, leave it) and hand over only once they've answered. A new brief with no task_id always runs at once. Pass the user's own words asking for this in because; a quote they did not write in this conversation is refused. Crew: ${crew}.${
workspace_id
? ` You are working in a workspace, so the task runs there: in this workspace's context.`
: ` Leave workspace_id out to run it in the crew member's own chat: only its own memory, files and directly assigned computers apply there, and the user finds the result by talking to it on its own. Add workspace_id to run it in one of the user's workspaces instead: the workspace's shared context, the member's instructions and memory there, its files and its computers (the workspace's own and the member's) all apply, and the result lands in its conversation in that workspace, beside the project it belongs to. Pick a workspace when the work belongs to that project; the member is added to it when it isn't in it yet. Workspaces: ${places || "none"}.`
@@ -220,7 +215,7 @@ export default function delegateTaskTool({
return `Task #${task.id} "${task.title}" is on ${worker.name}'s list now${where}, as to do. Nothing is running: they start when the user tells them to.${handed.joined}`;
}
return `Task #${task.id} "${task.title}" is with ${worker.name} now (job #${handed.job_id})${where}, marked doing.${handed.joined} They work that same task; the result is reported back here.`;
return `Task #${task.id} "${task.title}" is with ${worker.name} now (job #${handed.job_id})${where}, marked doing.${handed.joined} They work that same task in a session of its own; their report comes back here when it ends, and they can send you a word on the way.`;
}
if (!args.title?.trim() || !args.instructions?.trim()) {
@@ -238,55 +233,26 @@ export default function delegateTaskTool({
bot_id: worker.id,
workspace_id: target_workspace_id,
});
const worker_session = await ensureBotSession({
user_id,
bot_id: worker.id,
workspace_id: target_workspace_id,
});
const open = await grabOpenBotTask({
bot_id: worker.id,
session_id: Number(worker_session.id),
title,
});
if (open) {
throw new Error(
`${worker.name} already has run #${open.id} "${title}" ${open.status == "pending" ? "queued" : "under way"}. Don't hand it over again; it's reported back here when they finish.`,
);
}
/**
* When the hand-over comes from a crew request being answered,
* the worker's run carries the ask_id so its result also goes
* back to the bot that asked, not just to this conversation.
* The run opens a session of its own in the worker's
* conversation, so it never lands in whatever that was on, and
* its report comes back here (`startHandOverRun`).
*/
const ask = await grabOpenAskBySession({ session_id, user_id });
const job_id = await enqueueBotJob({
const { job_id } = await startHandOverRun({
user_id,
bot_id: worker.id,
session_id: Number(worker_session.id),
bot: worker,
workspace_id: target_workspace_id,
title,
instructions,
computer_id: computers[0]?.id || undefined,
brief: instructions,
computer_id: computers[0]?.id || null,
requested_by_bot_id: requester_id,
requested_by_session_id: session_id,
params: ask?.id ? { ask_id: Number(ask.id) } : undefined,
});
await pushBotNotice({
bot_id: worker.id,
message: await insertBotMessage({
bot_id: worker.id,
session_id: Number(worker_session.id),
workspace_id: target_workspace_id,
text: `${requester_name} asked me to: **${title}**`,
}),
notice: `${requester_name} asked me to: **${title}**`,
});
return `Run #${job_id} is with ${worker.name}${
target_workspace_id ? ` in workspace ${target_workspace_id}` : " in their own chat"
} (a run, not a task on the to-do list: list_tasks doesn't show it).${joined} Their result will be in that conversation and reported back here.`;
}, in a session of its own there (a run, not a task on the to-do list: list_tasks doesn't show it).${joined} Their report comes back here when it ends, and they can send you a word on the way.`;
},
};
}
@@ -108,7 +108,7 @@ describe("handOverTaskTool", () => {
expect(handedArgs?.start).toBe(true);
expect(String(answer)).toContain("is with Software Engineer now (job #312)");
expect(String(answer)).toContain("it's off your list");
expect(String(answer)).toContain("their result is reported back here");
expect(String(answer)).toContain("their report comes back here when it ends");
});
test("the same task, not a copy: it reports the new bot's joined note", async () => {
+1 -1
View File
@@ -139,7 +139,7 @@ export default function handOverTaskTool({ user_id, bot, session_id, powers, wor
return `Task #${task.id} "${task.title}" is on ${handed.bot_name}'s list now${where}, as to do. Nothing is running: they start when the user tells them to.${handed.joined ? ` ${handed.joined}` : ""}`;
}
return `Task #${task.id} "${task.title}" is with ${handed.bot_name} now (job #${handed.job_id})${where}, marked doing, and it's off your list.${handed.joined} They work that same task; their result is reported back here.`;
return `Task #${task.id} "${task.title}" is with ${handed.bot_name} now (job #${handed.job_id})${where}, marked doing, and it's off your list.${handed.joined} They work that same task in a session of its own; their report comes back here when it ends, and they can send you a word on the way.`;
},
};
}
@@ -56,7 +56,7 @@ export default function grabBotHookTools({
pauseHookTool({ user_id, bot_id, is_coordinator, workspace_id }),
deleteHookTool({ user_id, bot_id, is_coordinator, workspace_id }),
...(session_id && onPropose
? [proposeHookTool({ user_id, bot_id, session_id, workspace_id, computers, onPropose })]
? [proposeHookTool({ user_id, bot_id, session_id, workspace_id, computers, is_coordinator, onPropose })]
: []),
];
}
@@ -4,6 +4,7 @@ import { AppData } from "@/src/data/app-data";
import { BotHookSources, type BotHookSource } from "@/src/dict/bot-hook-dict";
import createHookProposal from "@/src/functions/backend/db/hook-proposals/create-hook-proposal";
import grabHookProposalView from "@/src/functions/backend/db/hook-proposals/grab-hook-proposal-view";
import computerRunDirs from "@/src/utils/computer-work-dirs";
import hookProposalRef from "@/src/utils/hook-proposal-ref";
import type { HarnessTool } from "../../../types";
import describeHookProposalForBot from "./describe-hook-proposal-for-bot";
@@ -23,6 +24,11 @@ type Params = {
* The bot's computers where it runs, the current one first.
*/
computers: BUN_SQLITE_COBBLE_COMPUTERS[];
/**
* The coordinator's folder is in the computer's workspace, a worker's
* in its own home: the runner folder is explained with the real paths.
*/
is_coordinator?: boolean;
/**
* Called with the proposal's ref, so the reply always carries its card.
*/
@@ -58,8 +64,12 @@ export default function proposeHookTool({
session_id,
workspace_id,
computers,
is_coordinator,
onPropose,
}: Params): HarnessTool<Args> {
const dirs = computerRunDirs({ bot_id, bot_kind: is_coordinator ? "coordinator" : null, user_id, workspace_id });
const home_relative = dirs.cwd.slice(dirs.bot_dir.length + 1);
const runner_folder = `relative to your bot folder ${dirs.bot_dir}, NOT to your ~ (${dirs.cwd}): a folder you made at ~/whatsapp is "${home_relative}/whatsapp", and "whatsapp" alone is ${dirs.bot_dir}/whatsapp. Empty: ${dirs.bot_dir} itself`;
const listed = computers.map((computer) => `${computer.id} (${computer.name || computer.kind})`).join(", ");
return {
@@ -68,7 +78,7 @@ export default function proposeHookTool({
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, 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.`,
} 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 (the folder it starts in, ${runner_folder}; the card shows the full path) 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({
hook_id: z.number().int().positive().optional().describe("The hook to change; leave out for a new one"),
title: z.string().trim().min(1).max(80).optional().describe(`A short name, e.g. "GitHub pushes"`),
@@ -92,7 +102,7 @@ export default function proposeHookTool({
.trim()
.max(AppData.BotHookRunnerDirMaxLength)
.optional()
.describe(`The folder it starts in, inside the bot's folder, e.g. "whatsapp". Empty: the bot's folder`),
.describe(`The folder it starts in, ${runner_folder}`),
runner_computer_id: z
.number()
.int()
+46 -12
View File
@@ -3,7 +3,11 @@ import grabBotPlan from "@/src/functions/backend/db/bot-plans/grab-bot-plan";
import saveBotPlanSteps from "@/src/functions/backend/db/bot-plans/save-bot-plan-steps";
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 {
BotPlanGoalSchema,
BotPlanStepTextsSchema,
BotPlanTitleSchema,
} from "@/src/schemas/bot-plan-schema";
import AppError from "@/src/utils/app-error";
import botPlanRef from "@/src/utils/bot-plan-ref";
import currentPlanStepIndex from "@/src/utils/current-plan-step-index";
@@ -37,29 +41,50 @@ type Args = {
* paused, because pausing was not a thing it could do). Approval and
* ending stay on the card.
*/
export default function updatePlanTool({ user_id, bot_id, session_id, onPlan }: Params): HarnessTool<Args> {
export default function updatePlanTool({
user_id,
bot_id,
session_id,
onPlan,
}: Params): HarnessTool<Args> {
return {
name: "update_plan",
description: `Change the plan you're working: rewrite its steps when what you found makes the rest of it wrong (send the whole list, in order, the steps already done first and unchanged: their notes are what was worked), or set its status to "paused" or "active" when the user asked to park the plan or pick it back up. Say in your reply what changed and why, in a line. Don't use it to make the plan look finished, and don't pause or resume on your own judgement: only when the message asked.`,
schema: z.object({
plan_id: z.number().int().positive().describe(`The plan's id, as your prompt gives it`),
steps: BotPlanStepTextsSchema.optional().describe(`The plan's steps as they should now read, done ones first and unchanged`),
title: BotPlanTitleSchema.optional().describe(`A new title, only when the work turned out to be something else`),
goal: BotPlanGoalSchema.optional().describe(`A new goal, only when what "done" means has changed`),
plan_id: z
.number()
.int()
.positive()
.describe(`The plan's id, as your prompt gives it`),
steps: BotPlanStepTextsSchema.optional().describe(
`The plan's steps as they should now read, done ones first and unchanged`,
),
title: BotPlanTitleSchema.optional().describe(
`A new title, only when the work turned out to be something else`,
),
goal: BotPlanGoalSchema.optional().describe(
`A new goal, only when what "done" means has changed`,
),
status: z
.enum(["paused", "active"])
.optional()
.describe(`"paused" parks a running plan where it stands, "active" picks a paused one back up: only when the user asked`),
.describe(
`"paused" parks a running plan where it stands, "active" picks a paused one back up: only when the user asked`,
),
}),
run: async ({ args }) => {
if (!args.steps && !args.status) {
throw new AppError(`Send the new steps or a status to set: update_plan changes one of them.`);
throw new AppError(
`Send the new steps or a status to set: update_plan changes one of them.`,
);
}
const row = await grabBotPlan({ plan_id: args.plan_id });
if (Number(row.session_id) != Number(session_id)) {
throw new AppError(`Plan #${args.plan_id} belongs to another conversation: change that conversation's plan.`);
throw new AppError(
`Plan #${args.plan_id} belongs to another conversation: change that conversation's plan.`,
);
}
if (args.steps) {
@@ -81,8 +106,14 @@ export default function updatePlanTool({ user_id, bot_id, session_id, onPlan }:
);
}
const result = await setBotPlanStatus({ plan_id: args.plan_id, user_id, status: args.status });
const at = currentPlanStepIndex({ steps: parseBotPlanSteps({ text: result.row.steps }) });
const result = await setBotPlanStatus({
plan_id: args.plan_id,
user_id,
status: args.status,
});
const at = currentPlanStepIndex({
steps: parseBotPlanSteps({ text: result.row.steps }),
});
moved =
args.status == "paused"
@@ -93,7 +124,10 @@ export default function updatePlanTool({ user_id, bot_id, session_id, onPlan }:
onPlan({ ref: botPlanRef({ plan_id: args.plan_id }) });
await pushBotPlan({ plan_id: args.plan_id, session_id, bot_id });
return moved || `Plan #${args.plan_id} is updated and its card shows the new steps. Say in a line what changed and why, then carry on with the step you're on.`;
return (
moved ||
`Plan #${args.plan_id} is updated and its card shows the new steps. Say in a line what changed and why, then carry on with the step you're on.`
);
},
};
}
+8 -2
View File
@@ -29,6 +29,11 @@ type Params = {
*/
plan_id?: number | null;
work: BotTaskWork;
/**
* The run queuing the work. A task run handing its work on is itself an
* open run on that computer, and was refused against its own job.
*/
job_id?: number | string;
/**
* The tool that asked, so a refusal tells the model to call that tool
* again rather than one it no longer has.
@@ -54,9 +59,10 @@ export default async function queueBotTask({
run_kind,
plan_id,
work,
job_id: asking_job_id,
tool_name,
}: Params): Promise<{ job_id: number; ahead: number; ask_id?: number }> {
const same = await grabOpenBotTask({ bot_id, session_id, title: work.title });
const same = await grabOpenBotTask({ bot_id, session_id, title: work.title, exclude_job_id: asking_job_id });
if (same) {
throw new Error(
@@ -66,7 +72,7 @@ export default async function queueBotTask({
const computer_id = work.computer_id ?? computers[0]?.id ?? undefined;
const open = work.separate ? null : await grabOpenBotTask({ bot_id, session_id, computer_id });
const open = work.separate ? null : await grabOpenBotTask({ bot_id, session_id, computer_id, exclude_job_id: asking_job_id });
if (open) {
throw new Error(
+18 -1
View File
@@ -21,8 +21,13 @@ mock.module("@/src/functions/backend/db/bots-queue/enqueue-bot-job", () => ({
return next_job_id++;
},
}));
const open_task_calls: Array<{ exclude_job_id?: number | string | null }> = [];
mock.module("@/src/functions/backend/db/bots-queue/grab-open-bot-task", () => ({
default: async () => null,
default: async (params: { exclude_job_id?: number | string | null }) => {
open_task_calls.push(params);
return null;
},
}));
mock.module("@/src/functions/backend/db/asks/grab-open-ask-by-session", () => ({
default: async () => null,
@@ -84,6 +89,18 @@ describe("sendReplyTool", () => {
expect(result).toContain("Your message beside this call goes out with it");
});
test("a task report handing work on leaves its own job out of the open-run checks (jobs 680, 700)", async () => {
open_task_calls.length = 0;
await tool({ job_id: 680 }).run({
args: { status: "working", work: { title: "Finish the composite", instructions: "Place the layers." } },
signal,
});
expect(open_task_calls.length).toBeGreaterThan(0);
expect(open_task_calls.every((call) => call.exclude_job_id === 680)).toBe(true);
});
test("queues the work once even if the call runs again", async () => {
const reply = tool();
const args = {
+1
View File
@@ -156,6 +156,7 @@ export default function sendReplyTool({
message_id,
run_kind,
plan_id,
job_id,
tool_name: "send_reply",
work: args.work,
});
+7
View File
@@ -30,6 +30,11 @@ type Params = {
* the child run's report ends on the card that moves the plan on.
*/
plan_id?: number | null;
/**
* The task run handing work on, so its own open job is not the run the
* new one is refused against.
*/
job_id?: number | string;
};
type Args = {
@@ -65,6 +70,7 @@ export default function startTaskTool({
message_id,
run_kind,
plan_id,
job_id: asking_job_id,
}: Params): HarnessTool<Args> {
const listed = computers
.map((computer) => `${computer.id} (${computer.name || computer.kind})`)
@@ -104,6 +110,7 @@ export default function startTaskTool({
message_id,
run_kind,
plan_id,
job_id: asking_job_id,
tool_name: "start_task",
work: {
title: args.title,
+7
View File
@@ -87,6 +87,13 @@ export default function useLiveBots({ bots, open_bot_id, workspace_id = null }:
...bot,
face: data.face,
status_line: data.status_line,
/**
* The chat the face came from, where the
* coordinator's Crew tab links the bot.
*/
...(data.face_workspace_id !== undefined
? { face_workspace_id: data.face_workspace_id }
: {}),
...(data.color !== undefined
? { color: data.color || undefined }
: {}),
@@ -0,0 +1,44 @@
import { useCallback, useEffect, useState } from "react";
import fetchLiveCrew from "@/src/layouts/bots/(functions)/fetch-live-crew";
import useRefocus from "@/src/hooks/use-refocus";
import type { BotWithLastMessage } from "@/src/types";
type Params = {
/**
* Read only when set: outside a workspace the page's crew is already
* the whole crew.
*/
enabled: boolean;
};
/**
* The whole crew the user chats with (the bots' own chats, every worker
* for the super admin), for the coordinator's Crew tab on a workspace
* page, whose own crew is only that workspace's bots. Read when the tab
* opens and again on every return to the page (`useRefocus`), since a
* push missed while it was in the background would leave it stale.
* `version` changes with each read, so the list taking it starts over.
*/
export default function useWholeCrew({ enabled }: Params) {
const [crew, setCrew] = useState<BotWithLastMessage[] | null>(null);
const [version, setVersion] = useState(0);
const load = useCallback(async () => {
if (!enabled) return;
const res = await fetchLiveCrew({ workspace_id: null }).catch(() => null);
if (!res?.success || !res.singleRes) return;
setCrew(res.singleRes.bots);
setVersion((v) => v + 1);
}, [enabled]);
useEffect(() => {
void load();
}, [load]);
useRefocus({ onRefocus: () => void load() });
return { crew, version };
}
@@ -7,6 +7,7 @@ import { ArrowLeft } from "lucide-react";
import conversationHref from "@/src/utils/conversation-href";
import askPreviousSessionId from "@/src/utils/ask-previous-session-id";
import type { AskOverview } from "@/src/types";
import askSessionBarText from "../(utils)/ask-session-bar-text";
type Props = {
bot_id: number;
@@ -65,9 +66,7 @@ export default function AskSessionBar({ bot_id, workspace_id, session_id }: Prop
<Stack className="shrink-0 gap-0! items-stretch border-0 border-b border-solid border-hairline">
<Row className="w-full max-w-container mx-auto py-3 gap-3! md:gap-4! flex-nowrap items-center justify-between px-3 md:px-6">
<Span className="min-w-0 text-sm text-ink-secondary truncate">
{ask.requester_name
? `This session is a crew request from ${ask.requester_name}.`
: "This session is a crew request."}
{askSessionBarText({ ask })}
</Span>
<Button
title="Go back to the conversation before this request"
@@ -29,6 +29,7 @@ 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";
import CrewAttentionTab from "./crew-attention-tab";
type Props = {
bot: BotWithLastMessage;
@@ -45,7 +46,7 @@ type Props = {
on_close: () => void;
};
type PanelTab = "settings" | "tools";
type PanelTab = "crew" | "settings" | "tools";
/**
* The bot's profile (picture, name, job, colour, instructions), what it keeps
@@ -55,7 +56,8 @@ type PanelTab = "settings" | "tools";
* about them. The avatar and the name beside it open it, and so does a swipe
* from the right on a phone (`BotPanelOpenEvent`, sent by the layout, so a
* page without a conversation has nobody listening). The tab's data loads when
* it opens, and Escape, the backdrop or the X closes it.
* it opens, and Escape, the backdrop or the X closes it. The coordinator's
* opens on a Crew tab first (`CrewAttentionTab`).
*/
export default function BotPanel({
bot,
@@ -69,7 +71,12 @@ export default function BotPanel({
const can_edit = canManageCrew({ user_types: pageProps?.user_types });
const may_write = !isReadOnlyUser({ user_types: pageProps?.user_types });
const title = can_edit ? `Edit ${name}` : `About ${name}`;
const [tab, setTab] = useState<PanelTab>("settings");
const is_coordinator = bot.kind == "coordinator";
/**
* The coordinator's panel opens on its Crew tab: the bots its status
* line counts, linked to the chat each one needs the user in.
*/
const [tab, setTab] = useState<PanelTab>(is_coordinator ? "crew" : "settings");
const workspace_id = Number(workspace?.id) || 0;
const { system_prompt, memory, user_memory, error } = useBotInstructions({
bot_id: Number(bot.id) || 0,
@@ -118,9 +125,14 @@ export default function BotPanel({
size={35}
/>
</Stack>
<H2 className="min-w-0 grow text-lg! leading-6! tracking-normal! font-bold text-ink truncate">
{title}
</H2>
<Stack className="min-w-0 grow gap-0! items-stretch">
<H2 className="min-w-0 text-lg! leading-6! tracking-normal! font-bold text-ink truncate">
{title}
</H2>
<Span className="text-xs leading-4 text-ink-secondary tabular-nums select-all">
{`Bot #${bot.id}`}
</Span>
</Stack>
<Button
title="Close"
type="button"
@@ -138,6 +150,13 @@ export default function BotPanel({
aria-label={title}
className="shrink-0 gap-1! flex-nowrap items-center px-3 py-2 border-0 border-b border-solid border-hairline"
>
{is_coordinator ? (
<TabButton
title="Crew"
active={tab == "crew"}
onPick={() => setTab("crew")}
/>
) : null}
<TabButton
title="Settings"
active={tab == "settings"}
@@ -150,6 +169,7 @@ export default function BotPanel({
/>
</Row>
<Stack className="grow min-h-0 overflow-y-auto gap-4! items-stretch px-4 pt-4 pb-6 [&>*]:shrink-0">
{open && tab == "crew" && is_coordinator ? <CrewAttentionTab workspace_id={workspace_id || null} /> : null}
{open && tab == "settings" ? (
can_edit ? (
<>
@@ -231,13 +251,13 @@ export default function BotPanel({
<BotReadOnlyBlock
title="Instructions"
content={system_prompt || ""}
className="h-52"
className="max-h-52"
/>
<Divider className="my-2 border-hairline dark:border-hairline" />
<BotReadOnlyBlock
title="Memory"
content={memory || ""}
className="h-52"
className="max-h-52"
/>
{workspace_id ? (
<>
@@ -249,7 +269,7 @@ export default function BotPanel({
.instructions
?.memory || ""
}
className="h-40"
className="max-h-40"
/>
</>
) : null}
@@ -1,4 +1,5 @@
import { useState } from "react";
import MarkdownText from "@/src/components/general/markdown-text";
import { twMerge } from "tailwind-merge";
import Button from "@moduletrace/twui/layout/Button";
import Span from "@moduletrace/twui/layout/Span";
@@ -93,7 +94,7 @@ export default function BotPlanCard({ plan_id }: Props) {
<Span className="text-[12px] leading-4 text-ink-secondary">{botPlanStatusLine({ view })}</Span>
{view.goal ? (
<Span className="text-[13px] leading-5 text-ink-secondary">{view.goal}</Span>
<MarkdownText text={view.goal} className="text-ink-secondary" />
) : null}
<Span className="flex w-full flex-col gap-1.5 pt-0.5">
@@ -1,4 +1,5 @@
import Span from "@moduletrace/twui/layout/Span";
import MarkdownText from "@/src/components/general/markdown-text";
import { twMerge } from "tailwind-merge";
import { Circle, CircleCheck, CircleSlash, CircleDot } from "lucide-react";
import type { BotPlanStep } from "@/src/types";
@@ -40,11 +41,11 @@ export default function BotPlanStepRow({ step, current }: Props) {
(done || skipped) && "text-ink-secondary",
)}
>
{step.text}
<MarkdownText text={step.text} />
</Span>
{step.note ? (
<Span className="text-[12px] leading-4 text-ink-secondary">{step.note}</Span>
<MarkdownText text={step.note} className="text-ink-secondary" />
) : current ? (
<Span className="text-[12px] leading-4 text-ink-secondary">Working on this now.</Span>
) : null}
@@ -1,4 +1,5 @@
import Input from "@moduletrace/twui/form/Input";
import MarkdownText from "@/src/components/general/markdown-text";
import Radios from "@moduletrace/twui/form/Radios";
import Span from "@moduletrace/twui/layout/Span";
import Stack from "@moduletrace/twui/layout/Stack";
@@ -54,9 +55,7 @@ export default function BotQuestionField({
return (
<Stack className="w-full gap-0! items-stretch">
<MessageDetailsHeading>{`${index + 1}. ${single ? "Pick one" : "Pick any"}`}</MessageDetailsHeading>
<Span className="whitespace-pre-wrap text-[13px] leading-5 font-bold text-ink break-words">
{item.question}
</Span>
<MarkdownText text={item.question} className="font-bold" />
{open ? (
<Stack className="mt-2 w-full gap-2! items-stretch">
@@ -1,25 +1,29 @@
import CodeEditor from "@/src/components/general/code-editor";
import Span from "@moduletrace/twui/layout/Span";
import Stack from "@moduletrace/twui/layout/Stack";
import MarkdownText from "@/src/components/general/markdown-text";
type BotReadOnlyBlockProps = {
title: string;
content: string;
/**
* The box's height cap (a `max-h-*`), so a long memory scrolls.
*/
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) {
/**
* A block of a bot's own text (its instructions, a memory) its panel shows
* a user read-only: markdown, rendered, never the raw text.
*/
export default function BotReadOnlyBlock({ title, content, className }: BotReadOnlyBlockProps) {
return (
<CodeEditor
title={title}
content={content || "Nothing yet."}
mode="markdown"
className={className}
readOnly
onChange={() => {}}
/>
<Stack className="w-full gap-1! items-stretch">
<Span className="text-[12px] leading-4 text-ink-secondary">{title}</Span>
{content.trim() ? (
<MarkdownText text={content} boxed className={className} />
) : (
<Span className="text-[13px] leading-5 text-ink-secondary">Nothing yet.</Span>
)}
</Stack>
);
}
}
@@ -74,7 +74,7 @@ export default function BotUserMemory({
<BotReadOnlyBlock
title="About you"
content={memory}
className="h-32"
className="max-h-32"
/>
</>
);
@@ -91,7 +91,7 @@ export default function BotUserMemory({
mode="markdown"
placeholder="What it should keep in mind about you..."
info="Markdown, replaced whole. Only this bot, and only when it works with you."
className="h-32"
className="max-h-32"
onChange={(value) => {
setText(value);
setSaved(false);
@@ -0,0 +1,46 @@
import Span from "@moduletrace/twui/layout/Span";
import Stack from "@moduletrace/twui/layout/Stack";
import type { BotWithLastMessage, WorkspaceWithActivity } from "@/src/types";
import type { CrewAttentionEntry } from "@/src/utils/crew-attention";
import CrewAttentionRow from "./crew-attention-row";
type Props = {
title: string;
entries: CrewAttentionEntry<BotWithLastMessage>[];
workspaces: WorkspaceWithActivity[];
/**
* The page's own path, so the chat on screen is marked.
*/
pathname?: string;
};
/**
* One list of the Crew tab (needs you, or working), with its count.
* Nothing when it's empty.
*/
export default function CrewAttentionGroup({ title, entries, workspaces, pathname }: Props) {
if (!entries.length) return null;
return (
<Stack className="w-full gap-1! items-stretch">
<Span className="text-[13px] leading-[18px] font-bold text-ink">
{`${title} (${entries.length})`}
</Span>
<Stack className="w-full gap-0.5! items-stretch">
{entries.map((entry) => (
<CrewAttentionRow
key={entry.bot.id}
bot={entry.bot}
href={entry.href}
current={pathname == entry.href}
workspace_name={
entry.workspace_id
? workspaces.find((w) => w.id == entry.workspace_id)?.name || "a workspace"
: null
}
/>
))}
</Stack>
</Stack>
);
}
@@ -0,0 +1,40 @@
import { useContext } from "react";
import Span from "@moduletrace/twui/layout/Span";
import { AppContext } from "@/src/pages/__root";
import type { BotWithLastMessage } from "@/src/types";
import crewAttention from "@/src/utils/crew-attention";
import { CrewWorkspacesContext } from "../(data)/crew-workspaces-context";
import CrewAttentionGroup from "./crew-attention-group";
type Props = {
bots: BotWithLastMessage[];
};
/**
* The Crew tab's lists over a crew: the bots that need the user first,
* then the ones working, or a line saying there are none.
*/
export default function CrewAttentionList({ bots }: Props) {
const { pageProps } = useContext(AppContext);
const workspaces = useContext(CrewWorkspacesContext);
const { needs_you, working } = crewAttention({ bots });
const pathname = pageProps?.url?.pathname;
if (!needs_you.length && !working.length) {
return (
<Span className="text-[13px] leading-[18px] text-ink-secondary">
Nothing needs you, and no bot is working.
</Span>
);
}
return (
<>
<Span className="text-[13px] leading-[18px] text-ink-secondary">
The bots that need you or are working, each opening the chat it's in.
</Span>
<CrewAttentionGroup title="Needs you" entries={needs_you} workspaces={workspaces} pathname={pathname} />
<CrewAttentionGroup title="Working" entries={working} workspaces={workspaces} pathname={pathname} />
</>
);
}
@@ -0,0 +1,60 @@
import Link from "@moduletrace/twui/layout/Link";
import Span from "@moduletrace/twui/layout/Span";
import Stack from "@moduletrace/twui/layout/Stack";
import { twMerge } from "tailwind-merge";
import BotAvatar from "@/src/components/general/bot-avatar";
import type { BotFace } from "@/src/dict/bot-dict";
import type { BotWithLastMessage } from "@/src/types";
import botStoneProps from "@/src/utils/bot-stone-props";
type Props = {
bot: BotWithLastMessage;
href: string;
/**
* The workspace the chat is in; none for the bot's own chat.
*/
workspace_name?: string | null;
/**
* The chat already on screen.
*/
current?: boolean;
};
/**
* One worker in the coordinator's Crew tab: its live stone, its name, its
* status line and the chat it's in, linking to that chat.
*/
export default function CrewAttentionRow({ bot, href, workspace_name, current }: Props) {
const name = bot.name || `Bot #${bot.id}`;
const place = workspace_name ? `In ${workspace_name}` : "Its own chat";
const title = workspace_name ? `Open ${name} in ${workspace_name}` : `Open ${name}`;
return (
<Link
href={href}
title={title}
aria-label={title}
aria-current={current ? "page" : undefined}
className={twMerge(
"flex shrink-0 items-center gap-3 rounded-default px-2 py-2 leading-normal text-ink",
"hover:opacity-100 hover:bg-sunken transition-colors duration-[var(--m-fast)]",
"focus-visible:ring-2 focus-visible:ring-ink",
current && "bg-sunken",
)}
>
<Span className="shrink-0 flex items-center justify-center">
<BotAvatar
image_media_id={bot.image_media_id}
{...botStoneProps({ color: bot.color, stone: bot.stone, hue: bot.hue })}
face={(bot.face || "idle") as BotFace}
/>
</Span>
<Stack className="grow min-w-0 gap-0!">
<Span className="w-full text-sm font-bold leading-5 text-ink truncate">{name}</Span>
<Span className="w-full text-xs leading-4 text-ink-secondary truncate">
{bot.status_line ? `${bot.status_line} · ${place}` : place}
</Span>
</Stack>
</Link>
);
}
@@ -0,0 +1,88 @@
import { describe, expect, test } from "bun:test";
import { renderToString } from "react-dom/server";
import type {
AppContextObject,
BotWithLastMessage,
PagePropsType,
WorkspaceWithActivity,
} from "@/src/types";
import { AppContext } from "@/src/pages/__root";
import { CrewBotsContext } from "../(data)/crew-bots-context";
import { CrewWorkspacesContext } from "../(data)/crew-workspaces-context";
import BotPanel from "./bot-panel";
import CrewAttentionTab from "./crew-attention-tab";
const coordinator = { id: 1, name: "Coordinator", kind: "coordinator", face: "idle" } as BotWithLastMessage;
const crew = [
coordinator,
{ id: 2, name: "Inbox", kind: "worker", face: "needs-you", status_line: "Waiting on you", face_workspace_id: 5 },
{ id: 3, name: "Draft", kind: "worker", face: "needs-you", status_line: "Waiting on you", face_workspace_id: null },
{ id: 4, name: "Shelf", kind: "worker", face: "working", status_line: "Working on a task", face_workspace_id: null },
{ id: 6, name: "Quiet", kind: "worker", face: "idle" },
] as BotWithLastMessage[];
const workspaces = [{ id: 5, name: "Moduletrace LTD" }] as WorkspaceWithActivity[];
const pageProps: PagePropsType = {
url: { pathname: "/admin/bots/1" } as PagePropsType["url"],
user_types: [{ user_type: "super_admin" }] as PagePropsType["user_types"],
};
function render({ bots = crew }: { bots?: BotWithLastMessage[] } = {}) {
return renderToString(
<AppContext.Provider value={{ pageProps } as AppContextObject}>
<CrewBotsContext.Provider value={bots}>
<CrewWorkspacesContext.Provider value={workspaces}>
<CrewAttentionTab />
</CrewWorkspacesContext.Provider>
</CrewBotsContext.Provider>
</AppContext.Provider>,
);
}
describe("CrewAttentionTab", () => {
test("links each bot to the chat it needs the user in", () => {
const html = render();
expect(html).toContain(`href="/admin/workspaces/5/bots/2"`);
expect(html).toContain("In Moduletrace LTD");
expect(html).toContain(`href="/admin/bots/3"`);
expect(html).toContain(`href="/admin/bots/4"`);
expect(html).not.toContain("Quiet");
expect(html).toContain("Needs you (2)");
expect(html).toContain("Working (1)");
});
test("in a workspace it waits for the whole crew instead of listing the page's", () => {
const html = renderToString(
<AppContext.Provider value={{ pageProps } as AppContextObject}>
<CrewBotsContext.Provider value={crew}>
<CrewWorkspacesContext.Provider value={workspaces}>
<CrewAttentionTab workspace_id={5} />
</CrewWorkspacesContext.Provider>
</CrewBotsContext.Provider>
</AppContext.Provider>,
);
expect(html).not.toContain("Needs you (");
});
test("says so when nothing needs the user", () => {
expect(render({ bots: [coordinator] })).toContain("Nothing needs you");
});
});
describe("BotPanel's Crew tab", () => {
test("only the coordinator's panel has it", () => {
const panel = (bot: BotWithLastMessage) =>
renderToString(
<AppContext.Provider value={{ pageProps } as AppContextObject}>
<BotPanel bot={bot} open={false} on_open={() => {}} on_close={() => {}} />
</AppContext.Provider>,
);
expect(panel(coordinator)).toContain(">Crew<");
expect(panel(crew[1] as BotWithLastMessage)).not.toContain(">Crew<");
});
});
@@ -0,0 +1,32 @@
import { useContext } from "react";
import Loading from "@moduletrace/twui/elements/Loading";
import { CrewBotsContext } from "../(data)/crew-bots-context";
import useWholeCrew from "../(hooks)/use-whole-crew";
import CrewAttentionList from "./crew-attention-list";
import LiveCrewAttentionList from "./live-crew-attention-list";
type Props = {
/**
* The workspace the coordinator's conversation is in, if any.
*/
workspace_id?: number | null;
};
/**
* The coordinator panel's Crew tab: the workers its status line counts,
* the ones that need the user first, each linking to the chat it needs
* them in (a workspace's or its own). In its own chat the page's live
* crew is the whole crew; in a workspace the page holds only that
* workspace's bots, so the tab reads the whole crew itself
* (`useWholeCrew`), or a bot needing the user elsewhere went unlisted.
*/
export default function CrewAttentionTab({ workspace_id }: Props) {
const page_bots = useContext(CrewBotsContext);
const { crew, version } = useWholeCrew({ enabled: Boolean(workspace_id) });
if (!workspace_id) return <CrewAttentionList bots={page_bots} />;
if (!crew) return <Loading />;
return <LiveCrewAttentionList key={version} bots={crew} />;
}
@@ -1,4 +1,5 @@
import { useContext, useState } from "react";
import MarkdownText from "@/src/components/general/markdown-text";
import Button from "@moduletrace/twui/layout/Button";
import Row from "@moduletrace/twui/layout/Row";
import Span from "@moduletrace/twui/layout/Span";
@@ -89,7 +90,7 @@ export default function HookProposalCard({ view, onDecided, onDone }: Props) {
) : null}
<MessageDetailsHeading>Why (written by the bot)</MessageDetailsHeading>
<Span className="whitespace-pre-wrap text-[13px] leading-5 text-ink break-words">{view.reason}</Span>
<MarkdownText text={view.reason || ""} />
{view.outcome ? <Span className="mt-4 text-[13px] leading-5 text-ink">{view.outcome}</Span> : null}
@@ -0,0 +1,20 @@
import useLiveBots from "@/src/hooks/use-live-bots";
import type { BotWithLastMessage } from "@/src/types";
import CrewAttentionList from "./crew-attention-list";
type Props = {
/**
* The whole crew as last read (`useWholeCrew`).
*/
bots: BotWithLastMessage[];
};
/**
* The Crew tab over a crew this page didn't load, kept current from the
* face pushes like the rail's (`useLiveBots` for the bots' own chats).
*/
export default function LiveCrewAttentionList({ bots }: Props) {
const live = useLiveBots({ bots, workspace_id: null });
return <CrewAttentionList bots={live} />;
}
@@ -187,11 +187,14 @@ export default function MessageThread({
/**
* The user's own message the thread ends on, with nothing on its way: a
* stopped run, or one that ended without a word, leaves it waiting
* forever. The row under it says so and offers to answer it again.
* forever. The row under it says so and offers to answer it again. A
* task run of this session is on its way too, even while it is still
* queued: a hand-over's session opens with the brief on the user's side
* and its answer is that run's report, not a reply.
*/
const last_shown = shown[shown.length - 1];
const unanswered =
!awaiting_reply && !receiving && !moved_on && last_shown?.author == "user"
!awaiting_reply && !receiving && !moved_on && !has_task && last_shown?.author == "user"
? last_shown
: null;
const scroll = useThreadScroll({ messages: shown });
@@ -1,4 +1,5 @@
import { useContext, useState } from "react";
import MarkdownText from "@/src/components/general/markdown-text";
import Button from "@moduletrace/twui/layout/Button";
import Row from "@moduletrace/twui/layout/Row";
import Span from "@moduletrace/twui/layout/Span";
@@ -84,7 +85,7 @@ export default function ProposalCard({ view, onDecided }: Props) {
<MessageDetailsHeading>
{is_skill ? "Review (written by the bot)" : "Background check (written by the bot)"}
</MessageDetailsHeading>
<Span className="whitespace-pre-wrap text-[13px] leading-5 text-ink break-words">{view.research}</Span>
<MarkdownText text={view.research || ""} />
<Stack className="mt-1 w-full gap-0! items-stretch">
{view.sources.length ? (
view.sources.map((url) => <ProposalSourceRow key={url} url={url} />)
@@ -0,0 +1,21 @@
import { describe, expect, test } from "bun:test";
import { renderToString } from "react-dom/server";
import ProposalDetailRow from "./proposal-detail-row";
describe("ProposalDetailRow", () => {
test("renders a markdown brief instead of showing it raw", () => {
const html = renderToString(
<ProposalDetailRow label="Brief" value={"## Steps\n\n1. **Read** the call"} block markdown />,
);
expect(html).toContain("<li");
expect(html).not.toContain("## Steps");
expect(html).not.toContain("**Read**");
});
test("keeps a code-like value word for word", () => {
const html = renderToString(<ProposalDetailRow label="Keeps running" value="./run.sh --flag **x**" block />);
expect(html).toContain("./run.sh --flag **x**");
});
});
@@ -1,24 +1,30 @@
import Row from "@moduletrace/twui/layout/Row";
import Span from "@moduletrace/twui/layout/Span";
import { twMerge } from "tailwind-merge";
import MarkdownText from "@/src/components/general/markdown-text";
import type { ExtensionProposalDetail } from "@/src/types";
/**
* One line of what a proposed server or tool would do, as the app read it
* from the config: a label, and its value, code-like ones as a block.
* from the config: a label, and its value, code-like ones as a block and
* markdown ones (a brief, a runbook) rendered.
*/
export default function ProposalDetailRow({ label, value, block }: ExtensionProposalDetail) {
export default function ProposalDetailRow({ label, value, block, markdown }: ExtensionProposalDetail) {
return (
<Row className="w-full py-2 gap-3! flex-nowrap items-baseline border-0 border-b border-solid border-hairline last:border-b-0">
<Span className="w-28 shrink-0 text-[12px] leading-4 text-ink-secondary">{label}</Span>
<Span
className={twMerge(
"grow min-w-0 text-[13px] leading-5 text-ink break-words",
block && "max-h-48 overflow-auto whitespace-pre-wrap rounded-default-xs bg-sunken px-2 py-1 font-mono text-[12px]",
)}
>
{value}
</Span>
{markdown ? (
<MarkdownText text={value} boxed={block} className="grow text-[13px] leading-5" />
) : (
<Span
className={twMerge(
"grow min-w-0 text-[13px] leading-5 text-ink break-words",
block && "max-h-48 overflow-auto whitespace-pre-wrap rounded-default-xs bg-sunken px-2 py-1 font-mono text-[12px]",
)}
>
{value}
</Span>
)}
</Row>
);
}
@@ -1,4 +1,5 @@
import { useContext, useState } from "react";
import MarkdownText from "@/src/components/general/markdown-text";
import Input from "@moduletrace/twui/form/Input";
import Button from "@moduletrace/twui/layout/Button";
import Row from "@moduletrace/twui/layout/Row";
@@ -113,11 +114,11 @@ export default function SecretRequestCard({ view, onDecided, onDone }: Props) {
return (
<Stack className="w-full gap-0! items-stretch">
<MessageDetailsHeading>What it is</MessageDetailsHeading>
<Span className="text-[13px] leading-5 text-ink break-words">{view.description}</Span>
<MarkdownText text={view.description || ""} />
<Span className="mt-1 text-[12px] leading-4 text-ink-secondary">{`Saved as ${view.key}, for your runs of ${view.bot_name} only.`}</Span>
<MessageDetailsHeading>Why (written by the bot)</MessageDetailsHeading>
<Span className="whitespace-pre-wrap text-[13px] leading-5 text-ink break-words">{view.reason}</Span>
<MarkdownText text={view.reason || ""} />
{open ? (
<Stack className="mt-5 w-full gap-2! items-stretch">
@@ -0,0 +1,19 @@
import { describe, expect, test } from "bun:test";
import askSessionBarText from "./ask-session-bar-text";
describe("askSessionBarText", () => {
test("a crew request names who asked", () => {
expect(askSessionBarText({ ask: { kind: "ask", requester_name: "Writer" } })).toBe(
"This session is a crew request from Writer.",
);
});
test("a hand-over says it is a task handed over", () => {
expect(askSessionBarText({ ask: { kind: "hand_over", requester_name: "Coordinator" } })).toBe(
"This session is a task Coordinator handed over.",
);
expect(askSessionBarText({ ask: { kind: "hand_over", requester_name: null } })).toBe(
"This session is a task handed over by another bot.",
);
});
});
@@ -0,0 +1,21 @@
import type { AskOverview } from "@/src/types";
type Params = {
ask: Pick<AskOverview, "kind" | "requester_name">;
};
/**
* What the bar over a session another bot opened says it is: a crew
* request, or a task handed over.
*/
export default function askSessionBarText({ ask }: Params) {
if (ask.kind == "hand_over") {
return ask.requester_name
? `This session is a task ${ask.requester_name} handed over.`
: "This session is a task handed over by another bot.";
}
return ask.requester_name
? `This session is a crew request from ${ask.requester_name}.`
: "This session is a crew request.";
}
+3 -2
View File
@@ -29,13 +29,13 @@ export const handler: BunextAPIRouteHandler<APIResponseObject<AskOverview>> = as
const [row] = (await BunSQLite.sql({
sql: ask_id
? `SELECT a.id, a.title, a.status, a.target_bot_id, a.workspace_id, a.session_id,
a.previous_session_id, b.name AS requester_name, t.name AS target_name
a.previous_session_id, a.kind, b.name AS requester_name, t.name AS target_name
FROM bot_asks a
LEFT JOIN bots b ON b.id = a.requester_bot_id
LEFT JOIN bots t ON t.id = a.target_bot_id
WHERE a.id = ? AND a.user_id = ? LIMIT 1`
: `SELECT a.id, a.title, a.status, a.target_bot_id, a.workspace_id, a.session_id,
a.previous_session_id, b.name AS requester_name, t.name AS target_name
a.previous_session_id, a.kind, b.name AS requester_name, t.name AS target_name
FROM bot_asks a
LEFT JOIN bots b ON b.id = a.requester_bot_id
LEFT JOIN bots t ON t.id = a.target_bot_id
@@ -57,6 +57,7 @@ export const handler: BunextAPIRouteHandler<APIResponseObject<AskOverview>> = as
session_id: row.session_id ? Number(row.session_id) : null,
previous_session_id: row.previous_session_id ? Number(row.previous_session_id) : null,
requester_name: row.requester_name ? String(row.requester_name) : null,
kind: row.kind == "hand_over" ? "hand_over" : "ask",
},
};
} catch (error: unknown) {
+32 -3
View File
@@ -16,6 +16,12 @@ import isReadOnlyUser from "@/src/utils/rbac/is-read-only-user";
import rerunReplyProblem from "@/src/utils/rerun-reply-problem";
import retryReplyProblem from "@/src/utils/retry-reply-problem";
import safeErrorMessage from "@/src/utils/safe-error-message";
import parseJobJson from "@/src/bots-queue/parse-job-json";
import pushBotPlan from "@/src/bots-queue/push-bot-plan";
import grabBotPlan from "@/src/functions/backend/db/bot-plans/grab-bot-plan";
import setBotPlanStatus from "@/src/functions/backend/db/bot-plans/set-bot-plan-status";
import enqueuePlanStep from "@/src/functions/backend/db/bot-plans/enqueue-plan-step";
import planStepRetryTarget from "@/src/utils/plan-step-retry-target";
/**
* Runs the bot's last reply again, queues a failed reply after its failure
@@ -52,8 +58,8 @@ export const handler: BunextAPIRouteHandler<APIResponseObject> = async ({ req, b
const message = await grabUserBotMessage({ user_id: user.id, message_id });
const job = (
await BunSQLite.sql<Pick<BUN_SQLITE_COBBLE_BOTS_QUEUE, "id" | "kind">>({
sql: `SELECT id, kind FROM bots_queue WHERE id = ? LIMIT 1`,
await BunSQLite.sql<Pick<BUN_SQLITE_COBBLE_BOTS_QUEUE, "id" | "kind" | "params" | "session_id">>({
sql: `SELECT id, kind, params, session_id FROM bots_queue WHERE id = ? LIMIT 1`,
values: [message.failed_job_id || 0],
})
).payload?.[0];
@@ -146,7 +152,30 @@ export const handler: BunextAPIRouteHandler<APIResponseObject> = async ({ req, b
throw new AppError(problem);
}
await enqueueBotReply({
/**
* A failed plan step paused its plan, and an ordinary reply can't
* tick a paused plan's step: it is retried as that step, with the
* plan running again, so the retry can finish what the plan holds.
*/
const plan_id = Number(parseJobJson({ text: job?.params })?.plan_id) || 0;
const plan = plan_id ? await grabBotPlan({ plan_id }).catch(() => null) : null;
const retry_step = planStepRetryTarget({
plan_id,
job_session_id: Number(message.session_id),
plan: plan ? { session_id: plan.session_id, status: plan.status } : null,
});
let step_job: number | null = null;
if (retry_step && plan) {
const { row, started } = await setBotPlanStatus({ plan_id, user_id: user.id, status: "active" });
await pushBotPlan({ plan_id: row.id, session_id: row.session_id, bot_id: row.bot_id });
step_job = started ? await enqueuePlanStep({ plan_id: row.id }) : null;
}
if (!step_job) await enqueueBotReply({
user_id: user.id,
bot_id: Number(message.bot_id),
session_id: Number(message.session_id),
+48
View File
@@ -0,0 +1,48 @@
import { describe, expect, test } from "bun:test";
import { z } from "zod";
import { BotQuestionItemsSchema } from "./bot-question-schema";
const question = { question: "How should the prompt handle the legs?", kind: "single" };
describe("BotQuestionItemsSchema", () => {
test("takes options as plain strings", () => {
const parsed = BotQuestionItemsSchema.parse([{ ...question, options: ["Crop them", "Keep them"] }]);
expect(parsed[0]!.options).toEqual(["Crop them", "Keep them"]);
});
test("reads an option written as an object by its label (job 694, first try)", () => {
const parsed = BotQuestionItemsSchema.parse([
{
...question,
options: [
{ label: "Crop them", description: "Removes the contradiction." },
{ text: "Keep them" },
],
},
]);
expect(parsed[0]!.options).toEqual(["Crop them", "Keep them"]);
});
test("reads questions passed as a JSON string of the array (job 694, second try)", () => {
const text = `\n${JSON.stringify([{ ...question, options: ["Crop them", "Keep them"] }])}\n`;
expect(BotQuestionItemsSchema.parse(text)[0]!.options).toEqual(["Crop them", "Keep them"]);
});
test("still refuses what it can't read", () => {
expect(BotQuestionItemsSchema.safeParse("not json").success).toBe(false);
expect(BotQuestionItemsSchema.safeParse([{ ...question, options: [{ description: "no label" }, "Keep"] }]).success).toBe(false);
expect(BotQuestionItemsSchema.safeParse([{ ...question, options: ["Same", "same"] }]).success).toBe(false);
});
test("the model is still shown options as plain strings", () => {
const schema = z.toJSONSchema(z.object({ questions: BotQuestionItemsSchema }), { target: "draft-7", io: "input" }) as {
properties: { questions: { type: string; items: { properties: { options: { items: { type: string } } } } } };
};
expect(schema.properties.questions.type).toBe("array");
expect(schema.properties.questions.items.properties.options.items.type).toBe("string");
});
});
+46 -10
View File
@@ -2,6 +2,36 @@ import { z } from "zod";
import { AppData } from "@/src/data/app-data";
import { BotQuestionKinds } from "@/src/dict/bot-question-dict";
/**
* An option written as `{ label, description }` (or `text`/`value`), the
* shape models reach for, is its label. Refused as "expected string", the
* card took job 694 three turns to put up.
*/
function optionLabel(value: unknown) {
if (!value || typeof value != "object" || Array.isArray(value)) return value;
const option = value as Record<string, unknown>;
const label = option.label ?? option.text ?? option.value;
return typeof label == "string" ? label : value;
}
/**
* Questions passed as a JSON string of the array (job 694's second try) are
* read as that array. Anything else is left for the schema to refuse.
*/
function questionsArray(value: unknown) {
if (typeof value != "string") return value;
try {
const parsed = JSON.parse(value.trim());
return Array.isArray(parsed) ? parsed : value;
} catch {
return value;
}
}
/**
* One question as a bot writes it (`ask_user`) and as it's stored.
*/
@@ -10,22 +40,28 @@ export const BotQuestionItemSchema = z.object({
kind: z
.enum(BotQuestionKinds)
.describe("single: the user picks exactly one option (radios). multiple: any number, at least one (checkboxes)."),
options: z
.array(z.string().trim().min(1).max(200))
.min(2, "Give at least two options")
.max(AppData.BotQuestionMaxOptions, `Give at most ${AppData.BotQuestionMaxOptions} options`)
.refine((options) => new Set(options.map((option) => option.toLowerCase())).size == options.length, "Options must differ")
.describe("The answers to choose from, each short and distinct"),
options: z.preprocess(
(value) => (Array.isArray(value) ? value.map(optionLabel) : value),
z
.array(z.string().trim().min(1).max(200))
.min(2, "Give at least two options")
.max(AppData.BotQuestionMaxOptions, `Give at most ${AppData.BotQuestionMaxOptions} options`)
.refine((options) => new Set(options.map((option) => option.toLowerCase())).size == options.length, "Options must differ")
.describe("The answers to choose from, each a plain string, short and distinct"),
),
allow_other: z
.boolean()
.optional()
.describe("Let the user type an answer of their own besides the options. Set it unless the options cover every case."),
});
export const BotQuestionItemsSchema = z
.array(BotQuestionItemSchema)
.min(1, "Ask at least one question")
.max(AppData.BotQuestionMaxQuestions, `Ask at most ${AppData.BotQuestionMaxQuestions} questions at once`);
export const BotQuestionItemsSchema = z.preprocess(
questionsArray,
z
.array(BotQuestionItemSchema)
.min(1, "Ask at least one question")
.max(AppData.BotQuestionMaxQuestions, `Ask at most ${AppData.BotQuestionMaxQuestions} questions at once`),
);
export const BotQuestionIdSchema = z.object({
question_id: z.coerce.number().int().positive("Pick the questions"),
+4
View File
@@ -14,6 +14,7 @@ import migrateLlmLogs from "./functions/backend/db/logs/migrate-llm-logs";
import clearImplicitSessionLinks from "./functions/backend/db/bot-sessions/clear-implicit-session-links";
import migrateChatroomsToAsks from "./functions/backend/db/bot-sessions/migrate-chatrooms-to-asks";
import migrateHookSilence from "./functions/backend/db/bot-hooks/migrate-hook-silence";
import migrateFaceWorkspaces from "./functions/backend/db/bots/migrate-face-workspaces";
import adoptChattedHookSessions from "./functions/backend/db/bot-hooks/adopt-chatted-hook-sessions";
import dropStoredFileText from "./functions/backend/db/stored-text/drop-stored-file-text";
import syncKnowledgebaseFts from "./functions/backend/db/knowledgebases/fts/sync-knowledgebase-fts";
@@ -58,6 +59,9 @@ await migrateChatroomsToAsks().catch((error) =>
await migrateHookSilence().catch((error) =>
logError({ title: "Could not make the existing hooks silent", error }).catch(() => {}),
);
await migrateFaceWorkspaces().catch((error) =>
logError({ title: "Could not place the existing bot faces", error }).catch(() => {}),
);
await adoptChattedHookSessions().catch((error) =>
logError({ title: "Could not hand the hooks' used threads to their users", error }).catch(() => {}),
);
+19
View File
@@ -90,6 +90,11 @@ export type User = {
export type BotWithFace = BUN_SQLITE_COBBLE_BOTS & {
face?: BotFace;
status_line?: string;
/**
* The workspace of the conversation whose job set the face, null for
* the bot's own chat: where the coordinator's Crew list links it.
*/
face_workspace_id?: number | null;
};
/**
@@ -644,6 +649,10 @@ export type AskOverview = {
session_id: number | null;
previous_session_id: number | null;
requester_name: string | null;
/**
* `hand_over`: a task another bot handed over on the user's word.
*/
kind: "ask" | "hand_over";
};
export type CrewRequest = {
@@ -703,6 +712,11 @@ export type BotUpdatedData = {
id: number;
face: BotFace;
status_line: string;
/**
* The workspace of the conversation whose job set the face, null for
* the bot's own chat.
*/
face_workspace_id?: number | null;
/**
* The newest of the user's active tasks, null when there is none. Kept
* for a reader that wants one; `tasks` has them all, since the newest
@@ -1603,6 +1617,11 @@ export type ExtensionProposalDetail = {
* Long or code-like: shown as a block.
*/
block?: boolean;
/**
* Written in markdown (a brief, a runbook, a prompt): rendered, never
* shown raw.
*/
markdown?: boolean;
};
/**
+9 -9
View File
@@ -6,9 +6,9 @@ const db = new Database(":memory:");
beforeAll(() => {
db.run(`CREATE TABLE bots (id INTEGER PRIMARY KEY)`);
db.run(`CREATE TABLE bot_user_faces (bot_id INTEGER, user_id INTEGER, face TEXT, status_line TEXT)`);
db.run(`CREATE TABLE bot_user_faces (bot_id INTEGER, user_id INTEGER, face TEXT, status_line TEXT, workspace_id INTEGER)`);
db.run(`INSERT INTO bots VALUES (1), (2)`);
db.run(`INSERT INTO bot_user_faces VALUES (1, 7, 'needs-you', 'Waiting on you'), (2, 8, 'working', 'Working on a task')`);
db.run(`INSERT INTO bot_user_faces VALUES (1, 7, 'needs-you', 'Waiting on you', 5), (2, 8, 'working', 'Working on a task', NULL)`);
});
function faces({ user_id, prefix }: { user_id: number; prefix?: string }) {
@@ -18,21 +18,21 @@ function faces({ user_id, prefix }: { user_id: number; prefix?: string }) {
}
describe("botFaceSql", () => {
test("each user sees only their own face of a bot", () => {
test("each user sees only their own face of a bot, with the workspace that set it", () => {
expect(faces({ user_id: 7 })).toEqual([
{ id: 1, face: "needs-you", status_line: "Waiting on you" },
{ id: 2, face: "idle", status_line: "" },
{ id: 1, face: "needs-you", status_line: "Waiting on you", face_workspace_id: 5 },
{ id: 2, face: "idle", status_line: "", face_workspace_id: null },
]);
expect(faces({ user_id: 8 })).toEqual([
{ id: 1, face: "idle", status_line: "" },
{ id: 2, face: "working", status_line: "Working on a task" },
{ id: 1, face: "idle", status_line: "", face_workspace_id: null },
{ id: 2, face: "working", status_line: "Working on a task", face_workspace_id: null },
]);
});
test("a user with no faces sees every bot idle, under the prefix", () => {
expect(faces({ user_id: 9, prefix: "bot_" })).toEqual([
{ id: 1, bot_face: "idle", bot_status_line: "" },
{ id: 2, bot_face: "idle", bot_status_line: "" },
{ id: 1, bot_face: "idle", bot_status_line: "", bot_face_workspace_id: null },
{ id: 2, bot_face: "idle", bot_status_line: "", bot_face_workspace_id: null },
]);
});
});
+4 -3
View File
@@ -16,14 +16,15 @@ type Params = {
* Select columns for a bot's face and status line as one user sees them
* (`bot_user_faces`): idle and no status line when the bot has none for
* them. Faces are per user, so a job one user's waiting on never shows
* on anyone else's screen.
* on anyone else's screen. `face_workspace_id` is the workspace of the
* conversation that set it (null for its own chat).
*/
export default function botFaceSql({ user_id, alias = "b", prefix = "" }: Params): SqlCondition {
const column = (name: string) =>
`(SELECT f.${name} FROM bot_user_faces f WHERE f.bot_id = ${alias}.id AND f.user_id = ?)`;
return {
sql: `COALESCE(${column("face")}, 'idle') AS ${prefix}face, COALESCE(${column("status_line")}, '') AS ${prefix}status_line`,
values: [Number(user_id), Number(user_id)],
sql: `COALESCE(${column("face")}, 'idle') AS ${prefix}face, COALESCE(${column("status_line")}, '') AS ${prefix}status_line, ${column("workspace_id")} AS ${prefix}face_workspace_id`,
values: [Number(user_id), Number(user_id), Number(user_id)],
};
}
+6
View File
@@ -71,6 +71,12 @@ describe("claimsWorkUnderWay", () => {
"I'm starting to think the brief is wrong.",
"I started the invoice last week.",
"Task #48 is doing, nothing is running yet.",
/**
* Job 809's plan report: status lines about a hand-over made
* days before, refused twice as work claimed under way.
*/
"- **#5 Technical quick wins** - handed to [bot:6] (PR #10 open, 7 of 9 items implemented)",
"- Task #5: Handed to [bot:6] (PR #10 open, 7/9 items implemented)",
]) {
expect(claimsWorkUnderWay({ text })).toBe(false);
}
+5 -2
View File
@@ -31,9 +31,12 @@ const UnderWayPatterns = [
/**
* "What I sent @SEO Expert", "I've passed the brief on to [bot:6]": a
* request claimed as made. Only `ask_bot` makes one, so the app's
* record decides whether it's true.
* record decides whether it's true. Only the bot's own claim counts
* ("I sent", "I've passed"): a status line such as "#5 - handed to
* [bot:6] (PR #10 open)" reports a hand-over made days before, and
* faulting it refused an honest plan report twice (job 809).
*/
/\b(?:sent|passed|forwarded|handed)\b[^.!?\n]{0,80}(?:@[a-z0-9_-]+|\[bot:\d+\])/i,
/\bI(?:(?:'|’)ve)?\s+(?:just\s+|now\s+|already\s+)?(?:sent|passed|forwarded|handed)\b[^.!?\n]{0,80}(?:@[a-z0-9_-]+|\[bot:\d+\])/i,
/**
* "I'm starting the hydration work on computer 1", "I've kicked off
* the run": a run claimed as started, without the "now" or the
+39
View File
@@ -0,0 +1,39 @@
import { describe, expect, test } from "bun:test";
import type { BotWithFace } from "@/src/types";
import crewAttention from "./crew-attention";
import { crewCounts } from "./crew-status";
const crew: BotWithFace[] = [
{ id: 1, kind: "coordinator", face: "needs-you" },
{ id: 2, kind: "worker", face: "needs-you", face_workspace_id: 5 },
{ id: 3, kind: "worker", face: "needs-you", face_workspace_id: null },
{ id: 4, kind: "worker", face: "working", face_workspace_id: 7 },
{ id: 5, kind: "worker", face: "asleep", face_workspace_id: 7 },
{ id: 6, kind: "worker", face: "idle" },
];
describe("crewAttention", () => {
test("lists the workers behind the counts, never the coordinator", () => {
const { needs_you, working } = crewAttention({ bots: crew });
const counts = crewCounts({ bots: crew });
expect(needs_you.map((entry) => entry.bot.id)).toEqual([2, 3]);
expect(working.map((entry) => entry.bot.id)).toEqual([4]);
expect(needs_you.length).toBe(counts.needs_you);
expect(working.length).toBe(counts.working);
});
test("links the workspace chat the face came from", () => {
const { needs_you, working } = crewAttention({ bots: crew });
expect(needs_you[0]?.href).toBe("/admin/workspaces/5/bots/2");
expect(working[0]?.href).toBe("/admin/workspaces/7/bots/4");
});
test("links the bot's own chat when no workspace set the face", () => {
const { needs_you } = crewAttention({ bots: crew });
expect(needs_you[1]?.workspace_id).toBeNull();
expect(needs_you[1]?.href).toBe("/admin/bots/3");
});
});

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