Keep a plan reachable from anywhere in its thread

A plan bar under the conversation header shows the open plan (title, status, step x of y) and opens it in a modal, and every message that belongs to a plan carries a Plan chip that opens the same card, so a plan is not lost once the thread moves on. The link is bot_messages.plan_id, 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 and its chips stay. The history read carries the open plan and server:bot-plan keeps it current.
This commit is contained in:
2026-11-21 10:55:30 +01:00
parent a9b7f7f304
commit f8439f7817
18 changed files with 259 additions and 5 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]` chip opening `BotQuestionCard`; 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. `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 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`).
- **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.
+5
View File
@@ -612,6 +612,11 @@ const schema: BUN_SQLITE_DatabaseSchemaType = {
fieldDescription: `The message this one replies to, quoted above it. Not a foreign key, so deleting the quoted message only drops the quote`,
dataType: "INTEGER",
},
{
fieldName: "plan_id",
fieldDescription: `The plan (\`bot_plans\`) this message belongs to: the one it wrote, or the step of it the run worked. Shown as a chip under the message so the plan can be opened from anywhere in the thread, and kept because a plan outlives the job that made it. Not a foreign key`,
dataType: "INTEGER",
},
{
fieldName: "tool_log",
fieldDescription: `JSON \`[{ name, ok }]\`: every tool call the run behind a bot message made (names only, never arguments), told to the bot with the message in later turns so it can't build on work it never did. Null: not recorded (user messages, interim ones, older messages)`,
+4
View File
@@ -429,6 +429,10 @@ export type BUN_SQLITE_COBBLE_BOT_MESSAGES = {
* The message this one replies to, quoted above it. Not a foreign key, so deleting the quoted message only drops the quote
*/
reply_to_message_id?: number | "";
/**
* The plan (`bot_plans`) this message belongs to: the one it wrote, or the step of it the run worked. Shown as a chip under the message so the plan can be opened from anywhere in the thread, and kept because a plan outlives the job that made it. Not a foreign key
*/
plan_id?: number | "";
/**
* JSON `[{ name, ok }]`: every tool call the run behind a bot message made (names only, never arguments), told to the bot with the message in later turns so it can't build on work it never did. Null: not recorded (user messages, interim ones, older messages)
*/
+1
View File
@@ -319,6 +319,7 @@ export default async function processBotJob({
attachments: outcome.attachments,
tool_log: outcome.tool_log,
task_ids: outcome.task_ids,
plan_id: outcome.plan_message_id,
exhausted: outcome.exhausted,
});
+13 -1
View File
@@ -86,6 +86,7 @@ import askUserTool from "@/src/harness/tools/bot/questions/ask-user-tool";
import suggestNextStepsTool from "@/src/harness/tools/bot/suggestions/suggest-next-steps-tool";
import grabBotPlanTools from "@/src/harness/tools/bot/plans/grab-bot-plan-tools";
import grabSessionPlan from "@/src/functions/backend/db/bot-plans/grab-session-plan";
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";
@@ -300,6 +301,11 @@ export default async function runBotReply({
* to approve it, so the reply needs them.
*/
const plan_refs: string[] = [];
/**
* The plan this reply belongs to, written or changed in it: its message
* carries a chip that opens the plan from anywhere in the thread.
*/
let message_plan_id: number | undefined;
/**
* Files the bot wrote and asked to send with its reply.
*/
@@ -555,7 +561,12 @@ export default async function runBotReply({
* it goes with the refs that set `needs_you`: the
* bot is waiting on them, not on itself.
*/
onPlan: ({ ref, waiting }) => (waiting ? plan_refs.push(ref) : shown.push(ref)),
onPlan: ({ ref, waiting }) => {
message_plan_id = botPlanRefIdFromText({ text: ref }) || message_plan_id;
if (waiting) plan_refs.push(ref);
else shown.push(ref);
},
})
: []),
...(has_past_sessions
@@ -720,6 +731,7 @@ export default async function runBotReply({
tool_log: result.tool_uses,
task_ids,
plan_id: on_plan_step ? plan?.id : undefined,
plan_message_id: message_plan_id ?? (on_plan_step ? 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
+7
View File
@@ -80,6 +80,13 @@ export type BotJobOutcome = {
* run asked for the user or started work that runs on its own.
*/
plan_id?: number;
/**
* The plan the reply's message belongs to: the step it worked, or the
* one it wrote. Kept on the message as a chip (`bot_messages.plan_id`),
* separately from `plan_id`, since a plan that is only written is not
* worked on.
*/
plan_message_id?: number;
};
export type BotJobRunner = (context: BotJobContext) => Promise<BotJobOutcome>;
@@ -1,9 +1,11 @@
import { AppData } from "@/src/data/app-data";
import type { ConversationHistory } from "@/src/types";
import type { BotPlanView, ConversationHistory } from "@/src/types";
import grabActiveBotTask from "../bots/grab-active-bot-task";
import grabBotMessages from "../bots/grab-bot-messages";
import grabSessionReplyStep from "../bots-queue/grab-session-reply-step";
import grabSessionOpenReplies from "../bots-queue/grab-session-open-replies";
import grabSessionPlan from "../bot-plans/grab-session-plan";
import toBotPlanView from "../bot-plans/to-bot-plan-view";
import ensureBotSession from "./ensure-bot-session";
import grabCarriedToSessionId from "./grab-carried-to-session-id";
import reopenBotSession from "./reopen-bot-session";
@@ -89,7 +91,7 @@ export default async function grabConversationHistory({
session.unread = 0;
}
const [messages, task, step, open_jobs] = await Promise.all([
const [messages, task, step, open_jobs, plan_row] = await Promise.all([
grabBotMessages({
session_id: session.id!,
user_id,
@@ -98,6 +100,7 @@ export default async function grabConversationHistory({
grabActiveBotTask({ bot_id: open_bot_id, session_id: session.id }),
grabSessionReplyStep({ session_id: session.id! }),
grabSessionOpenReplies({ session_id: session.id! }),
grabSessionPlan({ session_id: session.id! }),
]);
const has_more = messages.length > AppData.ConversationFirstMessages;
@@ -109,6 +112,7 @@ export default async function grabConversationHistory({
task,
step,
open_jobs,
plan: plan_row ? (toBotPlanView({ row: plan_row }) as BotPlanView) : null,
moved_to_session_id: carried_to,
};
}
@@ -50,6 +50,12 @@ type Params = {
* The tracker tasks the run worked on, linked under the message.
*/
task_ids?: number[];
/**
* The plan the message belongs to: the one the run wrote, or the step of
* it the run worked (`BotJobOutcome.plan_message_id`), shown as a chip
* under the message.
*/
plan_id?: number;
/**
* The run used every step it was allowed (`BotJobOutcome.exhausted`):
* a handed-over task it left open is blocked by `noteTrackerTask`, since
@@ -79,6 +85,7 @@ export default async function completeBotJob({
attachments,
tool_log,
task_ids = [],
plan_id,
exhausted,
}: Params) {
const job = await grabLockedBotJob({ job_id, worker });
@@ -111,6 +118,7 @@ export default async function completeBotJob({
media_ids: attachments,
tool_log,
task_ids: message_task_ids,
plan_id,
});
if (job.id && inserted?.id) {
@@ -34,6 +34,11 @@ type Params = {
* shown as chips under it.
*/
task_ids?: (number | string | null | undefined)[];
/**
* The plan this message belongs to: the one it wrote, or the step of it
* the run worked, shown as a chip under it.
*/
plan_id?: number | string | null;
/**
* Opens a session the conversation moved into
* (`carryOverBotSession`): the session it carries on from.
@@ -61,6 +66,7 @@ export default async function insertBotMessage({
media_ids = [],
tool_log,
task_ids,
plan_id,
carried_from_session_id,
failed_job_id,
}: Params): Promise<BUN_SQLITE_COBBLE_BOT_MESSAGES> {
@@ -87,6 +93,7 @@ export default async function insertBotMessage({
interim: interim_flag,
tool_log: tool_log_json,
task_ids: task_ids_json,
plan_id: plan_id ? Number(plan_id) : undefined,
carried_from_session_id,
failed_job_id,
},
@@ -131,6 +138,7 @@ export default async function insertBotMessage({
interim: interim_flag,
tool_log: tool_log_json,
task_ids: task_ids_json,
plan_id: plan_id ? Number(plan_id) : undefined,
carried_from_session_id,
failed_job_id,
created_at: now,
@@ -0,0 +1,32 @@
import type { BotPlanChangedData, BotPlanView } from "@/src/types";
import useServerEvent from "@/src/hooks/use-server-event";
import fetchBotPlan from "../(functions)/fetch-bot-plan";
type Params = {
/**
* The conversation on show: a plan only ever shows in its own.
*/
session_id?: number | null;
on_change: (plan: BotPlanView | null) => void;
};
/**
* The plan open in the conversation, for the thread's plan bar: seeded by
* the history's `plan`, then kept current from the app's pushes (written, a
* step done, approved, paused, ended). The bar hides a plan that is no
* longer open, so a finished one is read rather than pushed away.
*/
export default function useSessionPlan({ session_id, on_change }: Params) {
useServerEvent({
event: "server:bot-plan",
onData: (data: BotPlanChangedData) => {
if (!session_id || Number(data?.session_id) != Number(session_id)) return;
void fetchBotPlan({ plan_id: Number(data.plan_id) })
.then((res) => {
if (res.success && res.singleRes) on_change(res.singleRes);
})
.catch(() => null);
},
});
}
@@ -15,6 +15,7 @@ import MessageReactions from "./message-reactions";
import MessageReplyQuote from "./message-reply-quote";
import MessageImages from "./message-images";
import MessageNoToolsChip from "./message-no-tools-chip";
import MessagePlanChip from "./message-plan-chip";
import MessageTaskChips from "./message-task-chips";
import MessageUsageChip from "./message-usage-chip";
import NeedsYouChip from "./needs-you-chip";
@@ -85,6 +86,7 @@ function BotMessageLine({ message, bot_name, at, rerun }: Props) {
</Stack>
<MessageImages message={message} />
<MessageTaskChips tasks={message.tasks} />
{message.plan_id ? <MessagePlanChip plan_id={Number(message.plan_id)} /> : null}
{message.id ? (
<MessageReactions
message_id={message.id}
@@ -0,0 +1,30 @@
import AddModalShell from "@/src/layouts/bots/(partials)/add-modal-shell";
import Stack from "@moduletrace/twui/layout/Stack";
import BotPlanCard from "./bot-plan-card";
type Props = {
plan_id: number;
open: boolean;
onClose: () => void;
};
/**
* A plan opened away from where it was written: the same card the thread
* shows, from the plan bar or a chip under a step's report, so the plan can
* be read and moved on without scrolling back to it.
*/
export default function BotPlanModal({ plan_id, open, onClose }: Props) {
return (
<AddModalShell
open={open}
setOpen={(next) => {
if (!next) onClose();
}}
title="Plan"
>
<Stack className="w-full gap-2! items-stretch">
<BotPlanCard plan_id={plan_id} />
</Stack>
</AddModalShell>
);
}
@@ -0,0 +1,34 @@
import { useState } from "react";
import Button from "@moduletrace/twui/layout/Button";
import Span from "@moduletrace/twui/layout/Span";
import { ListChecks } from "lucide-react";
import BotPlanModal from "./bot-plan-modal";
type Props = {
plan_id: number;
};
/**
* The plan a bot message belongs to, under it: the one it wrote, or the
* step it worked. Opens the plan where it stands, so a step report deep in
* the thread still leads to it.
*/
export default function MessagePlanChip({ plan_id }: Props) {
const [open, set_open] = useState(false);
return (
<>
<Button
type="button"
variant="ghost"
title="Open the plan"
onClick={() => set_open(true)}
className="inline-flex h-6 max-w-full gap-1.5! flex-nowrap items-center px-1.5! py-0! align-middle rounded-default-xs border-0 bg-sunken hover:bg-sunken text-ink dark:bg-sunken dark:hover:bg-sunken dark:text-ink [&_.twui-button-content-wrapper]:min-w-0"
>
<ListChecks size={13} aria-hidden className="shrink-0" />
<Span className="min-w-0 truncate text-[13px] font-bold leading-4 whitespace-nowrap">Plan</Span>
</Button>
<BotPlanModal plan_id={plan_id} open={open} onClose={() => set_open(false)} />
</>
);
}
@@ -0,0 +1,64 @@
import { useState } from "react";
import Button from "@moduletrace/twui/layout/Button";
import Span from "@moduletrace/twui/layout/Span";
import Tag from "@moduletrace/twui/elements/Tag";
import { twMerge } from "tailwind-merge";
import { ChevronRight, ListChecks } from "lucide-react";
import { BotPlanOpenStates, BotPlanStates } from "@/src/dict/bot-plan-dict";
import type { BotPlanView } from "@/src/types";
import BotPlanModal from "./bot-plan-modal";
type Props = {
plan: BotPlanView | null;
};
/**
* The plan open in the conversation, above the thread: its title, where it
* stands and how far it got, so the plan is not lost above a long thread
* or in an older session. Only one plan is open per conversation; a
* finished or cancelled one is history and leaves the bar.
*/
export default function SessionPlanBar({ plan }: Props) {
const [open, set_open] = useState(false);
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 step = Math.min(plan.finished_steps + 1, plan.total_steps);
const progress =
plan.status == "planned"
? `${plan.total_steps} step${plan.total_steps == 1 ? "" : "s"}`
: plan.status == "paused"
? `Paused at step ${step} of ${plan.total_steps}`
: `Step ${step} of ${plan.total_steps}`;
return (
<>
<Button
type="button"
variant="ghost"
color="gray"
title="Open the plan"
onClick={() => set_open(true)}
className={twMerge(
"w-full shrink-0 justify-start gap-2! rounded-none! border-0 border-b border-solid border-hairline bg-surface px-3! py-2! text-left md:px-6!",
"[&_.twui-button-content-wrapper]:w-full [&_.twui-button-content-wrapper]:min-w-0 [&_.twui-button-content-wrapper]:justify-start",
)}
>
<ListChecks size={14} aria-hidden className="shrink-0 text-ink-secondary" />
<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">
{status}
</Tag>
<Span className="shrink-0 text-[12px] leading-4 text-ink-secondary whitespace-nowrap">
{progress}
</Span>
<ChevronRight size={14} aria-hidden className="shrink-0 text-ink-secondary" />
</Button>
<BotPlanModal plan_id={plan.id} open={open} onClose={() => set_open(false)} />
</>
);
}
@@ -7,6 +7,7 @@ import type {
BotJobUpdateData,
BotMessageReactionData,
BotMessageWithAttachments,
BotPlanView,
} from "@/src/types";
import { AppContext } from "@/src/pages/__root";
import fetchApi from "@moduletrace/twui/utils/fetch/fetchApi";
@@ -31,6 +32,7 @@ import useTaskProgress from "../(hooks)/use-task-progress";
import useReplyProgress from "../(hooks)/use-reply-progress";
import useReplyCatchUp from "../(hooks)/use-reply-catch-up";
import useOpenReplyJobs from "../(hooks)/use-open-reply-jobs";
import useSessionPlan from "../(hooks)/use-session-plan";
import usePlanMode from "../(hooks)/use-plan-mode";
import useSpeakMessage from "../(hooks)/use-speak-message";
import useOlderMessages from "../(hooks)/use-older-messages";
@@ -51,6 +53,7 @@ import mergeLoadedHistory from "../(utils)/merge-loaded-history";
import LoadingLine from "@/src/components/general/loading-line";
import SessionMovedBar from "../(partials)/session-moved-bar";
import AskSessionBar from "../(partials)/ask-session-bar";
import SessionPlanBar from "../(partials)/session-plan-bar";
import NoModelNotice from "../(partials)/no-model-notice";
import syncSessionQuery from "../(utils)/sync-session-query";
import announceShownSession from "@/src/functions/frontend/announce-shown-session";
@@ -112,6 +115,12 @@ export default function Conversation() {
* thread would wait on an answer that is never coming.
*/
const [open_reply_jobs, setOpenReplyJobs] = useState<number | null>(null);
/**
* The plan open in this session, as the history read and its pushes
* leave it: the bar above the thread keeps it one click away however
* far the conversation has moved on.
*/
const [session_plan, setSessionPlan] = useState<BotPlanView | null>(null);
/**
* The bot's message the user asked to run again, while its answer is on
* its way. The new reply lands as another message, so this stands the
@@ -268,6 +277,7 @@ export default function Conversation() {
progress.reset({ task: history.task });
setReplyStep(history.step || null);
setOpenReplyJobs(history.open_jobs ?? null);
setSessionPlan(history.plan ?? null);
setRerunAfterId(null);
},
});
@@ -325,6 +335,8 @@ export default function Conversation() {
on_open_jobs: () => setOpenReplyJobs(1),
});
useSessionPlan({ session_id, on_change: setSessionPlan });
/**
* The thread's pull-to-reload: the page's crew read again (the layout
* answers the request) and this conversation's history, which skips
@@ -551,6 +563,7 @@ export default function Conversation() {
onModelChange={setTextModel}
plan_mode={plan_mode}
/>
<SessionPlanBar plan={session_plan} />
{moved_to_session_id ? null : (
<AskSessionBar
bot_id={Number(bot.id)}
+6
View File
@@ -2391,6 +2391,12 @@ export type ConversationHistory = {
* way and its thinking row should show.
*/
open_jobs?: number | null;
/**
* The plan open in the session (\`bot_plans\`, waiting, being worked or
* paused), so the thread's plan bar shows without another read. Null:
* none open.
*/
plan?: BotPlanView | null;
/**
* When the session shown was carried over into a newer one (it stays
* closed, to read): that session. Null otherwise.
+12 -1
View File
@@ -1,5 +1,5 @@
import { describe, expect, test } from "bun:test";
import botPlanRef, { botPlanRefId, BotPlanRefHrefPrefix } from "./bot-plan-ref";
import botPlanRef, { botPlanRefId, botPlanRefIdFromText, BotPlanRefHrefPrefix } from "./bot-plan-ref";
import linkComputerRefs from "./link-computer-refs";
/**
@@ -22,6 +22,17 @@ describe("botPlanRef", () => {
});
});
describe("botPlanRefIdFromText", () => {
test("reads the plan a message names, and nothing from text that names none", () => {
expect(botPlanRefIdFromText({ text: "Written it: [plan:4]. Approve when ready." })).toBe(4);
expect(botPlanRefIdFromText({ text: "[plan:12]" })).toBe(12);
expect(botPlanRefIdFromText({ text: "no plan here" })).toBeNull();
expect(botPlanRefIdFromText({ text: "[plan:0]" })).toBeNull();
expect(botPlanRefIdFromText({ text: "[plan:twelve]" })).toBeNull();
expect(botPlanRefIdFromText({ text: null })).toBeNull();
});
});
describe("a plan ref in a message", () => {
test("turns a plan ref into a link", () => {
expect(linkComputerRefs({ text: "Here it is, [plan:4]: approve when ready." })).toContain(
+13
View File
@@ -23,5 +23,18 @@ export function botPlanRefId({ href }: { href?: string | null }) {
if (!Number.isInteger(plan_id) || plan_id <= 0) return null;
return plan_id;
}
/**
* The plan id in a message's text (`botPlanRef`), or null when it names
* none: how a run knows which plan its reply belongs to, so the chip under
* it opens that plan.
*/
export function botPlanRefIdFromText({ text }: { text?: string | null }) {
const plan_id = Number(/\[plan:(\d+)\]/.exec(text || "")?.[1] || 0);
if (!Number.isInteger(plan_id) || plan_id <= 0) return null;
return plan_id;
}