Compare commits

..
4 Commits
Author SHA1 Message Date
tben 037119c1df Bump version to 0.28.16
CI / check (push) Waiting to run
Release image / image (release) Waiting to run
Release image / computer-image (release) Waiting to run
2026-11-27 07:22:55 +01:00
tben b37539f0c4 Inject open tasks and the conversation plan into every run, add paused tasks, and let bots pause plans 2026-11-27 07:22:55 +01:00
tben 1660857a3c Bump version to 0.28.15
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
2026-11-26 15:34:39 +01:00
tben ccbd3efddf Let the composer's slash commands reach everything the header menu offers 2026-11-26 15:34:39 +01:00
47 changed files with 966 additions and 198 deletions
+3 -3
View File
File diff suppressed because one or more lines are too long
+1 -1
View File
@@ -583,7 +583,7 @@ export type BUN_SQLITE_COBBLE_TASKS = {
* The brief (markdown): what to do, where, and how you'll know it's done
*/
description?: string;
status?: "todo" | "doing" | "blocked" | "done" | "cancelled" | "";
status?: "todo" | "doing" | "blocked" | "paused" | "done" | "cancelled" | "";
/**
* What the user has to do to unblock it; only meaningful while `status` is blocked
*/
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "cobble",
"version": "0.28.14",
"version": "0.28.16",
"module": "index.ts",
"type": "module",
"private": true,
+18
View File
@@ -60,6 +60,24 @@ describe("planStepReviewNote", () => {
expect(note({ on_step: false, uses: [{ name: "write_file", ok: true }] })).toBeNull();
});
test("an ordinary reply that ticked a step without its card is sent back for the card", () => {
const fault = note({ on_step: false, uses: [{ name: "complete_plan_step", ok: true }] });
expect(fault).toContain("finished step 2 of Plan #3");
expect(fault).toContain("ask_user");
expect(fault).toContain("Continue to step 3");
expect(
note({
on_step: false,
uses: [
{ name: "complete_plan_step", ok: true },
{ name: "ask_user", ok: true },
],
}),
).toBeNull();
});
test("a plan with no step left is left alone", () => {
expect(planStepReviewNote({ plan: { ...plan, current_step: null }, on_step: true, tool_uses: [] })).toBeNull();
});
+15 -5
View File
@@ -11,7 +11,8 @@ type PlanStep = {
type Params = {
/**
* The plan the run works, when it was queued for one of its steps.
* The plan this run sits in: the one it was queued for, or the one
* open in its conversation.
*/
plan: PlanStep | null;
/**
@@ -34,10 +35,17 @@ const EndingTools = ["ask_user", "update_plan", ...PlanWorkStartingTools];
* Checks a plan step's reply before it goes out: the step ends on a card
* whose first option continues the plan, so the plan moves on from the card
* in front of the user, never from the bot remembering to ask. A reply that
* reports the step and ends is sent back.
* reports the step and ends is sent back. It holds for an ordinary reply
* too, once it has ticked a step with `complete_plan_step`: a step marked
* done with no card under its report leaves the plan with nothing to move
* on from.
*/
export default function planStepReviewNote({ plan, on_step, tool_uses, status }: Params) {
if (!on_step || !plan || plan.current_step == null) return null;
if (!plan || plan.current_step == null) return null;
const ticked = tool_uses.some((use) => use.ok && use.name == "complete_plan_step");
if (!on_step && !ticked) return null;
/**
* A reply that says what stopped it, or hands the work to a run of its
@@ -53,5 +61,7 @@ export default function planStepReviewNote({ plan, on_step, tool_uses, status }:
const next = step + 1;
const last_step = next > plan.total_steps;
return `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.`;
}
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.`;
}
+55 -9
View File
@@ -31,8 +31,10 @@ import {
PlanActiveNote,
PlanPausedNote,
PlanModeNote,
OpenTasksNote,
} from "@/src/data/harness-prompts";
import grabBotRunPowers from "@/src/functions/backend/db/bot-types/grab-bot-run-powers";
import grabTasks from "@/src/functions/backend/db/tasks/grab-tasks";
import workspaceAdminsNote from "./workspace-admins-note";
import type { WorkspaceAdminTools } from "@/src/harness/tools/bot/grab-workspace-admin-tools";
import { grabContextBudgetTokens, grabReplyMaxToolSteps, grabRunMaxPromptTokens } from "@/src/functions/backend/db/app-settings/grab-run-limits";
@@ -198,6 +200,13 @@ export default async function runBotReply({
: await grabSessionPlan({ session_id });
const plan = plan_row ? toBotPlanView({ row: plan_row }) : null;
/**
* Whether this reply finished a plan step with `complete_plan_step`,
* however it was queued. The message then carries the plan's card, and
* the card it ends on is what starts the next step.
*/
let plan_ticked = false;
/**
* A step job queued before the user paused (or dropped) the plan has
* nothing to do: it ends without a word, rather than reporting a step
@@ -364,6 +373,23 @@ export default async function runBotReply({
* workspace's admin.
*/
const powers = await grabBotRunPowers({ bot_id: bot.id, workspace_id });
/**
* The tasks this run could be working, injected into its prompt so an
* open task is never forgotten (a production bot left a Doing task
* open for months until the user said "close that task"). Paused ones
* are the user's to park: the bot reads them with `list_tasks`, they
* just don't ask for attention.
*/
const open_tasks = (
await grabTasks({
bot_id: bot.id,
is_coordinator: powers.is_coordinator,
admin_workspace_ids: powers.admin_workspace_ids,
workspace_id,
open_only: true,
limit: AppData.TaskDigestCount,
})
).filter((task) => task.status != "paused");
/**
* A crew request's session and a hook's run are hidden: nobody follows
* them.
@@ -618,11 +644,13 @@ export default async function runBotReply({
*/
plan_mode,
/**
* The plan whose step this reply works, when it does:
* the card it ends on is the plan's next move
* (`postBotQuestionAnswers`).
* The plan whose step this reply works: the card it ends
* on is the plan's next move
* (`postBotQuestionAnswers`). Read when the card is put
* up, so a reply that finishes a step as it goes links
* the card to that plan.
*/
plan_id: on_plan_step ? plan?.id : null,
plan_id: () => (on_plan_step || plan_ticked ? plan?.id ?? null : null),
onAsk: ({ ref }) => proposals.push(ref),
redact: redact_reply,
}),
@@ -644,6 +672,22 @@ export default async function runBotReply({
workspace_id,
job_id: job.id,
on_step: on_plan_step,
/**
* An ordinary reply may work and tick the plan's current
* step when the message asked for exactly that work, and
* may park or pick up the plan when the user said so. A
* paused plan gets the same tools so it can resume and
* work the step in one reply; finishing a step of a plan
* that is still paused is refused at the row. Not in
* Plan mode: nothing writes there.
*/
can_complete:
!on_plan_step &&
!plan_mode &&
(plan?.status == "active" || plan?.status == "paused"),
onCompleted: () => {
plan_ticked = true;
},
/**
* A plan nobody approved yet needs the user, so
* it goes with the refs that set `needs_you`: the
@@ -707,17 +751,19 @@ export default async function runBotReply({
? ComputerFilesNote({ computer_id: computers[0]?.id || 0, dirs, can_import: true })
: "",
TasksNote,
TaskReminderNote,
open_tasks.length
? `${OpenTasksNote({ tasks: open_tasks })}\n\n${TaskReminderNote}`
: "",
can_hand_over ? HandOverTaskNote : "",
ActionCheckNote,
RequestScopeNote({ can_ask: Boolean(attended) && !asked }),
attended && !asked ? PlansNote : "",
attended && !asked && plan?.status == "planned" ? PlanWaitingNote({ plan }) : "",
attended && !asked && plan?.status == "paused" ? PlanPausedNote({ plan }) : "",
attended && !asked && plan?.status == "planned" ? PlanWaitingNote({ plan, plan_mode }) : "",
attended && !asked && plan?.status == "paused" ? PlanPausedNote({ plan, plan_mode }) : "",
attended && !asked && plan?.status == "active"
? on_plan_step
? PlanStepNote({ plan })
: PlanActiveNote({ plan })
: PlanActiveNote({ plan, plan_mode })
: "",
attended ? QuestionsNote : "",
SecretsNote,
@@ -849,7 +895,7 @@ export default async function runBotReply({
attachments: attachments.length ? attachments : undefined,
tool_log: result.tool_uses,
task_ids,
plan_message_id: message_plan_id ?? (on_plan_step ? plan?.id : undefined),
plan_message_id: message_plan_id ?? ((on_plan_step || plan_ticked) ? plan?.id : undefined),
/**
* A reply handed a tracker task (`params.tracker_task_id`) that
* used every step it had stopped short of finishing it: left
+78 -17
View File
@@ -29,6 +29,9 @@ import {
taskPlanNote,
wrapUpWorktreeNote,
PlanStepNote,
PlanActiveNote,
PlanPausedNote,
OpenTasksNote,
} from "@/src/data/harness-prompts";
import {
grabContextBudgetTokens,
@@ -39,7 +42,9 @@ import {
import grabBotComputers from "@/src/functions/backend/db/computers/grab-bot-computers";
import grabBotPrompt from "@/src/functions/backend/db/bots/grab-bot-prompt";
import grabBotPlan from "@/src/functions/backend/db/bot-plans/grab-bot-plan";
import grabSessionPlan from "@/src/functions/backend/db/bot-plans/grab-session-plan";
import toBotPlanView from "@/src/functions/backend/db/bot-plans/to-bot-plan-view";
import grabTasks from "@/src/functions/backend/db/tasks/grab-tasks";
import grabUserWorkspaces from "@/src/functions/backend/db/workspaces/grab-user-workspaces";
import runTextLoop from "@/src/harness/text/run-text-loop";
import redactTrace from "@/src/harness/trace/redact-trace";
@@ -285,6 +290,43 @@ export default async function runBotTask({
* card to put up and reports as usual.
*/
const on_plan_step = can_ask && Boolean(plan && plan.status == "active" && plan.current_step != null);
/**
* The conversation's open plan, when this run is not a step's own
* work: a long task run is where a bot loses the plan (it used to
* see no plan at all unless the app queued it for a step). An
* attended run that is asked for the plan's current step may work
* and tick it like a step's own run; nothing here starts a step on
* its own.
*/
const session_plan_row =
!Number(params.plan_id) && session_id && can_ask
? await grabSessionPlan({ session_id: Number(session_id) }).catch(() => null)
: null;
const session_plan =
session_plan_row && (session_plan_row.status == "active" || session_plan_row.status == "paused")
? toBotPlanView({ row: session_plan_row })
: null;
let ticked_plan_id: number | null = null;
const can_complete_plan_step =
!on_plan_step &&
can_ask &&
(session_plan?.status == "active" || session_plan?.status == "paused");
/**
* The tasks this run could be working, injected into its prompt so
* an open task is never forgotten. Paused ones are the user's to
* park: the bot reads them with `list_tasks`, they just don't ask
* for attention.
*/
const open_tasks = (
await grabTasks({
bot_id: bot.id,
is_coordinator: powers.is_coordinator,
admin_workspace_ids: powers.admin_workspace_ids,
workspace_id,
open_only: true,
limit: AppData.TaskDigestCount,
})
).filter((task) => task.status != "paused");
/**
* The coordinator weighing a worker's install request
* (`request_install`): it answers it with answer_install_request.
@@ -342,21 +384,28 @@ export default async function runBotTask({
})),
...admin_tools,
/**
* The plan's own step: it finishes the step, or says the plan
* is wrong. Writing or cancelling a plan is a reply's job, never
* a run's, so those stay out.
* The plan this run sits in. Writing or cancelling a plan stays
* a reply's job. A step's own run finishes its step; an
* attended run that isn't one may tick a step only when the
* message asked for that step's work, and then owes the plan
* its card.
*/
...(on_plan_step
? grabBotPlanTools({
user_id,
bot_id: bot.id,
session_id: session_id!,
workspace_id,
job_id: job.id,
on_step: true,
onPlan: ({ ref }) => shown.push(ref),
})
: []),
...(on_plan_step || can_complete_plan_step
? grabBotPlanTools({
user_id,
bot_id: bot.id,
session_id: session_id!,
workspace_id,
job_id: job.id,
on_step: on_plan_step,
can_complete: can_complete_plan_step,
writes_plan: false,
onCompleted: ({ plan_id }) => {
ticked_plan_id = plan_id;
},
onPlan: ({ ref }) => shown.push(ref),
})
: []),
/**
* Part of a crew request (`start_task`/`delegate_task` in an
* answer session): the bot can send the asker an interim word
@@ -454,7 +503,7 @@ export default async function runBotTask({
session_id,
workspace_id,
in_task: true,
plan_id: on_plan_step ? plan?.id : null,
plan_id: () => (on_plan_step ? plan?.id ?? null : ticked_plan_id),
onAsk: ({ ref }) => take_overs.push(ref),
redact: redact_text,
}),
@@ -678,6 +727,18 @@ export default async function runBotTask({
computer ? ComputerFilesNote({ computer_id: job.computer_id || 0, dirs }) : "",
named_files_note,
TasksNote,
open_tasks.length ? OpenTasksNote({ tasks: open_tasks }) : "",
/**
* The plan this run sits in when it isn't a step's own work:
* an attended run may work that plan's current step when the
* message asked for it, and must tick it and end on the card
* like the run the app queued for the step.
*/
!on_plan_step && session_plan
? session_plan.status == "active"
? PlanActiveNote({ plan: session_plan })
: PlanPausedNote({ plan: session_plan })
: "",
/**
* The plan's step this run works: it finishes that step, or asks
* the user on the card, and the report says which. This is the
@@ -854,7 +915,7 @@ export default async function runBotTask({
}).then((note) => {
if (note) return note;
return planStepReviewNote({ plan, on_step: on_plan_step, tool_uses, status });
return planStepReviewNote({ plan: plan ?? session_plan, on_step: on_plan_step, tool_uses, status });
}),
/**
* A report goes out only through `send_reply`, so it can't say
@@ -925,7 +986,7 @@ export default async function runBotTask({
attachments: attachments.length ? attachments : undefined,
tool_log: result.tool_uses,
task_ids,
plan_message_id: on_plan_step ? plan?.id : undefined,
plan_message_id: on_plan_step ? plan?.id : ticked_plan_id ?? undefined,
/**
* The wrap up was announced (`steps` counts its turns), so the
* run never got to the end of the work it was given.
@@ -1,4 +1,5 @@
import ContinueSessionButton from "./continue-session-button";
import useOpenOnCommand from "@/src/hooks/use-open-on-command";
import useShownSession from "@/src/hooks/use-shown-session";
import conversationHref from "@/src/utils/conversation-href";
import {
@@ -37,6 +38,8 @@ type Props = {
* Runs as it opens, e.g. closing the menu it was opened from.
*/
on_open?: () => void;
/** The composer command that opens this modal (`/sessions`). */
command?: string;
};
/**
@@ -52,8 +55,11 @@ export default function BotSessionsModal({
target,
target_wrapper_props,
on_open,
command,
}: Props) {
const [open, setOpen] = useState(false);
useOpenOnCommand({ command, on_fire: () => setOpen(true) });
const on_screen = useShownSession({ bot_id: Number(bot.id), workspace_id });
const sessions = useBotSessions({
bot_id: Number(bot.id),
+3 -1
View File
@@ -13,7 +13,9 @@ type Props = {
className?: string;
};
const MoveStatuses = TaskStatuses.filter((it) => ["todo", "doing", "done"].includes(it.value));
const MoveStatuses = TaskStatuses.filter((it) =>
["todo", "doing", "paused", "done"].includes(it.value),
);
/**
* The buttons that move a task along (To do, Doing, Done), the one it's
+7
View File
@@ -541,6 +541,13 @@ export const AppData = {
* many `list_tasks` hands back at once.
*/
TaskReminderDigestCount: 3,
/**
* Open tasks put in front of every run (`OpenTasksNote`): a bot that
* never sees its own list is how a Doing task sits for weeks. Paused
* ones are left out (the user parked them), so this is what a run is
* reminded of at most.
*/
TaskDigestCount: 8,
TaskListToolLimit: 20,
/**
* Automatic model picks (`rankAutoModels`). A free model from outside
+3 -2
View File
@@ -1,4 +1,5 @@
import { describe, expect, test } from "bun:test";
import { TaskStatuses } from "@/src/dict/task-dict";
import { CoordinatorSystemPrompt } from "./coordinator-system-prompt";
import { SiteData } from "./site-data";
@@ -24,8 +25,8 @@ describe("CoordinatorSystemPrompt", () => {
});
test("uses the real task statuses, not invented ones", () => {
for (const status of ["todo", "doing", "blocked", "done", "cancelled"]) {
expect(CoordinatorSystemPrompt).toContain(status);
for (const { value } of TaskStatuses) {
expect(CoordinatorSystemPrompt).toContain(value);
}
// Words from the previous draft that no tool accepts.
+1 -1
View File
@@ -72,7 +72,7 @@ A tool result is the source of truth.
- Read the change back when the tool allows it. If it can't be read back, say the write was confirmed but not independently verified.
- Never claim to have read, saved, attached, deleted or verified something you didn't, and never claim to know what the user's screen shows.
Task states are \`todo\`, \`doing\`, \`blocked\` (with a \`blocked_reason\`), \`done\` and \`cancelled\`, moved with \`update_task\`. Queued is not running, started is not done, and done is not verified. Check state with tools instead of trusting the conversation.
Task states are \`todo\`, \`doing\`, \`blocked\` (with a \`blocked_reason\`), \`paused\` (the user parked it), \`done\` and \`cancelled\`, moved with \`update_task\`. Queued is not running, started is not done, and done is not verified. Check state with tools instead of trusting the conversation.
When a call fails, read the error, fix the cause, retry only with a reason to expect a different outcome, then check the result. Never repeat an identical failing call. After repeated failures, stop and say what's known and what's uncertain. Don't hand the user a technical problem you can solve yourself.
+56 -1
View File
@@ -17,6 +17,8 @@ import {
TaskRunNote,
TaskWrapUpIncomingNote,
TasksNote,
OpenTasksNote,
PlanModeNote,
wrapUpWorktreeNote,
PlansNote,
PlanStepNote,
@@ -359,9 +361,62 @@ describe("plan notes", () => {
expect(PlanActiveNote({ plan })).toContain("leave the plan where it is");
});
test("an active plan lets an ordinary reply tick the step and ends on the card", () => {
const note = PlanActiveNote({ plan });
expect(note).toContain("work it now: finish it with complete_plan_step");
expect(note).toContain('"Continue to step 3"');
expect(note).toContain('"Pause the plan"');
expect(note).toContain('status "paused"');
});
test("in Plan mode an active plan is refined, not worked", () => {
const note = PlanActiveNote({ plan, plan_mode: true });
expect(note).toContain("the plan is yours to pick up and refine here, not to work");
expect(note).toContain("update_plan");
expect(note).not.toContain("complete_plan_step");
expect(PlanModeNote).toContain("The plan is the point of this mode");
expect(PlanModeNote).toContain("refine it with update_plan as many times");
});
test("in Plan mode a waiting or paused plan is refined too", () => {
expect(PlanWaitingNote({ plan: { ...plan, status: "planned" }, plan_mode: true })).toContain(
"rewrite the steps with update_plan",
);
expect(PlanWaitingNote({ plan: { ...plan, status: "planned" } })).toContain("they make them on the card");
expect(PlanPausedNote({ plan: { ...plan, status: "paused" }, plan_mode: true })).toContain(
"the plan is yours to refine here with update_plan",
);
expect(PlanPausedNote({ plan: { ...plan, status: "paused" } })).toContain('status "active"');
});
test("a paused plan is the user's to resume", () => {
expect(PlanPausedNote({ plan: { ...plan, status: "paused" } })).toContain("paused by the user");
});
});
describe("open tasks digest", () => {
test("names each open task with its ref and status", () => {
const note = OpenTasksNote({
tasks: [
{ id: 33, title: "Fix the hero crop", status: "doing" },
{ id: 46, title: null, status: "todo" },
],
});
expect(note).toContain("- [task:33] Fix the hero crop (doing)");
expect(note).toContain("- [task:46] (todo)");
});
test("tells the run to keep the list true and never report a move it didn't make", () => {
const note = OpenTasksNote({ tasks: [{ id: 1, title: "One", status: "blocked" }] });
expect(note).toContain("Keep this list true as you work");
expect(note).toContain("update_task");
});
test("reads a row whose columns are missing", () => {
expect(OpenTasksNote({ tasks: [{}] })).toContain("- [task] (open)");
});
});
+58 -18
View File
@@ -783,23 +783,40 @@ Tasks are the crew's to-do list. A task belongs to one bot, on its own list or i
- list_tasks shows what's open: yours, a workspace's, or (as the coordinator) all of it. Check it before you plan work, so you don't start something already tracked.
- create_task adds one, with a brief: what to do, where, and what done looks like. Only add a task for work that will take more than this reply; never one for something you're doing now.
- update_task moves it along. Set doing when you start, blocked with a reason when only the user can unblock it, and done only once the work is verified (see the check note above). Add a note as you go: it's what the user reads on the task, so one short line per real step, not a play-by-play.
- update_task moves it along. Set doing when you start, blocked with a reason when only the user can unblock it, paused when the user has parked the work for now, and done only once the work is verified (see the check note above). Add a note as you go: it's what the user reads on the task, so one short line per real step, not a play-by-play.
- On a workspace-wide task, read its log first (list_tasks with task_id) to see which bot did what and when, take a part nobody has done yet, and log each part you finish with update_task. Every note is recorded under your name and id, so the log is how the crew stays in step.
- A deliverable is a file: save it first with write_file, make_pdf or generate_image, then pass its [file:ID] ref in deliverable_file_ids, so the task carries what it produced.
- When you name a task, write its [task:ID] ref, e.g. [task:12], so the user can open it. Only tasks from list_tasks or create_task have one; a run from send_reply's work, start_task or delegate_task is not a task.`;
/**
* Added to a chat reply: when and how to bring pending tasks up, so the bot
* reminds the user without nagging.
* Added to every run: the bot's open tasks as the app reads them, so it
* works against the list instead of remembering to look it up. Paused ones
* are left out: the user parked them, and the run needn't push them.
*/
export const OpenTasksNote = ({
tasks,
}: {
tasks: { id?: number | string; title?: string | null; status?: string }[];
}) => `# Your open tasks
These are open on your list now, as the app reads them:
${tasks.map((task) => `- ${task.id ? `[task:${task.id}]` : "[task]"}${task.title ? ` ${task.title}` : ""} (${task.status || "open"})`).join("\n")}
- Keep this list true as you work, without waiting to be asked: when a doing task's work is finished and verified, move it to done; when only the user can unblock one, move it to blocked with the reason; when they say work on one is parked, move it to paused.
- Never report a task as done, started or moved without update_task answering for it in this run.`;
/**
* Added to a chat reply: when and how to bring the digest tasks up, so the
* bot reminds the user without nagging.
*/
export const TaskReminderNote = `# Mentioning pending tasks
You have tasks of your own to keep up with. When the message is an opening ("hello", "what's up"), or when the work you're answering is done and you're about to offer what comes next, call list_tasks before you write your answer and put the reminder in the answer itself.
You have open tasks above to keep up with. When the message is an opening ("hello", "what's up"), or when the work you're answering is done and you're about to offer what comes next, put the reminder in the answer itself.
- If something is blocked on the user, or something open plainly connects to what they're asking, mention it in one short line with its status, at most ${AppData.TaskReminderDigestCount} tasks: "Still open: [task:12] send the signed form (blocked: you need to sign it), [task:14] recheck the invoices."
- If something is blocked on the user, or something open plainly connects to what they're asking, mention it in one short line with its status, at most ${AppData.TaskReminderDigestCount} of the tasks above: "Still open: [task:12] send the signed form (blocked: you need to sign it), [task:14] recheck the invoices."
- Don't list everything, don't repeat the same reminder reply after reply, and skip it when the user is mid-task, winding down, or you've just asked them a question. A greeting is a good moment; every greeting is not.
- Never invent a task: name only what list_tasks returned.
- Never send the answer and then call list_tasks: only your last message goes out, so the answer you wrote first would never reach the user. Look first, then answer once.`;
- Never invent a task: name only ones the list above or list_tasks returned. That list is the newest ${AppData.TaskDigestCount} open ones: for more, or for another bot's or a workspace's, call list_tasks first, never guess.`;
/**
* Added to a chat reply that has `hand_over_task`: a worker hands a task it
@@ -1109,11 +1126,16 @@ When a plan you worked through is one the same work comes back to (a new project
/**
* A plan waiting on the user: the bot wrote it and may not start it yet,
* whatever the user writes in the meantime.
* whatever the user writes in the meantime. In Plan mode the bot may still
* refine it (the mode's whole point), it just can't start it.
*/
export const PlanWaitingNote = ({ plan }: { plan: PlanPrompt }) => `# Your plan is waiting on the user
export const PlanWaitingNote = ({ plan, plan_mode }: { plan: PlanPrompt; plan_mode?: boolean }) => `# Your plan is waiting on the user
Plan #${plan.id} "${plan.title}" is on its card in this conversation, waiting for the user to approve it or change its steps. Its steps are not work yet: don't start them, don't report on them, and don't write another plan. Answer what the user wrote; if they asked for changes to the plan, they make them on the card.`;
Plan #${plan.id} "${plan.title}" is on its card in this conversation, waiting for the user to approve it or change its steps. Its steps are not work yet: don't start them, don't report on them, and don't write another plan. Answer what the user wrote.${
plan_mode
? ` This reply runs in Plan mode, so the plan is yours to refine here: when they ask for changes, rewrite the steps with update_plan (the whole list), as many times as they want, and say in a line what changed. Starting it is still theirs: they approve it on the card.`
: ` If they asked for changes to the plan, they make them on the card.`
}`;
/**
* Given to the run that works one step of an approved plan: that step only,
@@ -1145,9 +1167,15 @@ This run works step ${index + 1} only: ${step?.text || ""}
/**
* Given to any other run in a conversation whose plan is approved and being
* worked: the plan is in the prompt, and the user's own message comes first.
* The run may work a step when the message asks for it (`complete_plan_step`
* is offered), and it can park the plan when they asked: the card still
* gates every step nobody approved.
*/
export const PlanActiveNote = ({ plan }: { plan: PlanPrompt }) => {
export const PlanActiveNote = ({ plan, plan_mode }: { plan: PlanPrompt; plan_mode?: boolean }) => {
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}`;
return `# The plan in this conversation
@@ -1155,18 +1183,29 @@ Plan #${plan.id} "${plan.title}" is approved and in progress${index == null ? ""
${planStepLines({ plan })}
- Its steps are worked one per reply, each ending on a card the user answers to start the next one. This reply isn't working a step, so don't work one here: if they ask you to carry on, say the next step is step ${(index ?? 0) + 1} and they start it from the plan's card (Continue on the plan, under the report above), then answer whatever else they asked.
- If they asked something else, answer that and leave the plan where it is: it carries on from there.
- The steps are theirs to change on the card. If the work moved on from one of them, update_plan and say what changed.`;
${
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 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.`
}`;
};
/**
* A paused plan: the user stopped it, so its steps wait until they say
* otherwise. The bot still answers them.
* otherwise. The bot still answers them, and can pick the plan back up when
* they ask.
*/
export const PlanPausedNote = ({ plan }: { plan: PlanPrompt }) => `# A paused plan
export const PlanPausedNote = ({ plan, plan_mode }: { plan: PlanPrompt; plan_mode?: boolean }) => `# A paused plan
Plan #${plan.id} "${plan.title}" is paused by the user at step ${(plan.current_step ?? 0) + 1} of ${plan.steps.length}. Don't work its steps and don't finish them: answer what the user asks, and leave picking it back up to them (they resume it from the card).`;
Plan #${plan.id} "${plan.title}" is paused by the user at step ${(plan.current_step ?? 0) + 1} of ${plan.steps.length}. Don't work its steps and don't finish them: answer what the user asks, and leave picking it back up to them (they resume it from the card).${
plan_mode
? ` This reply runs in Plan mode: the plan is yours to refine here with update_plan (the whole step list, as many times as they ask), without starting it again.`
: ` If this message asks you to carry on, set the plan running again with update_plan and status "active", then work the step it stands on and end on the step's card like any step reply.`
}`;
/**
* Plan mode: the user turned it on in the composer, so this reply plans and
@@ -1179,7 +1218,8 @@ export const PlanModeNote = `# Plan mode
The user sent this message with Plan mode on. This reply plans, reads and asks; it changes nothing, anywhere.
- Read what you need: files, tasks, schedules, hooks, graphics, knowledgebases, skills, past conversations, computers and the crew are all readable. Then say what you found and what you would do.
- When the work is several pieces that build on each other, write the plan with create_plan (3 to 6 steps) and let them approve it. Nothing in it starts until they do, and working its steps is a later reply. Approving it ends Plan mode.
- **The plan is the point of this mode.** When the work is several pieces that build on each other, it ends on a plan card, not in prose: write it with create_plan (3 to 6 steps) and let them approve it. Nothing in it starts until they do, and working its steps is a later reply. Approving it ends Plan mode.
- When the conversation already has a plan (its note above names it: waiting, in progress or paused), that is the plan to work on here: refine it with update_plan as many times as the user wants changes, sending the whole step list each time. Don't write a second plan over it, and don't work or tick its steps: that waits until they turn the mode off.
- When a choice is theirs, ask it with ask_user instead of picking for them. Answering it does not end Plan mode: their answer is another planning turn.
- Nothing is written, run or changed in this mode: no files written, no tasks, schedules, hooks, memory or instructions changed, no secrets, no crew changes, no computers, browsers, MCP servers or custom tools. Those tools are still in your list and calling one is refused with the reason, so don't say you did any of it, don't say a run is under way, and don't look for another way in.
- When the result belongs in a file or somewhere outside the chat (a document, a task, a memory), don't paste it and never say a tool is missing: Plan mode is what stops the save. Say so in one sentence, and either write it as a plan they can approve (its steps save it) or say what you will do once they turn Plan mode off. A short template they asked to read can stay in the message.
+7 -3
View File
@@ -18,6 +18,10 @@ export const TaskStatuses = [
title: "Blocked",
value: "blocked",
},
{
title: "Paused",
value: "paused",
},
{
title: "Done",
value: "done",
@@ -31,10 +35,10 @@ export const TaskStatuses = [
export type TaskStatus = (typeof TaskStatuses)[number]["value"];
/**
* The statuses a task still needs work in: what a reminder may name and
* what a digest shows.
* The statuses a task still needs work in: a paused task is open (it waits
* for the user to pick it up), but the run digest leaves it out.
*/
export const OpenTaskStatuses = ["todo", "doing", "blocked"] as const;
export const OpenTaskStatuses = ["todo", "doing", "blocked", "paused"] as const;
/**
* Every status as a zod-friendly tuple of its values.
@@ -27,7 +27,7 @@ export default async function createBotPlan({ user_id, bot_id, session_id, works
if (open) {
throw new AppError(
`There's already a plan open in this conversation (#${open.id}, "${open.title || "untitled"}"): work that one, or cancel it before writing another.`,
`There's already a plan open in this conversation (#${open.id}, "${open.title || "untitled"}"): work that one, or refine it with update_plan, or cancel it before writing another.`,
);
}
@@ -129,7 +129,7 @@ describe("postBotQuestionAnswers", () => {
expect(paused).toHaveLength(0);
});
test("any other answer to a plan's card pauses the plan and still answers", async () => {
test("any other answer to a plan's card leaves the plan where it stands and lets the reply decide", async () => {
question.plan_id = 3;
await postBotQuestionAnswers({
@@ -137,8 +137,7 @@ describe("postBotQuestionAnswers", () => {
user_id: 1,
});
expect(paused).toHaveLength(1);
expect(paused[0]!.status).toBe("paused");
expect(paused).toHaveLength(0);
expect(step_jobs).toEqual([]);
expect(enqueued).toHaveLength(1);
});
@@ -152,6 +151,7 @@ describe("postBotQuestionAnswers", () => {
});
expect(step_jobs).toEqual([]);
expect(paused).toHaveLength(1);
expect(paused).toHaveLength(0);
expect(enqueued).toHaveLength(1);
});
});
@@ -1,7 +1,6 @@
import type { BUN_SQLITE_COBBLE_BOT_QUESTIONS, BUN_SQLITE_COBBLE_BOT_SESSIONS } from "@/db/types/db";
import { logError } from "@/src/functions/backend/logger";
import pushBotNotice from "@/src/bots-queue/push-bot-notice";
import pushBotPlan from "@/src/bots-queue/push-bot-plan";
import wakeBotsQueue from "@/src/bots-queue/wake-bots-queue";
import type { BotQuestionView } from "@/src/types";
import botQuestionAnswersText from "@/src/utils/bot-question-answers-text";
@@ -11,7 +10,6 @@ import ensureBotSession from "../bot-sessions/ensure-bot-session";
import grabUserBotSession from "../bot-sessions/grab-user-bot-session";
import insertUserMessage from "../bots/insert-user-message";
import enqueueBotReply from "../bots-queue/enqueue-bot-reply";
import setBotPlanStatus from "../bot-plans/set-bot-plan-status";
import enqueuePlanStep from "../bot-plans/enqueue-plan-step";
import grabBotQuestion from "./grab-bot-question";
@@ -28,8 +26,11 @@ type Params = {
* where the question was asked, never to whichever bot's page was open.
*
* A card a plan's step ended on is the plan's own next move: Continue
* starts its next step, and anything else pauses it, so the plan never
* waits on the user to say "move on" in the chat.
* starts its next step, and anything else leaves the plan where it stands:
* the reply the answer wakes reads it and either works the step now or
* parks the plan with `update_plan`, as the words on the card say.
* Pausing it here, unseen, was how one production plan got cancelled: the
* bot woke to a plan it had to explain and read "not paused" as "ended".
*
* Best effort: a failure is logged and never undoes the answer.
*/
@@ -68,18 +69,6 @@ export default async function postBotQuestionAnswers({ view, user_id }: Params)
const plan_id = Number(row.plan_id) || 0;
const continue_plan = plan_id > 0 && planContinueAnswer({ view });
if (plan_id > 0 && !continue_plan) {
await setBotPlanStatus({ plan_id, user_id, status: "paused" })
.then(async () => {
await pushBotPlan({
plan_id,
session_id: Number(session.id),
bot_id,
});
})
.catch(() => null);
}
if (continue_plan) {
const step_job = await enqueuePlanStep({ plan_id }).catch(() => null);
+2 -2
View File
@@ -53,7 +53,7 @@ type Params = {
*/
statuses?: string[];
/**
* Only the open ones (todo, doing, blocked).
* Only the open ones (todo, doing, blocked, paused).
*/
open_only?: boolean;
limit?: number;
@@ -136,7 +136,7 @@ export default async function grabTasks({
LEFT JOIN workspaces w ON w.id = t.workspace_id
LEFT JOIN tasks p ON p.id = t.parent_task_id
${where.length ? `WHERE ${where.join(" AND ")}` : ""}
ORDER BY CASE t.status WHEN 'blocked' THEN 0 WHEN 'doing' THEN 1 WHEN 'todo' THEN 2 WHEN 'done' THEN 3 ELSE 4 END,
ORDER BY CASE t.status WHEN 'blocked' THEN 0 WHEN 'doing' THEN 1 WHEN 'todo' THEN 2 WHEN 'paused' THEN 3 WHEN 'done' THEN 4 ELSE 5 END,
t.updated_at DESC, t.id DESC
${limit ? `LIMIT ${Number(limit)}` : ""}`,
values: [...face.values, ...OpenTaskStatuses, ...values],
@@ -12,6 +12,12 @@ type Params = {
* puts the step back (`pauseFailedPlanStep`).
*/
job_id?: number | string;
/**
* Called once the step is on record, so the run's message links the plan
* and its card counts as the plan's own (an ordinary reply that ticked
* a step advances the plan from its card, like a step's own run).
*/
onCompleted?: (params: { plan_id: number }) => void;
};
type Args = {
@@ -25,7 +31,7 @@ type Args = {
* ends on, so a step is only ever finished by a run that did the work, one
* at a time.
*/
export default function completePlanStepTool({ bot_id, session_id, job_id }: Params): HarnessTool<Args> {
export default function completePlanStepTool({ bot_id, session_id, job_id, onCompleted }: Params): HarnessTool<Args> {
let completed = false;
return {
@@ -62,6 +68,7 @@ export default function completePlanStepTool({ bot_id, session_id, job_id }: Par
* the push keeps the one that's there current.
*/
await pushBotPlan({ plan_id: done.plan_id, session_id, bot_id });
onCompleted?.({ plan_id: done.plan_id });
if (done.done) {
return `Step ${done.index + 1} is done and it was the last one: the plan is finished on its card. Write your report now, two or three sentences on what the plan produced. If this plan will come back (the same work, the next project or the next month), save its steps now with update_memory as a short checklist, and say in a line that you kept them.`;
@@ -31,7 +31,7 @@ type Args = {
export default function createPlanTool({ user_id, bot_id, session_id, workspace_id, onPlan }: Params): HarnessTool<Args> {
return {
name: "create_plan",
description: `Write the plan for work that is several steps, before starting it: the goal that says what finished looks like, and 3 to 6 steps in the order you'd do them, one line each, each naming what it produces. It goes to the user as a card in this conversation, and nothing of it runs until they approve it (they can change the steps first). Write the plan instead of answering with a long list of everything you're about to do. Only when a plan is already open in this conversation, work it instead.`,
description: `Write the plan for work that is several steps, before starting it: the goal that says what finished looks like, and 3 to 6 steps in the order you'd do them, one line each, each naming what it produces. It goes to the user as a card in this conversation, and nothing of it runs until they approve it (they can change the steps first). Write the plan instead of answering with a long list of everything you're about to do. Only when a plan is already open in this conversation, work that one or refine it with update_plan instead of writing a second.`,
schema: z.object({
title: BotPlanTitleSchema.describe(`A short name for the work, e.g. "Audit the pricing pages"`),
goal: BotPlanGoalSchema.describe(`What the plan is for and what "done" means, in one sentence`),
@@ -4,9 +4,10 @@ import grabBotPlanTools from "./grab-bot-plan-tools";
/**
* A run working a plan's step may only work it: writing another plan, or
* cancelling the one it was woken for, is the user's call on the card. Only
* a chat reply writes a plan. A reply that isn't a step can't finish one
* either, or the plan would sit active with no card to start the next step
* from.
* a reply that writes plans gets create and cancel (`writes_plan`): a task
* run in a planned conversation is there to work, not to plan. An ordinary
* attended reply may finish a step when the plan is active and its message
* asked for it (`can_complete`), since it then ends on the step's card too.
*/
const names = (tools: { name: string }[]) => tools.map((tool) => tool.name);
@@ -25,10 +26,26 @@ describe("grabBotPlanTools", () => {
expect(names(build())).toEqual(["create_plan", "cancel_plan", "update_plan"]);
});
test("a reply whose plan is active can also finish its step", () => {
expect(names(build({ can_complete: true }))).toEqual([
"create_plan",
"cancel_plan",
"update_plan",
"complete_plan_step",
]);
});
test("a run working a step can only change the plan and finish its step", () => {
expect(names(build({ on_step: true }))).toEqual(["update_plan", "complete_plan_step"]);
});
test("a task run picks up the conversation's plan without writing one", () => {
expect(names(build({ on_step: false, can_complete: true, writes_plan: false }))).toEqual([
"update_plan",
"complete_plan_step",
]);
});
test("a plan the app writes shows its card on the message", () => {
const refs: string[] = [];
@@ -14,6 +14,23 @@ type Params = {
* to write one or end one.
*/
on_step?: boolean;
/**
* The plan this run sits in is approved (running, or paused and about
* to be picked back up): an ordinary reply (or a task run the user
* follows) may work a step the message asked for, and must tick it and
* end on the card like a step's own run. A step of a still-paused plan
* is refused at the row, so resume comes first.
*/
can_complete?: boolean;
/**
* A task run: writing or cancelling a plan stays a reply's job.
*/
writes_plan?: boolean;
/**
* Called when the run finishes a step, so its message links the plan and
* its card belongs to it.
*/
onCompleted?: (params: { plan_id: number }) => void;
/**
* Called with each plan's ref, so the message carries its card.
*/
@@ -27,18 +44,19 @@ type Params = {
/**
* The tools a bot plans with: `create_plan` when work is several steps,
* `update_plan` when what it found makes the rest wrong, and
* `complete_plan_step` to finish the step it worked. A plan waits on its
* card for the user; only a chat reply writes one, since routines and hook
* calls already have their plan.
* `update_plan` when what it found makes the rest wrong (or to park and
* pick up a plan the user asked about), and `complete_plan_step` to finish
* the step it worked. A plan waits on its card for the user; only a chat
* reply writes one, since routines and hook calls already have their plan.
*
* A run that is itself working a plan gets neither `create_plan` (the
* conversation already has one open) nor `cancel_plan` (whether the plan
* stands is the user's call), so the only thing it can do is work it.
*
* Only a step's own run can finish a step: a reply that isn't one would
* finish it with no card under its report, and the plan would sit active
* with nothing to start the next one.
* A step is finished by a run that did the work: the step's own run, or an
* ordinary attended run whose message asked for that step. A run that
* ticks one owes the plan its card, and the step review sends it back
* until the card is up beside the report.
*/
export default function grabBotPlanTools({
user_id,
@@ -46,19 +64,24 @@ export default function grabBotPlanTools({
session_id,
workspace_id,
on_step,
can_complete,
writes_plan = true,
onCompleted,
onPlan,
job_id,
}: Params) {
const tools: HarnessTool[] = [];
if (!on_step) {
if (!on_step && writes_plan) {
tools.push(createPlanTool({ user_id, bot_id, session_id, workspace_id, onPlan }));
tools.push(cancelPlanTool({ user_id, bot_id, session_id }));
}
tools.push(updatePlanTool({ user_id, bot_id, session_id, onPlan }));
if (on_step) tools.push(completePlanStepTool({ bot_id, session_id, job_id }));
if (on_step || can_complete) {
tools.push(completePlanStepTool({ bot_id, session_id, job_id, onCompleted }));
}
return tools;
}
+51 -13
View File
@@ -1,10 +1,13 @@
import { z } from "zod";
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 AppError from "@/src/utils/app-error";
import botPlanRef from "@/src/utils/bot-plan-ref";
import currentPlanStepIndex from "@/src/utils/current-plan-step-index";
import parseBotPlanSteps from "@/src/utils/parse-bot-plan-steps";
import type { HarnessTool } from "../../../types";
type Params = {
@@ -16,9 +19,10 @@ type Params = {
type Args = {
plan_id: number;
steps: z.infer<typeof BotPlanStepTextsSchema>;
steps?: z.infer<typeof BotPlanStepTextsSchema>;
title?: string;
goal?: string;
status?: "paused" | "active";
};
/**
@@ -26,36 +30,70 @@ type Args = {
* was wrong. The same rules the user's edits follow hold: a step already
* done is a record of work that happened, so it stays at the top with its
* note, and everything after it is the bot's to rewrite.
*
* It also parks and picks the plan up, when the user asked: a typed answer
* to the plan's card is the bot's to read, and a cancel is never the right
* reading of "pause" (one production bot ended a plan the user had only
* 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> {
return {
name: "update_plan",
description: `Change the plan you're working when what you found makes the rest of it wrong. Send the whole list of steps, in order, the steps already done first and unchanged (their notes are what was worked). Say in your reply what changed and why, in a line. Don't use it to make the plan look finished.`,
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.describe(`The plan's steps as they should now read, done ones first and unchanged`),
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.describe(`A new goal, only when what "done" means has changed`),
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`),
}),
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.`);
}
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.`);
}
await saveBotPlanSteps({
plan_id: args.plan_id,
user_id,
title: args.title?.trim() || row.title || "",
goal: args.goal?.trim() || row.goal || "",
steps: args.steps,
});
if (args.steps) {
await saveBotPlanSteps({
plan_id: args.plan_id,
user_id,
title: args.title?.trim() || row.title || "",
goal: args.goal?.trim() || row.goal || "",
steps: args.steps,
});
}
let moved = "";
if (args.status) {
if (args.status == "active" && row.status == "planned") {
throw new AppError(
`Plan #${args.plan_id} is waiting for the user to approve it: approval is theirs to give on its card, not for you to set.`,
);
}
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"
? `Plan #${args.plan_id} is paused${at == null ? "" : ` at step ${at + 1}`}: say so in a line. It waits there until the user resumes it.`
: `Plan #${args.plan_id} is running again: if this message asked you to carry on, work its current step now and end on the step's card; otherwise say it is running and stop there.`;
}
onPlan({ ref: botPlanRef({ plan_id: args.plan_id }) });
await pushBotPlan({ plan_id: args.plan_id, session_id, bot_id });
return `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.`;
},
};
}
}
@@ -20,9 +20,12 @@ type Params = {
plan_mode?: boolean;
/**
* The plan whose step this run works, when the card ends that step: its
* first option continues the plan, anything else pauses it.
* first option continues the plan; any other answer leaves the plan
* where it stands and the woken reply reads it. A run that ticks a
* step mid-reply passes a getter, so the card made after the tick
* carries the plan's id.
*/
plan_id?: number | null;
plan_id?: number | null | (() => number | null);
/**
* Whether the run is a task, which stops and reports rather than waits.
*/
@@ -96,7 +99,7 @@ export default function askUserTool({
session_id,
workspace_id,
plan_mode: Boolean(plan_mode),
plan_id,
plan_id: typeof plan_id == "function" ? plan_id() : plan_id,
title: args.title?.trim() ? redact(args.title.trim()) : "",
questions: args.questions.map((item) => ({
question: redact(item.question),
@@ -47,7 +47,7 @@ type Args = {
export default function listTasksTool({ bot_id, user_id, is_coordinator, admin_workspace_ids, workspace_id, onTask }: Params): HarnessTool<Args> {
return {
name: "list_tasks",
description: `List tasks: yours (your own list and the ones you have in workspaces), the ones in ${workspace_id ? "this workspace" : "a workspace"}, or ${is_coordinator ? "every task in the install" : "every task you can reach (yours, the workspace-wide ones in your workspaces, and as a workspace's admin every task there)"}.${workspace_id ? " You are working in a workspace, so only its tasks are in reach: never another workspace's, nor your own list outside it." : ""} Each line is its id, status, title, whose it is, its files and its latest note with who wrote it. Open ones come first (blocked, then doing, then to do). Use it to plan work, and to check what's still pending when the user says hello or asks what's next. A workspace-wide task is worked on by every bot in its workspace: before you work on one, read it with task_id to see its brief and its whole log (which bot did what, and when), so you pick up where the others left off instead of redoing their part.`,
description: `List tasks: yours (your own list and the ones you have in workspaces), the ones in ${workspace_id ? "this workspace" : "a workspace"}, or ${is_coordinator ? "every task in the install" : "every task you can reach (yours, the workspace-wide ones in your workspaces, and as a workspace's admin every task there)"}.${workspace_id ? " You are working in a workspace, so only its tasks are in reach: never another workspace's, nor your own list outside it." : ""} Each line is its id, status, title, whose it is, its files and its latest note with who wrote it. Open ones come first (blocked, then doing, then to do, then paused). Use it to plan work, and to check what's still pending when the user says hello or asks what's next. A workspace-wide task is worked on by every bot in its workspace: before you work on one, read it with task_id to see its brief and its whole log (which bot did what, and when), so you pick up where the others left off instead of redoing their part.`,
schema: z.object({
task_id: z
.number()
@@ -62,7 +62,7 @@ export default function listTasksTool({ bot_id, user_id, is_coordinator, admin_w
open_only: z
.boolean()
.optional()
.describe(`Only the open ones (to do, doing, blocked). Defaults to false.`),
.describe(`Only the open ones (to do, doing, blocked, paused). Defaults to false.`),
}),
run: async ({ args }) => {
if (args.task_id) {
@@ -81,7 +81,7 @@ export default function updateTaskTool({
return {
name: "update_task",
description: `Move a task along. Rename it with title or rewrite its brief with description (never create a second task for the same work just to fix its name). Set its status (blocked needs a reason: what the user has to do), log a note of what you did or found, and file the files it produced. Call it as the work advances, not only at the end; every note is what the user sees on the task. A workspace-wide task is shared by every bot in its workspace: log a note for each part you do (it's recorded under your name and id, with the time) so the others see who did what, and don't mark it done while parts others are on are still open. Mark done only once you've verified the work (see the check note): starting a task isn't finishing it. To file a deliverable, save it first with write_file, make_pdf or generate_image, then pass its [file:ID] number. A task holds ${AppData.TaskMediaMaxPerTask} files: to make room, or to drop a superseded version, unlink files with unlink_file_ids (list_tasks with task_id shows what's filed; the file stays in its folder). Unlink first, then file, in the same call. A part of a workspace-wide task (its row says so) is one piece of that work: log your notes on it like any task, and unlink_parent: true takes it out of the parent if it stops being part of it. parent_task_id: N makes a task of your own the part you took on of the workspace-wide task #N in its workspace (one piece each, and the parent stays open until someone verifies them all).${can_share ? ` As ${is_coordinator ? "the coordinator" : "a workspace's admin"}, workspace_wide: true turns a bot's open task in ${is_coordinator ? "a" : "your"} workspace into a workspace-wide one every bot there works on (hand it to one bot again with delegate_task).` : ""}`,
description: `Move a task along. Rename it with title or rewrite its brief with description (never create a second task for the same work just to fix its name). Set its status (blocked needs a reason: what the user has to do; paused is work the user parked for later: it stays open but drops out of the task list a run is shown, and you move it back when it's picked up), log a note of what you did or found, and file the files it produced. Call it as the work advances, not only at the end; every note is what the user sees on the task. A workspace-wide task is shared by every bot in its workspace: log a note for each part you do (it's recorded under your name and id, with the time) so the others see who did what, and don't mark it done while parts others are on are still open. Mark done only once you've verified the work (see the check note): starting a task isn't finishing it. To file a deliverable, save it first with write_file, make_pdf or generate_image, then pass its [file:ID] number. A task holds ${AppData.TaskMediaMaxPerTask} files: to make room, or to drop a superseded version, unlink files with unlink_file_ids (list_tasks with task_id shows what's filed; the file stays in its folder). Unlink first, then file, in the same call. A part of a workspace-wide task (its row says so) is one piece of that work: log your notes on it like any task, and unlink_parent: true takes it out of the parent if it stops being part of it. parent_task_id: N makes a task of your own the part you took on of the workspace-wide task #N in its workspace (one piece each, and the parent stays open until someone verifies them all).${can_share ? ` As ${is_coordinator ? "the coordinator" : "a workspace's admin"}, workspace_wide: true turns a bot's open task in ${is_coordinator ? "a" : "your"} workspace into a workspace-wide one every bot there works on (hand it to one bot again with delegate_task).` : ""}`,
schema: z.object({
task_id: z.number().int(),
title: z
+35
View File
@@ -0,0 +1,35 @@
import { useEffect, useRef } from "react";
import { ComposerCommandEvent } from "@/src/utils/composer-command-event";
/**
* Answers a composer command by name: while `command` is set, `on_fire` runs
* when the composer dispatches that command. Components mounted behind a
* closed dropdown still hear it (twui keeps the content mounted), so the
* composer can open any of them. Pass `command` only to the instance the
* commands should drive.
*/
export default function useOpenOnCommand({
command,
on_fire,
}: {
command?: string;
on_fire: () => void;
}) {
const fire = useRef(on_fire);
fire.current = on_fire;
useEffect(() => {
if (!command) return;
function listen(event: Event) {
if ((event as CustomEvent).detail != command) return;
fire.current();
}
window.addEventListener(ComposerCommandEvent, listen);
return () => window.removeEventListener(ComposerCommandEvent, listen);
}, [command]);
}
@@ -1,15 +1,44 @@
/**
* The composer's slash commands: what `/new`, `/continue` and `/clear` do
* to the conversation's session, and how the list above the input
* describes them.
* The composer's slash commands. The session trio (`/new`, `/continue`,
* `/clear`) acts on the conversation's session and reloads the page; the
* modal ones open what the conversation header's menu opens (the list loads
* then, so nothing costs anything until picked); `/copy` and `/stop` do the
* menu's own two actions from the input; `/panel` slides the bot panel in
* and `/settings` goes to the bot's settings page. Which ones a user sees is
* `visibleComposerCommands`, mirroring the menu's own gates.
*/
export type ComposerCommandAction =
| "session"
| "modal"
| "copy"
| "stop"
| "panel"
| "link";
export type ComposerCommand = {
name: "new" | "continue" | "clear";
name: string;
description: string;
action: ComposerCommandAction;
/** For a session command: the API the composer posts to. */
path?: "new-session" | "continue-session" | "delete-session";
/** For a link command: where it goes. */
href?: (params: { bot_id: number }) => string;
};
export const ComposerCommands: ComposerCommand[] = [
{ name: "new", description: "Start a fresh session" },
{ name: "continue", description: "Carry this conversation into a new session, with a summary" },
{ name: "clear", description: "Delete this session and start a new one" },
];
{ name: "new", description: "Start a fresh session", action: "session", path: "new-session" },
{ name: "continue", description: "Carry this conversation into a new session, with a summary", action: "session", path: "continue-session" },
{ name: "clear", description: "Delete this session and start a new one", action: "session", path: "delete-session" },
{ name: "sessions", description: "List this bot's chat sessions", action: "modal" },
{ name: "files", description: "Browse the bot's files", action: "modal" },
{ name: "tasks", description: "See the tasks this bot works on", action: "modal" },
{ name: "routines", description: "See the routines this bot runs", action: "modal" },
{ name: "hooks", description: "See the hooks that wake this bot", action: "modal" },
{ name: "computers", description: "See the computers this bot works on", action: "modal" },
{ name: "models", description: "See and change the models this bot runs on", action: "modal" },
{ name: "instructions", description: "Edit what this bot does in this workspace", action: "modal" },
{ name: "panel", description: "Open the bot's panel", action: "panel" },
{ name: "copy", description: "Copy this session as markdown", action: "copy" },
{ name: "stop", description: "Stop the bot's queued and running work", action: "stop" },
{ name: "settings", description: "Open this bot's settings", action: "link", href: ({ bot_id }) => `/admin/settings/bots/${bot_id}` },
];
@@ -0,0 +1,34 @@
import conversationMarkdown from "@/src/utils/conversation-markdown";
import copyPendingText from "@/src/utils/copy-pending-text";
import fetchConversationExport from "./fetch-conversation-export";
/**
* Puts the conversation's active session on the clipboard as one markdown
* document. The clipboard write starts at once with a pending
* `ClipboardItem`, so it keeps the user's gesture (the menu's click, or the
* Enter keypress that ran `/copy`) even though the export is still
* fetching. Returns nothing on success, or the reason to show.
*/
export default async function copyConversation({
bot_id,
workspace_id,
}: {
bot_id: number;
workspace_id?: number | null;
}): Promise<string | null> {
const markdown = fetchConversationExport({ bot_id, workspace_id }).then((res) => {
if (!res?.success || !res.singleRes) {
throw new Error(res?.msg || "Couldn't load the chat.");
}
return conversationMarkdown({ conversation: res.singleRes, now: Date.now() });
});
try {
const worked = await copyPendingText({ text: markdown });
return worked ? null : "Couldn't copy the chat to the clipboard.";
} catch (error: unknown) {
return error instanceof Error ? error.message : "Couldn't copy the chat.";
}
}
@@ -1,4 +1,5 @@
import { useContext, useEffect, useState } from "react";
import useOpenOnCommand from "@/src/hooks/use-open-on-command";
import Modal from "@moduletrace/twui/elements/Modal";
import H2 from "@moduletrace/twui/layout/H2";
import Span from "@moduletrace/twui/layout/Span";
@@ -36,6 +37,8 @@ type Props = {
* (its text) instead of an icon: clicking it opens the modal.
*/
meta_text?: string;
/** The composer command that opens this modal (`/computers`). */
command?: string;
};
/**
@@ -51,11 +54,14 @@ export default function BotComputersModal({
menu_hint,
on_open,
meta_text,
command,
}: Props) {
const { computers, switching_id, error, switchComputer, openComputer } =
useContext(BotComputersContext);
const [open, setOpen] = useState(false);
useOpenOnCommand({ command, on_fire: () => setOpen(true) });
const current = computers[0];
useEffect(() => {
@@ -1,4 +1,5 @@
import { useContext, useEffect, useMemo, useState } from "react";
import useOpenOnCommand from "@/src/hooks/use-open-on-command";
import Modal from "@moduletrace/twui/elements/Modal";
import H2 from "@moduletrace/twui/layout/H2";
import Span from "@moduletrace/twui/layout/Span";
@@ -27,6 +28,8 @@ type Props = {
*/
menu?: boolean;
on_open?: () => void;
/** The composer command that opens this modal (`/files`). */
command?: string;
};
/**
@@ -36,9 +39,11 @@ type Props = {
* as the user types) goes through the same endpoint, so the page props
* stay small.
*/
export default function BotFilesModal({ bot, workspace, menu, on_open }: Props) {
export default function BotFilesModal({ bot, workspace, menu, on_open, command }: Props) {
const { pageProps } = useContext(AppContext);
const [open, setOpen] = useState(false);
useOpenOnCommand({ command, on_fire: () => setOpen(true) });
const [search, setSearch] = useState("");
const query = useDebouncedValue({ value: search.trim() });
const [busy_id, setBusyId] = useState<number>();
@@ -1,4 +1,5 @@
import { useContext, useEffect, useState } from "react";
import useOpenOnCommand from "@/src/hooks/use-open-on-command";
import Modal from "@moduletrace/twui/elements/Modal";
import H2 from "@moduletrace/twui/layout/H2";
import Row from "@moduletrace/twui/layout/Row";
@@ -37,6 +38,8 @@ type Props = {
bot: BotWithLastMessage;
workspace?: BUN_SQLITE_COBBLE_WORKSPACES | null;
on_open?: () => void;
/** The composer command that opens this modal (`/hooks`). */
command?: string;
};
/**
@@ -47,9 +50,11 @@ type Props = {
* their own; bots propose new hooks and changes from the chat
* (`propose_hook`), which the user confirms there.
*/
export default function BotHooksModal({ bot, workspace, on_open }: Props) {
export default function BotHooksModal({ bot, workspace, on_open, command }: Props) {
const { pageProps } = useContext(AppContext);
const [open, set_open] = useState(false);
useOpenOnCommand({ command, on_fire: () => set_open(true) });
const [view, set_view] = useState<View>();
const [opened, set_opened] = useState<BotHookWithNames>();
const [busy, set_busy] = useState(false);
@@ -1,4 +1,5 @@
import { useContext, useEffect, useState } from "react";
import useOpenOnCommand from "@/src/hooks/use-open-on-command";
import Modal from "@moduletrace/twui/elements/Modal";
import H2 from "@moduletrace/twui/layout/H2";
import Span from "@moduletrace/twui/layout/Span";
@@ -41,6 +42,8 @@ type Props = {
*/
meta_text?: string;
onSaved: (harnesses: HarnessOverview[]) => void;
/** The composer command that opens this modal (`/models`). */
command?: string;
};
/**
@@ -63,9 +66,12 @@ export default function BotModelsModal({
on_open,
meta_text,
onSaved,
command,
}: Props) {
const { pageProps } = useContext(AppContext);
const [open, setOpen] = useState(false);
useOpenOnCommand({ command, on_fire: () => setOpen(true) });
/**
* The pointer or focus reached the icon: start loading before the click.
*/
@@ -1,4 +1,5 @@
import { useEffect, useState } from "react";
import useOpenOnCommand from "@/src/hooks/use-open-on-command";
import Modal from "@moduletrace/twui/elements/Modal";
import H2 from "@moduletrace/twui/layout/H2";
import Row from "@moduletrace/twui/layout/Row";
@@ -28,6 +29,8 @@ type Props = {
*/
menu?: boolean;
on_open?: () => void;
/** The composer command that opens this modal (`/routines`). */
command?: string;
};
/**
@@ -37,8 +40,10 @@ type Props = {
* page's props stay small. The user pauses, resumes, edits, hands over
* and deletes their own; the bot makes them when asked in chat.
*/
export default function BotRoutinesModal({ bot, workspace, menu, on_open }: Props) {
export default function BotRoutinesModal({ bot, workspace, menu, on_open, command }: Props) {
const [open, set_open] = useState(false);
useOpenOnCommand({ command, on_fire: () => set_open(true) });
const [editing, set_editing] = useState<CronJobWithNames>();
const [handing, set_handing] = useState<CronJobWithNames>();
const [busy, set_busy] = useState(false);
@@ -16,6 +16,7 @@ import TaskListItem from "@/src/components/general/task-list-item";
import { AppContext } from "@/src/pages/__root";
import canManageCrew from "@/src/utils/rbac/can-manage-crew";
import useOpenOnCommand from "@/src/hooks/use-open-on-command";
import useBotTasks from "../(hooks)/use-bot-tasks";
import HeaderMenuItem from "./header-menu-item";
@@ -27,6 +28,11 @@ type Props = {
*/
menu?: boolean;
on_open?: () => void;
/**
* The composer command that opens this modal (`/tasks`): only the
* instance named by the header menu listens.
*/
command?: string;
};
/**
@@ -36,9 +42,11 @@ type Props = {
* and deletes; a card opens the task in a modal of its own with everything
* about it.
*/
export default function BotTasksModal({ bot, workspace, menu, on_open }: Props) {
export default function BotTasksModal({ bot, workspace, menu, on_open, command }: Props) {
const { pageProps } = useContext(AppContext);
const [open, setOpen] = useState(false);
useOpenOnCommand({ command, on_fire: () => setOpen(true) });
const [adding, set_adding] = useState(false);
const [open_task, set_open_task] = useState<TaskWithNames | null>(null);
const [busy, set_busy] = useState(false);
@@ -1,4 +1,5 @@
import { useEffect, useState } from "react";
import useOpenOnCommand from "@/src/hooks/use-open-on-command";
import Modal from "@moduletrace/twui/elements/Modal";
import Loading from "@moduletrace/twui/elements/Loading";
import H2 from "@moduletrace/twui/layout/H2";
@@ -15,6 +16,8 @@ type Props = {
bot: BotWithLastMessage;
workspace: BUN_SQLITE_COBBLE_WORKSPACES;
on_open?: () => void;
/** The composer command that opens this modal (`/instructions`). */
command?: string;
};
/**
@@ -23,8 +26,10 @@ type Props = {
* here (crew managers). Both load when it opens, so it shows the bot's
* own latest edits.
*/
export default function BotWorkspaceInstructionsModal({ bot, workspace, on_open }: Props) {
export default function BotWorkspaceInstructionsModal({ bot, workspace, on_open, command }: Props) {
const [open, setOpen] = useState(false);
useOpenOnCommand({ command, on_fire: () => setOpen(true) });
const name = bot.name || "This bot";
const place = workspace.name || "this workspace";
const { instructions, error } = useWorkspaceBotInstructions({
@@ -19,6 +19,12 @@ import type { ComposerCommand } from "../(data)/composer-commands";
import { CrewBotsContext } from "../(data)/crew-bots-context";
import { CrewWorkspacesContext } from "../(data)/crew-workspaces-context";
import postSessionApi from "@/src/functions/frontend/post-session-api";
import { AppContext } from "@/src/pages/__root";
import dispatchComposerCommand from "@/src/utils/composer-command-event";
import requestBotPanel from "@/src/utils/bot-panel-open-event";
import copyConversation from "../(functions)/copy-conversation";
import visibleComposerCommands from "../(utils)/visible-composer-commands";
import { StopBotContext } from "../(data)/stop-bot-context";
import sendBotMessage from "../(functions)/send-bot-message";
import transcribeVoice from "../(functions)/transcribe-voice";
import useComposerAttachments from "../(hooks)/use-composer-attachments";
@@ -161,12 +167,22 @@ export default function Composer({
const online = useOnlineStatus();
const bots = useContext(CrewBotsContext);
const workspaces = useContext(CrewWorkspacesContext);
const { pageProps } = useContext(AppContext);
const { stop, can_stop } = useContext(StopBotContext);
const send_ref = useRef<() => void>(() => {});
/**
* The slash commands the text is asking for, the one highlighted, and
* a command still on its way (`/continue` writes a summary).
* The slash commands the text is asking for, from the ones this user
* gets here, the one highlighted, and a command still on its way
* (`/continue` writes a summary).
*/
const commands = composerCommandMatches({ text });
const commands = composerCommandMatches({
text,
commands: visibleComposerCommands({
user_types: pageProps?.user_types,
bot_kind: bot.kind,
workspace_id,
}),
});
const [command_index, set_command_index] = useState(0);
const [command_busy, set_command_busy] = useState(false);
@@ -380,15 +396,77 @@ export default function Composer({
}
/**
* `/new`, `/continue` and `/clear` act on the conversation's session
* rather than being sent, and the page lands on the session they
* leave. `/clear` destroys messages, so it asks first. A failure puts
* the command back in the input with the reason under it (a session
* with a run in progress can't be deleted).
* A command acts on the page rather than being sent: the session trio
* posts and lands on the session it leaves (`/clear` destroys messages,
* so it asks first); the modal commands open what the header menu's
* rows open; `/copy` puts the session on the clipboard and `/stop`
* pulls the bot's plug; `/panel` slides the bot panel in; `/settings`
* goes to the settings page. A failure puts the command back in the
* input with the reason under it (a session with a run in progress
* can't be deleted, a bot with nothing running has nothing to stop).
*/
async function runCommand({ command }: { command: ComposerCommand }) {
if (sending.current) return;
setError(undefined);
const lost_text = text.trim();
const restore = () => {
if (!latest_text.current.trim()) {
setText(lost_text);
input.setMarkdown({ markdown: lost_text });
}
};
// Nothing to pull the plug on: say so and leave the command in the
// input (this is before the clear, so there is nothing to restore).
if (command.action == "stop" && !can_stop) {
setError(
`Nothing of ${bot.name || "the bot"}'s is running for you.`,
);
return;
}
if (command.action != "session") {
setText("");
history.reset();
input.clear();
switch (command.action) {
case "modal":
dispatchComposerCommand({ name: command.name });
return;
case "panel":
requestBotPanel();
return;
case "link":
if (command.href) {
window.location.assign(
command.href({ bot_id: Number(bot.id) }),
);
}
return;
case "copy": {
const failure = await copyConversation({
bot_id: Number(bot.id),
workspace_id,
});
if (failure) {
setError(failure);
restore();
}
return;
}
case "stop":
void stop();
return;
}
}
if (command.name == "clear") {
if (!session_id) {
setError("The session is still loading. Try again in a moment.");
@@ -406,21 +484,13 @@ export default function Composer({
sending.current = true;
set_command_busy(true);
setError(undefined);
const lost_text = text.trim();
setText("");
history.reset();
input.clear();
const res = await postSessionApi({
path:
command.name == "new"
? "new-session"
: command.name == "continue"
? "continue-session"
: "delete-session",
path: command.path || "new-session",
body:
command.name == "clear"
? { session_id }
@@ -437,11 +507,7 @@ export default function Composer({
sending.current = false;
set_command_busy(false);
setError(res?.msg || "That didn't work.");
if (!latest_text.current.trim()) {
setText(lost_text);
input.setMarkdown({ markdown: lost_text });
}
restore();
}
/**
@@ -120,6 +120,7 @@ export default function ConversationHeaderMenu({
<Stack className="w-full gap-0! items-stretch">
<BotSessionsModal
bot={bot}
command="sessions"
workspace_id={workspace?.id || null}
has_other_unread={has_other_unread}
target={
@@ -165,24 +166,28 @@ export default function ConversationHeaderMenu({
menu
bot={bot}
workspace={workspace}
command="files"
on_open={on_open}
/>
<BotTasksModal
menu
bot={bot}
workspace={workspace}
command="tasks"
on_open={on_open}
/>
<BotRoutinesModal
menu
bot={bot}
workspace={workspace}
command="routines"
on_open={on_open}
/>
{can_make_hooks ? (
<BotHooksModal
bot={bot}
workspace={workspace}
command="hooks"
on_open={on_open}
/>
) : null}
@@ -195,6 +200,7 @@ export default function ConversationHeaderMenu({
: null
}
menu_hint={computer_name}
command="computers"
on_open={on_open}
/>
<BotModelsModal
@@ -203,6 +209,7 @@ export default function ConversationHeaderMenu({
bot={bot}
workspace={workspace}
menu_hint={model_name}
command="models"
on_open={on_open}
onSaved={on_model_saved}
/>
@@ -210,6 +217,7 @@ export default function ConversationHeaderMenu({
<BotWorkspaceInstructionsModal
bot={bot}
workspace={workspace}
command="instructions"
on_open={on_open}
/>
) : null}
@@ -1,9 +1,7 @@
import { useEffect, useRef, useState } from "react";
import { Check, ClipboardCopy } from "lucide-react";
import { AppData } from "@/src/data/app-data";
import conversationMarkdown from "@/src/utils/conversation-markdown";
import copyPendingText from "@/src/utils/copy-pending-text";
import fetchConversationExport from "../(functions)/fetch-conversation-export";
import copyConversation from "../(functions)/copy-conversation";
import HeaderMenuItem from "./header-menu-item";
type Props = {
@@ -17,8 +15,8 @@ type Props = {
/**
* The header menu's "Copy chat": puts the session on screen on the
* clipboard as one markdown document (`conversationMarkdown`). The row shows a check for a moment, then the
* menu closes.
* clipboard as one markdown document (`copyConversation`). The row shows a
* check for a moment, then the menu closes.
*/
export default function CopyChatMenuItem({ bot_id, workspace_id, on_open }: Props) {
const [loading, setLoading] = useState(false);
@@ -34,33 +32,20 @@ export default function CopyChatMenuItem({ bot_id, workspace_id, on_open }: Prop
const copy = async () => {
setLoading(true);
const markdown = fetchConversationExport({ bot_id, workspace_id }).then((res) => {
if (!res?.success || !res.singleRes) {
throw new Error(res?.msg || "Couldn't load the chat.");
}
const failure = await copyConversation({ bot_id, workspace_id });
return conversationMarkdown({ conversation: res.singleRes, now: Date.now() });
});
setLoading(false);
try {
const worked = await copyPendingText({ text: markdown });
setLoading(false);
if (!worked) {
window.alert("Couldn't copy the chat to the clipboard.");
return;
}
setCopied(true);
timeout.current = setTimeout(() => {
setCopied(false);
on_open?.();
}, AppData.CopyConfirmationMs);
} catch (error: unknown) {
setLoading(false);
window.alert(error instanceof Error ? error.message : "Couldn't copy the chat.");
if (failure) {
window.alert(failure);
return;
}
setCopied(true);
timeout.current = setTimeout(() => {
setCopied(false);
on_open?.();
}, AppData.CopyConfirmationMs);
};
return (
@@ -10,7 +10,9 @@ import { BotMessageActionsContext } from "../(data)/message-actions-context";
* (it never sends on its own). Nothing shows once the mode is off.
*/
export default function PlanModeOffButton() {
const { plan_mode, onTurnOffPlanMode } = useContext(BotMessageActionsContext);
const { plan_mode, onTurnOffPlanMode } = useContext(
BotMessageActionsContext,
);
if (!plan_mode) return null;
@@ -21,8 +23,9 @@ export default function PlanModeOffButton() {
title="Turn Plan mode off: the next message can write, run and change things"
beforeIcon={<CircleOff size={14} aria-hidden />}
onClick={onTurnOffPlanMode}
variant="outlined"
>
Turn Plan mode off
</Button>
);
}
}
@@ -1,20 +1,49 @@
import { describe, expect, test } from "bun:test";
import composerCommandMatches from "./composer-command-matches";
import { ComposerCommands, type ComposerCommand } from "../(data)/composer-commands";
const names = ({ text }: { text: string }) =>
composerCommandMatches({ text }).map((command) => command.name);
const names = ({
text,
commands,
}: {
text: string;
commands?: ComposerCommand[];
}) => composerCommandMatches({ text, commands }).map((command) => command.name);
describe("composerCommandMatches", () => {
test("a lone slash offers every command", () => {
expect(names({ text: "/" })).toEqual(["new", "continue", "clear"]);
test("a lone slash offers every command, in the registry's order", () => {
expect(names({ text: "/" })).toEqual(
ComposerCommands.map((command) => command.name),
);
});
test("narrows by the letters typed", () => {
expect(names({ text: "/c" })).toEqual(["continue", "clear"]);
expect(names({ text: "/c" })).toEqual([
"continue",
"clear",
"computers",
"copy",
]);
expect(names({ text: "/s" })).toEqual(["sessions", "stop", "settings"]);
expect(names({ text: "/ne" })).toEqual(["new"]);
expect(names({ text: "/new" })).toEqual(["new"]);
});
test("only the commands the caller says this user gets", () => {
const session_trio = ComposerCommands.slice(0, 3);
expect(names({ text: "/", commands: session_trio })).toEqual([
"new",
"continue",
"clear",
]);
expect(names({ text: "/c", commands: session_trio })).toEqual([
"continue",
"clear",
]);
expect(names({ text: "/hooks", commands: session_trio })).toEqual([]);
});
test("ignores the case and the space around it", () => {
expect(names({ text: " /NEW " })).toEqual(["new"]);
});
@@ -26,4 +55,4 @@ describe("composerCommandMatches", () => {
expect(names({ text: "message" })).toEqual([]);
expect(names({ text: "" })).toEqual([]);
});
});
});
@@ -1,17 +1,23 @@
import { ComposerCommands, type ComposerCommand } from "../(data)/composer-commands";
/**
* The slash commands the composer's text is asking for: all of them while
* it is just `/`, then those the letters typed so far begin. Anything else
* (`/etc/hosts`, a command followed by more words) is an ordinary message
* and matches none.
* The slash commands the composer's text is asking for, from the list the
* caller says this user gets: all of them while it is just `/`, then those
* the letters typed so far begin. Anything else (`/etc/hosts`, a command
* followed by more words) is an ordinary message and matches none.
*/
export default function composerCommandMatches({ text }: { text: string }): ComposerCommand[] {
export default function composerCommandMatches({
text,
commands = ComposerCommands,
}: {
text: string;
commands?: ComposerCommand[];
}): ComposerCommand[] {
const match = /^\/([a-z]*)$/i.exec(text.trim());
if (!match) return [];
const typed = (match[1] ?? "").toLowerCase();
return ComposerCommands.filter((command) => command.name.startsWith(typed));
}
return commands.filter((command) => command.name.startsWith(typed));
}
@@ -0,0 +1,144 @@
import { describe, expect, test } from "bun:test";
import visibleComposerCommands from "./visible-composer-commands";
import type { BUN_SQLITE_COBBLE_USER_TYPES } from "@/db/types/db";
const as = (...user_types: string[]) =>
user_types.map((user_type) => ({ user_type })) as BUN_SQLITE_COBBLE_USER_TYPES[];
const names = (params: Parameters<typeof visibleComposerCommands>[0]) =>
visibleComposerCommands(params).map((command) => command.name);
const held = ({
params,
name,
}: {
params: Parameters<typeof visibleComposerCommands>[0];
name: string;
}) => names(params).includes(name);
describe("visibleComposerCommands", () => {
test("the session trio and the plain views are for everyone", () => {
const member = {
user_types: as("member"),
bot_kind: "worker" as const,
};
for (const name of [
"new",
"continue",
"clear",
"sessions",
"files",
"tasks",
"routines",
"computers",
"models",
"panel",
"copy",
"stop",
]) {
expect(held({ params: member, name })).toBe(true);
}
});
test("a read-only user does not get the hooks that wake a bot", () => {
expect(
held({
params: {
user_types: as("read_only"),
bot_kind: "worker",
},
name: "hooks",
}),
).toBe(false);
expect(
held({
params: { user_types: as("member"), bot_kind: "worker" },
name: "hooks",
}),
).toBe(true);
});
test("instructions need a workspace and a crew manager", () => {
expect(
held({
params: {
user_types: as("member"),
bot_kind: "worker",
workspace_id: 4,
},
name: "instructions",
}),
).toBe(false);
expect(
held({
params: {
user_types: as("admin"),
bot_kind: "worker",
workspace_id: null,
},
name: "instructions",
}),
).toBe(false);
expect(
held({
params: {
user_types: as("admin"),
bot_kind: "worker",
workspace_id: 4,
},
name: "instructions",
}),
).toBe(true);
});
test("a member gets no settings on either kind of bot", () => {
expect(
held({
params: { user_types: as("member"), bot_kind: "worker" },
name: "settings",
}),
).toBe(false);
expect(
held({
params: { user_types: as("member"), bot_kind: "coordinator" },
name: "settings",
}),
).toBe(false);
});
test("the coordinator's settings follow the menu: pass-through only", () => {
expect(
held({
params: { user_types: as("admin"), bot_kind: "coordinator" },
name: "settings",
}),
).toBe(false);
expect(
held({
params: {
user_types: as("super_admin"),
bot_kind: "coordinator",
},
name: "settings",
}),
).toBe(true);
});
test("a worker's settings are for crew managers", () => {
expect(
held({
params: { user_types: as("admin"), bot_kind: "worker" },
name: "settings",
}),
).toBe(true);
});
test("no user types at all is treated as a member", () => {
const listed = names({ user_types: null, bot_kind: "worker" });
expect(listed).not.toContain("settings");
expect(listed).not.toContain("instructions");
expect(listed).toContain("hooks");
});
});
@@ -0,0 +1,39 @@
import type { BUN_SQLITE_COBBLE_USER_TYPES } from "@/db/types/db";
import { ComposerCommands, type ComposerCommand } from "../(data)/composer-commands";
import canManageCrew from "@/src/utils/rbac/can-manage-crew";
import isPassThroughUser from "@/src/utils/rbac/is-pass-through-user";
import isReadOnlyUser from "@/src/utils/rbac/is-read-only-user";
type Params = {
user_types?: BUN_SQLITE_COBBLE_USER_TYPES[] | null;
bot_kind?: string | null;
workspace_id?: number | null;
};
/**
* The commands this user gets in this conversation, with exactly the gates
* the header menu puts on its rows: hooks start work, so a read-only user
* doesn't get them; instructions are per workspace and crew managers only;
* settings follow the menu (the coordinator's page only for pass-through
* actors, a worker's for crew managers).
*/
export default function visibleComposerCommands({
user_types,
bot_kind,
workspace_id,
}: Params): ComposerCommand[] {
const can_make_hooks = !isReadOnlyUser({ user_types });
const can_edit_here = Boolean(workspace_id && canManageCrew({ user_types }));
const can_open_settings =
bot_kind == "coordinator"
? isPassThroughUser({ user_types })
: canManageCrew({ user_types });
return ComposerCommands.filter((command) => {
if (command.name == "hooks") return can_make_hooks;
if (command.name == "instructions") return can_edit_here;
if (command.name == "settings") return can_open_settings;
return true;
});
}
+15
View File
@@ -0,0 +1,15 @@
export const ComposerCommandEvent = "cobble:composer-command";
/**
* Asks the page to do what a composer command names (open one of the header
* menu's modals): the composer sends it, and the mounted component listening
* for its own name answers. Like the bot panel's open event, a page without
* a listener simply ignores it.
*/
export default function dispatchComposerCommand({ name }: { name: string }) {
if (typeof window == "undefined") return;
window.dispatchEvent(
new CustomEvent(ComposerCommandEvent, { detail: name }),
);
}
+9 -1
View File
@@ -6,7 +6,15 @@ import type { TaskWithNames } from "@/src/types";
*/
export default function compareTasks(a: TaskWithNames, b: TaskWithNames) {
const rank = (task: TaskWithNames) =>
task.status == "blocked" ? 0 : task.status == "doing" ? 1 : task.status == "todo" ? 2 : 3;
task.status == "blocked"
? 0
: task.status == "doing"
? 1
: task.status == "todo"
? 2
: task.status == "paused"
? 3
: 4;
const diff = rank(a) - rank(b);
return diff != 0 ? diff : Number(b.updated_at || b.id || 0) - Number(a.updated_at || a.id || 0);