Keep a plan's steps on the plan, and end Plan mode when it starts

A step run that neither finished its step, asked the user, changed the plan nor handed work on is sent back, and a blocked step or one that queued work stops the plan instead of advancing over it. Approving or resuming a plan now turns Plan mode off for that conversation, since its steps write. The plan bar's In progress pill is gray outlined.
This commit is contained in:
2026-11-21 12:50:13 +01:00
parent ac28a5211f
commit ed67d6919c
14 changed files with 227 additions and 13 deletions
+1 -1
View File
@@ -102,7 +102,7 @@ Enables SQLite foreign keys (`enableForeignKeys`), `bunextInit()`, `ensureDocker
- **Copy chat** (header menu): the active session (the one on screen) as one markdown document (`api/admin/bots/conversation-export` -> `conversationMarkdown`, refs as names, message headings demoted). The clipboard write starts on the click with a pending `ClipboardItem` (`copyPendingText`), since Safari drops the gesture after a fetch. A message's Details modal has its own **Copy report** (`messageDetailsMarkdown`, the same pending write): that message's whole details, listing up to `AppData.MessageDetailsCopyMaxCalls` calls and failures (the route's `full=1`) instead of the modal's first `MessageDetailsMaxCalls`.
- **Asking before acting:** `ask_user` (`QuestionsNote`) puts up to `AppData.BotQuestionMaxQuestions` multiple-choice questions (`single` = radios, `multiple` = checkboxes, optional typed "Other") on one card, once per run (a second call returns the card already up instead of throwing: a refused re-ask read as a failed closing turn and the whole answer was thrown away) -> `bot_questions` -> `[question:ID]` (its card in the message, not a chip); the message needs the user. Answers are checked against the questions (`checkBotQuestionAnswers`) and stored, then sent as the user's chat message (`botQuestionAnswersText`); Skip says so. **The card belongs to the conversation it was asked in:** the answer and skip routes post that message into the question's own session (`postBotQuestionAnswers`), never the page's bot (a card answered on the requester's page woke the wrong bot), and `stripQuestionRefs` takes `[question:ID]` out of text copied into another bot's conversation (`relayJobToRequester`, a crew request's outcome, an install request's answer), which would otherwise show the same card in two sessions, answered in one and left waiting in the other. Replies and user-started tasks only: never routines, hook calls or a crew request's run (no one sees those). The reply's `ask_user`/`suggest_next_steps` and `QuestionsNote` are gated on `attended` (`isHiddenSession`), and a task run's on `can_ask` (`isHiddenSession` checked there too): a question in a hidden session has no card the user would see (one reached the coordinator as a bare `[question:22]`, its answer never getting back).
- **Suggested next steps:** `suggest_next_steps` puts up to `AppData.BotSuggestionMaxSteps` follow-ups under the answer, once per run (a second call returns the steps already attached instead of throwing) -> `bot_suggestions` -> `[suggestion:ID]` rendered inline as buttons (`BotSuggestionsRef`); clicking one inserts it into the composer (`ComposerHandle.insertText`, never sends) and nothing waits on it, so it's `shown` in `withTakeOverRefs`, never `refs`, and never sets `needs_you`. For when the work is done and the bot offers follow-ups; when the answer decides what it does next, it's `ask_user`. Same runs as `ask_user`. Both are closing tools (`ClosingToolNames`, `src/harness/tools/closing-tool-names.ts`): the turn that writes the answer and puts the card up ends the run, after the usual `review`, because a reply is only the run's **last** message. Without that, a bot answered with the PR links the user asked for, then called `list_tasks` (which `TaskReminderNote` told it to do after answering), and the user was sent the short "still open" line alone.
- **Plans:** work with several pieces that build on each other is written down before it starts, and worked one step per reply, since a bot answering such a request in one message is how a reply turns into a wall of text. `create_plan` (title, goal, 3 to `AppData.BotPlanMaxSteps` steps) -> `bot_plans` (one open plan per conversation, `BotPlanOpenStates`) -> `[plan:ID]` (`BotPlanCard`); nothing of it runs until the user approves it there, and they change the steps first (`BotPlanEditModal` -> `save-plan`), though a step already worked stays at the top with its note (`planStepsRewriteProblem`). Approving queues the first step as an ordinary **reply** job with `params.plan_id`, in the same conversation, so it has the bot's tools, computers, memory and files; the run gets `PlanStepNote` and works that step alone, `complete_plan_step` marks it done with what it produced (the card checks it off, `pushBotPlan` -> `server:bot-plan`), and `continueBotPlan` (from `process-bot-job`, after the notice) queues the next one. It stops on its own when the user is needed (`needs_you`), when the reply handed work to a run (`WorkStartingTools`), or when an unanswered reply already waits in the session, and never counts an approval as a step: `done` is the app's call once no step is pending. A run that is a plan's step can't write or cancel a plan, only work it, change it (`update_plan`) or finish its step. An ordinary reply in a conversation whose plan is open gets `PlanWaitingNote`/`PlanActiveNote`/`PlanPausedNote` instead of plan tools, so a plan is only ever advanced by the app. A **routine** writes its plan with `approve: true` (`ScheduledPlanNote`): nobody is there to approve it, so it starts itself and the run works every step, reporting at the end. Plan tools are not closing tools: the card and one sentence about it are the reply. When a plan is one the work comes back to, the bot saves its steps with `update_memory` (`PlansNote`); a repeating job is a routine instead. **A plan stays one click away however far the thread moves on:** while it is open a bar sits under the conversation header (`SessionPlanBar`: title, status, step x of y) and opens it in a modal (`BotPlanModal`), and every message that belongs to it (the one that wrote it, each step report) carries a Plan chip that opens the same card. The link is `bot_messages.plan_id`, the app's record written when the message is saved (the plan it wrote, or the step it worked), since the job that made it is pruned; a finished plan's bar goes, its chips stay. The history read carries the open plan (`history.plan`), and `server:bot-plan` keeps it current (`useSessionPlan`), so the bar never waits on another read. `bot_plans` is deleted with its session (`deleteBotPlanRows`, from `deleteSessionRows`).
- **Plans:** work with several pieces that build on each other is written down before it starts, and worked one step per reply, since a bot answering such a request in one message is how a reply turns into a wall of text. `create_plan` (title, goal, 3 to `AppData.BotPlanMaxSteps` steps) -> `bot_plans` (one open plan per conversation, `BotPlanOpenStates`) -> `[plan:ID]` (`BotPlanCard`); nothing of it runs until the user approves it there, and they change the steps first (`BotPlanEditModal` -> `save-plan`), though a step already worked stays at the top with its note (`planStepsRewriteProblem`). Approving or picking a paused plan back up ends Plan mode in that conversation (`announcePlanModeOff`): the user asked for the work to start, and its steps write, which the toggle otherwise promises nothing of. Approving queues the first step as an ordinary **reply** job with `params.plan_id`, in the same conversation, so it has the bot's tools, computers, memory and files; the run gets `PlanStepNote` and works that step alone, `complete_plan_step` marks it done with what it produced (the card checks it off, `pushBotPlan` -> `server:bot-plan`), and `continueBotPlan` (from `process-bot-job`, after the notice) queues the next one. A step's reply is held to the step (`planStepReviewNote`): one that neither finished it, asked the user, changed the plan nor handed work on is sent back, and a `blocked` step or a `send_reply` that queued work stops the plan instead of advancing over it (`started_work`). It stops on its own when the user is needed (`needs_you`), when the reply handed work to a run (`WorkStartingTools`), or when an unanswered reply already waits in the session, and never counts an approval as a step: `done` is the app's call once no step is pending. A run that is a plan's step can't write or cancel a plan, only work it, change it (`update_plan`) or finish its step. An ordinary reply in a conversation whose plan is open gets `PlanWaitingNote`/`PlanActiveNote`/`PlanPausedNote` instead of plan tools, so a plan is only ever advanced by the app. A **routine** writes its plan with `approve: true` (`ScheduledPlanNote`): nobody is there to approve it, so it starts itself and the run works every step, reporting at the end. Plan tools are not closing tools: the card and one sentence about it are the reply. When a plan is one the work comes back to, the bot saves its steps with `update_memory` (`PlansNote`); a repeating job is a routine instead. **A plan stays one click away however far the thread moves on:** while it is open a bar sits under the conversation header (`SessionPlanBar`: title, status, step x of y) and opens it in a modal (`BotPlanModal`), and every message that belongs to it (the one that wrote it, each step report) carries a Plan chip that opens the same card. The link is `bot_messages.plan_id`, the app's record written when the message is saved (the plan it wrote, or the step it worked), since the job that made it is pruned; a finished plan's bar goes, its chips stay. The history read carries the open plan (`history.plan`), and `server:bot-plan` keeps it current (`useSessionPlan`), so the bar never waits on another read. `bot_plans` is deleted with its session (`deleteBotPlanRows`, from `deleteSessionRows`).
- **Quoting:** selected text quotes into the composer through `quotableText`, which reads each ref chip as one inline label (`MarkdownLink` wraps chips with `QuoteInlineAttribute`; `Selection.toString()` broke a quote into a paragraph per chip).
- **A user's own long message is cut:** the bubble shows the first twenty lines (`max-h-[25rem]`, the bubble's `leading-5`) with **Read more** under it, and **Show less** puts it back (`use-bubble-clamp.ts` measures the cut text in the browser: `bubbleOverflows`); a pasted prompt should not fill the screen. Only what's shown is cut, so the bot, Copy chat and the export still get every character.
- **Replies/reactions:** `reply_to_message_id` (not an FK); reactions from the fixed `BotMessageReactions`, toggled by `react-message.ts` and the `react_to_message` tool, pushed as `server:bot-reaction`. A reply's history shows the user's own reactions on each bot message in its app record (`botMessagesToHarness`, so `run-bot-reply` loads history with `user_id`), and the chat reply note tells the bot to save lasting preferences they show in its memory of that user; 👎 is in the set for that.
+41
View File
@@ -0,0 +1,41 @@
import { describe, expect, test } from "bun:test";
import planStepReviewNote from "./plan-step-review";
const plan = { id: 3, title: "Open the shop", current_step: 1 };
const note = ({ on_step = true, uses = [], status }: { on_step?: boolean; uses?: { name: string; ok: boolean }[]; status?: "done" | "working" | "blocked" }) =>
planStepReviewNote({ plan, on_step, tool_uses: uses, status });
describe("planStepReviewNote", () => {
test("a reply that did not work its step is sent back to it", () => {
expect(note({ uses: [{ name: "write_file", ok: true }] })).toContain("step 2 of Plan #3");
expect(note({ uses: [{ name: "write_file", ok: true }] })).toContain("complete_plan_step");
});
test("finishing the step passes", () => {
expect(note({ uses: [{ name: "complete_plan_step", ok: true }] })).toBeNull();
});
test("a failed finish does not pass", () => {
expect(note({ uses: [{ name: "complete_plan_step", ok: false }] })).toContain("did not finish it");
});
test("asking, changing the plan or handing work on ends the step honestly", () => {
for (const name of ["ask_user", "update_plan", "start_task", "delegate_task", "ask_bot", "hand_over_task"]) {
expect(note({ uses: [{ name, ok: true }] })).toBeNull();
}
});
test("a reply that says it is blocked or has work coming passes", () => {
expect(note({ status: "blocked" })).toBeNull();
expect(note({ status: "working" })).toBeNull();
});
test("a reply that is not working a plan step is left alone", () => {
expect(note({ on_step: false, uses: [{ name: "write_file", 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();
});
});
+56
View File
@@ -0,0 +1,56 @@
import type { ReplyStatus } from "@/src/dict/reply-status-dict";
import type { HarnessToolUse } from "@/src/harness/types";
import { WorkStartingTools } from "@/src/utils/should-continue-plan";
type PlanStep = {
id: number;
title: string;
current_step: number | null;
};
type Params = {
/**
* The plan the run works, when it was queued for one of its steps.
*/
plan: PlanStep | null;
/**
* The job was queued by the plan (`enqueuePlanStep`), not by a message.
*/
on_step: boolean;
tool_uses: HarnessToolUse[];
status?: ReplyStatus;
};
/**
* The tools that end a step without finishing it, and are meant to: the run
* asks the user, changes the plan, or hands work on whose report comes
* later. A run that did none of these and never called
* `complete_plan_step` did something else entirely (a step of its own, a
* plan written to a file), and the app would otherwise carry the plan on
* past the step it never did.
*/
const EndingTools = ["ask_user", "update_plan", ...WorkStartingTools];
/**
* Checks a plan step's reply before it goes out: the run works one step,
* and must either finish it or say why it can't. Returns a note that sends
* the answer back to the model, or null when the reply ends the step the
* way the plan expects.
*/
export default function planStepReviewNote({ plan, on_step, tool_uses, status }: Params) {
if (!on_step || !plan || plan.current_step == null) return null;
/**
* A reply that started work or says what stopped it already ends the
* step honestly; the plan waits on the user or the run it started.
*/
if (status == "working" || status == "blocked") return null;
const ended = tool_uses.some((use) => use.ok && (use.name == "complete_plan_step" || EndingTools.includes(use.name)));
if (ended) return null;
const step = plan.current_step + 1;
return `This reply works step ${step} of Plan #${plan.id} ("${plan.title}") and did not finish it. Do that step, not another: finish it with complete_plan_step and what it produced, then report it in two or three sentences. If it needs the user, ask with ask_user. 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.`;
}
+1
View File
@@ -336,6 +336,7 @@ export default async function processBotJob({
plan_id: outcome.plan_id,
session_id: Number(completion.message?.session_id || job.session_id),
needs_you: Boolean(outcome.needs_you),
started_work: Boolean(outcome.started_work),
tool_names: (outcome.tool_log || []).map((use) => use.name),
}).then((job_id) => {
if (job_id) wakeBotsQueue();
+32 -9
View File
@@ -75,6 +75,7 @@ import withTakeOverRefs from "./with-take-over-refs";
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 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";
@@ -90,7 +91,8 @@ import { botPlanRefIdFromText } from "@/src/utils/bot-plan-ref";
import grabBotPlan from "@/src/functions/backend/db/bot-plans/grab-bot-plan";
import toBotPlanView from "@/src/functions/backend/db/bot-plans/to-bot-plan-view";
import type { BotMessageWithAttachments } from "@/src/types";
import type { HarnessMessage } from "@/src/harness/types";
import type { HarnessMessage, HarnessToolUse } from "@/src/harness/types";
import type { ReplyStatus } from "@/src/dict/reply-status-dict";
import type { BotJobContext, BotJobOutcome } from "./types";
import computerRunDirs from "@/src/utils/computer-work-dirs";
@@ -588,6 +590,18 @@ export default async function runBotReply({
];
try {
/**
* The app's record of the answer, then the plan's own check: a run
* queued for a step must finish that step or say why it can't, or
* the app would carry the plan on past work nobody did.
*/
const review_answer = ({ text, tool_uses, status }: { text: string; tool_uses: HarnessToolUse[]; status?: ReplyStatus }) =>
reviewRunAnswer({ bot_id: bot.id!, user_id, session_id, scopes, job_id: job.id })({ text, tool_uses, status }).then((note) => {
if (note) return note;
return planStepReviewNote({ plan, on_step: on_plan_step, tool_uses, status });
});
const result = await runTextLoop({
system: [
prompt,
@@ -660,7 +674,7 @@ export default async function runBotReply({
* Files, tasks and work the answer names are checked against
* the app's record before it goes out.
*/
review: reviewRunAnswer({ bot_id: bot.id!, user_id, session_id, scopes, job_id: job.id }),
review: review_answer,
/**
* The message goes out only through `send_reply`: text a turn
* writes without it is a draft, so no answer can promise work
@@ -689,14 +703,14 @@ export default async function runBotReply({
throw new BotJobFatalError(unsentAnswerMessage({ note: result.review_note }));
}
const answer = stripAppRecords({ text: result.text }).trim();
const answer_text = stripAppRecords({ text: result.text }).trim();
/**
* Nothing said is nothing to send: an empty message lands in the
* thread as a bubble with no text, and the user has no idea what
* happened. The job fails with why instead, which they do see.
*/
if (!answer && !shown.length && !attachments.length) {
if (!answer_text && !shown.length && !attachments.length) {
await dropUnsentQuestions({ refs: proposals });
for (const queued of queued_jobs) {
@@ -721,12 +735,21 @@ export default async function runBotReply({
await markReplyAnswered({ job_id: job.id, message_id: answering_id });
}
const answer_parts = withTakeOverRefs({
text: answer_text,
refs: [...take_overs, ...proposals, ...plan_refs],
shown,
});
return {
...withTakeOverRefs({
text: answer,
refs: [...take_overs, ...proposals, ...plan_refs],
shown,
}),
...answer_parts,
/**
* A step the run says is blocked stops the plan: carrying on to
* the next step over work that didn't happen is how a plan moved
* on while its reports said something else.
*/
needs_you: answer_parts.needs_you || result.status == "blocked" || undefined,
started_work: result.status == "working" || undefined,
attachments: attachments.length ? attachments : undefined,
tool_log: result.tool_uses,
task_ids,
+6
View File
@@ -87,6 +87,12 @@ export type BotJobOutcome = {
* worked on.
*/
plan_message_id?: number;
/**
* The closing `send_reply` queued a run (`status: "working"`): its report
* is still to come, so the plan waits for it instead of queueing its
* next step (`continueBotPlan`).
*/
started_work?: boolean;
};
export type BotJobRunner = (context: BotJobContext) => Promise<BotJobOutcome>;
@@ -19,6 +19,11 @@ type Params = {
* waits for it instead of talking over it.
*/
tool_names?: string[];
/**
* The reply queued a run (`send_reply` with work), whose report is still
* to come: the plan waits for it rather than working over it.
*/
started_work?: boolean;
};
/**
@@ -31,7 +36,7 @@ type Params = {
* meanwhile, or when the conversation already has a reply waiting (a message
* the user sent mid-step, whose own run picks the plan up from there).
*/
export default async function continueBotPlan({ plan_id, session_id, needs_you, tool_names }: Params) {
export default async function continueBotPlan({ plan_id, session_id, needs_you, tool_names, started_work }: Params) {
const row = await grabBotPlan({ plan_id });
const steps = parseBotPlanSteps({ text: row.steps });
@@ -48,6 +53,7 @@ export default async function continueBotPlan({ plan_id, session_id, needs_you,
status: row.status || "",
needs_you,
tool_names,
started_work,
plan_session_id: row.session_id,
session_id,
has_pending_step: currentPlanStepIndex({ steps }) != null,
@@ -1,6 +1,7 @@
import { useCallback, useEffect, useState } from "react";
import readPlanMode from "@/src/functions/frontend/read-plan-mode";
import rememberPlanMode from "@/src/functions/frontend/remember-plan-mode";
import { PlanModeOffEvent } from "@/src/utils/plan-mode-event";
type Params = {
bot_id?: number | string | null;
@@ -36,5 +37,17 @@ export default function usePlanMode({ bot_id, workspace_id }: Params) {
setPlanMode(!plan_mode);
}, [plan_mode, setPlanMode]);
/**
* Approving (or resuming) a plan ends Plan mode: its steps do the work,
* so the toggle's promise that nothing changes would be false.
*/
useEffect(() => {
const turnOff = () => setPlanMode(false);
window.addEventListener(PlanModeOffEvent, turnOff);
return () => window.removeEventListener(PlanModeOffEvent, turnOff);
}, [setPlanMode]);
return { plan_mode, set_plan_mode: setPlanMode, toggle_plan_mode: togglePlanMode };
}
@@ -7,6 +7,7 @@ import { BotPlanStates, type BotPlanState } from "@/src/dict/bot-plan-dict";
import setBotPlanState from "../(functions)/set-bot-plan-state";
import useBotPlan from "../(hooks)/use-bot-plan";
import botPlanStatusLine from "../(utils)/bot-plan-status-line";
import announcePlanModeOff from "@/src/utils/plan-mode-event";
import BotPlanEditModal from "./bot-plan-edit-modal";
import BotPlanStepRow from "./bot-plan-step-row";
@@ -59,6 +60,13 @@ export default function BotPlanCard({ plan_id }: Props) {
return;
}
/**
* Starting or resuming the plan starts its work, which writes:
* Plan mode would say nothing changes, so it ends here rather than
* sitting on while the steps run.
*/
if (status == "active") announcePlanModeOff();
setView(res.singleRes);
};
@@ -24,7 +24,8 @@ export default function SessionPlanBar({ plan }: Props) {
if (!plan || !BotPlanOpenStates.includes(plan.status)) return null;
const status = BotPlanStates.find((state) => state.value == plan.status)?.title || plan.status;
const color = plan.status == "active" ? "success" : plan.status == "paused" ? "warning" : "gray";
const color = plan.status == "paused" ? "warning" : "gray";
const variant = plan.status == "active" ? "outlined" : undefined;
const step = Math.min(plan.finished_steps + 1, plan.total_steps);
const progress =
plan.status == "planned"
@@ -50,7 +51,7 @@ export default function SessionPlanBar({ plan }: Props) {
<Span className="min-w-0 grow truncate text-[13px] leading-5 font-bold text-ink">
{plan.title || `Plan ${plan.id}`}
</Span>
<Tag color={color} className="shrink-0">
<Tag color={color} variant={variant} className="shrink-0">
{status}
</Tag>
<Span className="shrink-0 text-[12px] leading-4 text-ink-secondary whitespace-nowrap">
+22
View File
@@ -0,0 +1,22 @@
import { describe, expect, test } from "bun:test";
import announcePlanModeOff, { PlanModeOffEvent } from "./plan-mode-event";
describe("announcePlanModeOff", () => {
test("announces Plan mode off on the window it is given", () => {
const target = new EventTarget();
let heard = 0;
target.addEventListener(PlanModeOffEvent, () => {
heard += 1;
});
announcePlanModeOff({ target });
expect(heard).toBe(1);
expect(PlanModeOffEvent).toBe("cobble:plan-mode-off");
});
test("does nothing when there is no window", () => {
expect(() => announcePlanModeOff({ target: null })).not.toThrow();
});
});
+24
View File
@@ -0,0 +1,24 @@
/**
* The event the conversation listens for when Plan mode should go off
* without the user pressing Tab or the composer button: a plan they
* approved is about to work, and its steps write.
*/
export const PlanModeOffEvent = "cobble:plan-mode-off";
type Params = {
/**
* Where to announce it: the page's window, or a target in a test.
*/
target?: EventTarget | null;
};
/**
* Tells the open conversation that Plan mode is over, so its header tag,
* notice and next message all follow. Approving a plan is the user asking
* for the work to start, which Plan mode would otherwise contradict.
*/
export default function announcePlanModeOff({
target = typeof window == "undefined" ? null : window,
}: Params = {}) {
target?.dispatchEvent(new Event(PlanModeOffEvent));
}
+4
View File
@@ -33,6 +33,10 @@ describe("shouldContinuePlan", () => {
}
});
test("stops when send_reply queued a run of its own", () => {
expect(shouldContinuePlan({ ...go, started_work: true })).toBe(false);
});
test("stops when the plan was paused or ended mid-step", () => {
expect(shouldContinuePlan({ ...go, status: "paused" })).toBe(false);
expect(shouldContinuePlan({ ...go, status: "cancelled" })).toBe(false);
+9
View File
@@ -18,6 +18,12 @@ type Params = {
* for it instead of talking over it.
*/
tool_names?: string[];
/**
* The closing `send_reply` queued a run (`status: "working"`), whose
* report comes later: the plan waits for it just as it does for a
* `start_task`.
*/
started_work?: boolean;
/**
* The plan's session and the finished step's: a step job is queued for
* the conversation it belongs to, never another one's.
@@ -51,6 +57,7 @@ export default function shouldContinuePlan({
status,
needs_you,
tool_names,
started_work,
plan_session_id,
session_id,
has_pending_step,
@@ -58,6 +65,8 @@ export default function shouldContinuePlan({
}: Params) {
if (needs_you) return false;
if (started_work) return false;
if ((tool_names || []).some((name) => WorkStartingTools.includes(name))) return false;
if (Number(plan_session_id) != Number(session_id)) return false;